pi-spine 2.33.1 → 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,393 @@
1
+ /**
2
+ * `spine tasks from-issue` — scaffold SP-* packet from a GitHub issue (#384).
3
+ *
4
+ * Fetches issue title/body via `gh issue view <n> --json` and scaffolds
5
+ * `{tasksRoot}/SP-###-<slug>/` with PROMPT.md + STATUS.md stubs:
6
+ *
7
+ * - Mission first line uses `Closes #N` or `Partial #N` (#147 link format).
8
+ * - Mission stays thin (title + pointer to the issue; #385 thin packets).
9
+ * - Contract / File Scope / Steps are required stubs. The scaffold never
10
+ * claims Contract completeness: the Contract table ships with empty rows
11
+ * so `spine tasks validate <id>` fails until the operator fills it.
12
+ * - `dependencies.json` is never written (no silent DAG edges).
13
+ * - CONTEXT.md `Next Task ID` is read-only by default; it is only updated
14
+ * when the caller explicitly passes `nextId` (CLI `--next-id`).
15
+ *
16
+ * Independence: spine + `gh` only. No batch start, no File Scope invention.
17
+ */
18
+
19
+ import fs from "node:fs";
20
+ import path from "node:path";
21
+ import { spawnSync } from "node:child_process";
22
+
23
+ const TASK_ID_RE = /^[A-Z][A-Z0-9]*-\d+$/;
24
+ const NEXT_TASK_ID_LINE_RE = /^\*\*Next Task ID:\*\* ([A-Z][A-Z0-9]*-\d+)\s*$/m;
25
+ const GH_ISSUE_JSON_FIELDS = "number,title,body";
26
+ const GH_TIMEOUT_MS = 30_000;
27
+ const SLUG_MAX_LENGTH = 48;
28
+ // Safe folder slug: lowercase alphanumerics with single interior hyphens.
29
+ // Excludes dots, slashes, whitespace, and uppercase — blocks path traversal
30
+ // (`../`) and sibling-folder escapes from the `--slug` CLI override.
31
+ const SLUG_RE = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
32
+
33
+ /**
34
+ * Fail-loud error for from-issue scaffolding. `exitCode` is surfaced by the
35
+ * CLI handler (1 = fetch/validation, 2 = config/tasksRoot resolution).
36
+ */
37
+ export class FromIssueError extends Error {
38
+ /**
39
+ * @param {string} message
40
+ * @param {{ exitCode?: number }} [options]
41
+ */
42
+ constructor(message, { exitCode = 1 } = {}) {
43
+ super(message);
44
+ this.name = "FromIssueError";
45
+ this.exitCode = exitCode;
46
+ }
47
+ }
48
+
49
+ /**
50
+ * Parse and shape-check `gh issue view --json number,title,body` stdout.
51
+ * Input validation at the gh boundary (fail loud on malformed payloads).
52
+ *
53
+ * @param {string} stdout Raw gh stdout
54
+ * @param {number} expectedNumber Issue number that was requested
55
+ * @returns {{ number: number, title: string, body: string }}
56
+ */
57
+ export function parseIssueJson(stdout, expectedNumber) {
58
+ let payload;
59
+ try {
60
+ payload = JSON.parse(stdout);
61
+ } catch (err) {
62
+ throw new FromIssueError(
63
+ `gh issue view ${expectedNumber} returned malformed JSON: ${err instanceof Error ? err.message : String(err)}`,
64
+ );
65
+ }
66
+ if (payload === null || typeof payload !== "object" || Array.isArray(payload)) {
67
+ throw new FromIssueError(`gh issue view ${expectedNumber} returned a non-object JSON payload`);
68
+ }
69
+ if (payload.number !== expectedNumber) {
70
+ throw new FromIssueError(
71
+ `gh issue view returned issue #${payload.number} but #${expectedNumber} was requested`,
72
+ );
73
+ }
74
+ if (typeof payload.title !== "string" || payload.title.trim() === "") {
75
+ throw new FromIssueError(`gh issue view ${expectedNumber} returned no title`);
76
+ }
77
+ return {
78
+ number: payload.number,
79
+ title: payload.title.trim(),
80
+ body: typeof payload.body === "string" ? payload.body : "",
81
+ };
82
+ }
83
+
84
+ /**
85
+ * Fetch a GitHub issue via the `gh` CLI.
86
+ *
87
+ * @param {{ issueNumber: number, projectRoot?: string, ghCommand?: string }} options
88
+ * @returns {{ number: number, title: string, body: string }}
89
+ */
90
+ export function fetchIssueViaGh({ issueNumber, projectRoot = process.cwd(), ghCommand = "gh" }) {
91
+ if (!Number.isInteger(issueNumber) || issueNumber <= 0) {
92
+ throw new FromIssueError(`Invalid issue number: ${issueNumber}. Expected a positive integer.`);
93
+ }
94
+
95
+ const result = spawnSync(
96
+ ghCommand,
97
+ ["issue", "view", String(issueNumber), "--json", GH_ISSUE_JSON_FIELDS],
98
+ {
99
+ cwd: projectRoot,
100
+ encoding: "utf-8",
101
+ stdio: ["ignore", "pipe", "pipe"],
102
+ timeout: GH_TIMEOUT_MS,
103
+ },
104
+ );
105
+
106
+ if (result.error) {
107
+ const code = /** @type {NodeJS.ErrnoException} */ (result.error).code;
108
+ if (code === "ENOENT") {
109
+ throw new FromIssueError(
110
+ `gh CLI not found on PATH (looked for "${ghCommand}"). Install GitHub CLI or pass --gh <cmd>.`,
111
+ );
112
+ }
113
+ throw new FromIssueError(`gh issue view ${issueNumber} failed to run: ${result.error.message}`);
114
+ }
115
+ if (result.status !== 0) {
116
+ const stderr = (result.stderr ?? "").trim();
117
+ throw new FromIssueError(
118
+ stderr || `gh issue view ${issueNumber} exited with status ${result.status ?? "unknown"}`,
119
+ );
120
+ }
121
+ return parseIssueJson(result.stdout ?? "", issueNumber);
122
+ }
123
+
124
+ /**
125
+ * Slugify an issue title for the `SP-###-<slug>` folder name.
126
+ * Safe chars only [a-z0-9-]; falls back to `issue` when nothing remains.
127
+ *
128
+ * @param {string} title
129
+ * @param {{ maxLength?: number }} [options]
130
+ * @returns {string}
131
+ */
132
+ export function slugifyTitle(title, { maxLength = SLUG_MAX_LENGTH } = {}) {
133
+ const slug = String(title ?? "")
134
+ .toLowerCase()
135
+ .replace(/[^a-z0-9]+/g, "-")
136
+ .replace(/^-+|-+$/g, "")
137
+ .slice(0, maxLength)
138
+ .replace(/-+$/g, "");
139
+ return slug || "issue";
140
+ }
141
+
142
+ /**
143
+ * Build the scaffolded PROMPT.md. Contract rows are intentionally empty so
144
+ * `spine tasks validate` fails until the operator fills them.
145
+ *
146
+ * @param {{ taskId: string, issue: { number: number, title: string }, linkType: "closes"|"partial", created?: string }} options
147
+ * @returns {string}
148
+ */
149
+ export function buildPromptScaffold({ taskId, issue, linkType, created }) {
150
+ const day = created ?? new Date().toISOString().slice(0, 10);
151
+ const link = linkType === "partial" ? "Partial" : "Closes";
152
+ return `# Task: ${taskId} — ${issue.title}
153
+
154
+ **Created:** ${day}
155
+ **Size:** M
156
+ **Type:** llm
157
+
158
+ ## Review Level: 1 (Plan Only)
159
+
160
+ <!-- TODO(operator): adjust review level, risk, and score before batch start. -->
161
+
162
+ **Risk:** TODO(operator): severity and blast radius.
163
+ **Score:** 0/8 — Blast radius: 0, Pattern novelty: 0, Security: 0, Reversibility: 0
164
+
165
+ ## Mission
166
+
167
+ ${link} #${issue.number} — ${issue.title}. Narrative and acceptance criteria live on the issue; keep this packet thin (#385) and fill Contract, File Scope, and Steps below before batch start.
168
+
169
+ ## Dependencies
170
+
171
+ <!-- TODO(operator): list real dependencies only; this scaffold never writes dependencies.json edges. -->
172
+
173
+ - **None**
174
+
175
+ ## Context to Read First
176
+
177
+ - GitHub #${issue.number} — narrative and ACs (\`gh issue view ${issue.number}\`)
178
+
179
+ ## Environment
180
+
181
+ <!-- TODO(operator): fill workspace and required services. -->
182
+
183
+ - **Workspace:** TODO(operator)
184
+ - **Services required:** None
185
+
186
+ ## File Scope
187
+
188
+ <!-- TODO(operator): list files this task creates or modifies; used for lane packing. Do not leave empty. -->
189
+
190
+ ## Contract
191
+
192
+ <!-- TODO(operator): fill every field before batch start. \`spine tasks validate ${taskId}\` must pass after fill-in. -->
193
+
194
+ | Field | Value |
195
+ |-------|-------|
196
+ | testCommand | |
197
+ | fileScopeMustChange | |
198
+
199
+ ## Steps
200
+
201
+ ### Step 0: TODO(operator) — Implementation
202
+ - [ ] TODO(operator): define concrete outcomes for this task
203
+
204
+ ### Step 1: Testing & Verification
205
+ - [ ] Fill Contract testCommand, then run \`spine tasks validate ${taskId}\`
206
+
207
+ ## Completion Criteria
208
+
209
+ - [ ] Contract filled; \`spine tasks validate ${taskId}\` exits 0
210
+ - [ ] TODO(operator): concrete deliverables
211
+
212
+ ## Do NOT
213
+
214
+ - Auto \`spine batch start\` before Contract is filled
215
+ - Replace this packet with the issue body at runtime
216
+ - Edit \`.spine/\` or \`.review/\`
217
+ - Modify \`AGENTS.md\`, \`CLAUDE.md\`, or \`.gitnexus/\`
218
+
219
+ ## Git Commit Convention
220
+
221
+ - \`feat(${taskId}): <summary>\`
222
+
223
+ ## Amendments
224
+
225
+ - None
226
+ `;
227
+ }
228
+
229
+ /**
230
+ * Build the scaffolded STATUS.md mirroring the PROMPT steps.
231
+ *
232
+ * @param {{ taskId: string, created?: string }} options
233
+ * @returns {string}
234
+ */
235
+ export function buildStatusScaffold({ taskId, created }) {
236
+ const day = created ?? new Date().toISOString().slice(0, 10);
237
+ return `# STATUS — ${taskId}
238
+
239
+ **Task:** ${taskId}
240
+ **Current Step:** Step 0 — TODO(operator) Implementation
241
+ **Status:** 🔵 Ready for Execution
242
+ **Last Updated:** ${day}
243
+
244
+ ## Steps
245
+
246
+ ### Step 0: TODO(operator) — Implementation
247
+ **Status:** ⬜ Not Started
248
+
249
+ - [ ] TODO(operator): define concrete outcomes for this task
250
+
251
+ ### Step 1: Testing & Verification
252
+ **Status:** ⬜ Not Started
253
+
254
+ - [ ] Fill Contract testCommand, then run \`spine tasks validate ${taskId}\`
255
+
256
+ ## Blockers
257
+
258
+ - Contract/File Scope/Steps are stubs until the operator fills them (#384)
259
+
260
+ ## Discoveries
261
+
262
+ - Scaffolded from a GitHub issue via \`spine tasks from-issue\`; keep narrative on the issue (#385).
263
+ `;
264
+ }
265
+
266
+ /**
267
+ * Read `**Next Task ID:** PREFIX-###` from CONTEXT.md (read-only).
268
+ *
269
+ * @param {string} contextPath Absolute path to CONTEXT.md
270
+ * @returns {string|null} Task ID, or null when missing/unparsable
271
+ */
272
+ export function readNextTaskId(contextPath) {
273
+ let markdown;
274
+ try {
275
+ markdown = fs.readFileSync(contextPath, "utf-8");
276
+ } catch {
277
+ return null;
278
+ }
279
+ return NEXT_TASK_ID_LINE_RE.exec(markdown)?.[1] ?? null;
280
+ }
281
+
282
+ /**
283
+ * Update the `**Next Task ID:**` line in CONTEXT.md. Explicit opt-in only —
284
+ * this module never calls it without a caller-provided `nextId`.
285
+ *
286
+ * @param {string} contextPath Absolute path to CONTEXT.md
287
+ * @param {string} nextId New task ID (PREFIX-###)
288
+ */
289
+ export function updateNextTaskId(contextPath, nextId) {
290
+ if (!TASK_ID_RE.test(nextId)) {
291
+ throw new FromIssueError(
292
+ `Invalid --next-id value: "${nextId}". Expected PREFIX-### (e.g. SP-891).`,
293
+ );
294
+ }
295
+ let markdown;
296
+ try {
297
+ markdown = fs.readFileSync(contextPath, "utf-8");
298
+ } catch (err) {
299
+ throw new FromIssueError(`Cannot read CONTEXT.md at ${contextPath}: ${err instanceof Error ? err.message : String(err)}`);
300
+ }
301
+ if (!NEXT_TASK_ID_LINE_RE.test(markdown)) {
302
+ throw new FromIssueError(
303
+ `CONTEXT.md has no \`**Next Task ID:** PREFIX-###\` line; update it manually instead of using --next-id.`,
304
+ );
305
+ }
306
+ const updated = markdown.replace(NEXT_TASK_ID_LINE_RE, `**Next Task ID:** ${nextId}`);
307
+ fs.writeFileSync(contextPath, updated, "utf-8");
308
+ }
309
+
310
+ /**
311
+ * Scaffold `{tasksRoot}/{taskId}-{slug}/` with PROMPT.md + STATUS.md stubs.
312
+ *
313
+ * @param {object} options
314
+ * @param {string} options.tasksRoot Absolute tasks root
315
+ * @param {{ number: number, title: string }} options.issue Fetched issue (title/body)
316
+ * @param {"closes"|"partial"} options.linkType Mission link format
317
+ * @param {string} [options.taskId] Explicit task ID; defaults to CONTEXT.md Next Task ID
318
+ * @param {string} [options.slug] Folder slug override; defaults to slugified title. Validated: [a-z0-9-] only, max 48 chars
319
+ * @param {string} [options.nextId] Explicit CONTEXT.md Next Task ID update (opt-in)
320
+ * @param {string} [options.created] Override the Created date (ISO date)
321
+ * @returns {{ taskId: string, folderPath: string, promptPath: string, statusPath: string, contextNextIdUpdated: boolean }}
322
+ */
323
+ export function scaffoldTaskFolder({
324
+ tasksRoot,
325
+ issue,
326
+ linkType,
327
+ taskId,
328
+ slug,
329
+ nextId,
330
+ created,
331
+ }) {
332
+ if (linkType !== "closes" && linkType !== "partial") {
333
+ throw new FromIssueError(`Invalid linkType: ${linkType}. Expected "closes" or "partial".`);
334
+ }
335
+
336
+ /** @type {string | null | undefined} */
337
+ let resolvedTaskId = taskId;
338
+ if (resolvedTaskId === undefined || resolvedTaskId === null || resolvedTaskId === "") {
339
+ resolvedTaskId = readNextTaskId(path.join(tasksRoot, "CONTEXT.md"));
340
+ if (!resolvedTaskId) {
341
+ throw new FromIssueError(
342
+ `Cannot derive a task ID: no \`**Next Task ID:**\` in ${path.join(tasksRoot, "CONTEXT.md")}. Pass --id SP-### explicitly.`,
343
+ );
344
+ }
345
+ }
346
+ if (!TASK_ID_RE.test(resolvedTaskId)) {
347
+ throw new FromIssueError(`Invalid task ID: "${resolvedTaskId}". Expected PREFIX-### (e.g. SP-890).`);
348
+ }
349
+
350
+ const resolvedSlug = slug ?? slugifyTitle(issue.title);
351
+ if (typeof resolvedSlug !== "string" || !SLUG_RE.test(resolvedSlug) || resolvedSlug.length > SLUG_MAX_LENGTH) {
352
+ throw new FromIssueError(
353
+ `Invalid slug: ${JSON.stringify(resolvedSlug ?? String(slug))}. Expected lowercase alphanumerics with single hyphens (no dots, slashes, or traversal), max ${SLUG_MAX_LENGTH} chars.`,
354
+ );
355
+ }
356
+
357
+ const folderName = `${resolvedTaskId}-${resolvedSlug}`;
358
+ const folderPath = path.join(tasksRoot, folderName);
359
+ // Ensure the tasks root exists (race-free: recursive mkdir is a no-op when
360
+ // it already exists), then create the task folder atomically — EEXIST from
361
+ // the non-recursive call is the fail-loud duplicate guard.
362
+ fs.mkdirSync(tasksRoot, { recursive: true });
363
+ try {
364
+ fs.mkdirSync(folderPath, { recursive: false });
365
+ } catch (err) {
366
+ if (/** @type {NodeJS.ErrnoException} */ (err).code === "EEXIST") {
367
+ throw new FromIssueError(
368
+ `Task folder already exists: ${folderPath}. Pass --id/--slug or remove the folder first.`,
369
+ );
370
+ }
371
+ throw new FromIssueError(
372
+ `Cannot create task folder ${folderPath}: ${err instanceof Error ? err.message : String(err)}`,
373
+ );
374
+ }
375
+ const promptPath = path.join(folderPath, "PROMPT.md");
376
+ const statusPath = path.join(folderPath, "STATUS.md");
377
+ fs.writeFileSync(promptPath, buildPromptScaffold({ taskId: resolvedTaskId, issue, linkType, created }), "utf-8");
378
+ fs.writeFileSync(statusPath, buildStatusScaffold({ taskId: resolvedTaskId, created }), "utf-8");
379
+
380
+ let contextNextIdUpdated = false;
381
+ if (nextId !== undefined && nextId !== null && nextId !== "") {
382
+ updateNextTaskId(path.join(tasksRoot, "CONTEXT.md"), nextId);
383
+ contextNextIdUpdated = true;
384
+ }
385
+
386
+ return {
387
+ taskId: resolvedTaskId,
388
+ folderPath,
389
+ promptPath,
390
+ statusPath,
391
+ contextNextIdUpdated,
392
+ };
393
+ }