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,40 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+
4
+ /** Folder name: PREFIX-###-slug (e.g. TP-007-taskplane-parsers). */
5
+ export const TASK_FOLDER_RE = /^([A-Z][A-Z0-9]*-\d{3})-([a-z0-9][a-z0-9-]*)$/;
6
+
7
+ /**
8
+ * Discover Taskplane task packets under `{tasksRoot}/{PREFIX-###-slug}/PROMPT.md`.
9
+ * FR-TASK-01.
10
+ *
11
+ * @param {string} tasksRoot Absolute or relative path to tasks root (e.g. spine-tasks)
12
+ * @returns {Array<{ taskId: string, slug: string, folderName: string, folderPath: string, promptPath: string }>}
13
+ */
14
+ export function discoverTasks(tasksRoot) {
15
+ const entries = fs.readdirSync(tasksRoot, { withFileTypes: true });
16
+ const tasks = [];
17
+
18
+ for (const entry of entries) {
19
+ if (!entry.isDirectory()) continue;
20
+
21
+ const match = TASK_FOLDER_RE.exec(entry.name);
22
+ if (!match) continue;
23
+
24
+ const [, taskId, slug] = match;
25
+ const folderPath = path.join(tasksRoot, entry.name);
26
+ const promptPath = path.join(folderPath, "PROMPT.md");
27
+ if (!fs.existsSync(promptPath)) continue;
28
+
29
+ tasks.push({
30
+ taskId,
31
+ slug,
32
+ folderName: entry.name,
33
+ folderPath,
34
+ promptPath,
35
+ });
36
+ }
37
+
38
+ tasks.sort((a, b) => a.taskId.localeCompare(b.taskId));
39
+ return tasks;
40
+ }
@@ -0,0 +1,81 @@
1
+ /**
2
+ * Task packet parsers (FR-TASK-01–05).
3
+ *
4
+ * Usage (planner / preflight — see TP-008):
5
+ *
6
+ * ```js
7
+ * import {
8
+ * discoverTasks,
9
+ * loadDependenciesJson,
10
+ * loadTaskPacket,
11
+ * mergeTaskDeps,
12
+ * } from "./src/tasks/packet/index.mjs";
13
+ *
14
+ * const tasksRoot = "spine-tasks";
15
+ * const depsJson = loadDependenciesJson(tasksRoot);
16
+ *
17
+ * for (const discovered of discoverTasks(tasksRoot)) {
18
+ * const packet = loadTaskPacket(discovered.folderPath);
19
+ * const mergedDeps = mergeTaskDeps(
20
+ * { taskId: packet.prompt.taskId, prompt: packet.prompt },
21
+ * depsJson,
22
+ * );
23
+ * // packet.prompt.fileScope, packet.prompt.steps, mergedDeps → planner
24
+ * }
25
+ * ```
26
+ *
27
+ * Conformance: PRD §13, Taskplane reference task/status format docs.
28
+ */
29
+
30
+ import fs from "node:fs";
31
+ import path from "node:path";
32
+
33
+ import { parseStatus } from "./parse-status.mjs";
34
+ import { validatePrompt } from "./validate-prompt.mjs";
35
+
36
+ export { discoverTasks, TASK_FOLDER_RE } from "./discover.mjs";
37
+ export {
38
+ parsePrompt,
39
+ parsePromptDependencies,
40
+ parseContract,
41
+ CONTRACT_FIELD_NAMES,
42
+ TASK_HEADING_RE,
43
+ } from "./parse-prompt.mjs";
44
+ export { parseStatus, getStepProgress, listIncompleteSteps } from "./parse-status.mjs";
45
+ export { mergeDeps, mergeTaskDeps, loadDependenciesJson } from "./merge-deps.mjs";
46
+ export {
47
+ assertValidTaskPacket,
48
+ collectPromptValidationFailure,
49
+ formatPromptValidationFailures,
50
+ validatePrompt,
51
+ } from "./validate-prompt.mjs";
52
+ export {
53
+ validateContract,
54
+ resolveContractMode,
55
+ } from "./validate-contract.mjs";
56
+
57
+ /**
58
+ * Load PROMPT.md and STATUS.md for a task folder.
59
+ *
60
+ * @param {string} taskFolderPath Path to `{PREFIX-###-slug}/`
61
+ */
62
+ export function loadTaskPacket(taskFolderPath, options = {}) {
63
+ const promptPath = path.join(taskFolderPath, "PROMPT.md");
64
+ const promptMarkdown = fs.readFileSync(promptPath, "utf-8");
65
+ const validation = validatePrompt(promptMarkdown, options);
66
+ const prompt = validation.prompt;
67
+
68
+ const statusPath = path.join(taskFolderPath, "STATUS.md");
69
+ let status = null;
70
+ if (fs.existsSync(statusPath)) {
71
+ status = parseStatus(fs.readFileSync(statusPath, "utf-8"));
72
+ }
73
+
74
+ return {
75
+ promptPath,
76
+ statusPath: fs.existsSync(statusPath) ? statusPath : null,
77
+ prompt,
78
+ status,
79
+ validation,
80
+ };
81
+ }
@@ -0,0 +1,79 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+
4
+ import { parsePromptDependencies } from "./parse-prompt.mjs";
5
+
6
+ /**
7
+ * Merge PROMPT dependencies with dependencies.json entry.
8
+ * FR-TASK-05: union; when both sources define different ID sets, JSON wins.
9
+ *
10
+ * @param {string} taskId
11
+ * @param {string[]} promptDeps
12
+ * @param {{ tasks?: Record<string, string[]> }} dependenciesJson
13
+ * @returns {string[]}
14
+ */
15
+ export function mergeDeps(taskId, promptDeps, dependenciesJson) {
16
+ const jsonDeps = dependenciesJson?.tasks?.[taskId];
17
+ if (jsonDeps === undefined) {
18
+ return [...promptDeps];
19
+ }
20
+
21
+ const promptSet = new Set(promptDeps);
22
+ const jsonSet = new Set(jsonDeps);
23
+
24
+ if (promptSet.size === 0) {
25
+ return [...jsonDeps];
26
+ }
27
+
28
+ if (jsonSet.size === 0) {
29
+ return [...promptDeps];
30
+ }
31
+
32
+ const sameSet =
33
+ promptSet.size === jsonSet.size && [...promptSet].every((id) => jsonSet.has(id));
34
+
35
+ if (sameSet) {
36
+ return uniqueOrdered([...promptDeps, ...jsonDeps]);
37
+ }
38
+
39
+ return [...jsonDeps];
40
+ }
41
+
42
+ /**
43
+ * @param {{ dependenciesSection?: string, prompt?: { dependencies: string[] }, taskId: string }} task
44
+ * @param {{ tasks?: Record<string, string[]> }} dependenciesJson
45
+ */
46
+ export function mergeTaskDeps(task, dependenciesJson) {
47
+ const promptDeps =
48
+ task.prompt?.dependencies ??
49
+ (task.dependenciesSection
50
+ ? parsePromptDependencies(task.dependenciesSection)
51
+ : []);
52
+ return mergeDeps(task.taskId, promptDeps, dependenciesJson);
53
+ }
54
+
55
+ /**
56
+ * @param {string} tasksRoot
57
+ */
58
+ export function loadDependenciesJson(tasksRoot) {
59
+ const filePath = path.join(tasksRoot, "dependencies.json");
60
+ if (!fs.existsSync(filePath)) {
61
+ return { tasks: {} };
62
+ }
63
+ const raw = JSON.parse(fs.readFileSync(filePath, "utf-8"));
64
+ return {
65
+ version: raw.version,
66
+ tasks: raw.tasks ?? {},
67
+ };
68
+ }
69
+
70
+ function uniqueOrdered(ids) {
71
+ const seen = new Set();
72
+ const result = [];
73
+ for (const id of ids) {
74
+ if (seen.has(id)) continue;
75
+ seen.add(id);
76
+ result.push(id);
77
+ }
78
+ return result;
79
+ }
@@ -0,0 +1,445 @@
1
+ /** PRD §13.4 — em dash (U+2014) required between ID and title. */
2
+ export const TASK_HEADING_RE = /^# Task: ([A-Z][A-Z0-9]*-\d+) — (.+)$/m;
3
+
4
+ const REQUIRED_SECTIONS = [
5
+ "Mission",
6
+ "Dependencies",
7
+ "File Scope",
8
+ "Steps",
9
+ "Completion Criteria",
10
+ "Do NOT",
11
+ ];
12
+
13
+ const OPTIONAL_SECTIONS = ["Testing", "Context to Read First", "Environment", "Documentation Requirements"];
14
+
15
+ const H2_SECTION_RE = /^## (.+)$/gm;
16
+ const STEP_HEADING_RE = /^### Step (\d+): (.+)$/gm;
17
+ const SIZE_LINE_RE = /^\*\*Size:\*\*\s*(S|M|L|XL)\s*$/im;
18
+
19
+ /** Normative contract table fields per handoff §4.1. */
20
+ export const CONTRACT_FIELD_NAMES = Object.freeze([
21
+ "testCommand",
22
+ "fileScopeMustChange",
23
+ "fileScopeMustNotChange",
24
+ "minLineCoverage",
25
+ "artifactsMustExist",
26
+ ]);
27
+
28
+ const CONTRACT_KNOWN_FIELDS = new Set(CONTRACT_FIELD_NAMES);
29
+ const CONTRACT_TABLE_HEADER_RE = /^\|\s*Field\s*\|\s*Value\s*\|$/i;
30
+ const CONTRACT_TABLE_SEPARATOR_RE = /^\|[\s\-:|]+\|$/;
31
+ const CONTRACT_TABLE_ROW_RE = /^\|\s*([^|]+?)\s*\|\s*([^|]+?)\s*\|$/;
32
+ const TEST_COMMAND_MAX_LENGTH = 500;
33
+ export const SEE_FILE_SCOPE_RE = /^see\s+file\s+scope$/i;
34
+ const CONTRACT_EM_DASH_PLACEHOLDER_RE = /^[—\-]$/;
35
+ const CONTRACT_NONE_VALUES = new Set(["—", "-", "none", "n/a", "na"]);
36
+
37
+ /**
38
+ * @param {string} markdown PROMPT.md contents
39
+ */
40
+ export function parsePrompt(markdown) {
41
+ const headingMatch = TASK_HEADING_RE.exec(markdown);
42
+ const taskId = headingMatch?.[1] ?? null;
43
+ const title = headingMatch?.[2]?.trim() ?? null;
44
+ const headingLine = headingMatch ? lineNumberAt(markdown, headingMatch.index) : null;
45
+
46
+ const sections = extractH2Sections(markdown);
47
+ const steps = parseSteps(sections.Steps ?? "");
48
+ const fileScope = parseBulletPaths(sections["File Scope"] ?? "");
49
+ const dependencies = parsePromptDependencies(sections.Dependencies ?? "");
50
+ const hasTesting =
51
+ Boolean(sections.Testing) ||
52
+ steps.some((step) => /testing/i.test(step.title));
53
+
54
+ const missingSections = REQUIRED_SECTIONS.filter((name) => !sections[name]);
55
+ const sizeMatch = SIZE_LINE_RE.exec(markdown);
56
+ const size = sizeMatch ? sizeMatch[1].toUpperCase() : null;
57
+
58
+ return {
59
+ taskId,
60
+ title,
61
+ size,
62
+ headingLine,
63
+ sections,
64
+ steps,
65
+ fileScope,
66
+ dependencies,
67
+ hasTesting,
68
+ missingSections,
69
+ requiredSections: REQUIRED_SECTIONS,
70
+ optionalSections: OPTIONAL_SECTIONS,
71
+ };
72
+ }
73
+
74
+ /**
75
+ * @param {string} markdown
76
+ */
77
+ export function validatePrompt(markdown) {
78
+ const prompt = parsePrompt(markdown);
79
+ const errors = [];
80
+
81
+ if (!prompt.taskId || !prompt.title) {
82
+ errors.push(
83
+ "Missing or invalid heading; expected `# Task: PREFIX-### — Name` with em dash (U+2014)",
84
+ );
85
+ }
86
+
87
+ if (prompt.missingSections.length > 0) {
88
+ errors.push(`Missing required sections: ${prompt.missingSections.join(", ")}`);
89
+ }
90
+
91
+ if (!prompt.hasTesting) {
92
+ errors.push('Missing testing coverage: add `## Testing` or a step titled "Testing"');
93
+ }
94
+
95
+ if (prompt.steps.length === 0) {
96
+ errors.push("No steps found; expected `### Step N: ...` headings under ## Steps");
97
+ }
98
+
99
+ if (prompt.size === "XL") {
100
+ errors.push('Size XL is not allowed — split into multiple S/M tasks (see create-spine-tasks skill)');
101
+ }
102
+
103
+ return { ok: errors.length === 0, errors, prompt };
104
+ }
105
+
106
+ /**
107
+ * Parse the `## Contract` Markdown table from PROMPT.md (handoff §4.3).
108
+ *
109
+ * @param {string} markdown PROMPT.md contents
110
+ * @returns {{
111
+ * testCommand: string | null,
112
+ * fileScopeMustChange: string[],
113
+ * fileScopeMustNotChange: string[],
114
+ * minLineCoverage: number | null,
115
+ * artifactsMustExist: string[],
116
+ * rawTableValid: boolean,
117
+ * errors: string[],
118
+ * unknownFields: string[],
119
+ * hasSection: boolean,
120
+ * rawFieldValues: Record<string, string>,
121
+ * placeholderIssues: string[],
122
+ * }}
123
+ */
124
+ export function parseContract(markdown) {
125
+ const sections = extractH2Sections(markdown);
126
+ const contractSection = sections.Contract ?? "";
127
+ const fileScopePaths = parseBulletPaths(sections["File Scope"] ?? "");
128
+
129
+ /** @type {ReturnType<typeof parseContract>} */
130
+ const parsed = {
131
+ testCommand: null,
132
+ fileScopeMustChange: [],
133
+ fileScopeMustNotChange: [],
134
+ minLineCoverage: null,
135
+ artifactsMustExist: [],
136
+ rawTableValid: false,
137
+ errors: [],
138
+ unknownFields: [],
139
+ hasSection: Object.hasOwn(sections, "Contract"),
140
+ rawFieldValues: {},
141
+ placeholderIssues: [],
142
+ };
143
+
144
+ if (!parsed.hasSection) {
145
+ return parsed;
146
+ }
147
+
148
+ const tableRows = extractContractTableRows(contractSection);
149
+ if (tableRows === null) {
150
+ parsed.errors.push('Contract section must contain a Markdown table with header row "| Field | Value |"');
151
+ return parsed;
152
+ }
153
+
154
+ parsed.rawTableValid = true;
155
+ const seenFields = new Set();
156
+
157
+ for (const { field, value } of tableRows) {
158
+ if (seenFields.has(field)) {
159
+ parsed.errors.push(`Duplicate contract field row: ${field}`);
160
+ continue;
161
+ }
162
+ seenFields.add(field);
163
+
164
+ if (!CONTRACT_KNOWN_FIELDS.has(field)) {
165
+ parsed.unknownFields.push(field);
166
+ continue;
167
+ }
168
+
169
+ parsed.rawFieldValues[field] = value;
170
+ applyContractField(parsed, field, value);
171
+ }
172
+
173
+ resolveContractFileScopeReferences(parsed, fileScopePaths);
174
+ parsed.placeholderIssues = detectContractPlaceholderIssues(parsed, fileScopePaths);
175
+
176
+ return parsed;
177
+ }
178
+
179
+ /**
180
+ * @param {ReturnType<typeof parseContract>} parsed
181
+ * @param {string[]} fileScopePaths
182
+ * @returns {string[]}
183
+ */
184
+ export function detectContractPlaceholderIssues(parsed, fileScopePaths) {
185
+ /** @type {string[]} */
186
+ const issues = [];
187
+ const raw = parsed.rawFieldValues ?? {};
188
+
189
+ for (const field of ["fileScopeMustChange", "fileScopeMustNotChange", "artifactsMustExist"]) {
190
+ const value = String(raw[field] ?? "").trim();
191
+ if (!value) {
192
+ continue;
193
+ }
194
+
195
+ if (SEE_FILE_SCOPE_RE.test(value)) {
196
+ if (fileScopePaths.length === 0) {
197
+ issues.push(
198
+ `Contract ${field}: unresolved "see File Scope" placeholder (empty File Scope section)`,
199
+ );
200
+ }
201
+ continue;
202
+ }
203
+
204
+ if (CONTRACT_EM_DASH_PLACEHOLDER_RE.test(value)) {
205
+ issues.push(`Contract ${field}: em-dash placeholder; use an empty cell instead`);
206
+ }
207
+ }
208
+
209
+ return issues;
210
+ }
211
+
212
+ /**
213
+ * Expand contract placeholders such as "see File Scope" into concrete paths.
214
+ *
215
+ * @param {ReturnType<typeof parseContract>} parsed
216
+ * @param {string[]} fileScopePaths
217
+ */
218
+ export function resolveContractFileScopeReferences(parsed, fileScopePaths) {
219
+ /** @type {string[]} */
220
+ const expanded = [];
221
+ for (const pattern of parsed.fileScopeMustChange ?? []) {
222
+ if (SEE_FILE_SCOPE_RE.test(pattern.trim())) {
223
+ expanded.push(...fileScopePaths);
224
+ continue;
225
+ }
226
+ expanded.push(pattern);
227
+ }
228
+ parsed.fileScopeMustChange = [...new Set(expanded)];
229
+ }
230
+
231
+ /**
232
+ * @param {ReturnType<typeof parseContract>} parsed
233
+ * @param {string} field
234
+ * @param {string} rawValue
235
+ */
236
+ function applyContractField(parsed, field, rawValue) {
237
+ const value = rawValue.trim();
238
+ if (!value) {
239
+ return;
240
+ }
241
+
242
+ switch (field) {
243
+ case "testCommand": {
244
+ const command = parseContractScalar(value);
245
+ if (command.includes("\n")) {
246
+ parsed.errors.push("Contract testCommand must not contain newlines");
247
+ return;
248
+ }
249
+ if (command.length > TEST_COMMAND_MAX_LENGTH) {
250
+ parsed.errors.push(`Contract testCommand exceeds ${TEST_COMMAND_MAX_LENGTH} characters`);
251
+ return;
252
+ }
253
+ parsed.testCommand = command;
254
+ return;
255
+ }
256
+ case "fileScopeMustChange":
257
+ parsed.fileScopeMustChange = parseContractPathList(value);
258
+ return;
259
+ case "fileScopeMustNotChange":
260
+ parsed.fileScopeMustNotChange = parseContractPathList(value);
261
+ return;
262
+ case "artifactsMustExist":
263
+ parsed.artifactsMustExist = parseContractPathList(value);
264
+ return;
265
+ case "minLineCoverage": {
266
+ const coverage = parseContractScalar(value);
267
+ if (!/^\d+$/.test(coverage)) {
268
+ parsed.errors.push("Contract minLineCoverage must be an integer between 0 and 100");
269
+ return;
270
+ }
271
+ const numeric = Number(coverage);
272
+ if (numeric < 0 || numeric > 100) {
273
+ parsed.errors.push("Contract minLineCoverage must be an integer between 0 and 100");
274
+ return;
275
+ }
276
+ parsed.minLineCoverage = numeric;
277
+ return;
278
+ }
279
+ default:
280
+ return;
281
+ }
282
+ }
283
+
284
+ /**
285
+ * @param {string} section
286
+ * @returns {Array<{ field: string, value: string }> | null}
287
+ */
288
+ function extractContractTableRows(section) {
289
+ /** @type {Array<{ field: string, value: string }>} */
290
+ const rows = [];
291
+ let sawHeader = false;
292
+ let sawSeparator = false;
293
+
294
+ for (const line of section.split(/\r?\n/)) {
295
+ const trimmed = line.trim();
296
+ if (!trimmed.startsWith("|")) {
297
+ continue;
298
+ }
299
+
300
+ if (CONTRACT_TABLE_HEADER_RE.test(trimmed)) {
301
+ sawHeader = true;
302
+ continue;
303
+ }
304
+
305
+ if (CONTRACT_TABLE_SEPARATOR_RE.test(trimmed)) {
306
+ if (!sawHeader) {
307
+ return null;
308
+ }
309
+ sawSeparator = true;
310
+ continue;
311
+ }
312
+
313
+ const match = trimmed.match(CONTRACT_TABLE_ROW_RE);
314
+ if (!match) {
315
+ return null;
316
+ }
317
+
318
+ if (!sawHeader || !sawSeparator) {
319
+ return null;
320
+ }
321
+
322
+ rows.push({ field: match[1].trim(), value: match[2].trim() });
323
+ }
324
+
325
+ if (!sawHeader || !sawSeparator) {
326
+ return null;
327
+ }
328
+
329
+ return rows;
330
+ }
331
+
332
+ /**
333
+ * @param {string} raw
334
+ * @returns {string}
335
+ */
336
+ function parseContractScalar(raw) {
337
+ const backtick = raw.match(/^`([^`]*)`$/);
338
+ if (backtick) {
339
+ return backtick[1];
340
+ }
341
+ return raw;
342
+ }
343
+
344
+ /**
345
+ * @param {string} raw
346
+ * @returns {string[]}
347
+ */
348
+ function parseContractPathList(raw) {
349
+ return raw
350
+ .split(",")
351
+ .map((part) => parseContractScalar(part.trim()))
352
+ .filter((part) => part && !isContractNoneValue(part));
353
+ }
354
+
355
+ /**
356
+ * @param {string} value
357
+ */
358
+ function isContractNoneValue(value) {
359
+ const normalized = String(value ?? "").trim().toLowerCase();
360
+ return !normalized || CONTRACT_NONE_VALUES.has(normalized);
361
+ }
362
+
363
+ /**
364
+ * @param {string} depsSection
365
+ * @returns {string[]}
366
+ */
367
+ export function parsePromptDependencies(depsSection) {
368
+ const trimmed = depsSection.trim();
369
+ if (!trimmed || /\*\*None\*\*/i.test(trimmed) || /^-\s+\*\*None\*\*/im.test(trimmed)) {
370
+ return [];
371
+ }
372
+
373
+ const ids = [];
374
+ for (const line of depsSection.split(/\r?\n/)) {
375
+ const bullet = line.match(/^-\s+\*{0,2}([A-Z][A-Z0-9]*-\d+)\*{0,2}/);
376
+ if (bullet) {
377
+ if (!ids.includes(bullet[1])) ids.push(bullet[1]);
378
+ continue;
379
+ }
380
+ const bare = line.match(/^-\s+([A-Z][A-Z0-9]*-\d+)\b/);
381
+ if (bare) {
382
+ if (!ids.includes(bare[1])) ids.push(bare[1]);
383
+ continue;
384
+ }
385
+ const requires = line.match(/\*+Requires:\*+\s*(?:[a-z0-9-]+\/)?([A-Z][A-Z0-9]*-\d+)/i);
386
+ if (requires && !ids.includes(requires[1])) ids.push(requires[1]);
387
+ }
388
+ return ids;
389
+ }
390
+
391
+ /**
392
+ * @param {string} content
393
+ * @returns {Record<string, string>}
394
+ */
395
+ function extractH2Sections(content) {
396
+ const sections = {};
397
+ const matches = [...content.matchAll(H2_SECTION_RE)];
398
+
399
+ for (let i = 0; i < matches.length; i++) {
400
+ const name = matches[i][1].trim();
401
+ const start = matches[i].index + matches[i][0].length;
402
+ const end = i + 1 < matches.length ? matches[i + 1].index : content.length;
403
+ sections[name] = content.slice(start, end).trim();
404
+ }
405
+
406
+ return sections;
407
+ }
408
+
409
+ /**
410
+ * @param {string} stepsSection
411
+ */
412
+ function parseSteps(stepsSection) {
413
+ const steps = [];
414
+ const matches = [...stepsSection.matchAll(STEP_HEADING_RE)];
415
+
416
+ for (let i = 0; i < matches.length; i++) {
417
+ const number = Number(matches[i][1]);
418
+ const title = matches[i][2].trim();
419
+ const start = matches[i].index + matches[i][0].length;
420
+ const end = i + 1 < matches.length ? matches[i + 1].index : stepsSection.length;
421
+ steps.push({ number, title, body: stepsSection.slice(start, end).trim() });
422
+ }
423
+
424
+ return steps;
425
+ }
426
+
427
+ /**
428
+ * @param {string} section
429
+ * @returns {string[]}
430
+ */
431
+ function parseBulletPaths(section) {
432
+ const paths = [];
433
+ for (const line of section.split(/\r?\n/)) {
434
+ if (/\(optional\b/i.test(line) || /\bonly if\b/i.test(line)) {
435
+ continue;
436
+ }
437
+ const match = line.match(/^-\s+`([^`]+)`/);
438
+ if (match) paths.push(match[1]);
439
+ }
440
+ return paths;
441
+ }
442
+
443
+ function lineNumberAt(text, index) {
444
+ return text.slice(0, index).split(/\r?\n/).length;
445
+ }