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,297 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* In-process lane worker via pi-coding-agent createAgentSession (TP-050 spike).
|
|
3
|
+
*/
|
|
4
|
+
|
|
5
|
+
import fs from "node:fs";
|
|
6
|
+
import path from "node:path";
|
|
7
|
+
import { appendJournalEvent } from "./journal.mjs";
|
|
8
|
+
import { resolvePiSpineRoot } from "../config/pi-spine-root.mjs";
|
|
9
|
+
import { readReviewLevel } from "./review.mjs";
|
|
10
|
+
import { buildWorkerTailPrompt } from "./worker-prompt.mjs";
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* @param {object} params
|
|
14
|
+
* @param {string} params.worktreePath
|
|
15
|
+
* @param {string} params.taskFolder
|
|
16
|
+
* @param {object} [params.config]
|
|
17
|
+
* @param {string[]} [params.taskFileScope]
|
|
18
|
+
* @param {import("../config/worker-context.mjs").WorkerRulesJournalContext} [params.journal]
|
|
19
|
+
*/
|
|
20
|
+
export async function buildAgentSessionWorkerPrompt({
|
|
21
|
+
worktreePath,
|
|
22
|
+
taskFolder,
|
|
23
|
+
config = {},
|
|
24
|
+
taskFileScope = [],
|
|
25
|
+
journal,
|
|
26
|
+
}) {
|
|
27
|
+
const donePath = path.join(taskFolder, ".DONE");
|
|
28
|
+
return buildWorkerTailPrompt({
|
|
29
|
+
worktreePath,
|
|
30
|
+
taskFolder,
|
|
31
|
+
donePath,
|
|
32
|
+
reviewLevel: readReviewLevel(taskFolder),
|
|
33
|
+
includePromptInclude: true,
|
|
34
|
+
config,
|
|
35
|
+
projectRoot: worktreePath || process.cwd(),
|
|
36
|
+
taskFileScope,
|
|
37
|
+
journal,
|
|
38
|
+
});
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* @param {object} params
|
|
43
|
+
* @param {string} params.worktreePath
|
|
44
|
+
* @param {string} params.taskFolder
|
|
45
|
+
* @param {boolean} [params.fail]
|
|
46
|
+
*/
|
|
47
|
+
export function createStubAgentSession({ worktreePath, taskFolder, fail = false }) {
|
|
48
|
+
const donePath = path.join(taskFolder, ".DONE");
|
|
49
|
+
let streaming = false;
|
|
50
|
+
let aborted = false;
|
|
51
|
+
|
|
52
|
+
return {
|
|
53
|
+
get isStreaming() {
|
|
54
|
+
return streaming;
|
|
55
|
+
},
|
|
56
|
+
abort: async () => {
|
|
57
|
+
aborted = true;
|
|
58
|
+
streaming = false;
|
|
59
|
+
},
|
|
60
|
+
dispose: () => {},
|
|
61
|
+
prompt: async () => {
|
|
62
|
+
if (fail) {
|
|
63
|
+
throw new Error("stub agent session failed");
|
|
64
|
+
}
|
|
65
|
+
streaming = true;
|
|
66
|
+
if (aborted) {
|
|
67
|
+
streaming = false;
|
|
68
|
+
return;
|
|
69
|
+
}
|
|
70
|
+
if (process.env.SPINE_AGENT_SESSION_STUB_TOUCH === "1" && worktreePath) {
|
|
71
|
+
fs.writeFileSync(
|
|
72
|
+
path.join(worktreePath, "agent-session-stub-touch.txt"),
|
|
73
|
+
`agent session stub ${new Date().toISOString()}\n`,
|
|
74
|
+
"utf-8",
|
|
75
|
+
);
|
|
76
|
+
}
|
|
77
|
+
fs.writeFileSync(
|
|
78
|
+
donePath,
|
|
79
|
+
`Completed: ${new Date().toISOString()}\nTask: agent-session-stub\n`,
|
|
80
|
+
"utf-8",
|
|
81
|
+
);
|
|
82
|
+
streaming = false;
|
|
83
|
+
},
|
|
84
|
+
subscribe: () => () => {},
|
|
85
|
+
};
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* @param {object} [deps]
|
|
90
|
+
*/
|
|
91
|
+
async function loadCreateAgentSession(deps = {}) {
|
|
92
|
+
if (deps.createAgentSession) {
|
|
93
|
+
return deps.createAgentSession;
|
|
94
|
+
}
|
|
95
|
+
if (
|
|
96
|
+
process.env.SPINE_AGENT_SESSION_STUB === "1" ||
|
|
97
|
+
process.env.SPINE_WORKER_STUB === "1" ||
|
|
98
|
+
process.env.SPINE_WORKER_STUB === "true"
|
|
99
|
+
) {
|
|
100
|
+
return async (options = {}) => ({
|
|
101
|
+
session: createStubAgentSession({
|
|
102
|
+
worktreePath: options.cwd ?? process.cwd(),
|
|
103
|
+
taskFolder: process.env.SPINE_TASK_FOLDER ?? options.cwd ?? process.cwd(),
|
|
104
|
+
fail: process.env.SPINE_AGENT_SESSION_STUB_FAIL === "1",
|
|
105
|
+
}),
|
|
106
|
+
});
|
|
107
|
+
}
|
|
108
|
+
const pi = await import("@earendil-works/pi-coding-agent");
|
|
109
|
+
return pi.createAgentSession;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/**
|
|
113
|
+
* @param {{ transcript: string }} state
|
|
114
|
+
* @param {string} message
|
|
115
|
+
*/
|
|
116
|
+
function appendAgentSessionOutput(state, message) {
|
|
117
|
+
const parts = [];
|
|
118
|
+
if (state.transcript.trim()) parts.push(state.transcript.trim());
|
|
119
|
+
if (message) parts.push(message);
|
|
120
|
+
return parts.join("\n\n");
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/**
|
|
124
|
+
* @param {unknown} event
|
|
125
|
+
*/
|
|
126
|
+
function formatAgentSessionEvent(event) {
|
|
127
|
+
if (!event || typeof event !== "object") return "";
|
|
128
|
+
const record = /** @type {Record<string, unknown>} */ (event);
|
|
129
|
+
if (typeof record.text === "string" && record.text) {
|
|
130
|
+
return `${record.text}\n`;
|
|
131
|
+
}
|
|
132
|
+
if (typeof record.content === "string" && record.content) {
|
|
133
|
+
return `${record.content}\n`;
|
|
134
|
+
}
|
|
135
|
+
if (typeof record.delta === "string" && record.delta) {
|
|
136
|
+
return record.delta;
|
|
137
|
+
}
|
|
138
|
+
if (record.message && typeof record.message === "object") {
|
|
139
|
+
const message = /** @type {Record<string, unknown>} */ (record.message);
|
|
140
|
+
if (typeof message.content === "string" && message.content) {
|
|
141
|
+
return `${message.content}\n`;
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
return "";
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
/**
|
|
148
|
+
* @param {object} config
|
|
149
|
+
*/
|
|
150
|
+
function resolveThinkingLevel(config) {
|
|
151
|
+
const level = config.agents?.worker?.thinking;
|
|
152
|
+
if (level === "off" || level === "low" || level === "medium" || level === "high") {
|
|
153
|
+
return level;
|
|
154
|
+
}
|
|
155
|
+
return "high";
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/**
|
|
159
|
+
* Start an in-process agent session worker compatible with worker-host polling.
|
|
160
|
+
*
|
|
161
|
+
* @param {object} params
|
|
162
|
+
* @param {string} params.worktreePath
|
|
163
|
+
* @param {string} params.taskFolder
|
|
164
|
+
* @param {object} [params.config]
|
|
165
|
+
* @param {string[]} [params.taskFileScope]
|
|
166
|
+
* @param {import("../config/worker-context.mjs").WorkerRulesJournalContext} [params.journal]
|
|
167
|
+
* @param {object} [deps]
|
|
168
|
+
*/
|
|
169
|
+
export function startAgentSessionWorker(
|
|
170
|
+
{ worktreePath, taskFolder, config = {}, taskFileScope = [], journal, projectRoot },
|
|
171
|
+
deps = {},
|
|
172
|
+
) {
|
|
173
|
+
const donePath = path.join(taskFolder, ".DONE");
|
|
174
|
+
const state = {
|
|
175
|
+
exitCode: /** @type {number | null} */ (null),
|
|
176
|
+
output: "",
|
|
177
|
+
transcript: "",
|
|
178
|
+
session: /** @type {{ abort?: () => Promise<void>; dispose?: () => void; subscribe?: (fn: (event: unknown) => void) => () => void } | null} */ (
|
|
179
|
+
null
|
|
180
|
+
),
|
|
181
|
+
aborted: false,
|
|
182
|
+
};
|
|
183
|
+
|
|
184
|
+
const piSpineRoot = resolvePiSpineRoot(config, projectRoot ?? process.cwd());
|
|
185
|
+
process.env.PI_SPINE_ROOT = piSpineRoot;
|
|
186
|
+
|
|
187
|
+
const donePromise = (async () => {
|
|
188
|
+
try {
|
|
189
|
+
const createAgentSession = await loadCreateAgentSession(deps);
|
|
190
|
+
const promptText = await buildAgentSessionWorkerPrompt({
|
|
191
|
+
worktreePath,
|
|
192
|
+
taskFolder,
|
|
193
|
+
config,
|
|
194
|
+
taskFileScope,
|
|
195
|
+
journal,
|
|
196
|
+
});
|
|
197
|
+
const thinkingLevel = resolveThinkingLevel(config);
|
|
198
|
+
|
|
199
|
+
/** @type {Record<string, unknown>} */
|
|
200
|
+
const sessionOptions = {
|
|
201
|
+
cwd: worktreePath,
|
|
202
|
+
thinkingLevel,
|
|
203
|
+
};
|
|
204
|
+
|
|
205
|
+
if (deps.sessionManager) {
|
|
206
|
+
sessionOptions.sessionManager = deps.sessionManager;
|
|
207
|
+
} else if (
|
|
208
|
+
process.env.SPINE_AGENT_SESSION_STUB === "1" ||
|
|
209
|
+
process.env.SPINE_WORKER_STUB === "1" ||
|
|
210
|
+
process.env.SPINE_WORKER_STUB === "true"
|
|
211
|
+
) {
|
|
212
|
+
process.env.SPINE_TASK_FOLDER = taskFolder;
|
|
213
|
+
} else {
|
|
214
|
+
const pi = await import("@earendil-works/pi-coding-agent");
|
|
215
|
+
sessionOptions.sessionManager = pi.SessionManager.inMemory();
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
const { session } = await createAgentSession(sessionOptions);
|
|
219
|
+
state.session = session;
|
|
220
|
+
|
|
221
|
+
// Agent sessions do not expose a subprocess stdout/stderr stream; append
|
|
222
|
+
// streamed assistant/tool text when subscribe is available (pi-coding-agent).
|
|
223
|
+
let unsubscribe = () => {};
|
|
224
|
+
if (typeof session.subscribe === "function") {
|
|
225
|
+
unsubscribe = session.subscribe((event) => {
|
|
226
|
+
const chunk = formatAgentSessionEvent(event);
|
|
227
|
+
if (chunk) state.transcript += chunk;
|
|
228
|
+
});
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
try {
|
|
232
|
+
await session.prompt(promptText);
|
|
233
|
+
} finally {
|
|
234
|
+
unsubscribe();
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
if (state.aborted) {
|
|
238
|
+
state.exitCode = 130;
|
|
239
|
+
state.output = appendAgentSessionOutput(state, "agent session aborted");
|
|
240
|
+
return;
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
if (!fs.existsSync(donePath)) {
|
|
244
|
+
state.exitCode = 1;
|
|
245
|
+
state.output = appendAgentSessionOutput(
|
|
246
|
+
state,
|
|
247
|
+
"agent session finished but .DONE was not created",
|
|
248
|
+
);
|
|
249
|
+
return;
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
state.exitCode = 0;
|
|
253
|
+
state.output = state.transcript.trim();
|
|
254
|
+
} catch (err) {
|
|
255
|
+
state.exitCode = 1;
|
|
256
|
+
state.output = appendAgentSessionOutput(
|
|
257
|
+
state,
|
|
258
|
+
err instanceof Error ? err.message : String(err),
|
|
259
|
+
);
|
|
260
|
+
} finally {
|
|
261
|
+
state.session?.dispose?.();
|
|
262
|
+
state.session = null;
|
|
263
|
+
}
|
|
264
|
+
})();
|
|
265
|
+
|
|
266
|
+
return {
|
|
267
|
+
pid: process.pid,
|
|
268
|
+
get exitCode() {
|
|
269
|
+
return state.exitCode;
|
|
270
|
+
},
|
|
271
|
+
kill: (signal) => {
|
|
272
|
+
state.aborted = true;
|
|
273
|
+
if (signal === "SIGKILL") {
|
|
274
|
+
state.exitCode = 137;
|
|
275
|
+
}
|
|
276
|
+
const session = state.session;
|
|
277
|
+
if (session?.abort) {
|
|
278
|
+
void session.abort().catch((err) => {
|
|
279
|
+
const root =
|
|
280
|
+
process.env.SPINE_PROJECT_ROOT ?? projectRoot ?? process.cwd();
|
|
281
|
+
const batchId = process.env.SPINE_BATCH_ID;
|
|
282
|
+
if (batchId) {
|
|
283
|
+
appendJournalEvent(root, batchId, "lane.worker_abort_failed", {
|
|
284
|
+
taskId: process.env.SPINE_TASK_ID,
|
|
285
|
+
laneNumber: process.env.SPINE_LANE_NUMBER,
|
|
286
|
+
error: err instanceof Error ? err.message : String(err),
|
|
287
|
+
});
|
|
288
|
+
}
|
|
289
|
+
});
|
|
290
|
+
}
|
|
291
|
+
},
|
|
292
|
+
wait: async () => {
|
|
293
|
+
await donePromise;
|
|
294
|
+
return { exitCode: state.exitCode ?? 1, output: state.output };
|
|
295
|
+
},
|
|
296
|
+
};
|
|
297
|
+
}
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Batch state file resolution, load, and parse (leaf module — no reconcile/state imports).
|
|
3
|
+
*/
|
|
4
|
+
|
|
5
|
+
import fs from "node:fs";
|
|
6
|
+
import path from "node:path";
|
|
7
|
+
import { parseSpineBatchState } from "./readers/spine-state.mjs";
|
|
8
|
+
import { parseTaskplaneBatchState } from "./readers/taskplane-state.mjs";
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* @param {string} projectRoot
|
|
12
|
+
*/
|
|
13
|
+
export function resolveBatchStatePath(projectRoot) {
|
|
14
|
+
const spinePath = path.join(projectRoot, ".spine", "batch-state.json");
|
|
15
|
+
if (fs.existsSync(spinePath)) return spinePath;
|
|
16
|
+
|
|
17
|
+
const piPath = path.join(projectRoot, ".pi", "batch-state.json");
|
|
18
|
+
if (fs.existsSync(piPath)) return piPath;
|
|
19
|
+
|
|
20
|
+
return null;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* @param {string} projectRoot
|
|
25
|
+
* @param {string|null} [batchStatePath]
|
|
26
|
+
*/
|
|
27
|
+
export function loadBatchStateFile(projectRoot, batchStatePath = null) {
|
|
28
|
+
const resolved = batchStatePath ?? resolveBatchStatePath(projectRoot);
|
|
29
|
+
if (!resolved) return { path: null, raw: null, parseError: null };
|
|
30
|
+
|
|
31
|
+
try {
|
|
32
|
+
const raw = JSON.parse(fs.readFileSync(resolved, "utf-8"));
|
|
33
|
+
return { path: resolved, raw, parseError: null };
|
|
34
|
+
} catch (err) {
|
|
35
|
+
return {
|
|
36
|
+
path: resolved,
|
|
37
|
+
raw: null,
|
|
38
|
+
parseError: err instanceof Error ? err.message : String(err),
|
|
39
|
+
};
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* @param {unknown} raw
|
|
45
|
+
* @param {string} batchStatePath
|
|
46
|
+
*/
|
|
47
|
+
export function parseBatchState(raw, batchStatePath) {
|
|
48
|
+
if (!raw) return null;
|
|
49
|
+
if (batchStatePath.includes(`${path.sep}.pi${path.sep}`)) {
|
|
50
|
+
return parseTaskplaneBatchState(raw);
|
|
51
|
+
}
|
|
52
|
+
return parseSpineBatchState(raw) ?? parseTaskplaneBatchState(raw);
|
|
53
|
+
}
|
|
@@ -0,0 +1,310 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Machine contract verification in lane worktree (handoff §4.5, SP-154/SP-155).
|
|
3
|
+
*/
|
|
4
|
+
|
|
5
|
+
import fs from "node:fs";
|
|
6
|
+
import path from "node:path";
|
|
7
|
+
import { execFileSync, spawnSync } from "node:child_process";
|
|
8
|
+
import micromatch from "micromatch";
|
|
9
|
+
import { parseAggregateLineCoverage } from "../../scripts/coverage-parse.mjs";
|
|
10
|
+
import { resolveContractMode } from "../tasks/packet/validate-contract.mjs";
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* @param {string} taskId
|
|
14
|
+
* @param {ReturnType<import("../tasks/packet/parse-prompt.mjs").parseContract>} parsedContract
|
|
15
|
+
* @param {object} [config]
|
|
16
|
+
*/
|
|
17
|
+
export function shouldRunContractVerify(taskId, parsedContract, config = {}) {
|
|
18
|
+
const mode = resolveContractMode({
|
|
19
|
+
mode: config.contract?.mode,
|
|
20
|
+
taskId,
|
|
21
|
+
legacyTaskIdPrefixes: config.contract?.legacyTaskIdPrefixes,
|
|
22
|
+
});
|
|
23
|
+
if (mode === "legacy") return false;
|
|
24
|
+
if (!parsedContract?.hasSection) return false;
|
|
25
|
+
|
|
26
|
+
return Boolean(
|
|
27
|
+
parsedContract.testCommand ||
|
|
28
|
+
(parsedContract.fileScopeMustChange?.length ?? 0) > 0 ||
|
|
29
|
+
(parsedContract.fileScopeMustNotChange?.length ?? 0) > 0 ||
|
|
30
|
+
parsedContract.minLineCoverage != null ||
|
|
31
|
+
(parsedContract.artifactsMustExist?.length ?? 0) > 0,
|
|
32
|
+
);
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* Exit-verification tasks (§8 phase exit) must not stub-complete without contract pass.
|
|
37
|
+
*
|
|
38
|
+
* @param {string} promptMarkdown
|
|
39
|
+
*/
|
|
40
|
+
export function isExitVerificationTask(promptMarkdown) {
|
|
41
|
+
const text = String(promptMarkdown ?? "");
|
|
42
|
+
if (/^#\s*Task:.*exit verification/im.test(text)) {
|
|
43
|
+
return true;
|
|
44
|
+
}
|
|
45
|
+
if (/^##\s*Exit verification/im.test(text)) {
|
|
46
|
+
return true;
|
|
47
|
+
}
|
|
48
|
+
if (/Phase\s+\d+\s+exit verification/i.test(text)) {
|
|
49
|
+
return true;
|
|
50
|
+
}
|
|
51
|
+
return false;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* @param {string} promptMarkdown
|
|
56
|
+
* @param {ReturnType<import("../tasks/packet/parse-prompt.mjs").parseContract>} parsedContract
|
|
57
|
+
* @param {object} [config]
|
|
58
|
+
*/
|
|
59
|
+
export function shouldRunContractVerifyForWorker(promptMarkdown, parsedContract, config = {}) {
|
|
60
|
+
if (!shouldRunContractVerify(null, parsedContract, config)) {
|
|
61
|
+
return false;
|
|
62
|
+
}
|
|
63
|
+
const stubMode =
|
|
64
|
+
process.env.SPINE_WORKER_STUB === "1" || process.env.SPINE_WORKER_STUB === "true";
|
|
65
|
+
if (!stubMode) {
|
|
66
|
+
return true;
|
|
67
|
+
}
|
|
68
|
+
return isExitVerificationTask(promptMarkdown);
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* @param {string} worktreePath
|
|
73
|
+
* @param {string} [baseBranch]
|
|
74
|
+
*/
|
|
75
|
+
export function listChangedFiles(worktreePath, baseBranch = "main") {
|
|
76
|
+
try {
|
|
77
|
+
const output = execFileSync("git", ["diff", "--name-only", `${baseBranch}...HEAD`], {
|
|
78
|
+
cwd: worktreePath,
|
|
79
|
+
encoding: "utf-8",
|
|
80
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
81
|
+
timeout: 30_000,
|
|
82
|
+
});
|
|
83
|
+
return output
|
|
84
|
+
.split(/\r?\n/)
|
|
85
|
+
.map((line) => line.trim())
|
|
86
|
+
.filter(Boolean);
|
|
87
|
+
} catch {
|
|
88
|
+
try {
|
|
89
|
+
const output = execFileSync("git", ["diff", "--name-only", "HEAD"], {
|
|
90
|
+
cwd: worktreePath,
|
|
91
|
+
encoding: "utf-8",
|
|
92
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
93
|
+
timeout: 30_000,
|
|
94
|
+
});
|
|
95
|
+
return output
|
|
96
|
+
.split(/\r?\n/)
|
|
97
|
+
.map((line) => line.trim())
|
|
98
|
+
.filter(Boolean);
|
|
99
|
+
} catch {
|
|
100
|
+
return [];
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/**
|
|
106
|
+
* @param {string} file
|
|
107
|
+
* @param {string} pattern
|
|
108
|
+
*/
|
|
109
|
+
export function matchesContractPattern(file, pattern) {
|
|
110
|
+
return micromatch.isMatch(file, pattern, { dot: true });
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/**
|
|
114
|
+
* @param {string} worktreePath
|
|
115
|
+
* @param {string} command
|
|
116
|
+
*/
|
|
117
|
+
function runContractTestCommand(worktreePath, command) {
|
|
118
|
+
const trimmed = String(command ?? "").trim();
|
|
119
|
+
if (!trimmed || trimmed === "true") {
|
|
120
|
+
return { ok: true, exitCode: 0, output: "" };
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
const shell = process.env.SHELL || (process.platform === "win32" ? "cmd.exe" : "/bin/sh");
|
|
124
|
+
const shellFlag = process.platform === "win32" ? "/c" : "-c";
|
|
125
|
+
const result = spawnSync(shell, [shellFlag, trimmed], {
|
|
126
|
+
cwd: worktreePath,
|
|
127
|
+
encoding: "utf-8",
|
|
128
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
129
|
+
timeout: 10 * 60 * 1000,
|
|
130
|
+
maxBuffer: 256 * 1024,
|
|
131
|
+
});
|
|
132
|
+
|
|
133
|
+
const exitCode = Number(result.status ?? 1);
|
|
134
|
+
const stdout = String(result.stdout ?? "");
|
|
135
|
+
const stderr = String(result.stderr ?? "");
|
|
136
|
+
const output = `${stdout}\n${stderr}`;
|
|
137
|
+
if (exitCode === 0) {
|
|
138
|
+
return { ok: true, exitCode: 0, output };
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
const summary = [stdout.trim(), stderr.trim()].filter(Boolean).join("\n").slice(0, 500);
|
|
142
|
+
return { ok: false, exitCode, output, summary };
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/**
|
|
146
|
+
* @param {string} worktreePath
|
|
147
|
+
* @param {object} config
|
|
148
|
+
*/
|
|
149
|
+
function resolveCoverageCommand(config) {
|
|
150
|
+
return (
|
|
151
|
+
config?.testing?.testWithCoverage ??
|
|
152
|
+
config?.testing?.test ??
|
|
153
|
+
"npm run coverage:check"
|
|
154
|
+
);
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/**
|
|
158
|
+
* @param {string} worktreePath
|
|
159
|
+
* @param {ReturnType<import("../tasks/packet/parse-prompt.mjs").parseContract>} parsedContract
|
|
160
|
+
* @param {object} config
|
|
161
|
+
* @param {string} [testCommandOutput]
|
|
162
|
+
*/
|
|
163
|
+
function resolveLineCoverage(worktreePath, parsedContract, config, testCommandOutput = "") {
|
|
164
|
+
let output = testCommandOutput;
|
|
165
|
+
if (parsedContract.minLineCoverage != null) {
|
|
166
|
+
const parsedFromTest = parseAggregateLineCoverage(output);
|
|
167
|
+
if (parsedFromTest != null) {
|
|
168
|
+
return parsedFromTest;
|
|
169
|
+
}
|
|
170
|
+
const coverageCommand = resolveCoverageCommand(config);
|
|
171
|
+
const coverageResult = runContractTestCommand(worktreePath, coverageCommand);
|
|
172
|
+
output = coverageResult.output;
|
|
173
|
+
}
|
|
174
|
+
return parseAggregateLineCoverage(output);
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
/**
|
|
178
|
+
* @param {string} worktreePath
|
|
179
|
+
* @param {string} artifactPattern
|
|
180
|
+
* @returns {{ ok: boolean, matchedPath?: string }}
|
|
181
|
+
*/
|
|
182
|
+
function findArtifactMatch(worktreePath, artifactPattern) {
|
|
183
|
+
const normalized = String(artifactPattern ?? "").replace(/\\/g, "/");
|
|
184
|
+
if (!normalized) {
|
|
185
|
+
return { ok: false };
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
if (!/[*?[\]{}]/.test(normalized)) {
|
|
189
|
+
const fullPath = path.join(worktreePath, normalized);
|
|
190
|
+
return fs.existsSync(fullPath) ? { ok: true, matchedPath: normalized } : { ok: false };
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
const baseDir = path.dirname(normalized);
|
|
194
|
+
const searchRoot = path.join(worktreePath, baseDir);
|
|
195
|
+
if (!fs.existsSync(searchRoot)) {
|
|
196
|
+
return { ok: false };
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
/** @type {Array<{ abs: string, rel: string }>} */
|
|
200
|
+
const stack = [{ abs: searchRoot, rel: baseDir === "." ? "" : baseDir }];
|
|
201
|
+
while (stack.length > 0) {
|
|
202
|
+
const { abs, rel } = stack.pop();
|
|
203
|
+
for (const entry of fs.readdirSync(abs, { withFileTypes: true })) {
|
|
204
|
+
const entryRel = rel ? `${rel}/${entry.name}` : entry.name;
|
|
205
|
+
const entryAbs = path.join(abs, entry.name);
|
|
206
|
+
if (entry.isDirectory()) {
|
|
207
|
+
stack.push({ abs: entryAbs, rel: entryRel });
|
|
208
|
+
continue;
|
|
209
|
+
}
|
|
210
|
+
if (micromatch.isMatch(entryRel, normalized)) {
|
|
211
|
+
return { ok: true, matchedPath: entryRel };
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
return { ok: false };
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
/**
|
|
220
|
+
* @param {string} worktreePath
|
|
221
|
+
* @param {ReturnType<import("../tasks/packet/parse-prompt.mjs").parseContract>} parsedContract
|
|
222
|
+
* @param {object} [config]
|
|
223
|
+
* @returns {{ ok: boolean, checks: Array<{ field: string, ok: boolean, message: string }> }}
|
|
224
|
+
*/
|
|
225
|
+
export function verifyContract(worktreePath, parsedContract, config = {}) {
|
|
226
|
+
/** @type {Array<{ field: string, ok: boolean, message: string }>} */
|
|
227
|
+
const checks = [];
|
|
228
|
+
const baseBranch = config?.baseBranch ?? "main";
|
|
229
|
+
const changedFiles = listChangedFiles(worktreePath, baseBranch);
|
|
230
|
+
|
|
231
|
+
let testCommandOutput = "";
|
|
232
|
+
if (parsedContract.testCommand) {
|
|
233
|
+
const result = runContractTestCommand(worktreePath, parsedContract.testCommand);
|
|
234
|
+
testCommandOutput = result.output;
|
|
235
|
+
checks.push({
|
|
236
|
+
field: "testCommand",
|
|
237
|
+
ok: result.ok,
|
|
238
|
+
message: result.ok
|
|
239
|
+
? "testCommand passed"
|
|
240
|
+
: `Contract testCommand failed (exit ${result.exitCode}): ${result.summary || "(no output)"}`,
|
|
241
|
+
});
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
for (const pattern of parsedContract.fileScopeMustChange ?? []) {
|
|
245
|
+
const matched = changedFiles.some((file) => matchesContractPattern(file, pattern));
|
|
246
|
+
checks.push({
|
|
247
|
+
field: "fileScopeMustChange",
|
|
248
|
+
ok: matched,
|
|
249
|
+
message: matched
|
|
250
|
+
? `fileScopeMustChange matched: ${pattern}`
|
|
251
|
+
: `Contract fileScopeMustChange: no matching changes for ${pattern}`,
|
|
252
|
+
});
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
for (const pattern of parsedContract.fileScopeMustNotChange ?? []) {
|
|
256
|
+
const forbidden = changedFiles.filter((file) => matchesContractPattern(file, pattern));
|
|
257
|
+
if (forbidden.length === 0) {
|
|
258
|
+
checks.push({
|
|
259
|
+
field: "fileScopeMustNotChange",
|
|
260
|
+
ok: true,
|
|
261
|
+
message: `fileScopeMustNotChange respected: ${pattern}`,
|
|
262
|
+
});
|
|
263
|
+
} else {
|
|
264
|
+
for (const file of forbidden) {
|
|
265
|
+
checks.push({
|
|
266
|
+
field: "fileScopeMustNotChange",
|
|
267
|
+
ok: false,
|
|
268
|
+
message: `Contract fileScopeMustNotChange: forbidden change ${file}`,
|
|
269
|
+
});
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
if (parsedContract.minLineCoverage != null) {
|
|
275
|
+
const actual = resolveLineCoverage(worktreePath, parsedContract, config, testCommandOutput);
|
|
276
|
+
const required = parsedContract.minLineCoverage;
|
|
277
|
+
if (actual == null) {
|
|
278
|
+
checks.push({
|
|
279
|
+
field: "minLineCoverage",
|
|
280
|
+
ok: false,
|
|
281
|
+
message: `Contract minLineCoverage: could not parse coverage output (required ${required}%)`,
|
|
282
|
+
});
|
|
283
|
+
} else {
|
|
284
|
+
const ok = actual >= required;
|
|
285
|
+
checks.push({
|
|
286
|
+
field: "minLineCoverage",
|
|
287
|
+
ok,
|
|
288
|
+
message: ok
|
|
289
|
+
? `minLineCoverage met: ${actual.toFixed(2)}% >= ${required}%`
|
|
290
|
+
: `Contract minLineCoverage: ${actual.toFixed(2)}% < ${required}%`,
|
|
291
|
+
});
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
for (const artifactPath of parsedContract.artifactsMustExist ?? []) {
|
|
296
|
+
const match = findArtifactMatch(worktreePath, artifactPath);
|
|
297
|
+
checks.push({
|
|
298
|
+
field: "artifactsMustExist",
|
|
299
|
+
ok: match.ok,
|
|
300
|
+
message: match.ok
|
|
301
|
+
? `artifact exists: ${match.matchedPath ?? artifactPath}`
|
|
302
|
+
: `Contract artifactsMustExist: missing ${artifactPath}`,
|
|
303
|
+
});
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
return {
|
|
307
|
+
ok: checks.length === 0 || checks.every((check) => check.ok),
|
|
308
|
+
checks,
|
|
309
|
+
};
|
|
310
|
+
}
|