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,47 @@
1
+ /**
2
+ * Default GitHub provider for opt-in issue sync on land (#387, SP-892).
3
+ *
4
+ * Holds the `gh` CLI runner extracted from
5
+ * `src/integrations/github/sync-on-land.mjs`: array-args spawn (no shell),
6
+ * piped output, hard timeout, and the `{ status, stdout, stderr, error }`
7
+ * result shape. Sync callers keep the soft-fail contract — a missing,
8
+ * hung, or failing `gh` never throws from here; the caller inspects the
9
+ * result. Future non-github providers live alongside this module.
10
+ */
11
+
12
+ import { spawnSync } from "node:child_process";
13
+
14
+ /** Hard timeout per `gh` call so a hung CLI cannot stall the integrate path. */
15
+ export const GH_CALL_TIMEOUT_MS = 30_000;
16
+
17
+ /**
18
+ * @typedef {object} GhRunResult
19
+ * @property {number | null} status
20
+ * @property {string} [stdout]
21
+ * @property {string} [stderr]
22
+ * @property {Error | null} [error]
23
+ */
24
+
25
+ /**
26
+ * Default `gh` runner: array-args spawn (no shell), piped output, hard timeout.
27
+ *
28
+ * @param {string} projectRoot
29
+ * @param {string[]} args
30
+ * @param {object} [deps]
31
+ * @param {typeof import("node:child_process").spawnSync} [deps.spawn] Injectable spawn (tests stub this).
32
+ * @returns {GhRunResult}
33
+ */
34
+ export function defaultRunGh(projectRoot, args, { spawn = spawnSync } = {}) {
35
+ const result = spawn("gh", args, {
36
+ cwd: projectRoot,
37
+ encoding: "utf-8",
38
+ stdio: ["ignore", "pipe", "pipe"],
39
+ timeout: GH_CALL_TIMEOUT_MS,
40
+ });
41
+ return {
42
+ status: result.status ?? null,
43
+ stdout: typeof result.stdout === "string" ? result.stdout : "",
44
+ stderr: typeof result.stderr === "string" ? result.stderr : "",
45
+ error: result.error ?? null,
46
+ };
47
+ }
@@ -0,0 +1,453 @@
1
+ /**
2
+ * Opt-in GitHub issue sync on land (SP-887 / #383).
3
+ *
4
+ * After a successful integrate (`.DONE` tasks on the batch base), comment on
5
+ * and close issues referenced by task Mission `Closes #N` / `Partial #N`
6
+ * links (format per #147). Strictly opt-in via `integrations.issues.syncOnLand`
7
+ * (default off); every failure path is soft — integrate results never change
8
+ * because `gh` is missing, unauthenticated, or a single issue call fails.
9
+ */
10
+
11
+ import fs from "node:fs";
12
+ import path from "node:path";
13
+
14
+ import { parseMissionIssueLinks } from "./mission-issue-links.mjs";
15
+ import { defaultRunGh } from "./providers/github.mjs";
16
+ import { commandExists } from "../../util/command-exists.mjs";
17
+ import { appendJournalEvent } from "../../batch/journal.mjs";
18
+ import { resolveTasksRootPath } from "../../config/env-overrides.mjs";
19
+
20
+ /** Terminal-success statuses whose `.DONE` landed work on the batch base. */
21
+ const DONE_ON_BASE_STATUSES = new Set(["completed", "succeeded"]);
22
+
23
+ /** Directory (relative to projectRoot) for temp comment body files. */
24
+ const BODY_DIR = path.join(".spine", "issues-sync");
25
+
26
+ /**
27
+ * @typedef {import("./mission-issue-links.mjs").MissionIssueLinks} MissionIssueLinks
28
+ */
29
+
30
+ /**
31
+ * @typedef {import("./providers/github.mjs").GhRunResult} GhRunResult
32
+ */
33
+
34
+ /**
35
+ * Resolve the opt-in flag (forge-neutral `integrations.issues` since SP-890/#387;
36
+ * legacy `integrations.github` is rejected at config validation). Missing/invalid
37
+ * config disables sync (default off).
38
+ *
39
+ * @param {Record<string, any> | null | undefined} config Effective spine config.
40
+ * @returns {boolean} True only when `integrations.issues.syncOnLand === true`.
41
+ */
42
+ export function resolveIssueSyncOnLandConfig(config) {
43
+ return config?.integrations?.issues?.syncOnLand === true;
44
+ }
45
+
46
+ /**
47
+ * Tasks whose `.DONE` is on the batch base after a successful integrate:
48
+ * terminal-success tasks only (`completed`/`succeeded`; `skipped` lands no
49
+ * work, so its Mission issues must not be closed). Returns `{taskId,
50
+ * taskFolder}` pairs for PROMPT lookup.
51
+ *
52
+ * @param {{ tasks?: Array<{ taskId?: unknown, status?: unknown, taskFolder?: unknown }> } | null | undefined} batch Parsed batch state.
53
+ * @returns {Array<{ taskId: string, taskFolder: string | null }>}
54
+ */
55
+ export function collectDoneOnBaseTasks(batch) {
56
+ const tasks = Array.isArray(batch?.tasks) ? batch.tasks : [];
57
+ /** @type {Array<{ taskId: string, taskFolder: string | null }>} */
58
+ const done = [];
59
+ for (const task of tasks) {
60
+ if (!task || typeof task !== "object") continue;
61
+ const status = String(task.status ?? "").toLowerCase();
62
+ const taskId = String(task.taskId ?? "").trim();
63
+ if (!DONE_ON_BASE_STATUSES.has(status) || taskId === "") continue;
64
+ const taskFolder = task.taskFolder ? String(task.taskFolder) : null;
65
+ done.push({ taskId, taskFolder });
66
+ }
67
+ return done;
68
+ }
69
+
70
+ /**
71
+ * @param {string} filePath
72
+ * @returns {string}
73
+ */
74
+ function defaultReadTextFile(filePath) {
75
+ return fs.readFileSync(filePath, "utf-8");
76
+ }
77
+
78
+ /**
79
+ * Parse issue links from every `.DONE`-on-base task's PROMPT Mission.
80
+ *
81
+ * @param {object} params
82
+ * @param {string} params.tasksRoot Resolved tasks root (absolute).
83
+ * @param {Array<{ taskId: string, taskFolder: string | null }>} params.tasks DONE-on-base tasks.
84
+ * @param {(filePath: string) => string} [params.readTextFile] Injectable reader.
85
+ * @returns {{ links: Array<{ taskId: string, issue: number, action: "close"|"comment" }>, readErrors: string[] }}
86
+ */
87
+ export function collectIssueLinksFromTasks({ tasksRoot, tasks, readTextFile = defaultReadTextFile }) {
88
+ const read = readTextFile ?? defaultReadTextFile;
89
+ /** @type {Array<{ taskId: string, issue: number, action: "close"|"comment" }>} */
90
+ const links = [];
91
+ /** @type {string[]} */
92
+ const readErrors = [];
93
+ for (const task of tasks) {
94
+ const folder = task.taskFolder ?? task.taskId;
95
+ const promptPath = path.join(tasksRoot, folder, "PROMPT.md");
96
+ /** @type {string | null} */
97
+ let markdown = null;
98
+ try {
99
+ markdown = read(promptPath);
100
+ } catch (err) {
101
+ readErrors.push(
102
+ `${task.taskId}: ${err instanceof Error ? err.message : String(err)}`,
103
+ );
104
+ continue;
105
+ }
106
+ const missionMatch = /^## Mission\s*\n([\s\S]*?)(?=^## |\s*$)/m.exec(markdown);
107
+ const missionText = missionMatch ? missionMatch[1] : markdown;
108
+ const parsed = /** @type {MissionIssueLinks} */ (parseMissionIssueLinks(missionText));
109
+ for (const issue of parsed.closes) {
110
+ links.push({ taskId: task.taskId, issue, action: "close" });
111
+ }
112
+ for (const issue of parsed.partial) {
113
+ links.push({ taskId: task.taskId, issue, action: "comment" });
114
+ }
115
+ }
116
+ return { links, readErrors };
117
+ }
118
+
119
+ /**
120
+ * Build the land-comment body for one issue.
121
+ *
122
+ * @param {object} params
123
+ * @param {string} params.taskId
124
+ * @param {string} params.batchId
125
+ * @param {string | null} params.mergeCommit
126
+ * @param {"close"|"comment"} params.action
127
+ * @returns {string}
128
+ */
129
+ export function buildLandCommentBody({ taskId, batchId, mergeCommit, action }) {
130
+ const commitLine = mergeCommit ? `- Merge commit: \`${mergeCommit}\`\n` : "";
131
+ if (action === "close") {
132
+ return [
133
+ `Landed on \`main\` by **${taskId}** (batch \`${batchId}\`).`,
134
+ "",
135
+ commitLine +
136
+ "- Closed automatically by spine (`integrations.issues.syncOnLand`).",
137
+ "",
138
+ ].join("\n");
139
+ }
140
+ return [
141
+ `Partially addressed on \`main\` by **${taskId}** (batch \`${batchId}\`) — issue left open.`,
142
+ "",
143
+ commitLine +
144
+ "- Commented automatically by spine (`integrations.issues.syncOnLand`).",
145
+ "",
146
+ ].join("\n");
147
+ }
148
+
149
+ /**
150
+ * @param {object} params
151
+ * @param {string} params.projectRoot
152
+ * @param {string} params.batchId
153
+ * @param {number} params.issue
154
+ * @param {string} params.body
155
+ * @returns {{ filePath: string, cleanup: () => void }}
156
+ */
157
+ function writeCommentBodyFile({ projectRoot, batchId, issue, body }) {
158
+ const dir = path.join(projectRoot, BODY_DIR);
159
+ fs.mkdirSync(dir, { recursive: true });
160
+ const filePath = path.join(dir, `${batchId}-issue-${issue}.md`);
161
+ fs.writeFileSync(filePath, body, "utf-8");
162
+ return {
163
+ filePath,
164
+ cleanup: () => {
165
+ try {
166
+ fs.unlinkSync(filePath);
167
+ } catch {
168
+ // Best-effort cleanup of the temp body file.
169
+ }
170
+ },
171
+ };
172
+ }
173
+
174
+ /** @typedef {(projectRoot: string, batchId: string, type: string, payload?: Record<string, unknown>) => void} JournalAppendFn */
175
+
176
+ /**
177
+ * Integrate entry point (#383): resolve the `.DONE`-on-base task set and
178
+ * tasksRoot from batch state + effective config, then run the sync. Best-effort
179
+ * only — never throws into the integrate success path; internal errors journal
180
+ * as `issues.sync_failed` instead of failing the integrate.
181
+ *
182
+ * @param {object} params
183
+ * @param {string} params.projectRoot
184
+ * @param {string} params.batchId
185
+ * @param {object} params.batch Parsed batch state.
186
+ * @param {Record<string, any> | null | undefined} params.config Effective spine config (null → sync disabled).
187
+ * @param {string | null} [params.mergeCommit] Integrate merge commit.
188
+ * @param {boolean} [params.noIssueSync] `--no-issue-sync` escape hatch.
189
+ * @param {(projectRoot: string, args: string[]) => GhRunResult} [params.runGh] Injectable gh runner.
190
+ * @param {(cmd: string) => boolean} [params.ghPresent] Injectable gh probe.
191
+ * @param {JournalAppendFn} [params.journalAppend] Injectable journal appender.
192
+ * @param {(filePath: string) => string} [params.readTextFile] Injectable PROMPT reader.
193
+ * @returns {object | null} Sync summary, or null when the sync crashed internally.
194
+ */
195
+ export function syncIssuesAfterIntegrate({
196
+ projectRoot,
197
+ batchId,
198
+ batch,
199
+ config,
200
+ mergeCommit = null,
201
+ noIssueSync = false,
202
+ runGh,
203
+ ghPresent,
204
+ journalAppend,
205
+ readTextFile,
206
+ }) {
207
+ try {
208
+ return syncIssuesOnLand({
209
+ projectRoot,
210
+ batchId,
211
+ doneTasks: collectDoneOnBaseTasks(batch),
212
+ tasksRoot: config ? resolveTasksRootPath(projectRoot, config) : null,
213
+ config,
214
+ mergeCommit,
215
+ noIssueSync,
216
+ runGh,
217
+ ghPresent,
218
+ journalAppend,
219
+ readTextFile,
220
+ });
221
+ } catch (err) {
222
+ const message = err instanceof Error ? err.message : String(err);
223
+ try {
224
+ const journal = journalAppend ?? appendJournalEvent;
225
+ journal(projectRoot, batchId, "issues.sync_failed", {
226
+ reason: "internal_error",
227
+ error: message.slice(0, 500),
228
+ hint: "spine status --diagnose",
229
+ });
230
+ } catch {
231
+ // Journal append must never mask the integrate success path.
232
+ }
233
+ return null;
234
+ }
235
+ }
236
+
237
+ /**
238
+ * Sync GitHub issues for tasks whose `.DONE` landed on the batch base.
239
+ * Never throws and never signals integrate failure: every problem degrades to
240
+ * a journal event plus a `hint` the CLI can surface.
241
+ *
242
+ * @param {object} params
243
+ * @param {string} params.projectRoot Project root (gh cwd, journal root).
244
+ * @param {string} params.batchId Active batch id.
245
+ * @param {Array<{ taskId: string, taskFolder?: string | null }>} params.doneTasks `.DONE`-on-base tasks.
246
+ * @param {string | null} params.tasksRoot Resolved tasks root (null → skip).
247
+ * @param {Record<string, any> | null | undefined} params.config Effective config.
248
+ * @param {string | null} [params.mergeCommit] Integrate merge commit.
249
+ * @param {boolean} [params.dryRun] Plan only — no gh calls, no journal.
250
+ * @param {boolean} [params.noIssueSync] `--no-issue-sync` escape hatch.
251
+ * @param {(projectRoot: string, args: string[]) => GhRunResult} [params.runGh] Injectable gh runner.
252
+ * @param {(cmd: string) => boolean} [params.ghPresent] Injectable gh probe.
253
+ * @param {JournalAppendFn} [params.journalAppend] Injectable journal appender.
254
+ * @param {(filePath: string) => string} [params.readTextFile] Injectable PROMPT reader.
255
+ * @returns {{
256
+ * ok: boolean,
257
+ * skipped: boolean,
258
+ * softFailed: boolean,
259
+ * dryRun?: boolean,
260
+ * reason: string | null,
261
+ * hint: string | null,
262
+ * synced: Array<{ taskId: string, issue: number, action: string, closed: boolean }>,
263
+ * failures: Array<{ taskId: string, issue: number, action: string, error: string }>,
264
+ * planned: Array<{ taskId: string, issue: number, action: string }>,
265
+ * }}
266
+ */
267
+ export function syncIssuesOnLand({
268
+ projectRoot,
269
+ batchId,
270
+ doneTasks,
271
+ tasksRoot,
272
+ config,
273
+ mergeCommit = null,
274
+ dryRun = false,
275
+ noIssueSync = false,
276
+ runGh,
277
+ ghPresent,
278
+ journalAppend,
279
+ readTextFile,
280
+ }) {
281
+ const run = runGh ?? ((/** @type {string} */ root, /** @type {string[]} */ args) => defaultRunGh(root, args));
282
+ const present = ghPresent ?? commandExists;
283
+ const journal = journalAppend ?? appendJournalEvent;
284
+ const read = readTextFile ?? defaultReadTextFile;
285
+
286
+ /** @type {Array<{ taskId: string, issue: number, action: string }>} */
287
+ const planned = [];
288
+ /** @type {Array<{ taskId: string, issue: number, action: string, closed: boolean }>} */
289
+ const synced = [];
290
+ /** @type {Array<{ taskId: string, issue: number, action: string, error: string }>} */
291
+ const failures = [];
292
+
293
+ const skip = (/** @type {string} */ reason, /** @type {string | null} */ hint = null) => ({
294
+ ok: true,
295
+ skipped: true,
296
+ softFailed: false,
297
+ reason,
298
+ hint,
299
+ synced,
300
+ failures,
301
+ planned,
302
+ });
303
+
304
+ if (noIssueSync) {
305
+ return skip("no_issue_sync_flag");
306
+ }
307
+ if (!resolveIssueSyncOnLandConfig(config)) {
308
+ return skip("sync_disabled");
309
+ }
310
+ if (!tasksRoot) {
311
+ return skip("no_tasks_root", "Set paths.tasksRoot in spine-config.json");
312
+ }
313
+
314
+ let collection;
315
+ try {
316
+ collection = collectIssueLinksFromTasks({
317
+ tasksRoot,
318
+ tasks: doneTasks.map((task) => ({
319
+ taskId: task.taskId,
320
+ taskFolder: task.taskFolder ?? null,
321
+ })),
322
+ readTextFile: read,
323
+ });
324
+ } catch (err) {
325
+ const message = err instanceof Error ? err.message : String(err);
326
+ journal(projectRoot, batchId, "issues.sync_failed", {
327
+ reason: "parse_error",
328
+ error: message.slice(0, 500),
329
+ hint: "spine status --diagnose",
330
+ });
331
+ return skip("parse_error");
332
+ }
333
+ planned.push(...collection.links);
334
+ for (const readError of collection.readErrors) {
335
+ journal(projectRoot, batchId, "issues.sync_failed", {
336
+ reason: "prompt_unreadable",
337
+ error: readError.slice(0, 500),
338
+ hint: "spine status --diagnose",
339
+ });
340
+ }
341
+ if (planned.length === 0) {
342
+ return collection.readErrors.length > 0 ? skip("prompt_unreadable") : skip("no_issue_links");
343
+ }
344
+
345
+ if (dryRun) {
346
+ return {
347
+ ok: true,
348
+ skipped: false,
349
+ softFailed: false,
350
+ dryRun: true,
351
+ reason: null,
352
+ hint: null,
353
+ synced,
354
+ failures,
355
+ planned: [...planned],
356
+ };
357
+ }
358
+
359
+ if (!present("gh")) {
360
+ journal(projectRoot, batchId, "issues.sync_failed", {
361
+ reason: "gh_missing",
362
+ hint: "Install GitHub CLI (https://cli.github.com/) or disable integrations.issues.syncOnLand",
363
+ });
364
+ return skip("gh_missing", "Install GitHub CLI (https://cli.github.com/) or disable integrations.issues.syncOnLand");
365
+ }
366
+
367
+ const auth = run(projectRoot, ["auth", "status"]);
368
+ if ((auth.status ?? 1) !== 0) {
369
+ const stderr = (auth.stderr ?? "").trim().slice(0, 500);
370
+ journal(projectRoot, batchId, "issues.sync_failed", {
371
+ reason: "gh_auth",
372
+ error: stderr,
373
+ hint: "Run `gh auth login`, then re-run `spine integrate` (or close manually per the release-operator runbook §4.3c)",
374
+ });
375
+ return skip("gh_auth", "Run `gh auth login`, then re-run `spine integrate` (or close manually per the release-operator runbook §4.3c)");
376
+ }
377
+
378
+ for (const link of planned) {
379
+ const { taskId, issue, action } = link;
380
+ const body = buildLandCommentBody({ taskId, batchId, mergeCommit, action: /** @type {"close"|"comment"} */ (action) });
381
+ let bodyFile = null;
382
+ try {
383
+ bodyFile = writeCommentBodyFile({ projectRoot, batchId, issue, body });
384
+ } catch (err) {
385
+ const message = err instanceof Error ? err.message : String(err);
386
+ failures.push({ taskId, issue, action, error: message });
387
+ journal(projectRoot, batchId, "issues.sync_failed", {
388
+ issue,
389
+ action,
390
+ taskId,
391
+ reason: "body_write_failed",
392
+ error: message.slice(0, 500),
393
+ });
394
+ continue;
395
+ }
396
+
397
+ const comment = run(projectRoot, ["issue", "comment", String(issue), "--body-file", bodyFile.filePath]);
398
+ if ((comment.status ?? 1) !== 0) {
399
+ const stderr = (comment.stderr ?? comment.stdout ?? "").trim().slice(0, 500) || "gh issue comment failed";
400
+ failures.push({ taskId, issue, action, error: stderr });
401
+ journal(projectRoot, batchId, "issues.sync_failed", {
402
+ issue,
403
+ action,
404
+ taskId,
405
+ reason: "comment_failed",
406
+ error: stderr,
407
+ hint: "spine status --diagnose",
408
+ });
409
+ bodyFile.cleanup();
410
+ continue;
411
+ }
412
+
413
+ let closed = false;
414
+ if (action === "close") {
415
+ const close = run(projectRoot, ["issue", "close", String(issue), "--reason", "completed"]);
416
+ if ((close.status ?? 1) !== 0) {
417
+ const stderr = (close.stderr ?? close.stdout ?? "").trim().slice(0, 500) || "gh issue close failed";
418
+ failures.push({ taskId, issue, action, error: stderr });
419
+ journal(projectRoot, batchId, "issues.sync_failed", {
420
+ issue,
421
+ action,
422
+ taskId,
423
+ reason: "close_failed",
424
+ error: stderr,
425
+ hint: `gh issue close ${issue} --reason completed`,
426
+ });
427
+ bodyFile.cleanup();
428
+ continue;
429
+ }
430
+ closed = true;
431
+ }
432
+ bodyFile.cleanup();
433
+ synced.push({ taskId, issue, action, closed });
434
+ journal(projectRoot, batchId, "issues.synced", {
435
+ issue,
436
+ action,
437
+ taskId,
438
+ closed,
439
+ mergeCommit,
440
+ });
441
+ }
442
+
443
+ return {
444
+ ok: true,
445
+ skipped: false,
446
+ softFailed: failures.length > 0 && synced.length === 0,
447
+ reason: null,
448
+ hint: null,
449
+ synced,
450
+ failures,
451
+ planned: [...planned],
452
+ };
453
+ }