pi-spine 2.33.1 → 2.35.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.
@@ -0,0 +1,489 @@
1
+ /**
2
+ * Board selection (SP-889 / #386): map GitHub labels or a milestone to pending
3
+ * spine task IDs via Mission `Closes #N` / `Partial #N` links (SP-887 parser).
4
+ *
5
+ * Selection only — resolves and prints the comma-separated ID list for
6
+ * `spine plan` / `spine batch start`. Never starts batches, never polls, and
7
+ * never mutates issue state; re-run when the board changes.
8
+ *
9
+ * CLI surface: `node bin/spine-plan.mjs --issue-label <label>… [--milestone <m>] [--print-ids]`.
10
+ */
11
+
12
+ import { spawnSync } from "node:child_process";
13
+ import fs from "node:fs";
14
+ import path from "node:path";
15
+
16
+ import { compareTaskIds, discoverTasks } from "../tasks/packet/discover.mjs";
17
+ import { parseMissionIssueLinks } from "../integrations/issues/mission-issue-links.mjs";
18
+ import { loadSpineConfig } from "../config/spine-config-load.mjs";
19
+ import { resolveTasksRootPath } from "../config/env-overrides.mjs";
20
+ import { missingConfigHint } from "../config/missing-config-hint.mjs";
21
+
22
+ /** Wall-clock cap per `gh` call (array-args spawn, no shell). */
23
+ const GH_CALL_TIMEOUT_MS = 15_000;
24
+
25
+ /** Upper bound for the open-issue board pull (gh paginates up to the limit). */
26
+ const GH_ISSUE_LIMIT = 1000;
27
+
28
+ /**
29
+ * Mission section extraction — mirrors the `## Mission` slice rule used by
30
+ * `collectIssueLinksFromTasks` in `src/integrations/github/sync-on-land.mjs`.
31
+ */
32
+ const MISSION_SECTION_RE = /^## Mission\s*\n([\s\S]*?)(?=^## |\s*$)/m;
33
+
34
+ /**
35
+ * @typedef {object} BoardMatch
36
+ * @property {string} taskId Pending task ID (e.g. `SP-889`).
37
+ * @property {number[]} issues Board issues the task's Mission links (closes ∪ partial).
38
+ */
39
+
40
+ /**
41
+ * @typedef {object} BoardSelection
42
+ * @property {string[]} taskIds Pending task IDs on the board, sorted by `compareTaskIds`.
43
+ * @property {number} boardIssueCount Open issues matching the label/milestone filters.
44
+ * @property {BoardMatch[]} matches Per-task linked board issues.
45
+ * @property {number} excludedCount Tasks skipped because `.DONE`/`.SUPERSEDED` exists.
46
+ * @property {string[]} readErrors `PROMPT.md` read failures (warn-and-continue).
47
+ */
48
+ /**
49
+ * @typedef {object} GhRunResult
50
+ * @property {number | null} status
51
+ * @property {string} stdout
52
+ * @property {string} stderr
53
+ * @property {Error | null} error
54
+ */
55
+
56
+ /** argv flags that select a board rather than a scope. */
57
+ const BOARD_LABEL_FLAG = "--issue-label";
58
+ const BOARD_MILESTONE_FLAG = "--milestone";
59
+ const BOARD_PRINT_IDS_FLAG = "--print-ids";
60
+
61
+ /**
62
+ * Pre-SP-894 (#387) label flag spelling. Rejected fail-closed in
63
+ * `parseBoardSelectArgs` — no silent alias: scripts using the old flag
64
+ * must move to `--issue-label`.
65
+ */
66
+ const LEGACY_BOARD_LABEL_FLAG = "--github-label";
67
+
68
+ /**
69
+ * @param {string} filePath
70
+ * @returns {string}
71
+ */
72
+ function defaultReadTextFile(filePath) {
73
+ return fs.readFileSync(filePath, "utf-8");
74
+ }
75
+
76
+ /**
77
+ * Default `gh` runner — array-args spawn (no shell), piped output, hard timeout.
78
+ * Mirrors `defaultRunGh` in `src/integrations/github/sync-on-land.mjs`.
79
+ *
80
+ * @param {string} projectRoot
81
+ * @param {string[]} args
82
+ * @returns {GhRunResult}
83
+ */
84
+ export function defaultRunGh(projectRoot, args) {
85
+ const result = spawnSync("gh", args, {
86
+ cwd: projectRoot,
87
+ encoding: "utf-8",
88
+ stdio: ["ignore", "pipe", "pipe"],
89
+ timeout: GH_CALL_TIMEOUT_MS,
90
+ });
91
+ return {
92
+ status: result.status ?? null,
93
+ stdout: typeof result.stdout === "string" ? result.stdout : "",
94
+ stderr: typeof result.stderr === "string" ? result.stderr : "",
95
+ error: result.error ?? null,
96
+ };
97
+ }
98
+
99
+ /**
100
+ * Parse the board-select argv subset: repeatable `--issue-label <label>`
101
+ * (also `--issue-label=<label>`), optional `--milestone <m>` (title or
102
+ * number), and `--print-ids`. Unknown flags pass through in `rest`, except
103
+ * the retired `--github-label` spelling, which throws fail-closed (no
104
+ * silent alias; SP-894 / #387).
105
+ *
106
+ * @param {string[]} argv
107
+ * @returns {{ labels: string[], milestone: string | null, printIds: boolean, rest: string[] }}
108
+ */
109
+ export function parseBoardSelectArgs(argv) {
110
+ /** @type {string[]} */
111
+ const labels = [];
112
+ /** @type {string | null} */
113
+ let milestone = null;
114
+ let printIds = false;
115
+ /** @type {string[]} */
116
+ const rest = [];
117
+ /** @type {string | null} */
118
+ let pendingFlag = null;
119
+
120
+ for (const arg of argv) {
121
+ if (arg === LEGACY_BOARD_LABEL_FLAG || arg.startsWith(`${LEGACY_BOARD_LABEL_FLAG}=`)) {
122
+ // SP-894 (#387): fail closed — the old flag spelling is rejected,
123
+ // never aliased; scripts must move to --issue-label.
124
+ const err = new Error("Unknown option: --github-label (renamed to --issue-label; old flag not accepted)");
125
+ err.suggestedCommand = "spine plan --issue-label <label>";
126
+ throw err;
127
+ }
128
+ if (pendingFlag !== null && !arg.startsWith("--")) {
129
+ if (pendingFlag === BOARD_LABEL_FLAG) {
130
+ labels.push(arg);
131
+ } else {
132
+ milestone = arg;
133
+ }
134
+ pendingFlag = null;
135
+ continue;
136
+ }
137
+ // Flag-looking token after a valueless flag (or bare flag): drop the
138
+ // pending flag so validation reports the missing value.
139
+ pendingFlag = null;
140
+ if (arg === BOARD_LABEL_FLAG || arg === BOARD_MILESTONE_FLAG) {
141
+ pendingFlag = arg;
142
+ continue;
143
+ }
144
+ if (arg.startsWith(`${BOARD_LABEL_FLAG}=`)) {
145
+ labels.push(arg.slice(BOARD_LABEL_FLAG.length + 1));
146
+ continue;
147
+ }
148
+ if (arg.startsWith(`${BOARD_MILESTONE_FLAG}=`)) {
149
+ milestone = arg.slice(BOARD_MILESTONE_FLAG.length + 1);
150
+ continue;
151
+ }
152
+ if (arg === BOARD_PRINT_IDS_FLAG) {
153
+ printIds = true;
154
+ continue;
155
+ }
156
+ rest.push(arg);
157
+ }
158
+
159
+ return { labels, milestone, printIds, rest };
160
+ }
161
+
162
+ /**
163
+ * `gh issue list` argv for the open-issue board pull. Fields `number`,
164
+ * `labels`, `milestone` are filtered in-memory so multiple `--issue-label`
165
+ * values keep documented any-match semantics regardless of gh's own
166
+ * repeated-flag behavior.
167
+ *
168
+ * @returns {string[]}
169
+ */
170
+ export function buildGhIssueListArgs() {
171
+ return [
172
+ "issue",
173
+ "list",
174
+ "--state",
175
+ "open",
176
+ "--limit",
177
+ String(GH_ISSUE_LIMIT),
178
+ "--json",
179
+ "number,labels,milestone",
180
+ ];
181
+ }
182
+
183
+ /**
184
+ * Extract the `## Mission` section body from a PROMPT markdown string.
185
+ *
186
+ * @param {string} markdown
187
+ * @returns {string | null} Mission body text, or null when the section is absent.
188
+ */
189
+ export function extractMissionText(markdown) {
190
+ const match = MISSION_SECTION_RE.exec(String(markdown ?? ""));
191
+ return match ? match[1] : null;
192
+ }
193
+
194
+ /**
195
+ * @param {unknown} issue Parsed `gh issue list --json` entry.
196
+ * @returns {{ number: number, labelNames: string[], milestoneTitle: string | null, milestoneNumber: number | null }}
197
+ */
198
+ function normalizeGhIssue(issue) {
199
+ const number = Number(issue?.number);
200
+ const labels = Array.isArray(issue?.labels) ? issue.labels : [];
201
+ const labelNames = labels
202
+ .map((label) => String(label?.name ?? "").trim().toLowerCase())
203
+ .filter(Boolean);
204
+ const milestone = issue?.milestone ?? null;
205
+ return {
206
+ number,
207
+ labelNames,
208
+ milestoneTitle: milestone?.title != null ? String(milestone.title).trim() : null,
209
+ milestoneNumber: milestone?.number != null ? Number(milestone.number) : null,
210
+ };
211
+ }
212
+
213
+ /**
214
+ * Filter parsed `gh issue list` entries to the board: an issue is on the
215
+ * board when it carries ANY requested label (case-insensitive) or its
216
+ * milestone matches the requested title (case-insensitive) or number.
217
+ *
218
+ * @param {unknown[]} issues Parsed gh JSON entries.
219
+ * @param {{ labels: string[], milestone: string | null }} filters
220
+ * @returns {number[]} Matching open-issue numbers, ascending.
221
+ */
222
+ export function filterIssuesByBoard(issues, { labels, milestone }) {
223
+ const wantedLabels = new Set(
224
+ (Array.isArray(labels) ? labels : [])
225
+ .map((label) => String(label).trim().toLowerCase())
226
+ .filter(Boolean),
227
+ );
228
+ const milestoneRequest = milestone == null ? null : String(milestone).trim();
229
+ const milestoneAsNumber = milestoneRequest !== null && /^\d+$/.test(milestoneRequest)
230
+ ? Number(milestoneRequest)
231
+ : null;
232
+
233
+ /** @type {number[]} */
234
+ const matched = [];
235
+ for (const raw of issues) {
236
+ const issue = normalizeGhIssue(raw);
237
+ if (!Number.isInteger(issue.number) || issue.number <= 0) continue;
238
+ const labelHit = [...wantedLabels].some((label) => issue.labelNames.includes(label));
239
+ const milestoneHit =
240
+ milestoneRequest !== null &&
241
+ ((milestoneAsNumber !== null && issue.milestoneNumber === milestoneAsNumber) ||
242
+ (issue.milestoneTitle !== null &&
243
+ issue.milestoneTitle.toLowerCase() === milestoneRequest.toLowerCase()));
244
+ if (labelHit || milestoneHit) matched.push(issue.number);
245
+ }
246
+ return matched.sort((a, b) => a - b);
247
+ }
248
+
249
+ /**
250
+ * Resolve a GitHub board (label and/or milestone) to pending spine task IDs.
251
+ * Loads config to resolve `tasksRoot`, pulls open issues once via `gh`,
252
+ * discovers task folders, and matches each pending task whose PROMPT Mission
253
+ * links a board issue through the shared SP-887 parser.
254
+ *
255
+ * @param {object} params
256
+ * @param {string} [params.projectRoot]
257
+ * @param {string[]} params.labels Requested labels (any-match; may be empty).
258
+ * @param {string | null} params.milestone Requested milestone title or number.
259
+ * @param {(projectRoot: string, args: string[]) => GhRunResult} [params.runGh] Injectable gh runner.
260
+ * @param {(filePath: string) => string} [params.readTextFile] Injectable PROMPT reader.
261
+ * @param {typeof discoverTasks} [params.discover] Injectable task discovery.
262
+ * @param {string} [params.tasksRoot] Direct tasksRoot override (skips config load; tests).
263
+ * @param {(filePath: string) => boolean} [params.fileExists] Injectable marker probe (`.DONE`/`.SUPERSEDED`).
264
+ * @returns {BoardSelection & { filters: { labels: string[], milestone: string | null } }}
265
+ */
266
+ export function resolveBoardTaskIds({
267
+ projectRoot = process.cwd(),
268
+ labels,
269
+ milestone,
270
+ runGh,
271
+ readTextFile,
272
+ discover,
273
+ tasksRoot: tasksRootOverride,
274
+ fileExists,
275
+ } = {}) {
276
+ const requestedLabels = (Array.isArray(labels) ? labels : []).map((label) => String(label).trim()).filter(Boolean);
277
+ const requestedMilestone = milestone == null ? null : String(milestone).trim();
278
+ if (requestedLabels.length === 0 && (requestedMilestone === null || requestedMilestone === "")) {
279
+ const err = new Error(
280
+ "Board selection needs at least one --issue-label <label> or --milestone <title|number>",
281
+ );
282
+ err.suggestedCommand = "spine plan --issue-label <label>";
283
+ throw err;
284
+ }
285
+
286
+ const configResult = loadSpineConfig(projectRoot);
287
+ if (configResult.error) {
288
+ const err = new Error(configResult.error.message);
289
+ err.suggestedCommand = configResult.error.suggestedCommand;
290
+ throw err;
291
+ }
292
+
293
+ const tasksRoot =
294
+ tasksRootOverride ??
295
+ (() => {
296
+ const configResult = loadSpineConfig(projectRoot);
297
+ if (configResult.error) {
298
+ const err = new Error(configResult.error.message);
299
+ err.suggestedCommand = configResult.error.suggestedCommand;
300
+ throw err;
301
+ }
302
+ const resolved = resolveTasksRootPath(projectRoot, configResult.config);
303
+ if (!resolved) {
304
+ const err = new Error("Cannot resolve board: tasksRoot not configured");
305
+ err.suggestedCommand = missingConfigHint(projectRoot).suggestedCommand;
306
+ throw err;
307
+ }
308
+ return resolved;
309
+ })();
310
+
311
+ const run = runGh ?? defaultRunGh;
312
+ const read = readTextFile ?? defaultReadTextFile;
313
+ const findTasks = discover ?? discoverTasks;
314
+ const markerExists = fileExists ?? ((filePath) => fs.existsSync(filePath));
315
+
316
+ const ghResult = run(projectRoot, buildGhIssueListArgs());
317
+ if (ghResult.error) {
318
+ const err = new Error(`gh failed: ${ghResult.error.message}`);
319
+ err.suggestedCommand = "gh auth status && gh issue list --state open --limit 5";
320
+ throw err;
321
+ }
322
+ if (ghResult.status !== 0) {
323
+ const detail = (ghResult.stderr || ghResult.stdout || `exit ${ghResult.status}`).trim().slice(0, 300);
324
+ const err = new Error(`gh issue list failed: ${detail}`);
325
+ err.suggestedCommand = "gh auth login # then re-run board selection";
326
+ throw err;
327
+ }
328
+ /** @type {unknown[]} */
329
+ let issues;
330
+ try {
331
+ const parsed = /** @type {unknown} */ (JSON.parse(ghResult.stdout));
332
+ if (!Array.isArray(parsed)) throw new TypeError("expected a JSON array");
333
+ issues = parsed;
334
+ } catch (err2) {
335
+ const message = err2 instanceof Error ? err2.message : String(err2);
336
+ throw new Error(`gh issue list returned unparseable JSON (${message}); check gh version ≥ 2.x`);
337
+ }
338
+
339
+ const boardIssues = filterIssuesByBoard(issues, {
340
+ labels: requestedLabels,
341
+ milestone: requestedMilestone,
342
+ });
343
+ const boardSet = new Set(boardIssues);
344
+
345
+ const discovered = findTasks(tasksRoot);
346
+
347
+ /** @type {BoardMatch[]} */
348
+ const matches = [];
349
+ /** @type {string[]} */
350
+ const readErrors = [];
351
+ let excludedCount = 0;
352
+ for (const task of discovered) {
353
+ const isPending =
354
+ !markerExists(path.join(task.folderPath, ".DONE")) &&
355
+ !markerExists(path.join(task.folderPath, ".SUPERSEDED"));
356
+ if (!isPending) {
357
+ excludedCount += 1;
358
+ continue;
359
+ }
360
+ /** @type {string | null} */
361
+ let markdown = null;
362
+ try {
363
+ markdown = read(task.promptPath);
364
+ } catch (err3) {
365
+ readErrors.push(`${task.taskId}: ${err3 instanceof Error ? err3.message : String(err3)}`);
366
+ continue;
367
+ }
368
+ const missionText = extractMissionText(markdown);
369
+ if (missionText === null) continue;
370
+ const links = parseMissionIssueLinks(missionText);
371
+ const linked = [...new Set([...links.closes, ...links.partial])].filter((issue) => boardSet.has(issue));
372
+ if (linked.length > 0) matches.push({ taskId: task.taskId, issues: linked });
373
+ }
374
+
375
+ matches.sort((a, b) => compareTaskIds(a.taskId, b.taskId));
376
+ return {
377
+ taskIds: matches.map((match) => match.taskId),
378
+ boardIssueCount: boardIssues.length,
379
+ matches,
380
+ excludedCount,
381
+ readErrors,
382
+ filters: { labels: requestedLabels, milestone: requestedMilestone },
383
+ };
384
+ }
385
+
386
+ /**
387
+ * Comma-separated ID list for `spine batch start` / `spine plan` (both accept
388
+ * comma or whitespace separated IDs).
389
+ *
390
+ * @param {string[]} taskIds
391
+ * @returns {string}
392
+ */
393
+ export function formatBoardIdList(taskIds) {
394
+ return (Array.isArray(taskIds) ? taskIds : []).join(",");
395
+ }
396
+
397
+ /**
398
+ * Human-readable board selection output, including the explicit non-goal
399
+ * note (selection only — no auto batch start, no always-on poller).
400
+ *
401
+ * @param {object} params
402
+ * @param {{ labels: string[], milestone: string | null }} params.filters
403
+ * @param {number} params.boardIssueCount
404
+ * @param {string[]} params.taskIds
405
+ * @param {string[]} [params.readErrors]
406
+ * @returns {string}
407
+ */
408
+ export function formatBoardSelection({ filters, boardIssueCount, taskIds, readErrors = [] }) {
409
+ const filterParts = [];
410
+ if (filters.labels.length > 0) filterParts.push(`label: ${filters.labels.join(", ")}`);
411
+ if (filters.milestone !== null && filters.milestone !== "") {
412
+ filterParts.push(`milestone: ${filters.milestone}`);
413
+ }
414
+ const filterLine = filterParts.length > 0 ? filterParts.join(" · ") : "(none)";
415
+
416
+ const lines = [];
417
+ if (taskIds.length === 0) {
418
+ lines.push("Board selection — no match");
419
+ lines.push(`Filters: ${filterLine}`);
420
+ lines.push(`${boardIssueCount} open issue(s) on board → 0 pending task(s) linked.`);
421
+ lines.push("");
422
+ lines.push("No pending task PROMPT links the board's open issues (Mission Closes/Partial).");
423
+ } else {
424
+ lines.push("Board selection — GitHub → pending spine tasks");
425
+ lines.push(`Filters: ${filterLine}`);
426
+ lines.push(`${boardIssueCount} open issue(s) on board → ${taskIds.length} pending task(s) linked.`);
427
+ lines.push("");
428
+ lines.push(formatBoardIdList(taskIds));
429
+ lines.push("");
430
+ lines.push("→ spine batch start <ids>");
431
+ lines.push('→ spine plan "<ids>"');
432
+ }
433
+ for (const readError of readErrors) {
434
+ lines.push(`WARN unreadable PROMPT.md — ${readError}`);
435
+ }
436
+ lines.push("");
437
+ lines.push("Selection only — board select never starts batches and never polls GitHub; re-run to refresh.");
438
+ return lines.join("\n");
439
+ }
440
+
441
+ /**
442
+ * Full board-select CLI path: resolve + format. Used by `bin/spine-plan.mjs`
443
+ * when `--issue-label` / `--milestone` are present.
444
+ *
445
+ * @param {object} [params]
446
+ * @param {string} [params.projectRoot]
447
+ * @param {string[]} [params.labels]
448
+ * @param {string | null} [params.milestone]
449
+ * @param {boolean} [params.printIds] Print only the raw comma-separated list.
450
+ * @param {boolean} [params.json]
451
+ * @param {(projectRoot: string, args: string[]) => GhRunResult} [params.runGh]
452
+ * @param {(filePath: string) => string} [params.readTextFile]
453
+ * @param {typeof discoverTasks} [params.discover]
454
+ * @param {string} [params.tasksRoot] Direct tasksRoot override (skips config load; tests).
455
+ * @param {(filePath: string) => boolean} [params.fileExists] Injectable marker probe.
456
+ * @returns {Promise<{ output: string, selection: object }>}
457
+ */
458
+ export async function runBoardSelect({
459
+ projectRoot = process.cwd(),
460
+ labels = [],
461
+ milestone = null,
462
+ printIds = false,
463
+ json = false,
464
+ runGh,
465
+ readTextFile,
466
+ discover,
467
+ tasksRoot,
468
+ fileExists,
469
+ } = {}) {
470
+ const selection = resolveBoardTaskIds({
471
+ projectRoot,
472
+ labels,
473
+ milestone,
474
+ runGh,
475
+ readTextFile,
476
+ discover,
477
+ tasksRoot,
478
+ fileExists,
479
+ });
480
+ let output;
481
+ if (printIds) {
482
+ output = formatBoardIdList(selection.taskIds);
483
+ } else if (json) {
484
+ output = JSON.stringify(selection, null, 2);
485
+ } else {
486
+ output = formatBoardSelection(selection);
487
+ }
488
+ return { output, selection };
489
+ }
@@ -63,7 +63,20 @@ export const INTEGRATE_DEFAULTS = Object.freeze({
63
63
  allowHumanOnBaseBranch: "warn",
64
64
  });
