-
Notifications
You must be signed in to change notification settings - Fork 1.3k
Expand file tree
/
Copy pathmanager.go
More file actions
2513 lines (2229 loc) · 92.7 KB
/
manager.go
File metadata and controls
2513 lines (2229 loc) · 92.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Liftoff test: 2026-02-08T14:00:00
package polecat
import (
"context"
"errors"
"fmt"
"math/rand/v2"
"os"
"os/exec"
"path/filepath"
"strconv"
"strings"
"sync"
"syscall"
"time"
"github.com/gofrs/flock"
"github.com/steveyegge/gastown/internal/beads"
"github.com/steveyegge/gastown/internal/config"
"github.com/steveyegge/gastown/internal/doltserver"
"github.com/steveyegge/gastown/internal/git"
"github.com/steveyegge/gastown/internal/rig"
"github.com/steveyegge/gastown/internal/runtime"
"github.com/steveyegge/gastown/internal/session"
"github.com/steveyegge/gastown/internal/style"
"github.com/steveyegge/gastown/internal/telemetry"
"github.com/steveyegge/gastown/internal/templates"
"github.com/steveyegge/gastown/internal/tmux"
"github.com/steveyegge/gastown/internal/util"
)
// Retry constants for Dolt operations (matching hook update pattern in sling.go).
// Configurable via operational.polecat in settings/config.json.
const (
doltMaxRetries = 10
doltBaseBackoff = 500 * time.Millisecond
doltBackoffMax = 30 * time.Second
// doltStateRetries is a reduced retry count for SetAgentStateWithRetry.
// Agent state is a monitoring concern, not a correctness requirement (see
// comment on SetAgentStateWithRetry). 10 retries with exponential backoff
// wastes ~2 minutes on persistent failures, blocking `gt sling` for no
// benefit since the caller already treats errors as warn-only.
// 3 retries (total backoff ~3.5s) is sufficient to ride out transient
// Dolt hiccups without punishing interactive workflows.
// doltStateRetries is now managed via config.Operational.Polecat.DoltStateRetries
doltStateRetries = config.Get().Operational.Polecat.DoltStateRetries
)
// doltBackoff calculates exponential backoff with ±25% jitter for a given attempt (1-indexed).
// Formula: base * 2^(attempt-1) * (1 ± 25% random), capped at doltBackoffMax.
func doltBackoff(attempt int) time.Duration {
backoff := doltBaseBackoff
for i := 1; i < attempt; i++ {
backoff *= 2
if backoff > doltBackoffMax {
backoff = doltBackoffMax
break
}
}
// Apply ±25% jitter
jitter := 1.0 + (rand.Float64()-0.5)*0.5 // range [0.75, 1.25]
result := time.Duration(float64(backoff) * jitter)
if result > doltBackoffMax {
result = doltBackoffMax
}
return result
}
// isDoltOptimisticLockError returns true if the error is an optimistic lock / serialization failure.
// These indicate transient write conflicts from concurrent Dolt operations — worth retrying.
func isDoltOptimisticLockError(err error) bool {
if err == nil {
return false
}
msg := err.Error()
return strings.Contains(msg, "optimistic lock") ||
strings.Contains(msg, "serialization failure") ||
strings.Contains(msg, "lock wait timeout") ||
strings.Contains(msg, "try restarting transaction") ||
strings.Contains(msg, "database is read only") ||
strings.Contains(msg, "cannot update manifest")
}
// isDoltConfigError returns true if the error indicates a configuration or initialization
// problem rather than a transient failure. Config errors should NOT be retried because
// they will fail identically on every attempt, wasting ~3 minutes in the retry loop.
// See gt-2ra: polecat spawn hang when Dolt DB not initialized.
func isDoltConfigError(err error) bool {
if err == nil {
return false
}
msg := err.Error()
return strings.Contains(msg, "not initialized") ||
strings.Contains(msg, "no such table") ||
strings.Contains(msg, "table not found") ||
strings.Contains(msg, "issue_prefix") ||
strings.Contains(msg, "no database") ||
strings.Contains(msg, "database not found") ||
strings.Contains(msg, "connection refused") ||
strings.Contains(msg, "configure custom types") ||
strings.Contains(msg, "identity mismatch") ||
strings.Contains(msg, "Unknown database")
}
// Common errors
var (
ErrPolecatExists = errors.New("polecat already exists")
ErrPolecatNotFound = errors.New("polecat not found")
ErrHasChanges = errors.New("polecat has uncommitted changes")
ErrHasUncommittedWork = errors.New("polecat has uncommitted work")
ErrShellInWorktree = errors.New("shell working directory is inside polecat worktree")
ErrDoltUnhealthy = errors.New("dolt health check failed")
ErrDoltAtCapacity = errors.New("dolt server at connection capacity")
ErrDiskSpaceLow = errors.New("insufficient disk space")
)
// UncommittedWorkError provides details about uncommitted work.
type UncommittedWorkError struct {
PolecatName string
Status *git.UncommittedWorkStatus
}
func (e *UncommittedWorkError) Error() string {
return fmt.Sprintf("polecat %s has uncommitted work: %s", e.PolecatName, e.Status.String())
}
func (e *UncommittedWorkError) Unwrap() error {
return ErrHasUncommittedWork
}
// Manager handles polecat lifecycle.
type Manager struct {
rig *rig.Rig
git *git.Git
beads *beads.Beads
namePool *NamePool
tmux *tmux.Tmux
townRoot string // Computed once at construction; used by agentBeadID for deterministic IDs
}
// NewManager creates a new polecat manager.
func NewManager(r *rig.Rig, g *git.Git, t *tmux.Tmux) *Manager {
// Use the resolved beads directory to find where bd commands should run.
// For tracked beads: rig/.beads/redirect -> mayor/rig/.beads, so use mayor/rig
// For local beads: rig/.beads is the database, so use rig root
resolvedBeads := beads.ResolveBeadsDir(r.Path)
beadsPath := filepath.Dir(resolvedBeads) // Get the directory containing .beads
// Compute town root once for deterministic use across all Manager methods.
// Rig path is always filepath.Join(townRoot, rigName), so filepath.Dir is correct
// and avoids the non-determinism of workspace.Find which can fail or resolve
// differently depending on call-site context (gt-lph).
townRoot := filepath.Dir(r.Path)
// Try to load rig settings for namepool config
settingsPath := filepath.Join(r.Path, "settings", "config.json")
var pool *NamePool
settings, err := config.LoadRigSettings(settingsPath)
if err == nil && settings.Namepool != nil {
// If style is set but not built-in and no explicit names, resolve custom theme
names := settings.Namepool.Names
if len(names) == 0 && settings.Namepool.Style != "" && !IsBuiltinTheme(settings.Namepool.Style) {
if resolved, rErr := ResolveThemeNames(townRoot, settings.Namepool.Style); rErr == nil {
names = resolved
}
}
pool = NewNamePoolWithConfig(
r.Path,
r.Name,
settings.Namepool.Style,
names,
settings.Namepool.MaxBeforeNumbering,
)
} else {
// Fallback: check rig-level config.json for polecat_names
// (pool-init and gt rig config write namepool config here).
if rigCfg, rcErr := rig.LoadRigConfig(r.Path); rcErr == nil && len(rigCfg.PolecatNames) > 0 {
pool = NewNamePoolWithConfig(r.Path, r.Name, "", rigCfg.PolecatNames, 0)
} else {
pool = NewNamePool(r.Path, r.Name)
}
}
// Set town root for custom theme resolution in getNames()
pool.SetTownRoot(townRoot)
_ = pool.Load() // non-fatal: state file may not exist for new rigs
return &Manager{
rig: r,
git: g,
beads: beads.NewWithBeadsDir(beadsPath, resolvedBeads),
namePool: pool,
tmux: t,
townRoot: townRoot,
}
}
// GetNamePool returns the manager's name pool for external use (e.g., pool init).
func (m *Manager) GetNamePool() *NamePool {
return m.namePool
}
// lockPolecat acquires an exclusive file lock for a specific polecat.
// This prevents concurrent gt processes from racing on the same polecat's
// filesystem operations (Add, Remove, RepairWorktree).
// Caller must defer fl.Unlock().
func (m *Manager) lockPolecat(name string) (*flock.Flock, error) {
lockDir := filepath.Join(m.rig.Path, ".runtime", "locks")
if err := os.MkdirAll(lockDir, 0755); err != nil {
return nil, fmt.Errorf("creating lock dir: %w", err)
}
lockPath := filepath.Join(lockDir, fmt.Sprintf("polecat-%s.lock", name))
fl := flock.New(lockPath)
if err := fl.Lock(); err != nil {
return nil, fmt.Errorf("acquiring polecat lock for %s: %w", name, err)
}
return fl, nil
}
// lockPool acquires an exclusive file lock for name pool operations.
// This prevents concurrent gt processes from racing on AllocateName/ReconcilePool.
// Caller must defer fl.Unlock().
func (m *Manager) lockPool() (*flock.Flock, error) {
lockDir := filepath.Join(m.rig.Path, ".runtime", "locks")
if err := os.MkdirAll(lockDir, 0755); err != nil {
return nil, fmt.Errorf("creating lock dir: %w", err)
}
lockPath := filepath.Join(lockDir, "polecat-pool.lock")
fl := flock.New(lockPath)
if err := fl.Lock(); err != nil {
return nil, fmt.Errorf("acquiring pool lock: %w", err)
}
return fl, nil
}
// CheckDoltHealth verifies that the Dolt database is reachable before spawning.
// Returns an error if Dolt exists but is unhealthy after retries.
// Returns nil if beads is not configured (test/setup environments).
// If read-only errors persist after retries, attempts server recovery (gt-chx92).
// Fails fast on configuration/initialization errors (gt-2ra).
func (m *Manager) CheckDoltHealth() error {
var lastErr error
for attempt := 1; attempt <= doltMaxRetries; attempt++ {
// Use a lightweight beads operation to verify Dolt is responsive
_, err := m.beads.Show("__health_check_nonexistent__")
if err == nil || errors.Is(err, beads.ErrNotFound) || strings.Contains(err.Error(), "not found") {
// Dolt is healthy — a "not found" error means the DB responded
return nil
}
// Optimistic lock errors mean Dolt is alive but busy with concurrent writes
if isDoltOptimisticLockError(err) {
return nil
}
// If beads isn't configured at all, skip the health check
if strings.Contains(err.Error(), "does not exist") || errors.Is(err, beads.ErrNotInstalled) {
return nil
}
// Fail fast on config/init errors — retrying won't help (gt-2ra, gas-tc4)
if isDoltConfigError(err) {
return fmt.Errorf("%w: %v\n\nRecovery: run 'gt doctor --fix' to repair database configuration.\n"+
"If that doesn't help, try: bd init --force --server", ErrDoltUnhealthy, err)
}
lastErr = err
if attempt < doltMaxRetries {
backoff := doltBackoff(attempt)
style.PrintWarning("Dolt health check attempt %d failed, retrying in %v...", attempt, backoff)
time.Sleep(backoff)
}
}
// If the persistent failure looks like read-only, attempt server recovery
// before giving up. This is the gt-level recovery path (gt-chx92).
if lastErr != nil && doltserver.IsReadOnlyError(lastErr.Error()) {
if recoverErr := doltserver.RecoverReadOnly(m.townRoot); recoverErr == nil {
// Recovery succeeded — verify health once more
_, err := m.beads.Show("__health_check_nonexistent__")
if err == nil || errors.Is(err, beads.ErrNotFound) || strings.Contains(err.Error(), "not found") {
return nil
}
}
}
return fmt.Errorf("%w: %v\n\nRecovery: run 'gt doctor --fix' to diagnose and repair Dolt configuration", ErrDoltUnhealthy, lastErr)
}
// CheckDoltServerCapacity verifies the Dolt server has capacity for new connections.
// This is an admission control gate: if the server is near its max_connections limit,
// spawning another polecat (which will make many bd calls) could overwhelm it.
// Returns nil if capacity is available, ErrDoltAtCapacity if the server is overloaded.
// Fails closed if the check errors — a server that can't report capacity is likely
// already under stress (gt-lfc0d).
func (m *Manager) CheckDoltServerCapacity() error {
// NOTE: Prior to gt-lph, this method called workspace.Find to locate townRoot,
// which could fail and silently skip the capacity check (return nil). Now that
// m.townRoot is computed deterministically at Manager construction, errors from
// HasConnectionCapacity always propagate — this is intentional. A server that
// can't report capacity is likely under stress, and silently passing was a
// latent bug that allowed connection storms under load (gt-lfc0d).
hasCapacity, active, err := doltserver.HasConnectionCapacity(m.townRoot)
if err != nil {
// Fail closed: if we can't check capacity, the server may be overloaded.
// Proceeding optimistically caused read-only mode under load (gt-lfc0d).
return fmt.Errorf("%w: capacity check failed: %v", ErrDoltAtCapacity, err)
}
if !hasCapacity {
return fmt.Errorf("%w: %d active connections (server near limit)", ErrDoltAtCapacity, active)
}
return nil
}
// createAgentBeadWithRetry wraps CreateOrReopenAgentBead with retry logic.
// For transient Dolt failures (server exists but write fails), retries with backoff
// and fails hard — a polecat without an agent bead is untrackable.
// If beads is not configured (no .beads directory), warns and returns nil
// since this indicates a test/setup environment, not a Dolt failure.
// Fails fast on configuration/initialization errors (gt-2ra) — these are not
// transient and retrying them wastes ~3 minutes for identical failures.
func (m *Manager) createAgentBeadWithRetry(agentID string, fields *beads.AgentFields) error {
var lastErr error
for attempt := 1; attempt <= doltMaxRetries; attempt++ {
_, err := m.beads.CreateOrReopenAgentBead(agentID, agentID, fields)
if err == nil {
return nil
}
lastErr = err
// If beads directory doesn't exist, this is a test/setup env — warn only
if strings.Contains(err.Error(), "does not exist") || errors.Is(err, beads.ErrNotInstalled) {
style.PrintWarning("could not create agent bead (beads not configured): %v", err)
return nil
}
// Fail fast on config/init errors — retrying won't help (gt-2ra)
if isDoltConfigError(err) {
return fmt.Errorf("agent bead creation failed (DB not initialized — not retrying): %w", err)
}
if attempt < doltMaxRetries {
backoff := doltBackoff(attempt)
style.PrintWarning("agent bead creation attempt %d failed, retrying in %v: %v", attempt, backoff, err)
time.Sleep(backoff)
}
}
return fmt.Errorf("creating agent bead after %d attempts: %w", doltMaxRetries, lastErr)
}
// SetAgentStateWithRetry wraps SetAgentState with retry logic.
// Returns an error after exhausting retries, but callers may choose to warn
// rather than fail — e.g., in StartSession where the tmux session is already
// running and failing hard would orphan it. Agent state is a monitoring
// concern, not a correctness requirement.
// Fails fast on configuration/initialization errors (gt-2ra).
func (m *Manager) SetAgentStateWithRetry(name string, state string) error {
var lastErr error
for attempt := 1; attempt <= doltStateRetries; attempt++ {
err := m.SetAgentState(name, state)
if err == nil {
return nil
}
lastErr = err
// Fail fast on config/init errors — retrying won't help (gt-2ra)
if isDoltConfigError(err) {
return fmt.Errorf("setting agent state failed (DB not initialized — not retrying): %w", err)
}
if attempt < doltStateRetries {
backoff := doltBackoff(attempt)
style.PrintWarning("SetAgentState attempt %d failed, retrying in %v: %v", attempt, backoff, err)
time.Sleep(backoff)
}
}
return fmt.Errorf("setting agent state after %d attempts: %w", doltStateRetries, lastErr)
}
// assigneeID returns the beads assignee identifier for a polecat.
// Format: "rig/polecats/polecatName" (e.g., "gastown/polecats/Toast")
func (m *Manager) assigneeID(name string) string {
return fmt.Sprintf("%s/polecats/%s", m.rig.Name, name)
}
// agentBeadID returns the agent bead ID for a polecat.
// Format: "<prefix>-<rig>-polecat-<name>" (e.g., "gt-gastown-polecat-Toast", "bd-beads-polecat-obsidian")
// The prefix is looked up from routes.jsonl to support rigs with custom prefixes.
// Uses the town root computed at Manager construction for deterministic IDs
// regardless of call site (gt-lph).
func (m *Manager) agentBeadID(name string) string {
prefix := beads.GetPrefixForRig(m.townRoot, m.rig.Name)
return beads.PolecatBeadIDWithPrefix(prefix, m.rig.Name, name)
}
// getCleanupStatusFromBead reads the cleanup_status from the polecat's agent bead.
// Returns CleanupUnknown if the bead doesn't exist or has no cleanup_status.
// ZFC #10: This is the ZFC-compliant way to check if removal is safe.
func (m *Manager) getCleanupStatusFromBead(name string) CleanupStatus {
agentID := m.agentBeadID(name)
_, fields, err := m.beads.GetAgentBead(agentID)
if err != nil || fields == nil {
return CleanupUnknown
}
if fields.CleanupStatus == "" {
return CleanupUnknown
}
return CleanupStatus(fields.CleanupStatus)
}
// checkCleanupStatus validates the cleanup status against removal safety rules.
// Returns an error if removal should be blocked based on the status.
// force=true: allow has_uncommitted and has_unpushed, block has_stash
// force=false: block all non-clean statuses
func (m *Manager) checkCleanupStatus(name string, status CleanupStatus, force bool) error {
// Clean status is always safe
if status.IsSafe() {
return nil
}
// With force, uncommitted changes can be bypassed
if force && status.CanForceRemove() {
return nil
}
// Map status to appropriate error
switch status {
case CleanupUncommitted:
return &UncommittedWorkError{
PolecatName: name,
Status: &git.UncommittedWorkStatus{HasUncommittedChanges: true},
}
case CleanupStash:
return &UncommittedWorkError{
PolecatName: name,
Status: &git.UncommittedWorkStatus{StashCount: 1},
}
case CleanupUnpushed:
return &UncommittedWorkError{
PolecatName: name,
Status: &git.UncommittedWorkStatus{UnpushedCommits: 1},
}
default:
// Unknown status - be conservative and block
return &UncommittedWorkError{
PolecatName: name,
Status: &git.UncommittedWorkStatus{HasUncommittedChanges: true},
}
}
}
// repoBase returns the git directory and Git object to use for worktree operations.
// Prefers the shared bare repo (.repo.git) if it exists, otherwise falls back to mayor/rig.
// The bare repo architecture allows all worktrees (refinery, polecats) to share branch visibility.
func (m *Manager) repoBase() (*git.Git, error) {
// First check for shared bare repo (new architecture)
bareRepoPath := filepath.Join(m.rig.Path, ".repo.git")
if info, err := os.Stat(bareRepoPath); err == nil && info.IsDir() {
// Bare repo exists - use it
return git.NewGitWithDir(bareRepoPath, ""), nil
}
// Fall back to mayor/rig (legacy architecture)
mayorPath := filepath.Join(m.rig.Path, "mayor", "rig")
if _, err := os.Stat(mayorPath); os.IsNotExist(err) {
return nil, fmt.Errorf("no repo base found (neither .repo.git nor mayor/rig exists)")
}
return git.NewGit(mayorPath), nil
}
// polecatDir returns the parent directory for a polecat.
// This is polecats/<name>/ - the polecat's home directory.
func (m *Manager) polecatDir(name string) string {
return filepath.Join(m.rig.Path, "polecats", name)
}
// pendingPath returns the path of the allocation reservation marker for a name.
// Written inside the pool lock by AllocateName; removed by AddWithOptions after
// the polecat directory is created. Prevents concurrent processes from allocating
// the same name during the window between pool save and directory creation.
func (m *Manager) pendingPath(name string) string {
return filepath.Join(m.rig.Path, "polecats", name+".pending")
}
// clonePath returns the path where the git worktree lives.
// New structure: polecats/<name>/<rigname>/ - gives LLMs recognizable repo context.
// Falls back to old structure: polecats/<name>/ for backward compatibility.
func (m *Manager) clonePath(name string) string {
// New structure: polecats/<name>/<rigname>/
newPath := filepath.Join(m.rig.Path, "polecats", name, m.rig.Name)
if info, err := os.Stat(newPath); err == nil && info.IsDir() {
return newPath
}
// Old structure: polecats/<name>/ (backward compat)
oldPath := filepath.Join(m.rig.Path, "polecats", name)
if info, err := os.Stat(oldPath); err == nil && info.IsDir() {
// Check if this is actually a git worktree (has .git file or dir)
gitPath := filepath.Join(oldPath, ".git")
if _, err := os.Stat(gitPath); err == nil {
return oldPath
}
}
// Default to new structure for new polecats
return newPath
}
// ClonePath returns the path to a polecat's git worktree.
func (m *Manager) ClonePath(name string) string {
return m.clonePath(name)
}
// exists checks if a polecat exists.
func (m *Manager) exists(name string) bool {
_, err := os.Stat(m.polecatDir(name))
return err == nil
}
// AddOptions configures polecat creation.
type AddOptions struct {
HookBead string // Bead ID to set as hook_bead at spawn time (atomic assignment)
BaseBranch string // Override base branch for worktree (e.g., "origin/integration/gt-epic")
}
// Add creates a new polecat as a git worktree from the repo base.
// Uses the shared bare repo (.repo.git) if available, otherwise mayor/rig.
// This is much faster than a full clone and shares objects with all worktrees.
// buildBranchName creates a branch name using the configured template or default format.
// Supported template variables:
// - {user}: git config user.name
// - {year}: current year (YY format)
// - {month}: current month (MM format)
// - {name}: polecat name
// - {issue}: issue ID (without prefix)
// - {description}: sanitized issue title
// - {timestamp}: unique timestamp
//
// If no template is configured or template is empty, uses default format:
// - polecat/{name}/{issue}@{timestamp} when issue is available
// - polecat/{name}-{timestamp} otherwise
func (m *Manager) buildBranchName(name, issue string) string {
template := m.rig.GetStringConfig("polecat_branch_template")
// No template configured - use default behavior for backward compatibility
if template == "" {
timestamp := strconv.FormatInt(time.Now().UnixMilli(), 36)
if issue != "" {
return fmt.Sprintf("polecat/%s/%s@%s", name, issue, timestamp)
}
return fmt.Sprintf("polecat/%s-%s", name, timestamp)
}
// Build template variables
vars := make(map[string]string)
// {user} - from git config user.name
if userName, err := m.git.ConfigGet("user.name"); err == nil && userName != "" {
vars["{user}"] = userName
} else {
vars["{user}"] = "unknown"
}
// {year} and {month}
now := time.Now()
vars["{year}"] = now.Format("06") // YY format
vars["{month}"] = now.Format("01") // MM format
// {name}
vars["{name}"] = name
// {timestamp}
vars["{timestamp}"] = strconv.FormatInt(now.UnixMilli(), 36)
// {issue} - issue ID without prefix
if issue != "" {
// Strip prefix (e.g., "gt-123" -> "123")
if idx := strings.Index(issue, "-"); idx >= 0 {
vars["{issue}"] = issue[idx+1:]
} else {
vars["{issue}"] = issue
}
} else {
vars["{issue}"] = ""
}
// {description} - try to get from beads if issue is set
if issue != "" {
if issueData, err := m.beads.Show(issue); err == nil && issueData.Title != "" {
// Sanitize title for branch name: lowercase, replace spaces/special chars with hyphens
desc := strings.ToLower(issueData.Title)
desc = strings.Map(func(r rune) rune {
if (r >= 'a' && r <= 'z') || (r >= '0' && r <= '9') {
return r
}
return '-'
}, desc)
// Remove consecutive hyphens and trim
desc = strings.Trim(desc, "-")
for strings.Contains(desc, "--") {
desc = strings.ReplaceAll(desc, "--", "-")
}
// Limit length to keep branch names reasonable
if len(desc) > 40 {
desc = desc[:40]
}
vars["{description}"] = desc
} else {
vars["{description}"] = ""
}
} else {
vars["{description}"] = ""
}
// Replace all variables in template
result := template
for key, value := range vars {
result = strings.ReplaceAll(result, key, value)
}
// Clean up any remaining empty segments (e.g., "adam///" -> "adam")
parts := strings.Split(result, "/")
cleanParts := make([]string, 0, len(parts))
for _, part := range parts {
if part != "" {
cleanParts = append(cleanParts, part)
}
}
result = strings.Join(cleanParts, "/")
return result
}
// Polecat state is derived from beads assignee field, not state.json.
//
// Branch naming: Each polecat run gets a unique branch (polecat/<name>-<timestamp>).
// This prevents drift issues from stale branches and ensures a clean starting state.
// Old branches are ephemeral and never pushed to origin.
func (m *Manager) Add(name string) (*Polecat, error) {
return m.AddWithOptions(name, AddOptions{})
}
// AllocateAndAdd atomically allocates a name and creates a polecat.
// This eliminates the TOCTOU race between AllocateName and AddWithOptions
// (GH#2215) by holding the pool lock through directory creation, ensuring
// no concurrent process can allocate the same name.
func (m *Manager) AllocateAndAdd(opts AddOptions) (string, *Polecat, error) {
// Hold pool lock across allocation + directory creation to close the
// race window where a concurrent AllocateName could miss the pending
// marker and reallocate the same name.
poolLock, err := m.lockPool()
if err != nil {
return "", nil, err
}
m.reconcilePoolInternal()
name, err := m.namePool.Allocate()
if err != nil {
_ = poolLock.Unlock()
return "", nil, err
}
if err := m.namePool.Save(); err != nil {
_ = poolLock.Unlock()
return "", nil, fmt.Errorf("saving pool state: %w", err)
}
// Acquire per-polecat lock while still holding pool lock
polecatLock, err := m.lockPolecat(name)
if err != nil {
_ = poolLock.Unlock()
return "", nil, err
}
// Create polecat directory while holding both locks
polecatDir := m.polecatDir(name)
if err := os.MkdirAll(polecatDir, 0755); err != nil {
_ = polecatLock.Unlock()
_ = poolLock.Unlock()
return "", nil, fmt.Errorf("creating polecat dir: %w", err)
}
// Kill any lingering tmux session for this name (gt-pqf9x)
if m.tmux != nil {
sessionName := session.PolecatSessionName(session.PrefixFor(m.rig.Name), name)
if alive, _ := m.tmux.HasSession(sessionName); alive {
_ = m.tmux.KillSessionWithProcesses(sessionName)
}
}
// Directory exists — pool lock can be released. No concurrent AllocateName
// can reallocate this name because reconcilePoolInternal will see the directory.
_ = poolLock.Unlock()
// Continue with the rest of AddWithOptions under the polecat lock only.
// addWithOptionsLocked expects the polecat directory to already exist
// and the polecat lock to be held by the caller.
p, err := m.addWithOptionsLocked(name, opts, polecatDir)
_ = polecatLock.Unlock()
if err != nil {
return "", nil, err
}
return name, p, nil
}
// addWithOptionsLocked performs the expensive parts of polecat creation
// (worktree, beads, settings) after the directory has been created.
// Caller MUST hold the polecat lock and have already created polecatDir.
func (m *Manager) addWithOptionsLocked(name string, opts AddOptions, polecatDir string) (_ *Polecat, retErr error) {
defer func() { telemetry.RecordPolecatSpawn(context.Background(), name, retErr) }()
// Pre-check: Verify sufficient disk space before expensive worktree creation.
if level, msg, err := util.CheckDiskSpace(m.rig.Path); err == nil && level == util.DiskSpaceCritical {
return nil, fmt.Errorf("%w: %s", ErrDiskSpaceLow, msg)
}
clonePath := filepath.Join(polecatDir, m.rig.Name)
branchName := m.buildBranchName(name, opts.HookBead)
// Track resources created for rollback on error.
var worktreeCreated bool
cleanupOnError := func() {
aid := m.agentBeadID(name)
_ = m.beads.ResetAgentBeadForReuse(aid, "spawn rollback")
if worktreeCreated {
if rg, repoErr := m.repoBase(); repoErr == nil {
_ = rg.WorktreeRemove(clonePath, true)
}
}
_ = os.RemoveAll(polecatDir)
m.namePool.Release(name)
_ = m.namePool.Save()
}
repoGit, err := m.repoBase()
if err != nil {
cleanupOnError()
return nil, fmt.Errorf("finding repo base: %w", err)
}
if err := repoGit.Fetch("origin"); err != nil {
style.PrintWarning("could not fetch origin: %v", err)
}
var startPoint string
if opts.BaseBranch != "" {
startPoint = opts.BaseBranch
} else {
defaultBranch := "main"
if rigCfg, err := rig.LoadRigConfig(m.rig.Path); err == nil && rigCfg.DefaultBranch != "" {
defaultBranch = rigCfg.DefaultBranch
}
startPoint = fmt.Sprintf("origin/%s", defaultBranch)
}
if exists, err := repoGit.RefExists(startPoint); err != nil {
cleanupOnError()
return nil, fmt.Errorf("checking ref %s: %w", startPoint, err)
} else if !exists {
cleanupOnError()
return nil, fmt.Errorf("configured default_branch not found as %s in bare repo\n\n"+
"Possible causes:\n"+
" - Branch doesn't exist on the remote (create it there first)\n"+
" - default_branch is misconfigured (check %s/config.json)\n"+
" - Bare repo fetch failed (try: git -C %s fetch origin)\n\n"+
"Run 'gt doctor' to diagnose.",
startPoint, m.rig.Path, filepath.Join(m.rig.Path, ".repo.git"))
}
if err := repoGit.WorktreeAddFromRef(clonePath, branchName, startPoint); err != nil {
cleanupOnError()
return nil, fmt.Errorf("creating worktree from %s: %w", startPoint, err)
}
worktreeCreated = true
// Provision CLAUDE.md with gt done instructions (same as AddWithOptions path).
lockedRigName := filepath.Base(m.rig.Path)
if _, err := templates.CreatePolecatCLAUDEmd(clonePath, lockedRigName, name); err != nil {
style.PrintWarning("could not provision polecat CLAUDE.md: %v", err)
}
if err := m.setupSharedBeads(clonePath); err != nil {
cleanupOnError()
return nil, fmt.Errorf("setting up shared beads: %w (polecat cannot submit MRs without shared beads)", err)
}
if err := beads.ProvisionPrimeMDForWorktree(clonePath); err != nil {
style.PrintWarning("could not provision PRIME.md: %v", err)
}
if err := rig.CopyOverlay(m.rig.Path, clonePath); err != nil {
style.PrintWarning("could not copy overlay files: %v", err)
}
if err := rig.EnsureLocalExcludePatterns(clonePath); err != nil {
style.PrintWarning("could not update local git excludes: %v", err)
}
townRoot := filepath.Dir(m.rig.Path)
runtimeConfig := config.ResolveRoleAgentConfig("polecat", townRoot, m.rig.Path)
polecatSettingsDir := config.RoleSettingsDir("polecat", m.rig.Path)
if err := runtime.EnsureSettingsForRole(polecatSettingsDir, clonePath, "polecat", runtimeConfig); err != nil {
style.PrintWarning("could not install runtime settings: %v", err)
}
if err := rig.RunSetupHooks(m.rig.Path, clonePath); err != nil {
style.PrintWarning("could not run setup hooks: %v", err)
}
agentID := m.agentBeadID(name)
if err = m.createAgentBeadWithRetry(agentID, &beads.AgentFields{
RoleType: "polecat",
Rig: m.rig.Name,
AgentState: "spawning",
HookBead: opts.HookBead,
}); err != nil {
cleanupOnError()
return nil, fmt.Errorf("agent bead required for polecat tracking: %w", err)
}
now := time.Now()
polecat := &Polecat{
Name: name,
Rig: m.rig.Name,
State: StateWorking,
ClonePath: clonePath,
Branch: branchName,
CreatedAt: now,
UpdatedAt: now,
}
return polecat, nil
}
// AddWithOptions creates a new polecat with the specified options.
// This allows setting hook_bead atomically at creation time, avoiding
// cross-beads routing issues when slinging work to new polecats.
func (m *Manager) AddWithOptions(name string, opts AddOptions) (_ *Polecat, retErr error) {
defer func() { telemetry.RecordPolecatSpawn(context.Background(), name, retErr) }()
// Acquire per-polecat file lock to prevent concurrent Add/Remove/Repair races
fl, err := m.lockPolecat(name)
if err != nil {
return nil, err
}
defer func() { _ = fl.Unlock() }()
if m.exists(name) {
return nil, ErrPolecatExists
}
// Pre-check: Verify sufficient disk space before creating worktree.
// Spawning a polecat creates a git worktree, copies overlay files, and writes
// beads state — all requiring disk I/O. If the disk is nearly full, fail early
// with a clear message rather than leaving a half-created polecat.
// See: disk-space-resilience — 5 polecats died silently on disk exhaustion.
if level, msg, err := util.CheckDiskSpace(m.rig.Path); err == nil && level == util.DiskSpaceCritical {
return nil, fmt.Errorf("%w: %s", ErrDiskSpaceLow, msg)
}
// New structure: polecats/<name>/<rigname>/ for LLM ergonomics
// The polecat's home dir is polecats/<name>/, worktree is polecats/<name>/<rigname>/
polecatDir := m.polecatDir(name)
clonePath := filepath.Join(polecatDir, m.rig.Name)
// Build branch name using configured template or default format
branchName := m.buildBranchName(name, opts.HookBead)
// Create polecat directory (polecats/<name>/)
if err := os.MkdirAll(polecatDir, 0755); err != nil {
return nil, fmt.Errorf("creating polecat dir: %w", err)
}
// Directory created — remove the allocation reservation marker.
// reconcilePoolInternal will now find the directory directly and treat the
// name as in-use without needing the .pending file.
_ = os.Remove(m.pendingPath(name))
// Track resources created for rollback on error.
// AddWithOptions creates several resources in sequence (directory, worktree,
// agent bead); on failure, all created resources must be cleaned up to prevent
// leaking names, orphaning beads, or leaving stale worktree registrations.
// See: gt-2vs22
var worktreeCreated bool
cleanupOnError := func() {
// Best-effort reset of agent bead (may have been partially created
// by a failed createAgentBeadWithRetry)
aid := m.agentBeadID(name)
_ = m.beads.ResetAgentBeadForReuse(aid, "spawn rollback")
// Remove git worktree registration if worktree was successfully added.
// Must happen before directory removal so git can clean up properly.
if worktreeCreated {
if rg, repoErr := m.repoBase(); repoErr == nil {
_ = rg.WorktreeRemove(clonePath, true)
}
}
// Remove polecat directory
_ = os.RemoveAll(polecatDir)
// Release name back to pool so it can be reallocated immediately
// rather than waiting for the next reconcile cycle.
m.namePool.Release(name)
_ = m.namePool.Save()
}
// Get the repo base (bare repo or mayor/rig)
repoGit, err := m.repoBase()
if err != nil {
cleanupOnError()
return nil, fmt.Errorf("finding repo base: %w", err)
}
// Fetch latest from origin to ensure worktree starts from up-to-date code
if err := repoGit.Fetch("origin"); err != nil {
// Non-fatal - proceed with potentially stale code
style.PrintWarning("could not fetch origin: %v", err)
}
// Determine the start point for the new worktree
var startPoint string
if opts.BaseBranch != "" {
startPoint = opts.BaseBranch
} else {
defaultBranch := "main"
if rigCfg, err := rig.LoadRigConfig(m.rig.Path); err == nil && rigCfg.DefaultBranch != "" {
defaultBranch = rigCfg.DefaultBranch
}
startPoint = fmt.Sprintf("origin/%s", defaultBranch)
}
// Validate that startPoint ref exists before attempting worktree creation
if exists, err := repoGit.RefExists(startPoint); err != nil {
cleanupOnError()
return nil, fmt.Errorf("checking ref %s: %w", startPoint, err)
} else if !exists {
cleanupOnError()
return nil, fmt.Errorf("configured default_branch not found as %s in bare repo\n\n"+
"Possible causes:\n"+
" - Branch doesn't exist on the remote (create it there first)\n"+
" - default_branch is misconfigured (check %s/config.json)\n"+
" - Bare repo fetch failed (try: git -C %s fetch origin)\n\n"+
"Run 'gt doctor' to diagnose.",
startPoint, m.rig.Path, filepath.Join(m.rig.Path, ".repo.git"))
}
// Always create fresh branch - unique name guarantees no collision
// git worktree add -b polecat/<name>-<timestamp> <path> <startpoint>
// Worktree goes in polecats/<name>/<rigname>/ for LLM ergonomics
if err := repoGit.WorktreeAddFromRef(clonePath, branchName, startPoint); err != nil {
cleanupOnError()
return nil, fmt.Errorf("creating worktree from %s: %w", startPoint, err)
}
worktreeCreated = true
// Provision CLAUDE.md with gt done instructions and lifecycle context.
// This is the primary mechanism for polecats to learn about completion —
// the file persists across compaction and session restarts (unlike ephemeral
// gt prime output which scrolls past and gets lost).
rigName := filepath.Base(m.rig.Path)
if _, err := templates.CreatePolecatCLAUDEmd(clonePath, rigName, name); err != nil {
// Non-fatal — polecat can still learn via gt prime hook
style.PrintWarning("could not provision polecat CLAUDE.md: %v", err)
}
// Set up shared beads: polecat uses rig's .beads via redirect file.
// This eliminates git sync overhead - all polecats share one database.
// Fatal: without shared beads, gt done writes MR beads to a local .beads/
// that the Refinery never reads, causing the merge queue to stay empty.
if err := m.setupSharedBeads(clonePath); err != nil {
cleanupOnError()
return nil, fmt.Errorf("setting up shared beads: %w (polecat cannot submit MRs without shared beads)", err)
}
// Provision PRIME.md with Gas Town context for this worker.
// This is the fallback if SessionStart hook fails - ensures polecats
// always have GUPP and essential Gas Town context.
if err := beads.ProvisionPrimeMDForWorktree(clonePath); err != nil {
// Non-fatal - polecat can still work via hook, warn but don't fail
style.PrintWarning("could not provision PRIME.md: %v", err)
}
// Copy overlay files from .runtime/overlay/ to polecat root.
// This allows services to have .env and other config files at their root.
if err := rig.CopyOverlay(m.rig.Path, clonePath); err != nil {
// Non-fatal - log warning but continue
style.PrintWarning("could not copy overlay files: %v", err)
}
// Keep worktree runtime ignores local so the tracked tree stays clean.
if err := rig.EnsureLocalExcludePatterns(clonePath); err != nil {
style.PrintWarning("could not update local git excludes: %v", err)
}
// Install runtime settings in the shared polecats parent directory.
// Settings are passed to Claude Code via --settings flag.
townRoot := filepath.Dir(m.rig.Path)