pi-spine 2.33.0 → 2.34.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,473 @@
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 --github-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/github/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 = "--github-label";
58
+ const BOARD_MILESTONE_FLAG = "--milestone";
59
+ const BOARD_PRINT_IDS_FLAG = "--print-ids";
60
+
61
+ /**
62
+ * @param {string} filePath
63
+ * @returns {string}
64
+ */
65
+ function defaultReadTextFile(filePath) {
66
+ return fs.readFileSync(filePath, "utf-8");
67
+ }
68
+
69
+ /**
70
+ * Default `gh` runner — array-args spawn (no shell), piped output, hard timeout.
71
+ * Mirrors `defaultRunGh` in `src/integrations/github/sync-on-land.mjs`.
72
+ *
73
+ * @param {string} projectRoot
74
+ * @param {string[]} args
75
+ * @returns {GhRunResult}
76
+ */
77
+ export function defaultRunGh(projectRoot, args) {
78
+ const result = spawnSync("gh", args, {
79
+ cwd: projectRoot,
80
+ encoding: "utf-8",
81
+ stdio: ["ignore", "pipe", "pipe"],
82
+ timeout: GH_CALL_TIMEOUT_MS,
83
+ });
84
+ return {
85
+ status: result.status ?? null,
86
+ stdout: typeof result.stdout === "string" ? result.stdout : "",
87
+ stderr: typeof result.stderr === "string" ? result.stderr : "",
88
+ error: result.error ?? null,
89
+ };
90
+ }
91
+
92
+ /**
93
+ * Parse the board-select argv subset: repeatable `--github-label <label>`
94
+ * (also `--github-label=<label>`), optional `--milestone <m>` (title or
95
+ * number), and `--print-ids`. Unknown flags pass through in `rest`.
96
+ *
97
+ * @param {string[]} argv
98
+ * @returns {{ labels: string[], milestone: string | null, printIds: boolean, rest: string[] }}
99
+ */
100
+ export function parseBoardSelectArgs(argv) {
101
+ /** @type {string[]} */
102
+ const labels = [];
103
+ /** @type {string | null} */
104
+ let milestone = null;
105
+ let printIds = false;
106
+ /** @type {string[]} */
107
+ const rest = [];
108
+ /** @type {string | null} */
109
+ let pendingFlag = null;
110
+
111
+ for (const arg of argv) {
112
+ if (pendingFlag !== null && !arg.startsWith("--")) {
113
+ if (pendingFlag === BOARD_LABEL_FLAG) {
114
+ labels.push(arg);
115
+ } else {
116
+ milestone = arg;
117
+ }
118
+ pendingFlag = null;
119
+ continue;
120
+ }
121
+ // Flag-looking token after a valueless flag (or bare flag): drop the
122
+ // pending flag so validation reports the missing value.
123
+ pendingFlag = null;
124
+ if (arg === BOARD_LABEL_FLAG || arg === BOARD_MILESTONE_FLAG) {
125
+ pendingFlag = arg;
126
+ continue;
127
+ }
128
+ if (arg.startsWith(`${BOARD_LABEL_FLAG}=`)) {
129
+ labels.push(arg.slice(BOARD_LABEL_FLAG.length + 1));
130
+ continue;
131
+ }
132
+ if (arg.startsWith(`${BOARD_MILESTONE_FLAG}=`)) {
133
+ milestone = arg.slice(BOARD_MILESTONE_FLAG.length + 1);
134
+ continue;
135
+ }
136
+ if (arg === BOARD_PRINT_IDS_FLAG) {
137
+ printIds = true;
138
+ continue;
139
+ }
140
+ rest.push(arg);
141
+ }
142
+
143
+ return { labels, milestone, printIds, rest };
144
+ }
145
+
146
+ /**
147
+ * `gh issue list` argv for the open-issue board pull. Fields `number`,
148
+ * `labels`, `milestone` are filtered in-memory so multiple `--github-label`
149
+ * values keep documented any-match semantics regardless of gh's own
150
+ * repeated-flag behavior.
151
+ *
152
+ * @returns {string[]}
153
+ */
154
+ export function buildGhIssueListArgs() {
155
+ return [
156
+ "issue",
157
+ "list",
158
+ "--state",
159
+ "open",
160
+ "--limit",
161
+ String(GH_ISSUE_LIMIT),
162
+ "--json",
163
+ "number,labels,milestone",
164
+ ];
165
+ }
166
+
167
+ /**
168
+ * Extract the `## Mission` section body from a PROMPT markdown string.
169
+ *
170
+ * @param {string} markdown
171
+ * @returns {string | null} Mission body text, or null when the section is absent.
172
+ */
173
+ export function extractMissionText(markdown) {
174
+ const match = MISSION_SECTION_RE.exec(String(markdown ?? ""));
175
+ return match ? match[1] : null;
176
+ }
177
+
178
+ /**
179
+ * @param {unknown} issue Parsed `gh issue list --json` entry.
180
+ * @returns {{ number: number, labelNames: string[], milestoneTitle: string | null, milestoneNumber: number | null }}
181
+ */
182
+ function normalizeGhIssue(issue) {
183
+ const number = Number(issue?.number);
184
+ const labels = Array.isArray(issue?.labels) ? issue.labels : [];
185
+ const labelNames = labels
186
+ .map((label) => String(label?.name ?? "").trim().toLowerCase())
187
+ .filter(Boolean);
188
+ const milestone = issue?.milestone ?? null;
189
+ return {
190
+ number,
191
+ labelNames,
192
+ milestoneTitle: milestone?.title != null ? String(milestone.title).trim() : null,
193
+ milestoneNumber: milestone?.number != null ? Number(milestone.number) : null,
194
+ };
195
+ }
196
+
197
+ /**
198
+ * Filter parsed `gh issue list` entries to the board: an issue is on the
199
+ * board when it carries ANY requested label (case-insensitive) or its
200
+ * milestone matches the requested title (case-insensitive) or number.
201
+ *
202
+ * @param {unknown[]} issues Parsed gh JSON entries.
203
+ * @param {{ labels: string[], milestone: string | null }} filters
204
+ * @returns {number[]} Matching open-issue numbers, ascending.
205
+ */
206
+ export function filterIssuesByBoard(issues, { labels, milestone }) {
207
+ const wantedLabels = new Set(
208
+ (Array.isArray(labels) ? labels : [])
209
+ .map((label) => String(label).trim().toLowerCase())
210
+ .filter(Boolean),
211
+ );
212
+ const milestoneRequest = milestone == null ? null : String(milestone).trim();
213
+ const milestoneAsNumber = milestoneRequest !== null && /^\d+$/.test(milestoneRequest)
214
+ ? Number(milestoneRequest)
215
+ : null;
216
+
217
+ /** @type {number[]} */
218
+ const matched = [];
219
+ for (const raw of issues) {
220
+ const issue = normalizeGhIssue(raw);
221
+ if (!Number.isInteger(issue.number) || issue.number <= 0) continue;
222
+ const labelHit = [...wantedLabels].some((label) => issue.labelNames.includes(label));
223
+ const milestoneHit =
224
+ milestoneRequest !== null &&
225
+ ((milestoneAsNumber !== null && issue.milestoneNumber === milestoneAsNumber) ||
226
+ (issue.milestoneTitle !== null &&
227
+ issue.milestoneTitle.toLowerCase() === milestoneRequest.toLowerCase()));
228
+ if (labelHit || milestoneHit) matched.push(issue.number);
229
+ }
230
+ return matched.sort((a, b) => a - b);
231
+ }
232
+
233
+ /**
234
+ * Resolve a GitHub board (label and/or milestone) to pending spine task IDs.
235
+ * Loads config to resolve `tasksRoot`, pulls open issues once via `gh`,
236
+ * discovers task folders, and matches each pending task whose PROMPT Mission
237
+ * links a board issue through the shared SP-887 parser.
238
+ *
239
+ * @param {object} params
240
+ * @param {string} [params.projectRoot]
241
+ * @param {string[]} params.labels Requested labels (any-match; may be empty).
242
+ * @param {string | null} params.milestone Requested milestone title or number.
243
+ * @param {(projectRoot: string, args: string[]) => GhRunResult} [params.runGh] Injectable gh runner.
244
+ * @param {(filePath: string) => string} [params.readTextFile] Injectable PROMPT reader.
245
+ * @param {typeof discoverTasks} [params.discover] Injectable task discovery.
246
+ * @param {string} [params.tasksRoot] Direct tasksRoot override (skips config load; tests).
247
+ * @param {(filePath: string) => boolean} [params.fileExists] Injectable marker probe (`.DONE`/`.SUPERSEDED`).
248
+ * @returns {BoardSelection & { filters: { labels: string[], milestone: string | null } }}
249
+ */
250
+ export function resolveBoardTaskIds({
251
+ projectRoot = process.cwd(),
252
+ labels,
253
+ milestone,
254
+ runGh,
255
+ readTextFile,
256
+ discover,
257
+ tasksRoot: tasksRootOverride,
258
+ fileExists,
259
+ } = {}) {
260
+ const requestedLabels = (Array.isArray(labels) ? labels : []).map((label) => String(label).trim()).filter(Boolean);
261
+ const requestedMilestone = milestone == null ? null : String(milestone).trim();
262
+ if (requestedLabels.length === 0 && (requestedMilestone === null || requestedMilestone === "")) {
263
+ const err = new Error(
264
+ "Board selection needs at least one --github-label <label> or --milestone <title|number>",
265
+ );
266
+ err.suggestedCommand = "spine plan --github-label <label>";
267
+ throw err;
268
+ }
269
+
270
+ const configResult = loadSpineConfig(projectRoot);
271
+ if (configResult.error) {
272
+ const err = new Error(configResult.error.message);
273
+ err.suggestedCommand = configResult.error.suggestedCommand;
274
+ throw err;
275
+ }
276
+
277
+ const tasksRoot =
278
+ tasksRootOverride ??
279
+ (() => {
280
+ const configResult = loadSpineConfig(projectRoot);
281
+ if (configResult.error) {
282
+ const err = new Error(configResult.error.message);
283
+ err.suggestedCommand = configResult.error.suggestedCommand;
284
+ throw err;
285
+ }
286
+ const resolved = resolveTasksRootPath(projectRoot, configResult.config);
287
+ if (!resolved) {
288
+ const err = new Error("Cannot resolve board: tasksRoot not configured");
289
+ err.suggestedCommand = missingConfigHint(projectRoot).suggestedCommand;
290
+ throw err;
291
+ }
292
+ return resolved;
293
+ })();
294
+
295
+ const run = runGh ?? defaultRunGh;
296
+ const read = readTextFile ?? defaultReadTextFile;
297
+ const findTasks = discover ?? discoverTasks;
298
+ const markerExists = fileExists ?? ((filePath) => fs.existsSync(filePath));
299
+
300
+ const ghResult = run(projectRoot, buildGhIssueListArgs());
301
+ if (ghResult.error) {
302
+ const err = new Error(`gh failed: ${ghResult.error.message}`);
303
+ err.suggestedCommand = "gh auth status && gh issue list --state open --limit 5";
304
+ throw err;
305
+ }
306
+ if (ghResult.status !== 0) {
307
+ const detail = (ghResult.stderr || ghResult.stdout || `exit ${ghResult.status}`).trim().slice(0, 300);
308
+ const err = new Error(`gh issue list failed: ${detail}`);
309
+ err.suggestedCommand = "gh auth login # then re-run board selection";
310
+ throw err;
311
+ }
312
+ /** @type {unknown[]} */
313
+ let issues;
314
+ try {
315
+ const parsed = /** @type {unknown} */ (JSON.parse(ghResult.stdout));
316
+ if (!Array.isArray(parsed)) throw new TypeError("expected a JSON array");
317
+ issues = parsed;
318
+ } catch (err2) {
319
+ const message = err2 instanceof Error ? err2.message : String(err2);
320
+ throw new Error(`gh issue list returned unparseable JSON (${message}); check gh version ≥ 2.x`);
321
+ }
322
+
323
+ const boardIssues = filterIssuesByBoard(issues, {
324
+ labels: requestedLabels,
325
+ milestone: requestedMilestone,
326
+ });
327
+ const boardSet = new Set(boardIssues);
328
+
329
+ const discovered = findTasks(tasksRoot);
330
+
331
+ /** @type {BoardMatch[]} */
332
+ const matches = [];
333
+ /** @type {string[]} */
334
+ const readErrors = [];
335
+ let excludedCount = 0;
336
+ for (const task of discovered) {
337
+ const isPending =
338
+ !markerExists(path.join(task.folderPath, ".DONE")) &&
339
+ !markerExists(path.join(task.folderPath, ".SUPERSEDED"));
340
+ if (!isPending) {
341
+ excludedCount += 1;
342
+ continue;
343
+ }
344
+ /** @type {string | null} */
345
+ let markdown = null;
346
+ try {
347
+ markdown = read(task.promptPath);
348
+ } catch (err3) {
349
+ readErrors.push(`${task.taskId}: ${err3 instanceof Error ? err3.message : String(err3)}`);
350
+ continue;
351
+ }
352
+ const missionText = extractMissionText(markdown);
353
+ if (missionText === null) continue;
354
+ const links = parseMissionIssueLinks(missionText);
355
+ const linked = [...new Set([...links.closes, ...links.partial])].filter((issue) => boardSet.has(issue));
356
+ if (linked.length > 0) matches.push({ taskId: task.taskId, issues: linked });
357
+ }
358
+
359
+ matches.sort((a, b) => compareTaskIds(a.taskId, b.taskId));
360
+ return {
361
+ taskIds: matches.map((match) => match.taskId),
362
+ boardIssueCount: boardIssues.length,
363
+ matches,
364
+ excludedCount,
365
+ readErrors,
366
+ filters: { labels: requestedLabels, milestone: requestedMilestone },
367
+ };
368
+ }
369
+
370
+ /**
371
+ * Comma-separated ID list for `spine batch start` / `spine plan` (both accept
372
+ * comma or whitespace separated IDs).
373
+ *
374
+ * @param {string[]} taskIds
375
+ * @returns {string}
376
+ */
377
+ export function formatBoardIdList(taskIds) {
378
+ return (Array.isArray(taskIds) ? taskIds : []).join(",");
379
+ }
380
+
381
+ /**
382
+ * Human-readable board selection output, including the explicit non-goal
383
+ * note (selection only — no auto batch start, no always-on poller).
384
+ *
385
+ * @param {object} params
386
+ * @param {{ labels: string[], milestone: string | null }} params.filters
387
+ * @param {number} params.boardIssueCount
388
+ * @param {string[]} params.taskIds
389
+ * @param {string[]} [params.readErrors]
390
+ * @returns {string}
391
+ */
392
+ export function formatBoardSelection({ filters, boardIssueCount, taskIds, readErrors = [] }) {
393
+ const filterParts = [];
394
+ if (filters.labels.length > 0) filterParts.push(`label: ${filters.labels.join(", ")}`);
395
+ if (filters.milestone !== null && filters.milestone !== "") {
396
+ filterParts.push(`milestone: ${filters.milestone}`);
397
+ }
398
+ const filterLine = filterParts.length > 0 ? filterParts.join(" · ") : "(none)";
399
+
400
+ const lines = [];
401
+ if (taskIds.length === 0) {
402
+ lines.push("Board selection — no match");
403
+ lines.push(`Filters: ${filterLine}`);
404
+ lines.push(`${boardIssueCount} open issue(s) on board → 0 pending task(s) linked.`);
405
+ lines.push("");
406
+ lines.push("No pending task PROMPT links the board's open issues (Mission Closes/Partial).");
407
+ } else {
408
+ lines.push("Board selection — GitHub → pending spine tasks");
409
+ lines.push(`Filters: ${filterLine}`);
410
+ lines.push(`${boardIssueCount} open issue(s) on board → ${taskIds.length} pending task(s) linked.`);
411
+ lines.push("");
412
+ lines.push(formatBoardIdList(taskIds));
413
+ lines.push("");
414
+ lines.push("→ spine batch start <ids>");
415
+ lines.push('→ spine plan "<ids>"');
416
+ }
417
+ for (const readError of readErrors) {
418
+ lines.push(`WARN unreadable PROMPT.md — ${readError}`);
419
+ }
420
+ lines.push("");
421
+ lines.push("Selection only — board select never starts batches and never polls GitHub; re-run to refresh.");
422
+ return lines.join("\n");
423
+ }
424
+
425
+ /**
426
+ * Full board-select CLI path: resolve + format. Used by `bin/spine-plan.mjs`
427
+ * when `--github-label` / `--milestone` are present.
428
+ *
429
+ * @param {object} [params]
430
+ * @param {string} [params.projectRoot]
431
+ * @param {string[]} [params.labels]
432
+ * @param {string | null} [params.milestone]
433
+ * @param {boolean} [params.printIds] Print only the raw comma-separated list.
434
+ * @param {boolean} [params.json]
435
+ * @param {(projectRoot: string, args: string[]) => GhRunResult} [params.runGh]
436
+ * @param {(filePath: string) => string} [params.readTextFile]
437
+ * @param {typeof discoverTasks} [params.discover]
438
+ * @param {string} [params.tasksRoot] Direct tasksRoot override (skips config load; tests).
439
+ * @param {(filePath: string) => boolean} [params.fileExists] Injectable marker probe.
440
+ * @returns {Promise<{ output: string, selection: object }>}
441
+ */
442
+ export async function runBoardSelect({
443
+ projectRoot = process.cwd(),
444
+ labels = [],
445
+ milestone = null,
446
+ printIds = false,
447
+ json = false,
448
+ runGh,
449
+ readTextFile,
450
+ discover,
451
+ tasksRoot,
452
+ fileExists,
453
+ } = {}) {
454
+ const selection = resolveBoardTaskIds({
455
+ projectRoot,
456
+ labels,
457
+ milestone,
458
+ runGh,
459
+ readTextFile,
460
+ discover,
461
+ tasksRoot,
462
+ fileExists,
463
+ });
464
+ let output;
465
+ if (printIds) {
466
+ output = formatBoardIdList(selection.taskIds);
467
+ } else if (json) {
468
+ output = JSON.stringify(selection, null, 2);
469
+ } else {
470
+ output = formatBoardSelection(selection);
471
+ }
472
+ return { output, selection };
473
+ }
@@ -63,7 +63,17 @@ 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). Everything is opt-in: the section
68
+ * only exists so `syncOnLand` reads as an explicit, documented default rather
69
+ * than an accidental undefined.
70
+ *
71
+ * @type {Readonly<{ github: Readonly<{ syncOnLand: boolean }> }>} */
72
+ export const INTEGRATIONS_DEFAULTS = Object.freeze({
73
+ github: Object.freeze({ syncOnLand: false }),
74
+ });
75
+
76
+ /** @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
77
  export const CONFIG_V2_SECTION_DEFAULTS = Object.freeze({
68
78
  review: REVIEW_DEFAULTS,
69
79
  handoff: HANDOFF_DEFAULTS,
@@ -71,5 +81,6 @@ export const CONFIG_V2_SECTION_DEFAULTS = Object.freeze({
71
81
  contract: CONTRACT_DEFAULTS,
72
82
  lanes: LANES_DEFAULTS,
73
83
  integrate: INTEGRATE_DEFAULTS,
84
+ integrations: INTEGRATIONS_DEFAULTS,
74
85
  orchestrator: ORCHESTRATOR_DEFAULTS,
75
86
  });
@@ -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,49 @@ export function resolveSequenceStallMs({ config = {} } = {}) {
219
219
  return DEFAULT_SEQUENCE_STALL_MS;
220
220
  }
221
221
 
222
+ // --- Integrations (SP-887 / #383) ---
223
+
224
+ /**
225
+ * Validate `integrations.github.syncOnLand` (opt-in GitHub issue sync on land).
226
+ * Structural only: the boolean flag must be a boolean when set. Absent values
227
+ * are valid (defaults to false via INTEGRATIONS_DEFAULTS).
228
+ *
229
+ * @param {Record<string, any>} config
230
+ * @returns {null | { code: string; message: string; suggestedCommand: string }}
231
+ */
232
+ export function validateIntegrationsConfig(config) {
233
+ const integrations = config?.integrations;
234
+ if (integrations == null) {
235
+ return null;
236
+ }
237
+ if (!isPlainObject(integrations)) {
238
+ return {
239
+ code: "CONFIG_INTEGRATIONS_INVALID",
240
+ message: "integrations must be an object when set",
241
+ suggestedCommand: "spine init --force",
242
+ };
243
+ }
244
+ const github = integrations.github;
245
+ if (github == null) {
246
+ return null;
247
+ }
248
+ if (!isPlainObject(github)) {
249
+ return {
250
+ code: "CONFIG_INTEGRATIONS_INVALID",
251
+ message: "integrations.github must be an object when set",
252
+ suggestedCommand: "Edit .spine/spine-config.json: integrations.github must be an object",
253
+ };
254
+ }
255
+ if (github.syncOnLand != null && typeof github.syncOnLand !== "boolean") {
256
+ return {
257
+ code: "CONFIG_INTEGRATIONS_INVALID",
258
+ message: "integrations.github.syncOnLand must be a boolean when set",
259
+ suggestedCommand: "Edit .spine/spine-config.json: set integrations.github.syncOnLand to true or false",
260
+ };
261
+ }
262
+ return null;
263
+ }
264
+
222
265
  // --- Named agent model profiles (SP-664 / GitHub #216) ---
223
266
 
224
267
  /**
@@ -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
+ }