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.
Files changed (156) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +563 -0
  3. package/bin/get-version.mjs +35 -0
  4. package/bin/spine-batch.mjs +425 -0
  5. package/bin/spine-cli/batch.mjs +47 -0
  6. package/bin/spine-cli/gate.mjs +10 -0
  7. package/bin/spine-cli/integrate.mjs +10 -0
  8. package/bin/spine-cli/plan.mjs +12 -0
  9. package/bin/spine-cli/shared.mjs +73 -0
  10. package/bin/spine-cli/status.mjs +18 -0
  11. package/bin/spine-cli/verify.mjs +199 -0
  12. package/bin/spine-config.mjs +212 -0
  13. package/bin/spine-dashboard.mjs +178 -0
  14. package/bin/spine-deps.mjs +69 -0
  15. package/bin/spine-doctor.mjs +468 -0
  16. package/bin/spine-gate.mjs +137 -0
  17. package/bin/spine-init.mjs +398 -0
  18. package/bin/spine-integrate.mjs +77 -0
  19. package/bin/spine-journal.mjs +198 -0
  20. package/bin/spine-migrate-from-taskplane.mjs +136 -0
  21. package/bin/spine-plan.mjs +83 -0
  22. package/bin/spine-preflight.mjs +700 -0
  23. package/bin/spine-report-progress.d.mts +28 -0
  24. package/bin/spine-report-progress.mjs +126 -0
  25. package/bin/spine-review-step.d.mts +24 -0
  26. package/bin/spine-review-step.mjs +124 -0
  27. package/bin/spine-rules.mjs +35 -0
  28. package/bin/spine-settings.mjs +186 -0
  29. package/bin/spine-state.mjs +110 -0
  30. package/bin/spine-status.mjs +79 -0
  31. package/bin/spine-tasks.mjs +293 -0
  32. package/bin/spine-worker-runner.mjs +314 -0
  33. package/bin/spine.mjs +404 -0
  34. package/extensions/spine/settings-slash.ts +20 -0
  35. package/extensions/spine/slash-commands.ts +806 -0
  36. package/extensions/spine/worker-tools.ts +279 -0
  37. package/extensions/spine-orchestrator.ts +12 -0
  38. package/package.json +72 -0
  39. package/skills/.gitkeep +0 -0
  40. package/skills/create-spine-tasks/SKILL.md +375 -0
  41. package/skills/create-spine-tasks/references/context-template.md +25 -0
  42. package/skills/create-spine-tasks/references/contract-template.md +98 -0
  43. package/skills/create-spine-tasks/references/explore-template.md +63 -0
  44. package/skills/create-spine-tasks/references/prompt-template.md +276 -0
  45. package/src/batch/abort.mjs +272 -0
  46. package/src/batch/agent-session-worker.mjs +297 -0
  47. package/src/batch/batch-state-io.mjs +53 -0
  48. package/src/batch/contract-verify.mjs +310 -0
  49. package/src/batch/detached-start.mjs +778 -0
  50. package/src/batch/diagnosis.mjs +378 -0
  51. package/src/batch/engine-lanes/merge.mjs +632 -0
  52. package/src/batch/engine-lanes/queue.mjs +208 -0
  53. package/src/batch/engine-lanes/review.mjs +970 -0
  54. package/src/batch/engine-lanes.mjs +388 -0
  55. package/src/batch/engine-scope.mjs +251 -0
  56. package/src/batch/engine.mjs +445 -0
  57. package/src/batch/evidence-command.mjs +157 -0
  58. package/src/batch/evidence.mjs +203 -0
  59. package/src/batch/gate.mjs +359 -0
  60. package/src/batch/git-commit-env.mjs +46 -0
  61. package/src/batch/git-exec.mjs +26 -0
  62. package/src/batch/heartbeat.mjs +430 -0
  63. package/src/batch/integrate.mjs +414 -0
  64. package/src/batch/journal-rebuild.mjs +388 -0
  65. package/src/batch/journal.mjs +373 -0
  66. package/src/batch/lane-commit.mjs +153 -0
  67. package/src/batch/lifecycle.mjs +364 -0
  68. package/src/batch/metrics.mjs +265 -0
  69. package/src/batch/orphan-detect.mjs +210 -0
  70. package/src/batch/post-merge-limbo.mjs +80 -0
  71. package/src/batch/postmortem.mjs +296 -0
  72. package/src/batch/readers/spine-state.mjs +95 -0
  73. package/src/batch/readers/taskplane-state.mjs +136 -0
  74. package/src/batch/reconcile.mjs +729 -0
  75. package/src/batch/resume-common.mjs +104 -0
  76. package/src/batch/resume-engine.mjs +66 -0
  77. package/src/batch/resume-multi-lanes.mjs +479 -0
  78. package/src/batch/resume-multi-validate.mjs +187 -0
  79. package/src/batch/resume-multi.mjs +254 -0
  80. package/src/batch/resume.mjs +475 -0
  81. package/src/batch/retry.mjs +257 -0
  82. package/src/batch/review-scope.mjs +136 -0
  83. package/src/batch/review.mjs +1045 -0
  84. package/src/batch/salvage.mjs +332 -0
  85. package/src/batch/state.mjs +680 -0
  86. package/src/batch/task-stall-budget.mjs +88 -0
  87. package/src/batch/worker-host.mjs +683 -0
  88. package/src/batch/worker-output.mjs +253 -0
  89. package/src/batch/worker-prompt.mjs +84 -0
  90. package/src/batch/worktree.mjs +290 -0
  91. package/src/cli/deps.mjs +141 -0
  92. package/src/cli/handoff.mjs +364 -0
  93. package/src/cli/rules.mjs +429 -0
  94. package/src/cli/settings-set.mjs +171 -0
  95. package/src/cli/settings-show.mjs +140 -0
  96. package/src/cli/settings-slash.mjs +107 -0
  97. package/src/config/contract.mjs +56 -0
  98. package/src/config/cursor-rules/discover.mjs +416 -0
  99. package/src/config/cursor-rules/index.mjs +39 -0
  100. package/src/config/cursor-rules/match-globs.mjs +132 -0
  101. package/src/config/cursor-rules/parse-frontmatter.mjs +222 -0
  102. package/src/config/cursor-rules/priority.mjs +26 -0
  103. package/src/config/cursor-rules/profile.mjs +403 -0
  104. package/src/config/cursor-rules/select.mjs +259 -0
  105. package/src/config/defaults.mjs +36 -0
  106. package/src/config/env-overrides.mjs +207 -0
  107. package/src/config/merge-defaults.mjs +47 -0
  108. package/src/config/pi-spine-root.mjs +93 -0
  109. package/src/config/reviewer-context.mjs +243 -0
  110. package/src/config/settings-fields.mjs +265 -0
  111. package/src/config/worker-backend.mjs +116 -0
  112. package/src/config/worker-context.mjs +402 -0
  113. package/src/config/worker-launch-script.mjs +130 -0
  114. package/src/config/worktree-setup-hook.mjs +122 -0
  115. package/src/dashboard/public/dashboard.css +77 -0
  116. package/src/dashboard/public/dashboard.js +349 -0
  117. package/src/dashboard/public/index.html +80 -0
  118. package/src/dashboard/server.mjs +155 -0
  119. package/src/dashboard/snapshot.mjs +414 -0
  120. package/src/dashboard/sse.mjs +15 -0
  121. package/src/dashboard/view.mjs +292 -0
  122. package/src/doctor/agent-model-inherit.mjs +101 -0
  123. package/src/doctor/batch-size-guidance.mjs +72 -0
  124. package/src/doctor/coexistence.mjs +312 -0
  125. package/src/doctor/rules-manifest.mjs +133 -0
  126. package/src/doctor/stale-path.mjs +156 -0
  127. package/src/doctor/stall-config.mjs +108 -0
  128. package/src/doctor/suggest-max-parallel.mjs +53 -0
  129. package/src/doctor/task-packet-size.mjs +110 -0
  130. package/src/doctor/worktree-health.mjs +71 -0
  131. package/src/migrate/taskplane-config.mjs +116 -0
  132. package/src/planner/cycles.mjs +63 -0
  133. package/src/planner/format-plan.mjs +132 -0
  134. package/src/planner/graph.mjs +99 -0
  135. package/src/planner/index.mjs +125 -0
  136. package/src/planner/lanes.mjs +111 -0
  137. package/src/planner/pending.mjs +39 -0
  138. package/src/planner/scope.mjs +142 -0
  139. package/src/process/liveness.mjs +21 -0
  140. package/src/tasks/packet/discover.mjs +40 -0
  141. package/src/tasks/packet/index.mjs +81 -0
  142. package/src/tasks/packet/merge-deps.mjs +79 -0
  143. package/src/tasks/packet/parse-prompt.mjs +445 -0
  144. package/src/tasks/packet/parse-status.mjs +118 -0
  145. package/src/tasks/packet/validate-contract.mjs +115 -0
  146. package/src/tasks/packet/validate-prompt.mjs +99 -0
  147. package/src/worker-tools/report-progress.d.mts +18 -0
  148. package/src/worker-tools/report-progress.mjs +59 -0
  149. package/src/worker-tools/request-gate.d.mts +17 -0
  150. package/src/worker-tools/request-gate.mjs +54 -0
  151. package/templates/agents/reviewer.md +123 -0
  152. package/templates/agents/supervisor.md +59 -0
  153. package/templates/agents/worker.md +122 -0
  154. package/templates/rules-profile.json +27 -0
  155. package/templates/spine-config.json +64 -0
  156. package/templates/tasks/CONTEXT.md +30 -0
