pi-spine 2.27.0 → 2.28.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.
Files changed (71) hide show
  1. package/bin/spine-batch.mjs +46 -4
  2. package/bin/spine-tasks.mjs +1 -0
  3. package/bin/spine-worker-runner.mjs +17 -3
  4. package/package.json +1 -1
  5. package/skills/create-spine-tasks/SKILL.md +60 -33
  6. package/skills/create-spine-tasks/references/authoring-evidence.md +58 -0
  7. package/skills/create-spine-tasks/references/contract-template.md +52 -7
  8. package/skills/create-spine-tasks/references/prompt-template.md +77 -8
  9. package/skills/spine-release-operator/SKILL.md +43 -52
  10. package/skills/spine-release-operator/references/issue-intake-checklist.md +3 -1
  11. package/skills/spine-release-operator/references/pi-async-orchestration.md +13 -9
  12. package/skills/spine-release-operator/references/post-integrate-regression-gate.md +8 -1
  13. package/skills/spine-release-operator/references/publish-recovery.md +62 -0
  14. package/src/batch/contract-task-start.mjs +23 -1
  15. package/src/batch/diagnosis-alternatives.mjs +16 -1
  16. package/src/batch/diagnosis-handoff-packet.mjs +18 -0
  17. package/src/batch/diagnosis-pending-lane.mjs +18 -0
  18. package/src/batch/diagnosis-review-infra.mjs +144 -0
  19. package/src/batch/diagnosis-suggested-command.mjs +9 -0
  20. package/src/batch/diagnosis.mjs +19 -20
  21. package/src/batch/engine-lanes/merge.mjs +0 -8
  22. package/src/batch/engine-lanes/quota-fallback-run.mjs +11 -0
  23. package/src/batch/engine-lanes/quota-fallback-state.mjs +155 -8
  24. package/src/batch/engine-lanes/review-code.mjs +20 -0
  25. package/src/batch/engine-lanes/review-final.mjs +10 -2
  26. package/src/batch/engine-lanes/review-poll.mjs +37 -1
  27. package/src/batch/engine-lanes/task-agent-profile.mjs +324 -0
  28. package/src/batch/engine-lanes.mjs +18 -18
  29. package/src/batch/gate-posture-approve.mjs +154 -15
  30. package/src/batch/integrate-path-delete.mjs +85 -0
  31. package/src/batch/integrate-worktree.mjs +20 -27
  32. package/src/batch/journal.mjs +5 -3
  33. package/src/batch/metrics-rollup.mjs +98 -4
  34. package/src/batch/metrics.mjs +134 -9
  35. package/src/batch/provider-quota.mjs +156 -7
  36. package/src/batch/quota-fallback.mjs +87 -6
  37. package/src/batch/reconcile-diagnosis.mjs +24 -77
  38. package/src/batch/resume-lane-reviews.mjs +11 -10
  39. package/src/batch/retry-profile.mjs +77 -0
  40. package/src/batch/retry.mjs +32 -1
  41. package/src/batch/review-artifacts.mjs +3 -2
  42. package/src/batch/review-level-effective.mjs +19 -0
  43. package/src/batch/review-spawn.mjs +12 -1
  44. package/src/batch/review-step-run.mjs +18 -2
  45. package/src/batch/review-step.mjs +1 -0
  46. package/src/batch/reviewer-provider-error.mjs +153 -0
  47. package/src/batch/worker-heartbeat.mjs +10 -2
  48. package/src/batch/worker-host.mjs +1 -1
  49. package/src/batch/worker-prompt.mjs +9 -7
  50. package/src/cli/deps.mjs +3 -2
  51. package/src/config/agent-model-resolve.mjs +144 -8
  52. package/src/config/cursor-rules/discover.mjs +38 -1
  53. package/src/config/model-family.mjs +60 -0
  54. package/src/config/preflight/discovery.mjs +1 -0
  55. package/src/config/settings-fields.mjs +11 -0
  56. package/src/config/spine-config-schema.mjs +87 -0
  57. package/src/doctor/agent-model-inherit.mjs +78 -1
  58. package/src/doctor/pi-extension-hooks.mjs +322 -0
  59. package/src/doctor/run-doctor-checks.mjs +18 -2
  60. package/src/metrics/quota-cli.mjs +16 -0
  61. package/src/metrics/quota-probes.mjs +228 -31
  62. package/src/metrics/quota-snapshot.mjs +21 -2
  63. package/src/planner/graph.mjs +7 -5
  64. package/src/planner/pending.mjs +2 -2
  65. package/src/planner/scope.mjs +3 -3
  66. package/src/tasks/packet/parse-prompt.mjs +47 -0
  67. package/src/tasks/packet/validate-prompt.mjs +167 -2
  68. package/src/tasks/validate-contract-warn.mjs +16 -0
  69. package/templates/agents/reviewer.md +3 -1
  70. package/templates/agents/worker.md +15 -19
  71. package/templates/spine-config.json +1 -1
