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.
@@ -11,10 +11,42 @@ Options:
11
11
  --batch ID Target batch (default: active batch)
12
12
  --dry-run Show the merge plan without changing anything
13
13
  --force-integrate Bypass the gate (requires SPINE_ALLOW_FORCE=1)
14
+ --no-github-sync Skip the opt-in post-integrate GitHub issue sync (#383)
14
15
  --json Machine-readable output
15
16
  --help, -h Show this help without changing state
16
17
  `;
17
18
 
19
+ /**
20
+ * Human-readable GitHub sync summary lines (#383). Rendered after the merge
21
+ * details; soft failures show the hint without changing the exit code.
22
+ *
23
+ * @param {string[]} lines
24
+ * @param {object} sync githubSync summary from syncIssuesOnLand
25
+ */
26
+ function appendGithubSyncLines(lines, sync) {
27
+ if (sync.skipped) {
28
+ if (sync.reason === "no_github_sync_flag") {
29
+ lines.push("", " GitHub: sync skipped (--no-github-sync)");
30
+ }
31
+ return;
32
+ }
33
+ const synced = Array.isArray(sync.synced) ? sync.synced : [];
34
+ const failures = Array.isArray(sync.failures) ? sync.failures : [];
35
+ if (synced.length > 0) {
36
+ const closed = synced.filter((s) => s.closed).map((s) => `#${s.issue}`);
37
+ const commented = synced.filter((s) => !s.closed).map((s) => `#${s.issue}`);
38
+ const parts = [];
39
+ if (closed.length) parts.push(`closed ${closed.join(", ")}`);
40
+ if (commented.length) parts.push(`commented ${commented.join(", ")}`);
41
+ lines.push("", ` GitHub: synced ${synced.length} issue(s) — ${parts.join("; ")}`);
42
+ }
43
+ if (failures.length > 0) {
44
+ lines.push(` GitHub: ${failures.length} issue(s) failed — see journal (github.issue_sync_failed)`);
45
+ } else if (synced.length === 0 && sync.softFailed && sync.hint) {
46
+ lines.push("", ` GitHub: sync skipped — ${sync.hint}`);
47
+ }
48
+ }
49
+
18
50
  /**
19
51
  * @param {object} result
20
52
  * @param {boolean} json
@@ -42,6 +74,9 @@ export function formatIntegrateHuman(result, json = false) {
42
74
  if (result.mergePlan) {
43
75
  lines.push(` Plan: ${result.mergePlan}`);
44
76
  }
77
+ if (result.githubSync) {
78
+ appendGithubSyncLines(lines, result.githubSync);
79
+ }
45
80
  if (result.failureClass === "GateBlocked") {
46
81
  // Integrate actually stopped for a pending/missing/rejected gate (#359).
47
82
  lines.push("", " Gate: integrate blocked until approved");
@@ -75,7 +110,7 @@ export function runSpineIntegrate(options) {
75
110
  const { projectRoot, args } = options;
76
111
  const parsed = parseStrictArgs(args, {
77
112
  valued: ["--batch"],
78
- boolean: ["--dry-run", "--force-integrate", "--json"],
113
+ boolean: ["--dry-run", "--force-integrate", "--json", "--no-github-sync"],
79
114
  });
80
115
  const flags = parsed.flags;
81
116
  if (parsed.help) {
@@ -108,6 +143,7 @@ export function runSpineIntegrate(options) {
108
143
  dryRun: flags.has("--dry-run"),
109
144
  batchId: parsed.values.get("--batch") ?? null,
110
145
  forceIntegrate: flags.has("--force-integrate"),
146
+ noGithubSync: flags.has("--no-github-sync"),
111
147
  });
112
148
 
113
149
  return {
@@ -14,6 +14,7 @@ import { resolveTasksRootPath } from '../src/config/env-overrides.mjs';
14
14
  import { missingConfigHint } from '../src/config/missing-config-hint.mjs';
15
15
  import { buildPlan } from '../src/planner/index.mjs';
16
16
  import { formatPlanHuman } from '../src/planner/format-plan.mjs';
17
+ import { parseBoardSelectArgs, runBoardSelect } from '../src/cli/board-select.mjs';
17
18
 
18
19
  export { formatPlanHuman } from '../src/planner/format-plan.mjs';
19
20
 
@@ -121,7 +122,32 @@ export async function runSpinePlan({
121
122
  async function main() {
122
123
  const argv = process.argv.slice(2);
123
124
  const json = argv.includes('--json');
124
- const scope = argv.filter((a) => !a.startsWith('--')).join(' ') || 'all';
125
+
126
+ // SP-889 (#386): board selection — GitHub label/milestone → pending task IDs.
127
+ const board = parseBoardSelectArgs(argv);
128
+ if (board.labels.length > 0 || (board.milestone !== null && board.milestone !== '')) {
129
+ try {
130
+ const { output } = await runBoardSelect({
131
+ projectRoot: process.cwd(),
132
+ labels: board.labels,
133
+ milestone: board.milestone,
134
+ printIds: board.printIds,
135
+ json,
136
+ });
137
+ process.stdout.write(output + '\n');
138
+ } catch (err) {
139
+ const msg = err?.message ?? String(err);
140
+ if (err?.suggestedCommand) {
141
+ console.error(`Error: ${msg}\nSuggested: ${err.suggestedCommand}`);
142
+ } else {
143
+ console.error(`Error: ${msg}`);
144
+ }
145
+ process.exit(1);
146
+ }
147
+ return;
148
+ }
149
+
150
+ const scope = board.rest.filter((a) => !a.startsWith('--')).join(' ') || 'all';
125
151
 
126
152
  try {
127
153
  const { output } = await runSpinePlan({ projectRoot: process.cwd(), scope, json });
@@ -19,6 +19,10 @@ import {
19
19
  loadTaskPacket,
20
20
  } from '../src/tasks/packet/index.mjs';
21
21
  import { collectStaleFileScopeMustChangeWarnings } from '../src/tasks/packet/validate-prompt.mjs';
22
+ import {
23
+ fetchIssueViaGh,
24
+ scaffoldTaskFolder,
25
+ } from '../src/tasks/from-issue.mjs';
22
26
  import { parseScope } from '../src/planner/scope.mjs';
23
27
 
24
28
  /**
@@ -126,6 +130,7 @@ ${c.bold}spine tasks${c.reset} — validate and analyze task PROMPT packets (FR-
126
130
  ${c.bold}Usage:${c.reset}
127
131
  spine tasks validate <scope> [--json] [--warnings-only]
128
132
  spine tasks analyze <scope> [--json]
133
+ spine tasks from-issue <n> [options]
129
134
 
130
135
  ${c.bold}Scope:${c.reset}
131
136
  Same resolution as ${c.cyan}spine plan${c.reset}: all, pending, task IDs, globs.
@@ -139,6 +144,21 @@ ${c.bold}Analyze:${c.reset}
139
144
  Deterministic structural checks: parallel file-scope overlap, dependency cycles,
140
145
  orphan task IDs (blocking); wave M-count, explore refs, PROMPT/JSON deps drift (warnings).
141
146
 
147
+ ${c.bold}From-issue (#384):${c.reset}
148
+ Fetch a GitHub issue via gh and scaffold {tasksRoot}/SP-###-<slug>/ with
149
+ thin-packet stubs. Contract/File Scope/Steps stay incomplete until the
150
+ operator fills them; dependencies.json is never written.
151
+
152
+ ${c.bold}From-issue options:${c.reset}
153
+ --closes Mission first line "Closes #N" (default)
154
+ --partial Mission first line "Partial #N"
155
+ --id SP-### Explicit task ID (default: CONTEXT.md Next Task ID, read-only)
156
+ --slug SLUG Folder slug override: lowercase alphanumerics + single hyphens,
157
+ max 48 chars (default: slugified issue title)
158
+ --next-id SP-### Update CONTEXT.md Next Task ID (explicit opt-in, never automatic)
159
+ --gh CMD gh command to invoke (default: gh)
160
+ --json Print scaffold summary as JSON
161
+
142
162
  ${c.bold}Exit codes (validate):${c.reset}
143
163
  0 all selected tasks pass
144
164
  1 one or more PROMPT validation failures
@@ -149,12 +169,19 @@ ${c.bold}Exit codes (analyze):${c.reset}
149
169
  1 one or more blocking findings
150
170
  2 config, tasksRoot, or scope resolution error
151
171
 
172
+ ${c.bold}Exit codes (from-issue):${c.reset}
173
+ 0 scaffold written
174
+ 1 gh fetch, validation, or existing-folder error
175
+ 2 config or tasksRoot resolution error
176
+
152
177
  ${c.bold}Examples:${c.reset}
153
178
  spine tasks validate all
154
179
  spine tasks validate pending --warnings-only
155
180
  spine tasks validate FX-101 --json
156
181
  spine tasks analyze pending
157
182
  spine tasks analyze all --json
183
+ spine tasks from-issue 384 --partial --id SP-890
184
+ spine tasks from-issue 384 --next-id SP-891 # explicit CONTEXT.md update
158
185
  `);
159
186
  }
160
187
 
@@ -369,6 +396,180 @@ async function handleTasksAnalyze(args) {
369
396
  }
370
397
  }
371
398
 
399
+ /**
400
+ * Scaffold an SP-* packet from a GitHub issue (#384). Thin-packet stubs only:
401
+ * Contract/File Scope/Steps stay incomplete until the operator fills them;
402
+ * dependencies.json is never written; CONTEXT.md Next Task ID is touched
403
+ * only when `nextId` is explicitly provided.
404
+ *
405
+ * @param {object} [options]
406
+ * @param {string} [options.projectRoot]
407
+ * @param {number} [options.issueNumber]
408
+ * @param {boolean} [options.closes] Mission first line "Closes #N" (CLI default when --partial absent)
409
+ * @param {boolean} [options.partial] Mission first line "Partial #N"
410
+ * @param {string|null} [options.taskId] Explicit task ID (else CONTEXT.md Next Task ID)
411
+ * @param {string|null} [options.slug] Folder slug override
412
+ * @param {string|null} [options.nextId] Explicit CONTEXT.md Next Task ID update
413
+ * @param {string} [options.ghCommand]
414
+ * @param {boolean} [options.json]
415
+ * @returns {Promise<{output: string, exitCode: number}>}
416
+ */
417
+ export async function runSpineTasksFromIssue({
418
+ projectRoot = process.cwd(),
419
+ issueNumber,
420
+ closes = false,
421
+ partial = false,
422
+ taskId = null,
423
+ slug = null,
424
+ nextId = null,
425
+ ghCommand = 'gh',
426
+ json = false,
427
+ } = {}) {
428
+ if (!Number.isInteger(issueNumber) || issueNumber <= 0) {
429
+ throwTasksValidateError(`Invalid issue number: ${issueNumber ?? '(missing)'}. Expected a positive integer, e.g. spine tasks from-issue 384`);
430
+ }
431
+ if (closes && partial) {
432
+ throwTasksValidateError('Pass only one of --closes / --partial');
433
+ }
434
+
435
+ const configResult = loadSpineConfig(projectRoot);
436
+ if (configResult.error) {
437
+ throwTasksValidateError(configResult.error.message, {
438
+ suggestedCommand: configResult.error.suggestedCommand,
439
+ });
440
+ }
441
+ const tasksRoot = resolveTasksRootPath(projectRoot, configResult.config);
442
+ if (!tasksRoot) {
443
+ throwTasksValidateError('Cannot scaffold tasks: tasksRoot not configured', {
444
+ suggestedCommand: missingConfigHint(projectRoot).suggestedCommand,
445
+ });
446
+ }
447
+
448
+ let issue;
449
+ try {
450
+ issue = fetchIssueViaGh({ issueNumber, projectRoot, ghCommand });
451
+ } catch (err) {
452
+ throwTasksValidateError(err?.message ?? String(err), { exitCode: 1 });
453
+ }
454
+
455
+ let scaffold;
456
+ try {
457
+ scaffold = scaffoldTaskFolder({
458
+ tasksRoot,
459
+ issue,
460
+ linkType: partial ? 'partial' : 'closes',
461
+ taskId: taskId ?? undefined,
462
+ slug: slug ?? undefined,
463
+ nextId: nextId ?? undefined,
464
+ });
465
+ } catch (err) {
466
+ throwTasksValidateError(err?.message ?? String(err), { exitCode: 1 });
467
+ }
468
+
469
+ const missionLink = `${partial ? 'Partial' : 'Closes'} #${issueNumber}`;
470
+ if (json) {
471
+ const payload = {
472
+ taskId: scaffold.taskId,
473
+ issueNumber,
474
+ missionLink,
475
+ folder: path.relative(projectRoot, scaffold.folderPath),
476
+ promptPath: scaffold.promptPath,
477
+ statusPath: scaffold.statusPath,
478
+ contextNextIdUpdated: scaffold.contextNextIdUpdated,
479
+ };
480
+ return { output: `${JSON.stringify(payload, null, 2)}\n`, exitCode: 0 };
481
+ }
482
+
483
+ const relFolder = path.relative(projectRoot, scaffold.folderPath);
484
+ const contextNote = scaffold.contextNextIdUpdated
485
+ ? `CONTEXT.md Next Task ID updated via --next-id`
486
+ : `CONTEXT.md unchanged (pass --next-id SP-### to update)`;
487
+ const output = [
488
+ `Scaffolded ${scaffold.taskId} from issue #${issueNumber}`,
489
+ '',
490
+ ` Folder: ${relFolder}`,
491
+ ` Mission: ${missionLink} — ${issue.title}`,
492
+ ` Contract: EMPTY — fill Contract / File Scope / Steps before batch start`,
493
+ ` CONTEXT: ${contextNote}`,
494
+ '',
495
+ `Next: fill the stubs, then run ${c.cyan}spine tasks validate ${scaffold.taskId}${c.reset}.`,
496
+ `No dependencies.json edges were written (add real deps only, with confirmation).`,
497
+ '',
498
+ ].join('\n');
499
+ return { output, exitCode: 0 };
500
+ }
501
+
502
+ /**
503
+ * @param {string[]} args
504
+ */
505
+ async function handleTasksFromIssue(args) {
506
+ const rest = args.slice(1);
507
+ /** @type {Record<string, string|null>} */
508
+ const flagValues = { '--id': null, '--slug': null, '--next-id': null, '--gh': null };
509
+ const positionals = [];
510
+ let json = false;
511
+ let closes = false;
512
+ let partial = false;
513
+ for (let i = 0; i < rest.length; i++) {
514
+ const arg = rest[i];
515
+ if (arg === '--help' || arg === '-h') {
516
+ printTasksHelp();
517
+ return;
518
+ }
519
+ if (arg === '--json') {
520
+ json = true;
521
+ continue;
522
+ }
523
+ if (arg === '--closes') {
524
+ closes = true;
525
+ continue;
526
+ }
527
+ if (arg === '--partial') {
528
+ partial = true;
529
+ continue;
530
+ }
531
+ if (arg in flagValues) {
532
+ const value = rest[++i];
533
+ if (value === undefined || value.startsWith('--')) {
534
+ console.error(`Error: ${arg} requires a value.`);
535
+ process.exit(2);
536
+ }
537
+ flagValues[arg] = value;
538
+ continue;
539
+ }
540
+ if (arg.startsWith('--')) {
541
+ console.error(`Error: unknown from-issue flag: ${arg}\nRun ${c.cyan}spine help tasks${c.reset} for usage.`);
542
+ process.exit(2);
543
+ }
544
+ positionals.push(arg);
545
+ }
546
+ if (!closes && !partial) closes = true;
547
+
548
+ const issueNumber = Number(positionals[0]);
549
+ try {
550
+ const result = await runSpineTasksFromIssue({
551
+ projectRoot: process.cwd(),
552
+ issueNumber,
553
+ closes,
554
+ partial,
555
+ taskId: flagValues['--id'],
556
+ slug: flagValues['--slug'],
557
+ nextId: flagValues['--next-id'],
558
+ ghCommand: flagValues['--gh'] ?? 'gh',
559
+ json,
560
+ });
561
+ writeCommandResult(result);
562
+ } catch (err) {
563
+ const msg = err?.message ?? String(err);
564
+ if (err?.suggestedCommand) {
565
+ console.error(`Error: ${msg}\nSuggested: ${err.suggestedCommand}`);
566
+ } else {
567
+ console.error(`Error: ${msg}`);
568
+ }
569
+ process.exit(err?.exitCode ?? 2);
570
+ }
571
+ }
572
+
372
573
  /**
373
574
  * @param {string[]} args
374
575
  */