@@ -0,0 +1,132 @@
1
+ /**
2
+ * Human-readable plan output for `spine plan` and `/spine-plan`.
3
+ */
4
+
5
+ import { appendBatchSizeGuidanceToPlanOutput } from "../doctor/batch-size-guidance.mjs";
6
+
7
+ /**
8
+ * @param {string} taskId
9
+ * @param {Record<string, { title?: string|null }>|undefined} tasks
10
+ */
11
+ function formatTaskLine(taskId, tasks) {
12
+ const title = tasks?.[taskId]?.title?.trim();
13
+ if (title) {
14
+ return `${taskId} — ${title}`;
15
+ }
16
+ return taskId;
17
+ }
18
+
19
+ /**
20
+ * @param {Array<{ tickIndex: number, lanes: Array<{ laneNumber: number, taskIds: string[] }> }>} rounds
21
+ */
22
+ function summarizeWave(wave, rounds) {
23
+ const totalTasks = wave.taskIds?.length ?? 0;
24
+ if (totalTasks === 0) return "empty";
25
+
26
+ const maxLanesInRound = Math.max(...rounds.map((r) => r.lanes.length), 0);
27
+ const hasSerialLane = rounds.some((r) => r.lanes.some((l) => l.taskIds.length > 1));
28
+ const multiRound = rounds.length > 1;
29
+
30
+ if (multiRound) {
31
+ return `${totalTasks} tasks · ${rounds.length} rounds (queued by maxParallel)`;
32
+ }
33
+ if (maxLanesInRound > 1 && !hasSerialLane) {
34
+ return `${totalTasks} tasks · ${maxLanesInRound} lanes in parallel`;
35
+ }
36
+ if (hasSerialLane) {
37
+ return `serial · ${totalTasks} tasks (overlapping file scope)`;
38
+ }
39
+ if (totalTasks === 1) {
40
+ return "1 task";
41
+ }
42
+ return `${totalTasks} tasks`;
43
+ }
44
+
45
+ /**
46
+ * @param {{ index: number, taskIds: string[], ticks?: Array<{ index: number, lanes: string[][] }> }} wave
47
+ * @param {Record<string, { title?: string|null }>|undefined} tasks
48
+ */
49
+ function formatWaveLines(wave, tasks) {
50
+ const lines = [];
51
+
52
+ const rounds = [];
53
+ for (const tick of wave.ticks ?? []) {
54
+ const lanes = (tick.lanes ?? [])
55
+ .map((taskIds, laneIndex) => ({
56
+ laneNumber: laneIndex + 1,
57
+ taskIds: taskIds.filter(Boolean),
58
+ }))
59
+ .filter((lane) => lane.taskIds.length > 0);
60
+ if (lanes.length > 0) {
61
+ rounds.push({ tickIndex: tick.index, lanes });
62
+ }
63
+ }
64
+
65
+ lines.push(`Wave ${wave.index} · ${summarizeWave(wave, rounds)}`);
66
+
67
+ const multiRound = rounds.length > 1;
68
+ for (const round of rounds) {
69
+ if (multiRound) {
70
+ const parallelCount = round.lanes.length;
71
+ const roundLabel =
72
+ parallelCount > 1
73
+ ? `Round ${round.tickIndex + 1} (${parallelCount} parallel)`
74
+ : `Round ${round.tickIndex + 1}`;
75
+ lines.push(` ${roundLabel}:`);
76
+ }
77
+
78
+ for (const lane of round.lanes) {
79
+ if (lane.taskIds.length === 1) {
80
+ const prefix = multiRound ? " " : " ";
81
+ lines.push(`${prefix}Lane ${lane.laneNumber}: ${formatTaskLine(lane.taskIds[0], tasks)}`);
82
+ continue;
83
+ }
84
+
85
+ const prefix = multiRound ? " " : " ";
86
+ lines.push(`${prefix}Lane ${lane.laneNumber} (serial):`);
87
+ for (const taskId of lane.taskIds) {
88
+ lines.push(` · ${formatTaskLine(taskId, tasks)}`);
89
+ }
90
+ }
91
+ }
92
+
93
+ return lines;
94
+ }
95
+
96
+ /**
97
+ * @param {{ scope?: { mode?: string }, metadata?: { tasksSelected?: number, tasksExcluded?: number }, laneConfig?: { maxParallel?: number }, waves?: any[], tasks?: Record<string, { title?: string|null }> }} plan
98
+ */
99
+ export function formatPlanHuman(plan) {
100
+ const lines = [];
101
+ const mode = plan.scope?.mode ?? "custom";
102
+ const taskCount =
103
+ plan.metadata?.tasksSelected ?? (plan.tasks ? Object.keys(plan.tasks).length : "unknown");
104
+ const waveCount = plan.waves?.length ?? 0;
105
+ const maxParallel = plan.laneConfig?.maxParallel ?? 1;
106
+
107
+ lines.push(`Spine plan — ${mode}`);
108
+ lines.push(`${taskCount} task(s) · ${waveCount} wave(s) · maxParallel ${maxParallel}`);
109
+ if (plan.scope?.mode === "pending" && plan.metadata?.tasksExcluded != null) {
110
+ lines.push(`${plan.metadata.tasksExcluded} excluded (.DONE on disk)`);
111
+ }
112
+ lines.push("");
113
+
114
+ for (const wave of plan.waves ?? []) {
115
+ lines.push(...formatWaveLines(wave, plan.tasks));
116
+ lines.push("");
117
+ }
118
+
119
+ const firstWave = plan.waves?.[0];
120
+ if (firstWave?.taskIds?.length) {
121
+ lines.push(`Start: spine batch start ${firstWave.taskIds.join(" ")}`);
122
+ }
123
+
124
+ if ((plan.waves?.length ?? 0) > 1) {
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(" ")}`);
128
+ }
129
+ }
130
+
131
+ return appendBatchSizeGuidanceToPlanOutput(`${lines.join("\n").trimEnd()}\n`, plan);
132
+ }
@@ -0,0 +1,99 @@
1
+ /**
2
+ * FR-SCHED-01: build directed graph from dependencies and
3
+ * produce topological waves.
4
+ *
5
+ * Dependencies are expressed as:
6
+ * depsByTask[taskId] = [dependencyTaskId, ...]
7
+ *
8
+ * All task IDs appearing either as a key or dependency will be
9
+ * included in the graph.
10
+ */
11
+
12
+ /**
13
+ * @param {Record<string, string[]>} depsByTask
14
+ * @returns {{ nodes: string[], depsByTask: Record<string, string[]>, dependentsByTask: Record<string, string[]> }}
15
+ */
16
+ export function buildGraph(depsByTask) {
17
+ const normalized = {};
18
+ const dependentsByTask = {};
19
+ const nodesSet = new Set();
20
+
21
+ for (const [taskId, deps] of Object.entries(depsByTask)) {
22
+ const id = String(taskId);
23
+ nodesSet.add(id);
24
+ const list = Array.from(new Set((deps ?? []).map(String)));
25
+ normalized[id] = list;
26
+
27
+ for (const dep of list) {
28
+ nodesSet.add(dep);
29
+ if (!dependentsByTask[dep]) dependentsByTask[dep] = [];
30
+ if (!dependentsByTask[dep].includes(id)) dependentsByTask[dep].push(id);
31
+ }
32
+ }
33
+
34
+ for (const id of nodesSet) {
35
+ if (!normalized[id]) normalized[id] = [];
36
+ if (!dependentsByTask[id]) dependentsByTask[id] = [];
37
+ }
38
+
39
+ const nodes = Array.from(nodesSet).sort();
40
+ for (const id of Object.keys(dependentsByTask)) {
41
+ dependentsByTask[id].sort();
42
+ }
43
+
44
+ return { nodes, depsByTask: normalized, dependentsByTask };
45
+ }
46
+
47
+ /**
48
+ * Kahn-style topological sort that groups nodes into waves.
49
+ *
50
+ * Each wave contains nodes whose dependencies are satisfied by
51
+ * earlier waves.
52
+ *
53
+ * @param {{ nodes: string[], depsByTask: Record<string, string[]>, dependentsByTask: Record<string, string[]> }} graph
54
+ * @returns {{ waves: string[][], remainingWithDeps: string[] }}
55
+ */
56
+ export function topoWaves(graph) {
57
+ const indegree = new Map();
58
+
59
+ for (const id of graph.nodes) {
60
+ indegree.set(id, 0);
61
+ }
62
+
63
+ // indegree counts number of unsatisfied dependencies for each node
64
+ for (const [taskId, deps] of Object.entries(graph.depsByTask)) {
65
+ indegree.set(taskId, (deps ?? []).length);
66
+ }
67
+
68
+ const zero = Array.from(indegree.entries())
69
+ .filter(([, deg]) => deg === 0)
70
+ .map(([id]) => id)
71
+ .sort();
72
+
73
+ const waves = [];
74
+ let current = zero;
75
+
76
+ while (current.length > 0) {
77
+ waves.push(current);
78
+ const next = [];
79
+
80
+ for (const id of current) {
81
+ const dependents = graph.dependentsByTask[id] ?? [];
82
+ for (const dependent of dependents) {
83
+ const prev = indegree.get(dependent) ?? 0;
84
+ const nextDeg = prev - 1;
85
+ indegree.set(dependent, nextDeg);
86
+ if (nextDeg === 0) next.push(dependent);
87
+ }
88
+ }
89
+
90
+ current = next.sort();
91
+ }
92
+
93
+ const remainingWithDeps = Array.from(indegree.entries())
94
+ .filter(([, deg]) => deg > 0)
95
+ .map(([id]) => id)
96
+ .sort();
97
+
98
+ return { waves, remainingWithDeps };
99
+ }
@@ -0,0 +1,125 @@
1
+ /**
2
+ * src/planner/index.mjs
3
+ *
4
+ * FR-SCHED-01..04..06: build dependency DAG, topological waves, and lane assignment.
5
+ */
6
+
7
+ import {
8
+ collectPromptValidationFailure,
9
+ discoverTasks,
10
+ formatPromptValidationFailures,
11
+ loadTaskPacket,
12
+ loadDependenciesJson,
13
+ mergeTaskDeps,
14
+ } from '../tasks/packet/index.mjs';
15
+
16
+ import { buildGraph, topoWaves } from './graph.mjs';
17
+ import { findCyclePath } from './cycles.mjs';
18
+ import { assignLanesToWaves } from './lanes.mjs';
19
+ import { parseScope } from './scope.mjs';
20
+
21
+ /**
22
+ * @param {{ scope?: any, config: { lanes?: { maxParallel?: number, queueExcess?: boolean } }, tasksRoot: string }} args
23
+ */
24
+ export function buildPlan({ scope, config, tasksRoot }) {
25
+ if (!tasksRoot) throw new Error('buildPlan requires tasksRoot');
26
+ if (!config) throw new Error('buildPlan requires config');
27
+
28
+ const discovered = discoverTasks(tasksRoot);
29
+ const scopeResult = parseScope(scope, { tasksRoot, discoveredTasks: discovered });
30
+ const selectedIdsSorted = scopeResult.taskIds;
31
+ const selectedTaskIds = new Set(selectedIdsSorted);
32
+
33
+ const depsJson = loadDependenciesJson(tasksRoot);
34
+
35
+ /** @type {Record<string, { taskId: string, title: string|null, fileScope: string[], dependencies: string[] }> } */
36
+ const tasksById = {};
37
+ /** @type {Array<{ taskId: string, promptPath?: string, errors: string[] }>} */
38
+ const promptValidationFailures = [];
39
+
40
+ for (const discoveredTask of discovered) {
41
+ const taskId = discoveredTask.taskId;
42
+ if (!selectedTaskIds.has(taskId)) continue;
43
+
44
+ const packet = loadTaskPacket(discoveredTask.folderPath);
45
+ const validationFailure = collectPromptValidationFailure(packet, taskId);
46
+ if (validationFailure) {
47
+ promptValidationFailures.push(validationFailure);
48
+ continue;
49
+ }
50
+
51
+ const prompt = packet.prompt;
52
+ const mergedDeps = mergeTaskDeps({ taskId, prompt }, depsJson);
53
+
54
+ tasksById[taskId] = {
55
+ taskId,
56
+ title: prompt.title ?? null,
57
+ fileScope: Array.isArray(prompt.fileScope) ? prompt.fileScope : [],
58
+ dependencies: mergedDeps,
59
+ };
60
+ }
61
+
62
+ if (promptValidationFailures.length > 0) {
63
+ throw new Error(formatPromptValidationFailures(promptValidationFailures));
64
+ }
65
+
66
+ /** @type {Record<string, string[]>} */
67
+ const depsByTask = {};
68
+ for (const taskId of selectedIdsSorted) {
69
+ const deps = tasksById[taskId]?.dependencies ?? [];
70
+ depsByTask[taskId] = deps.filter((depId) => Boolean(tasksById[depId]));
71
+ }
72
+
73
+ const graph = buildGraph(depsByTask);
74
+
75
+ const cycle = findCyclePath(graph);
76
+ if (cycle) {
77
+ throw new Error('Dependency cycle detected: ' + cycle.join(' -> '));
78
+ }
79
+
80
+ const { waves, remainingWithDeps } = topoWaves(graph);
81
+ if (remainingWithDeps.length > 0) {
82
+ throw new Error(
83
+ 'Unexpected remaining nodes after topo sort (cycle likely): ' + remainingWithDeps.join(', '),
84
+ );
85
+ }
86
+
87
+ const maxParallel = config.lanes?.maxParallel ?? 1;
88
+ const queueExcess = config.lanes?.queueExcess ?? true;
89
+
90
+ const wavesWithLanes = assignLanesToWaves({
91
+ waves,
92
+ tasksById,
93
+ maxParallel,
94
+ queueExcess,
95
+ });
96
+
97
+ return {
98
+ generatedAt: new Date().toISOString(),
99
+ scope: {
100
+ mode: scopeResult.mode,
101
+ taskIds: selectedIdsSorted,
102
+ },
103
+ laneConfig: { maxParallel, queueExcess },
104
+ waves: wavesWithLanes,
105
+ tasks: Object.fromEntries(
106
+ selectedIdsSorted.map((taskId) => [
107
+ taskId,
108
+ {
109
+ taskId,
110
+ title: tasksById[taskId]?.title ?? null,
111
+ fileScope: tasksById[taskId]?.fileScope ?? [],
112
+ dependencies: tasksById[taskId]?.dependencies ?? [],
113
+ },
114
+ ]),
115
+ ),
116
+ metadata: {
117
+ tasksRoot,
118
+ tasksDiscovered: discovered.length,
119
+ tasksSelected: selectedIdsSorted.length,
120
+ ...(scopeResult.mode === 'pending'
121
+ ? { tasksExcluded: scopeResult.excludedCount ?? 0 }
122
+ : {}),
123
+ },
124
+ };
125
+ }
@@ -0,0 +1,111 @@
1
+ /**
2
+ * FR-SCHED-03/04: greedy lane assignment subject to file-scope disjointness.
3
+ */
4
+
5
+ function normalizeFileScopePath(p) {
6
+ let s = String(p ?? '').trim();
7
+ if (!s) return null;
8
+
9
+ s = s.replace(/\\/g, '/');
10
+ if (s.startsWith('./')) s = s.slice(2);
11
+ s = s.replace(/\/+$/g, '');
12
+
13
+ // Common "globs" used in scopes are treated as directory prefixes.
14
+ if (s.endsWith('/*')) s = s.slice(0, -2);
15
+ if (s.endsWith('/**')) s = s.slice(0, -3);
16
+
17
+ return s || null;
18
+ }
19
+
20
+ function pathsOverlap(a, b) {
21
+ if (a === b) return true;
22
+ // Only treat directory-prefix matches; a file prefix without a slash should not match.
23
+ return a.startsWith(b + '/') || b.startsWith(a + '/');
24
+ }
25
+
26
+ function taskOverlapsLane(taskPaths, lanePaths) {
27
+ for (const a of taskPaths) {
28
+ for (const b of lanePaths) {
29
+ if (pathsOverlap(a, b)) return true;
30
+ }
31
+ }
32
+ return false;
33
+ }
34
+
35
+ /**
36
+ * @param {{ waves: string[][], tasksById: Record<string, { fileScope?: string[] }>, maxParallel: number, queueExcess?: boolean }} args
37
+ * @returns {Array<{ index: number, taskIds: string[], virtualLaneCount: number, ticks: Array<{ index: number, lanes: string[][] }>, laneAssignments: Record<string, { virtualLane: number, tick: number, laneInTick: number }> }>
38
+ */
39
+ export function assignLanesToWaves({ waves, tasksById, maxParallel, queueExcess = true }) {
40
+ const planned = [];
41
+
42
+ for (let waveIndex = 0; waveIndex < waves.length; waveIndex++) {
43
+ const waveTaskIds = waves[waveIndex];
44
+
45
+ /** @type {{ lanePaths: string[] }} */
46
+ const virtualLanes = [];
47
+
48
+ /** @type {Record<string, { virtualLane: number, tick: number, laneInTick: number }>} */
49
+ const laneAssignments = {};
50
+
51
+ const virtualLaneForTask = {};
52
+
53
+ // Greedy packing into virtual lanes.
54
+ for (const taskId of waveTaskIds) {
55
+ const task = tasksById[taskId];
56
+ if (!task) {
57
+ throw new Error(`Missing task packet for ${taskId} during lane assignment`);
58
+ }
59
+
60
+ const taskPaths = (task.fileScope ?? [])
61
+ .map(normalizeFileScopePath)
62
+ .filter(Boolean);
63
+
64
+ let placed = false;
65
+ for (let i = 0; i < virtualLanes.length; i++) {
66
+ const lane = virtualLanes[i];
67
+ if (taskOverlapsLane(taskPaths, lane.lanePaths)) {
68
+ virtualLaneForTask[taskId] = i;
69
+ // Append to lane paths so future tasks are checked against everything already assigned.
70
+ lane.lanePaths.push(...taskPaths);
71
+ placed = true;
72
+ break;
73
+ }
74
+ }
75
+
76
+ if (!placed) {
77
+ const i = virtualLanes.length;
78
+ virtualLanes.push({ lanePaths: [...taskPaths] });
79
+ virtualLaneForTask[taskId] = i;
80
+ }
81
+ }
82
+
83
+ const virtualLaneCount = virtualLanes.length;
84
+ const tickCount = queueExcess ? Math.ceil(virtualLaneCount / maxParallel) : 1;
85
+
86
+ const ticks = Array.from({ length: tickCount }, (_, t) => {
87
+ return {
88
+ index: t,
89
+ lanes: Array.from({ length: maxParallel }, () => []),
90
+ };
91
+ });
92
+
93
+ for (const taskId of waveTaskIds) {
94
+ const virtualLane = virtualLaneForTask[taskId];
95
+ const tick = queueExcess ? Math.floor(virtualLane / maxParallel) : 0;
96
+ const laneInTick = virtualLane % maxParallel;
97
+ laneAssignments[taskId] = { virtualLane, tick, laneInTick };
98
+ ticks[tick].lanes[laneInTick].push(taskId);
99
+ }
100
+
101
+ planned.push({
102
+ index: waveIndex,
103
+ taskIds: waveTaskIds,
104
+ virtualLaneCount,
105
+ ticks,
106
+ laneAssignments,
107
+ });
108
+ }
109
+
110
+ return planned;
111
+ }
@@ -0,0 +1,39 @@
1
+ /**
2
+ * Pending task filter — tasks without a terminal `.DONE` marker (FR-SCHED-06, TP-024).
3
+ */
4
+
5
+ import fs from "node:fs";
6
+ import path from "node:path";
7
+
8
+ /**
9
+ * @param {Array<{ taskId: string, folderPath: string }>} discoveredTasks
10
+ * @param {string} tasksRoot
11
+ * @returns {string[]} Pending task IDs sorted lexicographically
12
+ */
13
+ export function filterPendingTaskIds(discoveredTasks, tasksRoot) {
14
+ const pending = [];
15
+
16
+ for (const task of discoveredTasks) {
17
+ const folderPath = task.folderPath ?? path.join(tasksRoot, `${task.taskId}-unknown`);
18
+ const donePath = path.join(folderPath, ".DONE");
19
+ if (!fs.existsSync(donePath)) {
20
+ pending.push(task.taskId);
21
+ }
22
+ }
23
+
24
+ return pending.sort();
25
+ }
26
+
27
+ /**
28
+ * @param {Array<{ taskId: string, folderPath: string }>} discoveredTasks
29
+ * @param {string} tasksRoot
30
+ * @returns {{ pendingIds: string[], excludedCount: number }}
31
+ */
32
+ export function summarizePendingScope(discoveredTasks, tasksRoot) {
33
+ const allIds = discoveredTasks.map((task) => task.taskId);
34
+ const pendingIds = filterPendingTaskIds(discoveredTasks, tasksRoot);
35
+ return {
36
+ pendingIds,
37
+ excludedCount: allIds.length - pendingIds.length,
38
+ };
39
+ }
@@ -0,0 +1,142 @@
1
+ /**
2
+ * FR-SCHED-06: scope parsing
3
+ *
4
+ * Supported scope forms:
5
+ * - "all"
6
+ * - "pending" (tasks without `.DONE` marker)
7
+ * - explicit task IDs (e.g. "TP-008")
8
+ * - glob-like path patterns (e.g. "spine-tasks/TP-008-*")
9
+ */
10
+
11
+ import path from 'node:path';
12
+ import { summarizePendingScope } from './pending.mjs';
13
+
14
+ export const TASK_ID_RE = /^[A-Z][A-Z0-9]*-\d{3,}$/;
15
+
16
+ export const NO_PENDING_TASKS_ERROR = 'No pending tasks (all discovered tasks have .DONE).';
17
+
18
+ function escapeRegexChar(ch) {
19
+ // Escape regex meta characters.
20
+ return /[\^$.*+?()[\]{}|]/.test(ch) ? '\\' + ch : ch;
21
+ }
22
+
23
+ function globToRegExp(pattern) {
24
+ // Very small glob subset:
25
+ // - ** => .*
26
+ // - * => [^/]*
27
+ // - ? => [^/]
28
+ // Everything else is treated as literal.
29
+ const posix = String(pattern ?? '').replace(/\\/g, '/');
30
+ let out = '^';
31
+
32
+ for (let i = 0; i < posix.length; ) {
33
+ const two = posix.slice(i, i + 2);
34
+ if (two === '**') {
35
+ out += '.*';
36
+ i += 2;
37
+ continue;
38
+ }
39
+
40
+ const ch = posix[i];
41
+ if (ch === '*') {
42
+ out += '[^/]*';
43
+ i += 1;
44
+ continue;
45
+ }
46
+
47
+ if (ch === '?') {
48
+ out += '[^/]';
49
+ i += 1;
50
+ continue;
51
+ }
52
+
53
+ out += escapeRegexChar(ch);
54
+ i += 1;
55
+ }
56
+
57
+ out += '$';
58
+ return new RegExp(out);
59
+ }
60
+
61
+ function tokenizeScope(scope) {
62
+ if (Array.isArray(scope)) return scope.map(String).filter(Boolean);
63
+ const s = String(scope ?? '').trim();
64
+ if (!s) return [];
65
+ return s.split(/[\s,]+/).filter(Boolean);
66
+ }
67
+
68
+ /**
69
+ * @param {any} scopeArg
70
+ * @param {{ tasksRoot: string, discoveredTasks: Array<{ taskId: string, folderPath: string }> }} args
71
+ * @returns {{ mode: 'all'|'pending'|'ids'|'glob'|'custom', taskIds: string[], excludedCount?: number }}
72
+ */
73
+ export function parseScope(scopeArg, { tasksRoot, discoveredTasks }) {
74
+ const allTaskIds = discoveredTasks.map((t) => t.taskId).sort();
75
+ const tasksRootPosix = String(tasksRoot).replace(/\\/g, '/');
76
+ const tasksRootBase = path.posix.basename(tasksRootPosix);
77
+
78
+ if (scopeArg == null || scopeArg === 'all') {
79
+ return { mode: 'all', taskIds: allTaskIds };
80
+ }
81
+
82
+ const tokens = tokenizeScope(scopeArg);
83
+ if (tokens.length === 0) {
84
+ return { mode: 'all', taskIds: allTaskIds };
85
+ }
86
+
87
+ if (tokens.length === 1 && tokens[0] === 'pending') {
88
+ const { pendingIds, excludedCount } = summarizePendingScope(discoveredTasks, tasksRoot);
89
+ if (pendingIds.length === 0) {
90
+ throw new Error(NO_PENDING_TASKS_ERROR);
91
+ }
92
+ return { mode: 'pending', taskIds: pendingIds, excludedCount };
93
+ }
94
+
95
+ const selected = new Set();
96
+ let sawGlob = false;
97
+ let sawId = false;
98
+
99
+ for (const token of tokens) {
100
+ if (token === 'all') {
101
+ return { mode: 'all', taskIds: allTaskIds };
102
+ }
103
+
104
+ if (token === 'pending') {
105
+ throw new Error('Use scope "pending" alone; do not combine with other tokens.');
106
+ }
107
+
108
+ if (TASK_ID_RE.test(token)) {
109
+ selected.add(token);
110
+ sawId = true;
111
+ continue;
112
+ }
113
+
114
+ sawGlob = true;
115
+ const regex = globToRegExp(token);
116
+
117
+ for (const discovered of discoveredTasks) {
118
+ const abs = String(discovered.folderPath);
119
+ const absNorm = abs.replace(/\\/g, '/');
120
+ const rel = path.posix.normalize(path.relative(tasksRoot, abs));
121
+ const relWithRoot = `${tasksRootBase}/${rel}`;
122
+ // Match against absolute, relative-to-tasksRoot, and relative-with tasksRoot basename.
123
+ if (regex.test(absNorm) || regex.test(rel) || regex.test(relWithRoot)) {
124
+ selected.add(discovered.taskId);
125
+ }
126
+ }
127
+ }
128
+
129
+ const resolved = Array.from(selected)
130
+ .filter((id) => allTaskIds.includes(id))
131
+ .sort();
132
+
133
+ if (resolved.length === 0) {
134
+ throw new Error(`Scope did not match any discovered task(s): ${String(scopeArg)}`);
135
+ }
136
+
137
+ let mode = 'custom';
138
+ if (sawGlob && !sawId) mode = 'glob';
139
+ else if (!sawGlob && sawId) mode = 'ids';
140
+
141
+ return { mode, taskIds: resolved };
142
+ }
@@ -0,0 +1,21 @@
1
+ /**
2
+ * Cross-platform process liveness check (signal 0 / kill -0 equivalent).
3
+ */
4
+
5
+ /**
6
+ * @param {unknown} pid
7
+ * @returns {boolean}
8
+ */
9
+ export function isProcessAlive(pid) {
10
+ const n = Number(pid);
11
+ if (!Number.isFinite(n) || n <= 0) return false;
12
+ try {
13
+ process.kill(n, 0);
14
+ return true;
15
+ } catch (err) {
16
+ if (err && typeof err === "object" && "code" in err && err.code === "EPERM") {
17
+ return true;
18
+ }
19
+ return false;
20
+ }
21
+ }