@@ -0,0 +1,322 @@
1
+ /**
2
+ * Detect context-rewriting pi extension hooks (SP-822).
3
+ *
4
+ * Batch workers can pass `pi -ne` to skip user extension discovery, and per
5
+ * SP-819 reviewers do the same unless spine config opts in with
6
+ * `agents.reviewer.loadUserExtensions: true`. When that opt-in is set, a pi
7
+ * package that registers a context-rewriting hook (`context`,
8
+ * `context_with_system`, `before_provider_request`) can silently rewrite what
9
+ * reviewers see. This scanner reports which installed packages register such
10
+ * hooks so doctor can surface an advisory warning. It never hard-fails:
11
+ * extensions are a legitimate feature, so the check is informational with an
12
+ * opt-out config key.
13
+ *
14
+ * Scan scope stays bounded: only packages declared in pi `settings.json`
15
+ * `packages` arrays are inspected (that is the set pi actually loads), and
16
+ * within each package only the entry files named in `package.json` →
17
+ * `pi.extensions` — or, when the manifest declares none, the conventional
18
+ * `extensions/` directory plus root `index.{ts,js,mjs}` files that pi
19
+ * discovers for manifest-less packages.
20
+ */
21
+
22
+ import fs from "node:fs";
23
+ import path from "node:path";
24
+
25
+ import {
26
+ readPiPackageSources,
27
+ resolvePiAgentDir,
28
+ resolvePiPackageSourcePath,
29
+ } from "./pi-extension-conflict.mjs";
30
+
31
+ /** Hooks that can rewrite the context a reviewer model sees. */
32
+ export const PI_CONTEXT_HOOK_NAMES = Object.freeze([
33
+ "context",
34
+ "context_with_system",
35
+ "before_provider_request",
36
+ ]);
37
+
38
+ /** Max installed packages scanned per run (bounded scan). */
39
+ export const MAX_PI_PACKAGES_SCANNED = 50;
40
+
41
+ /** Max extension entry files scanned per package (bounded scan). */
42
+ export const MAX_PI_EXTENSION_ENTRIES_PER_PACKAGE = 20;
43
+
44
+ /** Max bytes read from a single extension entry file (bounded scan). */
45
+ export const MAX_PI_EXTENSION_SOURCE_BYTES = 512 * 1024;
46
+
47
+ /** File extensions pi treats as extension entry files. */
48
+ const EXTENSION_ENTRY_FILE_PATTERN = /\.(?:ts|js|mjs)$/;
49
+
50
+ /** Conventional root entry files pi discovers when no manifest list exists. */
51
+ const FALLBACK_ROOT_ENTRIES = Object.freeze(["index.ts", "index.js", "index.mjs"]);
52
+
53
+ /**
54
+ * Patterns that indicate a context hook registration in an extension source
55
+ * file. All three hooks register through `pi.on("<event>", ...)`, so the
56
+ * patterns match the `.on("<event>"` / `.on('<event>'` call shape (see
57
+ * pi-coding-agent docs/extensions.md, "Events and concurrency"). Matching the
58
+ * call shape avoids false positives on unrelated identifiers that merely
59
+ * mention the event names.
60
+ *
61
+ * @type {ReadonlyArray<{ hook: string, pattern: RegExp }>}
62
+ */
63
+ const HOOK_PATTERNS = Object.freeze([
64
+ { hook: "context", pattern: /\.on\(\s*["']context["']/ },
65
+ { hook: "context_with_system", pattern: /\.on\(\s*["']context_with_system["']/ },
66
+ { hook: "before_provider_request", pattern: /\.on\(\s*["']before_provider_request["']/ },
67
+ ]);
68
+
69
+ /**
70
+ * Detect which context-rewriting hooks an extension source registers.
71
+ *
72
+ * @param {string} sourceText Extension entry file contents.
73
+ * @returns {string[]} Hook names in canonical PI_CONTEXT_HOOK_NAMES order.
74
+ */
75
+ export function scanPiExtensionSourceForContextHooks(sourceText) {
76
+ const text = String(sourceText ?? "");
77
+ const found = new Set();
78
+ for (const { hook, pattern } of HOOK_PATTERNS) {
79
+ if (pattern.test(text)) found.add(hook);
80
+ }
81
+ return PI_CONTEXT_HOOK_NAMES.filter((hook) => found.has(hook));
82
+ }
83
+
84
+ /**
85
+ * List the conventional entry files pi discovers when the manifest declares
86
+ * no `pi.extensions`: files in `extensions/` plus root `index.{ts,js,mjs}`.
87
+ *
88
+ * @param {string} packageDir Absolute path to the package root.
89
+ * @returns {string[]} Entry paths relative to the package root, sorted and
90
+ * capped at MAX_PI_EXTENSION_ENTRIES_PER_PACKAGE.
91
+ */
92
+ function discoverFallbackExtensionEntries(packageDir) {
93
+ /** @type {string[]} */
94
+ const entries = [];
95
+ const extensionsDir = path.join(packageDir, "extensions");
96
+ try {
97
+ for (const fileName of fs.readdirSync(extensionsDir).sort()) {
98
+ if (!EXTENSION_ENTRY_FILE_PATTERN.test(fileName)) continue;
99
+ if (!fs.statSync(path.join(extensionsDir, fileName)).isFile()) continue;
100
+ entries.push(path.join("extensions", fileName));
101
+ }
102
+ } catch {
103
+ // No readable extensions/ directory — fall through to root entries.
104
+ }
105
+ for (const rootEntry of FALLBACK_ROOT_ENTRIES) {
106
+ try {
107
+ if (fs.statSync(path.join(packageDir, rootEntry)).isFile()) {
108
+ entries.push(rootEntry);
109
+ }
110
+ } catch {
111
+ // Missing root entry — skip.
112
+ }
113
+ }
114
+ return entries.slice(0, MAX_PI_EXTENSION_ENTRIES_PER_PACKAGE);
115
+ }
116
+
117
+ /**
118
+ * Resolve the extension entry files for an installed package: the
119
+ * `package.json` → `pi.extensions` list when present, else the conventional
120
+ * `extensions/` directory and root `index.{ts,js,mjs}` files pi discovers.
121
+ *
122
+ * @param {string} packageDir Absolute path to the package root.
123
+ * @returns {{ name: string, entries: string[] } | null} Null when the package
124
+ * has no extension entries to scan.
125
+ */
126
+ function readPackageExtensionEntries(packageDir) {
127
+ const manifestPath = path.join(packageDir, "package.json");
128
+ let manifest;
129
+ try {
130
+ manifest = JSON.parse(fs.readFileSync(manifestPath, "utf-8"));
131
+ } catch {
132
+ manifest = null;
133
+ }
134
+ const name = typeof manifest?.name === "string" && manifest.name.trim()
135
+ ? manifest.name.trim()
136
+ : path.basename(packageDir);
137
+ const rawEntries = manifest?.pi?.extensions;
138
+ if (Array.isArray(rawEntries) && rawEntries.length > 0) {
139
+ const entries = rawEntries
140
+ .map((entry) => String(entry ?? "").trim())
141
+ .filter(Boolean)
142
+ .slice(0, MAX_PI_EXTENSION_ENTRIES_PER_PACKAGE);
143
+ return entries.length > 0 ? { name, entries } : null;
144
+ }
145
+ const entries = discoverFallbackExtensionEntries(packageDir);
146
+ return entries.length > 0 ? { name, entries } : null;
147
+ }
148
+
149
+ /**
150
+ * Read at most MAX_PI_EXTENSION_SOURCE_BYTES bytes from a file without ever
151
+ * allocating more than the cap, regardless of the file size on disk.
152
+ *
153
+ * @param {string} filePath
154
+ * @returns {string | null} Null when the file cannot be opened or read.
155
+ */
156
+ function readBoundedText(filePath) {
157
+ let fd;
158
+ try {
159
+ fd = fs.openSync(filePath, "r");
160
+ const stat = fs.fstatSync(fd);
161
+ const length = Math.min(stat.size, MAX_PI_EXTENSION_SOURCE_BYTES);
162
+ const buffer = Buffer.alloc(length);
163
+ const bytesRead = fs.readSync(fd, buffer, 0, length, 0);
164
+ return buffer.toString("utf-8", 0, bytesRead);
165
+ } catch {
166
+ return null;
167
+ } finally {
168
+ if (fd !== undefined) {
169
+ try {
170
+ fs.closeSync(fd);
171
+ } catch {
172
+ // Close errors must not mask read results.
173
+ }
174
+ }
175
+ }
176
+ }
177
+
178
+ /**
179
+ * Scan settings-declared pi packages for context-rewriting extension hooks.
180
+ * Missing or unreadable paths are skipped and noted in `skipped`; nothing is
181
+ * ever thrown.
182
+ *
183
+ * @param {object} [options]
184
+ * @param {string} [options.projectRoot]
185
+ * @param {string} [options.agentDir]
186
+ * @returns {{ packages: Array<{ source: string, hooks: string[] }>, packagesScanned: number, skipped: Array<{ source: string, reason: string }> }}
187
+ */
188
+ export function findContextRewritingExtensions({
189
+ projectRoot = process.cwd(),
190
+ agentDir = resolvePiAgentDir(),
191
+ } = {}) {
192
+ /** @type {Array<{ source: string, settingsDir: string }>} */
193
+ const declared = [];
194
+
195
+ const userSettings = path.join(agentDir, "settings.json");
196
+ for (const source of readPiPackageSources(userSettings)) {
197
+ declared.push({ source, settingsDir: agentDir });
198
+ }
199
+
200
+ const projectSettings = path.join(projectRoot, ".pi", "settings.json");
201
+ for (const source of readPiPackageSources(projectSettings)) {
202
+ declared.push({ source, settingsDir: path.dirname(projectSettings) });
203
+ }
204
+
205
+ /** @type {Set<string>} */
206
+ const seenPackages = new Set();
207
+ /** @type {Array<{ source: string, hooks: string[] }>} */
208
+ const packages = [];
209
+ /** @type {Array<{ source: string, reason: string }>} */
210
+ const skipped = [];
211
+ let packagesScanned = 0;
212
+
213
+ for (const { source, settingsDir } of declared) {
214
+ const packageDir = resolvePiPackageSourcePath(source, settingsDir, agentDir);
215
+ if (!packageDir) {
216
+ skipped.push({ source: String(source), reason: "unresolvable package source" });
217
+ continue;
218
+ }
219
+ const resolvedDir = path.resolve(packageDir);
220
+ if (seenPackages.has(resolvedDir)) continue;
221
+ seenPackages.add(resolvedDir);
222
+ if (packagesScanned >= MAX_PI_PACKAGES_SCANNED) {
223
+ skipped.push({ source: String(source), reason: "package scan cap reached" });
224
+ continue;
225
+ }
226
+ if (!fs.existsSync(resolvedDir)) {
227
+ skipped.push({ source: String(source), reason: "package path not found" });
228
+ continue;
229
+ }
230
+ packagesScanned++;
231
+
232
+ const parsed = readPackageExtensionEntries(resolvedDir);
233
+ if (!parsed) continue;
234
+
235
+ /** @type {Set<string>} */
236
+ const packageHooks = new Set();
237
+ for (const entry of parsed.entries) {
238
+ const entryPath = path.resolve(resolvedDir, entry);
239
+ if (entryPath !== resolvedDir && !entryPath.startsWith(resolvedDir + path.sep)) {
240
+ // Manifest entry escapes the package directory — never read outside it.
241
+ skipped.push({
242
+ source: String(source),
243
+ reason: `entry escapes package directory: ${entry}`,
244
+ });
245
+ continue;
246
+ }
247
+ const text = readBoundedText(entryPath);
248
+ if (text === null) {
249
+ skipped.push({ source: String(source), reason: `unreadable entry: ${entry}` });
250
+ continue;
251
+ }
252
+ for (const hook of scanPiExtensionSourceForContextHooks(text)) {
253
+ packageHooks.add(hook);
254
+ }
255
+ }
256
+ if (packageHooks.size > 0) {
257
+ packages.push({
258
+ source: String(source),
259
+ hooks: PI_CONTEXT_HOOK_NAMES.filter((hook) => packageHooks.has(hook)),
260
+ });
261
+ }
262
+ }
263
+
264
+ return { packages, packagesScanned, skipped };
265
+ }
266
+
267
+ /**
268
+ * @param {Array<{ source: string, hooks: string[] }>} packages
269
+ * @returns {string}
270
+ */
271
+ function summarizeFindings(packages) {
272
+ return packages
273
+ .map((pkg) => `${pkg.source} (${pkg.hooks.join(", ")})`)
274
+ .join("; ");
275
+ }
276
+
277
+ /**
278
+ * Advisory doctor check: warn when installed pi packages register
279
+ * context-rewriting hooks while reviewers load user extensions (SP-822).
280
+ *
281
+ * Never hard-fails (`ok` stays true); a `warning: true` check surfaces in
282
+ * doctor output without blocking batch start.
283
+ *
284
+ * @param {object} [options]
285
+ * @param {string} [options.projectRoot]
286
+ * @param {string} [options.agentDir]
287
+ * @param {Record<string, any> | null} [options.config] Loaded spine config.
288
+ * @returns {{ label: string, ok: true, warning?: boolean, detail: string, suggestedCommand?: string }}
289
+ */
290
+ export function buildContextHookExtensionDoctorCheck({
291
+ projectRoot = process.cwd(),
292
+ agentDir = resolvePiAgentDir(),
293
+ config,
294
+ } = {}) {
295
+ const label = "pi extensions rewriting reviewer context";
296
+ const { packages, packagesScanned } = findContextRewritingExtensions({ projectRoot, agentDir });
297
+
298
+ if (packages.length === 0) {
299
+ return {
300
+ label,
301
+ ok: true,
302
+ detail: `no context-rewriting hooks found in ${packagesScanned} installed pi package(s)`,
303
+ };
304
+ }
305
+
306
+ const summary = summarizeFindings(packages);
307
+ if (config?.agents?.reviewer?.loadUserExtensions === true) {
308
+ return {
309
+ label,
310
+ ok: true,
311
+ warning: true,
312
+ detail: `${summary} register context-rewriting hook(s) and reviewers load user extensions (agents.reviewer.loadUserExtensions=true); these hooks can rewrite reviewer context`,
313
+ suggestedCommand: "spine settings set agents.reviewer.loadUserExtensions false",
314
+ };
315
+ }
316
+
317
+ return {
318
+ label,
319
+ ok: true,
320
+ detail: `${packages.length} package(s) register context hooks (${summary}); reviewers isolated (pi -ne)`,
321
+ };
322
+ }
@@ -31,6 +31,7 @@ import { buildAgentModelInheritDoctorCheck, buildReviewerPerTypePinsDoctorCheck
31
31
  import { buildInheritProviderAuthDoctorCheck } from "./agents-model-inherit.mjs";
32
32
  import { buildAgentModelIdsDoctorCheck } from "./agent-models.mjs";
33
33
  import { buildPiExtensionConflictDoctorCheck } from "./pi-extension-conflict.mjs";
34
+ import { buildContextHookExtensionDoctorCheck } from "./pi-extension-hooks.mjs";
34
35
  import { buildSupervisorConfigDoctorCheck } from "./supervisor.mjs";
35
36
  import { buildAttachedOrphanRiskDoctorCheck } from "./attached-orphan-risk.mjs";
36
37
  import { buildQuotaRiskDoctorCheck } from "./quota-risk.mjs";
@@ -343,7 +344,20 @@ export function runDoctorChecks(projectRoot = process.cwd()) {
343
344
  projectRoot,
344
345
  }),
345
346
  );
347
+ // Load config once here so the advisory SP-822 check (pushed right after
348
+ // the extension-conflict check) and the config-driven checks below share it.
349
+ const configResult = loadSpineConfig(projectRoot);
346
350
  checks.push(buildPiExtensionConflictDoctorCheck({ projectRoot }));
351
+ // Advisory only (SP-822): warn when installed pi packages register
352
+ // context-rewriting hooks (context, context_with_system,
353
+ // before_provider_request) while reviewers load user extensions
354
+ // (agents.reviewer.loadUserExtensions). Never hard-fails.
355
+ checks.push(
356
+ buildContextHookExtensionDoctorCheck({
357
+ projectRoot,
358
+ config: configResult.config,
359
+ }),
360
+ );
347
361
  checks.push(buildAttachedOrphanRiskDoctorCheck());
348
362
 
349
363
  const piVersionText = getVersion("pi");
@@ -404,7 +418,6 @@ export function runDoctorChecks(projectRoot = process.cwd()) {
404
418
  warning: modelCheck.warning,
405
419
  });
406
420
 
407
- const configResult = loadSpineConfig(projectRoot);
408
421
  if (configResult.error) {
409
422
  record(".spine/spine-config.json valid", false, {
410
423
  detail: configResult.error.message,
@@ -447,7 +460,10 @@ export function runDoctorChecks(projectRoot = process.cwd()) {
447
460
  );
448
461
  checks.push(buildStallConfigDoctorCheck({ config: configResult.config }));
449
462
  checks.push(buildPiWorkerTimeoutDoctorCheck({ config: configResult.config }));
450
- checks.push(buildReviewerPerTypePinsDoctorCheck({ config: configResult.config }));
463
+ const reviewerPinsCheck = buildReviewerPerTypePinsDoctorCheck({ config: configResult.config });
464
+ checks.push(reviewerPinsCheck);
465
+ // SP-832 / #355: same-family worker/reviewer pairing blocks doctor and (via doctor) preflight.
466
+ if (!reviewerPinsCheck.ok) issueCount++;
451
467
  checks.push(buildAgentModelInheritDoctorCheck({
452
468
  config: configResult.config,
453
469
  projectRoot,
@@ -32,6 +32,18 @@ function formatReportFilename(now) {
32
32
  return `quota-snapshot-${iso}.json`;
33
33
  }
34
34
 
35
+ /**
36
+ * Format one quota window as `5h 63% (resets 2026-10-15T06:28:41Z)`.
37
+ *
38
+ * @param {import("./quota-probes.mjs").QuotaWindow} win
39
+ * @returns {string}
40
+ */
41
+ function formatWindow(win) {
42
+ let text = `${win.window} ${Math.round(win.percentUsed)}%`;
43
+ if (win.resetAt) text += ` (resets ${win.resetAt.replace(/\.\d+Z$/, "Z")})`;
44
+ return text;
45
+ }
46
+
35
47
  /**
36
48
  * Format a short human-readable summary of the snapshot.
37
49
  *
@@ -55,11 +67,15 @@ function formatHumanSummary(snapshot, reportPath) {
55
67
  for (const pool of pools) {
56
68
  const usage = pool.usage;
57
69
  const parts = [`${pool.poolId}: ${usage.taskCount} tasks`];
70
+ if (usage.reviewCount) parts.push(`${usage.reviewCount} reviews`);
58
71
  if (usage.durationMs > 0) parts.push(`${usage.durationMs}ms`);
59
72
  if (usage.tokensIn) parts.push(`${usage.tokensIn} in-tokens`);
60
73
  if (usage.tokensOut) parts.push(`${usage.tokensOut} out-tokens`);
61
74
  if (usage.estimatedUsd) parts.push(`$${usage.estimatedUsd.toFixed(4)} est`);
62
75
  lines.push(` ${parts.join(", ")}`);
76
+ for (const win of pool.windows ?? []) {
77
+ lines.push(` ${formatWindow(win)}`);
78
+ }
63
79
  }
64
80
 
65
81
  if (reportPath) {