pi-spine 1.1.0 → 1.2.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.
Files changed (102) hide show
  1. package/bin/spine-batch.mjs +160 -53
  2. package/bin/spine-cli/batch.mjs +3 -3
  3. package/bin/spine-cli/lane-logs.mjs +24 -0
  4. package/bin/spine-cli/scenarios.mjs +298 -0
  5. package/bin/spine-cli/wait.mjs +30 -0
  6. package/bin/spine-cli/watch.mjs +27 -0
  7. package/bin/spine-issue.mjs +196 -0
  8. package/bin/spine-journal.mjs +1 -0
  9. package/bin/spine-run.mjs +30 -0
  10. package/bin/spine-status.mjs +19 -1
  11. package/bin/spine-tasks.mjs +16 -2
  12. package/bin/spine-worker-runner.mjs +10 -10
  13. package/bin/spine.mjs +49 -1
  14. package/package.json +1 -1
  15. package/skills/create-spine-tasks/references/contract-template.md +19 -0
  16. package/src/batch/abort.mjs +2 -11
  17. package/src/batch/agent-session-worker.mjs +45 -5
  18. package/src/batch/attached-engine-handoff.mjs +188 -0
  19. package/src/batch/attached-runner.mjs +312 -0
  20. package/src/batch/contract-prelanded.mjs +180 -0
  21. package/src/batch/contract-verify.mjs +140 -2
  22. package/src/batch/detached-start.mjs +66 -2
  23. package/src/batch/diagnosis-alternatives.mjs +46 -0
  24. package/src/batch/diagnosis-merge-failure.mjs +79 -0
  25. package/src/batch/diagnosis-retry-limbo.mjs +34 -0
  26. package/src/batch/diagnosis-stub.mjs +109 -0
  27. package/src/batch/diagnosis-task-done.mjs +110 -0
  28. package/src/batch/diagnosis-worker-done-missing.mjs +96 -0
  29. package/src/batch/diagnosis.mjs +135 -68
  30. package/src/batch/engine-lanes/merge.mjs +110 -82
  31. package/src/batch/engine-lanes/queue.mjs +4 -1
  32. package/src/batch/engine-lanes/watch.mjs +29 -0
  33. package/src/batch/engine-lanes.mjs +1 -0
  34. package/src/batch/engine-scope.mjs +11 -1
  35. package/src/batch/engine.mjs +79 -24
  36. package/src/batch/evidence.mjs +78 -15
  37. package/src/batch/gate.mjs +43 -14
  38. package/src/batch/git-helpers.mjs +96 -0
  39. package/src/batch/heartbeat.mjs +73 -7
  40. package/src/batch/integrate.mjs +2 -4
  41. package/src/batch/journal.mjs +3 -0
  42. package/src/batch/lane-commit.mjs +90 -5
  43. package/src/batch/lifecycle.mjs +130 -3
  44. package/src/batch/macro-phase.mjs +226 -0
  45. package/src/batch/merge/adoption-doc-merge.mjs +93 -10
  46. package/src/batch/merge/wave-merge-state.mjs +3 -0
  47. package/src/batch/metrics.mjs +74 -5
  48. package/src/batch/orphan-detect.mjs +74 -0
  49. package/src/batch/pause.mjs +223 -0
  50. package/src/batch/post-merge-limbo.mjs +264 -8
  51. package/src/batch/reconcile.mjs +429 -54
  52. package/src/batch/resume-common.mjs +5 -1
  53. package/src/batch/resume-lane-reviews.mjs +16 -0
  54. package/src/batch/resume-multi-lanes.mjs +56 -1
  55. package/src/batch/resume-multi-validate.mjs +67 -6
  56. package/src/batch/resume-multi.mjs +9 -4
  57. package/src/batch/resume.mjs +52 -45
  58. package/src/batch/retry.mjs +56 -5
  59. package/src/batch/review-spawn.mjs +8 -2
  60. package/src/batch/rules-manifest-drift.mjs +157 -0
  61. package/src/batch/salvage.mjs +2 -1
  62. package/src/batch/sequence.mjs +454 -0
  63. package/src/batch/state.mjs +18 -3
  64. package/src/batch/status-json.mjs +67 -0
  65. package/src/batch/task-stall-budget.mjs +22 -10
  66. package/src/batch/worker-host.mjs +95 -7
  67. package/src/batch/worker-output.mjs +196 -3
  68. package/src/cli/issue-draft.mjs +180 -0
  69. package/src/cli/journal-follow.mjs +239 -0
  70. package/src/cli/lane-logs.mjs +291 -0
  71. package/src/cli/sequence.mjs +108 -0
  72. package/src/cli/settings-set.mjs +2 -21
  73. package/src/cli/wait.mjs +187 -0
  74. package/src/cli/watch.mjs +160 -0
  75. package/src/config/agent-model-resolve.mjs +48 -0
  76. package/src/config/cursor-rules/discover.mjs +3 -21
  77. package/src/config/defaults.mjs +7 -1
  78. package/src/config/settings-fields.mjs +48 -0
  79. package/src/config/spine-init-constants.mjs +1 -0
  80. package/src/config/spine-preflight-lib.mjs +471 -16
  81. package/src/dashboard/lane-throughput.mjs +351 -0
  82. package/src/dashboard/public/dashboard.css +25 -1
  83. package/src/dashboard/public/dashboard.js +223 -18
  84. package/src/dashboard/public/index.html +14 -2
  85. package/src/dashboard/server.mjs +4 -0
  86. package/src/dashboard/snapshot.mjs +215 -1
  87. package/src/dashboard/view.mjs +170 -17
  88. package/src/doctor/agent-model-inherit.mjs +61 -6
  89. package/src/doctor/run-doctor-checks.mjs +26 -1
  90. package/src/doctor/sequence-safety.mjs +57 -0
  91. package/src/doctor/stale-worktrees.mjs +102 -0
  92. package/src/fixtures/scenario-registry.mjs +194 -0
  93. package/src/fs/atomic-write.mjs +49 -0
  94. package/src/planner/file-scope.mjs +246 -0
  95. package/src/planner/format-plan.mjs +9 -7
  96. package/src/planner/index.mjs +6 -2
  97. package/src/planner/wave-scope.mjs +136 -0
  98. package/src/planner/waves.mjs +133 -0
  99. package/src/tasks/packet/index.mjs +1 -0
  100. package/src/tasks/packet/parse-prompt.mjs +42 -1
  101. package/src/tasks/packet/validate-prompt.mjs +124 -0
  102. package/templates/spine-config.json +8 -1
