Detect and clean stale POLECAT_DONE messages (#913)
* fix(witness): detect and ignore stale POLECAT_DONE messages Add timestamp validation to prevent witness from nuking newly spawned polecat sessions when processing stale POLECAT_DONE messages from previous sessions. - Add isStalePolecatDone() to compare message timestamp vs session created time - If message timestamp < session created time, message is stale and ignored - Add unit tests for timestamp parsing and stale detection logic Fixes #909 Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * feat(mail): add --stale flag to gt mail archive Add ability to archive stale messages (sent before current session started). This prevents old messages from cycling forever in patrol inbox. Changes: - Add --stale and --dry-run flags to gt mail archive - Move stale detection helpers to internal/session/stale.go for reuse - Add ParseAddress to parse mail addresses into AgentIdentity - Add SessionCreatedAt to get tmux session start time Usage: gt mail archive --stale # Archive all stale messages gt mail archive --stale --dry-run # Preview what would be archived Co-Authored-By: GPT-5.2 Codex <noreply@openai.com> --------- Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com> Co-authored-by: GPT-5.2 Codex <noreply@openai.com>
This commit is contained in:
@@ -42,6 +42,10 @@ var (
|
||||
|
||||
// Clear flags
|
||||
mailClearAll bool
|
||||
|
||||
// Archive flags
|
||||
mailArchiveStale bool
|
||||
mailArchiveDryRun bool
|
||||
)
|
||||
|
||||
var mailCmd = &cobra.Command{
|
||||
@@ -196,16 +200,22 @@ Examples:
|
||||
}
|
||||
|
||||
var mailArchiveCmd = &cobra.Command{
|
||||
Use: "archive <message-id> [message-id...]",
|
||||
Use: "archive [message-id...]",
|
||||
Short: "Archive messages",
|
||||
Long: `Archive one or more messages.
|
||||
|
||||
Removes the messages from your inbox by closing them in beads.
|
||||
|
||||
Use --stale to archive messages sent before your current session started.
|
||||
|
||||
Examples:
|
||||
gt mail archive hq-abc123
|
||||
gt mail archive hq-abc123 hq-def456 hq-ghi789`,
|
||||
Args: cobra.MinimumNArgs(1),
|
||||
gt mail archive hq-abc123 hq-def456 hq-ghi789
|
||||
gt mail archive --stale
|
||||
gt mail archive --stale --dry-run`,
|
||||
Args: func(cmd *cobra.Command, args []string) error {
|
||||
return nil
|
||||
},
|
||||
RunE: runMailArchive,
|
||||
}
|
||||
|
||||
@@ -487,6 +497,10 @@ func init() {
|
||||
// Clear flags
|
||||
mailClearCmd.Flags().BoolVar(&mailClearAll, "all", false, "Clear all messages (default behavior)")
|
||||
|
||||
// Archive flags
|
||||
mailArchiveCmd.Flags().BoolVar(&mailArchiveStale, "stale", false, "Archive messages sent before session start")
|
||||
mailArchiveCmd.Flags().BoolVarP(&mailArchiveDryRun, "dry-run", "n", false, "Show what would be archived without archiving")
|
||||
|
||||
// Add subcommands
|
||||
mailCmd.AddCommand(mailSendCmd)
|
||||
mailCmd.AddCommand(mailInboxCmd)
|
||||
|
||||
25
internal/cmd/mail_archive_test.go
Normal file
25
internal/cmd/mail_archive_test.go
Normal file
@@ -0,0 +1,25 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/steveyegge/gastown/internal/mail"
|
||||
)
|
||||
|
||||
func TestStaleMessagesForSession(t *testing.T) {
|
||||
sessionStart := time.Date(2026, 1, 24, 2, 0, 0, 0, time.UTC)
|
||||
messages := []*mail.Message{
|
||||
{ID: "msg-1", Subject: "Older", Timestamp: sessionStart.Add(-2 * time.Minute)},
|
||||
{ID: "msg-2", Subject: "Newer", Timestamp: sessionStart.Add(2 * time.Minute)},
|
||||
{ID: "msg-3", Subject: "Equal", Timestamp: sessionStart},
|
||||
}
|
||||
|
||||
stale := staleMessagesForSession(messages, sessionStart)
|
||||
if len(stale) != 1 {
|
||||
t.Fatalf("expected 1 stale message, got %d", len(stale))
|
||||
}
|
||||
if stale[0].Message.ID != "msg-1" {
|
||||
t.Fatalf("expected msg-1 stale, got %s", stale[0].Message.ID)
|
||||
}
|
||||
}
|
||||
@@ -7,9 +7,11 @@ import (
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
"github.com/steveyegge/gastown/internal/mail"
|
||||
"github.com/steveyegge/gastown/internal/session"
|
||||
"github.com/steveyegge/gastown/internal/style"
|
||||
)
|
||||
|
||||
@@ -289,6 +291,23 @@ func runMailArchive(cmd *cobra.Command, args []string) error {
|
||||
return err
|
||||
}
|
||||
|
||||
if mailArchiveStale {
|
||||
if len(args) > 0 {
|
||||
return errors.New("--stale cannot be combined with message IDs")
|
||||
}
|
||||
return runMailArchiveStale(mailbox, address)
|
||||
}
|
||||
if len(args) == 0 {
|
||||
return errors.New("message ID required unless using --stale")
|
||||
}
|
||||
if mailArchiveDryRun {
|
||||
fmt.Printf("%s Would archive %d message(s)\n", style.Dim.Render("(dry-run)"), len(args))
|
||||
for _, msgID := range args {
|
||||
fmt.Printf(" %s\n", style.Dim.Render(msgID))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Archive all specified messages
|
||||
archived := 0
|
||||
var errors []string
|
||||
@@ -318,6 +337,87 @@ func runMailArchive(cmd *cobra.Command, args []string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
type staleMessage struct {
|
||||
Message *mail.Message
|
||||
Reason string
|
||||
}
|
||||
|
||||
func runMailArchiveStale(mailbox *mail.Mailbox, address string) error {
|
||||
identity, err := session.ParseAddress(address)
|
||||
if err != nil {
|
||||
return fmt.Errorf("determining session for %s: %w", address, err)
|
||||
}
|
||||
|
||||
sessionName := identity.SessionName()
|
||||
if sessionName == "" {
|
||||
return fmt.Errorf("could not determine session name for %s", address)
|
||||
}
|
||||
|
||||
sessionStart, err := session.SessionCreatedAt(sessionName)
|
||||
if err != nil {
|
||||
return fmt.Errorf("getting session start time for %s: %w", sessionName, err)
|
||||
}
|
||||
|
||||
messages, err := mailbox.List()
|
||||
if err != nil {
|
||||
return fmt.Errorf("listing messages: %w", err)
|
||||
}
|
||||
|
||||
staleMessages := staleMessagesForSession(messages, sessionStart)
|
||||
if mailArchiveDryRun {
|
||||
if len(staleMessages) == 0 {
|
||||
fmt.Printf("%s No stale messages found\n", style.Success.Render("✓"))
|
||||
return nil
|
||||
}
|
||||
fmt.Printf("%s Would archive %d stale message(s):\n", style.Dim.Render("(dry-run)"), len(staleMessages))
|
||||
for _, stale := range staleMessages {
|
||||
fmt.Printf(" %s %s\n", style.Dim.Render(stale.Message.ID), stale.Message.Subject)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
if len(staleMessages) == 0 {
|
||||
fmt.Printf("%s No stale messages to archive\n", style.Success.Render("✓"))
|
||||
return nil
|
||||
}
|
||||
|
||||
archived := 0
|
||||
var errors []string
|
||||
for _, stale := range staleMessages {
|
||||
if err := mailbox.Delete(stale.Message.ID); err != nil {
|
||||
errors = append(errors, fmt.Sprintf("%s: %v", stale.Message.ID, err))
|
||||
} else {
|
||||
archived++
|
||||
}
|
||||
}
|
||||
|
||||
if len(errors) > 0 {
|
||||
fmt.Printf("%s Archived %d/%d stale messages\n", style.Bold.Render("⚠"), archived, len(staleMessages))
|
||||
for _, e := range errors {
|
||||
fmt.Printf(" Error: %s\n", e)
|
||||
}
|
||||
return fmt.Errorf("failed to archive %d stale messages", len(errors))
|
||||
}
|
||||
|
||||
if archived == 1 {
|
||||
fmt.Printf("%s Stale message archived\n", style.Bold.Render("✓"))
|
||||
} else {
|
||||
fmt.Printf("%s Archived %d stale messages\n", style.Bold.Render("✓"), archived)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func staleMessagesForSession(messages []*mail.Message, sessionStart time.Time) []staleMessage {
|
||||
var staleMessages []staleMessage
|
||||
for _, msg := range messages {
|
||||
stale, reason := session.StaleReasonForTimes(msg.Timestamp, sessionStart)
|
||||
if stale {
|
||||
staleMessages = append(staleMessages, staleMessage{Message: msg, Reason: reason})
|
||||
}
|
||||
}
|
||||
return staleMessages
|
||||
}
|
||||
|
||||
func runMailMarkRead(cmd *cobra.Command, args []string) error {
|
||||
// Determine which inbox
|
||||
address := detectSender()
|
||||
|
||||
@@ -25,6 +25,59 @@ type AgentIdentity struct {
|
||||
Name string // crew/polecat name (empty for mayor/deacon/witness/refinery)
|
||||
}
|
||||
|
||||
// ParseAddress parses a mail-style address into an AgentIdentity.
|
||||
func ParseAddress(address string) (*AgentIdentity, error) {
|
||||
address = strings.TrimSpace(address)
|
||||
if address == "" {
|
||||
return nil, fmt.Errorf("empty address")
|
||||
}
|
||||
|
||||
if address == "mayor" || address == "mayor/" {
|
||||
return &AgentIdentity{Role: RoleMayor}, nil
|
||||
}
|
||||
if address == "deacon" || address == "deacon/" {
|
||||
return &AgentIdentity{Role: RoleDeacon}, nil
|
||||
}
|
||||
if address == "overseer" {
|
||||
return nil, fmt.Errorf("overseer has no session")
|
||||
}
|
||||
|
||||
address = strings.TrimSuffix(address, "/")
|
||||
parts := strings.Split(address, "/")
|
||||
if len(parts) < 2 {
|
||||
return nil, fmt.Errorf("invalid address %q", address)
|
||||
}
|
||||
|
||||
rig := parts[0]
|
||||
switch len(parts) {
|
||||
case 2:
|
||||
name := parts[1]
|
||||
switch name {
|
||||
case "witness":
|
||||
return &AgentIdentity{Role: RoleWitness, Rig: rig}, nil
|
||||
case "refinery":
|
||||
return &AgentIdentity{Role: RoleRefinery, Rig: rig}, nil
|
||||
case "crew", "polecats":
|
||||
return nil, fmt.Errorf("invalid address %q", address)
|
||||
default:
|
||||
return &AgentIdentity{Role: RolePolecat, Rig: rig, Name: name}, nil
|
||||
}
|
||||
case 3:
|
||||
role := parts[1]
|
||||
name := parts[2]
|
||||
switch role {
|
||||
case "crew":
|
||||
return &AgentIdentity{Role: RoleCrew, Rig: rig, Name: name}, nil
|
||||
case "polecats":
|
||||
return &AgentIdentity{Role: RolePolecat, Rig: rig, Name: name}, nil
|
||||
default:
|
||||
return nil, fmt.Errorf("invalid address %q", address)
|
||||
}
|
||||
default:
|
||||
return nil, fmt.Errorf("invalid address %q", address)
|
||||
}
|
||||
}
|
||||
|
||||
// ParseSessionName parses a tmux session name into an AgentIdentity.
|
||||
//
|
||||
// Session name formats:
|
||||
|
||||
@@ -250,3 +250,71 @@ func TestParseSessionName_RoundTrip(t *testing.T) {
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseAddress(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
address string
|
||||
want AgentIdentity
|
||||
wantErr bool
|
||||
}{
|
||||
{
|
||||
name: "mayor",
|
||||
address: "mayor/",
|
||||
want: AgentIdentity{Role: RoleMayor},
|
||||
},
|
||||
{
|
||||
name: "deacon",
|
||||
address: "deacon",
|
||||
want: AgentIdentity{Role: RoleDeacon},
|
||||
},
|
||||
{
|
||||
name: "witness",
|
||||
address: "gastown/witness",
|
||||
want: AgentIdentity{Role: RoleWitness, Rig: "gastown"},
|
||||
},
|
||||
{
|
||||
name: "refinery",
|
||||
address: "rig-a/refinery",
|
||||
want: AgentIdentity{Role: RoleRefinery, Rig: "rig-a"},
|
||||
},
|
||||
{
|
||||
name: "crew",
|
||||
address: "gastown/crew/max",
|
||||
want: AgentIdentity{Role: RoleCrew, Rig: "gastown", Name: "max"},
|
||||
},
|
||||
{
|
||||
name: "polecat explicit",
|
||||
address: "gastown/polecats/nux",
|
||||
want: AgentIdentity{Role: RolePolecat, Rig: "gastown", Name: "nux"},
|
||||
},
|
||||
{
|
||||
name: "polecat canonical",
|
||||
address: "gastown/nux",
|
||||
want: AgentIdentity{Role: RolePolecat, Rig: "gastown", Name: "nux"},
|
||||
},
|
||||
{
|
||||
name: "invalid",
|
||||
address: "gastown/crew",
|
||||
wantErr: true,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
got, err := ParseAddress(tt.address)
|
||||
if tt.wantErr {
|
||||
if err == nil {
|
||||
t.Fatalf("expected error")
|
||||
}
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
t.Fatalf("ParseAddress(%q) error = %v", tt.address, err)
|
||||
}
|
||||
if *got != tt.want {
|
||||
t.Fatalf("ParseAddress(%q) = %#v, want %#v", tt.address, *got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
46
internal/session/stale.go
Normal file
46
internal/session/stale.go
Normal file
@@ -0,0 +1,46 @@
|
||||
package session
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/steveyegge/gastown/internal/tmux"
|
||||
)
|
||||
|
||||
// SessionCreatedAt returns the time a tmux session was created.
|
||||
func SessionCreatedAt(sessionName string) (time.Time, error) {
|
||||
t := tmux.NewTmux()
|
||||
info, err := t.GetSessionInfo(sessionName)
|
||||
if err != nil {
|
||||
return time.Time{}, err
|
||||
}
|
||||
|
||||
return ParseTmuxSessionCreated(info.Created)
|
||||
}
|
||||
|
||||
// ParseTmuxSessionCreated parses the tmux session created timestamp.
|
||||
func ParseTmuxSessionCreated(created string) (time.Time, error) {
|
||||
created = strings.TrimSpace(created)
|
||||
if created == "" {
|
||||
return time.Time{}, fmt.Errorf("empty session created time")
|
||||
}
|
||||
return time.ParseInLocation("2006-01-02 15:04:05", created, time.Local)
|
||||
}
|
||||
|
||||
// StaleReasonForTimes compares message time to session creation and returns staleness info.
|
||||
func StaleReasonForTimes(messageTime, sessionCreated time.Time) (bool, string) {
|
||||
if messageTime.IsZero() || sessionCreated.IsZero() {
|
||||
return false, ""
|
||||
}
|
||||
|
||||
if messageTime.Before(sessionCreated) {
|
||||
reason := fmt.Sprintf("message=%s session_started=%s",
|
||||
messageTime.Format(time.RFC3339),
|
||||
sessionCreated.Format(time.RFC3339),
|
||||
)
|
||||
return true, reason
|
||||
}
|
||||
|
||||
return false, ""
|
||||
}
|
||||
60
internal/session/stale_test.go
Normal file
60
internal/session/stale_test.go
Normal file
@@ -0,0 +1,60 @@
|
||||
package session
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestParseTmuxSessionCreated(t *testing.T) {
|
||||
input := "2026-01-24 01:02:03"
|
||||
expected, err := time.ParseInLocation("2006-01-02 15:04:05", input, time.Local)
|
||||
if err != nil {
|
||||
t.Fatalf("parse expected: %v", err)
|
||||
}
|
||||
|
||||
parsed, err := ParseTmuxSessionCreated(input)
|
||||
if err != nil {
|
||||
t.Fatalf("ParseTmuxSessionCreated: %v", err)
|
||||
}
|
||||
if !parsed.Equal(expected) {
|
||||
t.Fatalf("parsed time mismatch: got %v want %v", parsed, expected)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStaleReasonForTimes(t *testing.T) {
|
||||
now := time.Date(2026, 1, 24, 2, 0, 0, 0, time.UTC)
|
||||
newer := now.Add(2 * time.Minute)
|
||||
older := now.Add(-2 * time.Minute)
|
||||
|
||||
t.Run("message before session", func(t *testing.T) {
|
||||
stale, reason := StaleReasonForTimes(older, newer)
|
||||
if !stale {
|
||||
t.Fatalf("expected stale")
|
||||
}
|
||||
if !strings.Contains(reason, "message=") || !strings.Contains(reason, "session_started=") {
|
||||
t.Fatalf("expected reason details, got %q", reason)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("message after session", func(t *testing.T) {
|
||||
stale, reason := StaleReasonForTimes(newer, older)
|
||||
if stale || reason != "" {
|
||||
t.Fatalf("expected not stale, got %v %q", stale, reason)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("zero message time", func(t *testing.T) {
|
||||
stale, reason := StaleReasonForTimes(time.Time{}, now)
|
||||
if stale || reason != "" {
|
||||
t.Fatalf("expected not stale for zero message time, got %v %q", stale, reason)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("zero session time", func(t *testing.T) {
|
||||
stale, reason := StaleReasonForTimes(now, time.Time{})
|
||||
if stale || reason != "" {
|
||||
t.Fatalf("expected not stale for zero session time, got %v %q", stale, reason)
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -13,6 +13,7 @@ import (
|
||||
"github.com/steveyegge/gastown/internal/git"
|
||||
"github.com/steveyegge/gastown/internal/mail"
|
||||
"github.com/steveyegge/gastown/internal/rig"
|
||||
"github.com/steveyegge/gastown/internal/session"
|
||||
"github.com/steveyegge/gastown/internal/tmux"
|
||||
"github.com/steveyegge/gastown/internal/util"
|
||||
"github.com/steveyegge/gastown/internal/workspace"
|
||||
@@ -53,6 +54,12 @@ func HandlePolecatDone(workDir, rigName string, msg *mail.Message) *HandlerResul
|
||||
return result
|
||||
}
|
||||
|
||||
if stale, reason := isStalePolecatDone(rigName, payload.PolecatName, msg); stale {
|
||||
result.Handled = true
|
||||
result.Action = fmt.Sprintf("ignored stale POLECAT_DONE for %s (%s)", payload.PolecatName, reason)
|
||||
return result
|
||||
}
|
||||
|
||||
// Handle PHASE_COMPLETE: recycle polecat (session ends but worktree stays)
|
||||
// The polecat is registered as a waiter on the gate and will be re-dispatched
|
||||
// when the gate closes via gt gate wake.
|
||||
@@ -118,6 +125,21 @@ func HandlePolecatDone(workDir, rigName string, msg *mail.Message) *HandlerResul
|
||||
return result
|
||||
}
|
||||
|
||||
func isStalePolecatDone(rigName, polecatName string, msg *mail.Message) (bool, string) {
|
||||
if msg == nil {
|
||||
return false, ""
|
||||
}
|
||||
|
||||
sessionName := fmt.Sprintf("gt-%s-%s", rigName, polecatName)
|
||||
createdAt, err := session.SessionCreatedAt(sessionName)
|
||||
if err != nil {
|
||||
// Session not found or tmux not running - can't determine staleness, allow message
|
||||
return false, ""
|
||||
}
|
||||
|
||||
return session.StaleReasonForTimes(msg.Timestamp, createdAt)
|
||||
}
|
||||
|
||||
// HandleLifecycleShutdown processes a LIFECYCLE:Shutdown message.
|
||||
// Similar to POLECAT_DONE but triggered by daemon rather than polecat.
|
||||
// Auto-nukes if clean since shutdown means no pending work.
|
||||
|
||||
Reference in New Issue
Block a user