@tekyzinc/gsd-t 3.29.10 → 4.0.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (112) hide show
  1. package/CHANGELOG.md +176 -0
  2. package/bin/gsd-t-parallel.cjs +64 -13
  3. package/bin/gsd-t-test-data-adapters/file-json-array.cjs +27 -3
  4. package/bin/gsd-t-test-data-adapters/localstorage-key-prefix.cjs +6 -1
  5. package/bin/gsd-t-test-data-adapters/sqlite-table-where.cjs +16 -1
  6. package/bin/gsd-t-test-data-ledger.cjs +1 -0
  7. package/bin/gsd-t.js +48 -376
  8. package/bin/journey-coverage.cjs +6 -3
  9. package/bin/parallel-cli.cjs +13 -1
  10. package/commands/gsd-t-debug.md +47 -533
  11. package/commands/gsd-t-design-decompose.md +24 -497
  12. package/commands/gsd-t-doc-ripple.md +23 -139
  13. package/commands/gsd-t-execute.md +41 -958
  14. package/commands/gsd-t-help.md +0 -2
  15. package/commands/gsd-t-impact.md +26 -295
  16. package/commands/gsd-t-integrate.md +44 -369
  17. package/commands/gsd-t-milestone.md +25 -124
  18. package/commands/gsd-t-partition.md +28 -539
  19. package/commands/gsd-t-plan.md +26 -472
  20. package/commands/gsd-t-prd.md +25 -311
  21. package/commands/gsd-t-quick.md +1 -1
  22. package/commands/gsd-t-resume.md +0 -33
  23. package/commands/gsd-t-verify.md +52 -569
  24. package/commands/gsd-t-wave.md +41 -430
  25. package/package.json +1 -1
  26. package/scripts/gsd-t-calibration-hook.js +3 -1
  27. package/scripts/hooks/pre-commit-journey-coverage +0 -2
  28. package/scripts/hooks/pre-commit-playwright-gate +0 -2
  29. package/templates/CLAUDE-global.md +43 -173
  30. package/templates/CLAUDE-project.md +118 -104
  31. package/templates/prompts/design-verify-subagent.md +3 -0
  32. package/templates/prompts/qa-subagent.md +3 -0
  33. package/templates/prompts/red-team-subagent.md +5 -2
  34. package/templates/workflows/_lib.js +176 -0
  35. package/templates/workflows/gsd-t-debug.workflow.js +86 -0
  36. package/templates/workflows/gsd-t-execute.workflow.js +206 -0
  37. package/templates/workflows/gsd-t-integrate.workflow.js +71 -0
  38. package/templates/workflows/gsd-t-phase.workflow.js +94 -0
  39. package/templates/workflows/gsd-t-quick.workflow.js +72 -0
  40. package/templates/workflows/gsd-t-verify.workflow.js +348 -0
  41. package/templates/workflows/gsd-t-wave.workflow.js +43 -0
  42. package/bin/check-headless-sessions.js +0 -140
  43. package/bin/context-budget-audit.cjs +0 -447
  44. package/bin/context-meter-config.cjs +0 -101
  45. package/bin/context-meter-config.test.cjs +0 -101
  46. package/bin/event-stream.cjs +0 -205
  47. package/bin/gsd-t-benchmark-orchestrator.js +0 -437
  48. package/bin/gsd-t-capture-lint.cjs +0 -440
  49. package/bin/gsd-t-economics.cjs +0 -315
  50. package/bin/gsd-t-in-session-usage.cjs +0 -213
  51. package/bin/gsd-t-orchestrator-config.cjs +0 -161
  52. package/bin/gsd-t-orchestrator-queue.cjs +0 -180
  53. package/bin/gsd-t-orchestrator-recover.cjs +0 -231
  54. package/bin/gsd-t-orchestrator-worker.cjs +0 -219
  55. package/bin/gsd-t-orchestrator.js +0 -535
  56. package/bin/gsd-t-parallel-probe.cjs +0 -132
  57. package/bin/gsd-t-ratelimit-probe-worker.cjs +0 -237
  58. package/bin/gsd-t-ratelimit-probe.cjs +0 -648
  59. package/bin/gsd-t-report-tokens.cjs +0 -549
  60. package/bin/gsd-t-stream-feed-client.cjs +0 -151
  61. package/bin/gsd-t-token-backfill.cjs +0 -366
  62. package/bin/gsd-t-token-capture.cjs +0 -321
  63. package/bin/gsd-t-token-dashboard.cjs +0 -353
  64. package/bin/gsd-t-token-regenerate-log.cjs +0 -129
  65. package/bin/gsd-t-tool-attribution.cjs +0 -377
  66. package/bin/gsd-t-tool-cost.cjs +0 -195
  67. package/bin/gsd-t-transcript-tee.cjs +0 -246
  68. package/bin/gsd-t-unattended-heartbeat.cjs +0 -188
  69. package/bin/gsd-t-unattended-platform.cjs +0 -551
  70. package/bin/gsd-t-unattended-platform.js +0 -381
  71. package/bin/gsd-t-unattended-safety.cjs +0 -773
  72. package/bin/gsd-t-unattended-safety.js +0 -788
  73. package/bin/gsd-t-unattended.cjs +0 -2109
  74. package/bin/gsd-t-unattended.js +0 -1367
  75. package/bin/gsd-t-worker-dispatch.cjs +0 -211
  76. package/bin/handoff-lock.cjs +0 -249
  77. package/bin/handoff-lock.js +0 -249
  78. package/bin/headless-auto-spawn.cjs +0 -711
  79. package/bin/headless-auto-spawn.js +0 -373
  80. package/bin/headless-exit-codes.cjs +0 -67
  81. package/bin/live-activity-report.cjs +0 -615
  82. package/bin/log-tail.cjs +0 -81
  83. package/bin/m44-proof-measure.cjs +0 -285
  84. package/bin/m46-iter-proof.cjs +0 -149
  85. package/bin/m46-worker-proof.cjs +0 -201
  86. package/bin/m55-substrate-proof.cjs +0 -134
  87. package/bin/metrics-rollup.js +0 -200
  88. package/bin/model-windows.cjs +0 -99
  89. package/bin/model-windows.test.cjs +0 -75
  90. package/bin/parallelism-report.cjs +0 -535
  91. package/bin/runway-estimator.cjs +0 -242
  92. package/bin/spawn-plan-derive.cjs +0 -163
  93. package/bin/spawn-plan-status-updater.cjs +0 -292
  94. package/bin/spawn-plan-writer.cjs +0 -204
  95. package/bin/supervisor-pid-fingerprint.cjs +0 -126
  96. package/bin/token-budget.cjs +0 -265
  97. package/bin/unattended-watch-format.cjs +0 -178
  98. package/bin/watch-progress.js +0 -155
  99. package/commands/gsd-t-unattended-stop.md +0 -85
  100. package/commands/gsd-t-unattended-watch.md +0 -465
  101. package/commands/gsd-t-unattended.md +0 -476
  102. package/commands/gsd-t-visualize.md +0 -116
  103. package/scripts/gsd-t-context-meter.e2e.test.js +0 -364
  104. package/scripts/gsd-t-context-meter.js +0 -341
  105. package/scripts/gsd-t-context-meter.test.js +0 -471
  106. package/scripts/gsd-t-dashboard-server.js +0 -1203
  107. package/scripts/gsd-t-post-commit-spawn-plan.sh +0 -86
  108. package/scripts/gsd-t-transcript.html +0 -1821
  109. package/scripts/hooks/gsd-t-conversation-capture.js +0 -439
  110. package/scripts/hooks/gsd-t-in-session-usage-hook.js +0 -84
  111. package/scripts/spawn-plan-fmt-tokens.cjs +0 -80
  112. package/templates/hooks/post-commit-spawn-plan.sh +0 -85
