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,222 @@
1
+ /**
2
+ * Minimal YAML frontmatter parser for `.cursor/rules/*.{mdc,md}`.
3
+ */
4
+
5
+ const FRONTMATTER_OPEN_RE = /^---\r?\n/;
6
+ const KEY_VALUE_RE = /^([A-Za-z_][\w-]*)\s*:\s*(.*)$/;
7
+
8
+ /**
9
+ * @typedef {"ok" | "skip" | "warn"} CursorRuleParseStatus
10
+ */
11
+
12
+ /**
13
+ * @typedef {object} CursorRuleFrontmatterResult
14
+ * @property {CursorRuleParseStatus} parseStatus
15
+ * @property {string} relPath Path relative to `.cursor/rules/` (posix)
16
+ * @property {boolean} alwaysApply
17
+ * @property {string|null} description
18
+ * @property {string[]} globs Normalized glob patterns (empty when absent or `[]`)
19
+ * @property {string[]} warnings Non-fatal parse issues
20
+ */
21
+
22
+ /**
23
+ * @param {string} content Full file contents
24
+ * @param {string} relPath Path relative to `.cursor/rules/` (posix)
25
+ * @returns {CursorRuleFrontmatterResult}
26
+ */
27
+ export function parseCursorRuleFrontmatter(content, relPath) {
28
+ const normalizedRel = relPath.replace(/\\/g, "/");
29
+ if (!FRONTMATTER_OPEN_RE.test(content)) {
30
+ return emptyResult(normalizedRel, "skip");
31
+ }
32
+
33
+ const bodyStart = content.indexOf("\n---");
34
+ if (bodyStart === -1) {
35
+ return {
36
+ ...emptyResult(normalizedRel, "warn"),
37
+ warnings: ["unclosed frontmatter fence"],
38
+ };
39
+ }
40
+
41
+ const fenceEnd = bodyStart + 1;
42
+ const rawBlock = content.slice(content.match(FRONTMATTER_OPEN_RE)[0].length, fenceEnd);
43
+ const parsed = parseFrontmatterBlock(rawBlock);
44
+ const warnings = [...parsed.warnings];
45
+
46
+ if (parsed.unrecognizedKeys.length > 0) {
47
+ warnings.push(`unrecognized frontmatter keys: ${parsed.unrecognizedKeys.join(", ")}`);
48
+ }
49
+
50
+ const parseStatus = warnings.length > 0 ? "warn" : "ok";
51
+
52
+ return {
53
+ parseStatus,
54
+ relPath: normalizedRel,
55
+ alwaysApply: parsed.alwaysApply,
56
+ description: parsed.description,
57
+ globs: parsed.globs,
58
+ warnings,
59
+ };
60
+ }
61
+
62
+ /**
63
+ * @param {string} relPath
64
+ * @param {CursorRuleParseStatus} parseStatus
65
+ * @returns {CursorRuleFrontmatterResult}
66
+ */
67
+ function emptyResult(relPath, parseStatus) {
68
+ return {
69
+ parseStatus,
70
+ relPath,
71
+ alwaysApply: false,
72
+ description: null,
73
+ globs: [],
74
+ warnings: [],
75
+ };
76
+ }
77
+
78
+ /**
79
+ * @param {string} block
80
+ */
81
+ function parseFrontmatterBlock(block) {
82
+ /** @type {string[]} */
83
+ const warnings = [];
84
+ /** @type {string[]} */
85
+ const unrecognizedKeys = [];
86
+ let alwaysApply = false;
87
+ /** @type {string|null} */
88
+ let description = null;
89
+ /** @type {string[]} */
90
+ let globs = [];
91
+ let sawGlobs = false;
92
+
93
+ for (const line of block.split(/\r?\n/)) {
94
+ const trimmed = line.trim();
95
+ if (trimmed === "" || trimmed.startsWith("#")) {
96
+ continue;
97
+ }
98
+
99
+ const match = KEY_VALUE_RE.exec(trimmed);
100
+ if (!match) {
101
+ warnings.push(`ignored non key-value line: ${trimmed}`);
102
+ continue;
103
+ }
104
+
105
+ const key = match[1];
106
+ const rawValue = match[2].trim();
107
+
108
+ if (key === "alwaysApply") {
109
+ const coerced = coerceBoolean(rawValue);
110
+ if (coerced === null) {
111
+ warnings.push(`invalid alwaysApply value: ${rawValue}`);
112
+ } else {
113
+ alwaysApply = coerced;
114
+ }
115
+ continue;
116
+ }
117
+
118
+ if (key === "description") {
119
+ description = parseYamlString(rawValue);
120
+ continue;
121
+ }
122
+
123
+ if (key === "globs") {
124
+ sawGlobs = true;
125
+ const parsedGlobs = parseGlobsValue(rawValue);
126
+ globs = parsedGlobs.globs;
127
+ if (parsedGlobs.warning) {
128
+ warnings.push(parsedGlobs.warning);
129
+ }
130
+ continue;
131
+ }
132
+
133
+ unrecognizedKeys.push(key);
134
+ }
135
+
136
+ if (!sawGlobs) {
137
+ globs = [];
138
+ }
139
+
140
+ return {
141
+ alwaysApply,
142
+ description,
143
+ globs,
144
+ warnings,
145
+ unrecognizedKeys,
146
+ };
147
+ }
148
+
149
+ /**
150
+ * @param {string} raw
151
+ * @returns {boolean|null}
152
+ */
153
+ function coerceBoolean(raw) {
154
+ const normalized = raw.trim().toLowerCase();
155
+ if (normalized === "true" || normalized === "yes" || normalized === "1") {
156
+ return true;
157
+ }
158
+ if (normalized === "false" || normalized === "no" || normalized === "0" || normalized === "") {
159
+ return false;
160
+ }
161
+ return null;
162
+ }
163
+
164
+ /**
165
+ * @param {string} raw
166
+ * @returns {string|null}
167
+ */
168
+ function parseYamlString(raw) {
169
+ const trimmed = raw.trim();
170
+ if (trimmed === "" || trimmed === '""' || trimmed === "''") {
171
+ return "";
172
+ }
173
+ if (
174
+ (trimmed.startsWith('"') && trimmed.endsWith('"')) ||
175
+ (trimmed.startsWith("'") && trimmed.endsWith("'"))
176
+ ) {
177
+ return trimmed.slice(1, -1);
178
+ }
179
+ return trimmed;
180
+ }
181
+
182
+ /**
183
+ * @param {string} raw
184
+ * @returns {{ globs: string[], warning?: string }}
185
+ */
186
+ function parseGlobsValue(raw) {
187
+ const trimmed = raw.trim();
188
+ if (trimmed === "[]") {
189
+ return { globs: [] };
190
+ }
191
+
192
+ if (trimmed.startsWith("[")) {
193
+ try {
194
+ const parsed = JSON.parse(trimmed);
195
+ if (!Array.isArray(parsed)) {
196
+ return { globs: [], warning: `globs must be an array: ${trimmed}` };
197
+ }
198
+ const globs = [];
199
+ for (const entry of parsed) {
200
+ if (typeof entry !== "string" || !entry.trim()) {
201
+ return { globs: [], warning: `globs array entries must be non-empty strings` };
202
+ }
203
+ globs.push(entry.trim());
204
+ }
205
+ return { globs };
206
+ } catch {
207
+ return { globs: [], warning: `cannot parse globs array: ${trimmed}` };
208
+ }
209
+ }
210
+
211
+ const unquoted = parseYamlString(trimmed) ?? "";
212
+ if (unquoted === "") {
213
+ return { globs: [] };
214
+ }
215
+
216
+ return {
217
+ globs: unquoted
218
+ .split(",")
219
+ .map((part) => part.trim())
220
+ .filter(Boolean),
221
+ };
222
+ }
@@ -0,0 +1,26 @@
1
+ /**
2
+ * Stable ordering for worker rule selection (SP-091).
3
+ */
4
+
5
+ /** @typedef {'alwaysInclude' | 'always' | 'glob' | 'standards'} RuleSelectionSource */
6
+
7
+ /**
8
+ * Lower rank sorts earlier in the injected path list.
9
+ *
10
+ * @param {RuleSelectionSource} source
11
+ * @returns {number}
12
+ */
13
+ export function priorityRank(source) {
14
+ switch (source) {
15
+ case "alwaysInclude":
16
+ return 0;
17
+ case "always":
18
+ return 1;
19
+ case "glob":
20
+ return 2;
21
+ case "standards":
22
+ return 3;
23
+ default:
24
+ return 9;
25
+ }
26
+ }
@@ -0,0 +1,403 @@
1
+ /**
2
+ * Rules profile loader for `.spine/rules-profile.json` (cursor rules discovery).
3
+ */
4
+
5
+ import fs from "node:fs";
6
+ import path from "node:path";
7
+
8
+ /** Relative path from project root to the rules profile file. */
9
+ export const RULES_PROFILE_REL_PATH = ".spine/rules-profile.json";
10
+
11
+ /**
12
+ * @typedef {object} RulesProfileWorker
13
+ * @property {string[]} alwaysInclude Paths relative to `.cursor/rules/`
14
+ * @property {string[]} neverInclude Paths relative to `.cursor/rules/`
15
+ * @property {boolean} globMatch When true, glob-triggered rules may match PROMPT File Scope (SP-091)
16
+ */
17
+
18
+ /**
19
+ * @typedef {object} RulesProfileReviewer
20
+ * @property {boolean} enabled When false, reviewer rule selection is skipped (SP-247+)
21
+ * @property {string[]} alwaysInclude Paths relative to `.cursor/rules/`
22
+ * @property {string[]} neverInclude Paths relative to `.cursor/rules/`
23
+ * @property {boolean} globMatch When true, glob-triggered rules may match review context
24
+ * @property {number} maxRules Upper bound on rules selected for reviewer context
25
+ */
26
+
27
+ /**
28
+ * @typedef {object} RulesProfileDiscovery
29
+ * @property {string[]} excludePatterns Micromatch patterns against rule `relPath`
30
+ * @property {string[]} excludeRelPaths Paths under `.cursor/rules/` excluded from discovery
31
+ */
32
+
33
+ /**
34
+ * @typedef {object} RulesProfile
35
+ * @property {number} profileVersion
36
+ * @property {RulesProfileWorker} worker
37
+ * @property {RulesProfileReviewer} reviewer
38
+ * @property {RulesProfileDiscovery} discovery
39
+ */
40
+
41
+ /** Built-in profile when `.spine/rules-profile.json` is missing. */
42
+ export const DEFAULT_RULES_PROFILE = Object.freeze({
43
+ profileVersion: 1,
44
+ worker: Object.freeze({
45
+ alwaysInclude: Object.freeze(["taskplane-worker-cursor.mdc"]),
46
+ neverInclude: Object.freeze([]),
47
+ globMatch: true,
48
+ }),
49
+ reviewer: Object.freeze({
50
+ enabled: true,
51
+ alwaysInclude: Object.freeze([]),
52
+ neverInclude: Object.freeze([
53
+ "taskplane-worker-cursor.mdc",
54
+ "taskplane-task-authoring.mdc",
55
+ ]),
56
+ globMatch: true,
57
+ maxRules: 32,
58
+ }),
59
+ discovery: Object.freeze({
60
+ excludePatterns: Object.freeze(["*-brutal-audit"]),
61
+ excludeRelPaths: Object.freeze([
62
+ "audit-workflow.mdc",
63
+ "cursor-integration.mdc",
64
+ "taskplane/prompt-template.md",
65
+ "taskplane/status-template.md",
66
+ ]),
67
+ }),
68
+ });
69
+
70
+ /**
71
+ * @typedef {object} RulesProfileLoadSuccess
72
+ * @property {true} ok
73
+ * @property {RulesProfile} profile Merged profile (neverInclude applied to alwaysInclude)
74
+ * @property {"default" | "file"} source
75
+ * @property {string} [profilePath]
76
+ */
77
+
78
+ /**
79
+ * @typedef {object} RulesProfileLoadError
80
+ * @property {false} ok
81
+ * @property {{ code: string, message: string }} error
82
+ */
83
+
84
+ /**
85
+ * @param {string} projectRoot
86
+ * @returns {RulesProfileLoadSuccess | RulesProfileLoadError}
87
+ */
88
+ export function loadRulesProfile(projectRoot) {
89
+ const profilePath = path.join(projectRoot, RULES_PROFILE_REL_PATH);
90
+
91
+ if (!fs.existsSync(profilePath)) {
92
+ return {
93
+ ok: true,
94
+ profile: cloneProfile(DEFAULT_RULES_PROFILE),
95
+ source: "default",
96
+ };
97
+ }
98
+
99
+ let parsed;
100
+ try {
101
+ parsed = JSON.parse(fs.readFileSync(profilePath, "utf-8"));
102
+ } catch (err) {
103
+ return {
104
+ ok: false,
105
+ error: {
106
+ code: "RULES_PROFILE_INVALID",
107
+ message: `Cannot parse rules profile: ${err.message}`,
108
+ },
109
+ };
110
+ }
111
+
112
+ const validationError = validateRulesProfile(parsed);
113
+ if (validationError) {
114
+ return {
115
+ ok: false,
116
+ error: validationError,
117
+ };
118
+ }
119
+
120
+ const merged = mergeRulesProfile(DEFAULT_RULES_PROFILE, /** @type {RulesProfile} */ (parsed));
121
+ return {
122
+ ok: true,
123
+ profile: merged,
124
+ source: "file",
125
+ profilePath,
126
+ };
127
+ }
128
+
129
+ /**
130
+ * @param {unknown} profile
131
+ * @returns {{ code: string, message: string } | null}
132
+ */
133
+ export function validateRulesProfile(profile) {
134
+ if (typeof profile !== "object" || profile === null || Array.isArray(profile)) {
135
+ return {
136
+ code: "RULES_PROFILE_INVALID",
137
+ message: "rules-profile.json must be a JSON object",
138
+ };
139
+ }
140
+
141
+ if (profile.profileVersion !== 1) {
142
+ return {
143
+ code: "RULES_PROFILE_INVALID",
144
+ message: `profileVersion must be 1 (found ${profile.profileVersion ?? "missing"})`,
145
+ };
146
+ }
147
+
148
+ if (profile.worker != null) {
149
+ const workerError = validateWorkerSection(profile.worker);
150
+ if (workerError) {
151
+ return workerError;
152
+ }
153
+ }
154
+
155
+ if (profile.reviewer != null) {
156
+ const reviewerError = validateReviewerSection(profile.reviewer);
157
+ if (reviewerError) {
158
+ return reviewerError;
159
+ }
160
+ }
161
+
162
+ if (profile.discovery != null) {
163
+ const discoveryError = validateDiscoverySection(profile.discovery);
164
+ if (discoveryError) {
165
+ return discoveryError;
166
+ }
167
+ }
168
+
169
+ return null;
170
+ }
171
+
172
+ /**
173
+ * @param {unknown} worker
174
+ * @returns {{ code: string, message: string } | null}
175
+ */
176
+ function validateWorkerSection(worker) {
177
+ return validateRuleSelectionSection(worker, "worker");
178
+ }
179
+
180
+ /**
181
+ * @param {unknown} reviewer
182
+ * @returns {{ code: string, message: string } | null}
183
+ */
184
+ function validateReviewerSection(reviewer) {
185
+ const selectionError = validateRuleSelectionSection(reviewer, "reviewer");
186
+ if (selectionError) {
187
+ return selectionError;
188
+ }
189
+
190
+ if (reviewer.enabled != null && typeof reviewer.enabled !== "boolean") {
191
+ return {
192
+ code: "RULES_PROFILE_INVALID",
193
+ message: "reviewer.enabled must be a boolean",
194
+ };
195
+ }
196
+
197
+ if (reviewer.maxRules != null) {
198
+ if (
199
+ typeof reviewer.maxRules !== "number" ||
200
+ !Number.isInteger(reviewer.maxRules) ||
201
+ reviewer.maxRules < 1
202
+ ) {
203
+ return {
204
+ code: "RULES_PROFILE_INVALID",
205
+ message: "reviewer.maxRules must be a positive integer",
206
+ };
207
+ }
208
+ }
209
+
210
+ return null;
211
+ }
212
+
213
+ /**
214
+ * @param {unknown} section
215
+ * @param {string} label
216
+ * @returns {{ code: string, message: string } | null}
217
+ */
218
+ function validateRuleSelectionSection(section, label) {
219
+ if (typeof section !== "object" || section === null || Array.isArray(section)) {
220
+ return {
221
+ code: "RULES_PROFILE_INVALID",
222
+ message: `${label} must be an object`,
223
+ };
224
+ }
225
+
226
+ const alwaysError = validateStringArray(section.alwaysInclude, `${label}.alwaysInclude`, {
227
+ allowEmpty: true,
228
+ });
229
+ if (alwaysError) {
230
+ return alwaysError;
231
+ }
232
+
233
+ const neverError = validateStringArray(section.neverInclude, `${label}.neverInclude`, {
234
+ allowEmpty: true,
235
+ });
236
+ if (neverError) {
237
+ return neverError;
238
+ }
239
+
240
+ if (section.globMatch != null && typeof section.globMatch !== "boolean") {
241
+ return {
242
+ code: "RULES_PROFILE_INVALID",
243
+ message: `${label}.globMatch must be a boolean`,
244
+ };
245
+ }
246
+
247
+ return null;
248
+ }
249
+
250
+ /**
251
+ * @param {unknown} discovery
252
+ * @returns {{ code: string, message: string } | null}
253
+ */
254
+ function validateDiscoverySection(discovery) {
255
+ if (typeof discovery !== "object" || discovery === null || Array.isArray(discovery)) {
256
+ return {
257
+ code: "RULES_PROFILE_INVALID",
258
+ message: "discovery must be an object",
259
+ };
260
+ }
261
+
262
+ const patternsError = validateStringArray(
263
+ discovery.excludePatterns,
264
+ "discovery.excludePatterns",
265
+ { allowEmpty: true },
266
+ );
267
+ if (patternsError) {
268
+ return patternsError;
269
+ }
270
+
271
+ const relPathsError = validateStringArray(discovery.excludeRelPaths, "discovery.excludeRelPaths", {
272
+ allowEmpty: true,
273
+ });
274
+ if (relPathsError) {
275
+ return relPathsError;
276
+ }
277
+
278
+ return null;
279
+ }
280
+
281
+ /**
282
+ * @param {unknown} value
283
+ * @param {string} label
284
+ * @param {{ allowEmpty?: boolean }} [options]
285
+ * @returns {{ code: string, message: string } | null}
286
+ */
287
+ function validateStringArray(value, label, options = {}) {
288
+ if (value == null) {
289
+ return null;
290
+ }
291
+ if (!Array.isArray(value)) {
292
+ return {
293
+ code: "RULES_PROFILE_INVALID",
294
+ message: `${label} must be an array of strings`,
295
+ };
296
+ }
297
+ for (const entry of value) {
298
+ if (typeof entry !== "string" || (!options.allowEmpty && entry.trim() === "")) {
299
+ return {
300
+ code: "RULES_PROFILE_INVALID",
301
+ message: `${label} must contain non-empty strings`,
302
+ };
303
+ }
304
+ if (entry.includes("..")) {
305
+ return {
306
+ code: "RULES_PROFILE_INVALID",
307
+ message: `${label} must not contain path traversal`,
308
+ };
309
+ }
310
+ }
311
+ return null;
312
+ }
313
+
314
+ /**
315
+ * Deep-merge file profile onto defaults; `neverInclude` wins over `alwaysInclude`.
316
+ *
317
+ * @param {RulesProfile} defaults
318
+ * @param {RulesProfile} fileProfile
319
+ * @returns {RulesProfile}
320
+ */
321
+ export function mergeRulesProfile(defaults, fileProfile) {
322
+ const alwaysInclude = normalizeRulePaths([
323
+ ...defaults.worker.alwaysInclude,
324
+ ...(fileProfile.worker?.alwaysInclude ?? []),
325
+ ]);
326
+ const neverInclude = normalizeRulePaths([
327
+ ...defaults.worker.neverInclude,
328
+ ...(fileProfile.worker?.neverInclude ?? []),
329
+ ]);
330
+ const neverSet = new Set(neverInclude);
331
+
332
+ const reviewerAlwaysInclude = normalizeRulePaths([
333
+ ...defaults.reviewer.alwaysInclude,
334
+ ...(fileProfile.reviewer?.alwaysInclude ?? []),
335
+ ]);
336
+ const reviewerNeverInclude = normalizeRulePaths([
337
+ ...defaults.reviewer.neverInclude,
338
+ ...(fileProfile.reviewer?.neverInclude ?? []),
339
+ ]);
340
+ const reviewerNeverSet = new Set(reviewerNeverInclude);
341
+
342
+ return {
343
+ profileVersion: 1,
344
+ worker: {
345
+ alwaysInclude: alwaysInclude.filter((entry) => !neverSet.has(entry)),
346
+ neverInclude,
347
+ globMatch: fileProfile.worker?.globMatch ?? defaults.worker.globMatch,
348
+ },
349
+ reviewer: {
350
+ enabled: fileProfile.reviewer?.enabled ?? defaults.reviewer.enabled,
351
+ alwaysInclude: reviewerAlwaysInclude.filter((entry) => !reviewerNeverSet.has(entry)),
352
+ neverInclude: reviewerNeverInclude,
353
+ globMatch: fileProfile.reviewer?.globMatch ?? defaults.reviewer.globMatch,
354
+ maxRules: fileProfile.reviewer?.maxRules ?? defaults.reviewer.maxRules,
355
+ },
356
+ discovery: {
357
+ excludePatterns: normalizeRulePaths([
358
+ ...defaults.discovery.excludePatterns,
359
+ ...(fileProfile.discovery?.excludePatterns ?? []),
360
+ ]),
361
+ excludeRelPaths: normalizeRulePaths([
362
+ ...defaults.discovery.excludeRelPaths,
363
+ ...(fileProfile.discovery?.excludeRelPaths ?? []),
364
+ ]),
365
+ },
366
+ };
367
+ }
368
+
369
+ /**
370
+ * @param {string[]} paths
371
+ * @returns {string[]}
372
+ */
373
+ function normalizeRulePaths(paths) {
374
+ /** @type {string[]} */
375
+ const seen = [];
376
+ for (const entry of paths) {
377
+ const normalized = entry.trim().replace(/\\/g, "/").replace(/^\.\/+/, "");
378
+ if (!normalized || seen.includes(normalized)) {
379
+ continue;
380
+ }
381
+ seen.push(normalized);
382
+ }
383
+ return seen;
384
+ }
385
+
386
+ /**
387
+ * @param {RulesProfile} profile
388
+ * @returns {RulesProfile}
389
+ */
390
+ function cloneProfile(profile) {
391
+ return mergeRulesProfile(profile, {
392
+ profileVersion: 1,
393
+ worker: { alwaysInclude: [], neverInclude: [], globMatch: profile.worker.globMatch },
394
+ reviewer: {
395
+ alwaysInclude: [],
396
+ neverInclude: [],
397
+ globMatch: profile.reviewer.globMatch,
398
+ enabled: profile.reviewer.enabled,
399
+ maxRules: profile.reviewer.maxRules,
400
+ },
401
+ discovery: { excludePatterns: [], excludeRelPaths: [] },
402
+ });
403
+ }