pi-spine 1.0.2 → 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 (129) hide show
  1. package/README.md +61 -489
  2. package/bin/get-version.mjs +1 -13
  3. package/bin/spine-batch.mjs +162 -51
  4. package/bin/spine-cli/batch.mjs +3 -3
  5. package/bin/spine-cli/lane-logs.mjs +24 -0
  6. package/bin/spine-cli/scenarios.mjs +298 -0
  7. package/bin/spine-cli/wait.mjs +30 -0
  8. package/bin/spine-cli/watch.mjs +27 -0
  9. package/bin/spine-config.mjs +1 -212
  10. package/bin/spine-doctor.mjs +2 -418
  11. package/bin/spine-init.mjs +1 -398
  12. package/bin/spine-issue.mjs +196 -0
  13. package/bin/spine-journal.mjs +1 -0
  14. package/bin/spine-preflight.mjs +1 -700
  15. package/bin/spine-review-step.mjs +6 -4
  16. package/bin/spine-run.mjs +30 -0
  17. package/bin/spine-status.mjs +19 -1
  18. package/bin/spine-tasks.mjs +112 -13
  19. package/bin/spine-worker-runner.mjs +24 -14
  20. package/bin/spine.mjs +52 -2
  21. package/extensions/spine/worker-tools.ts +14 -12
  22. package/package.json +5 -2
  23. package/skills/create-spine-tasks/SKILL.md +135 -6
  24. package/skills/create-spine-tasks/references/clarify-template.md +73 -0
  25. package/skills/create-spine-tasks/references/contract-template.md +19 -0
  26. package/skills/create-spine-tasks/references/prompt-template.md +2 -0
  27. package/skills/create-spine-tasks/references/requirements-checklist-template.md +94 -0
  28. package/src/batch/abort.mjs +3 -12
  29. package/src/batch/agent-session-worker.mjs +45 -5
  30. package/src/batch/attached-engine-handoff.mjs +188 -0
  31. package/src/batch/attached-runner.mjs +312 -0
  32. package/src/batch/contract-prelanded.mjs +180 -0
  33. package/src/batch/contract-verify.mjs +140 -2
  34. package/src/batch/detached-start.mjs +105 -7
  35. package/src/batch/diagnosis-alternatives.mjs +46 -0
  36. package/src/batch/diagnosis-merge-failure.mjs +79 -0
  37. package/src/batch/diagnosis-retry-limbo.mjs +34 -0
  38. package/src/batch/diagnosis-stub.mjs +109 -0
  39. package/src/batch/diagnosis-task-done.mjs +110 -0
  40. package/src/batch/diagnosis-worker-done-missing.mjs +96 -0
  41. package/src/batch/diagnosis.mjs +174 -62
  42. package/src/batch/engine-lanes/merge.mjs +168 -77
  43. package/src/batch/engine-lanes/queue.mjs +4 -1
  44. package/src/batch/engine-lanes/review.mjs +32 -74
  45. package/src/batch/engine-lanes/watch.mjs +29 -0
  46. package/src/batch/engine-lanes.mjs +1 -0
  47. package/src/batch/engine-scope.mjs +42 -5
  48. package/src/batch/engine.mjs +115 -68
  49. package/src/batch/evidence.mjs +81 -17
  50. package/src/batch/gate.mjs +46 -17
  51. package/src/batch/git-helpers.mjs +96 -0
  52. package/src/batch/heartbeat.mjs +73 -7
  53. package/src/batch/integrate.mjs +3 -5
  54. package/src/batch/journal.mjs +25 -0
  55. package/src/batch/lane-commit.mjs +90 -5
  56. package/src/batch/lifecycle.mjs +131 -4
  57. package/src/batch/macro-phase.mjs +226 -0
  58. package/src/batch/merge/adoption-doc-merge.mjs +243 -0
  59. package/src/batch/merge/wave-merge-state.mjs +108 -0
  60. package/src/batch/metrics.mjs +74 -5
  61. package/src/batch/orphan-detect.mjs +74 -0
  62. package/src/batch/pause.mjs +223 -0
  63. package/src/batch/post-merge-limbo.mjs +345 -17
  64. package/src/batch/reconcile.mjs +473 -50
  65. package/src/batch/resume-common.mjs +6 -2
  66. package/src/batch/resume-engine.mjs +58 -1
  67. package/src/batch/resume-lane-reviews.mjs +16 -0
  68. package/src/batch/resume-multi-lanes.mjs +56 -1
  69. package/src/batch/resume-multi-validate.mjs +148 -8
  70. package/src/batch/resume-multi.mjs +45 -44
  71. package/src/batch/resume.mjs +64 -47
  72. package/src/batch/retry.mjs +56 -5
  73. package/src/batch/review-shared.mjs +196 -0
  74. package/src/batch/review-spawn.mjs +326 -0
  75. package/src/batch/review.mjs +178 -212
  76. package/src/batch/rules-manifest-drift.mjs +157 -0
  77. package/src/batch/salvage.mjs +2 -1
  78. package/src/batch/sequence.mjs +454 -0
  79. package/src/batch/state.mjs +18 -3
  80. package/src/batch/status-json.mjs +67 -0
  81. package/src/batch/task-stall-budget.mjs +94 -10
  82. package/src/batch/worker-host.mjs +185 -37
  83. package/src/batch/worker-output.mjs +196 -3
  84. package/src/batch/worktree.mjs +10 -0
  85. package/src/cli/handoff.mjs +1 -1
  86. package/src/cli/issue-draft.mjs +180 -0
  87. package/src/cli/journal-follow.mjs +239 -0
  88. package/src/cli/lane-logs.mjs +291 -0
  89. package/src/cli/rules.mjs +1 -1
  90. package/src/cli/sequence.mjs +108 -0
  91. package/src/cli/settings-set.mjs +3 -22
  92. package/src/cli/settings-slash.mjs +27 -5
  93. package/src/cli/wait.mjs +187 -0
  94. package/src/cli/watch.mjs +160 -0
  95. package/src/config/agent-model-resolve.mjs +48 -0
  96. package/src/config/cursor-rules/discover.mjs +3 -21
  97. package/src/config/defaults.mjs +7 -1
  98. package/src/config/settings-fields.mjs +48 -0
  99. package/src/config/spine-config-load.mjs +221 -0
  100. package/src/config/spine-init-constants.mjs +424 -0
  101. package/src/config/spine-preflight-lib.mjs +1180 -0
  102. package/src/dashboard/lane-throughput.mjs +351 -0
  103. package/src/dashboard/public/dashboard.css +25 -1
  104. package/src/dashboard/public/dashboard.js +224 -40
  105. package/src/dashboard/public/index.html +15 -9
  106. package/src/dashboard/server.mjs +4 -0
  107. package/src/dashboard/snapshot.mjs +387 -6
  108. package/src/dashboard/view.mjs +170 -15
  109. package/src/doctor/agent-model-inherit.mjs +61 -6
  110. package/src/doctor/run-doctor-checks.mjs +483 -0
  111. package/src/doctor/sequence-safety.mjs +57 -0
  112. package/src/doctor/stale-path.mjs +22 -0
  113. package/src/doctor/stale-worktrees.mjs +102 -0
  114. package/src/fixtures/scenario-registry.mjs +194 -0
  115. package/src/fs/atomic-write.mjs +49 -0
  116. package/src/migrate/taskplane-config.mjs +1 -1
  117. package/src/planner/file-scope.mjs +246 -0
  118. package/src/planner/format-plan.mjs +9 -7
  119. package/src/planner/index.mjs +6 -2
  120. package/src/planner/pending.mjs +92 -1
  121. package/src/planner/wave-scope.mjs +136 -0
  122. package/src/planner/waves.mjs +133 -0
  123. package/src/tasks/analyze/index.mjs +453 -0
  124. package/src/tasks/packet/index.mjs +1 -0
  125. package/src/tasks/packet/parse-prompt.mjs +42 -1
  126. package/src/tasks/packet/validate-prompt.mjs +124 -0
  127. package/src/util/command-exists.mjs +19 -0
  128. package/templates/docs/constitution.md +61 -0
  129. package/templates/spine-config.json +9 -2