@@ -1,773 +0,0 @@
1
- /**
2
- * gsd-t-unattended-safety.js
3
- *
4
- * Pure-function safety rails for the unattended supervisor.
5
- *
6
- * Contract: .gsd-t/contracts/unattended-supervisor-contract.md v1.0.0
7
- * §5 — Exit code table (2 = preflight-failure, 7 = protected-branch-refusal,
8
- * 8 = dirty-tree-refusal)
9
- * §12 — Safety Rails Hook Points
10
- * §13 — Configuration File schema (DEFAULTS authoritative source)
11
- *
12
- * This module exports synchronous, side-effect-light check functions called
13
- * by the supervisor between worker spawns. Each check returns
14
- * { ok: true } on allow
15
- * { ok: false, reason: string, code: number } on refuse
16
- *
17
- * The only permitted side effects are:
18
- * - reading git state via `git branch --show-current` and `git status --porcelain`
19
- * - reading the optional config file at `.gsd-t/.unattended/config.json`
20
- *
21
- * Zero external dependencies — Node built-ins only.
22
- *
23
- * Owner: m36-safety-rails
24
- */
25
-
26
- const fs = require("node:fs");
27
- const path = require("node:path");
28
- const { spawnSync } = require("node:child_process");
29
-
30
- // ── DEFAULTS ────────────────────────────────────────────────────────────────
31
- //
32
- // Source of truth: unattended-supervisor-contract.md §13.
33
- // Any drift here from the contract is a contract violation.
34
-
35
- const DEFAULTS = Object.freeze({
36
- protectedBranches: [
37
- "main",
38
- "master",
39
- "develop",
40
- "trunk",
41
- "release/*",
42
- "hotfix/*",
43
- ],
44
- dirtyTreeWhitelist: [
45
- ".gsd-t/heartbeat-*.jsonl",
46
- ".gsd-t/.context-meter-state.json",
47
- ".gsd-t/events/*.jsonl",
48
- ".gsd-t/token-metrics.jsonl",
49
- ".gsd-t/token-log.md",
50
- ".gsd-t/.unattended/*",
51
- ".gsd-t/.handoff/*",
52
- ".claude/settings.local.json",
53
- ".claude/settings.local.json.bak*",
54
- ],
55
- maxIterations: 200,
56
- hours: 24,
57
- gutterNoProgressIters: 5,
58
- // Absolute backstop — raised from 270_000 to 3_600_000 in contract v1.1.0
59
- // now that the heartbeat watchdog is the primary stuck-worker detector.
60
- workerTimeoutMs: 3600000,
61
- // Heartbeat watchdog threshold — events JSONL mtime must advance within
62
- // this many ms or the worker is SIGTERM'd. Contract v1.1.0 §"Heartbeat
63
- // Watchdog".
64
- staleHeartbeatMs: 300000,
65
- });
66
-
67
- // ── Glob → regex helper ─────────────────────────────────────────────────────
68
- //
69
- // Minimal glob matcher: `*` matches any run of characters except `/`,
70
- // `**` matches across path separators, everything else is a literal.
71
- // No external dependency. Sufficient for the whitelist patterns in §13.
72
-
73
- function globToRegex(glob) {
74
- let re = "^";
75
- for (let i = 0; i < glob.length; i++) {
76
- const c = glob[i];
77
- if (c === "*") {
78
- if (glob[i + 1] === "*") {
79
- re += ".*";
80
- i++;
81
- } else {
82
- re += "[^/]*";
83
- }
84
- } else if (c === "?") {
85
- re += "[^/]";
86
- } else if ("\\^$+.()|{}[]".includes(c)) {
87
- re += "\\" + c;
88
- } else {
89
- re += c;
90
- }
91
- }
92
- re += "$";
93
- return new RegExp(re);
94
- }
95
-
96
- function matchesAnyGlob(value, patterns) {
97
- for (const pattern of patterns) {
98
- if (globToRegex(pattern).test(value)) return true;
99
- }
100
- return false;
101
- }
102
-
103
- // ── loadConfig ──────────────────────────────────────────────────────────────
104
- //
105
- // Reads `.gsd-t/.unattended/config.json` if present, merges field-by-field
106
- // over DEFAULTS, returns a plain object. Missing file → return a deep copy
107
- // of DEFAULTS unchanged. Malformed JSON → throws a clear Error.
108
-
109
- function cloneDefaults() {
110
- // Defensive deep copy so callers can mutate the result without poisoning
111
- // the frozen DEFAULTS singleton.
112
- return {
113
- protectedBranches: DEFAULTS.protectedBranches.slice(),
114
- dirtyTreeWhitelist: DEFAULTS.dirtyTreeWhitelist.slice(),
115
- maxIterations: DEFAULTS.maxIterations,
116
- hours: DEFAULTS.hours,
117
- gutterNoProgressIters: DEFAULTS.gutterNoProgressIters,
118
- workerTimeoutMs: DEFAULTS.workerTimeoutMs,
119
- staleHeartbeatMs: DEFAULTS.staleHeartbeatMs,
120
- };
121
- }
122
-
123
- function loadConfig(projectDir) {
124
- const merged = cloneDefaults();
125
- const configPath = path.join(
126
- projectDir,
127
- ".gsd-t",
128
- ".unattended",
129
- "config.json",
130
- );
131
- if (!fs.existsSync(configPath)) return merged;
132
-
133
- let raw;
134
- try {
135
- raw = fs.readFileSync(configPath, "utf8");
136
- } catch (err) {
137
- throw new Error(
138
- `safety-rails: failed to read config at ${configPath}: ${err.message}`,
139
- );
140
- }
141
-
142
- let parsed;
143
- try {
144
- parsed = JSON.parse(raw);
145
- } catch (err) {
146
- throw new Error(
147
- `safety-rails: malformed JSON in ${configPath}: ${err.message}`,
148
- );
149
- }
150
-
151
- if (parsed && typeof parsed === "object") {
152
- for (const key of Object.keys(merged)) {
153
- if (parsed[key] !== undefined) {
154
- merged[key] = parsed[key];
155
- }
156
- }
157
- }
158
- return merged;
159
- }
160
-
161
- // ── checkGitBranch ──────────────────────────────────────────────────────────
162
- //
163
- // Runs `git branch --show-current` in projectDir. An empty result indicates
164
- // detached HEAD, which is treated as a protected-branch refusal (you cannot
165
- // safely run unattended on a detached HEAD — there's no branch to push to).
166
- // Otherwise, the current branch is matched against the protectedBranches
167
- // list using glob semantics. Match → refuse with code 7.
168
-
169
- function checkGitBranch(projectDir, config) {
170
- const cfg = config || loadConfig(projectDir);
171
- const result = spawnSync("git", ["branch", "--show-current"], {
172
- cwd: projectDir,
173
- encoding: "utf8",
174
- });
175
-
176
- if (result.error) {
177
- return {
178
- ok: false,
179
- reason: `git branch --show-current failed: ${result.error.message}`,
180
- code: 2,
181
- };
182
- }
183
- if (result.status !== 0) {
184
- return {
185
- ok: false,
186
- reason:
187
- `git branch --show-current exited ${result.status}: ` +
188
- (result.stderr || "").trim(),
189
- code: 2,
190
- };
191
- }
192
-
193
- const branch = (result.stdout || "").trim();
194
- if (!branch) {
195
- // Detached HEAD: refuse as protected.
196
- return {
197
- ok: false,
198
- reason: "detached HEAD: refusing to run unattended without a branch",
199
- code: 7,
200
- branch: "",
201
- };
202
- }
203
-
204
- if (matchesAnyGlob(branch, cfg.protectedBranches)) {
205
- return {
206
- ok: false,
207
- reason: `branch '${branch}' is protected (matches one of: ${cfg.protectedBranches.join(", ")})`,
208
- code: 7,
209
- branch,
210
- };
211
- }
212
-
213
- return { ok: true, branch };
214
- }
215
-
216
- // ── checkWorktreeCleanliness ────────────────────────────────────────────────
217
- //
218
- // Runs `git status --porcelain`, parses each line, filters whitelisted files
219
- // per dirtyTreeWhitelist (glob-aware). If any non-whitelisted dirty file
220
- // remains, refuse with code 8 and report the offenders.
221
- //
222
- // Fail-closed: any git failure → code 2 preflight-failure.
223
-
224
- function parsePorcelainLine(line) {
225
- // Porcelain v1 line shape: "XY path" (XY are 2 status chars, then a space).
226
- // Renames look like "R old -> new" — return the destination path.
227
- if (line.length < 4) return null;
228
- let payload = line.slice(3);
229
- const arrow = payload.indexOf(" -> ");
230
- if (arrow !== -1) payload = payload.slice(arrow + 4);
231
- // Strip optional surrounding quotes that git uses for special chars.
232
- if (payload.startsWith('"') && payload.endsWith('"')) {
233
- payload = payload.slice(1, -1);
234
- }
235
- return payload;
236
- }
237
-
238
- function checkWorktreeCleanliness(projectDir, config) {
239
- const cfg = config || loadConfig(projectDir);
240
- // `--untracked-files=all` expands untracked directories to individual file
241
- // paths. Without this, git would summarize new dirs as ".gsd-t/" and we'd
242
- // refuse a tree even when every file inside is whitelisted.
243
- const result = spawnSync(
244
- "git",
245
- ["status", "--porcelain", "--untracked-files=all"],
246
- { cwd: projectDir, encoding: "utf8" },
247
- );
248
-
249
- if (result.error) {
250
- return {
251
- ok: false,
252
- reason: `git status --porcelain failed: ${result.error.message}`,
253
- code: 2,
254
- };
255
- }
256
- if (result.status !== 0) {
257
- return {
258
- ok: false,
259
- reason:
260
- `git status --porcelain exited ${result.status}: ` +
261
- (result.stderr || "").trim(),
262
- code: 2,
263
- };
264
- }
265
-
266
- const stdout = (result.stdout || "").replace(/\r\n/g, "\n");
267
- const lines = stdout.split("\n").filter((l) => l.length > 0);
268
-
269
- const dirtyFiles = [];
270
- for (const line of lines) {
271
- const file = parsePorcelainLine(line);
272
- if (!file) continue;
273
- if (!matchesAnyGlob(file, cfg.dirtyTreeWhitelist)) {
274
- dirtyFiles.push(file);
275
- }
276
- }
277
-
278
- if (dirtyFiles.length > 0) {
279
- return {
280
- ok: false,
281
- reason:
282
- `worktree has ${dirtyFiles.length} non-whitelisted dirty file(s): ` +
283
- dirtyFiles.slice(0, 5).join(", ") +
284
- (dirtyFiles.length > 5 ? ", …" : ""),
285
- code: 8,
286
- dirtyFiles,
287
- };
288
- }
289
-
290
- return { ok: true };
291
- }
292
-
293
- // ── checkIterationCap ───────────────────────────────────────────────────────
294
- //
295
- // Pre-worker hook: refuses to spawn another worker if the iteration count has
296
- // reached the configured cap. Contract §12 lists this under the pre-worker
297
- // hook. The cap is resolved with the precedence:
298
- // 1. config.maxIterations (explicit override)
299
- // 2. DEFAULTS.maxIterations (hardcoded contract default)
300
- // 3. state.maxIterations (fallback — what the supervisor was launched with)
301
- //
302
- // Iteration cap is a soft gutter (not a crash), so it surfaces as code 6
303
- // per contract §5.
304
-
305
- function checkIterationCap(state, config) {
306
- const cap =
307
- (config && typeof config.maxIterations === "number"
308
- ? config.maxIterations
309
- : undefined) ??
310
- DEFAULTS.maxIterations ??
311
- (state && state.maxIterations);
312
-
313
- if (typeof cap !== "number" || !Number.isFinite(cap)) {
314
- return {
315
- ok: false,
316
- reason: "iteration cap is not a finite number",
317
- code: 2,
318
- };
319
- }
320
-
321
- const iter = state && typeof state.iter === "number" ? state.iter : 0;
322
- if (iter < cap) {
323
- return { ok: true };
324
- }
325
- return {
326
- ok: false,
327
- reason: `iteration cap exceeded: iter=${iter} >= maxIterations=${cap}`,
328
- code: 6,
329
- iter,
330
- maxIterations: cap,
331
- };
332
- }
333
-
334
- // ── checkWallClockCap ───────────────────────────────────────────────────────
335
- //
336
- // Pre-worker hook: refuses to spawn another worker if the total elapsed wall
337
- // clock time has reached the configured hours cap. The cap is resolved with
338
- // the precedence:
339
- // 1. config.hours (explicit override)
340
- // 2. DEFAULTS.hours (hardcoded contract default — 24)
341
- //
342
- // wallClockElapsedMs is an integer on state.json (§3). The cap is converted
343
- // to milliseconds for comparison. Wall-clock cap is a soft gutter → code 6.
344
-
345
- function checkWallClockCap(state, config) {
346
- const hours =
347
- config && typeof config.hours === "number"
348
- ? config.hours
349
- : DEFAULTS.hours;
350
-
351
- if (typeof hours !== "number" || !Number.isFinite(hours) || hours <= 0) {
352
- return {
353
- ok: false,
354
- reason: "wall-clock cap (hours) is not a positive finite number",
355
- code: 2,
356
- };
357
- }
358
-
359
- const capMs = hours * 3600 * 1000;
360
- const elapsedMs =
361
- state && typeof state.wallClockElapsedMs === "number"
362
- ? state.wallClockElapsedMs
363
- : 0;
364
-
365
- if (elapsedMs < capMs) {
366
- return { ok: true };
367
- }
368
- return {
369
- ok: false,
370
- reason:
371
- `wall-clock cap exceeded: elapsedMs=${elapsedMs} >= capMs=${capMs} ` +
372
- `(hours=${hours})`,
373
- code: 6,
374
- elapsedMs,
375
- capMs,
376
- };
377
- }
378
-
379
- // ── validateState ───────────────────────────────────────────────────────────
380
- //
381
- // Pure schema validator for state.json. Checks every REQUIRED field from
382
- // contract §3, verifies types, and validates the status enum from §4.
383
- //
384
- // Aggregates errors (does NOT fail-fast) so the caller can surface every
385
- // problem in a single preflight refusal. Returns code 2 (preflight-failure)
386
- // per contract §5 on any failure.
387
-
388
- const STATUS_ENUM = Object.freeze([
389
- "initializing",
390
- "running",
391
- "done",
392
- "failed",
393
- "stopped",
394
- "crashed",
395
- ]);
396
-
397
- const PLATFORM_ENUM = Object.freeze(["darwin", "linux", "win32"]);
398
-
399
- // Required fields per contract §3, with an expected-type tag. We check the
400
- // supervisor-critical fields listed in the Task 2 acceptance criteria.
401
- const REQUIRED_STATE_FIELDS = Object.freeze([
402
- { name: "version", type: "string" },
403
- { name: "sessionId", type: "string" },
404
- { name: "projectDir", type: "string" },
405
- { name: "status", type: "string" }, // enum-validated below
406
- { name: "milestone", type: "string" },
407
- { name: "iter", type: "integer" },
408
- { name: "maxIterations", type: "integer" },
409
- { name: "startedAt", type: "string" },
410
- { name: "lastTick", type: "string" },
411
- { name: "hours", type: "number" },
412
- { name: "wallClockElapsedMs", type: "integer" },
413
- { name: "supervisorPid", type: "integer" },
414
- { name: "logPath", type: "string" },
415
- { name: "platform", type: "string" }, // enum-validated below
416
- { name: "claudeBin", type: "string" },
417
- ]);
418
-
419
- function typeMatches(value, expected) {
420
- if (value === undefined || value === null) return false;
421
- switch (expected) {
422
- case "string":
423
- return typeof value === "string";
424
- case "number":
425
- return typeof value === "number" && Number.isFinite(value);
426
- case "integer":
427
- return (
428
- typeof value === "number" &&
429
- Number.isFinite(value) &&
430
- Number.isInteger(value)
431
- );
432
- default:
433
- return false;
434
- }
435
- }
436
-
437
- function validateState(state) {
438
- const errors = [];
439
-
440
- if (!state || typeof state !== "object" || Array.isArray(state)) {
441
- return {
442
- ok: false,
443
- code: 2,
444
- reason: "state-validation-failed",
445
- errors: ["state must be a non-null object"],
446
- };
447
- }
448
-
449
- for (const field of REQUIRED_STATE_FIELDS) {
450
- if (!(field.name in state)) {
451
- errors.push(`${field.name}: missing required field`);
452
- continue;
453
- }
454
- const value = state[field.name];
455
- if (!typeMatches(value, field.type)) {
456
- errors.push(
457
- `${field.name}: expected ${field.type}, got ${
458
- value === null ? "null" : typeof value
459
- }`,
460
- );
461
- }
462
- }
463
-
464
- // Status enum check — only if the field was present and a string. Skip if
465
- // we already flagged it as a type error to avoid double reporting.
466
- if (typeof state.status === "string" && !STATUS_ENUM.includes(state.status)) {
467
- errors.push(
468
- `status: invalid enum value '${state.status}' (expected one of: ${STATUS_ENUM.join(", ")})`,
469
- );
470
- }
471
-
472
- // Platform enum check.
473
- if (
474
- typeof state.platform === "string" &&
475
- !PLATFORM_ENUM.includes(state.platform)
476
- ) {
477
- errors.push(
478
- `platform: invalid enum value '${state.platform}' (expected one of: ${PLATFORM_ENUM.join(", ")})`,
479
- );
480
- }
481
-
482
- // Value sanity — only if the field was present and numeric.
483
- if (typeof state.iter === "number" && Number.isInteger(state.iter) && state.iter < 0) {
484
- errors.push(`iter: must be >= 0, got ${state.iter}`);
485
- }
486
- if (
487
- typeof state.maxIterations === "number" &&
488
- Number.isInteger(state.maxIterations) &&
489
- state.maxIterations <= 0
490
- ) {
491
- errors.push(
492
- `maxIterations: must be > 0, got ${state.maxIterations}`,
493
- );
494
- }
495
- if (
496
- typeof state.wallClockElapsedMs === "number" &&
497
- Number.isInteger(state.wallClockElapsedMs) &&
498
- state.wallClockElapsedMs < 0
499
- ) {
500
- errors.push(
501
- `wallClockElapsedMs: must be >= 0, got ${state.wallClockElapsedMs}`,
502
- );
503
- }
504
-
505
- if (errors.length > 0) {
506
- return {
507
- ok: false,
508
- code: 2,
509
- reason: "state-validation-failed",
510
- errors,
511
- };
512
- }
513
-
514
- return { ok: true };
515
- }
516
-
517
- // ── detectGutter ────────────────────────────────────────────────────────────
518
- //
519
- // Post-worker hook: scans the tail of run.log plus the supervisor state for
520
- // three stall patterns. A positive detection returns code 6 (gutter-detected)
521
- // per contract §5. Pure function — NO filesystem reads. The caller is
522
- // responsible for passing the run-log tail as a string (typically last ~200
523
- // lines) and the current state object.
524
- //
525
- // The three patterns:
526
- //
527
- // 1. repeated-error
528
- // Extract error lines (regex /error[:\s].*$/im) grouped by iteration
529
- // block (headers of the form "--- ITER N ---"). If the same error
530
- // signature appears in the last `gutterThreshold` (default 3) consecutive
531
- // iteration blocks, flag it.
532
- //
533
- // 2. file-thrash
534
- // Count `Edit(`/`Write(` tool operations per file across iteration
535
- // blocks. Heuristic: if the top file appears in >= `gutterThreshold`
536
- // iterations AND accounts for a dominant share of edits, flag it. This
537
- // is intentionally a cheap approximation — see §12 of the contract which
538
- // lists gutter detection as implementation-owned.
539
- //
540
- // 3. no-progress
541
- // If the caller passes `state.progressHash` and `state.progressHashHistory`
542
- // (an array of the last N hashes, one per iter), and the last
543
- // `gutterWindow` (default 5) hashes are all identical AND state.iter has
544
- // advanced by at least `gutterWindow`, flag it. Callers without history
545
- // can omit this signal and the function will skip the no-progress check
546
- // (low false-positive design).
547
- //
548
- // Config fields consumed (all optional):
549
- // - gutterThreshold (default 3) — min consecutive iters for pattern
550
- // - gutterWindow (default 5) — lookback window for no-progress
551
- // - gutterNoProgressIters (default 5) — alias for gutterWindow from §13
552
-
553
- const ITER_HEADER_RE = /^---\s*ITER\s+(\d+)\s*---/im;
554
-
555
- function splitIterBlocks(runLogTail) {
556
- // Split the tail into blocks keyed by the "--- ITER N ---" header. Content
557
- // before the first header is discarded (it belongs to an iteration we don't
558
- // have full visibility into).
559
- if (typeof runLogTail !== "string" || runLogTail.length === 0) return [];
560
- const lines = runLogTail.split(/\r?\n/);
561
- const blocks = [];
562
- let current = null;
563
- for (const line of lines) {
564
- const m = line.match(ITER_HEADER_RE);
565
- if (m) {
566
- if (current) blocks.push(current);
567
- current = { iter: Number(m[1]), lines: [] };
568
- } else if (current) {
569
- current.lines.push(line);
570
- }
571
- }
572
- if (current) blocks.push(current);
573
- return blocks;
574
- }
575
-
576
- // Extract the first error-looking line from a block and normalize it into a
577
- // signature for equality comparison. Returns null if no error line found.
578
- function extractErrorSignature(block) {
579
- for (const line of block.lines) {
580
- const m = line.match(/error[:\s]+(.+)$/i);
581
- if (m) {
582
- // Normalize whitespace and strip volatile numeric/path suffixes so that
583
- // two errors that differ only by line number still match.
584
- return m[1]
585
- .replace(/\s+/g, " ")
586
- .replace(/\b\d+\b/g, "N")
587
- .replace(/[/\\][\w./\\-]+/g, "PATH")
588
- .trim()
589
- .slice(0, 200);
590
- }
591
- }
592
- return null;
593
- }
594
-
595
- // Count `Edit(path=...)` / `Write(file_path=...)` mentions per file in a
596
- // block. The exact tool-call serialization isn't standardized, so we fall back
597
- // to a loose match: `(Edit|Write)\s*\(\s*(?:file_path|path)?\s*=?\s*['"]([^'"]+)['"]`
598
- const TOOL_CALL_RE =
599
- /(?:Edit|Write)\s*\(\s*(?:file_path|path)?\s*=?\s*['"]([^'"]+)['"]/gi;
600
-
601
- function extractEditedFiles(block) {
602
- const files = new Set();
603
- const text = block.lines.join("\n");
604
- let m;
605
- while ((m = TOOL_CALL_RE.exec(text)) !== null) {
606
- files.add(m[1]);
607
- }
608
- return files;
609
- }
610
-
611
- function detectGutter(state, runLogTail, config) {
612
- const cfg = config || {};
613
- const threshold =
614
- typeof cfg.gutterThreshold === "number" && cfg.gutterThreshold > 0
615
- ? cfg.gutterThreshold
616
- : 3;
617
- const window =
618
- typeof cfg.gutterWindow === "number" && cfg.gutterWindow > 0
619
- ? cfg.gutterWindow
620
- : typeof cfg.gutterNoProgressIters === "number" &&
621
- cfg.gutterNoProgressIters > 0
622
- ? cfg.gutterNoProgressIters
623
- : DEFAULTS.gutterNoProgressIters;
624
-
625
- const blocks = splitIterBlocks(runLogTail || "");
626
-
627
- // ── Pattern 1: repeated-error ─────────────────────────────────────────────
628
- if (blocks.length >= threshold) {
629
- const recent = blocks.slice(-threshold);
630
- const sigs = recent.map(extractErrorSignature);
631
- if (sigs.every((s) => s !== null) && sigs.every((s) => s === sigs[0])) {
632
- return {
633
- ok: false,
634
- code: 6,
635
- reason: "gutter-detected",
636
- pattern: "repeated-error",
637
- details: {
638
- signature: sigs[0],
639
- consecutiveIters: threshold,
640
- iters: recent.map((b) => b.iter),
641
- },
642
- };
643
- }
644
- }
645
-
646
- // ── Pattern 2: file-thrash ────────────────────────────────────────────────
647
- // Heuristic: for each file, count how many of the last `threshold` blocks
648
- // it was edited in. If any file appears in ALL `threshold` recent blocks AND
649
- // the top file accounts for a dominant share of edits (>= 50% of total
650
- // file-block pairs), flag it. This catches "keeps editing the same 2-3
651
- // files over and over" stalls without firing on normal healthy multi-file
652
- // churn.
653
- if (blocks.length >= threshold) {
654
- const recent = blocks.slice(-threshold);
655
- const fileCounts = new Map(); // file -> number of blocks it appears in
656
- let totalPairs = 0;
657
- for (const block of recent) {
658
- const files = extractEditedFiles(block);
659
- for (const f of files) {
660
- fileCounts.set(f, (fileCounts.get(f) || 0) + 1);
661
- totalPairs += 1;
662
- }
663
- }
664
- // Find files that appear in every block.
665
- const persistent = Array.from(fileCounts.entries())
666
- .filter(([, count]) => count >= threshold)
667
- .sort((a, b) => b[1] - a[1]);
668
- if (persistent.length > 0 && totalPairs > 0) {
669
- const topShare =
670
- persistent.reduce((sum, [, c]) => sum + c, 0) / totalPairs;
671
- // Dominant = the persistent files account for >= 50% of all edit
672
- // activity in the window. Tuned for low false-positive rate.
673
- if (topShare >= 0.5) {
674
- return {
675
- ok: false,
676
- code: 6,
677
- reason: "gutter-detected",
678
- pattern: "file-thrash",
679
- details: {
680
- files: persistent.map(([f]) => f),
681
- window: threshold,
682
- dominantShare: Number(topShare.toFixed(2)),
683
- },
684
- };
685
- }
686
- }
687
- }
688
-
689
- // ── Pattern 3: no-progress ────────────────────────────────────────────────
690
- // Only runs when caller supplies progressHashHistory. Absence = skip
691
- // (low-false-positive design — we'd rather miss a stall than flag a
692
- // healthy run as stalled).
693
- if (
694
- state &&
695
- Array.isArray(state.progressHashHistory) &&
696
- state.progressHashHistory.length >= window &&
697
- typeof state.iter === "number"
698
- ) {
699
- const history = state.progressHashHistory.slice(-window);
700
- const first = history[0];
701
- if (first && history.every((h) => h === first)) {
702
- return {
703
- ok: false,
704
- code: 6,
705
- reason: "gutter-detected",
706
- pattern: "no-progress",
707
- details: {
708
- unchangedHash: first,
709
- window,
710
- iter: state.iter,
711
- },
712
- };
713
- }
714
- }
715
-
716
- return { ok: true };
717
- }
718
-
719
- // ── detectBlockerSentinel ───────────────────────────────────────────────────
720
- //
721
- // Post-worker hook: scans the run.log tail for sentinel strings the worker
722
- // emits when it hits a human-gated blocker (destructive action guard, waiting
723
- // for user input, etc.). A match halts the supervisor with code 6 and the
724
- // matched pattern string so the watch loop can surface it to the user.
725
-
726
- const BLOCKER_SENTINEL_PATTERNS = Object.freeze([
727
- /\bblocked\s+needs\s+human\b/i,
728
- /\bblocker:\s+.+$/im,
729
- /\bdestructive\s+action\s+guard\b/i,
730
- /\bwaiting\s+for\s+user\b/i,
731
- ]);
732
-
733
- function detectBlockerSentinel(runLogTail) {
734
- if (typeof runLogTail !== "string" || runLogTail.length === 0) {
735
- return { ok: true };
736
- }
737
- for (const re of BLOCKER_SENTINEL_PATTERNS) {
738
- const m = runLogTail.match(re);
739
- if (m) {
740
- return {
741
- ok: false,
742
- code: 6,
743
- reason: "blocker-sentinel-detected",
744
- pattern: re.source,
745
- matchedText: m[0].slice(0, 200),
746
- };
747
- }
748
- }
749
- return { ok: true };
750
- }
751
-
752
- module.exports = {
753
- DEFAULTS,
754
- loadConfig,
755
- checkGitBranch,
756
- checkWorktreeCleanliness,
757
- checkIterationCap,
758
- checkWallClockCap,
759
- validateState,
760
- detectGutter,
761
- detectBlockerSentinel,
762
- // Internal helpers exported for unit tests.
763
- _globToRegex: globToRegex,
764
- _matchesAnyGlob: matchesAnyGlob,
765
- _parsePorcelainLine: parsePorcelainLine,
766
- _splitIterBlocks: splitIterBlocks,
767
- _extractErrorSignature: extractErrorSignature,
768
- _extractEditedFiles: extractEditedFiles,
769
- _BLOCKER_SENTINEL_PATTERNS: BLOCKER_SENTINEL_PATTERNS,
770
- _STATUS_ENUM: STATUS_ENUM,
771
- _PLATFORM_ENUM: PLATFORM_ENUM,
772
- _REQUIRED_STATE_FIELDS: REQUIRED_STATE_FIELDS,
773
- };