ceulen 0.11.0 → 0.12.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.
- package/CHANGELOG.md +51 -1
- package/extensions/index.ts +5 -1
- package/extensions/lib/env.test.ts +147 -0
- package/extensions/lib/env.ts +180 -0
- package/extensions/lib/order.test.ts +74 -0
- package/extensions/lib/registry.test.ts +8 -5
- package/extensions/lib/registry.ts +8 -3
- package/extensions/modules/a2a/configPanel.ts +42 -1
- package/extensions/modules/a2a/lib/config.ts +8 -3
- package/extensions/modules/a2a/test/configPanel.test.ts +7 -4
- package/extensions/modules/advisor/index.ts +6 -3
- package/extensions/modules/advisor/test/module.test.ts +31 -0
- package/extensions/modules/classifier/index.ts +55 -1
- package/extensions/modules/classifier/test/classifier.test.ts +62 -0
- package/extensions/modules/composer/test/module.test.ts +1 -1
- package/extensions/modules/repair/index.ts +26 -2
- package/extensions/modules/repair/test/freshness.test.ts +41 -1
- package/extensions/modules/repair/test/guard-selector.test.ts +67 -0
- package/extensions/modules/router/configPanel.ts +4 -4
- package/extensions/modules/router/index.ts +1 -1
- package/extensions/modules/router/lib/config.ts +9 -4
- package/extensions/modules/router/lib/systemone.ts +17 -4
- package/extensions/modules/router/test/unit.test.ts +46 -1
- package/extensions/modules/rules/index.ts +13 -3
- package/extensions/modules/rules/lib/rules.ts +24 -12
- package/extensions/modules/rules/test/lib.test.ts +20 -0
- package/extensions/modules/rules/test/module.test.ts +21 -0
- package/extensions/modules/subagent/index.ts +11 -5
- package/extensions/modules/subagent/lib/herdr.ts +5 -0
- package/extensions/modules/subagent/lib/routing.ts +31 -8
- package/extensions/modules/subagent/lib/runner.ts +8 -2
- package/extensions/modules/subagent/test/routing.test.ts +45 -0
- package/extensions/modules/web/configPanel.ts +67 -8
- package/extensions/modules/web/test/configPanel.test.ts +7 -3
- package/extensions/modules/web/test/settings.test.ts +6 -0
- package/package.json +2 -2
|
@@ -277,7 +277,7 @@ describe("configPanel contribution", () => {
|
|
|
277
277
|
);
|
|
278
278
|
});
|
|
279
279
|
|
|
280
|
-
it("gateway token: an EDITED token
|
|
280
|
+
it("gateway token: an EDITED token diverts to .env.local — never settings.json; unrelated edits touch nothing", async () => {
|
|
281
281
|
await withoutA2AEnv(() =>
|
|
282
282
|
withIsolatedPiDir(async (dir) => {
|
|
283
283
|
// Operator has a gateway configured in the GLOBAL file (env-sourced token case:
|
|
@@ -302,16 +302,19 @@ describe("configPanel contribution", () => {
|
|
|
302
302
|
hb.set(90);
|
|
303
303
|
await (cfg.save as SaveFn)(new Set(["a2a.gw.work.heartbeatSec"]), ctx);
|
|
304
304
|
let written = JSON.parse(fs.readFileSync(globalSettings, "utf-8"));
|
|
305
|
-
assert.equal(written.a2a.discovery.gateways.work.token, "file-token", "unedited token survives an unrelated edit");
|
|
305
|
+
assert.equal(written.a2a.discovery.gateways.work.token, "file-token", "unedited token survives an unrelated edit (legacy value untouched)");
|
|
306
306
|
|
|
307
|
-
// Now edit the token itself →
|
|
307
|
+
// Now edit the token itself → diverts to .env.local, scrubbed from settings.json.
|
|
308
308
|
const cfg2 = a2aConfig({} as never);
|
|
309
309
|
cfg2.groups();
|
|
310
310
|
const tok = rowsOf(cfg2.groups()).find((r) => r.key === "a2a.gw.work.token")!;
|
|
311
311
|
tok.set("rotated-token");
|
|
312
312
|
await (cfg2.save as SaveFn)(new Set(["a2a.gw.work.token"]), ctx);
|
|
313
313
|
written = JSON.parse(fs.readFileSync(globalSettings, "utf-8"));
|
|
314
|
-
assert.
|
|
314
|
+
assert.ok(!written.a2a.discovery.gateways.work.token, "edited token must NOT persist in settings.json");
|
|
315
|
+
const envLocal = fs.readFileSync(path.join(process.env.PI_CODING_AGENT_DIR!, ".env.local"), "utf-8");
|
|
316
|
+
assert.match(envLocal, /A2A_GATEWAY_WORK_TOKEN=rotated-token/, "edited token diverted to .env.local");
|
|
317
|
+
assert.equal(process.env.A2A_GATEWAY_WORK_TOKEN, "rotated-token", "live session resolves the diverted token immediately");
|
|
315
318
|
}),
|
|
316
319
|
);
|
|
317
320
|
});
|
|
@@ -89,7 +89,6 @@ export default function advisorModule(pi: ExtensionAPI): void {
|
|
|
89
89
|
// watchEnabled is only updated at the end of this function.
|
|
90
90
|
const willWatch = masterChanged ? next.enabled : watchEnabled;
|
|
91
91
|
const rt = runtime;
|
|
92
|
-
const wasEmpty = !rt || rt.models.length === 0;
|
|
93
92
|
if (rt) {
|
|
94
93
|
rt.config = next;
|
|
95
94
|
rt.models = next.models;
|
|
@@ -98,8 +97,12 @@ export default function advisorModule(pi: ExtensionAPI): void {
|
|
|
98
97
|
rt.stats.paused = false;
|
|
99
98
|
rt.failures = 0;
|
|
100
99
|
}
|
|
101
|
-
// Enabling mid-session must not replay history
|
|
102
|
-
|
|
100
|
+
// Enabling mid-session must not replay history: reseed on FIRST
|
|
101
|
+
// activation (cursor still undefined), which covers BOTH the 0→N chain
|
|
102
|
+
// transition and the enable-only save on a session that started with
|
|
103
|
+
// enabled:false + a configured chain (a no-chain or disabled session
|
|
104
|
+
// never seeds the cursor, so `undefined` is exactly "not yet active").
|
|
105
|
+
if (willWatch && rt.models.length > 0 && rt.cursor === undefined) reseedCursor(rt, ctx);
|
|
103
106
|
}
|
|
104
107
|
// An explicit master change re-arms/disarms the session; otherwise a
|
|
105
108
|
// /advisor watch-off override stays in place.
|
|
@@ -261,6 +261,37 @@ describe("advisor module wiring", () => {
|
|
|
261
261
|
await fire(pi, state, "agent_settled", step(available(fakeCtx(entries)), "tui"));
|
|
262
262
|
assert.equal(calls, 0, "nothing new since the reseed → no review of the pre-existing turn");
|
|
263
263
|
});
|
|
264
|
+
|
|
265
|
+
it("session_start(review off, chain configured) + enable-only save reseeds the cursor (no history replay)", async () => {
|
|
266
|
+
// Live-found defect (reviewer 2026-10-06): the reseed keyed on the 0→N
|
|
267
|
+
// chain transition, so enabling `Review settled turns` on a session that
|
|
268
|
+
// STARTED with enabled:false + a configured chain left cursor undefined —
|
|
269
|
+
// the first settled turn counted the ENTIRE session's tool calls and
|
|
270
|
+
// reviewed the whole transcript. The reseed must key on first activation.
|
|
271
|
+
const { pi, state } = createFakePi();
|
|
272
|
+
advisorModule(pi);
|
|
273
|
+
writeSettings({ advisor: { enabled: false, models: [MODEL] } });
|
|
274
|
+
let ctx = available(fakeCtx(toolCalls(4)));
|
|
275
|
+
await fire(pi, state, "session_start", ctx);
|
|
276
|
+
const rt = __getRuntimeForTest();
|
|
277
|
+
assert.ok(rt, "runtime created");
|
|
278
|
+
assert.equal(rt!.models.length, 1, "chain was configured all along");
|
|
279
|
+
assert.equal(rt!.cursor, undefined, "review off at start → cursor never seeded");
|
|
280
|
+
|
|
281
|
+
// Enable ONLY the review — the chain is untouched.
|
|
282
|
+
const entries = toolCalls(4);
|
|
283
|
+
ctx = available(fakeCtx(entries));
|
|
284
|
+
const m = advisorConfig();
|
|
285
|
+
m.groups()[0]!.rows[0]!.set(true);
|
|
286
|
+
await m.save(new Set(["advisor.enabled"]), ctx);
|
|
287
|
+
|
|
288
|
+
assert.equal(rt!.cursor, entries.at(-1).id, "enable-only save reseeds to the tail — history is not replayed");
|
|
289
|
+
|
|
290
|
+
let calls = 0;
|
|
291
|
+
__setIsolatedForTest(async (_c, models) => { calls++; return { text: "", model: models[0], usage: NO_USAGE }; });
|
|
292
|
+
await fire(pi, state, "agent_settled", step(available(fakeCtx(entries)), "tui"));
|
|
293
|
+
assert.equal(calls, 0, "no new work since enable → no review");
|
|
294
|
+
});
|
|
264
295
|
});
|
|
265
296
|
|
|
266
297
|
describe("advisor review flow", () => {
|
|
@@ -228,6 +228,26 @@ export default function (pi: ExtensionAPI) {
|
|
|
228
228
|
|
|
229
229
|
const cache = createVerdictCache();
|
|
230
230
|
|
|
231
|
+
// Failure circuit-breaker (advisor's MAX_CONSECUTIVE_FAILURES precedent):
|
|
232
|
+
// the bash hot path must never pay the classify deadline per command. With
|
|
233
|
+
// the transport's 30s deadline, a cataloged-but-dead endpoint would stall
|
|
234
|
+
// every unique non-risky command ~30s — repeatedly, buying nothing (the
|
|
235
|
+
// verdict never gates execution). After 3 consecutive failures the hook
|
|
236
|
+
// fails open instantly for CLASSIFIER_PAUSE_COOLDOWN_MS; a successful
|
|
237
|
+
// verdict or a settings change re-arms immediately.
|
|
238
|
+
let consecutiveFailures = 0;
|
|
239
|
+
let pausedUntil = 0;
|
|
240
|
+
let pausedSettingsRef = "";
|
|
241
|
+
const CLASSIFIER_PAUSE_AFTER = 3;
|
|
242
|
+
const CLASSIFIER_PAUSE_COOLDOWN_MS = 5 * 60_000;
|
|
243
|
+
// The bash hot path's OWN wait budget. The verdict is annotation-only in
|
|
244
|
+
// pi 1.0.0 (no approval prompt to skip), so nothing justifies parking a
|
|
245
|
+
// tool call on a slow Jev: a verdict that misses this budget reads as
|
|
246
|
+
// "no verdict" (fail open to the normal prompt, audited). The 30s
|
|
247
|
+
// transport deadline stays as the hard backstop; the circuit breaker
|
|
248
|
+
// above then stops repeated retries.
|
|
249
|
+
const CLASSIFIER_HOOK_BUDGET_MS = 2_500;
|
|
250
|
+
|
|
231
251
|
pi.on("tool_call", async (event, ctx) => {
|
|
232
252
|
if (event.toolName !== "bash") return undefined;
|
|
233
253
|
const command = String(event.input?.command || "");
|
|
@@ -236,6 +256,24 @@ export default function (pi: ExtensionAPI) {
|
|
|
236
256
|
const s = getClassifierSettings();
|
|
237
257
|
if (!s.permission.enabled) return undefined;
|
|
238
258
|
|
|
259
|
+
// Circuit open → instant fail-open (no network attempt). A changed
|
|
260
|
+
// settings object re-arms at once: the operator switching the classifier
|
|
261
|
+
// model mid-pause should not wait out the cooldown.
|
|
262
|
+
const settingsRef = JSON.stringify([s.model, s.permission.enabled, s.permission.mode, s.permission.threshold]);
|
|
263
|
+
if (settingsRef !== pausedSettingsRef) {
|
|
264
|
+
pausedSettingsRef = settingsRef;
|
|
265
|
+
if (consecutiveFailures >= CLASSIFIER_PAUSE_AFTER) consecutiveFailures = 0; // manual remediation
|
|
266
|
+
}
|
|
267
|
+
// Circuit open? Instant fail-open. Else, if the pause window has ELAPSED
|
|
268
|
+
// (pausedUntil > 0 — 0 means "never paused", which must not reset the
|
|
269
|
+
// counter), close the circuit and retry.
|
|
270
|
+
const paused = consecutiveFailures >= CLASSIFIER_PAUSE_AFTER;
|
|
271
|
+
if (paused && Date.now() < pausedUntil) return undefined;
|
|
272
|
+
if (paused && pausedUntil > 0 && Date.now() >= pausedUntil) {
|
|
273
|
+
consecutiveFailures = 0; // cooldown elapsed → retry
|
|
274
|
+
pausedUntil = 0;
|
|
275
|
+
}
|
|
276
|
+
|
|
239
277
|
// static list first — credential-touching / irreversible commands never
|
|
240
278
|
// reach Jev and never leave the normal prompt
|
|
241
279
|
if (segments(command).some(isRisky)) return undefined;
|
|
@@ -265,6 +303,7 @@ export default function (pi: ExtensionAPI) {
|
|
|
265
303
|
const started = Date.now();
|
|
266
304
|
try {
|
|
267
305
|
const answers = await askJev(ctx, state, questions);
|
|
306
|
+
consecutiveFailures = 0;
|
|
268
307
|
const rev = noul(answers, "reversible");
|
|
269
308
|
const serves = state.task ? noul(answers, "serves_task") : rev; // no task → reversibility only
|
|
270
309
|
const ok = rev >= s.permission.threshold && serves >= s.permission.threshold;
|
|
@@ -273,12 +312,27 @@ export default function (pi: ExtensionAPI) {
|
|
|
273
312
|
await audit({ command, ...decision, ms: Date.now() - started, model: s.model || "(auto)" });
|
|
274
313
|
return decision;
|
|
275
314
|
} catch (e) {
|
|
315
|
+
consecutiveFailures++;
|
|
316
|
+
if (consecutiveFailures >= CLASSIFIER_PAUSE_AFTER) {
|
|
317
|
+
pausedUntil = Date.now() + CLASSIFIER_PAUSE_COOLDOWN_MS;
|
|
318
|
+
await audit({ command, pause: true, failures: consecutiveFailures, cooldown_ms: CLASSIFIER_PAUSE_COOLDOWN_MS });
|
|
319
|
+
}
|
|
276
320
|
await audit({ command, error: String(e instanceof Error ? e.message : e), ms: Date.now() - started, model: s.model || "(auto)" });
|
|
277
321
|
return null; // fail-safe: fall back to the normal prompt
|
|
278
322
|
}
|
|
279
323
|
};
|
|
280
324
|
|
|
281
|
-
|
|
325
|
+
// Race the verdict against the hook budget — pi awaits this handler
|
|
326
|
+
// before executing bash, so the budget (not the transport deadline) is
|
|
327
|
+
// what the user feels. A late verdict is discarded (no cache poison).
|
|
328
|
+
let decision: { approve: boolean; reversible: number; serves_task: number } | null | undefined = cached;
|
|
329
|
+
if (decision === undefined) {
|
|
330
|
+
const budget = AbortSignal.timeout(CLASSIFIER_HOOK_BUDGET_MS);
|
|
331
|
+
decision = await Promise.race([
|
|
332
|
+
decide(),
|
|
333
|
+
new Promise<null>((resolve) => budget.addEventListener("abort", () => resolve(null), { once: true })),
|
|
334
|
+
]);
|
|
335
|
+
}
|
|
282
336
|
|
|
283
337
|
// Both modes only annotate; neither changes execution (pi 1.0.0 has no
|
|
284
338
|
// approval prompt for tool_call to skip — see module docstring). Enforce
|
|
@@ -374,6 +374,68 @@ describe("permission hook", () => {
|
|
|
374
374
|
} finally { fx2.cleanup(); }
|
|
375
375
|
});
|
|
376
376
|
|
|
377
|
+
it("circuit breaker: 3 consecutive classify failures pause the hook (instant fail-open, no network attempt)", async () => {
|
|
378
|
+
// With the transport's 30s deadline, a dead endpoint would stall every
|
|
379
|
+
// unique non-risky command ~30s — repeatedly. After 3 consecutive
|
|
380
|
+
// failures the hook must fail open instantly until the cooldown.
|
|
381
|
+
let classifyCalls = 0;
|
|
382
|
+
let fail = true;
|
|
383
|
+
const registry = stubRegistry({
|
|
384
|
+
classify: async () => {
|
|
385
|
+
classifyCalls++;
|
|
386
|
+
if (fail) throw new Error("endpoint dead");
|
|
387
|
+
return { stopReason: "stop", answers: { reversible: { type: "bool", probability: 0.99 } } };
|
|
388
|
+
},
|
|
389
|
+
});
|
|
390
|
+
const fx = await hookFixture(registry);
|
|
391
|
+
try {
|
|
392
|
+
fx.messageEnd("do some work");
|
|
393
|
+
// Three DISTINCT commands (fresh cache keys) each pay one failed call.
|
|
394
|
+
assert.equal(await fx.call("ls -la"), undefined);
|
|
395
|
+
assert.equal(await fx.call("git status"), undefined);
|
|
396
|
+
assert.equal(await fx.call("pwd"), undefined);
|
|
397
|
+
assert.equal(classifyCalls, 3);
|
|
398
|
+
assert.ok(readFileSync(fx.logPath, "utf8").includes('"pause":true'), "pause transition audited");
|
|
399
|
+
|
|
400
|
+
// Circuit open: further commands fail open with NO network attempt.
|
|
401
|
+
assert.equal(await fx.call("cat file.txt"), undefined);
|
|
402
|
+
assert.equal(await fx.call("echo hi"), undefined);
|
|
403
|
+
assert.equal(classifyCalls, 3, "no classify attempts while paused");
|
|
404
|
+
} finally { fx.cleanup(); }
|
|
405
|
+
|
|
406
|
+
// Fresh module state = fresh breaker; a healthy verdict serves normally.
|
|
407
|
+
const fx2 = await hookFixture(registry);
|
|
408
|
+
try {
|
|
409
|
+
fail = false;
|
|
410
|
+
fx2.messageEnd("more work");
|
|
411
|
+
assert.equal(await fx2.call("ls"), undefined);
|
|
412
|
+
assert.equal(classifyCalls, 4, "healthy verdict went through");
|
|
413
|
+
} finally { fx2.cleanup(); }
|
|
414
|
+
});
|
|
415
|
+
|
|
416
|
+
it("hook budget: a slow classify loses the race — bash proceeds without waiting for the verdict", async () => {
|
|
417
|
+
// pi awaits the tool_call handler before executing bash; the verdict is
|
|
418
|
+
// annotation-only, so a slow Jev must not sit on the hot path. A verdict
|
|
419
|
+
// slower than the budget is discarded (no cache poison).
|
|
420
|
+
let classifyCalls = 0;
|
|
421
|
+
const registry = stubRegistry({
|
|
422
|
+
classify: async () => {
|
|
423
|
+
classifyCalls++;
|
|
424
|
+
await new Promise((r) => setTimeout(r, 60_000)); // way over budget
|
|
425
|
+
return { stopReason: "stop", answers: { reversible: { type: "bool", probability: 0.99 } } };
|
|
426
|
+
},
|
|
427
|
+
});
|
|
428
|
+
const fx = await hookFixture(registry);
|
|
429
|
+
try {
|
|
430
|
+
fx.messageEnd("slow endpoint");
|
|
431
|
+
const t0 = Date.now();
|
|
432
|
+
assert.equal(await fx.call("ls -la"), undefined);
|
|
433
|
+
const elapsed = Date.now() - t0;
|
|
434
|
+
assert.ok(elapsed < 5_000, `hook returned in ${elapsed}ms — budget raced, not the 30s transport deadline`);
|
|
435
|
+
assert.equal(classifyCalls, 1, "one attempt was made (then raced away)");
|
|
436
|
+
} finally { fx.cleanup(); }
|
|
437
|
+
});
|
|
438
|
+
|
|
377
439
|
it("classify error / no-model → fail-safe to prompt", async () => {
|
|
378
440
|
for (const registry of [
|
|
379
441
|
stubRegistry({ classify: async () => ({ stopReason: "error", errorMessage: "boom", answers: {} }) }),
|
|
@@ -306,7 +306,7 @@ describe("core module contract", () => {
|
|
|
306
306
|
it("nextDisabled excludes core modules; withEnableRow adds no row for them", async () => {
|
|
307
307
|
const { nextDisabled, withEnableRow } = await import("../../config/index.js");
|
|
308
308
|
// working = enabled set; nextDisabled lists the NOT-enabled non-core modules.
|
|
309
|
-
assert.deepEqual(nextDisabled(new Set(["munin"])), ["zai", "ponytail", "subagent", "plan", "a2a", "todo", "cron", "repair", "serena", "fff", "web", "rules", "attachments", "gh", "
|
|
309
|
+
assert.deepEqual(nextDisabled(new Set(["munin"])), ["zai", "ponytail", "subagent", "plan", "a2a", "todo", "cron", "repair", "serena", "fff", "web", "rules", "attachments", "gh", "rtk", "steering", "permission"]);
|
|
310
310
|
assert.deepEqual(nextDisabled(new Set(["router", "classifier", "ux", "munin", "usage", "ponytail", "subagent", "plan", "a2a", "todo", "cron", "repair", "serena", "fff", "web", "gh", "rules", "steering", "zai", "rtk", "config", "attachments", "permission"])), [], "all-on → nothing disabled");
|
|
311
311
|
for (const core of ["composer", "advisor", "router", "classifier", "usage", "ux", "config"]) {
|
|
312
312
|
assert.ok(!nextDisabled(new Set()).includes(core), `core (${core}) is never disableable`);
|
|
@@ -384,6 +384,10 @@ export function wrapToolDefinition(
|
|
|
384
384
|
typeof params.offset === "number" ? params.offset : undefined,
|
|
385
385
|
typeof params.limit === "number" ? params.limit : undefined,
|
|
386
386
|
);
|
|
387
|
+
// Selector reads record the freshness baseline too (params.path is
|
|
388
|
+
// the peeled stem here) — a ranged read must not blind the write
|
|
389
|
+
// guard for the rest of the file (live finding, reviewer 2026-10-06).
|
|
390
|
+
await recordReadMtimes(params, cwd);
|
|
387
391
|
return { ...result, details: base.name === "read" ? undefined : result.details };
|
|
388
392
|
}
|
|
389
393
|
|
|
@@ -435,6 +439,12 @@ export function wrapToolDefinition(
|
|
|
435
439
|
try {
|
|
436
440
|
const result = await freshDef.execute(toolCallId, params, signal, onUpdate, ctx);
|
|
437
441
|
editMismatchCounts?.delete(resolvePath(cwd, typeof params?.path === "string" ? params.path : ""));
|
|
442
|
+
// Own edit refreshes the freshness baseline (same contract as write/
|
|
443
|
+
// apply_patch/str_replace_editor): without this, read → edit → write
|
|
444
|
+
// false-positives — the write compares against the stale READ-time
|
|
445
|
+
// mtime (live finding, reviewer 2026-10-06; recordMutatedMtimes'
|
|
446
|
+
// edit branch was dead code for exactly this reason).
|
|
447
|
+
await recordMutatedMtimes("edit", params, cwd);
|
|
438
448
|
return result;
|
|
439
449
|
} catch (catchedErr: any) {
|
|
440
450
|
let err: any = catchedErr;
|
|
@@ -461,7 +471,9 @@ export function wrapToolDefinition(
|
|
|
461
471
|
else fixedParams.oldText = retry.fixedEdits[0].oldText;
|
|
462
472
|
onRepair(base.name, ["trim-match-retry"]);
|
|
463
473
|
try {
|
|
464
|
-
|
|
474
|
+
const retried = await freshDef.execute(toolCallId, fixedParams, signal, onUpdate, ctx);
|
|
475
|
+
await recordMutatedMtimes("edit", fixedParams, cwd); // params.path unchanged by the retry
|
|
476
|
+
return retried;
|
|
465
477
|
} catch (retryErr: any) {
|
|
466
478
|
// A failed trim-retry is still a miss — fall through to the
|
|
467
479
|
// unresolvable path below so it counts toward escalation.
|
|
@@ -643,7 +655,19 @@ export default function repairModule(pi: ExtensionAPI) {
|
|
|
643
655
|
}
|
|
644
656
|
if (event.toolName === "read" && isRecord(event.input) && ctx.cwd) {
|
|
645
657
|
const filePath = typeof event.input.path === "string" ? event.input.path.trim() : "";
|
|
646
|
-
|
|
658
|
+
// Selector reads (`file.ts:50-200`) probe the STEM: this hook runs on
|
|
659
|
+
// the RAW path, but the selector is only peeled inside execute —
|
|
660
|
+
// probing the un-peeled path would hard-block the module's own
|
|
661
|
+
// advertised read grammar (live finding, reviewer 2026-10-06). An
|
|
662
|
+
// invalid selector keeps the raw path so execute surfaces the loud error.
|
|
663
|
+
let probe = filePath;
|
|
664
|
+
if (filePath && !existsSync(resolvePath(ctx.cwd, probe))) {
|
|
665
|
+
try {
|
|
666
|
+
const peeled = peelPathSelector(filePath);
|
|
667
|
+
if (peeled.selector) probe = peeled.stem;
|
|
668
|
+
} catch { /* invalid selector — keep the raw path */ }
|
|
669
|
+
}
|
|
670
|
+
if (filePath && looksLikeCodePath(probe) && !existsSync(resolvePath(ctx.cwd, probe))) {
|
|
647
671
|
const filename = filePath.split("/").pop() ?? filePath;
|
|
648
672
|
const relDir = dirname(filePath);
|
|
649
673
|
const dirPart = relDir !== "." ? ` under ${relDir}/` : "";
|
|
@@ -8,7 +8,7 @@ import { mkdtemp, readFile, rm, utimes, writeFile } from "node:fs/promises";
|
|
|
8
8
|
import { tmpdir } from "node:os";
|
|
9
9
|
import { join } from "node:path";
|
|
10
10
|
import { after, describe, it } from "node:test";
|
|
11
|
-
import { createReadToolDefinition, createWriteToolDefinition } from "@earendil-works/pi-coding-agent";
|
|
11
|
+
import { createEditToolDefinition, createReadToolDefinition, createWriteToolDefinition } from "@earendil-works/pi-coding-agent";
|
|
12
12
|
import { appendConflictFooter, checkWriteFresh, wrapToolDefinition } from "../index.js";
|
|
13
13
|
|
|
14
14
|
const dirs: string[] = [];
|
|
@@ -121,6 +121,46 @@ describe("write freshness guard", () => {
|
|
|
121
121
|
await rm(file);
|
|
122
122
|
assert.equal(await checkWriteFresh({ path: file }, dir), undefined);
|
|
123
123
|
});
|
|
124
|
+
|
|
125
|
+
it("a SELECTOR read records the freshness baseline (ranged reads don't blind the guard)", async () => {
|
|
126
|
+
// Live finding (reviewer 2026-10-06): the selector slice path returned
|
|
127
|
+
// early without recordReadMtimes, so read f.ts:5-10 → foreign write →
|
|
128
|
+
// blind full-file write silently clobbered the foreign edit.
|
|
129
|
+
const dir = await tempDir();
|
|
130
|
+
const file = join(dir, "sel.txt");
|
|
131
|
+
await writeFile(file, "l1\nl2\nl3\nl4\nl5\nl6\nl7\nl8\n");
|
|
132
|
+
const read = wrapToolDefinition(createReadToolDefinition(dir), createReadToolDefinition, () => false, () => {});
|
|
133
|
+
const sliced = await exec(read, { path: `${file}:2-4` }, dir);
|
|
134
|
+
assert.equal(sliced.isError, undefined);
|
|
135
|
+
// Foreign edit + mtime bump after our ranged read.
|
|
136
|
+
await writeFile(file, "FOREIGN\nl2\nl3\nl4\nl5\nl6\nl7\nl8\n");
|
|
137
|
+
const future = new Date(Date.now() + 1100);
|
|
138
|
+
await utimes(file, future, future);
|
|
139
|
+
const write = makeWrapped("write", dir);
|
|
140
|
+
const result = await exec(write, { path: file, content: "mine\n" }, dir);
|
|
141
|
+
assert.equal(result.isError, true, "selector read must arm the freshness guard");
|
|
142
|
+
assert.match(result.content[0].text, /Re-read the file/);
|
|
143
|
+
assert.match(await readFile(file, "utf8"), /FOREIGN/);
|
|
144
|
+
});
|
|
145
|
+
|
|
146
|
+
it("write after a wrapped EDIT does not false-positive (edit refreshes the baseline)", async () => {
|
|
147
|
+
// Live-found defect (reviewer 2026-10-06): a successful edit never
|
|
148
|
+
// refreshed the freshness baseline, so read → edit → write compared the
|
|
149
|
+
// write against the stale READ-time mtime and blocked with a false
|
|
150
|
+
// "File changed on disk" — recordMutatedMtimes' edit branch was dead code.
|
|
151
|
+
const dir = await tempDir();
|
|
152
|
+
const file = join(dir, "edit-baseline.txt");
|
|
153
|
+
await writeFile(file, "alpha\n");
|
|
154
|
+
const read = wrapToolDefinition(createReadToolDefinition(dir), createReadToolDefinition, () => false, () => {});
|
|
155
|
+
await exec(read, { path: file }, dir);
|
|
156
|
+
const edit = wrapToolDefinition(createEditToolDefinition(dir), createEditToolDefinition, () => false, () => {});
|
|
157
|
+
const edited = await exec(edit, { path: file, edits: [{ oldText: "alpha", newText: "alpha\nbeta" }] }, dir);
|
|
158
|
+
assert.equal(edited.isError, undefined, "edit succeeded");
|
|
159
|
+
const write = makeWrapped("write", dir);
|
|
160
|
+
const result = await exec(write, { path: file, content: "alpha\nbeta\ngamma\n" }, dir);
|
|
161
|
+
assert.equal(result.isError, undefined, "write after own edit must pass the freshness guard");
|
|
162
|
+
assert.equal(await readFile(file, "utf8"), "alpha\nbeta\ngamma\n");
|
|
163
|
+
});
|
|
124
164
|
});
|
|
125
165
|
|
|
126
166
|
// ── Conflict-marker footer ──────────────────────────────────────────────────
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
// Live-found defect (reviewer 2026-10-06): the always-on read-on-guessed-path
|
|
2
|
+
// guard hard-blocked every numeric path-selector read. The tool_call hook ran
|
|
3
|
+
// on the RAW path (`f.ts:50-200`) while the selector peels only inside
|
|
4
|
+
// execute, so existsSync probed a path that never exists on disk. This suite
|
|
5
|
+
// fires the REAL registered hook: a selector read whose stem exists must
|
|
6
|
+
// pass; genuinely missing paths (plain or with a selector suffix) still block.
|
|
7
|
+
|
|
8
|
+
import assert from "node:assert/strict";
|
|
9
|
+
import { mkdtemp, rm, writeFile } from "node:fs/promises";
|
|
10
|
+
import { tmpdir } from "node:os";
|
|
11
|
+
import { join } from "node:path";
|
|
12
|
+
import { after, describe, it } from "node:test";
|
|
13
|
+
import repairModule from "../index.js";
|
|
14
|
+
|
|
15
|
+
type Hook = (event: unknown, ctx: unknown) => unknown;
|
|
16
|
+
const dirs: string[] = [];
|
|
17
|
+
const originalAgentDir = process.env.PI_CODING_AGENT_DIR;
|
|
18
|
+
|
|
19
|
+
after(async () => {
|
|
20
|
+
if (originalAgentDir === undefined) delete process.env.PI_CODING_AGENT_DIR;
|
|
21
|
+
else process.env.PI_CODING_AGENT_DIR = originalAgentDir;
|
|
22
|
+
await Promise.all(dirs.map((d) => rm(d, { recursive: true, force: true })));
|
|
23
|
+
});
|
|
24
|
+
|
|
25
|
+
async function fixture() {
|
|
26
|
+
const dir = await mkdtemp(join(tmpdir(), "repair-guard-"));
|
|
27
|
+
dirs.push(dir);
|
|
28
|
+
process.env.PI_CODING_AGENT_DIR = dir; // neutral settings: guards default ON
|
|
29
|
+
await writeFile(join(dir, "f.ts"), "line1\nline2\nline3\nline4\nline5\n");
|
|
30
|
+
const handlers: Record<string, Hook> = {};
|
|
31
|
+
repairModule({
|
|
32
|
+
on: (event: string, handler: Hook) => { handlers[event] = handler; },
|
|
33
|
+
registerTool: () => {},
|
|
34
|
+
registerCommand: () => {},
|
|
35
|
+
} as never);
|
|
36
|
+
const call = (path: string) => handlers.tool_call!({ toolName: "read", input: { path } }, { cwd: dir });
|
|
37
|
+
return { dir, call };
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
describe("read guard × path-selector interaction", () => {
|
|
41
|
+
it("a selector read whose STEM exists passes the guard", async () => {
|
|
42
|
+
const { call } = await fixture();
|
|
43
|
+
assert.equal(await call("f.ts:2-4"), undefined, "existing stem + numeric selector must not be blocked");
|
|
44
|
+
assert.equal(await call("f.ts:5"), undefined);
|
|
45
|
+
assert.equal(await call("f.ts:-2"), undefined);
|
|
46
|
+
assert.equal(await call("f.ts:1-2,5"), undefined);
|
|
47
|
+
assert.equal(await call("f.ts:conflicts"), undefined, ":conflicts never matched looksLikeCodePath anyway");
|
|
48
|
+
});
|
|
49
|
+
|
|
50
|
+
it("missing paths still block — plain and selector-suffixed", async () => {
|
|
51
|
+
const { call } = await fixture();
|
|
52
|
+
const plain = await call("missing.ts") as { block: boolean; reason: string } | undefined;
|
|
53
|
+
assert.ok(plain?.block, "plain missing code path blocked");
|
|
54
|
+
const sel = await call("missing.ts:50") as { block: boolean; reason: string } | undefined;
|
|
55
|
+
assert.ok(sel?.block, "missing stem with selector blocked (peeled probe also missing)");
|
|
56
|
+
assert.match(sel.reason, /Path not found/);
|
|
57
|
+
});
|
|
58
|
+
|
|
59
|
+
it("an invalid selector on an existing file falls back to the raw probe (execute's loud error path)", async () => {
|
|
60
|
+
const { call } = await fixture();
|
|
61
|
+
// `:not-a-selector` doesn't parse → probe stays raw → raw doesn't exist →
|
|
62
|
+
// looksLikeCodePath(raw without digit-suffix strip)... the raw path
|
|
63
|
+
// "f.ts:zz" is not a code path (extension test on the full string fails),
|
|
64
|
+
// so the guard passes and execute surfaces the literal-not-found error.
|
|
65
|
+
assert.equal(await call("f.ts:zz"), undefined);
|
|
66
|
+
});
|
|
67
|
+
});
|
|
@@ -15,8 +15,8 @@ import { refreshActiveModel } from "./lib/refresh.js";
|
|
|
15
15
|
* shown), so the panel never hides what the next request will actually use.
|
|
16
16
|
* `trusted` is required — the caller decides, mirroring the rule the save-time
|
|
17
17
|
* ctx applies (see zai's precedent). */
|
|
18
|
-
export function readRouterSettings(trusted: boolean): RouterSettings {
|
|
19
|
-
return getSettings({ trustProject: trusted });
|
|
18
|
+
export function readRouterSettings(trusted: boolean, cwd?: string): RouterSettings {
|
|
19
|
+
return getSettings({ trustProject: trusted, cwd });
|
|
20
20
|
}
|
|
21
21
|
|
|
22
22
|
/** Build the router panel groups over a working copy (mutated by row setters).
|
|
@@ -66,7 +66,7 @@ export async function saveRouterConfig(pi: ExtensionAPI, before: RouterSettings,
|
|
|
66
66
|
enableReasoning: working.enableReasoning !== before.enableReasoning ? working.enableReasoning : undefined,
|
|
67
67
|
});
|
|
68
68
|
const trusted = ctx.isProjectTrusted?.() === true;
|
|
69
|
-
const effective = readRouterSettings(trusted);
|
|
69
|
+
const effective = readRouterSettings(trusted, ctx.cwd);
|
|
70
70
|
registerProvider(pi, effective);
|
|
71
71
|
try {
|
|
72
72
|
await maybeRefreshCatalog(ctx, { force: true });
|
|
@@ -91,7 +91,7 @@ export function routerConfig(pi: ExtensionAPI): ModuleConfig {
|
|
|
91
91
|
// Baseline = what the next request resolves: the factory gets no ctx, so the
|
|
92
92
|
// shared trust helper decides (same rule save-time ctx.isProjectTrusted
|
|
93
93
|
// applies) — an untrusted checkout must not show phantom project values.
|
|
94
|
-
const before = readRouterSettings(isProjectTrusted(process.cwd()));
|
|
94
|
+
const before = readRouterSettings(isProjectTrusted(process.cwd()), process.cwd());
|
|
95
95
|
const working = structuredClone(before);
|
|
96
96
|
return {
|
|
97
97
|
groups: () => buildRouterGroups(working),
|
|
@@ -41,7 +41,7 @@ export default function (pi: ExtensionAPI) {
|
|
|
41
41
|
lastCtx = ctx;
|
|
42
42
|
// Now ctx exists: trust-gate the repo scope. A trusted repo may add/override
|
|
43
43
|
// the endpoint; an untrusted one is ignored (attacker-redirect guard).
|
|
44
|
-
const s = getSettings({ trustProject: ctx.isProjectTrusted?.() === true });
|
|
44
|
+
const s = getSettings({ trustProject: ctx.isProjectTrusted?.() === true, cwd: ctx.cwd });
|
|
45
45
|
if (!s.baseUrl) {
|
|
46
46
|
ctx.ui.notify(
|
|
47
47
|
"router provider not configured — set `router.baseUrl` in ~/.pi/agent/settings.json (or ROUTER_BASE_URL), then /login router.",
|
|
@@ -13,8 +13,13 @@ export interface RouterSettings {
|
|
|
13
13
|
|
|
14
14
|
// ── Constants ────────────────────────────────────────────────────────────────
|
|
15
15
|
|
|
16
|
-
/** Repo-scope settings
|
|
17
|
-
|
|
16
|
+
/** Repo-scope settings path for one session cwd (zai/advisor/munin convention:
|
|
17
|
+
* resolved per call, never bound to process.cwd() at import — RPC/a2a child
|
|
18
|
+
* sessions and --cwd launches differ from the process dir, and the trust
|
|
19
|
+
* verdict applies to the SESSION's repo, so the file must too). */
|
|
20
|
+
function repoSettingsPath(cwd?: string): string {
|
|
21
|
+
return join(cwd ?? process.cwd(), ".pi", "settings.json");
|
|
22
|
+
}
|
|
18
23
|
|
|
19
24
|
function agentDir(): string {
|
|
20
25
|
return process.env.PI_CODING_AGENT_DIR || join(homedir(), ".pi", "agent");
|
|
@@ -41,10 +46,10 @@ const envReasoning = () => process.env.ROUTER_ENABLE_REASONING ?? process.env.NI
|
|
|
41
46
|
* untrusted checkout must not redirect `router.baseUrl` to an attacker
|
|
42
47
|
* endpoint while the auth.json credential is sent there as Bearer.
|
|
43
48
|
* Repo-scope `router.apiKey` is ignored (secrets must not come from a checked-in file). */
|
|
44
|
-
export function getSettings(opts: { trustProject?: boolean } = {}): RouterSettings {
|
|
49
|
+
export function getSettings(opts: { trustProject?: boolean; cwd?: string } = {}): RouterSettings {
|
|
45
50
|
const saved = readRouterSection(readFileJson(globalSettingsPath())) ?? {};
|
|
46
51
|
const repo = opts.trustProject
|
|
47
|
-
? readRouterSection(readFileJson(
|
|
52
|
+
? readRouterSection(readFileJson(repoSettingsPath(opts.cwd))) ?? {}
|
|
48
53
|
: {};
|
|
49
54
|
return {
|
|
50
55
|
baseUrl: normalizeUrl(envBaseUrl() || repo.baseUrl || saved.baseUrl || ""),
|
|
@@ -22,7 +22,13 @@ function isRecord(value: unknown): value is Record<string, unknown> {
|
|
|
22
22
|
}
|
|
23
23
|
|
|
24
24
|
function url(model: ClassifierModelT): string {
|
|
25
|
-
|
|
25
|
+
// Same /v1 convention as fetchSystemoneModels/fetchModels (client.ts):
|
|
26
|
+
// a baseUrl like http://host:20128 must POST to /v1/systemone or every
|
|
27
|
+
// classify silently 404s while model DISCOVERY worked (found live by
|
|
28
|
+
// review 2026-10-06) — never double the segment.
|
|
29
|
+
return /\/v1\/?$/.test(model.baseUrl)
|
|
30
|
+
? `${model.baseUrl.replace(/\/+$/u, "")}/systemone`
|
|
31
|
+
: `${model.baseUrl.replace(/\/+$/u, "")}/v1/systemone`;
|
|
26
32
|
}
|
|
27
33
|
|
|
28
34
|
function requiredNumber(label: string, value: unknown, field: string): number {
|
|
@@ -127,10 +133,17 @@ export const systemoneClassify: ClassifierImpl["classify"] = async (model, conte
|
|
|
127
133
|
"content-type": "application/json",
|
|
128
134
|
...(options.headers ?? {}),
|
|
129
135
|
};
|
|
130
|
-
|
|
131
|
-
|
|
136
|
+
// pi's model-runtime passes no timeoutMs for classify calls, and an
|
|
137
|
+
// unanswered fetch parks the caller's turn FOREVER (live incident
|
|
138
|
+
// 2026-10-06: two dispatches stuck 8h in kevent on an ESTABLISHED socket).
|
|
139
|
+
// A routing verdict is cheap — default to a hard 30s deadline unless the
|
|
140
|
+
// caller asked for something else. Never rejects (contract): the timeout
|
|
141
|
+
// surfaces as stopReason:"error" and callers fail open.
|
|
142
|
+
const timeoutMs = options?.timeoutMs ?? 30_000;
|
|
143
|
+
const timeoutSignal = AbortSignal.timeout(timeoutMs);
|
|
144
|
+
const signal = options?.signal
|
|
132
145
|
? AbortSignal.any([options.signal, timeoutSignal])
|
|
133
|
-
:
|
|
146
|
+
: timeoutSignal;
|
|
134
147
|
const response = await fetch(url(model), {
|
|
135
148
|
method: "POST",
|
|
136
149
|
headers,
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { describe, it, before, after, mock } from "node:test";
|
|
2
2
|
import assert from "node:assert/strict";
|
|
3
|
-
import { mkdirSync, writeFileSync, unlinkSync, existsSync, readFileSync, rmSync, statSync } from "node:fs";
|
|
3
|
+
import { mkdirSync, mkdtempSync, writeFileSync, unlinkSync, existsSync, readFileSync, rmSync, statSync } from "node:fs";
|
|
4
4
|
import { homedir } from "node:os";
|
|
5
5
|
import { join } from "node:path";
|
|
6
6
|
import { tmpdir } from "node:os";
|
|
@@ -91,6 +91,26 @@ describe("config", () => {
|
|
|
91
91
|
});
|
|
92
92
|
});
|
|
93
93
|
|
|
94
|
+
it("the repo overlay resolves from opts.cwd, not process.cwd() (session-cwd convention)", async () => {
|
|
95
|
+
// Live-found defect (reviewer 2026-10-06): REPO_SETTINGS_PATH was bound
|
|
96
|
+
// to process.cwd() at import — RPC/a2a child sessions with a different
|
|
97
|
+
// session cwd consulted the wrong file under the right trust verdict.
|
|
98
|
+
const { getSettings } = await import("../lib/config.js");
|
|
99
|
+
writeSettings({ baseUrl: "http://global" });
|
|
100
|
+
const dirA = mkdtempSync(join(tmpdir(), "router-cwd-a-"));
|
|
101
|
+
const dirB = mkdtempSync(join(tmpdir(), "router-cwd-b-"));
|
|
102
|
+
try {
|
|
103
|
+
mkdirSync(join(dirB, ".pi"), { recursive: true });
|
|
104
|
+
writeFileSync(join(dirB, ".pi", "settings.json"), JSON.stringify({ router: { baseUrl: "http://repo-b/v1" } }));
|
|
105
|
+
assert.equal(getSettings({ trustProject: true, cwd: dirA }).baseUrl, "http://global", "A has no repo file → global");
|
|
106
|
+
assert.equal(getSettings({ trustProject: true, cwd: dirB }).baseUrl, "http://repo-b/v1", "B's repo file serves B's session");
|
|
107
|
+
assert.equal(getSettings({ trustProject: false, cwd: dirB }).baseUrl, "http://global", "untrusted B → global regardless of cwd");
|
|
108
|
+
} finally {
|
|
109
|
+
rmSync(dirA, { recursive: true, force: true });
|
|
110
|
+
rmSync(dirB, { recursive: true, force: true });
|
|
111
|
+
}
|
|
112
|
+
});
|
|
113
|
+
|
|
94
114
|
it("trusted: env still beats repo", async () => {
|
|
95
115
|
try { unlinkSync(settingsPath()); } catch { /* ignore */ }
|
|
96
116
|
process.env.ROUTER_BASE_URL = "http://from-env";
|
|
@@ -922,6 +942,31 @@ describe("provider classifier catalog", () => {
|
|
|
922
942
|
}
|
|
923
943
|
});
|
|
924
944
|
|
|
945
|
+
it("classify carries a default 30s deadline — a silent endpoint fails open, never hangs the turn", async () => {
|
|
946
|
+
const { systemoneClassify } = await import("../lib/systemone.js");
|
|
947
|
+
const model = {
|
|
948
|
+
api: "typesafe-system-one",
|
|
949
|
+
provider: "router",
|
|
950
|
+
id: "combo/jev",
|
|
951
|
+
baseUrl: "http://h/v1",
|
|
952
|
+
cost: { input: 0, output: 0 },
|
|
953
|
+
} as never;
|
|
954
|
+
const context = { state: {}, questions: { q: { type: "noul", instructions: "x?", criteria: { yes: "y", no: "n" } } } } as never;
|
|
955
|
+
const realFetch = globalThis.fetch;
|
|
956
|
+
// Never-resolving fetch: without the default deadline this promise never
|
|
957
|
+
// settles (the live 8h hang). AbortSignal.timeout must cut it short.
|
|
958
|
+
globalThis.fetch = ((_input: unknown, init?: RequestInit) => new Promise<Response>((_resolve, reject) => {
|
|
959
|
+
init?.signal?.addEventListener("abort", () => reject(new Error("aborted: deadline")));
|
|
960
|
+
})) as unknown as typeof fetch;
|
|
961
|
+
try {
|
|
962
|
+
const result = await systemoneClassify(model, context, { apiKey: "sk" } as never);
|
|
963
|
+
assert.equal(result.stopReason, "error", "deadline expiry must surface as stopReason error, not a hang");
|
|
964
|
+
assert.match(result.errorMessage ?? "", /deadline/i);
|
|
965
|
+
} finally {
|
|
966
|
+
globalThis.fetch = realFetch;
|
|
967
|
+
}
|
|
968
|
+
});
|
|
969
|
+
|
|
925
970
|
it("registerProvider carries the typesafe-system-one classifier implementation", async () => {
|
|
926
971
|
const { registerProvider, PROVIDER_ID } = await import("../lib/provider.js");
|
|
927
972
|
let registered: { name: string; config: Record<string, unknown> } | null = null;
|