@@ -0,0 +1,194 @@
1
+ /**
2
+ * Scenario fixture registry — central catalog for incident, stub, adoption, and recipe fixtures.
3
+ */
4
+
5
+ import fs from "node:fs";
6
+ import path from "node:path";
7
+
8
+ import { resolvePiSpineRoot } from "../config/pi-spine-root.mjs";
9
+
10
+ export const REGISTRY_SCHEMA_VERSION = 1;
11
+
12
+ /** @type {readonly string[]} */
13
+ export const SCENARIO_KINDS = Object.freeze([
14
+ "incident",
15
+ "stub",
16
+ "adoption",
17
+ "recipe",
18
+ ]);
19
+
20
+ const REGISTRY_RELATIVE_PATH = path.join("tests", "fixtures", "scenarios", "registry.json");
21
+
22
+ /**
23
+ * @param {string} [packageRoot]
24
+ * @returns {string}
25
+ */
26
+ export function resolveRegistryPath(packageRoot = resolvePiSpineRoot({}, process.cwd(), import.meta.url)) {
27
+ return path.join(packageRoot, REGISTRY_RELATIVE_PATH);
28
+ }
29
+
30
+ /**
31
+ * @param {{ packageRoot?: string }} [options]
32
+ * @returns {{ schemaVersion: number, scenarios: object[] }}
33
+ */
34
+ export function loadRegistry(options = {}) {
35
+ const packageRoot =
36
+ options.packageRoot ?? resolvePiSpineRoot({}, process.cwd(), import.meta.url);
37
+ const registryPath = resolveRegistryPath(packageRoot);
38
+ const raw = fs.readFileSync(registryPath, "utf-8");
39
+ return JSON.parse(raw);
40
+ }
41
+
42
+ /**
43
+ * @param {{ packageRoot?: string }} [options]
44
+ * @returns {object[]}
45
+ */
46
+ export function listScenarios(options = {}) {
47
+ const registry = loadRegistry(options);
48
+ return [...registry.scenarios].sort((left, right) =>
49
+ String(left.id).localeCompare(String(right.id)),
50
+ );
51
+ }
52
+
53
+ /**
54
+ * @param {string} id
55
+ * @param {{ packageRoot?: string }} [options]
56
+ * @returns {object | null}
57
+ */
58
+ export function getScenario(id, options = {}) {
59
+ const registry = loadRegistry(options);
60
+ return registry.scenarios.find((entry) => entry.id === id) ?? null;
61
+ }
62
+
63
+ /**
64
+ * @param {unknown} value
65
+ * @returns {value is string}
66
+ */
67
+ function isNonEmptyString(value) {
68
+ return typeof value === "string" && value.trim().length > 0;
69
+ }
70
+
71
+ /**
72
+ * @param {unknown} value
73
+ * @returns {value is string[]}
74
+ */
75
+ function isStringArray(value) {
76
+ return Array.isArray(value) && value.every((entry) => isNonEmptyString(entry));
77
+ }
78
+
79
+ /**
80
+ * @param {object} scenario
81
+ * @param {Set<string>} seenIds
82
+ * @param {{ packageRoot: string, checkFixturePaths: boolean }} context
83
+ * @returns {string[]}
84
+ */
85
+ function validateScenarioEntry(scenario, seenIds, context) {
86
+ /** @type {string[]} */
87
+ const errors = [];
88
+
89
+ if (!scenario || typeof scenario !== "object" || Array.isArray(scenario)) {
90
+ return ["scenario entry must be an object"];
91
+ }
92
+
93
+ if (!isNonEmptyString(scenario.id)) {
94
+ errors.push("scenario.id must be a non-empty string");
95
+ } else if (seenIds.has(scenario.id)) {
96
+ errors.push(`duplicate scenario id: ${scenario.id}`);
97
+ } else {
98
+ seenIds.add(scenario.id);
99
+ }
100
+
101
+ if (!isNonEmptyString(scenario.kind)) {
102
+ errors.push("scenario.kind must be a non-empty string");
103
+ } else if (!SCENARIO_KINDS.includes(scenario.kind)) {
104
+ errors.push(`scenario.kind must be one of: ${SCENARIO_KINDS.join(", ")}`);
105
+ }
106
+
107
+ if (!isNonEmptyString(scenario.title)) {
108
+ errors.push("scenario.title must be a non-empty string");
109
+ }
110
+
111
+ if (scenario.description != null && typeof scenario.description !== "string") {
112
+ errors.push("scenario.description must be a string when set");
113
+ }
114
+
115
+ const requiresFixturePath = scenario.kind === "incident" || scenario.kind === "stub" || scenario.kind === "adoption";
116
+ if (requiresFixturePath && !isNonEmptyString(scenario.fixturePath)) {
117
+ errors.push(`scenario.fixturePath is required for kind ${scenario.kind ?? "(missing)"}`);
118
+ }
119
+
120
+ if (scenario.fixturePath != null && !isNonEmptyString(scenario.fixturePath)) {
121
+ errors.push("scenario.fixturePath must be a non-empty string when set");
122
+ }
123
+
124
+ if (scenario.batchId != null && !isNonEmptyString(scenario.batchId)) {
125
+ errors.push("scenario.batchId must be a non-empty string when set");
126
+ }
127
+
128
+ for (const field of ["tests", "docs", "relatedTasks", "tags"]) {
129
+ if (scenario[field] != null && !isStringArray(scenario[field])) {
130
+ errors.push(`scenario.${field} must be an array of non-empty strings when set`);
131
+ }
132
+ }
133
+
134
+ if (
135
+ context.checkFixturePaths &&
136
+ isNonEmptyString(scenario.fixturePath) &&
137
+ isNonEmptyString(scenario.id)
138
+ ) {
139
+ const fixturePath = path.join(context.packageRoot, scenario.fixturePath);
140
+ if (!fs.existsSync(fixturePath)) {
141
+ errors.push(`scenario.fixturePath does not exist: ${scenario.fixturePath}`);
142
+ }
143
+ }
144
+
145
+ return errors;
146
+ }
147
+
148
+ /**
149
+ * @param {object} registry
150
+ * @param {{ packageRoot?: string, checkFixturePaths?: boolean }} [options]
151
+ * @returns {{ ok: boolean, errors: string[] }}
152
+ */
153
+ export function validateRegistry(registry, options = {}) {
154
+ const packageRoot =
155
+ options.packageRoot ?? resolvePiSpineRoot({}, process.cwd(), import.meta.url);
156
+ const checkFixturePaths = options.checkFixturePaths ?? true;
157
+ /** @type {string[]} */
158
+ const errors = [];
159
+
160
+ if (!registry || typeof registry !== "object" || Array.isArray(registry)) {
161
+ return { ok: false, errors: ["registry must be an object"] };
162
+ }
163
+
164
+ if (registry.schemaVersion !== REGISTRY_SCHEMA_VERSION) {
165
+ errors.push(`schemaVersion must be ${REGISTRY_SCHEMA_VERSION}`);
166
+ }
167
+
168
+ if (!Array.isArray(registry.scenarios)) {
169
+ errors.push("scenarios must be an array");
170
+ return { ok: errors.length === 0, errors };
171
+ }
172
+
173
+ const seenIds = new Set();
174
+ for (const scenario of registry.scenarios) {
175
+ const prefix = isNonEmptyString(scenario?.id) ? `scenario ${scenario.id}:` : "scenario:";
176
+ for (const issue of validateScenarioEntry(scenario, seenIds, {
177
+ packageRoot,
178
+ checkFixturePaths,
179
+ })) {
180
+ errors.push(`${prefix} ${issue}`);
181
+ }
182
+ }
183
+
184
+ return { ok: errors.length === 0, errors };
185
+ }
186
+
187
+ /**
188
+ * Resolve package root from this module location (for tests and CLI callers).
189
+ *
190
+ * @returns {string}
191
+ */
192
+ export function scenarioRegistryPackageRoot() {
193
+ return resolvePiSpineRoot({}, process.cwd(), import.meta.url);
194
+ }
@@ -0,0 +1,49 @@
1
+ /**
2
+ * Atomic file writes via temp file + rename (orchestration artifact persistence).
3
+ */
4
+
5
+ import fs from "node:fs";
6
+ import path from "node:path";
7
+ import { randomBytes } from "node:crypto";
8
+
9
+ /**
10
+ * @param {string} targetPath
11
+ * @returns {string}
12
+ */
13
+ export function makeAtomicTempPath(targetPath) {
14
+ return `${targetPath}.${process.pid}.${randomBytes(4).toString("hex")}.tmp`;
15
+ }
16
+
17
+ /**
18
+ * @param {string} filePath
19
+ * @param {string} content
20
+ */
21
+ export function writeTextAtomic(filePath, content) {
22
+ const dir = path.dirname(filePath);
23
+ fs.mkdirSync(dir, { recursive: true });
24
+
25
+ const tmpPath = makeAtomicTempPath(filePath);
26
+
27
+ try {
28
+ fs.writeFileSync(tmpPath, content, "utf-8");
29
+ fs.renameSync(tmpPath, filePath);
30
+ } catch (err) {
31
+ try {
32
+ if (fs.existsSync(tmpPath)) {
33
+ fs.unlinkSync(tmpPath);
34
+ }
35
+ } catch {
36
+ // ignore cleanup failure
37
+ }
38
+ throw err;
39
+ }
40
+ }
41
+
42
+ /**
43
+ * @param {string} filePath
44
+ * @param {unknown} data
45
+ */
46
+ export function writeJsonAtomic(filePath, data) {
47
+ const content = `${JSON.stringify(data, null, 2)}\n`;
48
+ writeTextAtomic(filePath, content);
49
+ }
@@ -1,5 +1,5 @@
1
1
  import fs from "node:fs";
