pi-spine 1.10.0 → 2.0.0
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.
- package/bin/spine-batch.mjs +23 -0
- package/package.json +1 -1
- package/skills/create-spine-tasks/SKILL.md +1 -0
- package/skills/create-spine-tasks/references/prompt-template.md +9 -20
- package/src/batch/attached-runner.mjs +12 -0
- package/src/batch/contract-verify.mjs +37 -0
- package/src/batch/detached-spawn.mjs +5 -1
- package/src/batch/engine-lanes/watch.mjs +4 -2
- package/src/batch/heartbeat-subprocess.mjs +214 -0
- package/src/batch/heartbeat.mjs +38 -63
- package/src/batch/parent-session-monitor.mjs +201 -0
- package/src/config/spine-preflight-lib.mjs +12 -1
- package/src/dashboard/public/dashboard.js +6 -2
- package/src/dashboard/snapshot.mjs +85 -11
- package/src/doctor/attached-orphan-risk.mjs +35 -1
- package/src/tasks/packet/validate-contract.mjs +13 -1
- package/src/tasks/validate-contract-warn.mjs +76 -23
package/bin/spine-batch.mjs
CHANGED
|
@@ -20,6 +20,7 @@ import {
|
|
|
20
20
|
formatAttachedBatchCliResult,
|
|
21
21
|
runAttachedBatchEngine,
|
|
22
22
|
} from "../src/batch/attached-runner.mjs";
|
|
23
|
+
import { enforceAttachedOrphanRiskGuard } from "../src/doctor/attached-orphan-risk.mjs";
|
|
23
24
|
|
|
24
25
|
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
|
25
26
|
|
|
@@ -355,6 +356,17 @@ export async function runSpineBatch(options) {
|
|
|
355
356
|
}
|
|
356
357
|
|
|
357
358
|
if (parsed.subcommand === "resume") {
|
|
359
|
+
if (parsed.attached) {
|
|
360
|
+
const orphanGuard = enforceAttachedOrphanRiskGuard();
|
|
361
|
+
if (!orphanGuard.ok) {
|
|
362
|
+
return {
|
|
363
|
+
exitCode: orphanGuard.exitCode ?? 1,
|
|
364
|
+
output: orphanGuard.output ?? "",
|
|
365
|
+
result: orphanGuard,
|
|
366
|
+
};
|
|
367
|
+
}
|
|
368
|
+
}
|
|
369
|
+
|
|
358
370
|
if (!parsed.attached) {
|
|
359
371
|
const waitTerminal = resolveDefaultResumeWaitTerminal(
|
|
360
372
|
projectRoot,
|
|
@@ -398,6 +410,17 @@ export async function runSpineBatch(options) {
|
|
|
398
410
|
}
|
|
399
411
|
|
|
400
412
|
const useAttached = parsed.attached || parsed.dryRun;
|
|
413
|
+
if (parsed.attached && !parsed.dryRun) {
|
|
414
|
+
const orphanGuard = enforceAttachedOrphanRiskGuard();
|
|
415
|
+
if (!orphanGuard.ok) {
|
|
416
|
+
return {
|
|
417
|
+
exitCode: orphanGuard.exitCode ?? 1,
|
|
418
|
+
output: orphanGuard.output ?? "",
|
|
419
|
+
result: orphanGuard,
|
|
420
|
+
};
|
|
421
|
+
}
|
|
422
|
+
}
|
|
423
|
+
|
|
401
424
|
if (!useAttached) {
|
|
402
425
|
const detached = await startBatchDetached({
|
|
403
426
|
projectRoot,
|
package/package.json
CHANGED
|
@@ -298,6 +298,7 @@ Use [references/prompt-template.md](references/prompt-template.md). Spine-specif
|
|
|
298
298
|
- **Coverage gate** — when the task changes application code, add a coverage verification checkbox in the Testing step using `testing.testWithCoverage` (≥77% line coverage policy)
|
|
299
299
|
- **Contract (required for new SP-\* tasks)** — add `## Contract` after `## File Scope` using [references/contract-template.md](references/contract-template.md). Include `testCommand` for code tasks; use `` `true` `` for docs-only S tasks. When `testCommand` is `` `true` `` (docs-only), **always** include `fileScopeMustChange` listing at least one documentation deliverable path — without it, workers can pass contract by creating only `.DONE` (SP-214 batch `20260612T204048`, SP-457 batch `20260703T022335`). When using `fileScopeMustNotChange`, follow parallel-only semantics and never ban `spine-tasks/**` (see contract template and [File Scope and parallel batches](#file-scope-and-parallel-batches)). Legacy `TP-*` packets may omit Contract when `contract.legacyTaskIdPrefixes` includes `TP-`.
|
|
300
300
|
- **Completion** — worker creates `{task-folder}/.DONE`; batch engine may auto-commit remaining work
|
|
301
|
+
- **Documentation Requirements ↔ File Scope ([#144](https://github.com/beettlle/pi-spine/issues/144))** — every path under **Must Update** in `## Documentation Requirements` **must** also appear in `## File Scope`. Advisory docs belong in **Check If Affected**, not Must Update. Example: if Must Update lists `docs/adoption/operator-runbook.md`, add that path to File Scope alongside code paths — otherwise workers must choose between scope and documentation obligations (SP-435, SP-451).
|
|
301
302
|
|
|
302
303
|
### Step 5: Create STATUS.md
|
|
303
304
|
|
|
@@ -20,16 +20,6 @@ Review Level 0 is ONLY for trivial changes. Most M+ tasks need Level ≥1.
|
|
|
20
20
|
|
|
21
21
|
> **Real-pi batches (SP-195/SP-278):** Do **not** add per-step "Call `spine_review_step`" checkboxes for Review Level ≥ 1. The batch engine runs plan, code, and final reviews after worker `.DONE`. Stub batches (`SPINE_WORKER_STUB=1`) may still use in-worker stub plan review via the tool when a checkpoint marker requires it.
|
|
22
22
|
|
|
23
|
-
## Canonical Task Folder
|
|
24
|
-
|
|
25
|
-
```
|
|
26
|
-
[FULL_PATH_TO_TASK_FOLDER]/
|
|
27
|
-
├── PROMPT.md ← This file (immutable above --- divider)
|
|
28
|
-
├── STATUS.md ← Execution state (worker updates this)
|
|
29
|
-
├── .reviews/ ← Reviewer output (created by the orchestrator runtime)
|
|
30
|
-
└── .DONE ← Created when complete
|
|
31
|
-
```
|
|
32
|
-
|
|
33
23
|
## Mission
|
|
34
24
|
|
|
35
25
|
[One paragraph: what you're building and why it matters]
|
|
@@ -50,10 +40,7 @@ Review Level 0 is ONLY for trivial changes. Most M+ tasks need Level ≥1.
|
|
|
50
40
|
|
|
51
41
|
> Only list docs the worker actually needs. Less is better.
|
|
52
42
|
|
|
53
|
-
**Tier 2 (area context):**
|
|
54
43
|
- `[path/to/CONTEXT.md]`
|
|
55
|
-
|
|
56
|
-
**Tier 3 (load only if needed):**
|
|
57
44
|
- `[path/to/specific-doc.md]` — [why needed]
|
|
58
45
|
|
|
59
46
|
## Environment
|
|
@@ -69,6 +56,7 @@ Review Level 0 is ONLY for trivial changes. Most M+ tasks need Level ≥1.
|
|
|
69
56
|
|
|
70
57
|
- `[path/to/file.ext]`
|
|
71
58
|
- `[path/to/directory/*]`
|
|
59
|
+
- `[docs/adoption/operator-runbook.md]` — include when listed under Documentation Requirements **Must Update**
|
|
72
60
|
|
|
73
61
|
## Contract
|
|
74
62
|
|
|
@@ -109,7 +97,6 @@ Review Level 0 is ONLY for trivial changes. Most M+ tasks need Level ≥1.
|
|
|
109
97
|
- [ ] [Specific, verifiable task]
|
|
110
98
|
- [ ] [Specific, verifiable task]
|
|
111
99
|
- [ ] [Specific, verifiable task]
|
|
112
|
-
- [ ] Run targeted tests: `[test command] --changed` or specific test files
|
|
113
100
|
|
|
114
101
|
**Artifacts:**
|
|
115
102
|
- `path/to/file` (new | modified)
|
|
@@ -118,9 +105,7 @@ Review Level 0 is ONLY for trivial changes. Most M+ tasks need Level ≥1.
|
|
|
118
105
|
|
|
119
106
|
> **Required for every task** — including docs-only and Review Level 0 packets.
|
|
120
107
|
> ZERO test failures allowed. This step runs the FULL test suite as a quality gate.
|
|
121
|
-
>
|
|
122
|
-
> `node --experimental-strip-types --test tests/feature.test.mjs` (not `npm test -- path`,
|
|
123
|
-
> which runs the full suite in lane worktrees; see SP-522).
|
|
108
|
+
> Use `testCommand` from `## Contract` (often chains `npm run typecheck` with tests).
|
|
124
109
|
>
|
|
125
110
|
> **Docs-only tasks:** keep this step; run the full test suite. Omit the coverage-gate
|
|
126
111
|
> checkbox below when the task does not change application code.
|
|
@@ -129,7 +114,6 @@ Review Level 0 is ONLY for trivial changes. Most M+ tasks need Level ≥1.
|
|
|
129
114
|
- [ ] Run coverage gate: `[testWithCoverage command, e.g. npm run coverage:check]` — **≥77% line coverage** on in-scope changed code (code-related tasks only; omit for docs-only)
|
|
130
115
|
- [ ] Run integration tests (if applicable)
|
|
131
116
|
- [ ] Fix all failures
|
|
132
|
-
- [ ] Build passes: `[build command]`
|
|
133
117
|
|
|
134
118
|
### Step [N]: Documentation & Delivery
|
|
135
119
|
|
|
@@ -139,8 +123,12 @@ Review Level 0 is ONLY for trivial changes. Most M+ tasks need Level ≥1.
|
|
|
139
123
|
|
|
140
124
|
## Documentation Requirements
|
|
141
125
|
|
|
126
|
+
> **File Scope rule ([#144](https://github.com/beettlle/pi-spine/issues/144)):** Every path under **Must Update**
|
|
127
|
+
> **must** also appear in `## File Scope`. If a doc is advisory only, list it under **Check If Affected**
|
|
128
|
+
> instead — do not require workers to edit paths outside File Scope.
|
|
129
|
+
|
|
142
130
|
**Must Update:**
|
|
143
|
-
- `[path/to/doc.md]` — [what to add/change]
|
|
131
|
+
- `[path/to/doc.md]` — [what to add/change] *(also list this path in `## File Scope`)*
|
|
144
132
|
|
|
145
133
|
**Check If Affected:**
|
|
146
134
|
- `[path/to/doc.md]` — [update if relevant]
|
|
@@ -173,6 +161,8 @@ for this task MUST include the task ID for traceability:
|
|
|
173
161
|
|
|
174
162
|
## Amendments (Added During Execution)
|
|
175
163
|
|
|
164
|
+
> Rarely used — workers normally log discoveries in STATUS.md Notes instead.
|
|
165
|
+
|
|
176
166
|
<!-- Workers add amendments here if issues discovered during execution.
|
|
177
167
|
Format:
|
|
178
168
|
### Amendment N — YYYY-MM-DD HH:MM
|
|
@@ -233,7 +223,6 @@ this from PROMPT.md.
|
|
|
233
223
|
- [ ] Coverage gate passes (≥77% line coverage on in-scope code, when applicable)
|
|
234
224
|
- [ ] Integration tests (if applicable)
|
|
235
225
|
- [ ] All failures fixed
|
|
236
|
-
- [ ] Build passes
|
|
237
226
|
|
|
238
227
|
---
|
|
239
228
|
|
|
@@ -34,6 +34,7 @@ import {
|
|
|
34
34
|
import { classifyTaskDoneSemantics } from "./diagnosis-task-done.mjs";
|
|
35
35
|
import { resolveTasksRoot } from "../config/spine-preflight-lib.mjs";
|
|
36
36
|
import { journalHasTaskCompleted } from "./resume-common.mjs";
|
|
37
|
+
import { startParentSessionMonitor } from "./parent-session-monitor.mjs";
|
|
37
38
|
|
|
38
39
|
export { DEFAULT_ATTACHED_MILESTONE_POLL_MS } from "../config/spine-config-schema.mjs";
|
|
39
40
|
|
|
@@ -464,6 +465,16 @@ export async function runAttachedBatchEngine({
|
|
|
464
465
|
|
|
465
466
|
installAttachedExitFinalizeHandlers({ projectRoot, spineBin });
|
|
466
467
|
const reporter = await startAttachedMilestoneReporter({ projectRoot, write });
|
|
468
|
+
/** @type {{ stop: () => Promise<void> }} */
|
|
469
|
+
let parentMonitor = { stop: async () => {} };
|
|
470
|
+
if (process.env.SPINE_ALLOW_ATTACHED_HARNESS !== "1") {
|
|
471
|
+
parentMonitor = await startParentSessionMonitor({
|
|
472
|
+
projectRoot,
|
|
473
|
+
onParentDied: () => {
|
|
474
|
+
process.exit(1);
|
|
475
|
+
},
|
|
476
|
+
});
|
|
477
|
+
}
|
|
467
478
|
try {
|
|
468
479
|
const result = await runEngine();
|
|
469
480
|
const handoff = finalizeAttachedLandLoopBeforeExit({ projectRoot, spineBin, signal: "exit" });
|
|
@@ -472,6 +483,7 @@ export async function runAttachedBatchEngine({
|
|
|
472
483
|
}
|
|
473
484
|
return result;
|
|
474
485
|
} finally {
|
|
486
|
+
await parentMonitor.stop();
|
|
475
487
|
await reporter.stop();
|
|
476
488
|
}
|
|
477
489
|
}
|
|
@@ -21,6 +21,10 @@ import {
|
|
|
21
21
|
sanitizeFlutterBuildBeforeAnalyze,
|
|
22
22
|
shouldCleanFlutterBuildBeforeAnalyze,
|
|
23
23
|
} from "./lane-dirty-check.mjs";
|
|
24
|
+
import {
|
|
25
|
+
NPM_TEST_DASH_DASH_RE,
|
|
26
|
+
TEST_COMMAND_NPM_TEST_DASH_DASH_FIX_HINT,
|
|
27
|
+
} from "../tasks/validate-contract-warn.mjs";
|
|
24
28
|
|
|
25
29
|
export { resolvePromptRelPath, isFileScopePatternPrelanded, hasSpineTaskDeliveryChanges } from "./contract-prelanded.mjs";
|
|
26
30
|
|
|
@@ -346,6 +350,28 @@ export function writeContractFailureLog(taskFolder, command, result, attempt, to
|
|
|
346
350
|
return logPath;
|
|
347
351
|
}
|
|
348
352
|
|
|
353
|
+
/**
|
|
354
|
+
* Defense in depth: block `npm test -- <path>` before subprocess spawn (issue #187, SP-541).
|
|
355
|
+
*
|
|
356
|
+
* @param {string} command
|
|
357
|
+
* @returns {boolean}
|
|
358
|
+
*/
|
|
359
|
+
export function isRefusedNpmTestDashDashCommand(command) {
|
|
360
|
+
const trimmed = String(command ?? "").trim();
|
|
361
|
+
if (!trimmed || trimmed === "true") {
|
|
362
|
+
return false;
|
|
363
|
+
}
|
|
364
|
+
return NPM_TEST_DASH_DASH_RE.test(trimmed);
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
/**
|
|
368
|
+
* @param {string} command
|
|
369
|
+
* @returns {string}
|
|
370
|
+
*/
|
|
371
|
+
function formatRefusedNpmTestDashDashMessage(command) {
|
|
372
|
+
return `Contract testCommand refused before spawn: npm test -- <path> is blocked at runtime (command: ${command}). ${TEST_COMMAND_NPM_TEST_DASH_DASH_FIX_HINT}`;
|
|
373
|
+
}
|
|
374
|
+
|
|
349
375
|
/**
|
|
350
376
|
* @param {string} worktreePath
|
|
351
377
|
* @param {string} command
|
|
@@ -357,6 +383,17 @@ export function runContractTestCommand(worktreePath, command, options = {}) {
|
|
|
357
383
|
return { ok: true, exitCode: 0, output: "" };
|
|
358
384
|
}
|
|
359
385
|
|
|
386
|
+
if (isRefusedNpmTestDashDashCommand(trimmed)) {
|
|
387
|
+
const summary = formatRefusedNpmTestDashDashMessage(trimmed);
|
|
388
|
+
return {
|
|
389
|
+
ok: false,
|
|
390
|
+
exitCode: 1,
|
|
391
|
+
output: summary,
|
|
392
|
+
summary,
|
|
393
|
+
refusedBeforeSpawn: true,
|
|
394
|
+
};
|
|
395
|
+
}
|
|
396
|
+
|
|
360
397
|
const maxBuffer = options.maxBuffer ?? CONTRACT_TEST_COMMAND_MAX_BUFFER;
|
|
361
398
|
const shell = process.env.SHELL || (process.platform === "win32" ? "cmd.exe" : "/bin/sh");
|
|
362
399
|
const shellFlag = process.platform === "win32" ? "/c" : "-c";
|
|
@@ -69,7 +69,11 @@ export function spawnDetachedBatchEngine({ projectRoot, spineBin, argv }) {
|
|
|
69
69
|
cwd: projectRoot,
|
|
70
70
|
detached: true,
|
|
71
71
|
stdio: ["ignore", logFd, logFd],
|
|
72
|
-
env:
|
|
72
|
+
env: {
|
|
73
|
+
...process.env,
|
|
74
|
+
// Detached parent intentionally spawns an attached engine subprocess (#163 / SP-539).
|
|
75
|
+
SPINE_ALLOW_ATTACHED_HARNESS: "1",
|
|
76
|
+
},
|
|
73
77
|
});
|
|
74
78
|
child.unref();
|
|
75
79
|
fs.closeSync(logFd);
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
* Lane worker watch helpers — stall anchor slides on worker_alive while running (SP-341 / #32).
|
|
3
3
|
*/
|
|
4
4
|
|
|
5
|
-
/** @typedef {"launching" | "pi" | "verify" | "unknown"} WorkerPhase */
|
|
5
|
+
/** @typedef {"launching" | "pi" | "verify" | "subprocess" | "unknown"} WorkerPhase */
|
|
6
6
|
/** @typedef {"worker_alive" | "checkpoint" | "file_scope_activity"} HeartbeatKind */
|
|
7
7
|
|
|
8
8
|
/**
|
|
@@ -11,7 +11,9 @@
|
|
|
11
11
|
* @param {HeartbeatKind} params.heartbeatKind
|
|
12
12
|
*/
|
|
13
13
|
export function shouldSlideStallAnchorOnHeartbeat({ workerPhase, heartbeatKind }) {
|
|
14
|
-
return
|
|
14
|
+
return (
|
|
15
|
+
(workerPhase === "pi" || workerPhase === "subprocess") && heartbeatKind === "worker_alive"
|
|
16
|
+
);
|
|
15
17
|
}
|
|
16
18
|
|
|
17
19
|
/**
|
|
@@ -0,0 +1,214 @@
|
|
|
1
|
+
// @ts-nocheck
|
|
2
|
+
/**
|
|
3
|
+
* Subprocess heartbeat signals for long-running worker steps (issue #134 / SP-548).
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
/** @typedef {"launching" | "pi" | "verify" | "subprocess" | "unknown"} WorkerPhase */
|
|
7
|
+
|
|
8
|
+
const SUBPROCESS_COMMAND_MAX_LEN = 120;
|
|
9
|
+
|
|
10
|
+
const SUBPROCESS_FRIENDLY_LABELS = Object.freeze([
|
|
11
|
+
[/^npm\s+run\s+coverage(?::\w+)?/i, "coverage"],
|
|
12
|
+
[/^npm\s+run\s+typecheck/i, "typecheck"],
|
|
13
|
+
[/^npm\s+test\b/i, "tests"],
|
|
14
|
+
[/^node\s+--test\b/i, "tests"],
|
|
15
|
+
]);
|
|
16
|
+
|
|
17
|
+
const SUBPROCESS_STRING_REDACT_PATTERNS = [
|
|
18
|
+
/(?:bearer|token|secret|password|api[_-]?key)\s*[:=]\s*\S+/gi,
|
|
19
|
+
/sk-[a-zA-Z0-9]{20,}/g,
|
|
20
|
+
/ghp_[a-zA-Z0-9]{20,}/g,
|
|
21
|
+
/\b[A-Z][A-Z0-9_]*=\S+/g,
|
|
22
|
+
];
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* @param {string} text
|
|
26
|
+
*/
|
|
27
|
+
function redactSubprocessCommandText(text) {
|
|
28
|
+
let out = text;
|
|
29
|
+
for (const pattern of SUBPROCESS_STRING_REDACT_PATTERNS) {
|
|
30
|
+
out = out.replace(pattern, "[REDACTED]");
|
|
31
|
+
}
|
|
32
|
+
return out.replace(/\s+/g, " ").trim();
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* @param {string} raw
|
|
37
|
+
*/
|
|
38
|
+
function stripLeadingEnvAssignments(command) {
|
|
39
|
+
let rest = command.trim();
|
|
40
|
+
while (/^[A-Za-z_][A-Za-z0-9_]*=\S+\s+/.test(rest)) {
|
|
41
|
+
rest = rest.replace(/^[A-Za-z_][A-Za-z0-9_]*=\S+\s+/, "");
|
|
42
|
+
}
|
|
43
|
+
return rest.trim();
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* Redact secrets and shorten a subprocess command for heartbeat payloads.
|
|
48
|
+
*
|
|
49
|
+
* @param {string} raw
|
|
50
|
+
*/
|
|
51
|
+
export function redactSubprocessCommand(raw) {
|
|
52
|
+
if (!raw || typeof raw !== "string") return null;
|
|
53
|
+
const head = raw.split(/\s*(?:&&|;|\|)\s*/)[0]?.trim() ?? "";
|
|
54
|
+
if (!head) return null;
|
|
55
|
+
const withoutEnv = stripLeadingEnvAssignments(head);
|
|
56
|
+
const redacted = redactSubprocessCommandText(withoutEnv);
|
|
57
|
+
const trimmed =
|
|
58
|
+
redacted.length > SUBPROCESS_COMMAND_MAX_LEN
|
|
59
|
+
? `${redacted.slice(0, SUBPROCESS_COMMAND_MAX_LEN - 1)}…`
|
|
60
|
+
: redacted;
|
|
61
|
+
for (const [pattern, label] of SUBPROCESS_FRIENDLY_LABELS) {
|
|
62
|
+
if (pattern.test(trimmed)) return label;
|
|
63
|
+
}
|
|
64
|
+
return trimmed;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* @param {object} event
|
|
69
|
+
* @param {object} filter
|
|
70
|
+
* @param {number} [filter.laneNumber]
|
|
71
|
+
* @param {string} [filter.laneId]
|
|
72
|
+
* @param {string} [filter.taskId]
|
|
73
|
+
*/
|
|
74
|
+
function subprocessEventMatches(event, { laneNumber, laneId, taskId }) {
|
|
75
|
+
const payload = event.payload && typeof event.payload === "object" ? event.payload : {};
|
|
76
|
+
const expectedLaneId =
|
|
77
|
+
laneNumber != null ? `lane-${laneNumber}` : typeof laneId === "string" ? laneId : null;
|
|
78
|
+
if (taskId && event.taskId && event.taskId !== taskId) return false;
|
|
79
|
+
if (payload.taskId && taskId && payload.taskId !== taskId) return false;
|
|
80
|
+
if (expectedLaneId && event.laneId && event.laneId !== expectedLaneId) return false;
|
|
81
|
+
if (expectedLaneId && payload.laneId && payload.laneId !== expectedLaneId) return false;
|
|
82
|
+
if (laneNumber != null && payload.laneNumber != null && payload.laneNumber !== laneNumber) {
|
|
83
|
+
return false;
|
|
84
|
+
}
|
|
85
|
+
return true;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* Latest active subprocess signal from worker journal events (issue #134 / SP-548).
|
|
90
|
+
*
|
|
91
|
+
* @param {object[]} events
|
|
92
|
+
* @param {object} filter
|
|
93
|
+
* @param {number} [filter.laneNumber]
|
|
94
|
+
* @param {string} [filter.laneId]
|
|
95
|
+
* @param {string} [filter.taskId]
|
|
96
|
+
*/
|
|
97
|
+
export function findLatestSubprocessSignal(events, { laneNumber, laneId, taskId }) {
|
|
98
|
+
for (let index = events.length - 1; index >= 0; index -= 1) {
|
|
99
|
+
const event = events[index];
|
|
100
|
+
if (!subprocessEventMatches(event, { laneNumber, laneId, taskId })) continue;
|
|
101
|
+
|
|
102
|
+
const payload = event.payload && typeof event.payload === "object" ? event.payload : {};
|
|
103
|
+
const ts = Date.parse(event.timestamp);
|
|
104
|
+
if (Number.isNaN(ts)) continue;
|
|
105
|
+
|
|
106
|
+
if (event.type === "task.subprocess_ended") {
|
|
107
|
+
return null;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
const rawCommand =
|
|
111
|
+
typeof payload.subprocessCommand === "string"
|
|
112
|
+
? payload.subprocessCommand
|
|
113
|
+
: typeof payload.subprocessLabel === "string"
|
|
114
|
+
? payload.subprocessLabel
|
|
115
|
+
: null;
|
|
116
|
+
if (!rawCommand) continue;
|
|
117
|
+
|
|
118
|
+
if (event.type === "task.subprocess_active" || event.type === "task.step_completed") {
|
|
119
|
+
const subprocessCommand = redactSubprocessCommand(rawCommand);
|
|
120
|
+
if (!subprocessCommand) continue;
|
|
121
|
+
return { subprocessCommand, subprocessStartedAtMs: ts };
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
return null;
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/**
|
|
129
|
+
* @param {WorkerPhase} enginePhase
|
|
130
|
+
* @param {object | null | undefined} signals
|
|
131
|
+
*/
|
|
132
|
+
export function resolveEffectiveWorkerPhase(enginePhase, signals) {
|
|
133
|
+
if (signals?.subprocessCommand) return "subprocess";
|
|
134
|
+
return enginePhase;
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/**
|
|
138
|
+
* Progress-class heartbeat fields are omitted during launcher preflight so retries
|
|
139
|
+
* do not reuse stale STATUS / git checkpoint signals from a prior attempt.
|
|
140
|
+
*
|
|
141
|
+
* @param {object} signals
|
|
142
|
+
* @param {WorkerPhase} workerPhase
|
|
143
|
+
* @param {"worker_alive" | "checkpoint" | "file_scope_activity"} heartbeatKind
|
|
144
|
+
*/
|
|
145
|
+
export function buildHeartbeatPayloadFields(signals, workerPhase, heartbeatKind) {
|
|
146
|
+
const effectivePhase = resolveEffectiveWorkerPhase(workerPhase, signals);
|
|
147
|
+
const includeProgressFields =
|
|
148
|
+
effectivePhase !== "launching" &&
|
|
149
|
+
(heartbeatKind === "checkpoint" || heartbeatKind === "file_scope_activity");
|
|
150
|
+
|
|
151
|
+
/** @type {Record<string, unknown>} */
|
|
152
|
+
const payload = {
|
|
153
|
+
statusMtimeMs: null,
|
|
154
|
+
lastCommitAtMs: null,
|
|
155
|
+
fileScopeMtimeMs: null,
|
|
156
|
+
dirtyPathCount: 0,
|
|
157
|
+
};
|
|
158
|
+
|
|
159
|
+
if (effectivePhase === "subprocess" && signals?.subprocessCommand) {
|
|
160
|
+
payload.subprocessCommand = signals.subprocessCommand;
|
|
161
|
+
payload.subprocessStartedAtMs = signals.subprocessStartedAtMs ?? null;
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
if (!includeProgressFields) {
|
|
165
|
+
return payload;
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
return {
|
|
169
|
+
...payload,
|
|
170
|
+
statusMtimeMs: signals.statusMtimeMs,
|
|
171
|
+
lastCommitAtMs: signals.lastCommitAtMs,
|
|
172
|
+
fileScopeMtimeMs: signals.fileScopeMtimeMs,
|
|
173
|
+
dirtyPathCount: signals.dirtyPaths?.length ?? 0,
|
|
174
|
+
};
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
/**
|
|
178
|
+
* Bounded lane.progress_snapshot payload (issue #48).
|
|
179
|
+
*
|
|
180
|
+
* @param {object} signals
|
|
181
|
+
* @param {WorkerPhase} workerPhase
|
|
182
|
+
*/
|
|
183
|
+
export function buildProgressSnapshotPayload(signals, workerPhase) {
|
|
184
|
+
const effectivePhase = resolveEffectiveWorkerPhase(workerPhase, signals);
|
|
185
|
+
/** @type {Record<string, unknown>} */
|
|
186
|
+
const payload = {
|
|
187
|
+
workerPhase: effectivePhase,
|
|
188
|
+
dirtyPathCount: signals.dirtyPaths?.length ?? 0,
|
|
189
|
+
lastCommitAtMs: signals.lastCommitAtMs ?? null,
|
|
190
|
+
statusMtimeMs: signals.statusMtimeMs ?? null,
|
|
191
|
+
stepCompletedAtMs: signals.stepCompletedAtMs ?? null,
|
|
192
|
+
};
|
|
193
|
+
if (effectivePhase === "subprocess" && signals?.subprocessCommand) {
|
|
194
|
+
payload.subprocessCommand = signals.subprocessCommand;
|
|
195
|
+
payload.subprocessStartedAtMs = signals.subprocessStartedAtMs ?? null;
|
|
196
|
+
}
|
|
197
|
+
return payload;
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
/**
|
|
201
|
+
* @param {object | null} prev
|
|
202
|
+
* @param {object} next
|
|
203
|
+
*/
|
|
204
|
+
export function progressSnapshotPayloadChanged(prev, next) {
|
|
205
|
+
if (!prev) return true;
|
|
206
|
+
if (prev.workerPhase !== next.workerPhase) return true;
|
|
207
|
+
if (prev.dirtyPathCount !== next.dirtyPathCount) return true;
|
|
208
|
+
if (prev.lastCommitAtMs !== next.lastCommitAtMs) return true;
|
|
209
|
+
if (prev.statusMtimeMs !== next.statusMtimeMs) return true;
|
|
210
|
+
if (prev.stepCompletedAtMs !== next.stepCompletedAtMs) return true;
|
|
211
|
+
if (prev.subprocessCommand !== next.subprocessCommand) return true;
|
|
212
|
+
if (prev.subprocessStartedAtMs !== next.subprocessStartedAtMs) return true;
|
|
213
|
+
return false;
|
|
214
|
+
}
|
package/src/batch/heartbeat.mjs
CHANGED
|
@@ -11,6 +11,12 @@ import {
|
|
|
11
11
|
resolveDebouncedScopedDirtyPaths,
|
|
12
12
|
resolveFileScopeMtimeMs,
|
|
13
13
|
} from "./heartbeat-git-debounce.mjs";
|
|
14
|
+
import {
|
|
15
|
+
findLatestSubprocessSignal,
|
|
16
|
+
resolveEffectiveWorkerPhase,
|
|
17
|
+
buildHeartbeatPayloadFields,
|
|
18
|
+
buildProgressSnapshotPayload,
|
|
19
|
+
} from "./heartbeat-subprocess.mjs";
|
|
14
20
|
|
|
15
21
|
export {
|
|
16
22
|
clearGitPorcelainDebounceCache,
|
|
@@ -18,6 +24,15 @@ export {
|
|
|
18
24
|
resetGitPorcelainCallCount,
|
|
19
25
|
} from "./heartbeat-git-debounce.mjs";
|
|
20
26
|
|
|
27
|
+
export {
|
|
28
|
+
findLatestSubprocessSignal,
|
|
29
|
+
redactSubprocessCommand,
|
|
30
|
+
resolveEffectiveWorkerPhase,
|
|
31
|
+
buildHeartbeatPayloadFields,
|
|
32
|
+
buildProgressSnapshotPayload,
|
|
33
|
+
progressSnapshotPayloadChanged,
|
|
34
|
+
} from "./heartbeat-subprocess.mjs";
|
|
35
|
+
|
|
21
36
|
const DEFAULT_STALL_TIMEOUT_MIN = 60;
|
|
22
37
|
const DEFAULT_GRACE_AFTER_PROGRESS_MIN = 15;
|
|
23
38
|
const DEFAULT_HEARTBEAT_INTERVAL_MIN = 10;
|
|
@@ -30,7 +45,7 @@ const CHECKPOINT_WARNING_SUGGESTION =
|
|
|
30
45
|
"Commit step work and call spine_report_progress so stall grace tracks checkpoints, not file edits alone.";
|
|
31
46
|
|
|
32
47
|
/** @typedef {"worker_alive" | "checkpoint" | "file_scope_activity"} HeartbeatKind */
|
|
33
|
-
/** @typedef {"launching" | "pi" | "verify" | "unknown"} WorkerPhase */
|
|
48
|
+
/** @typedef {"launching" | "pi" | "verify" | "subprocess" | "unknown"} WorkerPhase */
|
|
34
49
|
|
|
35
50
|
/** @type {readonly HeartbeatKind[]} */
|
|
36
51
|
export const HEARTBEAT_KINDS = Object.freeze([
|
|
@@ -40,7 +55,13 @@ export const HEARTBEAT_KINDS = Object.freeze([
|
|
|
40
55
|
]);
|
|
41
56
|
|
|
42
57
|
/** @type {readonly WorkerPhase[]} */
|
|
43
|
-
export const WORKER_PHASES = Object.freeze([
|
|
58
|
+
export const WORKER_PHASES = Object.freeze([
|
|
59
|
+
"launching",
|
|
60
|
+
"pi",
|
|
61
|
+
"verify",
|
|
62
|
+
"subprocess",
|
|
63
|
+
"unknown",
|
|
64
|
+
]);
|
|
44
65
|
|
|
45
66
|
/**
|
|
46
67
|
* @param {object} [config]
|
|
@@ -196,6 +217,8 @@ export function collectProgressSignals({
|
|
|
196
217
|
);
|
|
197
218
|
|
|
198
219
|
let stepCompletedAtMs = null;
|
|
220
|
+
let subprocessCommand = null;
|
|
221
|
+
let subprocessStartedAtMs = null;
|
|
199
222
|
if (journalContext?.projectRoot && journalContext?.batchId) {
|
|
200
223
|
const events = readJournalEventsCached(journalContext.projectRoot, journalContext.batchId);
|
|
201
224
|
stepCompletedAtMs = findLatestStepCompletedMs(events, {
|
|
@@ -203,6 +226,15 @@ export function collectProgressSignals({
|
|
|
203
226
|
laneId: journalContext.laneId,
|
|
204
227
|
taskId: journalContext.taskId,
|
|
205
228
|
});
|
|
229
|
+
const subprocess = findLatestSubprocessSignal(events, {
|
|
230
|
+
laneNumber: journalContext.laneNumber,
|
|
231
|
+
laneId: journalContext.laneId,
|
|
232
|
+
taskId: journalContext.taskId,
|
|
233
|
+
});
|
|
234
|
+
if (subprocess) {
|
|
235
|
+
subprocessCommand = subprocess.subprocessCommand;
|
|
236
|
+
subprocessStartedAtMs = subprocess.subprocessStartedAtMs;
|
|
237
|
+
}
|
|
206
238
|
}
|
|
207
239
|
|
|
208
240
|
return {
|
|
@@ -211,6 +243,8 @@ export function collectProgressSignals({
|
|
|
211
243
|
fileScopeMtimeMs,
|
|
212
244
|
stepCompletedAtMs,
|
|
213
245
|
dirtyPaths,
|
|
246
|
+
subprocessCommand,
|
|
247
|
+
subprocessStartedAtMs,
|
|
214
248
|
};
|
|
215
249
|
}
|
|
216
250
|
|
|
@@ -323,66 +357,6 @@ export function resolveHeartbeatKind({
|
|
|
323
357
|
return "worker_alive";
|
|
324
358
|
}
|
|
325
359
|
|
|
326
|
-
/**
|
|
327
|
-
* Progress-class heartbeat fields are omitted during launcher preflight so retries
|
|
328
|
-
* do not reuse stale STATUS / git checkpoint signals from a prior attempt.
|
|
329
|
-
*
|
|
330
|
-
* @param {object} signals
|
|
331
|
-
* @param {WorkerPhase} workerPhase
|
|
332
|
-
* @param {HeartbeatKind} heartbeatKind
|
|
333
|
-
*/
|
|
334
|
-
export function buildHeartbeatPayloadFields(signals, workerPhase, heartbeatKind) {
|
|
335
|
-
const includeProgressFields =
|
|
336
|
-
workerPhase !== "launching" &&
|
|
337
|
-
(heartbeatKind === "checkpoint" || heartbeatKind === "file_scope_activity");
|
|
338
|
-
|
|
339
|
-
if (!includeProgressFields) {
|
|
340
|
-
return {
|
|
341
|
-
statusMtimeMs: null,
|
|
342
|
-
lastCommitAtMs: null,
|
|
343
|
-
fileScopeMtimeMs: null,
|
|
344
|
-
dirtyPathCount: 0,
|
|
345
|
-
};
|
|
346
|
-
}
|
|
347
|
-
|
|
348
|
-
return {
|
|
349
|
-
statusMtimeMs: signals.statusMtimeMs,
|
|
350
|
-
lastCommitAtMs: signals.lastCommitAtMs,
|
|
351
|
-
fileScopeMtimeMs: signals.fileScopeMtimeMs,
|
|
352
|
-
dirtyPathCount: signals.dirtyPaths?.length ?? 0,
|
|
353
|
-
};
|
|
354
|
-
}
|
|
355
|
-
|
|
356
|
-
/**
|
|
357
|
-
* Bounded lane.progress_snapshot payload (issue #48).
|
|
358
|
-
*
|
|
359
|
-
* @param {object} signals
|
|
360
|
-
* @param {WorkerPhase} workerPhase
|
|
361
|
-
*/
|
|
362
|
-
export function buildProgressSnapshotPayload(signals, workerPhase) {
|
|
363
|
-
return {
|
|
364
|
-
workerPhase,
|
|
365
|
-
dirtyPathCount: signals.dirtyPaths?.length ?? 0,
|
|
366
|
-
lastCommitAtMs: signals.lastCommitAtMs ?? null,
|
|
367
|
-
statusMtimeMs: signals.statusMtimeMs ?? null,
|
|
368
|
-
stepCompletedAtMs: signals.stepCompletedAtMs ?? null,
|
|
369
|
-
};
|
|
370
|
-
}
|
|
371
|
-
|
|
372
|
-
/**
|
|
373
|
-
* @param {object | null} prev
|
|
374
|
-
* @param {object} next
|
|
375
|
-
*/
|
|
376
|
-
export function progressSnapshotPayloadChanged(prev, next) {
|
|
377
|
-
if (!prev) return true;
|
|
378
|
-
if (prev.workerPhase !== next.workerPhase) return true;
|
|
379
|
-
if (prev.dirtyPathCount !== next.dirtyPathCount) return true;
|
|
380
|
-
if (prev.lastCommitAtMs !== next.lastCommitAtMs) return true;
|
|
381
|
-
if (prev.statusMtimeMs !== next.statusMtimeMs) return true;
|
|
382
|
-
if (prev.stepCompletedAtMs !== next.stepCompletedAtMs) return true;
|
|
383
|
-
return false;
|
|
384
|
-
}
|
|
385
|
-
|
|
386
360
|
/**
|
|
387
361
|
* @param {object} params
|
|
388
362
|
* @param {number} params.now
|
|
@@ -430,13 +404,14 @@ export function recordLaneHeartbeat({
|
|
|
430
404
|
workerPhase = "unknown",
|
|
431
405
|
heartbeatKind = "worker_alive",
|
|
432
406
|
}) {
|
|
407
|
+
const effectivePhase = resolveEffectiveWorkerPhase(workerPhase, signals);
|
|
433
408
|
const progressFields = buildHeartbeatPayloadFields(signals, workerPhase, heartbeatKind);
|
|
434
409
|
appendJournalEvent(projectRoot, batchId, "lane.heartbeat", {
|
|
435
410
|
laneNumber,
|
|
436
411
|
taskId,
|
|
437
412
|
correlationId,
|
|
438
413
|
heartbeatKind,
|
|
439
|
-
workerPhase,
|
|
414
|
+
workerPhase: effectivePhase,
|
|
440
415
|
...progressFields,
|
|
441
416
|
});
|
|
442
417
|
}
|
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
// @ts-nocheck
|
|
2
|
+
/**
|
|
3
|
+
* Attached engine parent session monitor (FR-STAB-01, GitHub #163, SP-539).
|
|
4
|
+
*
|
|
5
|
+
* Detects parent shell/session loss while an attached batch engine runs and
|
|
6
|
+
* reconciles orphan running tasks before the operator resumes detached.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import { isProcessAlive } from "../process/liveness.mjs";
|
|
10
|
+
import { loadSpineConfig } from "../config/spine-config-load.mjs";
|
|
11
|
+
import { resolveAttachedMilestonePollMs } from "../config/spine-config-schema.mjs";
|
|
12
|
+
import { appendJournalEvent } from "./journal.mjs";
|
|
13
|
+
import {
|
|
14
|
+
clearBatchEnginePid,
|
|
15
|
+
loadSpineBatchState,
|
|
16
|
+
readBatchEnginePid,
|
|
17
|
+
recomputeTaskCounters,
|
|
18
|
+
saveSpineBatchState,
|
|
19
|
+
updateSegmentForTask,
|
|
20
|
+
} from "./state.mjs";
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* @param {number} ms
|
|
24
|
+
*/
|
|
25
|
+
function sleep(ms) {
|
|
26
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* Parent session is lost when the process reparented or the recorded parent PID died.
|
|
31
|
+
*
|
|
32
|
+
* @param {object} params
|
|
33
|
+
* @param {number} params.initialParentPid
|
|
34
|
+
* @param {number} [params.currentParentPid]
|
|
35
|
+
* @param {(pid: number) => boolean} [params.isAlive]
|
|
36
|
+
*/
|
|
37
|
+
export function isParentSessionLost({
|
|
38
|
+
initialParentPid,
|
|
39
|
+
currentParentPid = process.ppid,
|
|
40
|
+
isAlive = isProcessAlive,
|
|
41
|
+
}) {
|
|
42
|
+
const initial = Number(initialParentPid);
|
|
43
|
+
const current = Number(currentParentPid);
|
|
44
|
+
if (!Number.isFinite(initial) || initial <= 0) {
|
|
45
|
+
return false;
|
|
46
|
+
}
|
|
47
|
+
if (!Number.isFinite(current) || current <= 0) {
|
|
48
|
+
return true;
|
|
49
|
+
}
|
|
50
|
+
if (current !== initial) {
|
|
51
|
+
return true;
|
|
52
|
+
}
|
|
53
|
+
return !isAlive(current);
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* Fail-closed reconcile when the attached engine parent session is gone.
|
|
58
|
+
*
|
|
59
|
+
* @param {object} params
|
|
60
|
+
* @param {string} params.projectRoot
|
|
61
|
+
* @param {number} params.parentPid
|
|
62
|
+
* @param {number} [params.enginePid]
|
|
63
|
+
* @returns {{ handled: boolean, batchId?: string, taskIds?: string[] }}
|
|
64
|
+
*/
|
|
65
|
+
export function reconcileParentSessionLost({ projectRoot, parentPid, enginePid = process.pid }) {
|
|
66
|
+
const loaded = loadSpineBatchState(projectRoot);
|
|
67
|
+
const state = loaded.raw;
|
|
68
|
+
if (!state || typeof state !== "object") {
|
|
69
|
+
return { handled: false };
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
const batchId = String(state.batchId ?? "");
|
|
73
|
+
if (!batchId) {
|
|
74
|
+
return { handled: false };
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
const phase = String(state.phase ?? "");
|
|
78
|
+
if (phase === "completed" || phase === "aborted" || phase === "failed") {
|
|
79
|
+
return { handled: false, batchId };
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
appendJournalEvent(projectRoot, batchId, "engine.parent_died", {
|
|
83
|
+
parentPid,
|
|
84
|
+
enginePid,
|
|
85
|
+
signal: "parent_exit",
|
|
86
|
+
});
|
|
87
|
+
|
|
88
|
+
const now = Date.now();
|
|
89
|
+
/** @type {string[]} */
|
|
90
|
+
const failedTaskIds = [];
|
|
91
|
+
let changed = false;
|
|
92
|
+
|
|
93
|
+
for (const task of state.tasks ?? []) {
|
|
94
|
+
if (!task || typeof task !== "object") continue;
|
|
95
|
+
if (String(task.status ?? "").toLowerCase() !== "running") continue;
|
|
96
|
+
|
|
97
|
+
const taskId = String(task.taskId ?? "");
|
|
98
|
+
if (!taskId) continue;
|
|
99
|
+
|
|
100
|
+
task.status = "failed";
|
|
101
|
+
task.endedAt = now;
|
|
102
|
+
task.exitReason = "parent_exit";
|
|
103
|
+
updateSegmentForTask(state, taskId, "failed");
|
|
104
|
+
failedTaskIds.push(taskId);
|
|
105
|
+
changed = true;
|
|
106
|
+
|
|
107
|
+
const laneNumber = Number(task.laneNumber ?? 1);
|
|
108
|
+
const lane = (state.lanes ?? []).find((entry) => Number(entry?.laneNumber) === laneNumber);
|
|
109
|
+
appendJournalEvent(projectRoot, batchId, "task.failed", {
|
|
110
|
+
taskId,
|
|
111
|
+
laneNumber,
|
|
112
|
+
laneId: lane?.laneId ?? `lane-${laneNumber}`,
|
|
113
|
+
reason: "parent_exit",
|
|
114
|
+
reconciled: true,
|
|
115
|
+
});
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
for (const lane of state.lanes ?? []) {
|
|
119
|
+
if (!lane || typeof lane !== "object") continue;
|
|
120
|
+
const workerPid = Number(/** @type {{ workerPid?: number }} */ (lane).workerPid);
|
|
121
|
+
if (Number.isFinite(workerPid) && workerPid > 0 && !isProcessAlive(workerPid)) {
|
|
122
|
+
delete lane.workerPid;
|
|
123
|
+
changed = true;
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
const recordedEnginePid = readBatchEnginePid(state);
|
|
128
|
+
if (recordedEnginePid != null) {
|
|
129
|
+
clearBatchEnginePid(state);
|
|
130
|
+
changed = true;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
if (phase !== "paused") {
|
|
134
|
+
state.phase = "paused";
|
|
135
|
+
changed = true;
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
if (!changed) {
|
|
139
|
+
return { handled: true, batchId, taskIds: failedTaskIds };
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
recomputeTaskCounters(state);
|
|
143
|
+
saveSpineBatchState(projectRoot, state, { bypassWriteGuard: true });
|
|
144
|
+
return { handled: true, batchId, taskIds: failedTaskIds };
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
/**
|
|
148
|
+
* @param {object} params
|
|
149
|
+
* @param {string} params.projectRoot
|
|
150
|
+
* @param {number} [params.pollIntervalMs]
|
|
151
|
+
* @param {(pid: number) => boolean} [params.isAlive]
|
|
152
|
+
* @param {() => number} [params.readParentPid]
|
|
153
|
+
* @param {(result: ReturnType<typeof reconcileParentSessionLost>) => void} [params.onParentDied]
|
|
154
|
+
* @returns {Promise<{ stop: () => Promise<void> }>}
|
|
155
|
+
*/
|
|
156
|
+
export async function startParentSessionMonitor({
|
|
157
|
+
projectRoot,
|
|
158
|
+
pollIntervalMs,
|
|
159
|
+
isAlive = isProcessAlive,
|
|
160
|
+
readParentPid = () => process.ppid,
|
|
161
|
+
onParentDied,
|
|
162
|
+
}) {
|
|
163
|
+
const configResult = loadSpineConfig(projectRoot);
|
|
164
|
+
const resolvedPollMs =
|
|
165
|
+
pollIntervalMs ??
|
|
166
|
+
resolveAttachedMilestonePollMs({ config: configResult.config ?? {} });
|
|
167
|
+
const initialParentPid = readParentPid();
|
|
168
|
+
let stopped = false;
|
|
169
|
+
let handled = false;
|
|
170
|
+
|
|
171
|
+
const loop = async () => {
|
|
172
|
+
while (!stopped) {
|
|
173
|
+
if (
|
|
174
|
+
!handled &&
|
|
175
|
+
isParentSessionLost({
|
|
176
|
+
initialParentPid,
|
|
177
|
+
currentParentPid: readParentPid(),
|
|
178
|
+
isAlive,
|
|
179
|
+
})
|
|
180
|
+
) {
|
|
181
|
+
handled = true;
|
|
182
|
+
const result = reconcileParentSessionLost({
|
|
183
|
+
projectRoot,
|
|
184
|
+
parentPid: initialParentPid,
|
|
185
|
+
enginePid: process.pid,
|
|
186
|
+
});
|
|
187
|
+
onParentDied?.(result);
|
|
188
|
+
}
|
|
189
|
+
await sleep(resolvedPollMs);
|
|
190
|
+
}
|
|
191
|
+
};
|
|
192
|
+
|
|
193
|
+
const loopPromise = loop();
|
|
194
|
+
|
|
195
|
+
return {
|
|
196
|
+
stop: async () => {
|
|
197
|
+
stopped = true;
|
|
198
|
+
await loopPromise;
|
|
199
|
+
},
|
|
200
|
+
};
|
|
201
|
+
}
|
|
@@ -190,7 +190,18 @@ export function checkDoctor(ctx) {
|
|
|
190
190
|
* @param {object} [_ctx]
|
|
191
191
|
* @param {{ stalePathCheckArgs?: object }} [options]
|
|
192
192
|
*/
|
|
193
|
-
export function checkStalePathSpine(
|
|
193
|
+
export function checkStalePathSpine(ctx = {}, options = {}) {
|
|
194
|
+
if (
|
|
195
|
+
ctx.projectRoot &&
|
|
196
|
+
path.resolve(ctx.projectRoot) !== path.resolve(PACKAGE_ROOT)
|
|
197
|
+
) {
|
|
198
|
+
return makeCheck(
|
|
199
|
+
"stale-path-spine",
|
|
200
|
+
true,
|
|
201
|
+
"stale PATH spine check skipped (isolated project fixture)",
|
|
202
|
+
);
|
|
203
|
+
}
|
|
204
|
+
|
|
194
205
|
const check = buildStalePathDoctorCheck({
|
|
195
206
|
packageRoot: PACKAGE_ROOT,
|
|
196
207
|
runningSpinePath: path.join(PACKAGE_ROOT, "bin", "spine.mjs"),
|
|
@@ -227,8 +227,12 @@ function renderLanes(lanes, laneTableSummary, tailActivity, expandedLaneId) {
|
|
|
227
227
|
tr.dataset.laneId = lane.laneId;
|
|
228
228
|
tr.setAttribute("aria-expanded", lane.laneId === expandedLaneId ? "true" : "false");
|
|
229
229
|
const throughput = lane.throughput ?? {};
|
|
230
|
-
const
|
|
231
|
-
|
|
230
|
+
const isTerminalFailure = lane.activityPhase === "failed";
|
|
231
|
+
// Completed lanes use terminal outcome only; failedCount stays a retry metric.
|
|
232
|
+
const isTaskFailed =
|
|
233
|
+
lane.status === "completed"
|
|
234
|
+
? isTerminalFailure
|
|
235
|
+
: (throughput.failedCount ?? 0) > 0 || isTerminalFailure;
|
|
232
236
|
const isTaskSucceeded = lane.status === "completed" && !isTaskFailed;
|
|
233
237
|
const isTaskRunning = lane.status === "running" && !isTaskFailed;
|
|
234
238
|
if (isTaskFailed) tr.classList.add("task-failed");
|
|
@@ -17,6 +17,7 @@ import {
|
|
|
17
17
|
} from "../batch/journal.mjs";
|
|
18
18
|
import { resolveStallConfig } from "../batch/heartbeat.mjs";
|
|
19
19
|
import { loadSpineConfig } from "../config/spine-config-load.mjs";
|
|
20
|
+
import { formatElapsedMs } from "./lane-throughput.mjs";
|
|
20
21
|
import {
|
|
21
22
|
deriveLanesThroughput,
|
|
22
23
|
summarizeLaneThroughput,
|
|
@@ -39,6 +40,75 @@ import {
|
|
|
39
40
|
/** Last N journal events included in dashboard snapshot tail (not full journal per client). */
|
|
40
41
|
export const DASHBOARD_JOURNAL_TAIL_LIMIT = 20;
|
|
41
42
|
|
|
43
|
+
/**
|
|
44
|
+
* @param {number} laneNumber
|
|
45
|
+
* @param {object[]} journalEvents
|
|
46
|
+
*/
|
|
47
|
+
export function resolveSubprocessHeartbeatMeta(laneNumber, journalEvents) {
|
|
48
|
+
for (let index = journalEvents.length - 1; index >= 0; index -= 1) {
|
|
49
|
+
const event = journalEvents[index];
|
|
50
|
+
if (event.type !== "lane.heartbeat") continue;
|
|
51
|
+
const payload = event.payload && typeof event.payload === "object" ? event.payload : {};
|
|
52
|
+
if (payload.laneNumber != null && payload.laneNumber !== laneNumber) continue;
|
|
53
|
+
if (event.laneId && event.laneId !== `lane-${laneNumber}`) continue;
|
|
54
|
+
return {
|
|
55
|
+
workerPhase: typeof payload.workerPhase === "string" ? payload.workerPhase : null,
|
|
56
|
+
subprocessCommand:
|
|
57
|
+
typeof payload.subprocessCommand === "string" ? payload.subprocessCommand : null,
|
|
58
|
+
subprocessStartedAtMs:
|
|
59
|
+
payload.subprocessStartedAtMs != null ? Number(payload.subprocessStartedAtMs) : null,
|
|
60
|
+
};
|
|
61
|
+
}
|
|
62
|
+
return { workerPhase: null, subprocessCommand: null, subprocessStartedAtMs: null };
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* @param {object} params
|
|
67
|
+
* @param {string} params.subprocessCommand
|
|
68
|
+
* @param {number | null} [params.subprocessStartedAtMs]
|
|
69
|
+
* @param {number} [params.now]
|
|
70
|
+
*/
|
|
71
|
+
export function formatSubprocessHeartbeatDisplay({
|
|
72
|
+
subprocessCommand,
|
|
73
|
+
subprocessStartedAtMs,
|
|
74
|
+
now = Date.now(),
|
|
75
|
+
}) {
|
|
76
|
+
const elapsedMs =
|
|
77
|
+
subprocessStartedAtMs != null && Number.isFinite(subprocessStartedAtMs)
|
|
78
|
+
? Math.max(0, now - subprocessStartedAtMs)
|
|
79
|
+
: null;
|
|
80
|
+
const elapsed = elapsedMs != null ? formatElapsedMs(elapsedMs) : null;
|
|
81
|
+
if (elapsed && elapsed !== "—") {
|
|
82
|
+
return `running ${subprocessCommand} (${elapsed})`;
|
|
83
|
+
}
|
|
84
|
+
return `running ${subprocessCommand}`;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* @param {object[]} lanes
|
|
89
|
+
* @param {object[]} journalEvents
|
|
90
|
+
* @param {number} [now]
|
|
91
|
+
*/
|
|
92
|
+
export function enrichLaneRowsWithSubprocessHeartbeat(lanes, journalEvents, now = Date.now()) {
|
|
93
|
+
return (lanes ?? []).map((lane) => {
|
|
94
|
+
const subprocessMeta = resolveSubprocessHeartbeatMeta(lane.laneNumber, journalEvents);
|
|
95
|
+
if (subprocessMeta.workerPhase !== "subprocess" || !subprocessMeta.subprocessCommand) {
|
|
96
|
+
return lane;
|
|
97
|
+
}
|
|
98
|
+
return {
|
|
99
|
+
...lane,
|
|
100
|
+
workerPhase: subprocessMeta.workerPhase,
|
|
101
|
+
subprocessCommand: subprocessMeta.subprocessCommand,
|
|
102
|
+
subprocessStartedAtMs: subprocessMeta.subprocessStartedAtMs,
|
|
103
|
+
heartbeatDisplay: formatSubprocessHeartbeatDisplay({
|
|
104
|
+
subprocessCommand: subprocessMeta.subprocessCommand,
|
|
105
|
+
subprocessStartedAtMs: subprocessMeta.subprocessStartedAtMs,
|
|
106
|
+
now,
|
|
107
|
+
}),
|
|
108
|
+
};
|
|
109
|
+
});
|
|
110
|
+
}
|
|
111
|
+
|
|
42
112
|
/**
|
|
43
113
|
* @param {string} projectRoot
|
|
44
114
|
*/
|
|
@@ -105,19 +175,23 @@ export function buildDashboardSnapshot(projectRoot) {
|
|
|
105
175
|
});
|
|
106
176
|
}
|
|
107
177
|
|
|
108
|
-
const lanes =
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
178
|
+
const lanes = enrichLaneRowsWithSubprocessHeartbeat(
|
|
179
|
+
buildLaneRows({
|
|
180
|
+
lanes: batch?.lanes ?? [],
|
|
181
|
+
classifiedTasks,
|
|
182
|
+
stallConfig,
|
|
183
|
+
currentWaveTaskIds,
|
|
184
|
+
journalTail,
|
|
185
|
+
journalEvents,
|
|
186
|
+
metricsLines,
|
|
187
|
+
projectRoot,
|
|
188
|
+
batchId: reconciliation.batchId,
|
|
189
|
+
now,
|
|
190
|
+
diagnosis: reconciliation.diagnosis,
|
|
191
|
+
}),
|
|
114
192
|
journalEvents,
|
|
115
|
-
metricsLines,
|
|
116
|
-
projectRoot,
|
|
117
|
-
batchId: reconciliation.batchId,
|
|
118
193
|
now,
|
|
119
|
-
|
|
120
|
-
});
|
|
194
|
+
);
|
|
121
195
|
const laneThroughputSummary = summarizeLaneThroughput(
|
|
122
196
|
deriveLanesThroughput({
|
|
123
197
|
lanes: batch?.lanes ?? [],
|
|
@@ -35,7 +35,7 @@ const AUTOMATION_ENV_PATTERNS = [
|
|
|
35
35
|
{ env: "CURSOR_SESSION_ID", id: "cursor_agent_shell", label: "Cursor agent shell" },
|
|
36
36
|
];
|
|
37
37
|
|
|
38
|
-
const DETACHED_RESUME_SUGGESTED =
|
|
38
|
+
export const DETACHED_RESUME_SUGGESTED =
|
|
39
39
|
"spine batch start|resume (omit --attached); spine wait --until completed,needs_integrate,failed,aborted --timeout 2h";
|
|
40
40
|
|
|
41
41
|
/**
|
|
@@ -82,6 +82,40 @@ export function detectAttachedOrphanRiskPatterns({
|
|
|
82
82
|
};
|
|
83
83
|
}
|
|
84
84
|
|
|
85
|
+
/**
|
|
86
|
+
* Fail-fast guard for `batch start|resume --attached` in risky shell contexts (SP-539 / #163).
|
|
87
|
+
*
|
|
88
|
+
* @param {object} [options]
|
|
89
|
+
* @param {boolean} [options.stdinIsTTY]
|
|
90
|
+
* @param {NodeJS.ProcessEnv} [options.env]
|
|
91
|
+
*/
|
|
92
|
+
export function enforceAttachedOrphanRiskGuard({
|
|
93
|
+
stdinIsTTY = process.stdin.isTTY === true,
|
|
94
|
+
env = process.env,
|
|
95
|
+
} = {}) {
|
|
96
|
+
if (env.SPINE_ALLOW_ATTACHED_HARNESS === "1") {
|
|
97
|
+
return { ok: true };
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
const { risky, patterns } = detectAttachedOrphanRiskPatterns({ stdinIsTTY, env });
|
|
101
|
+
if (!risky) {
|
|
102
|
+
return { ok: true };
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
const summary = patterns.map((pattern) => pattern.label).join("; ");
|
|
106
|
+
return {
|
|
107
|
+
ok: false,
|
|
108
|
+
exitCode: 1,
|
|
109
|
+
error: "attached_orphan_risk",
|
|
110
|
+
output:
|
|
111
|
+
`Refusing batch --attached in a risky shell context (#163).\n` +
|
|
112
|
+
`${summary}\n\n` +
|
|
113
|
+
`Parent shell exit orphans attached engines (exit 137). Use detached start instead:\n` +
|
|
114
|
+
` ${DETACHED_RESUME_SUGGESTED}\n`,
|
|
115
|
+
patterns,
|
|
116
|
+
};
|
|
117
|
+
}
|
|
118
|
+
|
|
85
119
|
/**
|
|
86
120
|
* Doctor advisory for attached orphan risk (#163 partial mitigation).
|
|
87
121
|
*
|
|
@@ -6,7 +6,10 @@
|
|
|
6
6
|
import micromatch from "micromatch";
|
|
7
7
|
|
|
8
8
|
import { matchesContractPattern } from "../../batch/contract-verify.mjs";
|
|
9
|
-
import {
|
|
9
|
+
import {
|
|
10
|
+
collectNpmTestDashDashErrors,
|
|
11
|
+
collectTestCommandScopeWarnings,
|
|
12
|
+
} from "../validate-contract-warn.mjs";
|
|
10
13
|
import { detectCommaInSingleBacktickPathLists } from "./parse-prompt.mjs";
|
|
11
14
|
|
|
12
15
|
/** Operator-facing hint when must-not-change blocks worker orchestration artifacts. */
|
|
@@ -116,9 +119,18 @@ export function validateContract(parsed, options = {}) {
|
|
|
116
119
|
}),
|
|
117
120
|
);
|
|
118
121
|
|
|
122
|
+
if (mode === "required") {
|
|
123
|
+
errors.push(
|
|
124
|
+
...collectNpmTestDashDashErrors(parsed, {
|
|
125
|
+
taskSize: options.taskSize ?? null,
|
|
126
|
+
}),
|
|
127
|
+
);
|
|
128
|
+
}
|
|
129
|
+
|
|
119
130
|
warnings.push(
|
|
120
131
|
...collectTestCommandScopeWarnings(parsed, {
|
|
121
132
|
taskSize: options.taskSize ?? null,
|
|
133
|
+
mode,
|
|
122
134
|
}),
|
|
123
135
|
);
|
|
124
136
|
|
|
@@ -18,47 +18,92 @@ export const TEST_COMMAND_NPM_TEST_DASH_DASH_FIX_HINT =
|
|
|
18
18
|
const PATCH_TASK_SIZES = new Set(["S", "M"]);
|
|
19
19
|
|
|
20
20
|
/** Matches `npm test --` followed by at least one path/token argument. */
|
|
21
|
-
const NPM_TEST_DASH_DASH_RE = /\bnpm\s+test\s+--\s+\S+/;
|
|
21
|
+
export const NPM_TEST_DASH_DASH_RE = /\bnpm\s+test\s+--\s+\S+/;
|
|
22
22
|
|
|
23
23
|
/**
|
|
24
|
-
*
|
|
24
|
+
* @param {ReturnType<import("./packet/parse-prompt.mjs").parseContract>} parsed
|
|
25
|
+
* @returns {boolean}
|
|
26
|
+
*/
|
|
27
|
+
function matchesNpmTestDashDashPattern(parsed) {
|
|
28
|
+
const testCommand = parsed?.testCommand;
|
|
29
|
+
if (!testCommand || testCommand === "true") {
|
|
30
|
+
return false;
|
|
31
|
+
}
|
|
32
|
+
return NPM_TEST_DASH_DASH_RE.test(testCommand);
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* @param {"S"|"M"|"L"} taskSize
|
|
37
|
+
* @returns {string}
|
|
38
|
+
*/
|
|
39
|
+
function formatNpmTestDashDashIssue(taskSize) {
|
|
40
|
+
return `Contract testCommand uses npm test -- <path> on Size ${taskSize} patch task; npm runs the full suite, not the path. ${TEST_COMMAND_NPM_TEST_DASH_DASH_FIX_HINT}`;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* Error when required-mode S/M contracts use npm test -- <path> false scoping (issue #187).
|
|
25
45
|
*
|
|
26
46
|
* @param {ReturnType<import("./packet/parse-prompt.mjs").parseContract>} parsed
|
|
27
47
|
* @param {{ taskSize?: "S"|"M"|"L"|"XL"|null }} [options]
|
|
28
48
|
* @returns {string[]}
|
|
29
49
|
*/
|
|
50
|
+
export function collectNpmTestDashDashErrors(parsed, options = {}) {
|
|
51
|
+
const taskSize = options.taskSize ?? null;
|
|
52
|
+
if (!PATCH_TASK_SIZES.has(taskSize)) {
|
|
53
|
+
return [];
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
if (!matchesNpmTestDashDashPattern(parsed)) {
|
|
57
|
+
return [];
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
return [formatNpmTestDashDashIssue(taskSize)];
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* Warn when S/M optional-mode or L task contracts use npm test -- <path> false scoping (issues #187, #141).
|
|
65
|
+
*
|
|
66
|
+
* @param {ReturnType<import("./packet/parse-prompt.mjs").parseContract>} parsed
|
|
67
|
+
* @param {{ taskSize?: "S"|"M"|"L"|"XL"|null, mode?: "required" | "optional" | "legacy" }} [options]
|
|
68
|
+
* @returns {string[]}
|
|
69
|
+
*/
|
|
30
70
|
export function collectNpmTestDashDashWarnings(parsed, options = {}) {
|
|
31
71
|
const taskSize = options.taskSize ?? null;
|
|
72
|
+
const mode = options.mode ?? "optional";
|
|
73
|
+
|
|
74
|
+
if (taskSize === "L") {
|
|
75
|
+
if (!matchesNpmTestDashDashPattern(parsed)) {
|
|
76
|
+
return [];
|
|
77
|
+
}
|
|
78
|
+
return [formatNpmTestDashDashIssue(taskSize)];
|
|
79
|
+
}
|
|
80
|
+
|
|
32
81
|
if (!PATCH_TASK_SIZES.has(taskSize)) {
|
|
33
82
|
return [];
|
|
34
83
|
}
|
|
35
84
|
|
|
36
|
-
|
|
37
|
-
if (
|
|
85
|
+
// Required S/M promotes to validation errors in validateContract.
|
|
86
|
+
if (mode === "required") {
|
|
38
87
|
return [];
|
|
39
88
|
}
|
|
40
89
|
|
|
41
|
-
if (!
|
|
90
|
+
if (!matchesNpmTestDashDashPattern(parsed)) {
|
|
42
91
|
return [];
|
|
43
92
|
}
|
|
44
93
|
|
|
45
|
-
return [
|
|
46
|
-
`Contract testCommand uses npm test -- <path> on Size ${taskSize} patch task; npm runs the full suite, not the path. ${TEST_COMMAND_NPM_TEST_DASH_DASH_FIX_HINT}`,
|
|
47
|
-
];
|
|
94
|
+
return [formatNpmTestDashDashIssue(taskSize)];
|
|
48
95
|
}
|
|
49
96
|
|
|
50
97
|
/**
|
|
51
98
|
* Warn when S/M task contracts chain full-suite gates in testCommand.
|
|
52
99
|
*
|
|
53
100
|
* @param {ReturnType<import("./packet/parse-prompt.mjs").parseContract>} parsed
|
|
54
|
-
* @param {{ taskSize?: "S"|"M"|"L"|"XL"|null }} [options]
|
|
101
|
+
* @param {{ taskSize?: "S"|"M"|"L"|"XL"|null, mode?: "required" | "optional" | "legacy" }} [options]
|
|
55
102
|
* @returns {string[]}
|
|
56
103
|
*/
|
|
57
104
|
export function collectTestCommandScopeWarnings(parsed, options = {}) {
|
|
58
105
|
const taskSize = options.taskSize ?? null;
|
|
59
|
-
|
|
60
|
-
return [];
|
|
61
|
-
}
|
|
106
|
+
const mode = options.mode ?? "optional";
|
|
62
107
|
|
|
63
108
|
const testCommand = parsed?.testCommand;
|
|
64
109
|
if (!testCommand || testCommand === "true") {
|
|
@@ -68,19 +113,27 @@ export function collectTestCommandScopeWarnings(parsed, options = {}) {
|
|
|
68
113
|
/** @type {string[]} */
|
|
69
114
|
const warnings = [];
|
|
70
115
|
|
|
71
|
-
if (
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
116
|
+
if (PATCH_TASK_SIZES.has(taskSize)) {
|
|
117
|
+
if (/\bcoverage:check\b/.test(testCommand)) {
|
|
118
|
+
warnings.push(
|
|
119
|
+
`Contract testCommand chains full coverage gate (coverage:check) on Size ${taskSize} patch task. ${TEST_COMMAND_COVERAGE_FIX_HINT}`,
|
|
120
|
+
);
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
const npmTestDashDashWarnings = collectNpmTestDashDashWarnings(parsed, { taskSize, mode });
|
|
124
|
+
if (npmTestDashDashWarnings.length > 0) {
|
|
125
|
+
warnings.push(...npmTestDashDashWarnings);
|
|
126
|
+
} else if (/\bnpm test\b/.test(testCommand)) {
|
|
127
|
+
warnings.push(
|
|
128
|
+
`Contract testCommand uses npm test on Size ${taskSize} patch task. ${TEST_COMMAND_NPM_TEST_FIX_HINT}`,
|
|
129
|
+
);
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
return warnings;
|
|
75
133
|
}
|
|
76
134
|
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
warnings.push(...npmTestDashDashWarnings);
|
|
80
|
-
} else if (/\bnpm test\b/.test(testCommand)) {
|
|
81
|
-
warnings.push(
|
|
82
|
-
`Contract testCommand uses npm test on Size ${taskSize} patch task. ${TEST_COMMAND_NPM_TEST_FIX_HINT}`,
|
|
83
|
-
);
|
|
135
|
+
if (taskSize === "L") {
|
|
136
|
+
warnings.push(...collectNpmTestDashDashWarnings(parsed, { taskSize, mode }));
|
|
84
137
|
}
|
|
85
138
|
|
|
86
139
|
return warnings;
|