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,136 @@
1
+ /**
2
+ * Planner wave filtering for batch start (GitHub #54 Tier 1 SP-A).
3
+ */
4
+
5
+ /**
6
+ * @param {string[]} args
7
+ * @returns {{ waveFilter: number|null, error?: string, output?: string }}
8
+ */
9
+ export function parseBatchStartWaveFilter(args) {
10
+ const throughIdx = args.indexOf("--through-wave");
11
+ const waveIdx = args.indexOf("--wave");
12
+
13
+ if (throughIdx >= 0 && waveIdx >= 0) {
14
+ return {
15
+ waveFilter: null,
16
+ error: "conflicting_wave_flags",
17
+ output:
18
+ "Use either --wave N or --through-wave N for batch start, not both.\n",
19
+ };
20
+ }
21
+
22
+ const flagIdx = throughIdx >= 0 ? throughIdx : waveIdx;
23
+ if (flagIdx < 0) {
24
+ return { waveFilter: null };
25
+ }
26
+
27
+ const flagName = throughIdx >= 0 ? "--through-wave" : "--wave";
28
+ const raw = args[flagIdx + 1];
29
+ if (raw == null || raw.startsWith("--")) {
30
+ return {
31
+ waveFilter: null,
32
+ error: "wave_flag_missing_value",
33
+ output: `${flagName} requires a non-negative integer wave index.\n`,
34
+ };
35
+ }
36
+
37
+ const waveIndex = Number(raw);
38
+ if (!Number.isInteger(waveIndex) || waveIndex < 0) {
39
+ return {
40
+ waveFilter: null,
41
+ error: "wave_flag_invalid_value",
42
+ output: `${flagName} requires a non-negative integer wave index (got ${JSON.stringify(raw)}).\n`,
43
+ };
44
+ }
45
+
46
+ return { waveFilter: waveIndex };
47
+ }
48
+
49
+ /**
50
+ * @param {object} plan
51
+ * @param {number} waveIndex
52
+ */
53
+ export function resolveWaveTaskIds(plan, waveIndex) {
54
+ const waves = plan?.waves ?? [];
55
+ if (!Number.isInteger(waveIndex) || waveIndex < 0 || waveIndex >= waves.length) {
56
+ return {
57
+ ok: /** @type {const} */ (false),
58
+ error: "wave_out_of_range",
59
+ waveIndex,
60
+ waveCount: waves.length,
61
+ output: `Wave index ${waveIndex} is out of range (plan has ${waves.length} wave(s)).`,
62
+ };
63
+ }
64
+
65
+ const taskIds = [...(waves[waveIndex]?.taskIds ?? [])];
66
+ if (taskIds.length === 0) {
67
+ return {
68
+ ok: /** @type {const} */ (false),
69
+ error: "wave_empty",
70
+ waveIndex,
71
+ waveCount: waves.length,
72
+ output: `Planner wave ${waveIndex} has no tasks.`,
73
+ };
74
+ }
75
+
76
+ return { ok: /** @type {const} */ (true), waveIndex, taskIds, waveCount: waves.length };
77
+ }
78
+
79
+ /**
80
+ * Restrict a planner plan to a single wave for batch start.
81
+ *
82
+ * @param {object} plan
83
+ * @param {number} waveIndex
84
+ */
85
+ export function filterPlanToWave(plan, waveIndex) {
86
+ const resolved = resolveWaveTaskIds(plan, waveIndex);
87
+ if (!resolved.ok) {
88
+ return resolved;
89
+ }
90
+
91
+ const selectedWave = plan.waves?.[waveIndex];
92
+ if (!selectedWave) {
93
+ return {
94
+ ok: /** @type {const} */ (false),
95
+ error: "wave_missing",
96
+ waveIndex,
97
+ waveCount: resolved.waveCount,
98
+ output: `Planner wave ${waveIndex} is missing from plan.`,
99
+ };
100
+ }
101
+
102
+ /** @type {Record<string, object>} */
103
+ const filteredTasks = {};
104
+ for (const taskId of resolved.taskIds) {
105
+ if (plan.tasks?.[taskId]) {
106
+ filteredTasks[taskId] = plan.tasks[taskId];
107
+ }
108
+ }
109
+
110
+ const filteredWave = {
111
+ ...selectedWave,
112
+ index: 0,
113
+ taskIds: [...resolved.taskIds],
114
+ };
115
+
116
+ return {
117
+ ok: /** @type {const} */ (true),
118
+ waveIndex: resolved.waveIndex,
119
+ taskIds: resolved.taskIds,
120
+ waveCount: resolved.waveCount,
121
+ plan: {
122
+ ...plan,
123
+ scope: {
124
+ ...plan.scope,
125
+ taskIds: [...resolved.taskIds],
126
+ },
127
+ waves: [filteredWave],
128
+ tasks: filteredTasks,
129
+ metadata: {
130
+ ...plan.metadata,
131
+ tasksSelected: resolved.taskIds.length,
132
+ waveFilter: resolved.waveIndex,
133
+ },
134
+ },
135
+ };
136
+ }
@@ -0,0 +1,133 @@
1
+ /**
2
+ * Wave planning with file-scope overlap detection and lane serialization (SP-353 / issue #31).
3
+ */
4
+
5
+ import { fileScopesOverlap, findWaveFileScopeOverlaps } from './file-scope.mjs';
6
+
7
+ /**
8
+ * @param {string[]} taskScope
9
+ * @param {string[][]} laneTaskScopes
10
+ * @returns {boolean}
11
+ */
12
+ function taskOverlapsLane(taskScope, laneTaskScopes) {
13
+ for (const laneScope of laneTaskScopes) {
14
+ if (fileScopesOverlap(taskScope, laneScope)) return true;
15
+ }
16
+ return false;
17
+ }
18
+
19
+ /**
20
+ * Greedy lane packing using glob-aware overlap checks from file-scope.mjs.
21
+ *
22
+ * @param {{ waves: string[][], tasksById: Record<string, { fileScope?: string[] }>, maxParallel: number, queueExcess?: boolean }} args
23
+ * @returns {Array<{ index: number, taskIds: string[], virtualLaneCount: number, ticks: Array<{ index: number, lanes: string[][] }>, laneAssignments: Record<string, { virtualLane: number, tick: number, laneInTick: number }> }>}
24
+ */
25
+ export function assignLanesToWaves({ waves, tasksById, maxParallel, queueExcess = true }) {
26
+ const planned = [];
27
+
28
+ for (let waveIndex = 0; waveIndex < waves.length; waveIndex++) {
29
+ const waveTaskIds = waves[waveIndex];
30
+
31
+ /** @type {{ taskScopes: string[][] }} */
32
+ const virtualLanes = [];
33
+
34
+ /** @type {Record<string, { virtualLane: number, tick: number, laneInTick: number }>} */
35
+ const laneAssignments = {};
36
+
37
+ const virtualLaneForTask = {};
38
+
39
+ for (const taskId of waveTaskIds) {
40
+ const task = tasksById[taskId];
41
+ if (!task) {
42
+ throw new Error(`Missing task packet for ${taskId} during lane assignment`);
43
+ }
44
+
45
+ const taskScope = Array.isArray(task.fileScope) ? task.fileScope : [];
46
+
47
+ let placed = false;
48
+ for (let i = 0; i < virtualLanes.length; i++) {
49
+ const lane = virtualLanes[i];
50
+ if (taskOverlapsLane(taskScope, lane.taskScopes)) {
51
+ virtualLaneForTask[taskId] = i;
52
+ lane.taskScopes.push(taskScope);
53
+ placed = true;
54
+ break;
55
+ }
56
+ }
57
+
58
+ if (!placed) {
59
+ const i = virtualLanes.length;
60
+ virtualLanes.push({ taskScopes: [taskScope] });
61
+ virtualLaneForTask[taskId] = i;
62
+ }
63
+ }
64
+
65
+ const virtualLaneCount = virtualLanes.length;
66
+ const tickCount = queueExcess ? Math.ceil(virtualLaneCount / maxParallel) : 1;
67
+
68
+ const ticks = Array.from({ length: tickCount }, (_, t) => {
69
+ return {
70
+ index: t,
71
+ lanes: Array.from({ length: maxParallel }, () => []),
72
+ };
73
+ });
74
+
75
+ for (const taskId of waveTaskIds) {
76
+ const virtualLane = virtualLaneForTask[taskId];
77
+ const tick = queueExcess ? Math.floor(virtualLane / maxParallel) : 0;
78
+ const laneInTick = virtualLane % maxParallel;
79
+ laneAssignments[taskId] = { virtualLane, tick, laneInTick };
80
+ ticks[tick].lanes[laneInTick].push(taskId);
81
+ }
82
+
83
+ planned.push({
84
+ index: waveIndex,
85
+ taskIds: waveTaskIds,
86
+ virtualLaneCount,
87
+ ticks,
88
+ laneAssignments,
89
+ });
90
+ }
91
+
92
+ return planned;
93
+ }
94
+
95
+ /**
96
+ * @typedef {import('./file-scope.mjs').FileScopeOverlapPair} FileScopeOverlapPair
97
+ */
98
+
99
+ /**
100
+ * Detect same-wave file-scope overlaps and assign lanes that serialize conflicts.
101
+ *
102
+ * @param {{ waves: string[][], tasksById: Record<string, { fileScope?: string[] }>, maxParallel: number, queueExcess?: boolean }} args
103
+ * @returns {{ waves: ReturnType<typeof assignLanesToWaves>, fileScopeOverlaps: FileScopeOverlapPair[] }}
104
+ */
105
+ export function planWaves({ waves, tasksById, maxParallel, queueExcess = true }) {
106
+ const fileScopeOverlaps = findWaveFileScopeOverlaps(waves, tasksById);
107
+ const wavesWithLanes = assignLanesToWaves({
108
+ waves,
109
+ tasksById,
110
+ maxParallel,
111
+ queueExcess,
112
+ });
113
+
114
+ return { waves: wavesWithLanes, fileScopeOverlaps };
115
+ }
116
+
117
+ /**
118
+ * Human-readable overlap report lines for plan output consumers.
119
+ *
120
+ * @param {FileScopeOverlapPair[]} overlaps
121
+ * @returns {string[]}
122
+ */
123
+ export function formatFileScopeOverlapWarnings(overlaps) {
124
+ if (!Array.isArray(overlaps) || overlaps.length === 0) {
125
+ return [];
126
+ }
127
+
128
+ const lines = ['File scope overlaps (tasks serialized to the same lane):'];
129
+ for (const overlap of overlaps) {
130
+ lines.push(` Wave ${overlap.waveIndex}: ${overlap.taskA} ↔ ${overlap.taskB}`);
131
+ }
132
+ return lines;
133
+ }
@@ -0,0 +1,453 @@
1
+ /**
2
+ * Deterministic structural checks for task packets in a planner scope (SP-292/SP-298/SP-299).
3
+ *
4
+ * Blocking checks:
5
+ * - Parallel-eligible tasks (same wave) with overlapping ## File Scope
6
+ * - dependencies.json cycles or orphan task IDs
7
+ *
8
+ * Warning checks (SP-299):
9
+ * - Wave with more than four M-sized tasks
10
+ * - CONTEXT.md references explore findings.md that is missing
11
+ * - PROMPT ## Dependencies drift from dependencies.json
12
+ */
13
+
14
+ import fs from 'node:fs';
15
+ import path from 'node:path';
16
+
17
+ import { resolveTasksRootPath } from '../../config/env-overrides.mjs';
18
+ import { loadSpineConfig } from '../../config/spine-config-load.mjs';
19
+ import { findCyclePath } from '../../planner/cycles.mjs';
20
+ import { buildGraph, topoWaves } from '../../planner/graph.mjs';
21
+ import { parseScope } from '../../planner/scope.mjs';
22
+ import {
23
+ discoverTasks,
24
+ loadDependenciesJson,
25
+ loadTaskPacket,
26
+ mergeTaskDeps,
27
+ } from '../packet/index.mjs';
28
+
29
+ /** @typedef {'blocking' | 'warning'} AnalyzeSeverity */
30
+
31
+ /**
32
+ * @typedef {{
33
+ * severity: AnalyzeSeverity,
34
+ * code: string,
35
+ * message: string,
36
+ * taskIds?: string[],
37
+ * paths?: string[],
38
+ * cycle?: string[],
39
+ * }} AnalyzeFinding
40
+ */
41
+
42
+ function normalizeFileScopePath(p) {
43
+ let s = String(p ?? '').trim();
44
+ if (!s) return null;
45
+
46
+ s = s.replace(/\\/g, '/');
47
+ if (s.startsWith('./')) s = s.slice(2);
48
+ s = s.replace(/\/+$/g, '');
49
+
50
+ if (s.endsWith('/*')) s = s.slice(0, -2);
51
+ if (s.endsWith('/**')) s = s.slice(0, -3);
52
+
53
+ return s || null;
54
+ }
55
+
56
+ /**
57
+ * @param {string} a
58
+ * @param {string} b
59
+ * @returns {boolean}
60
+ */
61
+ export function pathsOverlap(a, b) {
62
+ if (a === b) return true;
63
+ return a.startsWith(b + '/') || b.startsWith(a + '/');
64
+ }
65
+
66
+ /**
67
+ * @param {string[]} left
68
+ * @param {string[]} right
69
+ * @returns {boolean}
70
+ */
71
+ export function fileScopesOverlap(left, right) {
72
+ const leftPaths = left.map(normalizeFileScopePath).filter(Boolean);
73
+ const rightPaths = right.map(normalizeFileScopePath).filter(Boolean);
74
+
75
+ for (const a of leftPaths) {
76
+ for (const b of rightPaths) {
77
+ if (pathsOverlap(a, b)) return true;
78
+ }
79
+ }
80
+
81
+ return false;
82
+ }
83
+
84
+ /**
85
+ * @param {string[][]} waves
86
+ * @param {Record<string, { fileScope?: string[] }>} tasksById
87
+ * @returns {AnalyzeFinding[]}
88
+ */
89
+ export function collectParallelFileScopeOverlapFindings(waves, tasksById) {
90
+ /** @type {AnalyzeFinding[]} */
91
+ const findings = [];
92
+
93
+ for (let waveIndex = 0; waveIndex < waves.length; waveIndex++) {
94
+ const waveTaskIds = waves[waveIndex];
95
+ if (waveTaskIds.length < 2) continue;
96
+
97
+ for (let i = 0; i < waveTaskIds.length; i++) {
98
+ for (let j = i + 1; j < waveTaskIds.length; j++) {
99
+ const taskA = waveTaskIds[i];
100
+ const taskB = waveTaskIds[j];
101
+ const scopeA = tasksById[taskA]?.fileScope ?? [];
102
+ const scopeB = tasksById[taskB]?.fileScope ?? [];
103
+
104
+ if (!fileScopesOverlap(scopeA, scopeB)) continue;
105
+
106
+ findings.push({
107
+ severity: 'blocking',
108
+ code: 'parallel_file_scope_overlap',
109
+ message:
110
+ `Parallel-eligible tasks ${taskA} and ${taskB} overlap in ## File Scope (wave ${waveIndex})`,
111
+ taskIds: [taskA, taskB],
112
+ paths: [...new Set([...scopeA, ...scopeB])].sort(),
113
+ });
114
+ }
115
+ }
116
+ }
117
+
118
+ return findings;
119
+ }
120
+
121
+ /**
122
+ * @param {{ tasks?: Record<string, string[]> }} depsJson
123
+ * @param {string[]} discoveredTaskIds
124
+ * @returns {string[]}
125
+ */
126
+ export function collectOrphanTaskIds(depsJson, discoveredTaskIds) {
127
+ const known = new Set(discoveredTaskIds);
128
+ /** @type {Set<string>} */
129
+ const orphans = new Set();
130
+
131
+ for (const [taskId, deps] of Object.entries(depsJson?.tasks ?? {})) {
132
+ if (!known.has(taskId)) orphans.add(taskId);
133
+ for (const dep of deps ?? []) {
134
+ if (!known.has(String(dep))) orphans.add(String(dep));
135
+ }
136
+ }
137
+
138
+ return [...orphans].sort();
139
+ }
140
+
141
+ /**
142
+ * @param {string[]} orphanTaskIds
143
+ * @returns {AnalyzeFinding[]}
144
+ */
145
+ export function collectOrphanTaskFindings(orphanTaskIds) {
146
+ if (orphanTaskIds.length === 0) return [];
147
+
148
+ return [
149
+ {
150
+ severity: 'blocking',
151
+ code: 'orphan_task_id',
152
+ message: `dependencies.json references unknown task ID(s): ${orphanTaskIds.join(', ')}`,
153
+ taskIds: orphanTaskIds,
154
+ },
155
+ ];
156
+ }
157
+
158
+ /**
159
+ * @param {ReturnType<typeof buildGraph>} graph
160
+ * @returns {AnalyzeFinding[]}
161
+ */
162
+ export function collectDependencyCycleFindings(graph) {
163
+ const cyclePath = findCyclePath(graph);
164
+ if (!cyclePath) return [];
165
+
166
+ const cycleNodes = cyclePath[cyclePath.length - 1] === cyclePath[0]
167
+ ? cyclePath.slice(0, -1)
168
+ : cyclePath;
169
+
170
+ return [
171
+ {
172
+ severity: 'blocking',
173
+ code: 'dependency_cycle',
174
+ message: `Dependency cycle detected: ${cyclePath.join(' -> ')}`,
175
+ taskIds: [...new Set(cycleNodes.map(String))].sort(),
176
+ cycle: cyclePath,
177
+ },
178
+ ];
179
+ }
180
+
181
+ const WAVE_M_COUNT_THRESHOLD = 4;
182
+
183
+ const EXPLORE_FINDINGS_PATH_RE = /_explore\/([a-zA-Z0-9][a-zA-Z0-9_-]*)\/findings\.md/g;
184
+
185
+ /**
186
+ * @param {string} contextMarkdown
187
+ * @returns {string[]}
188
+ */
189
+ export function extractExploreSlugsFromContext(contextMarkdown) {
190
+ /** @type {Set<string>} */
191
+ const slugs = new Set();
192
+ let match = EXPLORE_FINDINGS_PATH_RE.exec(contextMarkdown);
193
+ while (match) {
194
+ slugs.add(match[1]);
195
+ match = EXPLORE_FINDINGS_PATH_RE.exec(contextMarkdown);
196
+ }
197
+ return [...slugs].sort();
198
+ }
199
+
200
+ /**
201
+ * @param {string[][]} waves
202
+ * @param {Record<string, { size?: string | null }>} tasksById
203
+ * @returns {AnalyzeFinding[]}
204
+ */
205
+ export function collectWaveMCountFindings(waves, tasksById) {
206
+ /** @type {AnalyzeFinding[]} */
207
+ const findings = [];
208
+
209
+ for (let waveIndex = 0; waveIndex < waves.length; waveIndex++) {
210
+ const mTaskIds = waves[waveIndex].filter((taskId) => tasksById[taskId]?.size === 'M');
211
+ if (mTaskIds.length <= WAVE_M_COUNT_THRESHOLD) continue;
212
+
213
+ findings.push({
214
+ severity: 'warning',
215
+ code: 'wave_m_count',
216
+ message:
217
+ `Wave ${waveIndex} includes ${mTaskIds.length} M-sized tasks (>4) — ` +
218
+ 'consider smaller parallel waves',
219
+ taskIds: mTaskIds,
220
+ });
221
+ }
222
+
223
+ return findings;
224
+ }
225
+
226
+ /**
227
+ * @param {string} tasksRoot
228
+ * @param {string} contextMarkdown
229
+ * @returns {AnalyzeFinding[]}
230
+ */
231
+ export function collectExploreReferenceFindings(tasksRoot, contextMarkdown) {
232
+ if (!contextMarkdown) return [];
233
+
234
+ /** @type {AnalyzeFinding[]} */
235
+ const findings = [];
236
+
237
+ for (const slug of extractExploreSlugsFromContext(contextMarkdown)) {
238
+ const relPath = `_explore/${slug}/findings.md`;
239
+ const findingsPath = path.join(tasksRoot, '_explore', slug, 'findings.md');
240
+ if (fs.existsSync(findingsPath)) continue;
241
+
242
+ findings.push({
243
+ severity: 'warning',
244
+ code: 'explore_findings_missing',
245
+ message: `CONTEXT references ${relPath} but file is missing`,
246
+ paths: [relPath],
247
+ });
248
+ }
249
+
250
+ return findings;
251
+ }
252
+
253
+ /**
254
+ * @param {Record<string, { promptDependencies?: string[] }>} tasksById
255
+ * @param {{ tasks?: Record<string, string[]> }} depsJson
256
+ * @returns {AnalyzeFinding[]}
257
+ */
258
+ export function collectPromptJsonDepsDriftFindings(tasksById, depsJson) {
259
+ /** @type {AnalyzeFinding[]} */
260
+ const findings = [];
261
+
262
+ for (const [taskId, task] of Object.entries(tasksById)) {
263
+ const promptDeps = task.promptDependencies ?? [];
264
+ if (promptDeps.length === 0) continue;
265
+
266
+ const jsonDeps = depsJson?.tasks?.[taskId];
267
+ if (!jsonDeps) {
268
+ findings.push({
269
+ severity: 'warning',
270
+ code: 'prompt_deps_json_missing',
271
+ message: `PROMPT lists dependencies but ${taskId} is missing from dependencies.json`,
272
+ taskIds: [taskId],
273
+ });
274
+ continue;
275
+ }
276
+
277
+ const missing = promptDeps.filter((depId) => !jsonDeps.includes(depId));
278
+ if (missing.length === 0) continue;
279
+
280
+ findings.push({
281
+ severity: 'warning',
282
+ code: 'prompt_deps_json_drift',
283
+ message:
284
+ `PROMPT dependencies not in dependencies.json for ${taskId}: ${missing.join(', ')}`,
285
+ taskIds: [taskId],
286
+ });
287
+ }
288
+
289
+ return findings;
290
+ }
291
+
292
+ /**
293
+ * @param {{ findings: AnalyzeFinding[], scope: ReturnType<typeof parseScope> }} args
294
+ */
295
+ export function buildAnalyzeTasksResult({ findings, scope }) {
296
+ const blockingCount = findings.filter((finding) => finding.severity === 'blocking').length;
297
+ const warningCount = findings.filter((finding) => finding.severity === 'warning').length;
298
+
299
+ return {
300
+ ok: blockingCount === 0,
301
+ scope: {
302
+ mode: scope.mode,
303
+ taskCount: scope.taskIds.length,
304
+ taskIds: scope.taskIds,
305
+ },
306
+ findings,
307
+ blockingCount,
308
+ warningCount,
309
+ };
310
+ }
311
+
312
+ /**
313
+ * @param {{ findings: AnalyzeFinding[], scope: ReturnType<typeof parseScope> }} args
314
+ * @returns {string}
315
+ */
316
+ export function formatAnalyzeTasksHuman({ findings, scope }) {
317
+ const blocking = findings.filter((finding) => finding.severity === 'blocking');
318
+ const warnings = findings.filter((finding) => finding.severity === 'warning');
319
+
320
+ const lines = [
321
+ `Analyzed ${scope.taskIds.length} task(s): ${blocking.length} blocking, ${warnings.length} warning`,
322
+ ];
323
+
324
+ if (findings.length === 0) {
325
+ lines.push('');
326
+ lines.push('No structural issues found.');
327
+ } else {
328
+ lines.push('');
329
+ for (const finding of findings) {
330
+ lines.push(`${finding.severity}: ${finding.message}`);
331
+ }
332
+ }
333
+
334
+ return lines.join('\n').trimEnd() + '\n';
335
+ }
336
+
337
+ /**
338
+ * @param {string} message
339
+ * @param {{ suggestedCommand?: string, exitCode?: number }} [options]
340
+ */
341
+ function throwAnalyzeError(message, { suggestedCommand, exitCode = 2 } = {}) {
342
+ const err = new Error(message);
343
+ if (suggestedCommand) err.suggestedCommand = suggestedCommand;
344
+ err.exitCode = exitCode;
345
+ throw err;
346
+ }
347
+
348
+ /**
349
+ * @param {{ projectRoot?: string, scope?: string }} [args]
350
+ */
351
+ export async function analyzeTasksScope({ projectRoot = process.cwd(), scope = 'all' } = {}) {
352
+ const configResult = loadSpineConfig(projectRoot);
353
+ if (configResult.error) {
354
+ throwAnalyzeError(configResult.error.message, {
355
+ suggestedCommand: configResult.error.suggestedCommand,
356
+ });
357
+ }
358
+
359
+ const config = configResult.config;
360
+ const tasksRoot = resolveTasksRootPath(projectRoot, config);
361
+ if (!tasksRoot) {
362
+ throwAnalyzeError('Cannot analyze tasks: tasksRoot not configured', {
363
+ suggestedCommand: 'spine init',
364
+ });
365
+ }
366
+
367
+ const discovered = discoverTasks(tasksRoot);
368
+ let scopeResult;
369
+ try {
370
+ scopeResult = parseScope(scope, { tasksRoot, discoveredTasks: discovered });
371
+ } catch (err) {
372
+ throwAnalyzeError(err?.message ?? String(err));
373
+ }
374
+
375
+ const depsJson = loadDependenciesJson(tasksRoot);
376
+ const discoveredTaskIds = discovered.map((task) => task.taskId);
377
+ const selectedTaskIds = new Set(scopeResult.taskIds);
378
+
379
+ /** @type {Record<string, { taskId: string, fileScope: string[], dependencies: string[], size: string | null, promptDependencies: string[] }>} */
380
+ const tasksById = {};
381
+
382
+ for (const discoveredTask of discovered) {
383
+ const taskId = discoveredTask.taskId;
384
+ if (!selectedTaskIds.has(taskId)) continue;
385
+
386
+ const packet = loadTaskPacket(discoveredTask.folderPath, {
387
+ contract: config.contract,
388
+ });
389
+ const prompt = packet.prompt;
390
+ const mergedDeps = mergeTaskDeps({ taskId, prompt }, depsJson);
391
+
392
+ tasksById[taskId] = {
393
+ taskId,
394
+ fileScope: Array.isArray(prompt.fileScope) ? prompt.fileScope : [],
395
+ dependencies: mergedDeps,
396
+ size: prompt.size ?? null,
397
+ promptDependencies: Array.isArray(prompt.dependencies) ? prompt.dependencies : [],
398
+ };
399
+ }
400
+
401
+ /** @type {Record<string, string[]>} */
402
+ const depsByTask = {};
403
+ for (const taskId of scopeResult.taskIds) {
404
+ const deps = tasksById[taskId]?.dependencies ?? [];
405
+ depsByTask[taskId] = deps
406
+ .map(String)
407
+ .filter((depId) => Boolean(tasksById[depId]));
408
+ }
409
+
410
+ const graph = buildGraph(depsByTask);
411
+ const { waves, remainingWithDeps } = topoWaves(graph);
412
+
413
+ /** @type {AnalyzeFinding[]} */
414
+ const findings = [
415
+ ...collectOrphanTaskFindings(collectOrphanTaskIds(depsJson, discoveredTaskIds)),
416
+ ...collectDependencyCycleFindings(graph),
417
+ ];
418
+
419
+ if (findings.some((finding) => finding.code === 'dependency_cycle') === false) {
420
+ if (remainingWithDeps.length > 0) {
421
+ findings.push({
422
+ severity: 'blocking',
423
+ code: 'dependency_cycle',
424
+ message:
425
+ 'Unexpected remaining nodes after topo sort (cycle likely): ' +
426
+ remainingWithDeps.join(', '),
427
+ taskIds: remainingWithDeps,
428
+ });
429
+ } else {
430
+ findings.push(...collectParallelFileScopeOverlapFindings(waves, tasksById));
431
+ }
432
+ }
433
+
434
+ const contextPath = path.join(tasksRoot, 'CONTEXT.md');
435
+ const contextMarkdown = fs.existsSync(contextPath)
436
+ ? fs.readFileSync(contextPath, 'utf-8')
437
+ : '';
438
+
439
+ findings.push(
440
+ ...collectWaveMCountFindings(waves, tasksById),
441
+ ...collectExploreReferenceFindings(tasksRoot, contextMarkdown),
442
+ ...collectPromptJsonDepsDriftFindings(tasksById, depsJson),
443
+ );
444
+
445
+ const result = buildAnalyzeTasksResult({ findings, scope: scopeResult });
446
+
447
+ return {
448
+ scope: scopeResult,
449
+ result,
450
+ output: formatAnalyzeTasksHuman({ findings, scope: scopeResult }),
451
+ exitCode: result.ok ? 0 : 1,
452
+ };
453
+ }