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,416 @@
1
+ /**
2
+ * Discover `.cursor/rules/` and build `.spine/rules-manifest.json`.
3
+ */
4
+
5
+ import fs from "node:fs";
6
+ import path from "node:path";
7
+ import { execFileSync } from "node:child_process";
8
+ import { randomBytes } from "node:crypto";
9
+
10
+ import micromatch from "micromatch";
11
+
12
+ import { parseCursorRuleFrontmatter } from "./parse-frontmatter.mjs";
13
+ import { DEFAULT_RULES_PROFILE, loadRulesProfile } from "./profile.mjs";
14
+
15
+ /** Relative path from project root to Cursor rules directory. */
16
+ export const CURSOR_RULES_ROOT_REL = ".cursor/rules";
17
+
18
+ /** Relative path from project root to committed rules manifest. */
19
+ export const RULES_MANIFEST_REL_PATH = ".spine/rules-manifest.json";
20
+
21
+ /** Maximum discovered rule files per scan. */
22
+ export const DISCOVER_MAX_FILES = 200;
23
+
24
+ /** Maximum bytes read per rule file. */
25
+ export const DISCOVER_MAX_FILE_BYTES = 512 * 1024;
26
+
27
+ const RULE_FILE_RE = /\.(mdc|md)$/i;
28
+
29
+ /**
30
+ * @typedef {"always" | "glob" | "manual" | "excluded"} CursorRuleSpineClass
31
+ */
32
+
33
+ /**
34
+ * @typedef {object} CursorRuleManifestEntry
35
+ * @property {string} relPath Path relative to `.cursor/rules/` (posix)
36
+ * @property {Exclude<CursorRuleSpineClass, "excluded">} spineClass
37
+ * @property {boolean} alwaysApply
38
+ * @property {string|null} description
39
+ * @property {string[]} globs
40
+ * @property {"ok" | "skip" | "warn"} parseStatus
41
+ * @property {string[]} [warnings]
42
+ */
43
+
44
+ /**
45
+ * @typedef {object} CursorRuleExcludedEntry
46
+ * @property {string} relPath Path relative to `.cursor/rules/` (posix)
47
+ * @property {"excludePattern" | "excludeRelPath"} reason
48
+ * @property {CursorRuleSpineClass} spineClass Always `"excluded"`
49
+ */
50
+
51
+ /**
52
+ * @typedef {object} CursorRulesManifest
53
+ * @property {string} generatedAt ISO-8601 timestamp
54
+ * @property {string} rulesRoot Relative path to rules directory (posix)
55
+ * @property {CursorRuleManifestEntry[]} rules
56
+ * @property {CursorRuleExcludedEntry[]} excluded
57
+ * @property {string[]} [warnings] Non-fatal discovery issues (truncation, oversize files)
58
+ */
59
+
60
+ /**
61
+ * @typedef {object} DiscoverCursorRulesResult
62
+ * @property {true} ok
63
+ * @property {CursorRulesManifest} manifest
64
+ * @property {string} [manifestPath] Written manifest path when `writeManifest` is true
65
+ */
66
+
67
+ /**
68
+ * @param {string} relPath
69
+ * @returns {string}
70
+ */
71
+ function toPosixRelPath(relPath) {
72
+ return relPath.replace(/\\/g, "/").replace(/^\.\/+/, "");
73
+ }
74
+
75
+ /**
76
+ * @param {import("./profile.mjs").RulesProfileDiscovery} discovery
77
+ * @param {string} relPath
78
+ * @returns {"excludePattern" | "excludeRelPath" | null}
79
+ */
80
+ export function getCursorRuleExclusionReason(discovery, relPath) {
81
+ const normalized = toPosixRelPath(relPath);
82
+ const relPathSet = new Set(discovery.excludeRelPaths.map(toPosixRelPath));
83
+ if (relPathSet.has(normalized)) {
84
+ return "excludeRelPath";
85
+ }
86
+
87
+ const matchTargets = [normalized];
88
+ const baseName = path.posix.basename(normalized);
89
+ const stem = baseName.replace(/\.(mdc|md)$/i, "");
90
+ if (stem !== normalized) {
91
+ matchTargets.push(stem);
92
+ }
93
+ if (baseName !== normalized) {
94
+ matchTargets.push(baseName);
95
+ }
96
+
97
+ for (const target of matchTargets) {
98
+ if (micromatch.isMatch(target, discovery.excludePatterns)) {
99
+ return "excludePattern";
100
+ }
101
+ }
102
+ return null;
103
+ }
104
+
105
+ /**
106
+ * @param {ReturnType<typeof parseCursorRuleFrontmatter>} parsed
107
+ * @returns {Exclude<CursorRuleSpineClass, "excluded">}
108
+ */
109
+ export function classifyCursorRuleSpineClass(parsed) {
110
+ if (parsed.alwaysApply) {
111
+ return "always";
112
+ }
113
+ if (parsed.globs.length > 0) {
114
+ return "glob";
115
+ }
116
+ return "manual";
117
+ }
118
+
119
+ /**
120
+ * @param {ReturnType<typeof parseCursorRuleFrontmatter>} parsed
121
+ * @returns {CursorRuleManifestEntry}
122
+ */
123
+ export function buildCursorRuleManifestEntry(parsed) {
124
+ /** @type {CursorRuleManifestEntry} */
125
+ const entry = {
126
+ relPath: parsed.relPath,
127
+ spineClass: classifyCursorRuleSpineClass(parsed),
128
+ alwaysApply: parsed.alwaysApply,
129
+ description: parsed.description,
130
+ globs: parsed.globs,
131
+ parseStatus: parsed.parseStatus,
132
+ };
133
+ if (parsed.warnings.length > 0) {
134
+ entry.warnings = parsed.warnings;
135
+ }
136
+ return entry;
137
+ }
138
+
139
+ /**
140
+ * Recursively collect `.mdc`/`.md` paths under `rulesRoot`, sorted by posix relPath.
141
+ *
142
+ * @param {string} rulesRootAbs
143
+ * @param {string} [currentAbs]
144
+ * @returns {string[]} Absolute file paths
145
+ */
146
+ function collectRuleFiles(rulesRootAbs, currentAbs = rulesRootAbs) {
147
+ /** @type {string[]} */
148
+ const files = [];
149
+
150
+ if (!fs.existsSync(currentAbs)) {
151
+ return files;
152
+ }
153
+
154
+ for (const entry of fs.readdirSync(currentAbs, { withFileTypes: true })) {
155
+ const absPath = path.join(currentAbs, entry.name);
156
+ if (entry.isDirectory()) {
157
+ files.push(...collectRuleFiles(rulesRootAbs, absPath));
158
+ continue;
159
+ }
160
+ if (entry.isFile() && RULE_FILE_RE.test(entry.name)) {
161
+ files.push(absPath);
162
+ }
163
+ }
164
+
165
+ return files.sort((left, right) =>
166
+ toPosixRelPath(path.relative(rulesRootAbs, left)).localeCompare(
167
+ toPosixRelPath(path.relative(rulesRootAbs, right)),
168
+ ),
169
+ );
170
+ }
171
+
172
+ /**
173
+ * @param {string} projectRoot
174
+ * @param {CursorRulesManifest} manifest
175
+ */
176
+ export function writeRulesManifestAtomic(projectRoot, manifest) {
177
+ const manifestPath = path.join(projectRoot, RULES_MANIFEST_REL_PATH);
178
+ const dir = path.dirname(manifestPath);
179
+ fs.mkdirSync(dir, { recursive: true });
180
+
181
+ const tmpPath = `${manifestPath}.${process.pid}.${randomBytes(4).toString("hex")}.tmp`;
182
+ const content = `${JSON.stringify(manifest, null, 2)}\n`;
183
+
184
+ try {
185
+ fs.writeFileSync(tmpPath, content, "utf-8");
186
+ fs.renameSync(tmpPath, manifestPath);
187
+ } catch (err) {
188
+ try {
189
+ if (fs.existsSync(tmpPath)) {
190
+ fs.unlinkSync(tmpPath);
191
+ }
192
+ } catch {
193
+ // ignore cleanup failure
194
+ }
195
+ throw err;
196
+ }
197
+
198
+ return manifestPath;
199
+ }
200
+
201
+ /**
202
+ * @param {object} params
203
+ * @param {string} params.projectRoot
204
+ * @param {import("./profile.mjs").RulesProfile} [params.profile]
205
+ * @param {boolean} [params.writeManifest]
206
+ * @returns {DiscoverCursorRulesResult}
207
+ */
208
+ export function discoverCursorRules({ projectRoot, profile, writeManifest = true }) {
209
+ const profileResult = profile ? { ok: true, profile } : loadRulesProfile(projectRoot);
210
+ const resolvedProfile =
211
+ profileResult.ok && profileResult.profile ? profileResult.profile : DEFAULT_RULES_PROFILE;
212
+ const rulesRootAbs = path.join(projectRoot, CURSOR_RULES_ROOT_REL);
213
+ const allFiles = collectRuleFiles(rulesRootAbs);
214
+
215
+ /** @type {string[]} */
216
+ const warnings = [];
217
+ const scannedFiles = allFiles.slice(0, DISCOVER_MAX_FILES);
218
+ if (allFiles.length > DISCOVER_MAX_FILES) {
219
+ warnings.push(
220
+ `truncated discovery at ${DISCOVER_MAX_FILES} files (${allFiles.length} found)`,
221
+ );
222
+ }
223
+
224
+ /** @type {CursorRuleManifestEntry[]} */
225
+ const rules = [];
226
+ /** @type {CursorRuleExcludedEntry[]} */
227
+ const excluded = [];
228
+
229
+ for (const absPath of scannedFiles) {
230
+ const relPath = toPosixRelPath(path.relative(rulesRootAbs, absPath));
231
+ const exclusionReason = getCursorRuleExclusionReason(resolvedProfile.discovery, relPath);
232
+ if (exclusionReason) {
233
+ excluded.push({
234
+ relPath,
235
+ reason: exclusionReason,
236
+ spineClass: "excluded",
237
+ });
238
+ continue;
239
+ }
240
+
241
+ const stat = fs.statSync(absPath);
242
+ if (stat.size > DISCOVER_MAX_FILE_BYTES) {
243
+ warnings.push(`skipped oversize rule file (${stat.size} bytes): ${relPath}`);
244
+ const parsed = parseCursorRuleFrontmatter("", relPath);
245
+ const entry = buildCursorRuleManifestEntry({
246
+ ...parsed,
247
+ parseStatus: "warn",
248
+ warnings: [
249
+ ...parsed.warnings,
250
+ `file exceeds ${DISCOVER_MAX_FILE_BYTES} byte limit`,
251
+ ],
252
+ });
253
+ rules.push(entry);
254
+ continue;
255
+ }
256
+
257
+ const content = fs.readFileSync(absPath, "utf-8");
258
+ const parsed = parseCursorRuleFrontmatter(content, relPath);
259
+ rules.push(buildCursorRuleManifestEntry(parsed));
260
+ }
261
+
262
+ /** @type {CursorRulesManifest} */
263
+ const manifest = {
264
+ generatedAt: new Date().toISOString(),
265
+ rulesRoot: CURSOR_RULES_ROOT_REL,
266
+ rules,
267
+ excluded,
268
+ };
269
+ if (warnings.length > 0) {
270
+ manifest.warnings = warnings;
271
+ }
272
+
273
+ /** @type {DiscoverCursorRulesResult} */
274
+ const result = { ok: true, manifest };
275
+ if (writeManifest) {
276
+ result.manifestPath = writeRulesManifestAtomic(projectRoot, manifest);
277
+ }
278
+ return result;
279
+ }
280
+
281
+ /**
282
+ * Stable fingerprint for semantic comparison (ignores `generatedAt`).
283
+ *
284
+ * @param {CursorRulesManifest} manifest
285
+ */
286
+ export function fingerprintRulesManifest(manifest) {
287
+ const payload = {
288
+ rulesRoot: manifest.rulesRoot,
289
+ rules: [...manifest.rules]
290
+ .map((rule) => ({
291
+ relPath: rule.relPath,
292
+ spineClass: rule.spineClass,
293
+ alwaysApply: rule.alwaysApply,
294
+ description: rule.description,
295
+ globs: rule.globs,
296
+ parseStatus: rule.parseStatus,
297
+ warnings: rule.warnings ?? [],
298
+ }))
299
+ .sort((left, right) => left.relPath.localeCompare(right.relPath)),
300
+ excluded: [...manifest.excluded]
301
+ .map((entry) => ({
302
+ relPath: entry.relPath,
303
+ reason: entry.reason,
304
+ spineClass: entry.spineClass,
305
+ }))
306
+ .sort((left, right) => left.relPath.localeCompare(right.relPath)),
307
+ warnings: manifest.warnings ?? [],
308
+ };
309
+ return JSON.stringify(payload);
310
+ }
311
+
312
+ /**
313
+ * @param {string} text
314
+ */
315
+ export function parseRulesManifestJson(text) {
316
+ try {
317
+ return {
318
+ ok: /** @type {const} */ (true),
319
+ manifest: /** @type {CursorRulesManifest} */ (JSON.parse(text)),
320
+ };
321
+ } catch (err) {
322
+ return {
323
+ ok: /** @type {const} */ (false),
324
+ error: err instanceof Error ? err.message : String(err),
325
+ };
326
+ }
327
+ }
328
+
329
+ /**
330
+ * Merge two manifest versions when only `generatedAt` differs.
331
+ *
332
+ * @param {object} params
333
+ * @param {CursorRulesManifest} params.ours
334
+ * @param {CursorRulesManifest} params.theirs
335
+ */
336
+ export function resolveRulesManifestGeneratedAtMerge({ ours, theirs }) {
337
+ if (fingerprintRulesManifest(ours) !== fingerprintRulesManifest(theirs)) {
338
+ return {
339
+ ok: /** @type {const} */ (false),
340
+ failureClass: "RulesManifestMergeConflict",
341
+ error:
342
+ "Cannot auto-merge .spine/rules-manifest.json: rules[] (or excluded/rulesRoot) differ between orch and lane",
343
+ };
344
+ }
345
+
346
+ const oursMs = Date.parse(ours.generatedAt);
347
+ const theirsMs = Date.parse(theirs.generatedAt);
348
+ const generatedAt =
349
+ Number.isFinite(oursMs) && Number.isFinite(theirsMs)
350
+ ? oursMs >= theirsMs
351
+ ? ours.generatedAt
352
+ : theirs.generatedAt
353
+ : ours.generatedAt >= theirs.generatedAt
354
+ ? ours.generatedAt
355
+ : theirs.generatedAt;
356
+
357
+ return {
358
+ ok: /** @type {const} */ (true),
359
+ manifest: { ...ours, generatedAt },
360
+ };
361
+ }
362
+
363
+ /**
364
+ * @param {string} projectRoot
365
+ * @returns {CursorRulesManifest | null}
366
+ */
367
+ export function loadRulesManifest(projectRoot) {
368
+ const manifestPath = path.join(projectRoot, RULES_MANIFEST_REL_PATH);
369
+ if (!fs.existsSync(manifestPath)) {
370
+ return null;
371
+ }
372
+ return /** @type {CursorRulesManifest} */ (JSON.parse(fs.readFileSync(manifestPath, "utf-8")));
373
+ }
374
+
375
+ /**
376
+ * True when the only dirty path is `.spine/rules-manifest.json` and rules[] fingerprint matches HEAD.
377
+ *
378
+ * @param {string} projectRoot
379
+ * @param {string[]} dirtyPaths Trimmed paths from `git status --porcelain` (no status prefix).
380
+ * @returns {{ ok: boolean, reason?: string, manifestPath?: string }}
381
+ */
382
+ export function isRulesManifestGeneratedAtOnlyDrift(projectRoot, dirtyPaths) {
383
+ const normalized = (dirtyPaths ?? []).map((entry) => String(entry).trim()).filter(Boolean);
384
+ if (normalized.length !== 1 || normalized[0] !== RULES_MANIFEST_REL_PATH) {
385
+ return { ok: false, reason: "not_manifest_only" };
386
+ }
387
+
388
+ const manifestPath = path.join(projectRoot, RULES_MANIFEST_REL_PATH);
389
+ if (!fs.existsSync(manifestPath)) {
390
+ return { ok: false, reason: "manifest_missing" };
391
+ }
392
+
393
+ let headText = "";
394
+ try {
395
+ headText = execFileSync("git", ["show", `HEAD:${RULES_MANIFEST_REL_PATH}`], {
396
+ cwd: projectRoot,
397
+ encoding: "utf-8",
398
+ stdio: ["ignore", "pipe", "pipe"],
399
+ timeout: 5000,
400
+ });
401
+ } catch {
402
+ return { ok: false, reason: "no_head_manifest" };
403
+ }
404
+
405
+ const headParsed = parseRulesManifestJson(headText);
406
+ const workParsed = parseRulesManifestJson(fs.readFileSync(manifestPath, "utf-8"));
407
+ if (!headParsed.ok || !workParsed.ok) {
408
+ return { ok: false, reason: "manifest_parse_error" };
409
+ }
410
+
411
+ if (fingerprintRulesManifest(headParsed.manifest) !== fingerprintRulesManifest(workParsed.manifest)) {
412
+ return { ok: false, reason: "rules_content_drift" };
413
+ }
414
+
415
+ return { ok: true, manifestPath: RULES_MANIFEST_REL_PATH };
416
+ }
@@ -0,0 +1,39 @@
1
+ /**
2
+ * Cursor rules discovery (SP-089 parser/profile, SP-090 manifest).
3
+ * @module config/cursor-rules
4
+ */
5
+
6
+ export { parseCursorRuleFrontmatter } from "./parse-frontmatter.mjs";
7
+ export {
8
+ DEFAULT_RULES_PROFILE,
9
+ RULES_PROFILE_REL_PATH,
10
+ loadRulesProfile,
11
+ mergeRulesProfile,
12
+ validateRulesProfile,
13
+ } from "./profile.mjs";
14
+ export {
15
+ buildCursorRuleManifestEntry,
16
+ classifyCursorRuleSpineClass,
17
+ CURSOR_RULES_ROOT_REL,
18
+ DISCOVER_MAX_FILE_BYTES,
19
+ DISCOVER_MAX_FILES,
20
+ discoverCursorRules,
21
+ getCursorRuleExclusionReason,
22
+ loadRulesManifest,
23
+ RULES_MANIFEST_REL_PATH,
24
+ writeRulesManifestAtomic,
25
+ } from "./discover.mjs";
26
+ export {
27
+ expandFileScopeProbes,
28
+ ruleGlobsMatchFileScope,
29
+ SYNTHETIC_PROBE_EXTENSIONS,
30
+ } from "./match-globs.mjs";
31
+ export { priorityRank } from "./priority.mjs";
32
+ export {
33
+ contextPathToRuleRelPath,
34
+ DEFAULT_SELECT_MAX_RULES,
35
+ ruleRelPathToContextPath,
36
+ selectRulesForReviewer,
37
+ selectRulesForWorker,
38
+ selectRulesFromManifest,
39
+ } from "./select.mjs";
@@ -0,0 +1,132 @@
1
+ /**
2
+ * Micromatch helpers for PROMPT File Scope vs rule globs (SP-091).
3
+ */
4
+
5
+ import micromatch from "micromatch";
6
+
7
+ /** Synthetic extensions used when expanding directory or wildcard scope entries. */
8
+ export const SYNTHETIC_PROBE_EXTENSIONS = Object.freeze([
9
+ ".mjs",
10
+ ".js",
11
+ ".ts",
12
+ ".tsx",
13
+ ".swift",
14
+ ".py",
15
+ ".go",
16
+ ".java",
17
+ ".rs",
18
+ ".md",
19
+ ]);
20
+
21
+ const PROBE_BASENAME = "__probe__";
22
+
23
+ /**
24
+ * @param {string} raw
25
+ * @returns {string}
26
+ */
27
+ function normalizeScopePath(raw) {
28
+ return raw.trim().replace(/\\/g, "/").replace(/^\.\/+/, "");
29
+ }
30
+
31
+ /**
32
+ * Expand PROMPT File Scope paths into concrete probe paths for glob matching.
33
+ * Handles literals, `dir/*`, `dir/**`, and in-path wildcards (e.g. `bin/*.mjs`).
34
+ *
35
+ * @param {string[]} fileScope
36
+ * @returns {string[]}
37
+ */
38
+ export function expandFileScopeProbes(fileScope) {
39
+ if (!Array.isArray(fileScope) || fileScope.length === 0) {
40
+ return [];
41
+ }
42
+
43
+ /** @type {Set<string>} */
44
+ const probes = new Set();
45
+
46
+ for (const raw of fileScope) {
47
+ const entry = normalizeScopePath(raw);
48
+ if (!entry) {
49
+ continue;
50
+ }
51
+
52
+ probes.add(entry);
53
+
54
+ if (entry.endsWith("/**")) {
55
+ const base = entry.slice(0, -3);
56
+ for (const ext of SYNTHETIC_PROBE_EXTENSIONS) {
57
+ probes.add(`${base}/${PROBE_BASENAME}/${PROBE_BASENAME}${ext}`);
58
+ probes.add(`${base}/nested/${PROBE_BASENAME}${ext}`);
59
+ }
60
+ continue;
61
+ }
62
+
63
+ if (entry.endsWith("/*")) {
64
+ const base = entry.slice(0, -2);
65
+ for (const ext of SYNTHETIC_PROBE_EXTENSIONS) {
66
+ probes.add(`${base}/${PROBE_BASENAME}${ext}`);
67
+ }
68
+ continue;
69
+ }
70
+
71
+ if (entry.includes("*")) {
72
+ probes.add(entry.replace(/\*/g, PROBE_BASENAME));
73
+ continue;
74
+ }
75
+
76
+ const baseName = entry.split("/").pop() ?? "";
77
+ if (!/\.\w[\w\d]*$/.test(baseName)) {
78
+ for (const ext of SYNTHETIC_PROBE_EXTENSIONS) {
79
+ probes.add(`${entry}/${PROBE_BASENAME}${ext}`);
80
+ }
81
+ }
82
+ }
83
+
84
+ return [...probes];
85
+ }
86
+
87
+ /**
88
+ * @param {string} glob
89
+ * @returns {boolean}
90
+ */
91
+ function isUniversalGlob(glob) {
92
+ return glob === "**/*" || glob === "**";
93
+ }
94
+
95
+ /**
96
+ * True when any rule glob matches the task file scope (via probes and raw scope entries).
97
+ * Empty fileScope never triggers glob-matched rules.
98
+ *
99
+ * @param {string[]} globs Rule frontmatter globs
100
+ * @param {string[]} fileScope PROMPT File Scope paths
101
+ * @returns {boolean}
102
+ */
103
+ export function ruleGlobsMatchFileScope(globs, fileScope) {
104
+ if (!Array.isArray(fileScope) || fileScope.length === 0) {
105
+ return false;
106
+ }
107
+ if (!Array.isArray(globs) || globs.length === 0) {
108
+ return false;
109
+ }
110
+
111
+ const probes = expandFileScopeProbes(fileScope);
112
+ const scopeEntries = fileScope.map(normalizeScopePath).filter(Boolean);
113
+ if (probes.length === 0) {
114
+ return false;
115
+ }
116
+
117
+ for (const glob of globs) {
118
+ if (isUniversalGlob(glob)) {
119
+ return true;
120
+ }
121
+
122
+ if (scopeEntries.some((entry) => micromatch.isMatch(entry, glob))) {
123
+ return true;
124
+ }
125
+
126
+ if (probes.some((probe) => micromatch.isMatch(probe, glob))) {
127
+ return true;
128
+ }
129
+ }
130
+
131
+ return false;
132
+ }