Repository navigation
Expand file tree
/
Copy pathwatch.ts
More file actions
1490 lines (1398 loc) · 63.4 KB
/
Copy pathwatch.ts
File metadata and controls
1490 lines (1398 loc) · 63.4 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
/**
* Phase 5 — GitHub issue watcher: poll a label, fan out into batches, spawn
* worktrees through the EXISTING bash spawner, and track idempotency in a
* durable state file.
*
* Sweep flow (per tick):
* 1. listIssues({ owner, repo, label: targetLabel, state: open }).
* 2. Partition: new (no entry / status pending / failed-with-retry) vs
* already processed (everything else — skipped this sweep).
* 3. Apply the maxPerSweep cap: the first `maxPerSweep` new issues are
* spawned; the rest are recorded as status "pending" so the NEXT sweep
* picks them up (a label storm never spawns more than N worktrees per
* sweep).
* 4. For each spawned issue (write-ahead ordering):
* a. markProcessed(status "spawned") + save ← durable BEFORE spawn
* b. splitIssues([issue]) -> specs
* c. writeTaskFiles(...) + spawn via
* scripts/spawn-parallel-worktrees.sh (bash -c — the bash script
* remains the ACTUAL spawner; no worktree creation in TS)
* d. ordinary issues: markProcessed(status "done" | "failed") + save;
* headlesscode-job issues stay "spawned" until a later poll checks
* their completion markers and updates GitHub lifecycle state
* 5. Log the sweep (issues found / new / skipped / spawned / deferred).
*
* The state file is the idempotency source of truth: a restart loads it and
* continues; a crash between (a) and (d) leaves a "spawned" entry which the
* next restart treats as processed — a double-spawn is impossible.
*/
import { spawnSync } from "node:child_process"
import { createHash, randomUUID } from "node:crypto"
import * as fs from "node:fs"
import * as path from "node:path"
import { fileURLToPath } from "node:url"
import {
activeSessionCount,
ConcurrencyLimiter,
maxConcurrentSessionsFromEnv,
} from "../budget/concurrency.js"
import { Logger } from "../engine/logger.js"
import { museUnsupportedSettingsReason, parseHeadlessCodeJobBody, resolveAgentExecutorSelection, type AgentExecutor, type AgentExecutorSelection } from "../agent-executor.js"
import { splitIssues, type SplitIssue, type WorktreeSpec } from "../orchestrator/split.js"
import { loadStateSync } from "../orchestrator/state.js"
import { writeTaskFiles } from "../orchestrator/task-files.js"
import { createGhClient, DEFAULT_GH_BASE_URL, type GhClient, type GitHubIssue, type GitHubPullRequestSummary } from "./github.js"
import { GitHubIssueClaimStore, type ClaimSnapshot, type RunnerClaim } from "./claims.js"
import {
isProcessed,
loadWatcherState,
markProcessed,
saveWatcherState,
type WatcherIssueEntry,
type WatcherIssueStatus,
type WatcherState,
} from "./state.js"
/** The harness repo root (parent of src/watcher) — same pattern as the CLI. */
const HARNESS_ROOT = fileURLToPath(new URL("../..", import.meta.url))
export const DEFAULT_POLL_INTERVAL_MS = 60_000
export const DEFAULT_MAX_PER_SWEEP = 5
export const HEADLESSCODE_JOB_LABEL = "headlesscode-job"
export interface SpawnBatch {
issue: GitHubIssue
/** Worktree groups from splitIssues([issue]). */
specs: WorktreeSpec[]
/** Local target repo root where worktrees are created. */
repoRoot: string
/** Batch id (watcher-<date>). */
batch: string
/** Random dispatch identity for headlesscode-job supervisor receipts. */
jobAttempt?: string
executor: AgentExecutor
museModel?: string
}
export interface SpawnResult {
ok: boolean
/** The exact bash command that was (or would be) run. */
command?: string
/** True when spawn threw after dispatch may have begun and outcome is uncertain. */
mayHaveDispatched?: boolean
/** spawnSync exit status (null = spawn failed to launch). */
status?: number | null
error?: string
}
export interface WatcherBatchInfo {
issue: GitHubIssue
specs: WorktreeSpec[]
batch: string
statePath: string
/** Recorded status: headlesscode-job remains spawned after detached launch. */
status: WatcherIssueStatus
}
export interface WatcherConfig {
/** GitHub owner (e.g. "my-org"). */
owner: string
/** GitHub repo name (e.g. "my-repo"). */
repo: string
/** The label that triggers processing (e.g. "needs-agent"). */
targetLabel: string
/** GitHub token (GH_TOKEN / GITHUB_TOKEN). Never logged or persisted. */
token: string
/** Sweep interval (default 60000ms). */
pollIntervalMs?: number
/** GitHub API base URL (default: $GITHUB_API_BASE_URL or api.github.com). */
ghBaseUrl?: string
/** Durable state file (default: <repoRoot>/.worktrees/.watcher-state.json). */
stateFile?: string
/** Local target repo root where worktrees are spawned (default: cwd). */
repoRoot?: string
/** Called after each batch is processed (spawn done/failed). */
onBatch?: (info: WatcherBatchInfo) => void | Promise<void>
/** true = one sweep then return; false = continuous loop. */
runOnce?: boolean
/** Abort the loop (continuous mode clean shutdown). */
signal?: AbortSignal
/** Per-sweep cap on newly spawned issues (default 5). */
maxPerSweep?: number
/**
* Concurrent-session cap across orchestrator + watcher state files. In
* runner-pool mode, durable claims also count jobs held by this machine.
* Issues exceeding the cap stay 'pending' and are picked up on a later sweep.
*/
maxConcurrentSessions?: number
/** Stable per-machine identity; enables GitHub-ref claim-based dispatch. */
runnerId?: string
runnerAssignee?: string
/** Lease duration for claim-based runners (default 120 seconds). */
claimLeaseMs?: number
/** Injectable claim store for CPU tests. */
claimStore?: GitHubIssueClaimStore
/** Retry previously-failed issues on the next sweep (default: no). */
retryFailed?: boolean
/** Sweep + report without spawning or writing state. */
dryRun?: boolean
/** Injected GitHub client for tests (default: createGhClient(token)). */
gh?: GhClient
/** Injected spawn function for tests (default: the real bash spawner). */
spawn?: (batch: SpawnBatch) => SpawnResult | Promise<SpawnResult>
/** Harness mode for workers (forwarded to the spawner as ORCHESTRATOR_MODE). */
mode?: string
executionProvider?: "local" | "openshell"
/** Default worker executor; issue labels can select per-job overrides. */
executor?: AgentExecutor
museModel?: string
/** Memory dir for workers (forwarded to the spawner as HEADLESSCODE_MEMORY_DIR). */
memoryDir?: string
/** Phase 4 pass-through: recorded on the batch entry (see docs). */
qa?: boolean
/** Phase 4 pass-through: recorded on the batch entry (see docs). */
deploy?: boolean
logger?: Logger
}
export interface SweepResult {
issuesFound: number
newIssues: number
skipped: number
spawned: number
deferred: number
failures: number
state: WatcherState
/** Dry-run only: what WOULD be spawned per new issue. */
dryRunPlan?: Array<{ issue: GitHubIssue; specs: WorktreeSpec[]; selection?: AgentExecutorSelection }>
error?: string
}
export interface WatchResult {
/** One entry per completed sweep. */
sweeps: SweepResult[]
/** Total batches spawned across all sweeps. */
spawned: number
/** 0 = ok; 1 = one or more spawns failed. */
exitCode: number
}
/**
* Run the watcher. Continuous mode loops until the abort signal fires;
* `runOnce` performs a single sweep and returns. State is loaded from disk at
* startup (restart-safe) and saved after every sweep.
*/
export async function watchIssues(config: WatcherConfig): Promise<WatchResult> {
const owner = config.owner
const repo = config.repo
const targetLabel = config.targetLabel
const token = config.token
if (!token) {
throw new Error("watcher: no GitHub token (set GH_TOKEN or GITHUB_TOKEN)")
}
if (!owner || !repo || !targetLabel) {
throw new Error("watcher: owner, repo and targetLabel are required")
}
const repoRoot = path.resolve(config.repoRoot ?? process.cwd())
const statePath = path.resolve(config.stateFile ?? path.join(repoRoot, ".worktrees", ".watcher-state.json"))
const pollIntervalMs = config.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS
const maxPerSweep = config.maxPerSweep ?? DEFAULT_MAX_PER_SWEEP
// One in-process limiter per watchIssues run guards the sweep spawn loop;
// durable state and (in runner-pool mode) claims guard machine capacity.
const maxConcurrentSessions = config.maxConcurrentSessions ?? maxConcurrentSessionsFromEnv()
if (config.runnerId && config.runOnce && !config.dryRun) throw new Error("watcher runner pool requires continuous mode; --run-once cannot maintain claim leases")
if (config.runnerId && !/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/.test(config.runnerId)) throw new Error("watcher: runnerId must be a stable safe identifier")
if (config.runnerId && !config.runnerAssignee) throw new Error("watcher runner pool requires runnerAssignee so the GitHub issue shows its current claimant")
const claimStore = config.claimStore ?? (config.runnerId ? new GitHubIssueClaimStore({
token,
owner,
repo,
runnerId: config.runnerId,
runnerAssignee: config.runnerAssignee,
...(config.ghBaseUrl ? { baseUrl: config.ghBaseUrl } : {}),
...(config.claimLeaseMs ? { leaseMs: config.claimLeaseMs } : {}),
}) : undefined)
if (config.runnerId && claimStore && pollIntervalMs > Math.floor(claimStore.leaseDurationMs / 2)) {
throw new Error(`watcher runner pool poll interval (${pollIntervalMs}ms) must be at most half the claim lease (${claimStore.leaseDurationMs}ms) so claims can be renewed before expiry`)
}
const limiter = new ConcurrencyLimiter(maxConcurrentSessions)
const gh = config.gh ?? createGhClient({ token, baseUrl: config.ghBaseUrl })
const logger = config.logger ?? new Logger({ level: "info" })
const spawn = config.spawn ?? ((batch: SpawnBatch): SpawnResult => defaultSpawn(batch, config))
const qa = config.qa ?? false
const deploy = config.deploy ?? false
let state = await loadWatcherState(statePath)
const sweeps: SweepResult[] = []
let spawnedTotal = 0
let exitCode = 0
for (;;) {
if (config.signal?.aborted) {
break
}
const sweep = await sweepOnce({
gh,
ghBaseUrl: config.ghBaseUrl,
owner,
repo,
targetLabel,
state,
statePath,
repoRoot,
maxPerSweep,
maxConcurrentSessions,
...(claimStore ? { claimStore } : {}),
runnerId: config.runnerId,
executor: config.executor,
museModel: config.museModel,
mode: config.mode ?? "code",
executionProvider: config.executionProvider ?? "local",
memoryDir: config.memoryDir,
limiter,
retryFailed: config.retryFailed,
dryRun: config.dryRun,
spawn,
onBatch: config.onBatch,
logger,
qa,
deploy,
})
state = sweep.state
sweeps.push(sweep)
spawnedTotal += sweep.spawned
// A list failure OR any failed spawn makes the run "error out"
// (runOnce exits 1; continuous mode logs and keeps going).
if (sweep.error || sweep.failures > 0) {
exitCode = 1
}
if (config.runOnce) {
break
}
await sleepOrAbort(pollIntervalMs, config.signal)
}
if (config.signal?.aborted && claimStore && config.runnerId) {
state = await stopRunnerClaims(state, claimStore, config.runnerId, repoRoot, logger)
}
// Final save so lastSweep is durable even after a clean abort.
// Dry-run writes nothing at all.
if (!config.dryRun) {
await saveWatcherState(statePath, state)
}
return { sweeps, spawned: spawnedTotal, exitCode }
}
interface SweepInput {
gh: GhClient
ghBaseUrl?: string
owner: string
repo: string
targetLabel: string
state: WatcherState
statePath: string
repoRoot: string
maxPerSweep: number
/** Phase 6: global concurrent-session cap (see WatcherConfig). */
maxConcurrentSessions: number
claimStore?: GitHubIssueClaimStore
runnerId?: string
executor?: AgentExecutor
museModel?: string
mode: string
executionProvider: "local" | "openshell"
memoryDir?: string
/** Phase 6: in-process limiter guarding the sweep spawn loop. */
limiter: ConcurrencyLimiter
retryFailed?: boolean
dryRun?: boolean
spawn: (batch: SpawnBatch) => SpawnResult | Promise<SpawnResult>
onBatch?: (info: WatcherBatchInfo) => void | Promise<void>
logger: Logger
/** Recorded on each batch entry (pass-through for the follow-up round). */
qa: boolean
/** Recorded on each batch entry (pass-through for the follow-up round). */
deploy: boolean
}
/** One full sweep: list → partition → cap (per-sweep + global) → spawn → log. */
async function sweepOnce(input: SweepInput): Promise<SweepResult> {
const {
gh,
owner,
repo,
targetLabel,
statePath,
repoRoot,
maxPerSweep,
maxConcurrentSessions,
limiter,
retryFailed,
dryRun,
spawn,
logger,
} = input
let state = input.state
let activeRunnerClaims: ClaimSnapshot[] = []
const foreignRunnerClaimIssues = new Set<number>()
const runnerPoolClaimConflictIssues = new Set<number>()
if (input.claimStore && input.runnerId && !dryRun) {
try {
const all = await input.claimStore.listActiveClaims()
for (const snapshot of all) {
if (snapshot.claim.runnerId !== input.runnerId) foreignRunnerClaimIssues.add(snapshot.claim.issue)
}
activeRunnerClaims = all.filter((entry) => entry.claim.runnerId === input.runnerId)
const reconciled = await reconcileRunnerClaims(state, activeRunnerClaims, input.claimStore, repoRoot, logger)
state = reconciled.state
activeRunnerClaims = reconciled.claims
} catch (err) {
state = await stopLocalClaimsOnUncertainty(state, repoRoot, logger)
const error = `watcher claim check failed; local workers were stopped where teardown could be confirmed and claims remain quarantined: ${err instanceof Error ? err.message : String(err)}`
logger.error(error)
return { issuesFound: 0, newIssues: 0, skipped: 0, spawned: 0, deferred: 0, failures: 0, state, error }
}
}
let issues: GitHubIssue[]
try {
issues = await gh.listIssues({ owner, repo, label: targetLabel, state: "open" })
} catch (err) {
const error = `watcher sweep failed listing issues for ${owner}/${repo}: ${
err instanceof Error ? err.message : String(err)
}`
logger.error(error)
return { issuesFound: 0, newIssues: 0, skipped: 0, spawned: 0, deferred: 0, failures: 0, state, error }
}
// Deterministic processing order (ascending issue number).
issues = [...issues].sort((a, b) => a.number - b.number)
const reconciledJobs = await reconcileHeadlessCodeJobs({
state,
issues,
gh,
owner,
repo,
repoRoot,
ghBaseUrl: input.ghBaseUrl,
claims: activeRunnerClaims,
claimStore: input.claimStore,
dryRun,
logger,
})
state = reconciledJobs.state
const newIssues = issues.filter((i) => !isProcessedForSweep(state, i.number, retryFailed))
const skipped = issues.length - newIssues.length
// maxPerSweep bounds a single sweep's burst; the cap bounds the running
// sessions seen across local durable state and (in runner-pool mode) claims
// (orchestrator groups in spawned/running + watcher in-flight 'spawned'
// entries). Effective new spawns this sweep:
// min(maxPerSweep, maxConcurrentSessions - active)
// Issues beyond it stay 'pending' (same durable deferral as maxPerSweep
// overflow) and are picked up on a later sweep. Missing orchestrator state
// file → active = 0 (the cap still applies to this pipeline alone).
const orchPath = path.join(repoRoot, ".worktrees", ".orchestrator-state.json")
const orchState = loadStateSync(orchPath)
const localActive = activeSessionCount(orchState, state)
// A claim is per issue, but an issue may fan out into several worktrees.
// Capacity is per worker session, so count every assigned worktree (including
// quarantined claims retained by reconciliation).
const active = input.claimStore && input.runnerId
? countRunnerPoolSessions(orchState, state, activeRunnerClaims)
: localActive
const available = Math.max(0, maxConcurrentSessions - active)
const runnerPoolMode = !!input.claimStore && !!input.runnerId && !dryRun
// A different runner may own an earlier issue in the sorted list. In pool
// mode, scan past claim conflicts until this machine fills its available
// slots; otherwise a held lowest-numbered issue can starve every later one.
const toSpawn = runnerPoolMode
? newIssues
: newIssues.slice(0, Math.min(maxPerSweep, available))
let deferred = runnerPoolMode ? newIssues : newIssues.slice(toSpawn.length)
const runnerPoolIssueLimit = Math.min(maxPerSweep, available)
let runnerPoolCandidatesConsidered = 0
// Accounting for the sweep log: how much of the deferral was maxPerSweep
// vs the global cap (both ≥ 0).
let maxPerSweepDeferred = newIssues.length - Math.min(newIssues.length, maxPerSweep)
let globalCapDeferred = deferred.length - maxPerSweepDeferred
const dryRunPlan: SweepResult["dryRunPlan"] = dryRun ? [] : undefined
let spawned = 0
let failures = reconciledJobs.failures
// Naming collision avoidance (mirrors orchestrator/cli.ts's orchestrate
// path): seed from whatever `.worktrees/wN` dirs already exist — a
// still-running `orchestrate` round, or an earlier sweep this same
// process — then reserve each issue's assigned names as we go, so two
// issues spawned in the SAME sweep never both land on w1 either.
let occupiedNames: Set<string>
try {
occupiedNames = new Set(
fs
.readdirSync(path.join(repoRoot, ".worktrees"), { withFileTypes: true })
.filter((d) => d.isDirectory())
.map((d) => d.name),
)
} catch {
occupiedNames = new Set()
}
// Record deferred issues as "pending" so the next sweep picks them up
// (persisted by the per-issue saves below, or the final save). Dry-run
// writes nothing.
if (!dryRun) {
for (const issue of deferred) {
state = markProcessed(state, pendingEntry(issue, targetLabel))
}
}
for (const issue of toSpawn) {
if (runnerPoolMode && runnerPoolCandidatesConsidered >= runnerPoolIssueLimit) break
if (runnerPoolMode && foreignRunnerClaimIssues.has(issue.number)) continue
if (runnerPoolMode) runnerPoolCandidatesConsidered++
const prior = state.processed[String(issue.number)]
const retryingFailed = retryFailed && prior?.status === "failed"
const isHeadlessCodeJob = issue.labels.includes(HEADLESSCODE_JOB_LABEL)
const parsedJob = isHeadlessCodeJob ? parseHeadlessCodeJobBody(issue.body) : undefined
if (parsedJob && !parsedJob.submission) {
const message = `watcher: issue #${issue.number} has invalid headlesscode-job intake: ${parsedJob.error}`
logger.error(message, { issue: issue.number })
failures++
if (!dryRun) {
state = markProcessed(state, {
number: issue.number,
title: issue.title,
label: targetLabel,
...(isHeadlessCodeJob ? { jobContract: true } : {}),
status: "failed",
updatedAt: new Date().toISOString(),
error: message,
})
await saveWatcherState(statePath, state)
if (isHeadlessCodeJob) await reportJobIntakeFailure(gh, owner, repo, issue.number, message, logger)
}
continue
}
const dispatchIssue = parsedJob?.submission ? { ...issue, body: parsedJob.submission.task } : issue
const retryModelLabels = issue.labels.filter((label) => /^muse-model(?::|$)/i.test(label))
if (retryingFailed && prior?.executor && (retryModelLabels.length > 1 || (retryModelLabels.length === 1 && retryModelLabels[0]!.slice(retryModelLabels[0]!.indexOf(":") + 1) !== (prior.museModel ?? "")))) {
const message = `watcher: issue #${issue.number} Muse model label changed since its failed spawn; restore the recorded selection before retrying`
logger.error(message, { issue: issue.number })
failures++
if (isHeadlessCodeJob && !dryRun) {
state = markProcessed(state, { ...prior!, jobContract: true, status: "failed", error: message, updatedAt: new Date().toISOString() })
await saveWatcherState(statePath, state)
await reportJobIntakeFailure(gh, owner, repo, issue.number, message, logger)
}
continue
}
const selectionDefaults = retryingFailed && prior?.executor
? { executor: prior.executor, museModel: prior.museModel }
: { executor: input.executor, museModel: input.museModel }
const resolvedSelection = resolveAgentExecutorSelection(issue.labels, selectionDefaults, parsedJob?.submission?.executor)
if (!resolvedSelection.selection) {
const message = `watcher: issue #${issue.number} has invalid agent selection: ${resolvedSelection.error}`
logger.error(message, { issue: issue.number })
failures++
if (!dryRun) {
const failedAt = new Date().toISOString()
state = markProcessed(state, {
number: issue.number,
title: issue.title,
label: targetLabel,
...(isHeadlessCodeJob ? { jobContract: true } : {}),
status: "failed",
updatedAt: failedAt,
error: message,
})
await saveWatcherState(statePath, state)
if (isHeadlessCodeJob) await reportJobIntakeFailure(gh, owner, repo, issue.number, message, logger)
}
continue
}
const selection = resolvedSelection.selection
if (selection.executor === "muse" && (input.mode !== "code" || input.executionProvider !== "local")) {
const message = `watcher: issue #${issue.number} selects Muse, which requires local execution and mode code`
logger.error(message, { issue: issue.number })
failures++
if (!dryRun) {
const failedAt = new Date().toISOString()
state = markProcessed(state, {
number: issue.number,
title: issue.title,
label: targetLabel,
...(isHeadlessCodeJob ? { jobContract: true } : {}),
status: "failed",
updatedAt: failedAt,
error: message,
executor: selection.executor,
...(selection.museModel ? { museModel: selection.museModel } : {}),
})
await saveWatcherState(statePath, state)
if (isHeadlessCodeJob) await reportJobIntakeFailure(gh, owner, repo, issue.number, message, logger)
}
continue
}
if (selection.executor === "muse") {
const unsupported = museUnsupportedSettingsReason(input.memoryDir)
if (unsupported) {
const message = `watcher: issue #${issue.number} selects Muse, but ${unsupported}`
logger.error(message, { issue: issue.number })
failures++
if (!dryRun) {
const failedAt = new Date().toISOString()
state = markProcessed(state, {
number: issue.number,
title: issue.title,
label: targetLabel,
...(isHeadlessCodeJob ? { jobContract: true } : {}),
status: "failed",
updatedAt: failedAt,
error: message,
executor: selection.executor,
...(selection.museModel ? { museModel: selection.museModel } : {}),
})
await saveWatcherState(statePath, state)
if (isHeadlessCodeJob) await reportJobIntakeFailure(gh, owner, repo, issue.number, message, logger)
}
continue
}
}
const specs = splitIssues([dispatchIssue], { occupiedNames })
for (const spec of specs) {
occupiedNames.add(spec.name)
}
if (dryRun) {
dryRunPlan!.push({ issue: dispatchIssue, specs, selection })
continue
}
// In-process fail-fast guard (ConcurrencyLimiter). The durable-state
// view above already pre-capped toSpawn, so this only fires if the
// fleet picture changed mid-sweep (another process spawned); the issue
// is deferred to 'pending' rather than over-spawning.
const acq = limiter.acquire()
if (!acq.ok) {
state = markProcessed(state, pendingEntry(issue, targetLabel))
logger.warn(`watcher: issue #${issue.number} deferred by the global concurrency cap — ${acq.reason}`, {})
continue
}
try {
let ownedClaim: RunnerClaim | undefined
if (input.claimStore && input.runnerId) {
let acquired
try {
acquired = await input.claimStore.acquire(issue.number, { worktreeNames: specs.map((spec) => spec.name) })
} catch (err) {
state = markProcessed(state, pendingEntry(issue, targetLabel))
await saveWatcherState(statePath, state)
failures++
logger.error(`watcher: claim acquisition failed for issue #${issue.number}; no worker spawned: ${err instanceof Error ? err.message : String(err)}`)
continue
}
if (!acquired.acquired) {
state = markProcessed(state, pendingEntry(issue, targetLabel))
logger.info(`watcher: issue #${issue.number} deferred; claim ${acquired.reason} on runner ${acquired.claim.runnerId}`)
if (runnerPoolMode) {
runnerPoolCandidatesConsidered--
runnerPoolClaimConflictIssues.add(issue.number)
}
continue
}
ownedClaim = acquired.claim
}
// ── Write-ahead: durable "spawned" entry BEFORE the spawn ──
const batch = batchId()
const spawnedAt = new Date().toISOString()
const jobAttempt = isHeadlessCodeJob ? randomUUID() : undefined
const entry: WatcherIssueEntry = {
number: issue.number,
title: issue.title,
label: targetLabel,
batch,
groups: specs,
spawnedAt,
status: "spawned",
updatedAt: spawnedAt,
...(isHeadlessCodeJob ? { jobContract: true } : {}),
...(jobAttempt ? { jobAttempt } : {}),
...(parsedJob?.submission ? { submittedBy: parsedJob.submission.submittedBy } : {}),
...(input.qa ? { qa: true } : {}),
...(input.deploy ? { deploy: true } : {}),
executor: selection.executor,
...(selection.museModel ? { museModel: selection.museModel } : {}),
...(ownedClaim ? { claim: claimReference(ownedClaim) } : {}),
}
state = markProcessed(state, entry)
await saveWatcherState(statePath, state)
if (jobAttempt) {
try {
const dir = jobReceiptDirectory(repoRoot, jobAttempt)
fs.mkdirSync(dir, { recursive: true, mode: 0o700 })
fs.chmodSync(dir, 0o700)
} catch (error) {
state = markProcessed(state, { ...entry, status: "failed", error: `could not prepare private supervisor receipt directory: ${safeError(error)}` })
await saveWatcherState(statePath, state)
failures++
continue
}
}
if (ownedClaim && input.claimStore) {
try {
ownedClaim = await input.claimStore.verifyActive(issue.number, ownedClaim)
} catch (err) {
await releaseClaimIfNoWorkers(input.claimStore, ownedClaim, logger, "spawn-failed")
state = markProcessed(state, { ...entry, status: "failed", claim: undefined, error: `claim verification failed before dispatch: ${err instanceof Error ? err.message : String(err)}` })
failures++
await saveWatcherState(statePath, state)
continue
}
}
const batchInfo = { issue: dispatchIssue, specs, repoRoot, batch, ...(jobAttempt ? { jobAttempt } : {}), ...selection }
let result: SpawnResult
try {
result = await spawn(batchInfo)
} catch (err) {
result = { ok: false, mayHaveDispatched: true, error: err instanceof Error ? err.message : String(err) }
}
if (result.ok) {
let claimCurrentForLifecycle = true
if (ownedClaim && input.claimStore) {
try {
ownedClaim = await input.claimStore.markRunning(issue.number, ownedClaim)
} catch (err) {
claimCurrentForLifecycle = false
logger.error(`watcher: could not mark issue #${issue.number} claim running; stopping its workers: ${err instanceof Error ? err.message : String(err)}`)
await stopWorkerGroupsBestEffort(repoRoot, ownedClaim.worktreeNames, logger)
logger.warn(`watcher: issue #${issue.number} claim remains quarantined after claim-stage failure; worker markers cannot authorize release`)
}
}
if (entry.jobContract) {
state = markProcessed(state, {
...entry,
status: "spawned",
updatedAt: new Date().toISOString(),
...(ownedClaim ? { claim: claimReference(ownedClaim) } : {}),
})
try {
if (!claimCurrentForLifecycle) throw new Error("claim no longer verified after dispatch")
await setIssueLifecycle(gh, owner, repo, issue.number, "running")
} catch (error) {
failures++
logger.warn(`watcher: issue #${issue.number} launched, but its running label could not be applied; it remains active in local state: ${safeError(error)}`)
}
} else {
state = markProcessed(state, { ...entry, status: "done", updatedAt: new Date().toISOString() })
if (entry.claim && ownedClaim) state = markProcessed(state, { ...entry, status: "done", claim: claimReference(ownedClaim) })
if (entry.claim && !ownedClaim) state = markProcessed(state, { ...entry, status: "done", claim: undefined })
}
spawned++
logger.info(`watcher: ${entry.jobContract ? "launched" : "spawned"} issue #${issue.number} (${specs.map((s) => s.name).join(", ")})`, {
batch,
groups: specs.map((s) => s.taskFile),
})
} else {
const error = result.error ?? `spawn exited ${result.status ?? "unknown"}`
const uncertainJobDispatch = !!entry.jobContract && (!!result.command || !!result.mayHaveDispatched)
let claimReferenceStillActive = !!ownedClaim
if (ownedClaim && input.claimStore) {
if (!result.command && !result.mayHaveDispatched) {
await releaseClaimIfNoWorkers(input.claimStore, ownedClaim, logger, "spawn-failed")
claimReferenceStillActive = false
} else {
if (result.command) await stopWorkerGroupsBestEffort(repoRoot, ownedClaim.worktreeNames, logger)
logger.warn(`watcher: issue #${issue.number} ${result.mayHaveDispatched ? "spawn outcome is uncertain" : "spawn failed after dispatch"}; claim remains quarantined for operator recovery`)
}
}
state = markProcessed(state, {
...entry,
status: uncertainJobDispatch ? "spawned" : "failed",
error,
updatedAt: new Date().toISOString(),
...(claimReferenceStillActive && ownedClaim ? { claim: claimReference(ownedClaim) } : { claim: undefined }),
})
if (entry.jobContract) {
try {
if (uncertainJobDispatch) await setIssueLifecycle(gh, owner, repo, issue.number, "running")
else await setIssueLifecycle(gh, owner, repo, issue.number, "failed")
} catch (lifecycleError) {
logger.warn(`watcher: issue #${issue.number} spawn failure status could not be reflected in GitHub labels: ${safeError(lifecycleError)}`)
}
}
failures++
// Loud by design: a failed spawn is NOT silently retried (default).
// Re-run with --retry-failed to force a retry next sweep.
logger.error(`watcher: spawn FAILED for issue #${issue.number} — ${error}`, { batch })
}
await saveWatcherState(statePath, state)
await input.onBatch?.({ issue, specs, batch, statePath, status: state.processed[String(issue.number)]?.status ?? "failed" })
} finally {
limiter.release()
}
}
state.lastSweep = new Date().toISOString()
if (runnerPoolMode) {
deferred = newIssues.filter((issue) => state.processed[String(issue.number)]?.status === "pending")
const eligibleIssues = newIssues.filter((issue) =>
!foreignRunnerClaimIssues.has(issue.number) && !runnerPoolClaimConflictIssues.has(issue.number),
).length
const withinPerSweepLimit = Math.min(eligibleIssues, maxPerSweep)
maxPerSweepDeferred = eligibleIssues - withinPerSweepLimit
globalCapDeferred = withinPerSweepLimit - Math.min(withinPerSweepLimit, available)
}
if (!dryRun) {
await saveWatcherState(statePath, state)
}
logger.info(`watcher sweep: ${issues.length} issue(s) with label "${targetLabel}"`, {
found: issues.length,
new: newIssues.length,
skipped,
spawned,
deferred: dryRun ? newIssues.length - toSpawn.length : deferred.length,
global_cap_deferred: globalCapDeferred,
max_per_sweep_deferred: maxPerSweepDeferred,
active_sessions: active,
failures,
})
return {
issuesFound: issues.length,
newIssues: newIssues.length,
skipped,
spawned,
deferred: dryRun ? newIssues.length - toSpawn.length : deferred.length,
failures,
state,
...(dryRunPlan ? { dryRunPlan } : {}),
}
}
/** isProcessed plus the retry-failed override (see state.ts). */
function isProcessedForSweep(state: WatcherState, number: number, retryFailed?: boolean): boolean {
return isProcessed(state, number, { retryFailed })
}
function pendingEntry(issue: GitHubIssue, label: string): WatcherIssueEntry {
return {
number: issue.number,
title: issue.title,
label,
status: "pending",
updatedAt: new Date().toISOString(),
}
}
const JOB_LIFECYCLE_LABELS = ["headlesscode:running", "headlesscode:done", "headlesscode:failed"] as const
type JobLifecycle = (typeof JOB_LIFECYCLE_LABELS)[number] extends `headlesscode:${infer S}` ? S : never
interface JobReconcileInput {
state: WatcherState
issues: GitHubIssue[]
gh: GhClient
owner: string
repo: string
repoRoot: string
ghBaseUrl?: string
claims: ClaimSnapshot[]
claimStore?: GitHubIssueClaimStore
dryRun?: boolean
logger: Logger
}
/**
* A successful spawner exit only means detached workers were launched. A
* headlesscode-job stays in the active "spawned" state until every assigned
* worktree publishes both of run-worker.sh's terminal markers. This pass is
* intentionally a later-poll reconciliation; one-shot runs return while the
* issue is still labelled running.
*/
async function reconcileHeadlessCodeJobs(input: JobReconcileInput): Promise<{ state: WatcherState; failures: number }> {
let state = input.state
let failures = 0
const currentIssues = new Map(input.issues.map((issue) => [issue.number, issue]))
for (const entry of Object.values(state.processed)) {
if (!entry.jobContract) continue
if (entry.status === "failed") {
if (input.dryRun || !await verifyJobClaim(entry, input.claims, input.claimStore)) continue
try {
await setIssueLifecycle(input.gh, input.owner, input.repo, entry.number, "failed")
const marker = jobFailureMarker(entry)
const comments = await requireComments(input.gh, input.owner, input.repo, entry.number)
if (!comments.some((body) => body.includes(marker))) {
const completion = readJobCompletion(input.repoRoot, entry.groups ?? [], entry.jobAttempt)
const summary = completion.terminal
? completion.exitCodes.map((code, index) => `${entry.groups?.[index]?.name ?? `worker-${index + 1}`}: exit ${code}`).join("; ")
: safeError(entry.error ?? "job did not start")
const logSummary = completion.terminal ? completion.logs.filter(Boolean).join("\n\n").slice(-8000) : ""
await requireCommentWriter(input.gh)(input.owner, input.repo, entry.number,
`HeadlessCode job failed (${summary}). The watcher does not close failed job issues; review the worker summary before retrying.\n\n${logSummary ? `Bounded worker log summary:\n\n\`\`\`text\n${logSummary}\n\`\`\`\n\n` : ""}${marker}`)
}
} catch (error) {
failures++
input.logger.warn(`watcher: issue #${entry.number} failure result could not be reflected in GitHub; it will retry on a later poll: ${safeError(error)}`)
}
continue
}
if (entry.status !== "spawned") continue
const completion = readJobCompletion(input.repoRoot, entry.groups ?? [], entry.jobAttempt)
if (!completion.terminal) {
const issue = currentIssues.get(entry.number)
const lifecycleOutOfSync = !!issue && (!issue.labels.includes("headlesscode:running") || JOB_LIFECYCLE_LABELS.some((label) => label !== "headlesscode:running" && issue.labels.includes(label)))
if (issue && lifecycleOutOfSync && !input.dryRun && await verifyJobClaim(entry, input.claims, input.claimStore)) {
try { await setIssueLifecycle(input.gh, input.owner, input.repo, entry.number, "running") }
catch (error) { failures++; input.logger.warn(`watcher: issue #${entry.number} is still running, but its lifecycle label could not be refreshed: ${safeError(error)}`) }
}
continue
}
if (!await verifyJobClaim(entry, input.claims, input.claimStore)) {
input.logger.warn(`watcher: issue #${entry.number} completion found, but its runner claim could not be verified; leaving lifecycle unchanged`)
continue
}
if (input.dryRun) continue
const terminal: "done" | "failed" = completion.exitCodes.every((code) => code === 0) ? "done" : "failed"
const summary = completion.exitCodes.map((code, index) => `${entry.groups?.[index]?.name ?? `worker-${index + 1}`}: exit ${code}`).join("; ")
try {
await setIssueLifecycle(input.gh, input.owner, input.repo, entry.number, terminal)
const commentMarker = terminal === "failed" ? jobFailureMarker({ ...entry, error: summary }) : jobCommentMarker(entry)
const priorComments = await requireComments(input.gh, input.owner, input.repo, entry.number)
if (!priorComments.some((body) => body.includes(commentMarker))) {
const logSummary = completion.logs.filter(Boolean).join("\n\n").slice(-8000)
if (terminal === "done") {
const lookup = await findVerifiedJobPullRequests(input, entry)
const prText = lookup.pullRequests.length > 0
? lookup.pullRequests.map((pr) => `- [#${pr.number}](${pr.url})`).join("\n")
: lookup.branchesChecked > 0
? "No pull request was found for the generated worker branches."
: "Pull request lookup was unavailable because no generated worker branch could be verified; no PR link is included."
await requireCommentWriter(input.gh)(input.owner, input.repo, entry.number,
`HeadlessCode job finished successfully (${summary}).\n\n${logSummary ? `Bounded worker log summary:\n\n\`\`\`text\n${logSummary}\n\`\`\`\n\n` : ""}Pull request lookup:\n${prText}\n\n${commentMarker}`)
} else {
await requireCommentWriter(input.gh)(input.owner, input.repo, entry.number,
`HeadlessCode job failed (${summary}). The watcher does not close failed job issues; review the worker summary before retrying.\n\n${logSummary ? `Bounded worker log summary:\n\n\`\`\`text\n${logSummary}\n\`\`\`\n\n` : ""}${commentMarker}`)
}
}
if (terminal === "done") await requireIssueCloser(input.gh)(input.owner, input.repo, entry.number)
state = markProcessed(state, { ...entry, status: terminal, updatedAt: new Date().toISOString(), ...(terminal === "failed" ? { error: summary } : { error: undefined }) })
} catch (error) {
failures++
input.logger.warn(`watcher: issue #${entry.number} reached ${terminal}, but GitHub lifecycle update did not finish; it will retry on a later poll: ${safeError(error)}`)
}
}
return { state, failures }
}
async function verifyJobClaim(
entry: WatcherIssueEntry,
claims: readonly ClaimSnapshot[],
store: GitHubIssueClaimStore | undefined,
): Promise<boolean> {
if (!entry.claim) return true
if (!store) return false
const snapshot = claims.find(({ claim }) => claim.issue === entry.number &&
claim.runnerId === entry.claim!.runnerId && claim.leaseNonce === entry.claim!.leaseNonce &&
claim.epoch === entry.claim!.epoch && sameStringArray(claim.worktreeNames, entry.claim!.worktreeNames))
if (!snapshot) return false
try {
const current = await store.read(entry.number)
return !!current && current.claim.phase === "active" &&
current.claim.runnerId === snapshot.claim.runnerId && current.claim.leaseNonce === snapshot.claim.leaseNonce &&
current.claim.epoch === snapshot.claim.epoch && sameStringArray(current.claim.worktreeNames, snapshot.claim.worktreeNames)
} catch {
return false
}
}
function sameStringArray(left: readonly string[], right: readonly string[]): boolean {
return left.length === right.length && left.every((value, index) => value === right[index])
}
async function setIssueLifecycle(gh: GhClient, owner: string, repo: string, number: number, lifecycle: JobLifecycle): Promise<void> {
const selected = `headlesscode:${lifecycle}`
if (!gh.removeLabel) throw new Error("GitHub client cannot remove stale job lifecycle labels")
await gh.addLabel(owner, repo, number, selected)
for (const label of JOB_LIFECYCLE_LABELS) if (label !== selected) await gh.removeLabel(owner, repo, number, label)
}
function requireComments(gh: GhClient, owner: string, repo: string, number: number): Promise<string[]> {
if (!gh.listIssueComments) throw new Error("GitHub client cannot check existing job result comments")
return gh.listIssueComments(owner, repo, number)
}
function requireCommentWriter(gh: GhClient): NonNullable<GhClient["createIssueComment"]> {
if (!gh.createIssueComment) throw new Error("GitHub client cannot post job result comments")
return gh.createIssueComment.bind(gh)
}
function requireIssueCloser(gh: GhClient): NonNullable<GhClient["closeIssue"]> {
if (!gh.closeIssue) throw new Error("GitHub client cannot close completed job issues")
return gh.closeIssue.bind(gh)
}
async function reportJobIntakeFailure(gh: GhClient, owner: string, repo: string, number: number, message: string, logger: Logger): Promise<void> {
const marker = jobFailureMarker({ number, error: message })
try {
await setIssueLifecycle(gh, owner, repo, number, "failed")
const comments = await requireComments(gh, owner, repo, number)
if (!comments.some((body) => body.includes(marker))) {
await requireCommentWriter(gh)(owner, repo, number, `HeadlessCode could not dispatch this job: ${safeError(message)}\n\n${marker}`)
}
} catch (error) {
logger.warn(`watcher: issue #${number} intake failure could not be reflected in GitHub: ${safeError(error)}`)
}
}
function jobCommentMarker(entry: WatcherIssueEntry): string {
const key = createHash("sha256").update(`${entry.number}\0${entry.spawnedAt ?? ""}`).digest("hex").slice(0, 24)
return `<!-- headlesscode-job-result:${key} -->`
}
function jobFailureMarker(entry: Pick<WatcherIssueEntry, "number"> & Partial<Pick<WatcherIssueEntry, "spawnedAt" | "error">>): string {
const key = createHash("sha256").update(`${entry.number}\0${entry.spawnedAt ?? ""}\0${entry.error ?? ""}`).digest("hex").slice(0, 24)
return `<!-- headlesscode-job-failure:${key} -->`
}
interface JobCompletion {
terminal: boolean
exitCodes: number[]
logs: string[]
}
function readJobCompletion(repoRoot: string, groups: readonly WorktreeSpec[], attemptId?: string): JobCompletion {
if (!attemptId || !/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(attemptId) || groups.length === 0 || groups.length > 16) return { terminal: false, exitCodes: [], logs: [] }
const exitCodes: number[] = []
const logs: string[] = []
for (const group of groups) {
if (!/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/.test(group.name)) return { terminal: false, exitCodes: [], logs: [] }
const worktree = path.join(repoRoot, ".worktrees", group.name)
try {
const rootStat = fs.lstatSync(path.join(repoRoot, ".worktrees"))
const worktreeStat = fs.lstatSync(worktree)
if (rootStat.isSymbolicLink() || !rootStat.isDirectory() || worktreeStat.isSymbolicLink() || !worktreeStat.isDirectory()) return { terminal: false, exitCodes: [], logs: [] }
} catch {
return { terminal: false, exitCodes: [], logs: [] }
}
// The OpenShell provider leaves this host-side marker in place when
// sandbox deletion cannot be verified. Its presence vetoes completion;
// the worker cannot turn a failed guest teardown into a terminal issue.
try {
fs.lstatSync(path.join(worktree, ".harness.openshell-sandbox"))
return { terminal: false, exitCodes: [], logs: [] }
} catch (error) {
if (!(error && typeof error === "object" && "code" in error && error.code === "ENOENT")) return { terminal: false, exitCodes: [], logs: [] }
}
// Worktree markers are useful diagnostics only. Terminal status requires
// an attempt-bound receipt written outside the worker-controlled tree and