pi-spine 2.27.0 → 2.27.1
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.
- package/bin/spine-worker-runner.mjs +1 -0
- package/package.json +1 -1
- package/skills/create-spine-tasks/SKILL.md +60 -33
- package/skills/create-spine-tasks/references/authoring-evidence.md +58 -0
- package/skills/create-spine-tasks/references/contract-template.md +52 -7
- package/skills/create-spine-tasks/references/prompt-template.md +72 -8
- package/skills/spine-release-operator/SKILL.md +30 -51
- package/skills/spine-release-operator/references/issue-intake-checklist.md +3 -1
- package/skills/spine-release-operator/references/pi-async-orchestration.md +13 -9
- package/skills/spine-release-operator/references/post-integrate-regression-gate.md +8 -1
- package/skills/spine-release-operator/references/publish-recovery.md +62 -0
- package/src/batch/diagnosis-alternatives.mjs +16 -1
- package/src/batch/diagnosis-pending-lane.mjs +18 -0
- package/src/batch/diagnosis-review-infra.mjs +144 -0
- package/src/batch/diagnosis-suggested-command.mjs +9 -0
- package/src/batch/diagnosis.mjs +19 -20
- package/src/batch/engine-lanes/merge.mjs +0 -8
- package/src/batch/engine-lanes/review-poll.mjs +4 -1
- package/src/batch/engine-lanes.mjs +0 -1
- package/src/batch/gate-posture-approve.mjs +154 -15
- package/src/batch/integrate-path-delete.mjs +85 -0
- package/src/batch/integrate-worktree.mjs +20 -27
- package/src/batch/provider-quota.mjs +1 -1
- package/src/batch/reconcile-diagnosis.mjs +24 -77
- package/src/batch/review-artifacts.mjs +3 -2
- package/src/batch/review-level-effective.mjs +19 -0
- package/src/batch/review-spawn.mjs +12 -1
- package/src/batch/review-step-run.mjs +14 -2
- package/src/batch/reviewer-provider-error.mjs +153 -0
- package/src/batch/worker-prompt.mjs +5 -2
- package/src/config/cursor-rules/discover.mjs +38 -1
- package/src/config/settings-fields.mjs +5 -0
- package/src/config/spine-config-schema.mjs +38 -0
- package/src/doctor/pi-extension-hooks.mjs +322 -0
- package/src/doctor/run-doctor-checks.mjs +14 -1
- package/src/tasks/packet/validate-prompt.mjs +11 -1
- package/src/tasks/validate-contract-warn.mjs +16 -0
- package/templates/spine-config.json +1 -1
|
@@ -43,6 +43,10 @@ import {
|
|
|
43
43
|
journalReviewEvent,
|
|
44
44
|
writeStubReviewArtifact,
|
|
45
45
|
} from "./review-step.mjs";
|
|
46
|
+
import {
|
|
47
|
+
classifyReviewerSpawnFailure,
|
|
48
|
+
providerErrorFields,
|
|
49
|
+
} from "./reviewer-provider-error.mjs";
|
|
46
50
|
|
|
47
51
|
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
|
48
52
|
const PACKAGE_ROOT = path.resolve(__dirname, "../..");
|
|
@@ -290,6 +294,11 @@ export async function runStepReview({
|
|
|
290
294
|
if (honoredRetry) return honoredRetry;
|
|
291
295
|
}
|
|
292
296
|
|
|
297
|
+
// SP-820 / #334: classify the terminal attempt once, after the SP-814
|
|
298
|
+
// re-spawn loop. A set `reason` means a dedicated path (nested-spawn guard
|
|
299
|
+
// returned above; timeout keeps `review_timeout`) — those stay unchanged.
|
|
300
|
+
const providerError = spawnResult.reason ? null : classifyReviewerSpawnFailure(spawnResult);
|
|
301
|
+
|
|
293
302
|
if (spawnResult.spawnFailed) {
|
|
294
303
|
if (spawnResult.reason === NESTED_REVIEW_SPAWN_REASON) {
|
|
295
304
|
return completeNestedReviewSpawnSkipped({
|
|
@@ -335,7 +344,8 @@ export async function runStepReview({
|
|
|
335
344
|
error: spawnResult.error,
|
|
336
345
|
spawnFailed: true,
|
|
337
346
|
exitCode: spawnResult.exitCode,
|
|
338
|
-
...(spawnResult.reason ? { reason: spawnResult.reason } : {}),
|
|
347
|
+
...(spawnResult.reason && !providerError ? { reason: spawnResult.reason } : {}),
|
|
348
|
+
...providerErrorFields(providerError),
|
|
339
349
|
...diagnostics,
|
|
340
350
|
});
|
|
341
351
|
return {
|
|
@@ -348,7 +358,7 @@ export async function runStepReview({
|
|
|
348
358
|
spawnFailed: true,
|
|
349
359
|
error: spawnResult.error,
|
|
350
360
|
exitCode: spawnResult.exitCode ?? 1,
|
|
351
|
-
reason: spawnResult.reason,
|
|
361
|
+
...(providerError ? providerErrorFields(providerError) : { reason: spawnResult.reason }),
|
|
352
362
|
...diagnostics,
|
|
353
363
|
};
|
|
354
364
|
}
|
|
@@ -378,6 +388,7 @@ export async function runStepReview({
|
|
|
378
388
|
error,
|
|
379
389
|
spawnFailed: true,
|
|
380
390
|
exitCode: spawnResult.exitCode ?? 0,
|
|
391
|
+
...providerErrorFields(providerError),
|
|
381
392
|
...diagnostics,
|
|
382
393
|
});
|
|
383
394
|
return {
|
|
@@ -390,6 +401,7 @@ export async function runStepReview({
|
|
|
390
401
|
spawnFailed: true,
|
|
391
402
|
error,
|
|
392
403
|
exitCode: 1,
|
|
404
|
+
...providerErrorFields(providerError),
|
|
393
405
|
...diagnostics,
|
|
394
406
|
};
|
|
395
407
|
}
|
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Pure classifier for provider request errors in reviewer output
|
|
3
|
+
* (SP-820, partial #334).
|
|
4
|
+
*
|
|
5
|
+
* When the reviewer's model provider rejects the request — Gemini HTTP 400
|
|
6
|
+
* `INVALID_ARGUMENT` ("Function call is missing a thought_signature") or a
|
|
7
|
+
* `MALFORMED_FUNCTION_CALL` finish reason — the reviewer exits non-zero, or
|
|
8
|
+
* exits 0 without writing the review artifact. Both used to collapse into the
|
|
9
|
+
* generic `${reviewType}_review_spawn_failed` exit reason, indistinguishable
|
|
10
|
+
* from a missing `pi` binary or an empty model turn. This module recognizes
|
|
11
|
+
* the provider payload shapes and reports the provider's message so the
|
|
12
|
+
* journal records *why* the reviewer died.
|
|
13
|
+
*
|
|
14
|
+
* Quota exhaustion (HTTP 429 / z.ai `1308` / Kimi usage limits) keeps its own
|
|
15
|
+
* path: `classifyReviewerProviderError` returns null whenever
|
|
16
|
+
* `classifyProviderQuotaError` matches, so quota output is never relabelled.
|
|
17
|
+
*/
|
|
18
|
+
import {
|
|
19
|
+
classifyProviderQuotaError,
|
|
20
|
+
collectStatusPayloads,
|
|
21
|
+
} from "./provider-quota.mjs";
|
|
22
|
+
|
|
23
|
+
/** `reason` carried by the `review.failed` payload and the review result. */
|
|
24
|
+
export const REVIEW_PROVIDER_ERROR_REASON = "review_provider_error";
|
|
25
|
+
|
|
26
|
+
/** Provider messages can embed long request dumps; keep a bounded slice. */
|
|
27
|
+
const MAX_PROVIDER_MESSAGE_LENGTH = 500;
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* Markers that identify a provider request error even without a
|
|
31
|
+
* status-prefixed JSON payload (plain-text stdout/stderr from pi, or a
|
|
32
|
+
* finishReason inside a larger JSON chunk).
|
|
33
|
+
*/
|
|
34
|
+
const PROVIDER_ERROR_MARKERS = [
|
|
35
|
+
"INVALID_ARGUMENT",
|
|
36
|
+
"thought_signature",
|
|
37
|
+
"MALFORMED_FUNCTION_CALL",
|
|
38
|
+
];
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* @param {string} message
|
|
42
|
+
* @returns {string}
|
|
43
|
+
*/
|
|
44
|
+
function truncateProviderMessage(message) {
|
|
45
|
+
return message.length > MAX_PROVIDER_MESSAGE_LENGTH
|
|
46
|
+
? message.slice(0, MAX_PROVIDER_MESSAGE_LENGTH)
|
|
47
|
+
: message;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* Extracts the provider's message text from a parsed status payload:
|
|
52
|
+
* nested `error.message` (Gemini/Kimi envelope) or flat `message` (z.ai).
|
|
53
|
+
*
|
|
54
|
+
* @param {Record<string, any>} payload
|
|
55
|
+
* @returns {string|null}
|
|
56
|
+
*/
|
|
57
|
+
function payloadProviderMessage(payload) {
|
|
58
|
+
const error = payload?.error && typeof payload.error === "object" ? payload.error : null;
|
|
59
|
+
if (typeof error?.message === "string" && error.message.trim()) return error.message.trim();
|
|
60
|
+
if (typeof payload?.message === "string" && payload.message.trim()) return payload.message.trim();
|
|
61
|
+
return null;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* Finds the first output line containing a provider error marker, trimmed
|
|
66
|
+
* and capped — the provider message for marker-only matches.
|
|
67
|
+
*
|
|
68
|
+
* @param {string} output
|
|
69
|
+
* @returns {string|null}
|
|
70
|
+
*/
|
|
71
|
+
function markerLine(output) {
|
|
72
|
+
for (const line of output.split("\n")) {
|
|
73
|
+
if (PROVIDER_ERROR_MARKERS.some((marker) => line.includes(marker))) {
|
|
74
|
+
return truncateProviderMessage(line.trim());
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
return null;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* Classifies a provider request error in raw reviewer output. Pure: no I/O,
|
|
82
|
+
* no clocks, no configuration reads.
|
|
83
|
+
*
|
|
84
|
+
* Match rules (SP-820 / #334):
|
|
85
|
+
* - any status-prefixed JSON payload with an HTTP 4xx status other than
|
|
86
|
+
* 408 (request timeout) and 429 (rate limit — quota's own path), or
|
|
87
|
+
* - any of the markers `INVALID_ARGUMENT`, `thought_signature`,
|
|
88
|
+
* `MALFORMED_FUNCTION_CALL` anywhere in the output.
|
|
89
|
+
*
|
|
90
|
+
* Returns null when `classifyProviderQuotaError(output)` matches (quota
|
|
91
|
+
* keeps its own handling), and for empty or non-string input. When several
|
|
92
|
+
* payloads qualify, the last one is classified — it is the terminal error
|
|
93
|
+
* the reviewer actually died on.
|
|
94
|
+
*
|
|
95
|
+
* @param {string|null|undefined} output Reviewer error text / redacted output tails.
|
|
96
|
+
* @returns {{ httpStatus: number|null, providerMessage: string }|null}
|
|
97
|
+
*/
|
|
98
|
+
export function classifyReviewerProviderError(output) {
|
|
99
|
+
if (typeof output !== "string" || !output) return null;
|
|
100
|
+
if (classifyProviderQuotaError(output)) return null;
|
|
101
|
+
|
|
102
|
+
const payloads = collectStatusPayloads(output);
|
|
103
|
+
for (let i = payloads.length - 1; i >= 0; i--) {
|
|
104
|
+
const { httpStatus, payload } = payloads[i];
|
|
105
|
+
if (httpStatus >= 400 && httpStatus < 500 && httpStatus !== 408 && httpStatus !== 429) {
|
|
106
|
+
return {
|
|
107
|
+
httpStatus,
|
|
108
|
+
providerMessage: truncateProviderMessage(
|
|
109
|
+
// The message must describe THIS payload — an unrelated earlier
|
|
110
|
+
// marker line must not be attributed to the terminal 4xx. The
|
|
111
|
+
// raw payload text is the faithful fallback (stet 3295372).
|
|
112
|
+
payloadProviderMessage(payload) ?? JSON.stringify(payload),
|
|
113
|
+
),
|
|
114
|
+
};
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
const marker = markerLine(output);
|
|
119
|
+
if (marker) return { httpStatus: null, providerMessage: marker };
|
|
120
|
+
return null;
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/**
|
|
124
|
+
* SP-820 fields added to the `review.failed` payload and the returned review
|
|
125
|
+
* result when the terminal attempt matched the classifier. Empty for generic
|
|
126
|
+
* failures, quota payloads (their own path), and timeouts.
|
|
127
|
+
*
|
|
128
|
+
* @param {{ httpStatus: number|null, providerMessage: string }|null} providerError
|
|
129
|
+
* @returns {Record<string, any>}
|
|
130
|
+
*/
|
|
131
|
+
export function providerErrorFields(providerError) {
|
|
132
|
+
if (!providerError) return {};
|
|
133
|
+
return {
|
|
134
|
+
reason: REVIEW_PROVIDER_ERROR_REASON,
|
|
135
|
+
providerMessage: providerError.providerMessage,
|
|
136
|
+
...(typeof providerError.httpStatus === "number" ? { httpStatus: providerError.httpStatus } : {}),
|
|
137
|
+
};
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/**
|
|
141
|
+
* Runs the classifier over a reviewer spawn attempt's error text and redacted
|
|
142
|
+
* output tails, joined in failure-order (error, stderr, stdout). Quota
|
|
143
|
+
* payloads anywhere in the combined text keep the generic path.
|
|
144
|
+
*
|
|
145
|
+
* @param {{ error?: string, stderrTail?: string, stdoutTail?: string }|null|undefined} spawnResult
|
|
146
|
+
* @returns {{ httpStatus: number|null, providerMessage: string }|null}
|
|
147
|
+
*/
|
|
148
|
+
export function classifyReviewerSpawnFailure(spawnResult) {
|
|
149
|
+
const combined = [spawnResult?.error, spawnResult?.stderrTail, spawnResult?.stdoutTail]
|
|
150
|
+
.filter((part) => typeof part === "string" && part)
|
|
151
|
+
.join("\n");
|
|
152
|
+
return classifyReviewerProviderError(combined);
|
|
153
|
+
}
|
|
@@ -48,6 +48,7 @@ export async function buildWorkerTailPrompt({
|
|
|
48
48
|
taskIdHint = taskIdFromFolder(taskFolder),
|
|
49
49
|
reviewLevel = 0,
|
|
50
50
|
includePromptInclude = false,
|
|
51
|
+
includeAgentInclude = true,
|
|
51
52
|
config = {},
|
|
52
53
|
projectRoot = worktreePath || process.cwd(),
|
|
53
54
|
taskFileScope = [],
|
|
@@ -58,7 +59,9 @@ export async function buildWorkerTailPrompt({
|
|
|
58
59
|
: null;
|
|
59
60
|
const promptPath = path.join(taskFolder, "PROMPT.md");
|
|
60
61
|
const agentAppend =
|
|
61
|
-
workerAgentPath && fs.existsSync(workerAgentPath)
|
|
62
|
+
includeAgentInclude && workerAgentPath && fs.existsSync(workerAgentPath)
|
|
63
|
+
? `\n\n@${workerAgentPath}`
|
|
64
|
+
: "";
|
|
62
65
|
const promptInclude =
|
|
63
66
|
includePromptInclude && fs.existsSync(promptPath) ? `\n\n@${promptPath}` : "";
|
|
64
67
|
|
|
@@ -70,7 +73,7 @@ export async function buildWorkerTailPrompt({
|
|
|
70
73
|
});
|
|
71
74
|
|
|
72
75
|
return (
|
|
73
|
-
`Complete this task in the worktree (${worktreePath || "."}). Follow PROMPT.md, keep STATUS.md current, run
|
|
76
|
+
`Complete this task in the worktree (${worktreePath || "."}). Follow PROMPT.md, keep STATUS.md current, and run the Contract testCommand from PROMPT.md; the full suite runs at post-integrate release:check. ` +
|
|
74
77
|
WORKER_TOOLS_HINT +
|
|
75
78
|
buildReviewLevelHint(reviewLevel) +
|
|
76
79
|
buildCommitBoundaryHint(taskIdHint) +
|
|
@@ -181,6 +181,31 @@ export function writeRulesManifestAtomic(projectRoot, manifest) {
|
|
|
181
181
|
return manifestPath;
|
|
182
182
|
}
|
|
183
183
|
|
|
184
|
+
/**
|
|
185
|
+
* Read an existing rules manifest for fingerprint comparison. Returns null when
|
|
186
|
+
* the file is missing, unreadable, or not a parseable manifest — the caller then
|
|
187
|
+
* falls through to a normal write.
|
|
188
|
+
*
|
|
189
|
+
* @param {string} manifestPath
|
|
190
|
+
* @returns {CursorRulesManifest | null}
|
|
191
|
+
*/
|
|
192
|
+
function loadExistingManifestForFingerprint(manifestPath) {
|
|
193
|
+
try {
|
|
194
|
+
const parsed = parseRulesManifestJson(fs.readFileSync(manifestPath, "utf-8"));
|
|
195
|
+
if (
|
|
196
|
+
!parsed.ok ||
|
|
197
|
+
!Array.isArray(parsed.manifest?.rules) ||
|
|
198
|
+
!Array.isArray(parsed.manifest?.excluded) ||
|
|
199
|
+
typeof parsed.manifest.generatedAt !== "string"
|
|
200
|
+
) {
|
|
201
|
+
return null;
|
|
202
|
+
}
|
|
203
|
+
return parsed.manifest;
|
|
204
|
+
} catch {
|
|
205
|
+
return null;
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
|
|
184
209
|
/**
|
|
185
210
|
* @param {object} params
|
|
186
211
|
* @param {string} params.projectRoot
|
|
@@ -256,7 +281,19 @@ export function discoverCursorRules({ projectRoot, profile, writeManifest = true
|
|
|
256
281
|
/** @type {DiscoverCursorRulesResult} */
|
|
257
282
|
const result = { ok: true, manifest };
|
|
258
283
|
if (writeManifest) {
|
|
259
|
-
|
|
284
|
+
const manifestPath = path.join(projectRoot, RULES_MANIFEST_REL_PATH);
|
|
285
|
+
const existing = loadExistingManifestForFingerprint(manifestPath);
|
|
286
|
+
if (
|
|
287
|
+
existing &&
|
|
288
|
+
fingerprintRulesManifest(existing) === fingerprintRulesManifest(manifest)
|
|
289
|
+
) {
|
|
290
|
+
// Unchanged rules set: skip the write and keep the existing `generatedAt`
|
|
291
|
+
// so `spine rules sync` is idempotent (#315).
|
|
292
|
+
result.manifest = { ...manifest, generatedAt: existing.generatedAt };
|
|
293
|
+
result.manifestPath = manifestPath;
|
|
294
|
+
} else {
|
|
295
|
+
result.manifestPath = writeRulesManifestAtomic(projectRoot, manifest);
|
|
296
|
+
}
|
|
260
297
|
}
|
|
261
298
|
return result;
|
|
262
299
|
}
|
|
@@ -86,6 +86,11 @@ export const SETTINGS_FIELDS = Object.freeze([
|
|
|
86
86
|
type: "enum",
|
|
87
87
|
enum: ["off", "low", "medium", "high", "inherit"],
|
|
88
88
|
},
|
|
89
|
+
{
|
|
90
|
+
path: "agents.reviewer.loadUserExtensions",
|
|
91
|
+
label: "Reviewer loads user pi extensions",
|
|
92
|
+
type: "boolean",
|
|
93
|
+
},
|
|
89
94
|
{
|
|
90
95
|
path: "agents.reviewer.plan.model",
|
|
91
96
|
label: "Plan reviewer model",
|
|
@@ -235,6 +235,31 @@ function validateAgentSectionModelTypes(agents, label) {
|
|
|
235
235
|
return null;
|
|
236
236
|
}
|
|
237
237
|
|
|
238
|
+
/**
|
|
239
|
+
* SP-819 / #334: type-check `reviewer.loadUserExtensions` (boolean, default false) wherever
|
|
240
|
+
* a reviewer section appears: the base `agents.reviewer` and any
|
|
241
|
+
* `agents.profiles.<name>.reviewer`. Absent values are valid (defaults to false).
|
|
242
|
+
*
|
|
243
|
+
* @param {any} reviewer A reviewer-shaped section (may be undefined or a non-object).
|
|
244
|
+
* @param {string} label Dotted path used in the error message.
|
|
245
|
+
* @param {string} suggestedCommand Repair hint shown to the operator.
|
|
246
|
+
* @returns {null | { code: string; message: string; suggestedCommand: string }}
|
|
247
|
+
*/
|
|
248
|
+
function validateReviewerLoadUserExtensions(reviewer, label, suggestedCommand) {
|
|
249
|
+
if (
|
|
250
|
+
isPlainObject(reviewer) &&
|
|
251
|
+
reviewer.loadUserExtensions != null &&
|
|
252
|
+
typeof reviewer.loadUserExtensions !== "boolean"
|
|
253
|
+
) {
|
|
254
|
+
return {
|
|
255
|
+
code: "CONFIG_AGENT_PROFILE_INVALID",
|
|
256
|
+
message: `${label}.loadUserExtensions must be a boolean when set`,
|
|
257
|
+
suggestedCommand,
|
|
258
|
+
};
|
|
259
|
+
}
|
|
260
|
+
return null;
|
|
261
|
+
}
|
|
262
|
+
|
|
238
263
|
/**
|
|
239
264
|
* Validate `agents.profiles`, `agents.activeProfile`, and `agents.escalatePolicy`.
|
|
240
265
|
*
|
|
@@ -251,6 +276,13 @@ export function validateAgentProfilesConfig(config) {
|
|
|
251
276
|
return null;
|
|
252
277
|
}
|
|
253
278
|
|
|
279
|
+
const reviewerLoadError = validateReviewerLoadUserExtensions(
|
|
280
|
+
agents.reviewer,
|
|
281
|
+
"agents.reviewer",
|
|
282
|
+
"spine settings set agents.reviewer.loadUserExtensions false",
|
|
283
|
+
);
|
|
284
|
+
if (reviewerLoadError) return reviewerLoadError;
|
|
285
|
+
|
|
254
286
|
const profiles = agents.profiles;
|
|
255
287
|
if (profiles != null) {
|
|
256
288
|
if (!isPlainObject(profiles)) {
|
|
@@ -270,6 +302,12 @@ export function validateAgentProfilesConfig(config) {
|
|
|
270
302
|
}
|
|
271
303
|
const shapeError = validateAgentSectionModelTypes(profile, `agents.profiles.${name}`);
|
|
272
304
|
if (shapeError) return shapeError;
|
|
305
|
+
const profileReviewerError = validateReviewerLoadUserExtensions(
|
|
306
|
+
profile.reviewer,
|
|
307
|
+
`agents.profiles.${name}.reviewer`,
|
|
308
|
+
"spine init --force",
|
|
309
|
+
);
|
|
310
|
+
if (profileReviewerError) return profileReviewerError;
|
|
273
311
|
}
|
|
274
312
|
}
|
|
275
313
|
|
|
@@ -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
|
+
}
|