2
- import { loadSpineConfigTemplate } from "../../bin/spine-init.mjs";
2
+ import { loadSpineConfigTemplate } from "../config/spine-init-constants.mjs";
3
3
 
4
4
  export const DEFAULT_TASKPLANE_SOURCE_PATH = ".pi/taskplane-config.json";
5
5
  export const defaultTaskplaneSourcePath = DEFAULT_TASKPLANE_SOURCE_PATH;
@@ -0,0 +1,246 @@
1
+ /**
2
+ * File Scope overlap detection for wave planner (SP-352 / issue #31).
3
+ *
4
+ * Detects when two tasks' ## File Scope globs could touch the same paths so
5
+ * parallel lane assignment would risk merge conflicts.
6
+ */
7
+
8
+ import micromatch from 'micromatch';
9
+
10
+ /** Synthetic basename used when expanding globs into concrete probe paths. */
11
+ const PROBE_BASENAME = '__probe__';
12
+
13
+ /** Extensions probed when expanding directory or wildcard scope entries. */
14
+ const SYNTHETIC_PROBE_EXTENSIONS = Object.freeze([
15
+ '.mjs',
16
+ '.js',
17
+ '.ts',
18
+ '.tsx',
19
+ '.swift',
20
+ '.py',
21
+ '.go',
22
+ '.java',
23
+ '.rs',
24
+ '.md',
25
+ ]);
26
+
27
+ /**
28
+ * @param {string} raw: raw File Scope path or glob from PROMPT.md
29
+ * @returns {string|null}
30
+ */
31
+ export function normalizeFileScopePath(raw) {
32
+ let s = String(raw ?? '').trim();
33
+ if (!s) return null;
34
+
35
+ s = s.replace(/\\/g, '/');
36
+ if (s.startsWith('./')) s = s.slice(2);
37
+ s = s.replace(/\/+$/g, '');
38
+
39
+ // Directory-style globs are treated as path prefixes for overlap checks.
40
+ if (s.endsWith('/*')) s = s.slice(0, -2);
41
+ if (s.endsWith('/**')) s = s.slice(0, -3);
42
+
43
+ return s || null;
44
+ }
45
+
46
+ /**
47
+ * True when normalized paths share a directory prefix or are equal.
48
+ *
49
+ * @param {string} a
50
+ * @param {string} b
51
+ * @returns {boolean}
52
+ */
53
+ export function pathsOverlap(a, b) {
54
+ if (a === b) return true;
55
+ // Only treat directory-prefix matches; a file prefix without a slash should not match.
56
+ return a.startsWith(b + '/') || b.startsWith(a + '/');
57
+ }
58
+
59
+ /**
60
+ * @param {string} raw
61
+ * @returns {string}
62
+ */
63
+ function normalizeScopeEntry(raw) {
64
+ return String(raw ?? '').trim().replace(/\\/g, '/').replace(/^\.\/+/, '');
65
+ }
66
+
67
+ /**
68
+ * Expand a single File Scope entry into concrete paths for glob overlap probes.
69
+ *
70
+ * @param {string} raw
71
+ * @returns {string[]}
72
+ */
73
+ function expandScopeEntryProbes(raw) {
74
+ const entry = normalizeScopeEntry(raw);
75
+ if (!entry) return [];
76
+
77
+ /** @type {Set<string>} */
78
+ const probes = new Set([entry]);
79
+
80
+ if (entry.endsWith('/**')) {
81
+ const base = entry.slice(0, -3);
82
+ for (const ext of SYNTHETIC_PROBE_EXTENSIONS) {
83
+ probes.add(`${base}/${PROBE_BASENAME}/${PROBE_BASENAME}${ext}`);
84
+ probes.add(`${base}/nested/${PROBE_BASENAME}${ext}`);
85
+ }
86
+ return [...probes];
87
+ }
88
+
89
+ if (entry.endsWith('/*')) {
90
+ const base = entry.slice(0, -2);
91
+ for (const ext of SYNTHETIC_PROBE_EXTENSIONS) {
92
+ probes.add(`${base}/${PROBE_BASENAME}${ext}`);
93
+ }
94
+ return [...probes];
95
+ }
96
+
97
+ if (/[*?[\\]/.test(entry)) {
98
+ probes.add(entry.replace(/\*/g, PROBE_BASENAME).replace(/\?/g, 'x'));
99
+ return [...probes];
100
+ }
101
+
102
+ const baseName = entry.split('/').pop() ?? '';
103
+ if (!/\.\w[\w\d]*$/.test(baseName)) {
104
+ for (const ext of SYNTHETIC_PROBE_EXTENSIONS) {
105
+ probes.add(`${entry}/${PROBE_BASENAME}${ext}`);
106
+ }
107
+ }
108
+
109
+ return [...probes];
110
+ }
111
+
112
+ /**
113
+ * @param {string[]} fileScope
114
+ * @returns {string[]}
115
+ */
116
+ export function expandFileScopeProbes(fileScope) {
117
+ if (!Array.isArray(fileScope) || fileScope.length === 0) {
118
+ return [];
119
+ }
120
+
121
+ /** @type {Set<string>} */
122
+ const probes = new Set();
123
+
124
+ for (const raw of fileScope) {
125
+ for (const probe of expandScopeEntryProbes(raw)) {
126
+ probes.add(probe);
127
+ }
128
+ }
129
+
130
+ return [...probes];
131
+ }
132
+
133
+ /**
134
+ * @param {string} pattern
135
+ * @returns {boolean}
136
+ */
137
+ function patternHasGlobMeta(pattern) {
138
+ return /[*?[\\]/.test(pattern);
139
+ }
140
+
141
+ /**
142
+ * True when two File Scope patterns could match the same repository path.
143
+ *
144
+ * @param {string} leftPattern
145
+ * @param {string} rightPattern
146
+ * @returns {boolean}
147
+ */
148
+ export function fileScopePatternsOverlap(leftPattern, rightPattern) {
149
+ const leftEntry = normalizeScopeEntry(leftPattern);
150
+ const rightEntry = normalizeScopeEntry(rightPattern);
151
+ if (!leftEntry || !rightEntry) return false;
152
+
153
+ const leftPrefix = normalizeFileScopePath(leftPattern);
154
+ const rightPrefix = normalizeFileScopePath(rightPattern);
155
+ if (leftPrefix && rightPrefix && pathsOverlap(leftPrefix, rightPrefix)) {
156
+ return true;
157
+ }
158
+
159
+ const leftProbes = expandScopeEntryProbes(leftPattern);
160
+ const rightProbes = expandScopeEntryProbes(rightPattern);
161
+ const matchOpts = { dot: true };
162
+
163
+ for (const probe of leftProbes) {
164
+ if (micromatch.isMatch(probe, rightEntry, matchOpts)) return true;
165
+ }
166
+
167
+ for (const probe of rightProbes) {
168
+ if (micromatch.isMatch(probe, leftEntry, matchOpts)) return true;
169
+ }
170
+
171
+ if (!patternHasGlobMeta(leftEntry) && micromatch.isMatch(leftEntry, rightEntry, matchOpts)) {
172
+ return true;
173
+ }
174
+
175
+ if (!patternHasGlobMeta(rightEntry) && micromatch.isMatch(rightEntry, leftEntry, matchOpts)) {
176
+ return true;
177
+ }
178
+
179
+ return false;
180
+ }
181
+
182
+ /**
183
+ * @param {string[]} left
184
+ * @param {string[]} right
185
+ * @returns {boolean}
186
+ */
187
+ export function fileScopesOverlap(left, right) {
188
+ const leftPatterns = Array.isArray(left) ? left : [];
189
+ const rightPatterns = Array.isArray(right) ? right : [];
190
+
191
+ for (const a of leftPatterns) {
192
+ for (const b of rightPatterns) {
193
+ if (fileScopePatternsOverlap(a, b)) return true;
194
+ }
195
+ }
196
+
197
+ return false;
198
+ }
199
+
200
+ /**
201
+ * @typedef {{
202
+ * waveIndex: number,
203
+ * taskA: string,
204
+ * taskB: string,
205
+ * scopesA: string[],
206
+ * scopesB: string[],
207
+ * }} FileScopeOverlapPair
208
+ */
209
+
210
+ /**
211
+ * Find overlapping File Scope pairs among tasks scheduled in the same wave.
212
+ *
213
+ * @param {string[][]} waves
214
+ * @param {Record<string, { fileScope?: string[] }>} tasksById
215
+ * @returns {FileScopeOverlapPair[]}
216
+ */
217
+ export function findWaveFileScopeOverlaps(waves, tasksById) {
218
+ /** @type {FileScopeOverlapPair[]} */
219
+ const overlaps = [];
220
+
221
+ for (let waveIndex = 0; waveIndex < waves.length; waveIndex++) {
222
+ const waveTaskIds = waves[waveIndex];
223
+ if (waveTaskIds.length < 2) continue;
224
+
225
+ for (let i = 0; i < waveTaskIds.length; i++) {
226
+ for (let j = i + 1; j < waveTaskIds.length; j++) {
227
+ const taskA = waveTaskIds[i];
228
+ const taskB = waveTaskIds[j];
229
+ const scopesA = tasksById[taskA]?.fileScope ?? [];
230
+ const scopesB = tasksById[taskB]?.fileScope ?? [];
231
+
232
+ if (!fileScopesOverlap(scopesA, scopesB)) continue;
233
+
234
+ overlaps.push({
235
+ waveIndex,
236
+ taskA,
237
+ taskB,
238
+ scopesA: [...scopesA],
239
+ scopesB: [...scopesB],
240
+ });
241
+ }
242
+ }
243
+ }
244
+
245
+ return overlaps;
246
+ }
@@ -116,16 +116,18 @@ export function formatPlanHuman(plan) {
116
116
  lines.push("");
117
117
  }
118
118
 
119
- const firstWave = plan.waves?.[0];
120
- if (firstWave?.taskIds?.length) {
121
- lines.push(`Start: spine batch start ${firstWave.taskIds.join(" ")}`);
122
- }
119
+ const waves = plan.waves ?? [];
120
+ const firstWave = waves[0];
121
+ const multiWave = waves.length > 1;
123
122
 
124
- if ((plan.waves?.length ?? 0) > 1) {
123
+ if (multiWave && firstWave != null) {
124
+ lines.push(`Start: spine batch start ${mode} --wave ${firstWave.index}`);
125
125
  lines.push("Then (after each wave lands):");
126
- for (const wave of plan.waves.slice(1)) {
127
- lines.push(` Wave ${wave.index}: spine batch start ${wave.taskIds.join(" ")}`);
126
+ for (const wave of waves.slice(1)) {
127
+ lines.push(` Wave ${wave.index}: spine batch start ${mode} --wave ${wave.index}`);
128
128
  }
129
+ } else if (firstWave?.taskIds?.length) {
130
+ lines.push(`Start: spine batch start ${firstWave.taskIds.join(" ")}`);
129
131
  }
130
132
 
131
133
  return appendBatchSizeGuidanceToPlanOutput(`${lines.join("\n").trimEnd()}\n`, plan);
@@ -15,8 +15,8 @@ import {
15
15
 
16
16
  import { buildGraph, topoWaves } from './graph.mjs';
17
17
  import { findCyclePath } from './cycles.mjs';
18
- import { assignLanesToWaves } from './lanes.mjs';
19
18
  import { parseScope } from './scope.mjs';
19
+ import { formatFileScopeOverlapWarnings, planWaves } from './waves.mjs';
20
20
 
21
21
  /**
22
22
  * @param {{ scope?: any, config: { lanes?: { maxParallel?: number, queueExcess?: boolean } }, tasksRoot: string }} args
@@ -87,13 +87,15 @@ export function buildPlan({ scope, config, tasksRoot }) {
87
87
  const maxParallel = config.lanes?.maxParallel ?? 1;
88
88
  const queueExcess = config.lanes?.queueExcess ?? true;
89
89
 
90
- const wavesWithLanes = assignLanesToWaves({
90
+ const { waves: wavesWithLanes, fileScopeOverlaps } = planWaves({
91
91
  waves,
92
92
  tasksById,
93
93
  maxParallel,
94
94
  queueExcess,
95
95
  });
96
96
 
97
+ const overlapWarnings = formatFileScopeOverlapWarnings(fileScopeOverlaps);
98
+
97
99
  return {
98
100
  generatedAt: new Date().toISOString(),
99
101
  scope: {
@@ -120,6 +122,8 @@ export function buildPlan({ scope, config, tasksRoot }) {
120
122
  ...(scopeResult.mode === 'pending'
121
123
  ? { tasksExcluded: scopeResult.excludedCount ?? 0 }
122
124
  : {}),
125
+ ...(fileScopeOverlaps.length > 0 ? { fileScopeOverlaps } : {}),
123
126
  },
127
+ ...(overlapWarnings.length > 0 ? { overlapWarnings } : {}),
124
128
  };
125
129
  }
@@ -4,6 +4,7 @@
4
4
 
5
5
  import fs from "node:fs";
6
6
  import path from "node:path";
7
+ import { TASK_ID_RE } from "./scope.mjs";
7
8
 
8
9
  /**
9
10
  * @param {Array<{ taskId: string, folderPath: string }>} discoveredTasks
@@ -16,7 +17,8 @@ export function filterPendingTaskIds(discoveredTasks, tasksRoot) {
16
17
  for (const task of discoveredTasks) {
17
18
  const folderPath = task.folderPath ?? path.join(tasksRoot, `${task.taskId}-unknown`);
18
19
  const donePath = path.join(folderPath, ".DONE");
19
- if (!fs.existsSync(donePath)) {
20
+ const supersededPath = path.join(folderPath, ".SUPERSEDED");
21
+ if (!fs.existsSync(donePath) && !fs.existsSync(supersededPath)) {
20
22
  pending.push(task.taskId);
21
23
  }
22
24
  }
@@ -37,3 +39,92 @@ export function summarizePendingScope(discoveredTasks, tasksRoot) {
37
39
  excludedCount: allIds.length - pendingIds.length,
38
40
  };
39
41
  }
42
+
43
+ /**
44
+ * Parse replacement task IDs from a `.SUPERSEDED` marker body.
45
+ *
46
+ * @param {string} content
47
+ * @returns {string[]}
48
+ */
49
+ export function parseSupersededReplacementIds(content) {
50
+ const match = /Superseded by\s+([^\n]+)/i.exec(String(content ?? ""));
51
+ if (!match) return [];
52
+
53
+ return match[1]
54
+ .split(/[,;]+/)
55
+ .flatMap((segment) => segment.trim().split(/\s+/))
56
+ .map((token) => token.trim())
57
+ .filter((token) => TASK_ID_RE.test(token));
58
+ }
59
+
60
+ /**
61
+ * Fail closed when explicit batch start requests superseded task IDs.
62
+ *
63
+ * @param {string[]} taskIds
64
+ * @param {string} tasksRoot
65
+ * @param {Array<{ taskId: string, folderPath: string }>} discoveredTasks
66
+ * @param {{ forceSuperseded?: boolean }} [options]
67
+ */
68
+ export function assertBatchStartTasksNotSuperseded(
69
+ taskIds,
70
+ tasksRoot,
71
+ discoveredTasks,
72
+ options = {},
73
+ ) {
74
+ if (options.forceSuperseded) {
75
+ return { ok: true };
76
+ }
77
+
78
+ const folderById = new Map(
79
+ discoveredTasks.map((task) => [
80
+ task.taskId,
81
+ task.folderPath ?? path.join(tasksRoot, `${task.taskId}-unknown`),
82
+ ]),
83
+ );
84
+
85
+ /** @type {Array<{ taskId: string, replacements: string[] }>} */
86
+ const superseded = [];
87
+
88
+ for (const taskId of taskIds) {
89
+ const folderPath = folderById.get(taskId);
90
+ if (!folderPath) continue;
91
+
92
+ const supersededPath = path.join(folderPath, ".SUPERSEDED");
93
+ if (!fs.existsSync(supersededPath)) continue;
94
+
95
+ const content = fs.readFileSync(supersededPath, "utf-8");
96
+ superseded.push({
97
+ taskId,
98
+ replacements: parseSupersededReplacementIds(content),
99
+ });
100
+ }
101
+
102
+ if (superseded.length === 0) {
103
+ return { ok: true };
104
+ }
105
+
106
+ const lines = [
107
+ "Batch start rejected: requested task(s) are superseded (.SUPERSEDED marker present).",
108
+ "",
109
+ ];
110
+
111
+ for (const entry of superseded) {
112
+ const replacementHint =
113
+ entry.replacements.length > 0 ? ` → use ${entry.replacements.join(", ")}` : "";
114
+ lines.push(` ${entry.taskId}${replacementHint}`);
115
+ }
116
+
117
+ lines.push(
118
+ "",
119
+ "Prefer task IDs from: spine plan pending",
120
+ "To rerun superseded tasks deliberately: spine batch start <ids> --force-superseded",
121
+ "",
122
+ );
123
+
124
+ return {
125
+ ok: false,
126
+ error: "superseded_tasks",
127
+ output: lines.join("\n"),
128
+ supersededTaskIds: superseded.map((entry) => entry.taskId),
129
+ };
130
+ }