@@ -382,6 +583,10 @@ export async function handleTasks(args) {
382
583
  await handleTasksAnalyze(args);
383
584
  return;
384
585
  }
586
+ if (sub === 'from-issue') {
587
+ await handleTasksFromIssue(args);
588
+ return;
589
+ }
385
590
 
386
591
  const { die } = await import('./spine-cli/shared.mjs');
387
592
  die(
@@ -48,6 +48,14 @@ import {
48
48
  } from "../src/doctor/pi-extension-conflict.mjs";
49
49
  import { PROMPT_THINKING_LEVELS, parseContract, parsePrompt } from "../src/tasks/packet/parse-prompt.mjs";
50
50
 
51
+ /**
52
+ * `pi --mode json` streams the full system prompt (rules + extension tool schemas)
53
+ * as one NDJSON event. Node's spawnSync default maxBuffer is 1 MiB; exceeding it
54
+ * kills the child with ENOBUFS → SIGTERM (exit 143) and truncates stdout mid-event.
55
+ * Keep this well above observed worker system-prompt sizes (multi-MiB with extensions).
56
+ */
57
+ export const WORKER_PI_JSON_MAX_BUFFER = 64 * 1024 * 1024;
58
+
51
59
  /**
52
60
  * Actionable hint when pi worker spawn fails on duplicate extension tool registration.
53
61
  *
@@ -624,6 +632,7 @@ async function runWorkerRunner() {
624
632
  cwd: worktreePath || process.cwd(),
625
633
  encoding: "utf-8",
626
634
  timeout: timeoutMs,
635
+ maxBuffer: WORKER_PI_JSON_MAX_BUFFER,
627
636
  });
628
637
 
629
638
  // SP-879 (#338): persist provider-reported usage before any terminal exit so
@@ -640,6 +649,19 @@ async function runWorkerRunner() {
640
649
  process.exit(124);
641
650
  }
642
651
 
652
+ if (result.error?.code === "ENOBUFS") {
653
+ console.error(
654
+ `pi --mode json stdout exceeded maxBuffer (${WORKER_PI_JSON_MAX_BUFFER} bytes); ` +
655
+ "raise WORKER_PI_JSON_MAX_BUFFER or shrink worker system prompt (rules/extensions).",
656
+ );
657
+ if (piLogText) {
658
+ process.stdout.write(
659
+ `\n[pi assistant output]\n${truncateLiveLogBytes(piLogText, resolveWorkerOutputConfig(spineConfig).maxBytes)}\n`,
660
+ );
661
+ }
662
+ process.exit(1);
663
+ }
664
+
643
665
  if (result.status !== 0) {
644
666
  const combined = `${result.stderr ?? ""}${result.stdout ?? ""}`;
645
667
  const conflictHint = formatPiExtensionConflictHint(combined);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-spine",
3
- "version": "2.33.0",
3
+ "version": "2.34.0",
4
4
  "description": "Orchestration spine for long-running pi development",
5
5
  "keywords": [
6
6
  "pi-package",
@@ -544,6 +544,55 @@ Packet shape decides most of a batch's token spend. Each choice below removes LL
544
544
 
545
545
  ---
546
546
 
547
+ ## Thin packets (issue narrative vs packet Contract) — #385 / #382
548
+
549
+ **Dual-layer seam:** GitHub Issues hold goals and discussion (human/intake SoR). Packets under `paths.tasksRoot` hold Contract, File Scope, Steps, Do NOT, and STATUS (agent/engine SoR). Do **not** paste full issue threads into worker context.
550
+
551
+ | Layer | Keep here | Do not dump here |
552
+ |-------|-----------|------------------|
553
+ | GitHub issue | Narrative, ACs discussion, comments, board labels | Machine Contract / File Scope as the only source of truth |
554
+ | Packet `## Mission` | One short paragraph + `Closes #N` / `Partial #N` pointing at the issue | Multi-page issue body or all comment history |
555
+ | Packet Contract / File Scope / Steps / Do NOT | Complete, local, authoritative for the batch | “See issue for File Scope” without listing paths |
556
+ | Context to Read First | Few high-signal paths the worker needs | Unbounded “read all comments on #N” or pasted mega-dumps |
557
+
558
+ **Good Mission example:**
559
+
560
+ ```markdown
561
+ ## Mission
562
+
563
+ Closes #384 — Scaffold SP-* packets from a GitHub issue via `spine tasks from-issue`. Keep Contract stubs incomplete until the operator fills File Scope.
564
+ ```
565
+
566
+ **Fat-context anti-pattern:** Pasting the entire issue body plus comment thread into Context to Read First or Mission. Prefer the `#N` link and a one-line pointer; use `neverLoad` for docs that must stay out of worker context.
567
+
568
+ **Advisory validate (deferred):** A warn-only `spine tasks validate` heuristic for mega Context dumps is **deferred** — hard to distinguish legitimate multi-doc Context from dumps without false positives, and hard-fail on any issue link is explicitly out of scope for #385. Authors rely on this DoR item until a later advisory lands.
569
+
570
+ ## Hydrate from a GitHub issue — `spine tasks from-issue` (#384 / #382)
571
+
572
+ Thin CLI path from an open issue to a stub packet. Fetches the issue title via `gh issue view --json`, scaffolds `{tasksRoot}/SP-###-<slug>/`, and stops before inventing Contract content:
573
+
574
+ ```bash
575
+ spine tasks from-issue 384 # Mission "Closes #384" (default)
576
+ spine tasks from-issue 384 --partial # one of several tasks for the issue
577
+ spine tasks from-issue 384 --id SP-890 --slug hydrate-issue
578
+ spine tasks from-issue 384 --next-id SP-891 # explicit CONTEXT.md counter update
579
+ ```
580
+
581
+ | Concern | Behavior |
582
+ |---------|----------|
583
+ | Task ID | `--id SP-###`, else **Next Task ID** read from `{tasksRoot}/CONTEXT.md` (read-only); fails loud when neither is available |
584
+ | Mission | First line `Closes #N — <title>` / `Partial #N` ([#147](https://github.com/beettlle/pi-spine/issues/147)); thin pointer to the issue, never the pasted body (#385) |
585
+ | Contract / File Scope / Steps | Required stubs with `TODO(operator)` markers; the Contract table ships **empty** so `spine tasks validate <id>` fails until the operator fills it |
586
+ | `dependencies.json` | Never written — add real edges only, with confirmation |
587
+ | CONTEXT.md | Unchanged unless `--next-id SP-###` is passed explicitly |
588
+ | Exit codes | 0 scaffolded · 1 gh fetch / validation / existing-folder · 2 config or tasksRoot |
589
+
590
+ **Validate-after-fill loop (required):** the operator fills Contract / File Scope / Steps, then `spine tasks validate <id>` must pass before `spine tasks analyze`, `spine plan`, or `spine batch start`. Never start a batch from a scaffold with empty Contract rows — the packet fails validation by design until the fill-in is done.
591
+
592
+ **When to use which path:** `from-issue` is single-issue intake (one packet from one issue, operator completes the Contract). Use the full PRD decomposition workflow (Step A → Step C) when slicing an epic into many packets — the scaffold does not split work or infer File Scope.
593
+
594
+ ---
595
+
547
596
  ## Unsupported (spine v1)
548
597
 
549
598
  Do **not** generate Taskplane polyrepo **`#### Segment: <repoId>`** markers — pi-spine is monorepo-only (PRD §13.2). Split multi-repo work into separate tasks with dependencies instead.
@@ -574,6 +623,8 @@ Before reporting launch commands:
574
623
  - [ ] Size S/M/L — split if XL
575
624
  - [ ] PROMPT.md from template: Mission, Dependencies, Context, File Scope, Contract (SP-\*), Steps, Do NOT, Git Commit Convention, Amendments
576
625
  - [ ] Mission uses `Closes #N` or `Partial #N` on first line when tracking GitHub issues ([#147](https://github.com/beettlle/pi-spine/issues/147))
626
+ - [ ] Thin packet: short Mission + `#N` pointer; Contract/File Scope/Steps/Do NOT complete locally — no pasted issue-thread mega-dumps in Context ([#385](https://github.com/beettlle/pi-spine/issues/385) / [Thin packets](#thin-packets-issue-narrative-vs-packet-contract--385--382))
627
+ - [ ] Issue intake via `spine tasks from-issue`: Contract / File Scope / Steps filled and `spine tasks validate <id>` passing before plan/batch ([#384](https://github.com/beettlle/pi-spine/issues/384) / [Hydrate](#hydrate-from-a-github-issue--spine-tasks-from-issue-384--382))
577
628
  - [ ] Split-successor tasks include `Parent split: SP-###` in Context to Read First ([#146](https://github.com/beettlle/pi-spine/issues/146))
578
629
  - [ ] `## Do NOT` bans `.spine/`, `AGENTS.md`, `CLAUDE.md`, `.gitnexus/` ([#149](https://github.com/beettlle/pi-spine/issues/149))
579
630
  - [ ] Level 2+ only when operator environment supports cross-model review ([#150](https://github.com/beettlle/pi-spine/issues/150))
@@ -53,6 +53,7 @@ Deterministic commands use the [execute-task variant](#execute-task-variant) ins
53
53
  ## Context to Read First
54
54
 
55
55
  > Only list docs the worker actually needs. Less is better.
56
+ > **Thin packets (#385):** do not paste full GitHub issue threads here — use Mission `Closes #N` / `Partial #N` and keep narrative on the issue.
56
57
 
57
58
  - `[path/to/CONTEXT.md]`
58
59
  - `[path/to/specific-doc.md]` — [why needed]
@@ -79,6 +79,7 @@ START
79
79
  ## Wave picker algorithm
80
80
 
81
81
  1. Run `spine plan pending` (or `spine plan all` / explicit task scope).
82
+ - **Board-driven alternative (SP-889 / #386):** when the operator names a GitHub label or milestone, resolve the scope first — `node bin/spine-plan.mjs --github-label <label> --print-ids` (Mission `Closes`/`Partial` links → pending task IDs, selection only, no auto-start) — then plan that ID list to confirm wave structure.
82
83
  2. Parse wave index and task list:
83
84
  - **JSON:** `spine plan pending --json` → `waveCount`, per-wave `tasks[]`
84
85
  - **Text:** read wave headers from CLI output
@@ -409,6 +409,8 @@ Do not let `main` drift far ahead of `origin` between waves — v2.12.1 ran **24
409
409
 
410
410
  ### 4.3c Close GitHub issues for landed tasks (blocking hygiene)
411
411
 
412
+ > **Automated sync (SP-887 / #383):** repos with `integrations.github.syncOnLand: true` get the `Closes #N` / `Partial #N` actions below applied automatically by `spine integrate` (close = comment + close; partial = comment only; journal `github.issue_synced` / `github.issue_sync_failed`; escape hatch `spine integrate --no-github-sync`). The default is **off** — when disabled or soft-failed (missing `gh`/auth), perform this §4.3c sweep manually.
413
+
412
414
  After §4.3a is green (and §4.3b push when remote publish is the goal), **close every open issue fully resolved by tasks that just landed** — same wave, same land loop. Do not wait for Phase 6 or npm publish.
413
415
 
414
416
  ```bash
@@ -8,6 +8,7 @@ import { resolveTasksRootPath } from "../../config/env-overrides.mjs";
8
8
  import { discoverTasks, loadDependenciesJson } from "../../tasks/packet/index.mjs";
9
9
  import { loadTaskFileScopePaths } from "./queue.mjs";
10
10
  import { syncLaneWorktreeFromOrch } from "../worktree.mjs";
11
+ import { gitExec } from "../git-exec.mjs";
11
12
 
12
13
  /**
13
14
  * @param {string} projectRoot
@@ -131,3 +132,111 @@ export function ensureLaneSyncedForSharedScopeDeps({
131
132
  return { ok: false, error: message, sharedDeps };
132
133
  }
133
134
  }
135
+
136
+ /**
137
+ * Packet files refreshed from the base tasks root into the lane worktree on
138
+ * whole-task retry (#378). PROMPT.md carries the Contract the next worker run
139
+ * is parsed and verified against. STATUS.md stays lane-owned (worker progress
140
+ * + resume state) and is never overwritten by retry.
141
+ */
142
+ const PACKET_REFRESH_FILES = ["PROMPT.md"];
143
+
144
+ /**
145
+ * Resolve the base packet folder for a task. Prefers `state.tasks[].taskFolder`
146
+ * (absolute as authored by `discoverTasks`; relative values resolve against
147
+ * `projectRoot`, since cwd may differ), then falls back to discovering the
148
+ * task in the tasks root.
149
+ *
150
+ * @param {object} params
151
+ * @param {string} params.projectRoot
152
+ * @param {string} params.tasksRoot
153
+ * @param {Array<Record<string, any>>} params.stateTasks
154
+ * @param {string} params.taskId
155
+ * @returns {string | null}
156
+ */
157
+ function resolveBasePacketFolder({ projectRoot, tasksRoot, stateTasks, taskId }) {
158
+ const fromState = stateTasks.find((entry) => entry?.taskId === taskId)?.taskFolder;
159
+ if (typeof fromState === "string" && fromState.trim()) {
160
+ const candidate = path.isAbsolute(fromState) ? fromState : path.join(projectRoot, fromState);
161
+ if (fs.existsSync(candidate)) return candidate;
162
+ }
163
+ if (!fs.existsSync(tasksRoot)) return null;
164
+ const match = discoverTasks(tasksRoot).find((entry) => entry.taskId === taskId);
165
+ return match?.folderPath ?? null;
166
+ }
167
+
168
+ /**
169
+ * Refresh operator-edited packet files from the base tasks root into the lane
170
+ * worktree before a retried task re-runs (#378). `retryTask` resets batch
171
+ * state, but the lane worktree keeps the packet copy the failed run saw — an
172
+ * operator fix on base would never reach the next worker run (which reads
173
+ * `PROMPT.md` from `taskFolderInWorktree`), so `contract_failed` repeats.
174
+ *
175
+ * Best-effort by design: any missing path (no base packet, no lane worktree,
176
+ * no lane packet folder) skips the refresh without failing the retry. When a
177
+ * file does change, it is copied and committed with a pathspec limited to the
178
+ * packet file, so uncommitted lane product work from the failed run stays
179
+ * untouched.
180
+ *
181
+ * @param {object} params
182
+ * @param {string} params.projectRoot
183
+ * @param {Record<string, any>} params.state
184
+ * @param {string} params.taskId
185
+ * @param {Record<string, any>} [params.task] Live task entry (for laneNumber).
186
+ * @param {Record<string, any>} [params.config]
187
+ * @returns {{ ok: boolean, refreshed: Array<{ file: string, committed: boolean, commitSha: string | null }>, skipped: string | null, error: string | null }}
188
+ */
189
+ export function refreshTaskPacketFromBase({ projectRoot, state, taskId, task, config = {} }) {
190
+ try {
191
+ const tasksRoot = resolveBatchTasksRoot(projectRoot, config);
192
+ const stateTasks = Array.isArray(state?.tasks) ? state.tasks : [];
193
+ const baseFolder = resolveBasePacketFolder({ projectRoot, tasksRoot, stateTasks, taskId });
194
+ if (!baseFolder) {
195
+ return { ok: true, refreshed: [], skipped: "base_packet_missing", error: null };
196
+ }
197
+ const taskFolderRel = path.relative(projectRoot, baseFolder);
198
+ if (!taskFolderRel || taskFolderRel.startsWith("..") || path.isAbsolute(taskFolderRel)) {
199
+ return { ok: true, refreshed: [], skipped: "base_packet_outside_project", error: null };
200
+ }
201
+
202
+ const laneNumber = Number(task?.laneNumber ?? 1);
203
+ const worktreePath = (Array.isArray(state?.lanes) ? state.lanes : []).find(
204
+ (entry) => Number(entry?.laneNumber ?? -1) === laneNumber,
205
+ )?.worktreePath;
206
+ if (!worktreePath || !fs.existsSync(worktreePath)) {
207
+ return { ok: true, refreshed: [], skipped: "lane_worktree_missing", error: null };
208
+ }
209
+ const lanePacketFolder = path.join(worktreePath, taskFolderRel);
210
+ if (!fs.existsSync(lanePacketFolder)) {
211
+ return { ok: true, refreshed: [], skipped: "lane_packet_missing", error: null };
212
+ }
213
+
214
+ /** @type {Array<{ file: string, committed: boolean, commitSha: string | null }>} */
215
+ const refreshed = [];
216
+ for (const file of PACKET_REFRESH_FILES) {
217
+ const baseFilePath = path.join(baseFolder, file);
218
+ const laneFilePath = path.join(lanePacketFolder, file);
219
+ if (!fs.existsSync(baseFilePath) || !fs.existsSync(laneFilePath)) continue;
220
+ const baseContent = fs.readFileSync(baseFilePath, "utf-8");
221
+ if (fs.readFileSync(laneFilePath, "utf-8") === baseContent) continue;
222
+
223
+ fs.writeFileSync(laneFilePath, baseContent, "utf-8");
224
+ const rel = `${taskFolderRel.replace(/\\/g, "/")}/${file}`;
225
+ gitExec(worktreePath, ["add", "--", rel], { projectRoot });
226
+ const committed =
227
+ gitExec(
228
+ worktreePath,
229
+ ["commit", "-m", `sync packet from base before retry (${taskId})`, "--", rel],
230
+ { throwOnError: false, projectRoot },
231
+ ) !== null;
232
+ const commitSha = committed
233
+ ? gitExec(worktreePath, ["rev-parse", "HEAD"], { projectRoot })
234
+ : null;
235
+ refreshed.push({ file, committed, commitSha });
236
+ }
237
+ return { ok: true, refreshed, skipped: null, error: null };
238
+ } catch (err) {
239
+ const message = err instanceof Error ? err.message : String(err);
240
+ return { ok: false, refreshed: [], skipped: null, error: message };
241
+ }
242
+ }
@@ -80,6 +80,13 @@ export function attachTaskUsageFromSidecar({ taskFolder, task }) {
80
80
  return false;
81
81
  }
82
82
  if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) return false;
83
+ // SP-884 (#377): the sidecar is a process-boundary input (a child runner
84
+ // writes it), so identity is required, not optional — default to rejection
85
+ // unless the file is explicitly stamped with the current record type and
86
+ // schema. The writer has stamped both fields since the sidecar shipped
87
+ // (SP-879), so an unstamped lookalike `worker-usage.json` is foreign input,
88
+ // not a legacy format: it must not inject tokens into metric rows.
89
+ if (parsed.recordType !== "worker-usage" || parsed.schemaVersion !== 1) return false;
83
90
  let attached = false;
84
91
  for (const key of WORKER_USAGE_KEYS) {
85
92
  const value = parsed[key];