65
65
 
66
- /** @type {Readonly<{ review: typeof REVIEW_DEFAULTS; handoff: typeof HANDOFF_DEFAULTS; metrics: typeof METRICS_DEFAULTS; contract: typeof CONTRACT_DEFAULTS; lanes: typeof LANES_DEFAULTS; integrate: typeof INTEGRATE_DEFAULTS; orchestrator: typeof ORCHESTRATOR_DEFAULTS }>} */
66
+ /**
67
+ * Third-party integrations (SP-887 / #383; forge-neutral rename SP-890 / #387).
68
+ * The section is the `issues` umbrella with a `provider` field: only the default
69
+ * provider `"github"` has a working backend today, and `syncOnLand` stays opt-in
70
+ * so the key reads as an explicit, documented default rather than an accidental
71
+ * undefined. The legacy `integrations.github` key is rejected fail-closed at
72
+ * validation time — no silent alias.
73
+ *
74
+ * @type {Readonly<{ issues: Readonly<{ provider: string; syncOnLand: boolean }> }>} */
75
+ export const INTEGRATIONS_DEFAULTS = Object.freeze({
76
+ issues: Object.freeze({ provider: "github", syncOnLand: false }),
77
+ });
78
+
79
+ /** @type {Readonly<{ review: typeof REVIEW_DEFAULTS; handoff: typeof HANDOFF_DEFAULTS; metrics: typeof METRICS_DEFAULTS; contract: typeof CONTRACT_DEFAULTS; lanes: typeof LANES_DEFAULTS; integrate: typeof INTEGRATE_DEFAULTS; integrations: typeof INTEGRATIONS_DEFAULTS; orchestrator: typeof ORCHESTRATOR_DEFAULTS }>} */
67
80
  export const CONFIG_V2_SECTION_DEFAULTS = Object.freeze({
68
81
  review: REVIEW_DEFAULTS,
69
82
  handoff: HANDOFF_DEFAULTS,
@@ -71,5 +84,6 @@ export const CONFIG_V2_SECTION_DEFAULTS = Object.freeze({
71
84
  contract: CONTRACT_DEFAULTS,
72
85
  lanes: LANES_DEFAULTS,
73
86
  integrate: INTEGRATE_DEFAULTS,
87
+ integrations: INTEGRATIONS_DEFAULTS,
74
88
  orchestrator: ORCHESTRATOR_DEFAULTS,
75
89
  });
@@ -10,7 +10,7 @@ import { validateWorkerBackendConfig } from "./worker-backend.mjs";
10
10
  import { validateWorkerContextConfig } from "./worker-context.mjs";
11
11
  import { validateWorkerLaunchScriptConfig } from "./worker-launch-script.mjs";
12
12
  import { validateWorktreeSetupHookConfig } from "./worktree-setup-hook.mjs";
13
- import { validateOrchestratorConfig, validateAgentProfilesConfig } from "./spine-config-schema.mjs";
13
+ import { validateOrchestratorConfig, validateAgentProfilesConfig, validateIntegrationsConfig } from "./spine-config-schema.mjs";
14
14
  import { missingConfigHint } from "./missing-config-hint.mjs";
15
15
 
16
16
  export { resolveGatePostureConfig } from "./gate-posture-config.mjs";
@@ -310,6 +310,11 @@ export function validateSpineConfig(config) {
310
310
  return orchestratorError;
311
311
  }
312
312
 
313
+ const integrationsError = validateIntegrationsConfig(config);
314
+ if (integrationsError) {
315
+ return integrationsError;
316
+ }
317
+
313
318
  const profilesError = validateAgentProfilesConfig(config);
314
319
  if (profilesError) {
315
320
  return profilesError;
@@ -219,6 +219,65 @@ export function resolveSequenceStallMs({ config = {} } = {}) {
219
219
  return DEFAULT_SEQUENCE_STALL_MS;
220
220
  }
221
221
 
222
+ // --- Integrations (SP-887 / #383; forge-neutral rename SP-890 / #387) ---
223
+
224
+ /**
225
+ * Validate `integrations.issues` (forge-neutral issue-tracker section, #387).
226
+ * Structural only: `provider` must be a string when set (defaults to "github"
227
+ * via INTEGRATIONS_DEFAULTS) and `syncOnLand` must be a boolean when set
228
+ * (defaults to false). Absent values are valid. The legacy `integrations.github`
229
+ * key is rejected fail-closed — no silent alias (#387).
230
+ *
231
+ * @param {Record<string, any>} config
232
+ * @returns {null | { code: string; message: string; suggestedCommand: string }}
233
+ */
234
+ export function validateIntegrationsConfig(config) {
235
+ const integrations = config?.integrations;
236
+ if (integrations == null) {
237
+ return null;
238
+ }
239
+ if (!isPlainObject(integrations)) {
240
+ return {
241
+ code: "CONFIG_INTEGRATIONS_INVALID",
242
+ message: "integrations must be an object when set",
243
+ suggestedCommand: "spine init --force",
244
+ };
245
+ }
246
+ if ("github" in integrations) {
247
+ return {
248
+ code: "CONFIG_INTEGRATIONS_INVALID",
249
+ message: 'integrations.github is no longer supported — rename it to integrations.issues (the default provider remains "github")',
250
+ suggestedCommand: 'Edit .spine/spine-config.json: rename integrations.github to integrations.issues, e.g. "issues": { "provider": "github", "syncOnLand": true }',
251
+ };
252
+ }
253
+ const issues = integrations.issues;
254
+ if (issues == null) {
255
+ return null;
256
+ }
257
+ if (!isPlainObject(issues)) {
258
+ return {
259
+ code: "CONFIG_INTEGRATIONS_INVALID",
260
+ message: "integrations.issues must be an object when set",
261
+ suggestedCommand: "Edit .spine/spine-config.json: integrations.issues must be an object",
262
+ };
263
+ }
264
+ if (issues.provider != null && typeof issues.provider !== "string") {
265
+ return {
266
+ code: "CONFIG_INTEGRATIONS_INVALID",
267
+ message: "integrations.issues.provider must be a string when set",
268
+ suggestedCommand: 'Edit .spine/spine-config.json: set integrations.issues.provider to "github"',
269
+ };
270
+ }
271
+ if (issues.syncOnLand != null && typeof issues.syncOnLand !== "boolean") {
272
+ return {
273
+ code: "CONFIG_INTEGRATIONS_INVALID",
274
+ message: "integrations.issues.syncOnLand must be a boolean when set",
275
+ suggestedCommand: "Edit .spine/spine-config.json: set integrations.issues.syncOnLand to true or false",
276
+ };
277
+ }
278
+ return null;
279
+ }
280
+
222
281
  // --- Named agent model profiles (SP-664 / GitHub #216) ---
223
282
 
224
283
  /**
@@ -0,0 +1,80 @@
1
+ /**
2
+ * Shared Mission issue-link parser (SP-887 / #383, format rules from #147).
3
+ *
4
+ * #147 standard: `Closes #N` (fully resolves) or `Partial #N` (one of several),
5
+ * with or without a trailing colon. SP-889 (board selection) reuses this module —
6
+ * keep it leaf-pure: no fs, no git, no config imports.
7
+ */
8
+
9
+ /**
10
+ * A keyword run: the link keyword plus every `#N` ref that follows it on the
11
+ * same clause (`Closes #1, #2`). Requires a word boundary so `Encloses` /
12
+ * `Partials` never match, and a following ref so prose (`Closes the gap`)
13
+ * never matches.
14
+ */
15
+ const LINK_RUN_RE = /\b(closes|partial)\s*:?\s*#(\d+)(?:[\s,;]+#\d+)*/gi;
16
+
17
+ /** Individual `#N` refs inside a matched run. */
18
+ const ISSUE_REF_RE = /#(\d+)/g;
19
+
20
+ /**
21
+ * @typedef {object} MissionIssueLinks
22
+ * @property {number[]} closes Issues the task fully resolves (closed on land).
23
+ * @property {number[]} partial Issues the task partially addresses (comment only).
24
+ */
25
+
26
+ /**
27
+ * @param {string} text Raw text to scan.
28
+ * @param {"closes"|"partial"} action Action keyword of this pass.
29
+ * @returns {number[]} Deduped issue numbers, in first-appearance order.
30
+ */
31
+ function collectIssueNumbers(text, action) {
32
+ /** @type {number[]} */
33
+ const found = [];
34
+ /** @type {Set<number>} */
35
+ const seen = new Set();
36
+ LINK_RUN_RE.lastIndex = 0;
37
+ /** @type {RegExpExecArray | null} */
38
+ let run;
39
+ while ((run = LINK_RUN_RE.exec(text)) !== null) {
40
+ if (run[1].toLowerCase() !== action) continue;
41
+ const refs = run[0].match(ISSUE_REF_RE) ?? [];
42
+ for (const ref of refs) {
43
+ const issue = Number(ref.slice(1));
44
+ if (!Number.isInteger(issue) || issue <= 0 || seen.has(issue)) continue;
45
+ seen.add(issue);
46
+ found.push(issue);
47
+ }
48
+ }
49
+ return found;
50
+ }
51
+
52
+ /**
53
+ * Parse Mission issue links (`Closes #N` / `Partial #N`, colon optional,
54
+ * case-insensitive). An issue listed under both keywords resolves to
55
+ * `closes` — the explicit full-resolution intent wins over the partial note.
56
+ *
57
+ * @param {string} missionText Mission section text (any PROMPT.md section text).
58
+ * @returns {MissionIssueLinks} `{ closes, partial }`; empty arrays when no links.
59
+ */
60
+ export function parseMissionIssueLinks(missionText) {
61
+ const text = String(missionText ?? "");
62
+ const closes = collectIssueNumbers(text, "closes");
63
+ const partial = collectIssueNumbers(text, "partial").filter((issue) => !closes.includes(issue));
64
+ return { closes, partial };
65
+ }
66
+
67
+ /**
68
+ * Flatten parsed links into per-issue action entries, closes before partial,
69
+ * stable within each action.
70
+ *
71
+ * @param {MissionIssueLinks} links Parsed links from `parseMissionIssueLinks`.
72
+ * @returns {Array<{ issue: number, action: "close"|"comment" }>}
73
+ */
74
+ export function issueLinkActions(links) {
75
+ const { closes = [], partial = [] } = links ?? {};
76
+ return [
77
+ ...closes.map((issue) => ({ issue, action: /** @type {"close"} */ ("close") })),
78
+ ...partial.map((issue) => ({ issue, action: /** @type {"comment"} */ ("comment") })),
79
+ ];
80
+ }