ceulen 0.10.1 → 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 +107 -1
- package/README.md +56 -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/plan-bridge.ts +18 -0
- package/extensions/lib/registry.test.ts +8 -5
- package/extensions/lib/registry.ts +22 -3
- package/extensions/modules/a2a/configPanel.ts +42 -1
- package/extensions/modules/a2a/index.ts +4 -2
- 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/attachments/configPanel.ts +91 -0
- package/extensions/modules/attachments/index.ts +274 -0
- package/extensions/modules/attachments/lib/clipboard-files.ts +80 -0
- package/extensions/modules/attachments/lib/pastes.ts +45 -0
- package/extensions/modules/attachments/lib/paths.ts +74 -0
- package/extensions/modules/attachments/lib/registry.ts +70 -0
- package/extensions/modules/attachments/lib/settings.ts +99 -0
- package/extensions/modules/attachments/lib/tray.ts +74 -0
- package/extensions/modules/attachments/test/configPanel.test.ts +122 -0
- package/extensions/modules/attachments/test/index.test.ts +870 -0
- package/extensions/modules/attachments/test/module.test.ts +53 -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 +2 -2
- package/extensions/modules/config/index.ts +3 -0
- package/extensions/modules/config/test/renderTools.test.ts +1 -1
- package/extensions/modules/cron/configPanel.ts +103 -0
- package/extensions/modules/cron/index.ts +638 -0
- package/extensions/modules/cron/lib/jobs.ts +201 -0
- package/extensions/modules/cron/lib/schedule.ts +161 -0
- package/extensions/modules/cron/test/cwd-repro.test.ts +98 -0
- package/extensions/modules/cron/test/index.test.ts +859 -0
- package/extensions/modules/cron/test/schedule.test.ts +93 -0
- package/extensions/modules/munin/index.ts +3 -1
- package/extensions/modules/permission/index.ts +567 -0
- package/extensions/modules/permission/test/permission.test.ts +789 -0
- package/extensions/modules/plan/index.ts +5 -0
- package/extensions/modules/repair/index.ts +160 -5
- package/extensions/modules/repair/test/freshness.test.ts +209 -0
- 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 +49 -10
- 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 +356 -14
- package/extensions/modules/subagent/test/routing.test.ts +45 -0
- package/extensions/modules/subagent/test/worktree.test.ts +230 -0
- package/extensions/modules/usage/index.ts +193 -71
- package/extensions/modules/usage/test/context.test.ts +160 -120
- package/extensions/modules/web/configPanel.ts +67 -8
- package/extensions/modules/web/index.ts +3 -1
- package/extensions/modules/web/test/a11y.test.ts +1 -1
- 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
- package/skills/cron/SKILL.md +58 -0
|
@@ -57,6 +57,7 @@ import { readDisabledTools } from "../../lib/tools.js";
|
|
|
57
57
|
// frontmatter (user + project + bundled). discoverAgents is a pure fs loader,
|
|
58
58
|
// independent of whether the subagent module itself is enabled.
|
|
59
59
|
import { discoverAgents } from "../subagent/lib/agents.js";
|
|
60
|
+
import { setPlanActive } from "../../lib/plan-bridge.ts";
|
|
60
61
|
|
|
61
62
|
export const PLAN_STATUS_KEY = "ceulen-plan";
|
|
62
63
|
export const PLAN_ENTRY_TYPE = "ceulen-plan";
|
|
@@ -203,6 +204,10 @@ export default function planModule(pi: ExtensionAPI): void {
|
|
|
203
204
|
|
|
204
205
|
function updateStatus(ctx: ExtensionContext): void {
|
|
205
206
|
ctx.ui.setStatus(PLAN_STATUS_KEY, planModeEnabled ? ctx.ui.theme.fg("accent", "Plan mode") : undefined);
|
|
207
|
+
// Publish for the permission module (plan-bridge) — updateStatus runs after
|
|
208
|
+
// EVERY planModeEnabled assignment site, so this one line covers toggle,
|
|
209
|
+
// session restore, startup flag, and exit-for-execution.
|
|
210
|
+
setPlanActive(planModeEnabled);
|
|
206
211
|
}
|
|
207
212
|
|
|
208
213
|
/** Restore branch-scoped state (session_start / session_tree). */
|
|
@@ -27,7 +27,7 @@
|
|
|
27
27
|
|
|
28
28
|
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
29
29
|
import { existsSync } from "node:fs";
|
|
30
|
-
import { readFile } from "node:fs/promises";
|
|
30
|
+
import { readFile, stat } from "node:fs/promises";
|
|
31
31
|
import { dirname, resolve as resolvePath } from "node:path";
|
|
32
32
|
import {
|
|
33
33
|
createBashToolDefinition,
|
|
@@ -182,11 +182,111 @@ function addReadDefaults(args: unknown): unknown {
|
|
|
182
182
|
return out;
|
|
183
183
|
}
|
|
184
184
|
|
|
185
|
+
// ── Write freshness guard (multi-session blind-overwrite protection) ──
|
|
186
|
+
// A `write` replaces a file wholesale: unlike edit/apply_patch (anchored on
|
|
187
|
+
// exact content) it cannot notice a foreign change. Record each file's mtime
|
|
188
|
+
// when read; before a write, compare — a mismatch means ANOTHER session or
|
|
189
|
+
// process changed the file since we last saw it. Only files this session
|
|
190
|
+
// actually read are guarded (intentional never-read overwrites stay legal).
|
|
191
|
+
const seenMtime = new Map<string, number>();
|
|
192
|
+
|
|
193
|
+
async function statMtime(abs: string): Promise<number | undefined> {
|
|
194
|
+
try {
|
|
195
|
+
return (await stat(abs)).mtimeMs;
|
|
196
|
+
} catch {
|
|
197
|
+
return undefined;
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
/** Record mtimes for files a successful read just returned. */
|
|
202
|
+
async function recordReadMtimes(params: any, cwd: string): Promise<void> {
|
|
203
|
+
if (!isRecord(params) || typeof params.path !== "string" || params.path.includes("://")) return;
|
|
204
|
+
const mtime = await statMtime(resolvePath(cwd, params.path));
|
|
205
|
+
if (mtime !== undefined) seenMtime.set(resolvePath(cwd, params.path), mtime);
|
|
206
|
+
// ponytail: the map grows with files-read-per-process; a cap keeps it
|
|
207
|
+
// bounded without an eviction policy.
|
|
208
|
+
if (seenMtime.size > 2000) seenMtime.clear();
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
/** After a successful mutation, refresh the recorded mtime so a FOLLOW-UP
|
|
212
|
+
* write compares against what this session last wrote, not what it read. */
|
|
213
|
+
async function recordMutatedMtimes(toolName: string, params: any, cwd: string): Promise<void> {
|
|
214
|
+
const paths: string[] = [];
|
|
215
|
+
if (toolName === "write" && isRecord(params) && typeof params.path === "string") paths.push(params.path);
|
|
216
|
+
if (toolName === "edit" && isRecord(params) && typeof params.path === "string") paths.push(params.path);
|
|
217
|
+
if (toolName === "apply_patch" && isRecord(params) && typeof params.patch === "string") {
|
|
218
|
+
paths.push(...parsePatchTargetPaths(params.patch));
|
|
219
|
+
}
|
|
220
|
+
for (const p of paths) {
|
|
221
|
+
const abs = resolvePath(cwd, p);
|
|
222
|
+
const mtime = await statMtime(abs);
|
|
223
|
+
if (mtime !== undefined) seenMtime.set(abs, mtime);
|
|
224
|
+
else seenMtime.delete(abs);
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
/** V4D patch targets: `*** Update File: <path>` / Add / Delete / rename. */
|
|
229
|
+
function parsePatchTargetPaths(patch: string): string[] {
|
|
230
|
+
const out: string[] = [];
|
|
231
|
+
for (const m of patch.matchAll(/^\*{3} (?:Add|Delete|Update) File: (.+?)(?: → .+)?$/gm)) {
|
|
232
|
+
const target = m[1].trim();
|
|
233
|
+
if (target && !target.includes("://")) out.push(target.split(" → ")[0].trim());
|
|
234
|
+
}
|
|
235
|
+
return out;
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
/** Public seam for tools registered outside wrapToolDefinition (apply_patch,
|
|
239
|
+
* str_replace_editor) to refresh the freshness baseline after their own
|
|
240
|
+
* successful mutations. */
|
|
241
|
+
export async function refreshMtime(path: string, cwd: string): Promise<void> {
|
|
242
|
+
const abs = resolvePath(cwd, path);
|
|
243
|
+
const mtime = await statMtime(abs);
|
|
244
|
+
if (mtime !== undefined) seenMtime.set(abs, mtime);
|
|
245
|
+
else seenMtime.delete(abs);
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
/** Pre-write check. Returns an error message when the file changed since this
|
|
249
|
+
* session last read it, else undefined (allowed). Exported for tests. */
|
|
250
|
+
export async function checkWriteFresh(params: any, cwd: string): Promise<string | undefined> {
|
|
251
|
+
if (!isRecord(params) || typeof params.path !== "string" || params.path.includes("://")) return undefined;
|
|
252
|
+
const abs = resolvePath(cwd, params.path);
|
|
253
|
+
const seen = seenMtime.get(abs);
|
|
254
|
+
if (seen === undefined) return undefined; // never read here — intentional overwrite is legal
|
|
255
|
+
const current = await statMtime(abs);
|
|
256
|
+
if (current === undefined) return undefined; // gone since read — write recreates it
|
|
257
|
+
if (current !== seen) {
|
|
258
|
+
return `File changed on disk since this session last read it (mtime differs — another session/process likely wrote it). Re-read the file, then re-apply your write to <${params.path}>.`;
|
|
259
|
+
}
|
|
260
|
+
return undefined;
|
|
261
|
+
}
|
|
262
|
+
|
|
185
263
|
function appendReadNote(result: any, note: unknown) {
|
|
186
264
|
if (typeof note !== "string" || !note) return result;
|
|
187
265
|
return { ...result, content: [...(Array.isArray(result?.content) ? result.content : []), { type: "text", text: note }] };
|
|
188
266
|
}
|
|
189
267
|
|
|
268
|
+
/** Auto-detect unresolved git conflict markers in a full-file read and append
|
|
269
|
+
* a footer naming them (OMP's conflict-detect workflow). Zero extra I/O —
|
|
270
|
+
* scans the text blocks the read already returned. The `:conflicts` selector
|
|
271
|
+
* path is excluded (it lists blocks explicitly). Exported for tests. */
|
|
272
|
+
export function appendConflictFooter(result: any, params: any, selector: ParsedSelector | undefined, cwd: string): any {
|
|
273
|
+
if (selector) return result;
|
|
274
|
+
const p = isRecord(params) && typeof params.path === "string" ? params.path : "";
|
|
275
|
+
if (!p) return result;
|
|
276
|
+
const texts = (Array.isArray(result?.content) ? result.content : [])
|
|
277
|
+
.filter((c: any) => c?.type === "text" && typeof c.text === "string")
|
|
278
|
+
.map((c: any) => c.text as string);
|
|
279
|
+
if (texts.length === 0) return result;
|
|
280
|
+
const lines = texts.join("\n").split("\n") as string[];
|
|
281
|
+
// Cheap pre-check before the block scanner.
|
|
282
|
+
if (!lines.some((l) => l.startsWith("<<<<<<<"))) return result;
|
|
283
|
+
const blocks = extractConflictBlocks(lines);
|
|
284
|
+
if (blocks.length === 0) return result;
|
|
285
|
+
const first = lines.indexOf(blocks[0][0]) + 1;
|
|
286
|
+
const footer = `⚠ ${blocks.length} unresolved merge conflict block(s) detected in ${p} (first at line ${first}) — read with :conflicts to list them, then edit to resolve.`;
|
|
287
|
+
return { ...result, content: [...(result.content as any[]), { type: "text", text: footer }] };
|
|
288
|
+
}
|
|
289
|
+
|
|
190
290
|
// Strip read-tool contamination notices from an edit's oldText fields. Mutates
|
|
191
291
|
// in place and reports whether anything changed.
|
|
192
292
|
function decontaminateEditArgs(args: any): boolean {
|
|
@@ -284,13 +384,35 @@ export function wrapToolDefinition(
|
|
|
284
384
|
typeof params.offset === "number" ? params.offset : undefined,
|
|
285
385
|
typeof params.limit === "number" ? params.limit : undefined,
|
|
286
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);
|
|
287
391
|
return { ...result, details: base.name === "read" ? undefined : result.details };
|
|
288
392
|
}
|
|
289
393
|
|
|
290
394
|
if (base.name !== "edit") {
|
|
291
395
|
try {
|
|
396
|
+
// Write freshness guard (see checkWriteFresh): a `write` to a file
|
|
397
|
+
// THIS session read earlier but someone else changed since must
|
|
398
|
+
// fail loudly instead of clobbering the foreign edit.
|
|
399
|
+
if (base.name === "write") {
|
|
400
|
+
const stale = await checkWriteFresh(params, cwd);
|
|
401
|
+
if (stale) {
|
|
402
|
+
return { content: [{ type: "text", text: stale }], isError: true, details: undefined };
|
|
403
|
+
}
|
|
404
|
+
}
|
|
292
405
|
const result = await freshDef.execute(toolCallId, params, signal, onUpdate, ctx);
|
|
293
|
-
|
|
406
|
+
if (base.name === "read") {
|
|
407
|
+
const withNote = appendReadNote(result, readNote);
|
|
408
|
+
await recordReadMtimes(params, cwd);
|
|
409
|
+
return appendConflictFooter(withNote, params, selector ?? peeledSelector, cwd);
|
|
410
|
+
}
|
|
411
|
+
// Own mutations refresh the freshness baseline so later writes
|
|
412
|
+
// compare against what THIS session last left on disk. Awaited:
|
|
413
|
+
// a write immediately following must observe the new baseline.
|
|
414
|
+
await recordMutatedMtimes(base.name, params, cwd);
|
|
415
|
+
return result;
|
|
294
416
|
} catch (err: any) {
|
|
295
417
|
// Session mining: "(no output) / Command exited with code 1" after a
|
|
296
418
|
// search reads as a crash, so models retry the same command. Annotate
|
|
@@ -317,6 +439,12 @@ export function wrapToolDefinition(
|
|
|
317
439
|
try {
|
|
318
440
|
const result = await freshDef.execute(toolCallId, params, signal, onUpdate, ctx);
|
|
319
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);
|
|
320
448
|
return result;
|
|
321
449
|
} catch (catchedErr: any) {
|
|
322
450
|
let err: any = catchedErr;
|
|
@@ -343,7 +471,9 @@ export function wrapToolDefinition(
|
|
|
343
471
|
else fixedParams.oldText = retry.fixedEdits[0].oldText;
|
|
344
472
|
onRepair(base.name, ["trim-match-retry"]);
|
|
345
473
|
try {
|
|
346
|
-
|
|
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;
|
|
347
477
|
} catch (retryErr: any) {
|
|
348
478
|
// A failed trim-retry is still a miss — fall through to the
|
|
349
479
|
// unresolvable path below so it counts toward escalation.
|
|
@@ -460,6 +590,9 @@ export default function repairModule(pi: ExtensionAPI) {
|
|
|
460
590
|
}
|
|
461
591
|
try {
|
|
462
592
|
const res = await applyPatchToFiles(parsed, cwd);
|
|
593
|
+
// Refresh freshness baselines: a later write to a patched file must
|
|
594
|
+
// compare against this patch's mtime, not an older read.
|
|
595
|
+
await Promise.all(res.files.map((f) => refreshMtime(f.path, cwd)));
|
|
463
596
|
const summary = res.files.map((f) => {
|
|
464
597
|
if (f.kind === "add") return `Added ${f.path}`;
|
|
465
598
|
if (f.kind === "delete") return `Deleted ${f.path}`;
|
|
@@ -479,8 +612,18 @@ export default function repairModule(pi: ExtensionAPI) {
|
|
|
479
612
|
});
|
|
480
613
|
|
|
481
614
|
// ── str_replace_editor: DSH Minimal-pair editor (byte-faithful schema) ──
|
|
615
|
+
const strReplaceDef = createStrReplaceEditorToolDefinition(process.cwd());
|
|
482
616
|
pi.registerTool({
|
|
483
|
-
...
|
|
617
|
+
...strReplaceDef,
|
|
618
|
+
async execute(toolCallId: string, params: any, signal: any, onUpdate: any, ctx: any) {
|
|
619
|
+
const result = await strReplaceDef.execute(toolCallId, params, signal, onUpdate, ctx);
|
|
620
|
+
// Refresh the freshness baseline for the edited file (same rationale as
|
|
621
|
+
// apply_patch above) — only on success, only for plain file paths.
|
|
622
|
+
if (!result?.isError && isRecord(params) && typeof params.path === "string" && !params.path.includes("://")) {
|
|
623
|
+
await refreshMtime(params.path, ctx?.cwd || process.cwd());
|
|
624
|
+
}
|
|
625
|
+
return result;
|
|
626
|
+
},
|
|
484
627
|
defaultActive: !disabled.has("str_replace_editor"),
|
|
485
628
|
});
|
|
486
629
|
|
|
@@ -512,7 +655,19 @@ export default function repairModule(pi: ExtensionAPI) {
|
|
|
512
655
|
}
|
|
513
656
|
if (event.toolName === "read" && isRecord(event.input) && ctx.cwd) {
|
|
514
657
|
const filePath = typeof event.input.path === "string" ? event.input.path.trim() : "";
|
|
515
|
-
|
|
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))) {
|
|
516
671
|
const filename = filePath.split("/").pop() ?? filePath;
|
|
517
672
|
const relDir = dirname(filePath);
|
|
518
673
|
const dirPart = relDir !== "." ? ` under ${relDir}/` : "";
|
|
@@ -0,0 +1,209 @@
|
|
|
1
|
+
// Multi-session safety in the repair module: the write freshness guard
|
|
2
|
+
// (read→foreign-write→write must fail loud) and the auto conflict-marker
|
|
3
|
+
// footer on full-file reads. Real temp files, real wrapped tool definitions —
|
|
4
|
+
// the wrapper.test.ts integration precedent.
|
|
5
|
+
|
|
6
|
+
import assert from "node:assert/strict";
|
|
7
|
+
import { mkdtemp, readFile, rm, utimes, writeFile } from "node:fs/promises";
|
|
8
|
+
import { tmpdir } from "node:os";
|
|
9
|
+
import { join } from "node:path";
|
|
10
|
+
import { after, describe, it } from "node:test";
|
|
11
|
+
import { createEditToolDefinition, createReadToolDefinition, createWriteToolDefinition } from "@earendil-works/pi-coding-agent";
|
|
12
|
+
import { appendConflictFooter, checkWriteFresh, wrapToolDefinition } from "../index.js";
|
|
13
|
+
|
|
14
|
+
const dirs: string[] = [];
|
|
15
|
+
const originalAgentDir = process.env.PI_CODING_AGENT_DIR;
|
|
16
|
+
|
|
17
|
+
after(async () => {
|
|
18
|
+
if (originalAgentDir === undefined) delete process.env.PI_CODING_AGENT_DIR;
|
|
19
|
+
else process.env.PI_CODING_AGENT_DIR = originalAgentDir;
|
|
20
|
+
await Promise.all(dirs.map((d) => rm(d, { recursive: true, force: true })));
|
|
21
|
+
});
|
|
22
|
+
|
|
23
|
+
async function tempDir(): Promise<string> {
|
|
24
|
+
const dir = await mkdtemp(join(tmpdir(), "repair-freshness-"));
|
|
25
|
+
dirs.push(dir);
|
|
26
|
+
process.env.PI_CODING_AGENT_DIR = dir;
|
|
27
|
+
return dir;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
// Minimal wrapToolDefinition harness — the real core definitions, no repair
|
|
31
|
+
// toggles needed (defaults off for arguments; freshness/footer are always-on).
|
|
32
|
+
function makeWrapped(name: "read" | "write", cwd: string) {
|
|
33
|
+
const factory = name === "read" ? createReadToolDefinition : createWriteToolDefinition;
|
|
34
|
+
return wrapToolDefinition(factory(cwd), factory, () => false, () => {});
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
const exec = (wrapped: any, params: any, cwd: string) =>
|
|
38
|
+
wrapped.execute("t1", params, undefined, undefined, { cwd });
|
|
39
|
+
|
|
40
|
+
// ── Write freshness guard ───────────────────────────────────────────────────
|
|
41
|
+
|
|
42
|
+
describe("write freshness guard", () => {
|
|
43
|
+
it("write after read, no foreign change → succeeds and content lands", async () => {
|
|
44
|
+
const dir = await tempDir();
|
|
45
|
+
const file = join(dir, "a.txt");
|
|
46
|
+
await writeFile(file, "one\n");
|
|
47
|
+
const read = makeWrapped("read", dir);
|
|
48
|
+
await exec(read, { path: file }, dir);
|
|
49
|
+
const write = makeWrapped("write", dir);
|
|
50
|
+
const result = await exec(write, { path: file, content: "one\ntwo\n" }, dir);
|
|
51
|
+
assert.equal(result.isError, undefined);
|
|
52
|
+
assert.equal(await readFile(file, "utf8"), "one\ntwo\n");
|
|
53
|
+
});
|
|
54
|
+
|
|
55
|
+
it("read → FOREIGN write → write fails loud without clobbering", async () => {
|
|
56
|
+
const dir = await tempDir();
|
|
57
|
+
const file = join(dir, "b.txt");
|
|
58
|
+
await writeFile(file, "mine\n");
|
|
59
|
+
const read = makeWrapped("read", dir);
|
|
60
|
+
await exec(read, { path: file }, dir);
|
|
61
|
+
// Another session/process writes the file between our read and write.
|
|
62
|
+
await writeFile(file, "theirs\n");
|
|
63
|
+
// Ensure mtime actually advances (same-ms writes would false-pass).
|
|
64
|
+
const st = await readFile(file, "utf8");
|
|
65
|
+
const future = new Date(Date.now() + 1100);
|
|
66
|
+
await utimes(file, future, future);
|
|
67
|
+
assert.equal(st, "theirs\n");
|
|
68
|
+
const write = makeWrapped("write", dir);
|
|
69
|
+
const result = await exec(write, { path: file, content: "mine v2\n" }, dir);
|
|
70
|
+
assert.equal(result.isError, true);
|
|
71
|
+
assert.match(result.content[0].text, /Re-read the file/);
|
|
72
|
+
assert.equal(await readFile(file, "utf8"), "theirs\n"); // foreign edit survived
|
|
73
|
+
});
|
|
74
|
+
|
|
75
|
+
it("write after own edit does not false-positive", async () => {
|
|
76
|
+
const dir = await tempDir();
|
|
77
|
+
const file = join(dir, "c.txt");
|
|
78
|
+
await writeFile(file, "x\n");
|
|
79
|
+
const read = makeWrapped("read", dir);
|
|
80
|
+
await exec(read, { path: file }, dir);
|
|
81
|
+
const write = makeWrapped("write", dir);
|
|
82
|
+
await exec(write, { path: file, content: "y\n" }, dir);
|
|
83
|
+
const again = await exec(write, { path: file, content: "z\n" }, dir);
|
|
84
|
+
assert.equal(again.isError, undefined);
|
|
85
|
+
assert.equal(await readFile(file, "utf8"), "z\n");
|
|
86
|
+
});
|
|
87
|
+
|
|
88
|
+
it("write to a never-read file is allowed (intentional overwrite is legal)", async () => {
|
|
89
|
+
const dir = await tempDir();
|
|
90
|
+
const file = join(dir, "d.txt");
|
|
91
|
+
await writeFile(file, "old\n");
|
|
92
|
+
const write = makeWrapped("write", dir);
|
|
93
|
+
const result = await exec(write, { path: file, content: "new\n" }, dir);
|
|
94
|
+
assert.equal(result.isError, undefined);
|
|
95
|
+
});
|
|
96
|
+
|
|
97
|
+
it("write after own apply_patch does not false-positive", async () => {
|
|
98
|
+
const dir = await tempDir();
|
|
99
|
+
const file = join(dir, "e.txt");
|
|
100
|
+
await writeFile(file, "alpha\n");
|
|
101
|
+
const read = makeWrapped("read", dir);
|
|
102
|
+
await exec(read, { path: file }, dir);
|
|
103
|
+
// Simulate the apply_patch flow: patch tool mutates (externally to the
|
|
104
|
+
// wrapped write), refreshes the baseline, then a write must pass.
|
|
105
|
+
await writeFile(file, "alpha\nbeta\n");
|
|
106
|
+
const future = new Date(Date.now() + 1100);
|
|
107
|
+
await utimes(file, future, future);
|
|
108
|
+
const { refreshMtime } = await import("../index.js");
|
|
109
|
+
await refreshMtime(file, dir);
|
|
110
|
+
const write = makeWrapped("write", dir);
|
|
111
|
+
const result = await exec(write, { path: file, content: "alpha\nbeta\ngamma\n" }, dir);
|
|
112
|
+
assert.equal(result.isError, undefined);
|
|
113
|
+
});
|
|
114
|
+
|
|
115
|
+
it("checkWriteFresh unit: missing file since read is allowed (recreate)", async () => {
|
|
116
|
+
const dir = await tempDir();
|
|
117
|
+
const file = join(dir, "gone.txt");
|
|
118
|
+
await writeFile(file, "x\n");
|
|
119
|
+
const read = makeWrapped("read", dir);
|
|
120
|
+
await exec(read, { path: file }, dir);
|
|
121
|
+
await rm(file);
|
|
122
|
+
assert.equal(await checkWriteFresh({ path: file }, dir), undefined);
|
|
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
|
+
});
|
|
164
|
+
});
|
|
165
|
+
|
|
166
|
+
// ── Conflict-marker footer ──────────────────────────────────────────────────
|
|
167
|
+
|
|
168
|
+
describe("conflict footer", () => {
|
|
169
|
+
it("pure function: appends footer when completed blocks present", () => {
|
|
170
|
+
const content = "a\n<<<<<<< HEAD\nours\n=======\ntheirs\n>>>>>>> branch\nb\n";
|
|
171
|
+
const result = appendConflictFooter(
|
|
172
|
+
{ content: [{ type: "text", text: content }] },
|
|
173
|
+
{ path: "f.txt" },
|
|
174
|
+
undefined,
|
|
175
|
+
"/cwd",
|
|
176
|
+
);
|
|
177
|
+
const footer = result.content[result.content.length - 1];
|
|
178
|
+
assert.match(footer.text, /1 unresolved merge conflict block/);
|
|
179
|
+
assert.match(footer.text, /first at line 2/);
|
|
180
|
+
});
|
|
181
|
+
|
|
182
|
+
it("pure function: silent without conflicts, and open (unclosed) markers don't count", () => {
|
|
183
|
+
const clean = appendConflictFooter({ content: [{ type: "text", text: "no markers\n" }] }, { path: "f.txt" }, undefined, "/c");
|
|
184
|
+
assert.equal(clean.content.length, 1);
|
|
185
|
+
const open = appendConflictFooter({ content: [{ type: "text", text: "<<<<<<< HEAD\nnever closed\n" }] }, { path: "f.txt" }, undefined, "/c");
|
|
186
|
+
assert.equal(open.content.length, 1);
|
|
187
|
+
});
|
|
188
|
+
|
|
189
|
+
it("selector reads are excluded (the :conflicts path lists blocks explicitly)", () => {
|
|
190
|
+
const content = "<<<<<<< HEAD\nours\n=======\ntheirs\n>>>>>>> b\n";
|
|
191
|
+
const result = appendConflictFooter(
|
|
192
|
+
{ content: [{ type: "text", text: content }] },
|
|
193
|
+
{ path: "f.txt" },
|
|
194
|
+
{ kind: "lines", startLine: 1 } as never,
|
|
195
|
+
"/c",
|
|
196
|
+
);
|
|
197
|
+
assert.equal(result.content.length, 1);
|
|
198
|
+
});
|
|
199
|
+
|
|
200
|
+
it("integration: wrapped read of a conflicted file carries the footer", async () => {
|
|
201
|
+
const dir = await tempDir();
|
|
202
|
+
const file = join(dir, "conflicted.txt");
|
|
203
|
+
await writeFile(file, "top\n<<<<<<< HEAD\nours\n=======\ntheirs\n>>>>>>> other\nbottom\n");
|
|
204
|
+
const read = makeWrapped("read", dir);
|
|
205
|
+
const result = await exec(read, { path: file }, dir);
|
|
206
|
+
const texts = result.content.map((c: any) => c.text).join("\n");
|
|
207
|
+
assert.match(texts, /1 unresolved merge conflict block/);
|
|
208
|
+
});
|
|
209
|
+
});
|
|
@@ -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,
|