pi-spine 1.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/LICENSE +21 -0
- package/README.md +563 -0
- package/bin/get-version.mjs +35 -0
- package/bin/spine-batch.mjs +425 -0
- package/bin/spine-cli/batch.mjs +47 -0
- package/bin/spine-cli/gate.mjs +10 -0
- package/bin/spine-cli/integrate.mjs +10 -0
- package/bin/spine-cli/plan.mjs +12 -0
- package/bin/spine-cli/shared.mjs +73 -0
- package/bin/spine-cli/status.mjs +18 -0
- package/bin/spine-cli/verify.mjs +199 -0
- package/bin/spine-config.mjs +212 -0
- package/bin/spine-dashboard.mjs +178 -0
- package/bin/spine-deps.mjs +69 -0
- package/bin/spine-doctor.mjs +468 -0
- package/bin/spine-gate.mjs +137 -0
- package/bin/spine-init.mjs +398 -0
- package/bin/spine-integrate.mjs +77 -0
- package/bin/spine-journal.mjs +198 -0
- package/bin/spine-migrate-from-taskplane.mjs +136 -0
- package/bin/spine-plan.mjs +83 -0
- package/bin/spine-preflight.mjs +700 -0
- package/bin/spine-report-progress.d.mts +28 -0
- package/bin/spine-report-progress.mjs +126 -0
- package/bin/spine-review-step.d.mts +24 -0
- package/bin/spine-review-step.mjs +124 -0
- package/bin/spine-rules.mjs +35 -0
- package/bin/spine-settings.mjs +186 -0
- package/bin/spine-state.mjs +110 -0
- package/bin/spine-status.mjs +79 -0
- package/bin/spine-tasks.mjs +293 -0
- package/bin/spine-worker-runner.mjs +314 -0
- package/bin/spine.mjs +404 -0
- package/extensions/spine/settings-slash.ts +20 -0
- package/extensions/spine/slash-commands.ts +806 -0
- package/extensions/spine/worker-tools.ts +279 -0
- package/extensions/spine-orchestrator.ts +12 -0
- package/package.json +72 -0
- package/skills/.gitkeep +0 -0
- package/skills/create-spine-tasks/SKILL.md +375 -0
- package/skills/create-spine-tasks/references/context-template.md +25 -0
- package/skills/create-spine-tasks/references/contract-template.md +98 -0
- package/skills/create-spine-tasks/references/explore-template.md +63 -0
- package/skills/create-spine-tasks/references/prompt-template.md +276 -0
- package/src/batch/abort.mjs +272 -0
- package/src/batch/agent-session-worker.mjs +297 -0
- package/src/batch/batch-state-io.mjs +53 -0
- package/src/batch/contract-verify.mjs +310 -0
- package/src/batch/detached-start.mjs +778 -0
- package/src/batch/diagnosis.mjs +378 -0
- package/src/batch/engine-lanes/merge.mjs +632 -0
- package/src/batch/engine-lanes/queue.mjs +208 -0
- package/src/batch/engine-lanes/review.mjs +970 -0
- package/src/batch/engine-lanes.mjs +388 -0
- package/src/batch/engine-scope.mjs +251 -0
- package/src/batch/engine.mjs +445 -0
- package/src/batch/evidence-command.mjs +157 -0
- package/src/batch/evidence.mjs +203 -0
- package/src/batch/gate.mjs +359 -0
- package/src/batch/git-commit-env.mjs +46 -0
- package/src/batch/git-exec.mjs +26 -0
- package/src/batch/heartbeat.mjs +430 -0
- package/src/batch/integrate.mjs +414 -0
- package/src/batch/journal-rebuild.mjs +388 -0
- package/src/batch/journal.mjs +373 -0
- package/src/batch/lane-commit.mjs +153 -0
- package/src/batch/lifecycle.mjs +364 -0
- package/src/batch/metrics.mjs +265 -0
- package/src/batch/orphan-detect.mjs +210 -0
- package/src/batch/post-merge-limbo.mjs +80 -0
- package/src/batch/postmortem.mjs +296 -0
- package/src/batch/readers/spine-state.mjs +95 -0
- package/src/batch/readers/taskplane-state.mjs +136 -0
- package/src/batch/reconcile.mjs +729 -0
- package/src/batch/resume-common.mjs +104 -0
- package/src/batch/resume-engine.mjs +66 -0
- package/src/batch/resume-multi-lanes.mjs +479 -0
- package/src/batch/resume-multi-validate.mjs +187 -0
- package/src/batch/resume-multi.mjs +254 -0
- package/src/batch/resume.mjs +475 -0
- package/src/batch/retry.mjs +257 -0
- package/src/batch/review-scope.mjs +136 -0
- package/src/batch/review.mjs +1045 -0
- package/src/batch/salvage.mjs +332 -0
- package/src/batch/state.mjs +680 -0
- package/src/batch/task-stall-budget.mjs +88 -0
- package/src/batch/worker-host.mjs +683 -0
- package/src/batch/worker-output.mjs +253 -0
- package/src/batch/worker-prompt.mjs +84 -0
- package/src/batch/worktree.mjs +290 -0
- package/src/cli/deps.mjs +141 -0
- package/src/cli/handoff.mjs +364 -0
- package/src/cli/rules.mjs +429 -0
- package/src/cli/settings-set.mjs +171 -0
- package/src/cli/settings-show.mjs +140 -0
- package/src/cli/settings-slash.mjs +107 -0
- package/src/config/contract.mjs +56 -0
- package/src/config/cursor-rules/discover.mjs +416 -0
- package/src/config/cursor-rules/index.mjs +39 -0
- package/src/config/cursor-rules/match-globs.mjs +132 -0
- package/src/config/cursor-rules/parse-frontmatter.mjs +222 -0
- package/src/config/cursor-rules/priority.mjs +26 -0
- package/src/config/cursor-rules/profile.mjs +403 -0
- package/src/config/cursor-rules/select.mjs +259 -0
- package/src/config/defaults.mjs +36 -0
- package/src/config/env-overrides.mjs +207 -0
- package/src/config/merge-defaults.mjs +47 -0
- package/src/config/pi-spine-root.mjs +93 -0
- package/src/config/reviewer-context.mjs +243 -0
- package/src/config/settings-fields.mjs +265 -0
- package/src/config/worker-backend.mjs +116 -0
- package/src/config/worker-context.mjs +402 -0
- package/src/config/worker-launch-script.mjs +130 -0
- package/src/config/worktree-setup-hook.mjs +122 -0
- package/src/dashboard/public/dashboard.css +77 -0
- package/src/dashboard/public/dashboard.js +349 -0
- package/src/dashboard/public/index.html +80 -0
- package/src/dashboard/server.mjs +155 -0
- package/src/dashboard/snapshot.mjs +414 -0
- package/src/dashboard/sse.mjs +15 -0
- package/src/dashboard/view.mjs +292 -0
- package/src/doctor/agent-model-inherit.mjs +101 -0
- package/src/doctor/batch-size-guidance.mjs +72 -0
- package/src/doctor/coexistence.mjs +312 -0
- package/src/doctor/rules-manifest.mjs +133 -0
- package/src/doctor/stale-path.mjs +156 -0
- package/src/doctor/stall-config.mjs +108 -0
- package/src/doctor/suggest-max-parallel.mjs +53 -0
- package/src/doctor/task-packet-size.mjs +110 -0
- package/src/doctor/worktree-health.mjs +71 -0
- package/src/migrate/taskplane-config.mjs +116 -0
- package/src/planner/cycles.mjs +63 -0
- package/src/planner/format-plan.mjs +132 -0
- package/src/planner/graph.mjs +99 -0
- package/src/planner/index.mjs +125 -0
- package/src/planner/lanes.mjs +111 -0
- package/src/planner/pending.mjs +39 -0
- package/src/planner/scope.mjs +142 -0
- package/src/process/liveness.mjs +21 -0
- package/src/tasks/packet/discover.mjs +40 -0
- package/src/tasks/packet/index.mjs +81 -0
- package/src/tasks/packet/merge-deps.mjs +79 -0
- package/src/tasks/packet/parse-prompt.mjs +445 -0
- package/src/tasks/packet/parse-status.mjs +118 -0
- package/src/tasks/packet/validate-contract.mjs +115 -0
- package/src/tasks/packet/validate-prompt.mjs +99 -0
- package/src/worker-tools/report-progress.d.mts +18 -0
- package/src/worker-tools/report-progress.mjs +59 -0
- package/src/worker-tools/request-gate.d.mts +17 -0
- package/src/worker-tools/request-gate.mjs +54 -0
- package/templates/agents/reviewer.md +123 -0
- package/templates/agents/supervisor.md +59 -0
- package/templates/agents/worker.md +122 -0
- package/templates/rules-profile.json +27 -0
- package/templates/spine-config.json +64 -0
- package/templates/tasks/CONTEXT.md +30 -0
|
@@ -0,0 +1,680 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* pi-spine batch-state.json read/write (schema v1, PRD §10.1).
|
|
3
|
+
*/
|
|
4
|
+
|
|
5
|
+
import fs from "node:fs";
|
|
6
|
+
import path from "node:path";
|
|
7
|
+
import { appendJournalEvent } from "./journal.mjs";
|
|
8
|
+
import { loadBatchStateFile } from "./batch-state-io.mjs";
|
|
9
|
+
import { isProcessAlive } from "../process/liveness.mjs";
|
|
10
|
+
|
|
11
|
+
export const SPINE_BATCH_STATE_REL = path.join(".spine", "batch-state.json");
|
|
12
|
+
|
|
13
|
+
/** @type {ReadonlySet<string>} */
|
|
14
|
+
export const ACTIVE_PHASES = new Set(["planning", "running", "paused"]);
|
|
15
|
+
|
|
16
|
+
/** @type {ReadonlySet<string>} */
|
|
17
|
+
export const TERMINAL_BATCH_PHASES = new Set(["completed", "failed", "aborted"]);
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* @returns {string} batchId `{YYYYMMDD}T{HHmmss}` UTC
|
|
21
|
+
*/
|
|
22
|
+
export function generateBatchId(now = new Date()) {
|
|
23
|
+
const y = now.getUTCFullYear();
|
|
24
|
+
const m = String(now.getUTCMonth() + 1).padStart(2, "0");
|
|
25
|
+
const d = String(now.getUTCDate()).padStart(2, "0");
|
|
26
|
+
const h = String(now.getUTCHours()).padStart(2, "0");
|
|
27
|
+
const min = String(now.getUTCMinutes()).padStart(2, "0");
|
|
28
|
+
const s = String(now.getUTCSeconds()).padStart(2, "0");
|
|
29
|
+
return `${y}${m}${d}T${h}${min}${s}`;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* @param {string} projectRoot
|
|
34
|
+
*/
|
|
35
|
+
export function spineBatchStatePath(projectRoot) {
|
|
36
|
+
return path.join(projectRoot, SPINE_BATCH_STATE_REL);
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* @param {string} projectRoot
|
|
41
|
+
*/
|
|
42
|
+
export function loadSpineBatchState(projectRoot) {
|
|
43
|
+
const filePath = spineBatchStatePath(projectRoot);
|
|
44
|
+
if (!fs.existsSync(filePath)) {
|
|
45
|
+
return { path: null, raw: null, parseError: null };
|
|
46
|
+
}
|
|
47
|
+
try {
|
|
48
|
+
const raw = JSON.parse(fs.readFileSync(filePath, "utf-8"));
|
|
49
|
+
return { path: filePath, raw, parseError: null };
|
|
50
|
+
} catch (err) {
|
|
51
|
+
return {
|
|
52
|
+
path: filePath,
|
|
53
|
+
raw: null,
|
|
54
|
+
parseError: err instanceof Error ? err.message : String(err),
|
|
55
|
+
};
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* @param {string} projectRoot
|
|
61
|
+
* @param {string} batchId
|
|
62
|
+
*/
|
|
63
|
+
function archivedBatchStatePath(projectRoot, batchId) {
|
|
64
|
+
return path.join(projectRoot, ".spine", "runtime", batchId, "archive", "batch-state.json");
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* Reject cache writes from non-owner engines or post-archive resurrection (SP-254).
|
|
69
|
+
*
|
|
70
|
+
* @param {string} projectRoot
|
|
71
|
+
* @param {object} state
|
|
72
|
+
* @returns {{ allowed: boolean, reason?: string }}
|
|
73
|
+
*/
|
|
74
|
+
export function evaluateBatchStateWriteGuard(projectRoot, state) {
|
|
75
|
+
const filePath = spineBatchStatePath(projectRoot);
|
|
76
|
+
const batchId = String(state.batchId ?? "");
|
|
77
|
+
const incomingPhase = String(state.phase ?? "");
|
|
78
|
+
|
|
79
|
+
if (fs.existsSync(filePath)) {
|
|
80
|
+
try {
|
|
81
|
+
const onDisk = JSON.parse(fs.readFileSync(filePath, "utf-8"));
|
|
82
|
+
const ownerPid = readBatchEnginePid(onDisk);
|
|
83
|
+
if (ownerPid && ownerPid !== process.pid && isProcessAlive(ownerPid)) {
|
|
84
|
+
return { allowed: false, reason: "stale_engine_pid" };
|
|
85
|
+
}
|
|
86
|
+
} catch {
|
|
87
|
+
/* corrupt on-disk state — allow overwrite */
|
|
88
|
+
}
|
|
89
|
+
} else if (batchId && ACTIVE_PHASES.has(incomingPhase)) {
|
|
90
|
+
if (fs.existsSync(archivedBatchStatePath(projectRoot, batchId))) {
|
|
91
|
+
return { allowed: false, reason: "archived_batch_resurrection" };
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
return { allowed: true };
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* @param {string} projectRoot
|
|
100
|
+
* @param {object} state
|
|
101
|
+
* @param {{ bypassWriteGuard?: boolean }} [options]
|
|
102
|
+
*/
|
|
103
|
+
export function saveSpineBatchState(projectRoot, state, options = {}) {
|
|
104
|
+
const guard = options.bypassWriteGuard
|
|
105
|
+
? { allowed: true }
|
|
106
|
+
: evaluateBatchStateWriteGuard(projectRoot, state);
|
|
107
|
+
if (!guard.allowed) {
|
|
108
|
+
const loaded = loadSpineBatchState(projectRoot);
|
|
109
|
+
return loaded.raw ?? state;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
const filePath = spineBatchStatePath(projectRoot);
|
|
113
|
+
fs.mkdirSync(path.dirname(filePath), { recursive: true });
|
|
114
|
+
if (TERMINAL_BATCH_PHASES.has(String(state.phase ?? ""))) {
|
|
115
|
+
clearBatchEnginePid(state);
|
|
116
|
+
}
|
|
117
|
+
const next = { ...state, updatedAt: Date.now() };
|
|
118
|
+
fs.writeFileSync(filePath, `${JSON.stringify(next, null, 2)}\n`, "utf-8");
|
|
119
|
+
return next;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/**
|
|
123
|
+
* @param {unknown} raw
|
|
124
|
+
* @returns {number|null}
|
|
125
|
+
*/
|
|
126
|
+
export function readBatchEnginePid(raw) {
|
|
127
|
+
if (!raw || typeof raw !== "object") return null;
|
|
128
|
+
/** @type {Record<string, unknown>} */
|
|
129
|
+
const state = /** @type {Record<string, unknown>} */ (raw);
|
|
130
|
+
const resilience =
|
|
131
|
+
state.resilience && typeof state.resilience === "object"
|
|
132
|
+
? /** @type {Record<string, unknown>} */ (state.resilience)
|
|
133
|
+
: null;
|
|
134
|
+
const fromResilience = Number(resilience?.enginePid);
|
|
135
|
+
if (Number.isFinite(fromResilience) && fromResilience > 0) return fromResilience;
|
|
136
|
+
const topLevel = Number(state.enginePid);
|
|
137
|
+
if (Number.isFinite(topLevel) && topLevel > 0) return topLevel;
|
|
138
|
+
return null;
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/**
|
|
142
|
+
* @param {object} state
|
|
143
|
+
* @param {number} enginePid
|
|
144
|
+
*/
|
|
145
|
+
export function recordBatchEnginePid(state, enginePid) {
|
|
146
|
+
const pid = Number(enginePid);
|
|
147
|
+
if (!Number.isFinite(pid) || pid <= 0) return;
|
|
148
|
+
state.resilience = state.resilience ?? {};
|
|
149
|
+
state.resilience.enginePid = pid;
|
|
150
|
+
state.resilience.engineStartedAt = Date.now();
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/**
|
|
154
|
+
* @param {object} state
|
|
155
|
+
*/
|
|
156
|
+
export function clearBatchEnginePid(state) {
|
|
157
|
+
if (!state?.resilience || typeof state.resilience !== "object") return;
|
|
158
|
+
delete state.resilience.enginePid;
|
|
159
|
+
delete state.resilience.engineStartedAt;
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/**
|
|
163
|
+
* Mark running tasks that lost their worker when the engine exits unexpectedly.
|
|
164
|
+
*
|
|
165
|
+
* @param {object} state
|
|
166
|
+
* @param {string} [exitReason]
|
|
167
|
+
*/
|
|
168
|
+
export function reconcileGhostRunningTasks(state, exitReason = "engine_crashed") {
|
|
169
|
+
const now = Date.now();
|
|
170
|
+
for (const task of state.tasks ?? []) {
|
|
171
|
+
if (!task || task.status !== "running") continue;
|
|
172
|
+
task.status = "failed";
|
|
173
|
+
task.endedAt = now;
|
|
174
|
+
task.exitReason = task.exitReason ?? exitReason;
|
|
175
|
+
updateSegmentForTask(state, task.taskId, "failed");
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
for (const lane of state.lanes ?? []) {
|
|
179
|
+
if (!lane || typeof lane !== "object") continue;
|
|
180
|
+
delete lane.workerPid;
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
const tasks = state.tasks ?? [];
|
|
184
|
+
state.succeededTasks = tasks.filter((task) => task?.status === "succeeded").length;
|
|
185
|
+
state.failedTasks = tasks.filter((task) => task?.status === "failed").length;
|
|
186
|
+
state.skippedTasks = tasks.filter((task) => task?.status === "skipped").length;
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
/**
|
|
190
|
+
* Fail closed when the detached resume engine throws: terminal journal, phase, ghost cleanup.
|
|
191
|
+
*
|
|
192
|
+
* @param {object} params
|
|
193
|
+
* @param {string} params.projectRoot
|
|
194
|
+
* @param {object} params.state
|
|
195
|
+
* @param {string} params.batchId
|
|
196
|
+
* @param {unknown} params.error
|
|
197
|
+
* @param {string|null} [params.taskId]
|
|
198
|
+
* @param {number|null} [params.laneNumber]
|
|
199
|
+
*/
|
|
200
|
+
export function failBatchFromEngineError({
|
|
201
|
+
projectRoot,
|
|
202
|
+
state,
|
|
203
|
+
batchId,
|
|
204
|
+
error,
|
|
205
|
+
taskId = null,
|
|
206
|
+
laneNumber = null,
|
|
207
|
+
}) {
|
|
208
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
209
|
+
const fromPhase = String(state.phase ?? "running");
|
|
210
|
+
|
|
211
|
+
reconcileGhostRunningTasks(state);
|
|
212
|
+
state.endedAt = Date.now();
|
|
213
|
+
state.lastError = message.slice(0, 500);
|
|
214
|
+
state.phase = "failed";
|
|
215
|
+
|
|
216
|
+
appendJournalEvent(projectRoot, batchId, "batch.failed", {
|
|
217
|
+
fromPhase,
|
|
218
|
+
toPhase: "failed",
|
|
219
|
+
reason: "engine_error",
|
|
220
|
+
error: message,
|
|
221
|
+
taskId,
|
|
222
|
+
laneNumber,
|
|
223
|
+
});
|
|
224
|
+
|
|
225
|
+
saveSpineBatchState(projectRoot, state);
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
/**
|
|
229
|
+
* @param {string} projectRoot
|
|
230
|
+
*/
|
|
231
|
+
export function assertNoActiveBatch(projectRoot) {
|
|
232
|
+
const spine = loadSpineBatchState(projectRoot);
|
|
233
|
+
if (spine.path && spine.raw) {
|
|
234
|
+
const phase = String(spine.raw.phase ?? "");
|
|
235
|
+
if (ACTIVE_PHASES.has(phase)) {
|
|
236
|
+
throw new Error(
|
|
237
|
+
`Active pi-spine batch ${spine.raw.batchId} (phase=${phase}). Run spine batch dismiss or complete first.`,
|
|
238
|
+
);
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
const any = loadBatchStateFile(projectRoot);
|
|
243
|
+
if (any.path && any.raw) {
|
|
244
|
+
const phase = String(any.raw.phase ?? "");
|
|
245
|
+
const active =
|
|
246
|
+
ACTIVE_PHASES.has(phase) || phase === "executing" || phase === "merging" || phase === "stopped";
|
|
247
|
+
if (active && !any.raw.endedAt) {
|
|
248
|
+
throw new Error(
|
|
249
|
+
`Active batch ${any.raw.batchId} at ${any.path} (phase=${phase}). Dismiss or abort before spine batch start.`,
|
|
250
|
+
);
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
/**
|
|
256
|
+
* @param {object} params
|
|
257
|
+
*/
|
|
258
|
+
export const BATCH_HISTORY_REL = path.join(".spine", "batch-history.json");
|
|
259
|
+
|
|
260
|
+
/**
|
|
261
|
+
* @param {string} projectRoot
|
|
262
|
+
*/
|
|
263
|
+
export function batchHistoryPath(projectRoot) {
|
|
264
|
+
return path.join(projectRoot, BATCH_HISTORY_REL);
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
/**
|
|
268
|
+
* @param {unknown} state
|
|
269
|
+
* @returns {{ ok: true } | { ok: false, errors: string[], suggestedCommand: string }}
|
|
270
|
+
*/
|
|
271
|
+
export function validateBatchState(state) {
|
|
272
|
+
/** @type {string[]} */
|
|
273
|
+
const errors = [];
|
|
274
|
+
|
|
275
|
+
if (!state || typeof state !== "object" || Array.isArray(state)) {
|
|
276
|
+
return {
|
|
277
|
+
ok: false,
|
|
278
|
+
errors: ["batch state must be a JSON object"],
|
|
279
|
+
suggestedCommand: "spine state validate --diagnose",
|
|
280
|
+
};
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
/** @type {Record<string, unknown>} */
|
|
284
|
+
const raw = /** @type {Record<string, unknown>} */ (state);
|
|
285
|
+
|
|
286
|
+
if (raw.schemaVersion !== 1) {
|
|
287
|
+
errors.push(`schemaVersion must be 1 (found ${String(raw.schemaVersion)})`);
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
const batchId = String(raw.batchId ?? "").trim();
|
|
291
|
+
if (!batchId) errors.push("batchId is required");
|
|
292
|
+
|
|
293
|
+
const phase = String(raw.phase ?? "").trim();
|
|
294
|
+
const validPhases = new Set(["planning", "running", "paused", "completed", "failed", "aborted"]);
|
|
295
|
+
if (!validPhases.has(phase)) {
|
|
296
|
+
errors.push(`phase must be one of ${[...validPhases].join(", ")} (found ${phase || "missing"})`);
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
for (const field of ["baseBranch", "orchBranch", "startedAt", "updatedAt", "totalTasks"]) {
|
|
300
|
+
if (raw[field] == null || raw[field] === "") {
|
|
301
|
+
errors.push(`${field} is required`);
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
if (!Array.isArray(raw.wavePlan)) errors.push("wavePlan must be an array");
|
|
306
|
+
if (!Array.isArray(raw.tasks)) errors.push("tasks must be an array");
|
|
307
|
+
if (!Array.isArray(raw.lanes)) errors.push("lanes must be an array");
|
|
308
|
+
if (!Array.isArray(raw.mergeResults)) errors.push("mergeResults must be an array");
|
|
309
|
+
if (!Array.isArray(raw.segments)) errors.push("segments must be an array");
|
|
310
|
+
|
|
311
|
+
const totalTasks = Number(raw.totalTasks ?? 0);
|
|
312
|
+
const succeededTasks = Number(raw.succeededTasks ?? 0);
|
|
313
|
+
const failedTasks = Number(raw.failedTasks ?? 0);
|
|
314
|
+
const skippedTasks = Number(raw.skippedTasks ?? 0);
|
|
315
|
+
const blockedTasks = Number(raw.blockedTasks ?? 0);
|
|
316
|
+
const taskCount = Array.isArray(raw.tasks) ? raw.tasks.length : 0;
|
|
317
|
+
|
|
318
|
+
if (taskCount !== totalTasks) {
|
|
319
|
+
errors.push(`tasks.length (${taskCount}) must match totalTasks (${totalTasks})`);
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
const terminalSum = succeededTasks + failedTasks + skippedTasks + blockedTasks;
|
|
323
|
+
if (terminalSum > totalTasks) {
|
|
324
|
+
errors.push(
|
|
325
|
+
`succeeded+failed+skipped+blocked (${terminalSum}) exceeds totalTasks (${totalTasks})`,
|
|
326
|
+
);
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
const lanes = Array.isArray(raw.lanes) ? raw.lanes : [];
|
|
330
|
+
const laneNumbers = new Set(
|
|
331
|
+
lanes.map((lane) =>
|
|
332
|
+
lane && typeof lane === "object" ? Number(/** @type {{ laneNumber?: number }} */ (lane).laneNumber) : NaN,
|
|
333
|
+
),
|
|
334
|
+
);
|
|
335
|
+
|
|
336
|
+
for (const task of Array.isArray(raw.tasks) ? raw.tasks : []) {
|
|
337
|
+
if (!task || typeof task !== "object") continue;
|
|
338
|
+
const taskId = String(/** @type {{ taskId?: string }} */ (task).taskId ?? "").trim();
|
|
339
|
+
if (!taskId) errors.push("each task must have taskId");
|
|
340
|
+
|
|
341
|
+
const laneNumber = Number(/** @type {{ laneNumber?: number }} */ (task).laneNumber);
|
|
342
|
+
if (!Number.isNaN(laneNumber) && laneNumbers.size > 0 && !laneNumbers.has(laneNumber)) {
|
|
343
|
+
errors.push(`task ${taskId} references missing lane ${laneNumber}`);
|
|
344
|
+
}
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
for (const lane of lanes) {
|
|
348
|
+
if (!lane || typeof lane !== "object") continue;
|
|
349
|
+
const laneNumber = Number(/** @type {{ laneNumber?: number }} */ (lane).laneNumber);
|
|
350
|
+
const taskIds = Array.isArray(/** @type {{ taskIds?: string[] }} */ (lane).taskIds)
|
|
351
|
+
? /** @type {{ taskIds?: string[] }} */ (lane).taskIds
|
|
352
|
+
: [];
|
|
353
|
+
for (const taskId of taskIds) {
|
|
354
|
+
const found = (raw.tasks ?? []).some(
|
|
355
|
+
(task) =>
|
|
356
|
+
task &&
|
|
357
|
+
typeof task === "object" &&
|
|
358
|
+
String(/** @type {{ taskId?: string }} */ (task).taskId) === taskId &&
|
|
359
|
+
Number(/** @type {{ laneNumber?: number }} */ (task).laneNumber) === laneNumber,
|
|
360
|
+
);
|
|
361
|
+
if (!found) {
|
|
362
|
+
errors.push(`lane ${laneNumber} lists task ${taskId} not assigned to that lane`);
|
|
363
|
+
}
|
|
364
|
+
}
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
const segments = Array.isArray(raw.segments) ? raw.segments : [];
|
|
368
|
+
const taskIds = new Set(
|
|
369
|
+
(Array.isArray(raw.tasks) ? raw.tasks : [])
|
|
370
|
+
.map((task) =>
|
|
371
|
+
task && typeof task === "object"
|
|
372
|
+
? String(/** @type {{ taskId?: string }} */ (task).taskId ?? "").trim()
|
|
373
|
+
: "",
|
|
374
|
+
)
|
|
375
|
+
.filter(Boolean),
|
|
376
|
+
);
|
|
377
|
+
const segmentIds = new Set();
|
|
378
|
+
|
|
379
|
+
for (const segment of segments) {
|
|
380
|
+
if (!segment || typeof segment !== "object") {
|
|
381
|
+
errors.push("each segment must be an object");
|
|
382
|
+
continue;
|
|
383
|
+
}
|
|
384
|
+
const segmentId = String(/** @type {{ segmentId?: string }} */ (segment).segmentId ?? "").trim();
|
|
385
|
+
const taskId = String(/** @type {{ taskId?: string }} */ (segment).taskId ?? "").trim();
|
|
386
|
+
const status = String(/** @type {{ status?: string }} */ (segment).status ?? "").trim();
|
|
387
|
+
|
|
388
|
+
if (!segmentId) errors.push("each segment must have segmentId");
|
|
389
|
+
if (!taskId) errors.push("each segment must have taskId");
|
|
390
|
+
if (!status) errors.push(`segment ${segmentId || "(missing)"} must have status`);
|
|
391
|
+
if (segmentId && segmentIds.has(segmentId)) {
|
|
392
|
+
errors.push(`duplicate segmentId ${segmentId}`);
|
|
393
|
+
}
|
|
394
|
+
if (segmentId) segmentIds.add(segmentId);
|
|
395
|
+
if (taskId && !taskIds.has(taskId)) {
|
|
396
|
+
errors.push(`segment ${segmentId || taskId} references unknown task ${taskId}`);
|
|
397
|
+
}
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
for (const taskId of taskIds) {
|
|
401
|
+
const hasSegment = segments.some(
|
|
402
|
+
(segment) =>
|
|
403
|
+
segment &&
|
|
404
|
+
typeof segment === "object" &&
|
|
405
|
+
String(/** @type {{ taskId?: string }} */ (segment).taskId) === taskId,
|
|
406
|
+
);
|
|
407
|
+
if (!hasSegment) {
|
|
408
|
+
errors.push(`task ${taskId} has no matching segment record`);
|
|
409
|
+
}
|
|
410
|
+
}
|
|
411
|
+
|
|
412
|
+
if (errors.length > 0) {
|
|
413
|
+
return {
|
|
414
|
+
ok: false,
|
|
415
|
+
errors,
|
|
416
|
+
suggestedCommand: "spine state validate --diagnose",
|
|
417
|
+
};
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
return { ok: true };
|
|
421
|
+
}
|
|
422
|
+
|
|
423
|
+
/**
|
|
424
|
+
* @param {string} projectRoot
|
|
425
|
+
* @param {string|null} [batchId]
|
|
426
|
+
*/
|
|
427
|
+
export function resolveBatchStateFileForValidation(projectRoot, batchId = null) {
|
|
428
|
+
if (batchId) {
|
|
429
|
+
const archived = path.join(
|
|
430
|
+
projectRoot,
|
|
431
|
+
".spine",
|
|
432
|
+
"runtime",
|
|
433
|
+
batchId,
|
|
434
|
+
"archive",
|
|
435
|
+
"batch-state.json",
|
|
436
|
+
);
|
|
437
|
+
if (fs.existsSync(archived)) {
|
|
438
|
+
return { path: archived, source: "archive" };
|
|
439
|
+
}
|
|
440
|
+
}
|
|
441
|
+
|
|
442
|
+
const active = spineBatchStatePath(projectRoot);
|
|
443
|
+
if (fs.existsSync(active)) {
|
|
444
|
+
const loaded = loadSpineBatchState(projectRoot);
|
|
445
|
+
if (batchId && loaded.raw && String(loaded.raw.batchId) !== batchId) {
|
|
446
|
+
return { path: null, source: null, error: `Active batch is ${loaded.raw.batchId}, not ${batchId}` };
|
|
447
|
+
}
|
|
448
|
+
return { path: active, source: "active" };
|
|
449
|
+
}
|
|
450
|
+
|
|
451
|
+
if (batchId) {
|
|
452
|
+
return { path: null, source: null, error: `No batch-state found for batch ${batchId}` };
|
|
453
|
+
}
|
|
454
|
+
|
|
455
|
+
return { path: null, source: null, error: "No active batch-state.json" };
|
|
456
|
+
}
|
|
457
|
+
|
|
458
|
+
/**
|
|
459
|
+
* @param {string} projectRoot
|
|
460
|
+
* @param {object} entry
|
|
461
|
+
*/
|
|
462
|
+
export function appendBatchHistoryEntry(projectRoot, entry) {
|
|
463
|
+
const filePath = batchHistoryPath(projectRoot);
|
|
464
|
+
fs.mkdirSync(path.dirname(filePath), { recursive: true });
|
|
465
|
+
|
|
466
|
+
/** @type {object[]} */
|
|
467
|
+
let history = [];
|
|
468
|
+
if (fs.existsSync(filePath)) {
|
|
469
|
+
try {
|
|
470
|
+
const parsed = JSON.parse(fs.readFileSync(filePath, "utf-8"));
|
|
471
|
+
if (Array.isArray(parsed)) history = parsed;
|
|
472
|
+
} catch {
|
|
473
|
+
history = [];
|
|
474
|
+
}
|
|
475
|
+
}
|
|
476
|
+
|
|
477
|
+
history.push(entry);
|
|
478
|
+
fs.writeFileSync(filePath, `${JSON.stringify(history, null, 2)}\n`, "utf-8");
|
|
479
|
+
return filePath;
|
|
480
|
+
}
|
|
481
|
+
|
|
482
|
+
/**
|
|
483
|
+
* @param {string} taskId
|
|
484
|
+
*/
|
|
485
|
+
export function defaultSegmentId(taskId) {
|
|
486
|
+
return `${taskId}::default`;
|
|
487
|
+
}
|
|
488
|
+
|
|
489
|
+
/**
|
|
490
|
+
* @param {Array<{ taskId: string }>} tasks
|
|
491
|
+
*/
|
|
492
|
+
export function buildSegmentsFromTasks(tasks) {
|
|
493
|
+
return tasks.map((task) => ({
|
|
494
|
+
segmentId: defaultSegmentId(task.taskId),
|
|
495
|
+
taskId: task.taskId,
|
|
496
|
+
status: "pending",
|
|
497
|
+
repoId: "default",
|
|
498
|
+
}));
|
|
499
|
+
}
|
|
500
|
+
|
|
501
|
+
/**
|
|
502
|
+
* @param {object} state
|
|
503
|
+
* @param {string} taskId
|
|
504
|
+
* @param {string} status
|
|
505
|
+
*/
|
|
506
|
+
export function updateSegmentForTask(state, taskId, status) {
|
|
507
|
+
if (!Array.isArray(state.segments)) return;
|
|
508
|
+
for (const segment of state.segments) {
|
|
509
|
+
if (segment && typeof segment === "object" && segment.taskId === taskId) {
|
|
510
|
+
segment.status = status;
|
|
511
|
+
}
|
|
512
|
+
}
|
|
513
|
+
}
|
|
514
|
+
|
|
515
|
+
/**
|
|
516
|
+
* @param {object} task
|
|
517
|
+
*/
|
|
518
|
+
export function clearTaskFailureMetadata(task) {
|
|
519
|
+
if (!task || typeof task !== "object") return;
|
|
520
|
+
task.exitReason = null;
|
|
521
|
+
if ("classification" in task) delete task.classification;
|
|
522
|
+
}
|
|
523
|
+
|
|
524
|
+
/**
|
|
525
|
+
* @param {object} state
|
|
526
|
+
*/
|
|
527
|
+
export function recomputeTaskCounters(state) {
|
|
528
|
+
const tasks = state.tasks ?? [];
|
|
529
|
+
state.succeededTasks = tasks.filter((task) => task?.status === "succeeded").length;
|
|
530
|
+
state.failedTasks = tasks.filter((task) => task?.status === "failed").length;
|
|
531
|
+
state.skippedTasks = tasks.filter((task) => task?.status === "skipped").length;
|
|
532
|
+
}
|
|
533
|
+
|
|
534
|
+
/**
|
|
535
|
+
* @param {object} state
|
|
536
|
+
* @param {string} taskId
|
|
537
|
+
* @returns {{ previousClassification: string, wasFailed: boolean } | null}
|
|
538
|
+
*/
|
|
539
|
+
export function resetTaskForRetry(state, taskId) {
|
|
540
|
+
const task = (state.tasks ?? []).find(
|
|
541
|
+
(entry) => entry && typeof entry === "object" && entry.taskId === taskId,
|
|
542
|
+
);
|
|
543
|
+
if (!task) return null;
|
|
544
|
+
|
|
545
|
+
const previousClassification = String(task.status ?? "unknown");
|
|
546
|
+
const wasFailed = task.status === "failed";
|
|
547
|
+
|
|
548
|
+
clearTaskFailureMetadata(task);
|
|
549
|
+
task.status = "pending";
|
|
550
|
+
task.startedAt = null;
|
|
551
|
+
task.endedAt = null;
|
|
552
|
+
task.doneFileFound = false;
|
|
553
|
+
|
|
554
|
+
for (const segment of state.segments ?? []) {
|
|
555
|
+
if (!segment || segment.taskId !== taskId) continue;
|
|
556
|
+
segment.status = "pending";
|
|
557
|
+
if ("startedAt" in segment) segment.startedAt = null;
|
|
558
|
+
if ("endedAt" in segment) segment.endedAt = null;
|
|
559
|
+
if ("exitReason" in segment) segment.exitReason = null;
|
|
560
|
+
if ("classification" in segment) delete segment.classification;
|
|
561
|
+
}
|
|
562
|
+
|
|
563
|
+
state.blockedTaskIds = (state.blockedTaskIds ?? []).filter((id) => id !== taskId);
|
|
564
|
+
recomputeTaskCounters(state);
|
|
565
|
+
|
|
566
|
+
return { previousClassification, wasFailed };
|
|
567
|
+
}
|
|
568
|
+
|
|
569
|
+
/**
|
|
570
|
+
* @param {object} state
|
|
571
|
+
* @param {string} taskId
|
|
572
|
+
* @param {object} [options]
|
|
573
|
+
* @param {string} [options.exitReason]
|
|
574
|
+
* @param {boolean} [options.doneFileFound]
|
|
575
|
+
* @param {number|null} [options.endedAt]
|
|
576
|
+
* @param {number|null} [options.startedAt]
|
|
577
|
+
* @returns {boolean}
|
|
578
|
+
*/
|
|
579
|
+
export function recordTaskSucceeded(state, taskId, options = {}) {
|
|
580
|
+
const task = (state.tasks ?? []).find(
|
|
581
|
+
(entry) => entry && typeof entry === "object" && entry.taskId === taskId,
|
|
582
|
+
);
|
|
583
|
+
if (!task) return false;
|
|
584
|
+
|
|
585
|
+
const exitReason = options.exitReason ?? "done";
|
|
586
|
+
const doneFileFound = options.doneFileFound ?? true;
|
|
587
|
+
const endedAt = options.endedAt ?? Date.now();
|
|
588
|
+
const startedAt = options.startedAt ?? null;
|
|
589
|
+
|
|
590
|
+
if ("classification" in task) delete task.classification;
|
|
591
|
+
task.status = "succeeded";
|
|
592
|
+
task.endedAt = endedAt;
|
|
593
|
+
task.doneFileFound = doneFileFound;
|
|
594
|
+
task.exitReason = exitReason;
|
|
595
|
+
if (startedAt != null && !task.startedAt) task.startedAt = startedAt;
|
|
596
|
+
|
|
597
|
+
updateSegmentForTask(state, taskId, "succeeded");
|
|
598
|
+
recomputeTaskCounters(state);
|
|
599
|
+
return true;
|
|
600
|
+
}
|
|
601
|
+
|
|
602
|
+
/**
|
|
603
|
+
* Single write path: persist batch-state then append matching journal event (FR-REL-04).
|
|
604
|
+
*
|
|
605
|
+
* @param {object} params
|
|
606
|
+
* @param {string} params.projectRoot
|
|
607
|
+
* @param {object} params.state
|
|
608
|
+
* @param {string} params.journalType
|
|
609
|
+
* @param {Record<string, unknown>} [params.journalPayload]
|
|
610
|
+
*/
|
|
611
|
+
export function recordTaskTransition({
|
|
612
|
+
projectRoot,
|
|
613
|
+
state,
|
|
614
|
+
journalType,
|
|
615
|
+
journalPayload = {},
|
|
616
|
+
}) {
|
|
617
|
+
const batchId = String(state.batchId ?? "");
|
|
618
|
+
saveSpineBatchState(projectRoot, state);
|
|
619
|
+
if (!batchId) return state;
|
|
620
|
+
appendJournalEvent(projectRoot, batchId, journalType, journalPayload);
|
|
621
|
+
return state;
|
|
622
|
+
}
|
|
623
|
+
|
|
624
|
+
/**
|
|
625
|
+
* @param {object} state
|
|
626
|
+
* @param {string} [taskId]
|
|
627
|
+
*/
|
|
628
|
+
export function countPendingSegments(state, taskId = null) {
|
|
629
|
+
const segments = Array.isArray(state.segments) ? state.segments : [];
|
|
630
|
+
return segments.filter((segment) => {
|
|
631
|
+
if (!segment || typeof segment !== "object") return false;
|
|
632
|
+
if (taskId && segment.taskId !== taskId) return false;
|
|
633
|
+
const status = String(segment.status ?? "pending").toLowerCase();
|
|
634
|
+
return status === "pending" || status === "running";
|
|
635
|
+
}).length;
|
|
636
|
+
}
|
|
637
|
+
|
|
638
|
+
/**
|
|
639
|
+
* @param {object} params
|
|
640
|
+
*/
|
|
641
|
+
export function createInitialBatchState({
|
|
642
|
+
batchId,
|
|
643
|
+
baseBranch,
|
|
644
|
+
orchBranch,
|
|
645
|
+
wavePlan,
|
|
646
|
+
tasks,
|
|
647
|
+
lanes,
|
|
648
|
+
}) {
|
|
649
|
+
const now = Date.now();
|
|
650
|
+
return {
|
|
651
|
+
schemaVersion: 1,
|
|
652
|
+
phase: "planning",
|
|
653
|
+
batchId,
|
|
654
|
+
baseBranch,
|
|
655
|
+
orchBranch,
|
|
656
|
+
startedAt: now,
|
|
657
|
+
updatedAt: now,
|
|
658
|
+
endedAt: null,
|
|
659
|
+
currentWaveIndex: 0,
|
|
660
|
+
totalWaves: wavePlan.length,
|
|
661
|
+
wavePlan,
|
|
662
|
+
lanes: lanes.map((lane) => ({ ...lane, lastHeartbeatAt: lane.lastHeartbeatAt ?? null })),
|
|
663
|
+
tasks,
|
|
664
|
+
segments: buildSegmentsFromTasks(tasks),
|
|
665
|
+
mergeResults: [],
|
|
666
|
+
totalTasks: tasks.length,
|
|
667
|
+
succeededTasks: 0,
|
|
668
|
+
failedTasks: 0,
|
|
669
|
+
skippedTasks: 0,
|
|
670
|
+
blockedTasks: 0,
|
|
671
|
+
blockedTaskIds: [],
|
|
672
|
+
lastError: null,
|
|
673
|
+
resilience: {
|
|
674
|
+
resumeForced: false,
|
|
675
|
+
retryCountByScope: {},
|
|
676
|
+
lastFailureClass: null,
|
|
677
|
+
repairHistory: [],
|
|
678
|
+
},
|
|
679
|
+
};
|
|
680
|
+
}
|