@@ -0,0 +1,196 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * GitHub issue draft CLI (issue #60 Tier 1c).
4
+ * Usage: spine issue draft [--type bug|enhancement|question] [--title TITLE] [--json] [--out PATH] [--create]
5
+ */
6
+
7
+ import fs from "node:fs";
8
+ import path from "node:path";
9
+ import { spawnSync } from "node:child_process";
10
+
11
+ import { buildIssueDraftBody } from "../src/cli/issue-draft.mjs";
12
+ import { commandExists } from "../src/util/command-exists.mjs";
13
+ import { c, die, isCliEntrypoint } from "./spine-cli/shared.mjs";
14
+
15
+ const DEFAULT_OUT_PATH = ".spine/issue-draft.md";
16
+
17
+ /**
18
+ * @param {string[]} argv
19
+ */
20
+ export function parseIssueDraftArgs(argv) {
21
+ /** @type {{ issueType: "bug"|"enhancement"|"question", title: string|null, json: boolean, outPath: string, create: boolean }} */
22
+ const args = {
23
+ issueType: "bug",
24
+ title: null,
25
+ json: false,
26
+ outPath: DEFAULT_OUT_PATH,
27
+ create: false,
28
+ };
29
+
30
+ for (let i = 0; i < argv.length; i++) {
31
+ const arg = argv[i];
32
+ if (arg === "--type") {
33
+ const value = argv[++i];
34
+ if (value !== "bug" && value !== "enhancement" && value !== "question") {
35
+ die(`Invalid --type value: ${value ?? "(missing)"}\nExpected bug, enhancement, or question.`);
36
+ }
37
+ args.issueType = value;
38
+ } else if (arg === "--title") {
39
+ args.title = argv[++i] ?? null;
40
+ } else if (arg === "--json") {
41
+ args.json = true;
42
+ } else if (arg === "--out") {
43
+ args.outPath = argv[++i] ?? DEFAULT_OUT_PATH;
44
+ } else if (arg === "--create") {
45
+ args.create = true;
46
+ } else if (arg === "--help" || arg === "-h") {
47
+ return { ...args, help: true };
48
+ } else {
49
+ die(`Unknown argument: ${arg}\nRun ${c.cyan}spine issue draft --help${c.reset} for usage.`);
50
+ }
51
+ }
52
+
53
+ return args;
54
+ }
55
+
56
+ export function printIssueDraftHelp() {
57
+ console.log(`
58
+ ${c.bold}spine issue draft${c.reset} — build a GitHub issue draft from project state
59
+
60
+ ${c.bold}Usage:${c.reset}
61
+ spine issue draft [--type bug|enhancement|question] [--title TITLE] [--json] [--out PATH] [--create]
62
+
63
+ ${c.bold}Options:${c.reset}
64
+ --type TYPE Issue type label: bug (default), enhancement, or question
65
+ --title TITLE Override issue title (default: diagnosis headline)
66
+ --json Print { title, body, labels, draftPath? } as JSON
67
+ --out PATH Write markdown body to PATH (default: ${DEFAULT_OUT_PATH})
68
+ --create Create GitHub issue via gh CLI (requires gh on PATH)
69
+ `);
70
+ }
71
+
72
+ /**
73
+ * @param {object} options
74
+ * @param {string} options.projectRoot
75
+ * @param {string[]} [options.args]
76
+ */
77
+ export function runSpineIssueDraft(options) {
78
+ const { projectRoot, args: argv = [] } = options;
79
+ const parsed = parseIssueDraftArgs(argv);
80
+ if ("help" in parsed && parsed.help) {
81
+ printIssueDraftHelp();
82
+ return { exitCode: 0, output: "" };
83
+ }
84
+
85
+ let draft;
86
+ try {
87
+ draft = buildIssueDraftBody({
88
+ projectRoot,
89
+ issueType: parsed.issueType,
90
+ title: parsed.title ?? undefined,
91
+ });
92
+ } catch (err) {
93
+ const message = err instanceof Error ? err.message : String(err);
94
+ return { exitCode: 1, output: `ERROR: ${message}\n` };
95
+ }
96
+
97
+ const draftPath = path.resolve(projectRoot, parsed.outPath);
98
+ let wroteDraft = false;
99
+ if (!parsed.json) {
100
+ fs.mkdirSync(path.dirname(draftPath), { recursive: true });
101
+ fs.writeFileSync(draftPath, draft.body, "utf-8");
102
+ wroteDraft = true;
103
+ }
104
+
105
+ if (parsed.create) {
106
+ if (!commandExists("gh")) {
107
+ return {
108
+ exitCode: 1,
109
+ output:
110
+ "ERROR: gh CLI not found on PATH. Install GitHub CLI or omit --create.\n",
111
+ };
112
+ }
113
+
114
+ const bodyFilePath = wroteDraft ? draftPath : path.join(projectRoot, ".spine", ".issue-draft-body.tmp.md");
115
+ if (!wroteDraft) {
116
+ fs.mkdirSync(path.dirname(bodyFilePath), { recursive: true });
117
+ fs.writeFileSync(bodyFilePath, draft.body, "utf-8");
118
+ }
119
+
120
+ const ghArgs = [
121
+ "issue",
122
+ "create",
123
+ "--title",
124
+ draft.title,
125
+ "--body-file",
126
+ bodyFilePath,
127
+ ];
128
+ for (const label of draft.labels) {
129
+ ghArgs.push("--label", label);
130
+ }
131
+
132
+ const ghResult = spawnSync("gh", ghArgs, {
133
+ cwd: projectRoot,
134
+ encoding: "utf-8",
135
+ stdio: ["ignore", "pipe", "pipe"],
136
+ });
137
+
138
+ if (!wroteDraft && bodyFilePath.endsWith(".issue-draft-body.tmp.md")) {
139
+ try {
140
+ fs.unlinkSync(bodyFilePath);
141
+ } catch {
142
+ // Best-effort cleanup of temp body file.
143
+ }
144
+ }
145
+
146
+ if (ghResult.status !== 0) {
147
+ const stderr = (ghResult.stderr ?? "").trim();
148
+ return {
149
+ exitCode: ghResult.status ?? 1,
150
+ output: stderr ? `ERROR: ${stderr}\n` : "ERROR: gh issue create failed\n",
151
+ };
152
+ }
153
+ }
154
+
155
+ if (parsed.json) {
156
+ const payload = {
157
+ title: draft.title,
158
+ body: draft.body,
159
+ labels: draft.labels,
160
+ };
161
+ if (wroteDraft) {
162
+ payload.draftPath = path.relative(projectRoot, draftPath);
163
+ }
164
+ return { exitCode: 0, output: `${JSON.stringify(payload, null, 2)}\n` };
165
+ }
166
+
167
+ const humanOutput = [`# ${draft.title}`, "", draft.body, ""].join("\n");
168
+ return { exitCode: 0, output: humanOutput };
169
+ }
170
+
171
+ /**
172
+ * @param {object} options
173
+ * @param {string} options.projectRoot
174
+ * @param {string[]} [options.args]
175
+ */
176
+ export function runSpineIssue(options) {
177
+ const { projectRoot, args: argv = [] } = options;
178
+ const sub = argv[0];
179
+ if (sub !== "draft") {
180
+ return {
181
+ exitCode: 1,
182
+ output:
183
+ `Usage: spine issue draft [--type bug|enhancement|question] [--title TITLE] [--json] [--out PATH] [--create]\n`,
184
+ };
185
+ }
186
+ return runSpineIssueDraft({ projectRoot, args: argv.slice(1) });
187
+ }
188
+
189
+ if (isCliEntrypoint(import.meta.url)) {
190
+ const { exitCode, output } = runSpineIssue({
191
+ projectRoot: process.cwd(),
192
+ args: process.argv.slice(2),
193
+ });
194
+ process.stdout.write(output ?? "");
195
+ process.exit(exitCode);
196
+ }
@@ -81,6 +81,7 @@ export function formatJournalReplayTable(events) {
81
81
  const JOURNAL_USAGE =
82
82
  "Usage:\n" +
83
83
  " spine journal replay --batch {id} [--json]\n" +
84
+ " spine journal follow [--batch {id}] [--lane lane-N] [--json]\n" +
84
85
  " spine journal export --batch {id} --format markdown|jsonl [--output path]\n";
85
86
 
86
87
  /**
@@ -0,0 +1,30 @@
1
+ import path from "node:path";
2
+ import { fileURLToPath } from "node:url";
3
+
4
+ const __dirname = path.dirname(fileURLToPath(import.meta.url));
5
+
6
+ /**
7
+ * Route `spine run` subcommands.
8
+ * - `spine run sequence <scope>` — planner wave sequence (GitHub #54 Tier 2)
9
+ * - `spine run <scope>` — alias for `spine batch start <scope>` (TP-024)
10
+ *
11
+ * @param {object} options
12
+ * @param {string} options.projectRoot
13
+ * @param {string[]} options.args
14
+ */
15
+ export async function runSpineRun({ projectRoot, args }) {
16
+ if (args[0] === "sequence") {
17
+ const { runSpineSequence } = await import("../src/cli/sequence.mjs");
18
+ return runSpineSequence({
19
+ projectRoot,
20
+ args: args.slice(1),
21
+ spineBin: path.join(__dirname, "spine.mjs"),
22
+ });
23
+ }
24
+
25
+ const { runSpineBatch } = await import("./spine-batch.mjs");
26
+ return runSpineBatch({
27
+ projectRoot,
28
+ args: ["start", ...args],
29
+ });
30
+ }
@@ -2,6 +2,7 @@ import { loadBatchStateFile } from "../src/batch/reconcile.mjs";
2
2
  import { generateBatchPostMortem } from "../src/batch/postmortem.mjs";
3
3
  import { readJournalEvents, readJournalTail } from "../src/batch/journal.mjs";
4
4
  import { reconcileBatch } from "../src/batch/reconcile.mjs";
5
+ import { formatStatusJson } from "../src/batch/status-json.mjs";
5
6
 
6
7
  /**
7
8
  * @param {object} options
@@ -17,7 +18,7 @@ export function runSpineStatus(options) {
17
18
  if (json) {
18
19
  return {
19
20
  exitCode: 0,
20
- output: `${JSON.stringify(result, null, 2)}\n`,
21
+ output: formatStatusJson(result),
21
22
  };
22
23
  }
23
24
 
@@ -32,10 +33,27 @@ export function runSpineStatus(options) {
32
33
  if (result.diagnosis) {
33
34
  lines.push(` Diagnosis: ${result.diagnosis}`);
34
35
  }
36
+ if (result.macroPhase) {
37
+ lines.push(` Macro phase: ${result.macroPhaseLabel ?? result.macroPhase}`);
38
+ }
35
39
 
36
40
  lines.push("", ` ${result.headline}`, "");
37
41
  lines.push(` → ${result.suggestedCommand}`);
38
42
 
43
+ if (diagnose && result.mergeFailed) {
44
+ lines.push("");
45
+ lines.push(` Merge failed: ${result.failedMerges} wave(s)`);
46
+ if (result.failedWaveIndex != null) {
47
+ lines.push(` Failed wave: ${Number(result.failedWaveIndex) + 1} (index ${result.failedWaveIndex})`);
48
+ }
49
+ if (result.failedLane != null) {
50
+ lines.push(` Failed lane: ${result.failedLane}`);
51
+ }
52
+ if (result.lastError) {
53
+ lines.push(` Last error: ${result.lastError}`);
54
+ }
55
+ }
56
+
39
57
  if (result.alternatives?.length) {
40
58
  lines.push("", " Alternatives:");
41
59
  for (const alt of result.alternatives) {
@@ -5,6 +5,7 @@
5
5
  * FR-UXB-02: validate task PROMPT packets for a planner scope.
6
6
  */
7
7
 
8
+ import path from 'node:path';
8
9
  import { c, isCliEntrypoint, writeCommandResult } from './spine-cli/shared.mjs';
9
10
  import { loadSpineConfig } from './spine-config.mjs';
10
11
  import { resolveTasksRootPath } from '../src/config/env-overrides.mjs';
@@ -16,6 +17,7 @@ import {
16
17
  loadDependenciesJson,
17
18
  loadTaskPacket,
18
19
  } from '../src/tasks/packet/index.mjs';
20
+ import { collectStaleFileScopeMustChangeWarnings } from '../src/tasks/packet/validate-prompt.mjs';
19
21
  import { parseScope } from '../src/planner/scope.mjs';
20
22
 
21
23
  /**
@@ -50,9 +52,10 @@ export function formatTasksValidateHuman({
50
52
  * @param {object} packet
51
53
  * @param {{ taskId: string, folderName: string }} discoveredTask
52
54
  * @param {{ tasks?: Record<string, string[]> }} depsJson
55
+ * @param {string} [projectRoot]
53
56
  * @returns {string[]}
54
57
  */
55
- export function collectTaskAdvisoryWarnings(packet, discoveredTask, depsJson) {
58
+ export function collectTaskAdvisoryWarnings(packet, discoveredTask, depsJson, projectRoot) {
56
59
  /** @type {string[]} */
57
60
  const warnings = [];
58
61
 
@@ -84,6 +87,17 @@ export function collectTaskAdvisoryWarnings(packet, discoveredTask, depsJson) {
84
87
  }
85
88
  }
86
89
 
90
+ if (projectRoot && packet.promptPath && packet.validation?.contract) {
91
+ const promptRelPath = path.relative(projectRoot, packet.promptPath);
92
+ warnings.push(
93
+ ...collectStaleFileScopeMustChangeWarnings(
94
+ projectRoot,
95
+ packet.validation.contract,
96
+ promptRelPath,
97
+ ),
98
+ );
99
+ }
100
+
87
101
  return warnings;
88
102
  }
89
103
 
@@ -207,7 +221,7 @@ export async function runSpineTasksValidate({
207
221
  /** @type {string[]} */
208
222
  const warnings = warningsOnly
209
223
  ? [
210
- ...collectTaskAdvisoryWarnings(packet, discoveredTask, depsJson),
224
+ ...collectTaskAdvisoryWarnings(packet, discoveredTask, depsJson, projectRoot),
211
225
  ...(packet.validation?.warnings ?? []),
212
226
  ]
213
227
  : [];
@@ -8,6 +8,7 @@
8
8
  * SPINE_TASK_FOLDER — absolute path to taskplane-tasks/TP-NNN-…/
9
9
  * SPINE_WORKTREE — lane git worktree root
10
10
  * SPINE_PROJECT_ROOT — pi-spine project root (journal + gate paths)
11
+ * SPINE_RULES_PROJECT_ROOT — lane worktree for rules manifest reads (SP-317)
11
12
  * SPINE_BATCH_ID — active batch id
12
13
  * SPINE_TASK_ID — e.g. TP-038
13
14
  * SPINE_LANE_NUMBER — 1-based lane index
@@ -28,6 +29,7 @@ import {
28
29
  import { reportTaskProgress } from "../src/worker-tools/report-progress.mjs";
29
30
  import { isCliEntrypoint } from "./spine-cli/shared.mjs";
30
31
  import { loadSpineConfig } from "./spine-config.mjs";
32
+ import { writeWorkerDoneMarker } from "../src/batch/worker-output.mjs";
31
33
  import { buildWorkerTailPrompt, taskIdFromFolder } from "../src/batch/worker-prompt.mjs";
32
34
  import { parsePrompt } from "../src/tasks/packet/parse-prompt.mjs";
33
35
 
@@ -83,7 +85,8 @@ export async function buildWorkerPiArgs({
83
85
  piArgs.push(`@${promptPath}`);
84
86
  }
85
87
  appendWorkerAgentModelArgs(piArgs, spineConfig);
86
- const projectRoot = process.env.SPINE_PROJECT_ROOT || worktreePath || process.cwd();
88
+ const projectRoot =
89
+ process.env.SPINE_RULES_PROJECT_ROOT || worktreePath || process.env.SPINE_PROJECT_ROOT || process.cwd();
87
90
  const taskFileScope = resolveTaskFileScope(taskFolder);
88
91
  const tailPrompt = await buildWorkerTailPrompt({
89
92
  worktreePath,
@@ -161,25 +164,25 @@ async function runWorkerRunner() {
161
164
  const mode = process.argv.includes("--stub") ? "stub" : "pi";
162
165
 
163
166
  if (mode === "stub") {
164
- const taskIdFromFolder = path.basename(taskFolder).match(/^([A-Z]+-\d+)/)?.[1] ?? "";
167
+ const parsedTaskId = path.basename(taskFolder).match(/^([A-Z]+-\d+)/)?.[1] ?? "";
165
168
  const failTasks = String(process.env.SPINE_WORKER_STUB_FAIL_TASKS ?? "")
166
169
  .split(/[,\s]+/)
167
170
  .filter(Boolean);
168
- if (failTasks.includes(taskIdFromFolder)) {
171
+ if (failTasks.includes(parsedTaskId)) {
169
172
  const dirtyRel = process.env.SPINE_WORKER_STUB_DIRTY_FILE;
170
173
  if (dirtyRel && worktreePath) {
171
174
  const dirtyPath = path.join(worktreePath, dirtyRel);
172
175
  fs.mkdirSync(path.dirname(dirtyPath), { recursive: true });
173
176
  fs.writeFileSync(dirtyPath, `stub dirty ${new Date().toISOString()}\n`, "utf-8");
174
177
  }
175
- console.error(`stub worker forced failure for ${taskIdFromFolder}`);
178
+ console.error(`stub worker forced failure for ${parsedTaskId}`);
176
179
  process.exit(1);
177
180
  }
178
181
 
179
182
  if (process.env.SPINE_WORKER_STUB_SAT020 === "1") {
180
183
  const journal = buildReviewJournal();
181
184
  const laneNumber = Number(process.env.SPINE_LANE_NUMBER || 1);
182
- const taskId = process.env.SPINE_TASK_ID || taskIdFromFolder;
185
+ const taskId = process.env.SPINE_TASK_ID || parsedTaskId;
183
186
  const correlationId = process.env.SPINE_LANE_CORRELATION_ID;
184
187
  // Let the host poll once before checkpoint signals land.
185
188
  spawnSync("sleep", ["1"], { stdio: "ignore" });
@@ -257,11 +260,8 @@ async function runWorkerRunner() {
257
260
  await enforceStubReviewIfConfigured(taskFolder, worktreePath);
258
261
 
259
262
  const donePath = path.join(taskFolder, ".DONE");
260
- fs.writeFileSync(
261
- donePath,
262
- `Completed: ${new Date().toISOString()}\nTask: stub\n`,
263
- "utf-8",
264
- );
263
+ const stubTaskId = process.env.SPINE_TASK_ID || taskIdFromFolder(taskFolder) || "stub";
264
+ writeWorkerDoneMarker(donePath, { taskId: stubTaskId });
265
265
  process.exit(0);
266
266
  }
267
267
 
package/bin/spine.mjs CHANGED
@@ -33,6 +33,10 @@ import {
33
33
  WARN,
34
34
  } from "./spine-cli/shared.mjs";
35
35
  import { handleStatus } from "./spine-cli/status.mjs";
36
+ import { handleLane } from "./spine-cli/lane-logs.mjs";
37
+ import { handleWatch } from "./spine-cli/watch.mjs";
38
+ import { handleWait } from "./spine-cli/wait.mjs";
39
+ import { handleScenarios } from "./spine-cli/scenarios.mjs";
36
40
  import { loadSpineConfig } from "./spine-config.mjs";
37
41
  import { cmdInit, SPINE_GITIGNORE_ENTRIES } from "./spine-init.mjs";
38
42
  import { cmdMigrateFromTaskplane } from "./spine-migrate-from-taskplane.mjs";
@@ -58,6 +62,15 @@ async function cmdPreflight(args) {
58
62
  }
59
63
 
60
64
  async function cmdJournal(args) {
65
+ const subcommand = args[0];
66
+ if (subcommand === "follow") {
67
+ const { runJournalFollow } = await import("../src/cli/journal-follow.mjs");
68
+ const result = await runJournalFollow({ projectRoot: process.cwd(), args: args.slice(1) });
69
+ process.stdout.write(result.output);
70
+ if (result.exitCode !== 0) process.exit(result.exitCode);
71
+ return;
72
+ }
73
+
61
74
  const { runSpineJournal } = await import("./spine-journal.mjs");
62
75
  const result = runSpineJournal({ projectRoot: process.cwd(), args });
63
76
  process.stdout.write(result.output);
@@ -131,6 +144,13 @@ async function cmdHandoff(args) {
131
144
  if (result.exitCode !== 0) process.exit(result.exitCode);
132
145
  }
133
146
 
147
+ async function cmdIssue(args) {
148
+ const { runSpineIssue } = await import("./spine-issue.mjs");
149
+ const result = runSpineIssue({ projectRoot: process.cwd(), args });
150
+ process.stdout.write(result.output ?? "");
151
+ if (result.exitCode !== 0) process.exit(result.exitCode);
152
+ }
153
+
134
154
  async function cmdMetrics(args) {
135
155
  const sub = args[0];
136
156
  if (sub !== "show") {
@@ -232,9 +252,12 @@ ${c.bold}Commands:${c.reset}
232
252
  ${c.cyan}settings${c.reset} Show or set editable spine-config fields (FR-CFG-03)
233
253
  ${c.cyan}rules${c.reset} Discover, select, and sync Cursor rules manifest
234
254
  ${c.cyan}status${c.reset} Reconciled batch diagnosis and lane health (FR-BATCH-14)
255
+ ${c.cyan}watch${c.reset} Poll reconcile loop for live batch monitoring (#44)
256
+ ${c.cyan}wait${c.reset} Block until diagnosis reaches target set (#46)
235
257
  ${c.cyan}batch${c.reset} Start, dismiss, or complete batch (Phase 2 start)
236
- ${c.cyan}run${c.reset} Start batch (alias for batch start; PRD §15.2)
258
+ ${c.cyan}run${c.reset} Start batch or planner wave sequence (PRD §15.2, #54)
237
259
  ${c.cyan}handoff${c.reset} Write operator handoff note (FR-UXB-05)
260
+ ${c.cyan}issue draft${c.reset} Build GitHub issue draft from project state (#60)
238
261
  ${c.cyan}metrics${c.reset} Show run metrics JSONL (FR-UXB-06)
239
262
  ${c.cyan}review step${c.reset} Spawn reviewer for a task step (FR-REV)
240
263
  ${c.cyan}report progress${c.reset} Emit task.step_completed to batch journal (FR-WORK-09)
@@ -246,6 +269,7 @@ ${c.bold}Commands:${c.reset}
246
269
  ${c.cyan}next${c.reset} Print or execute suggested next command (dry-run default)
247
270
  ${c.cyan}dashboard${c.reset} Local SSE dashboard (default http://127.0.0.1:8109)
248
271
  ${c.cyan}tasks${c.reset} Validate task PROMPT packets (FR-UXB-02)
272
+ ${c.cyan}scenarios${c.reset} List, show, and materialize scenario fixtures
249
273
  ${c.cyan}version${c.reset} Show version information
250
274
  ${c.cyan}help${c.reset} Show this help message
251
275
 
@@ -270,6 +294,9 @@ ${c.bold}Examples:${c.reset}
270
294
  spine doctor # check installation health
271
295
  spine preflight # verify batch readiness
272
296
  spine status --diagnose # reconciled batch diagnosis
297
+ spine watch # compact live reconcile poll (5s default)
298
+ spine watch --json --once # one NDJSON snapshot for scripts
299
+ spine wait --until completed,failed --timeout 2h # CI: block until terminal diagnosis
273
300
  spine deps all # show dependency graph
274
301
  spine deps TP-031 --json # JSON graph for one task scope
275
302
  spine settings show # list editable config fields
@@ -282,9 +309,12 @@ ${c.bold}Examples:${c.reset}
282
309
  spine batch start TP-012 # detached batch engine (default)
283
310
  spine batch start TP-012 --attached # foreground batch engine
284
311
  spine run pending --dry-run # run unfinished tasks (alias for batch start)
312
+ spine run sequence pending --dry-run # print wave-by-wave land loop commands (#54)
313
+ spine run sequence pending --from-wave 1 # resume sequence from planner wave 1
285
314
  spine batch dismiss --reason limbo-recovery # archive and clear stale batch
286
315
  spine batch complete --detect-manual-merge # complete after manual git merge
287
316
  spine handoff [--batch ID] [--json] # operator handoff note
317
+ spine issue draft [--type bug] [--json] # GitHub issue draft from diagnose state
288
318
  spine metrics show [--batch ID] [--last N] # read run-metrics.jsonl
289
319
  spine review step --step N [--type plan|code|final] # step or final review
290
320
  spine report progress --step N # journal step progress (worker shell-out)
@@ -301,6 +331,9 @@ ${c.bold}Examples:${c.reset}
301
331
  spine tasks analyze pending # structural checks (overlap, cycles, warnings)
302
332
  spine tasks analyze pending --json # structured AnalyzeTasksResult
303
333
  spine help tasks # tasks subcommand usage
334
+ spine scenarios list # list registered scenario fixtures
335
+ spine scenarios show orphan-running-resume # show one scenario entry
336
+ spine scenarios materialize orphan-running-resume --target . # write batch-state + journal
304
337
  spine version # show package and environment info
305
338
  `);
306
339
  }
@@ -337,9 +370,18 @@ if (isCliEntrypoint(import.meta.url)) {
337
370
  case "tasks":
338
371
  await cmdTasks(args);
339
372
  break;
373
+ case "scenarios":
374
+ await handleScenarios(args);
375
+ break;
340
376
  case "status":
341
377
  await handleStatus(args);
342
378
  break;
379
+ case "watch":
380
+ await handleWatch(args);
381
+ break;
382
+ case "wait":
383
+ await handleWait(args);
384
+ break;
343
385
  case "batch":
344
386
  await handleBatch(args);
345
387
  break;
@@ -349,6 +391,9 @@ if (isCliEntrypoint(import.meta.url)) {
349
391
  case "journal":
350
392
  await cmdJournal(args);
351
393
  break;
394
+ case "lane":
395
+ await handleLane(args);
396
+ break;
352
397
  case "state":
353
398
  await cmdState(args);
354
399
  break;
@@ -361,6 +406,9 @@ if (isCliEntrypoint(import.meta.url)) {
361
406
  case "handoff":
362
407
  await cmdHandoff(args);
363
408
  break;
409
+ case "issue":
410
+ await cmdIssue(args);
411
+ break;
364
412
  case "metrics":
365
413
  await cmdMetrics(args);
366
414
  break;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-spine",
3
- "version": "1.1.0",
3
+ "version": "1.2.0",
4
4
  "description": "Orchestration spine for long-running pi development",
5
5
  "keywords": [
6
6
  "pi-package",
@@ -33,6 +33,8 @@ Normative schema: [PRD v2.0 implementation handoff §4](../../docs/PRD-v2.0-impl
33
33
  | `fileScopeMustNotChange` | When parallel tasks must not collide | Comma-separated paths/globs |
34
34
  | `minLineCoverage` | When task changes application code | Integer 0–100 (pi-spine policy: **77**) |
35
35
  | `artifactsMustExist` | When deliverables must exist on disk | Comma-separated file paths |
36
+ | `stallTimeoutMinutes` | Long external jobs (operator matrix, CI arms) exceeding global/size stall budget | Positive integer minutes; engine uses `max(global, size floor, contract)` |
37
+ | `extendGraceOnFileScope` | STATUS-only progress during long external work | `true` or `false`; when `true`, file-scope mtime extends stall grace for this task |
36
38
 
37
39
  Unknown field names produce **warnings** at validate time (not errors). Duplicate rows are errors.
38
40
 
@@ -85,6 +87,23 @@ Unknown field names produce **warnings** at validate time (not errors). Duplicat
85
87
  | artifactsMustExist | `tests/batch/final-verdict.test.mjs` |
86
88
  ```
87
89
 
90
+ ### Operator matrix / long external job (SP-314)
91
+
92
+ Use when a task runs a multi-hour external matrix or CI arm with little in-repo checkpoint progress (only `STATUS.md` edits). Per-task override avoids raising global `lanes.stallTimeoutMinutes` for the whole batch.
93
+
94
+ ```markdown
95
+ ## Contract
96
+
97
+ | Field | Value |
98
+ |-------|-------|
99
+ | testCommand | `npm run typecheck && SPINE_WORKER_STUB=1 npm test` |
100
+ | stallTimeoutMinutes | 240 |
101
+ | extendGraceOnFileScope | true |
102
+ | fileScopeMustChange | `spine-tasks/SP-029-*/STATUS.md` |
103
+ ```
104
+
105
+ Recommended: **240** minutes for jobs expected to run 2+ hours. Size S floor (90m) and global default (120m) are additive floors; contract value wins when higher.
106
+
88
107
  ---
89
108
 
90
109
  ## Validate before plan
@@ -10,6 +10,7 @@ import { appendJournalEvent, journalPath, readJournalEvents, readJournalTail } f
10
10
  import { loadBatchStateFile } from "./reconcile.mjs";
11
11
  import { appendBatchHistoryEntry } from "./state.mjs";
12
12
  import { removeLaneWorktree } from "./worktree.mjs";
13
+ import { terminateLaneWorkers } from "./worker-host.mjs";
13
14
 
14
15
  /**
15
16
  * @param {string} projectRoot
@@ -79,17 +80,7 @@ function clearActiveBatchState(batchStatePath) {
79
80
  * @param {boolean} hard
80
81
  */
81
82
  function killLaneWorkers(lanes, hard) {
82
- const signal = hard ? "SIGKILL" : "SIGTERM";
83
- for (const lane of lanes ?? []) {
84
- if (!lane || typeof lane !== "object") continue;
85
- const pid = Number(/** @type {{ workerPid?: number }} */ (lane).workerPid);
86
- if (!Number.isFinite(pid) || pid <= 0) continue;
87
- try {
88
- process.kill(pid, signal);
89
- } catch {
90
- // process may already be gone
91
- }
92
- }
83
+ terminateLaneWorkers(lanes, { hard });
93
84
  }
94
85
 
95
86
  /**
@@ -7,8 +7,22 @@ import path from "node:path";
7
7
  import { appendJournalEvent } from "./journal.mjs";
8
8
  import { resolvePiSpineRoot } from "../config/pi-spine-root.mjs";
9
9
  import { readReviewLevel } from "./review.mjs";
10
+ import { writeWorkerDoneMarker, createWorkerLiveLogWriter } from "./worker-output.mjs";
10
11
  import { buildWorkerTailPrompt } from "./worker-prompt.mjs";
11
12
 
13
+ const LIVE_LOG_FLUSH_INTERVAL_MS = 2_000;
14
+
15
+ /**
16
+ * @param {string} taskFolder
17
+ */
18
+ function resolveTaskIdFromFolder(taskFolder) {
19
+ return (
20
+ process.env.SPINE_TASK_ID ||
21
+ path.basename(taskFolder).match(/^([A-Z]+-\d+)/)?.[1] ||
22
+ "unknown"
23
+ );
24
+ }
25
+
12
26
  /**
13
27
  * @param {object} params
14
28
  * @param {string} params.worktreePath
@@ -74,11 +88,7 @@ export function createStubAgentSession({ worktreePath, taskFolder, fail = false
74
88
  "utf-8",
75
89
  );
76
90
  }
77
- fs.writeFileSync(
78
- donePath,
79
- `Completed: ${new Date().toISOString()}\nTask: agent-session-stub\n`,
80
- "utf-8",
81
- );
91
+ writeWorkerDoneMarker(donePath, { taskId: resolveTaskIdFromFolder(taskFolder) });
82
92
  streaming = false;
83
93
  },
84
94
  subscribe: () => () => {},
@@ -184,6 +194,31 @@ export function startAgentSessionWorker(
184
194
  const piSpineRoot = resolvePiSpineRoot(config, projectRoot ?? process.cwd());
185
195
  process.env.PI_SPINE_ROOT = piSpineRoot;
186
196
 
197
+ const liveLogWriter = createWorkerLiveLogWriter({
198
+ projectRoot: journal?.projectRoot ?? projectRoot,
199
+ batchId: journal?.batchId ?? process.env.SPINE_BATCH_ID,
200
+ laneNumber:
201
+ journal?.laneNumber ??
202
+ (process.env.SPINE_LANE_NUMBER ? Number(process.env.SPINE_LANE_NUMBER) : undefined),
203
+ taskId: journal?.taskId ?? process.env.SPINE_TASK_ID ?? resolveTaskIdFromFolder(taskFolder),
204
+ config,
205
+ });
206
+ let lastFlushedTranscriptLength = 0;
207
+ /** @type {ReturnType<typeof setInterval> | null} */
208
+ let liveLogFlushTimer = null;
209
+
210
+ const flushTranscriptToLiveLog = () => {
211
+ if (!liveLogWriter) return;
212
+ const delta = state.transcript.slice(lastFlushedTranscriptLength);
213
+ if (!delta) return;
214
+ liveLogWriter.append(delta);
215
+ lastFlushedTranscriptLength = state.transcript.length;
216
+ };
217
+
218
+ if (liveLogWriter) {
219
+ liveLogFlushTimer = setInterval(flushTranscriptToLiveLog, LIVE_LOG_FLUSH_INTERVAL_MS);
220
+ }
221
+
187
222
  const donePromise = (async () => {
188
223
  try {
189
224
  const createAgentSession = await loadCreateAgentSession(deps);
@@ -258,6 +293,11 @@ export function startAgentSessionWorker(
258
293
  err instanceof Error ? err.message : String(err),
259
294
  );
260
295
  } finally {
296
+ if (liveLogFlushTimer) {
297
+ clearInterval(liveLogFlushTimer);
298
+ liveLogFlushTimer = null;
299
+ }
300
+ flushTranscriptToLiveLog();
261
301
  state.session?.dispose?.();
262
302
  state.session = null;
263
303
  }