ceulen 0.13.0 → 0.14.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 +42 -0
- package/extensions/modules/a2a/lib/config.ts +15 -1
- package/extensions/modules/a2a/test/config.test.ts +27 -0
- package/extensions/modules/fff/index.ts +19 -0
- package/extensions/modules/fff/test/index.test.ts +31 -4
- package/extensions/modules/gh/configPanel.ts +9 -6
- package/extensions/modules/gh/test/gh.test.ts +61 -0
- package/extensions/modules/jfind/index.ts +10 -1
- package/extensions/modules/jfind/lib/cascade.ts +15 -1
- package/extensions/modules/jfind/lib/lexical.ts +18 -6
- package/extensions/modules/jfind/lib/tree.ts +34 -4
- package/extensions/modules/jfind/test/cascade.test.ts +56 -1
- package/extensions/modules/repair/configPanel.ts +11 -8
- package/extensions/modules/repair/index.ts +58 -25
- package/extensions/modules/repair/lib/auto-bg.ts +45 -2
- package/extensions/modules/repair/lib/auto-generated.ts +14 -4
- package/extensions/modules/repair/lib/read-archive.ts +14 -0
- package/extensions/modules/repair/lib/read-sqlite.ts +10 -4
- package/extensions/modules/repair/lib/settings.ts +19 -8
- package/extensions/modules/repair/test/auto-bg.test.ts +66 -0
- package/extensions/modules/repair/test/hardening.test.ts +214 -0
- package/extensions/modules/repair/test/settings.test.ts +52 -13
- package/extensions/modules/shells/index.ts +31 -14
- package/extensions/modules/shells/lib/sessions.ts +76 -8
- package/extensions/modules/shells/test/output.test.ts +130 -0
- package/extensions/modules/shells/test/sessions.test.ts +127 -5
- package/extensions/modules/web/lib/pdf.ts +4 -2
- package/extensions/modules/web/test/pdf.test.ts +84 -0
- package/package.json +1 -1
|
@@ -0,0 +1,214 @@
|
|
|
1
|
+
// Regression suite for the 2026-10-07 hardening round (reviewer findings):
|
|
2
|
+
// A1 archive member+range reads, A2 guard × archive-member reads, A4 tar
|
|
3
|
+
// option-injection gate, A6 auto-gen guard rel-path correctness, A9 ascii
|
|
4
|
+
// rename-arrow target paths. index.ts helpers are driven through the real
|
|
5
|
+
// module wiring where practical (guard-selector.test.ts precedent).
|
|
6
|
+
|
|
7
|
+
import assert from "node:assert/strict";
|
|
8
|
+
import { execFileSync } from "node:child_process";
|
|
9
|
+
import { mkdtempSync, mkdirSync, writeFileSync, rmSync } from "node:fs";
|
|
10
|
+
import { mkdtemp, rm, writeFile } from "node:fs/promises";
|
|
11
|
+
import { tmpdir } from "node:os";
|
|
12
|
+
import path from "node:path";
|
|
13
|
+
import { after, before, describe, it } from "node:test";
|
|
14
|
+
import { matchMember, readArchiveMember, archiveKind } from "../lib/read-archive.js";
|
|
15
|
+
import { checkAutoGenerated } from "../lib/auto-generated.js";
|
|
16
|
+
import { applySpecialView } from "../index.js";
|
|
17
|
+
import { parsePatch } from "../lib/patch.js";
|
|
18
|
+
|
|
19
|
+
const dir = mkdtempSync(path.join(tmpdir(), "ceulen-repair-hardening-"));
|
|
20
|
+
after(() => rmSync(dir, { recursive: true, force: true }));
|
|
21
|
+
|
|
22
|
+
// ── A1: member + line ranges ────────────────────────────────────────────────
|
|
23
|
+
|
|
24
|
+
describe("archive member+range (A1)", () => {
|
|
25
|
+
const proj = path.join(dir, "a1");
|
|
26
|
+
const archive = path.join(proj, "pkg.tgz");
|
|
27
|
+
before(() => {
|
|
28
|
+
mkdirSync(proj, { recursive: true });
|
|
29
|
+
writeFileSync(path.join(proj, "src.ts"), "ignored on disk\n");
|
|
30
|
+
execFileSync("tar", ["-czf", archive, "-C", proj, "src.ts"]);
|
|
31
|
+
// Overwrite the MEMBER content so the disk copy can't mask a failure.
|
|
32
|
+
writeFileSync(path.join(dir, "member-body.txt"), "one\ntwo\nthree\nfour\nfive\n");
|
|
33
|
+
execFileSync("tar", ["-czf", archive, "-C", dir, "member-body.txt"]);
|
|
34
|
+
rmSync(path.join(dir, "member-body.txt"));
|
|
35
|
+
});
|
|
36
|
+
|
|
37
|
+
it("pkg.tgz:member:50-80 reads the real member, sliced — not an error", () => {
|
|
38
|
+
const out = applySpecialView("pkg.tgz:member-body.txt:2-3", proj);
|
|
39
|
+
assert.ok(out, "special view triggered");
|
|
40
|
+
assert.match(out!.text, /member-body\.txt/);
|
|
41
|
+
assert.match(out!.text, /two/);
|
|
42
|
+
assert.match(out!.text, /three/);
|
|
43
|
+
assert.doesNotMatch(out!.text, /four|five/);
|
|
44
|
+
assert.doesNotMatch(out!.text, /no member matching/);
|
|
45
|
+
});
|
|
46
|
+
|
|
47
|
+
it("member without a range is unchanged", () => {
|
|
48
|
+
const out = applySpecialView("pkg.tgz:member-body.txt", proj);
|
|
49
|
+
assert.ok(out);
|
|
50
|
+
assert.match(out!.text, /one/);
|
|
51
|
+
assert.match(out!.text, /five/);
|
|
52
|
+
});
|
|
53
|
+
|
|
54
|
+
it("a bare-number member does NOT peel as a selector", () => {
|
|
55
|
+
// A member literally named "123" parses as a line selector — it must stay
|
|
56
|
+
// whole for the member lookup (no phantom "" member + sliced error text).
|
|
57
|
+
writeFileSync(path.join(dir, "123"), "numeric member\n");
|
|
58
|
+
execFileSync("tar", ["-czf", path.join(proj, "nums.tgz"), "-C", dir, "123"]);
|
|
59
|
+
const out = applySpecialView(`nums.tgz:123`, proj);
|
|
60
|
+
assert.ok(out);
|
|
61
|
+
assert.match(out!.text, /123/);
|
|
62
|
+
assert.match(out!.text, /numeric member/);
|
|
63
|
+
rmSync(path.join(dir, "123"));
|
|
64
|
+
});
|
|
65
|
+
|
|
66
|
+
it("tail selector :-2 works over the member body", () => {
|
|
67
|
+
const out = applySpecialView("pkg.tgz:member-body.txt:-2", proj);
|
|
68
|
+
assert.ok(out);
|
|
69
|
+
assert.match(out!.text, /four/);
|
|
70
|
+
assert.match(out!.text, /five/);
|
|
71
|
+
assert.doesNotMatch(out!.text, /one\n|two\n|three\n/);
|
|
72
|
+
});
|
|
73
|
+
});
|
|
74
|
+
|
|
75
|
+
// ── A2: guard × archive-member reads ────────────────────────────────────────
|
|
76
|
+
|
|
77
|
+
describe("read guard × archive-member reads (A2)", () => {
|
|
78
|
+
it("pkg.tgz:src/x.ts and pkg.tgz:src/x.ts:50-80 pass the guard when the archive exists", async () => {
|
|
79
|
+
const { default: repairModule } = await import("../index.js");
|
|
80
|
+
const proj = await mkdtemp(path.join(tmpdir(), "repair-guard-arch-"));
|
|
81
|
+
const archive = path.join(proj, "pkg.tgz");
|
|
82
|
+
writeFileSync(path.join(proj, "x.ts"), "member\n");
|
|
83
|
+
execFileSync("tar", ["-czf", archive, "-C", proj, "x.ts"]);
|
|
84
|
+
const handlers: Record<string, (event: unknown, ctx: unknown) => unknown> = {};
|
|
85
|
+
const orig = process.env.PI_CODING_AGENT_DIR;
|
|
86
|
+
process.env.PI_CODING_AGENT_DIR = proj;
|
|
87
|
+
try {
|
|
88
|
+
repairModule({
|
|
89
|
+
on: (event: string, handler: (event: unknown, ctx: unknown) => unknown) => { handlers[event] = handler; },
|
|
90
|
+
registerTool: () => {},
|
|
91
|
+
registerCommand: () => {},
|
|
92
|
+
} as never);
|
|
93
|
+
const call = (p: string) =>
|
|
94
|
+
handlers.tool_call!({ toolName: "read", input: { path: p } }, { cwd: proj }) as { block: boolean } | undefined;
|
|
95
|
+
assert.equal(await call("pkg.tgz:x.ts"), undefined, "member read not blocked");
|
|
96
|
+
assert.equal(await call("pkg.tgz:x.ts:1-2"), undefined, "member+range read not blocked");
|
|
97
|
+
assert.equal(await call("pkg.tgz:missing.ts"), undefined, "missing member in an EXISTING archive still passes (the archive view handles it)");
|
|
98
|
+
const blocked = await call("missing.tgz:x.ts") as { block: boolean } | undefined;
|
|
99
|
+
assert.ok(blocked?.block, "a missing .ts-shaped path still blocks");
|
|
100
|
+
} finally {
|
|
101
|
+
if (orig === undefined) delete process.env.PI_CODING_AGENT_DIR;
|
|
102
|
+
else process.env.PI_CODING_AGENT_DIR = orig;
|
|
103
|
+
await rm(proj, { recursive: true, force: true });
|
|
104
|
+
}
|
|
105
|
+
});
|
|
106
|
+
});
|
|
107
|
+
|
|
108
|
+
// ── A4: tar option-injection gate ───────────────────────────────────────────
|
|
109
|
+
|
|
110
|
+
describe("archive option-injection gate (A4)", () => {
|
|
111
|
+
it("matchMember still matches normal members", () => {
|
|
112
|
+
assert.deepEqual(matchMember(["a.ts", "b.ts"], "a.ts"), { member: "a.ts", via: "exact" });
|
|
113
|
+
});
|
|
114
|
+
|
|
115
|
+
it("readArchiveMember refuses a dash-leading member before any spawn", () => {
|
|
116
|
+
// Build an archive with a member named "--checkpoint-action=exec=evil".
|
|
117
|
+
// bsdtar/GNU tar only treats it as an option during EXTRACTION with
|
|
118
|
+
// positional args — exactly what extractMember does — so listing it works.
|
|
119
|
+
const evilDir = path.join(dir, "a4");
|
|
120
|
+
mkdirSync(evilDir, { recursive: true });
|
|
121
|
+
const archive = path.join(evilDir, "evil.tgz");
|
|
122
|
+
const staging = path.join(evilDir, "stage");
|
|
123
|
+
mkdirSync(staging, { recursive: true });
|
|
124
|
+
writeFileSync(path.join(staging, "safe.txt"), "safe\n");
|
|
125
|
+
execFileSync("tar", ["-czf", path.join(evilDir, "plain.tgz"), "-C", staging, "safe.txt"]);
|
|
126
|
+
// Craft the dash member via a tar file listing manipulation: rename inside
|
|
127
|
+
// a ustar header is fiddly — instead create the file and rely on tar -C.
|
|
128
|
+
const evilFile = path.join(staging, "--checkpoint-action=exec=echo pwned");
|
|
129
|
+
writeFileSync(evilFile, "evil\n");
|
|
130
|
+
execFileSync("tar", ["-czf", archive, "-C", staging, "--", "--checkpoint-action=exec=echo pwned", "safe.txt"]);
|
|
131
|
+
const members = ["--checkpoint-action=exec=echo pwned", "safe.txt"];
|
|
132
|
+
assert.equal(archiveKind(archive), "tgz");
|
|
133
|
+
const out = readArchiveMember(archive, "tgz", "--checkpoint-action=exec=echo pwned", "evil.tgz");
|
|
134
|
+
assert.match(out.text, /refusing member/);
|
|
135
|
+
assert.match(out.text, /parsed as tar\/unzip options/);
|
|
136
|
+
void members;
|
|
137
|
+
});
|
|
138
|
+
|
|
139
|
+
it("a dash-leading request through the matcher surfaces the gate", () => {
|
|
140
|
+
const out = readArchiveMember(path.join(dir, "a4", "plain.tgz"), "tgz", "--checkpoint-action=exec=echo pwned", "p.tgz");
|
|
141
|
+
assert.match(out.text, /refusing member|no member matching/);
|
|
142
|
+
});
|
|
143
|
+
});
|
|
144
|
+
|
|
145
|
+
// ── A6: auto-gen guard rel path ─────────────────────────────────────────────
|
|
146
|
+
|
|
147
|
+
describe("auto-generated rel-path correctness (A6)", () => {
|
|
148
|
+
const cwd = path.join(dir, "a6", "proj");
|
|
149
|
+
before(() => mkdirSync(path.join(cwd, "dist"), { recursive: true }));
|
|
150
|
+
|
|
151
|
+
it("in-cwd absolute paths still match", () => {
|
|
152
|
+
assert.ok(checkAutoGenerated(path.join(cwd, "package-lock.json"), cwd));
|
|
153
|
+
assert.ok(checkAutoGenerated(path.join(cwd, "dist", "x.js"), cwd));
|
|
154
|
+
});
|
|
155
|
+
|
|
156
|
+
it("an absolute path OUTSIDE cwd matches nothing (no garbage rel)", () => {
|
|
157
|
+
const outside = path.resolve(cwd, "../elsewhere/dist/x.js");
|
|
158
|
+
assert.ok(!outside.startsWith(cwd));
|
|
159
|
+
assert.equal(checkAutoGenerated(outside, cwd), null);
|
|
160
|
+
});
|
|
161
|
+
|
|
162
|
+
it("cwd itself resolves to '.' and matches nothing", () => {
|
|
163
|
+
assert.equal(checkAutoGenerated(cwd, cwd), null);
|
|
164
|
+
});
|
|
165
|
+
|
|
166
|
+
it("relative inputs are matched as given", () => {
|
|
167
|
+
assert.ok(checkAutoGenerated("package-lock.json", cwd));
|
|
168
|
+
assert.equal(checkAutoGenerated("src/app.ts", cwd), null);
|
|
169
|
+
});
|
|
170
|
+
});
|
|
171
|
+
|
|
172
|
+
// ── A9: ascii rename arrow in patch target paths ────────────────────────────
|
|
173
|
+
|
|
174
|
+
describe("patch rename arrows (A9)", () => {
|
|
175
|
+
it("parsePatch accepts both arrows (lib contract)", () => {
|
|
176
|
+
assert.equal(parsePatch("*** Update File: a.ts → b.ts\n*** End Patch").ops[0]!.movePath, "b.ts");
|
|
177
|
+
assert.equal(parsePatch("*** Update File: a.ts -> b.ts\n*** End Patch").ops[0]!.movePath, "b.ts");
|
|
178
|
+
});
|
|
179
|
+
|
|
180
|
+
it("the guard/mtime target parser yields the SOURCE path for both arrows", async () => {
|
|
181
|
+
// parsePatchTargetPaths is module-private; drive it through the wrapper:
|
|
182
|
+
// an auto-gen-guarded RENAME with the ascii arrow must be refused because
|
|
183
|
+
// the SOURCE (a lockfile) is the file being touched.
|
|
184
|
+
const { default: repairModule } = await import("../index.js");
|
|
185
|
+
const proj = await mkdtemp(path.join(tmpdir(), "repair-arrow-"));
|
|
186
|
+
const orig = process.env.PI_CODING_AGENT_DIR;
|
|
187
|
+
process.env.PI_CODING_AGENT_DIR = proj;
|
|
188
|
+
const tools: any[] = [];
|
|
189
|
+
try {
|
|
190
|
+
repairModule({
|
|
191
|
+
on: () => {},
|
|
192
|
+
registerTool: (def: any) => tools.push(def),
|
|
193
|
+
registerCommand: () => {},
|
|
194
|
+
} as never);
|
|
195
|
+
const applyPatch = tools.find((t) => t.name === "apply_patch");
|
|
196
|
+
assert.ok(applyPatch, "apply_patch registered");
|
|
197
|
+
for (const arrow of ["→", "->"]) {
|
|
198
|
+
const res = await applyPatch.execute(
|
|
199
|
+
"t1",
|
|
200
|
+
{ patch: `*** Begin Patch\n*** Update File: package-lock.json ${arrow} package-lock2.json\n@@ x\n-y\n+z\n*** End Patch` },
|
|
201
|
+
undefined,
|
|
202
|
+
undefined,
|
|
203
|
+
{ cwd: proj },
|
|
204
|
+
);
|
|
205
|
+
assert.equal(res.isError, true, `ascii arrow: rename of a lockfile refused (${arrow})`);
|
|
206
|
+
assert.match(res.content[0].text, /auto-generated/);
|
|
207
|
+
}
|
|
208
|
+
} finally {
|
|
209
|
+
if (orig === undefined) delete process.env.PI_CODING_AGENT_DIR;
|
|
210
|
+
else process.env.PI_CODING_AGENT_DIR = orig;
|
|
211
|
+
await rm(proj, { recursive: true, force: true });
|
|
212
|
+
}
|
|
213
|
+
});
|
|
214
|
+
});
|
|
@@ -7,7 +7,6 @@ import { after, beforeEach, describe, it } from "node:test";
|
|
|
7
7
|
import { mkdtemp, mkdir, readFile, rm, writeFile } from "node:fs/promises";
|
|
8
8
|
import { tmpdir } from "node:os";
|
|
9
9
|
import { join } from "node:path";
|
|
10
|
-
import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
11
10
|
import {
|
|
12
11
|
DEFAULT_REPAIR_SETTINGS,
|
|
13
12
|
projectShadow,
|
|
@@ -29,14 +28,17 @@ async function tempDir(): Promise<string> {
|
|
|
29
28
|
return dir;
|
|
30
29
|
}
|
|
31
30
|
|
|
32
|
-
|
|
33
|
-
|
|
31
|
+
/** The settings reader resolves trust via lib/registry isProjectTrusted —
|
|
32
|
+
* <agentDir>/trust.json. Write the trust entry instead of a ctx stub. */
|
|
33
|
+
async function setProjectTrust(trusted: boolean): Promise<void> {
|
|
34
|
+
await writeFile(join(agentDir, "trust.json"), JSON.stringify({ [cwd]: trusted }));
|
|
34
35
|
}
|
|
35
36
|
|
|
36
37
|
beforeEach(async () => {
|
|
37
38
|
agentDir = await tempDir();
|
|
38
39
|
cwd = await tempDir();
|
|
39
40
|
process.env.PI_CODING_AGENT_DIR = agentDir;
|
|
41
|
+
await setProjectTrust(true);
|
|
40
42
|
});
|
|
41
43
|
|
|
42
44
|
after(async () => {
|
|
@@ -56,12 +58,12 @@ async function writeProject(cwdPath: string, repair: unknown): Promise<void> {
|
|
|
56
58
|
|
|
57
59
|
describe("readRepairSettings", () => {
|
|
58
60
|
it("defaults: repair on, guards on, autoBg off @120s", () => {
|
|
59
|
-
assert.deepEqual(readRepairSettings(
|
|
61
|
+
assert.deepEqual(readRepairSettings(cwd), DEFAULT_REPAIR_SETTINGS);
|
|
60
62
|
});
|
|
61
63
|
|
|
62
64
|
it("reads the global agent-dir `repair` section", async () => {
|
|
63
65
|
await writeGlobal({ arguments: false, autoBg: true, autoBgSecs: 30 });
|
|
64
|
-
const s = readRepairSettings(
|
|
66
|
+
const s = readRepairSettings(cwd);
|
|
65
67
|
assert.equal(s.arguments, false);
|
|
66
68
|
assert.equal(s.autoBg, true);
|
|
67
69
|
assert.equal(s.autoBgSecs, 30);
|
|
@@ -71,7 +73,7 @@ describe("readRepairSettings", () => {
|
|
|
71
73
|
it("trusted project file overrides the global layer field-wise", async () => {
|
|
72
74
|
await writeGlobal({ guards: false, autoBgSecs: 30 });
|
|
73
75
|
await writeProject(cwd, { guards: true, autoBgSecs: 45, autoBg: true });
|
|
74
|
-
const s = readRepairSettings(
|
|
76
|
+
const s = readRepairSettings(cwd);
|
|
75
77
|
assert.equal(s.guards, true, "project wins");
|
|
76
78
|
assert.equal(s.autoBgSecs, 45, "project wins");
|
|
77
79
|
assert.equal(s.autoBg, true, "project-only key");
|
|
@@ -80,29 +82,36 @@ describe("readRepairSettings", () => {
|
|
|
80
82
|
it("an UNTRUSTED project file is ignored entirely", async () => {
|
|
81
83
|
await writeGlobal({ guards: false });
|
|
82
84
|
await writeProject(cwd, { guards: true, autoBg: true });
|
|
83
|
-
|
|
85
|
+
await setProjectTrust(false);
|
|
86
|
+
const s = readRepairSettings(cwd);
|
|
84
87
|
assert.equal(s.guards, false, "global value survives an untrusted project");
|
|
85
88
|
assert.equal(s.autoBg, false);
|
|
89
|
+
await setProjectTrust(true); // restore for the later suites
|
|
90
|
+
});
|
|
91
|
+
|
|
92
|
+
it("no cwd argument → global layer only (ctx-less callers)", async () => {
|
|
93
|
+
await writeProject(cwd, { autoBgSecs: 45 });
|
|
94
|
+
assert.equal(readRepairSettings().autoBgSecs, 120, "project layer skipped without cwd");
|
|
86
95
|
});
|
|
87
96
|
|
|
88
97
|
it("clamps autoBgSecs: fractional floors to ≥1, garbage falls back", async () => {
|
|
89
98
|
await writeGlobal({ autoBgSecs: 0.5 });
|
|
90
|
-
assert.equal(readRepairSettings(
|
|
99
|
+
assert.equal(readRepairSettings(cwd).autoBgSecs, 1, "0.5 → floor 0 → clamped to 1");
|
|
91
100
|
await writeGlobal({ autoBgSecs: -10 });
|
|
92
|
-
assert.equal(readRepairSettings(
|
|
101
|
+
assert.equal(readRepairSettings(cwd).autoBgSecs, 1);
|
|
93
102
|
await writeGlobal({ autoBgSecs: "abc" });
|
|
94
|
-
assert.equal(readRepairSettings(
|
|
103
|
+
assert.equal(readRepairSettings(cwd).autoBgSecs, 120, "non-number → default");
|
|
95
104
|
await writeGlobal({ autoBgSecs: 30.9 });
|
|
96
|
-
assert.equal(readRepairSettings(
|
|
105
|
+
assert.equal(readRepairSettings(cwd).autoBgSecs, 30);
|
|
97
106
|
});
|
|
98
107
|
|
|
99
108
|
it("ignores wrong-typed booleans and a corrupt file", async () => {
|
|
100
109
|
await writeGlobal({ arguments: "yes", guards: 0 });
|
|
101
|
-
let s = readRepairSettings(
|
|
110
|
+
let s = readRepairSettings(cwd);
|
|
102
111
|
assert.equal(s.arguments, true);
|
|
103
112
|
assert.equal(s.guards, true);
|
|
104
113
|
await writeFile(settingsPath(), "{ not json");
|
|
105
|
-
s = readRepairSettings(
|
|
114
|
+
s = readRepairSettings(cwd);
|
|
106
115
|
assert.deepEqual(s, DEFAULT_REPAIR_SETTINGS);
|
|
107
116
|
});
|
|
108
117
|
});
|
|
@@ -133,6 +142,36 @@ describe("projectShadow", () => {
|
|
|
133
142
|
});
|
|
134
143
|
});
|
|
135
144
|
|
|
145
|
+
describe("tool_call honors the trusted-project layer (A5 e2e)", () => {
|
|
146
|
+
it("project autoGenGuard:false blocks a guarded write through the REAL wrapped tool", async () => {
|
|
147
|
+
await writeGlobal({}); // global layer silent
|
|
148
|
+
await writeProject(cwd, { autoGenGuard: false });
|
|
149
|
+
const { wrapToolDefinition } = await import("../index.js");
|
|
150
|
+
const { createWriteToolDefinition } = await import("@earendil-works/pi-coding-agent");
|
|
151
|
+
const wrapped = wrapToolDefinition(createWriteToolDefinition(cwd), createWriteToolDefinition, () => false, () => {});
|
|
152
|
+
const res: any = await wrapped.execute("t1", { path: join(cwd, "package-lock.json"), content: "{}" }, undefined, undefined, { cwd });
|
|
153
|
+
assert.equal(res.isError, undefined, "project layer OFF → guard must NOT fire, write lands");
|
|
154
|
+
assert.match(await readFile(join(cwd, "package-lock.json"), "utf8"), /\{\}/);
|
|
155
|
+
// And with the project layer silent again, the same write is refused.
|
|
156
|
+
await rm(join(cwd, ".pi"), { recursive: true, force: true });
|
|
157
|
+
const res2: any = await wrapped.execute("t2", { path: join(cwd, "package-lock.json"), content: "{}" }, undefined, undefined, { cwd });
|
|
158
|
+
assert.equal(res2.isError, true);
|
|
159
|
+
assert.match(res2.content[0].text, /auto-generated/);
|
|
160
|
+
});
|
|
161
|
+
|
|
162
|
+
it("an UNTRUSTED project file never reaches the guard", async () => {
|
|
163
|
+
await setProjectTrust(false);
|
|
164
|
+
await writeGlobal({});
|
|
165
|
+
await writeProject(cwd, { autoGenGuard: false });
|
|
166
|
+
const { wrapToolDefinition } = await import("../index.js");
|
|
167
|
+
const { createWriteToolDefinition } = await import("@earendil-works/pi-coding-agent");
|
|
168
|
+
const wrapped = wrapToolDefinition(createWriteToolDefinition(cwd), createWriteToolDefinition, () => false, () => {});
|
|
169
|
+
const res: any = await wrapped.execute("t3", { path: join(cwd, "yarn.lock"), content: "{}" }, undefined, undefined, { cwd });
|
|
170
|
+
assert.equal(res.isError, true);
|
|
171
|
+
assert.match(res.content[0].text, /auto-generated/, "untrusted project layer ignored — global/default governs");
|
|
172
|
+
});
|
|
173
|
+
});
|
|
174
|
+
|
|
136
175
|
describe("buildRepairGroups (panel contract)", () => {
|
|
137
176
|
it("renders the six repair.* rows on the Tools tab with the documented defaults", () => {
|
|
138
177
|
const groups = buildRepairGroups({ ...DEFAULT_REPAIR_SETTINGS });
|
|
@@ -66,20 +66,30 @@ function renderOutput(session: ShellSession, params: Record<string, unknown>): s
|
|
|
66
66
|
const since = params.since === "last" ? "last" : "start";
|
|
67
67
|
const out: string[] = [];
|
|
68
68
|
let truncated = false;
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
69
|
+
// Each stream slices by ITS OWN cursor — one shared offset went stale on
|
|
70
|
+
// the shorter stream (stderr duplicated when stdout was longer, invisible
|
|
71
|
+
// when shorter). Cursors are lifetime line counts, not array indices:
|
|
72
|
+
// a ring-cap trip SHRINKS the visible array, which strands an index
|
|
73
|
+
// cursor above it forever (permanent "no new output yet" blackout).
|
|
74
|
+
const cursorOf = { stdout: "lastStdoutOffset", stderr: "lastStderrOffset" } as const;
|
|
75
|
+
for (const stream of ["stdout", "stderr"] as const) {
|
|
76
|
+
const buf = session[stream];
|
|
77
|
+
if (since === "last") {
|
|
78
|
+
const fresh = buf.linesSince(session[cursorOf[stream]]);
|
|
79
|
+
if (fresh.length === 0) continue;
|
|
80
|
+
const shown = fresh.slice(-max);
|
|
81
|
+
if (fresh.length > shown.length) truncated = true;
|
|
82
|
+
out.push(`── ${stream} (new) ──`, ...shown);
|
|
83
|
+
// Advance ONLY on since:"last" reads, and only forward.
|
|
84
|
+
session[cursorOf[stream]] = Math.max(session[cursorOf[stream]], buf.lifetimeLines());
|
|
85
|
+
} else {
|
|
86
|
+
const all = buf.lines();
|
|
87
|
+
if (all.length === 0) continue;
|
|
88
|
+
const shown = all.slice(-max);
|
|
89
|
+
if (all.length > shown.length) truncated = true;
|
|
90
|
+
out.push(`── ${stream} ──`, ...shown);
|
|
91
|
+
}
|
|
80
92
|
}
|
|
81
|
-
// Advance the cursor ONLY on since:"last" reads.
|
|
82
|
-
if (since === "last") session.lastOutputOffset = Math.max(session.stdout.lines().length, session.lastOutputOffset);
|
|
83
93
|
if (out.length === 0) return `${session.id}: no ${since === "last" ? "new " : ""}output yet`;
|
|
84
94
|
const totalLines = session.stdout.lines().length + session.stderr.lines().length;
|
|
85
95
|
out.push(`── total ${totalLines} line(s)${truncated || session.stdout.isTruncated() || session.stderr.isTruncated() ? ", buffer truncated" : ""} ──`);
|
|
@@ -88,10 +98,11 @@ function renderOutput(session: ShellSession, params: Record<string, unknown>): s
|
|
|
88
98
|
|
|
89
99
|
export default function shellsModule(pi: ExtensionAPI): void {
|
|
90
100
|
const store = new SessionStore();
|
|
101
|
+
(shellsModule as unknown as { __storeForTests?: SessionStore }).__storeForTests = store;
|
|
91
102
|
|
|
92
103
|
pi.on("session_start", () => {
|
|
93
104
|
// A fresh session can't reach children from a replaced one.
|
|
94
|
-
store.
|
|
105
|
+
store.clear(); // killAll already ran on shutdown; plain clear
|
|
95
106
|
});
|
|
96
107
|
|
|
97
108
|
pi.on("session_shutdown", () => {
|
|
@@ -208,3 +219,9 @@ export default function shellsModule(pi: ExtensionAPI): void {
|
|
|
208
219
|
},
|
|
209
220
|
});
|
|
210
221
|
}
|
|
222
|
+
|
|
223
|
+
// ponytail: test seam — a constructor-injected store would be the upgrade
|
|
224
|
+
// path if non-test code ever needs it; one module-scope slot, last load wins.
|
|
225
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
226
|
+
const shellsModuleAny = shellsModule as unknown as { __storeForTests?: SessionStore };
|
|
227
|
+
export const getStoreForTests = (): SessionStore | undefined => shellsModuleAny.__storeForTests;
|
|
@@ -39,6 +39,8 @@ export class RingBuffer {
|
|
|
39
39
|
private partial = ""; // unterminated tail not yet a line
|
|
40
40
|
private totalBytes = 0;
|
|
41
41
|
private lifetimeBytes = 0;
|
|
42
|
+
private lifetimeLineCount = 0; // complete lines ever pushed — never shrinks
|
|
43
|
+
private tailStart = 0; // once capped: index of the first tail line (the marker sits at tailStart - 1)
|
|
42
44
|
private capped = false;
|
|
43
45
|
|
|
44
46
|
push(chunk: string): void {
|
|
@@ -47,6 +49,7 @@ export class RingBuffer {
|
|
|
47
49
|
this.partial = "";
|
|
48
50
|
this.partial = parts.pop() ?? "";
|
|
49
51
|
for (const line of parts) this.linesArr.push(line);
|
|
52
|
+
this.lifetimeLineCount += parts.length;
|
|
50
53
|
this.totalBytes += Buffer.byteLength(chunk, "utf8");
|
|
51
54
|
this.lifetimeBytes += Buffer.byteLength(chunk, "utf8");
|
|
52
55
|
if (this.totalBytes > TOTAL_BYTES) this.enforceCap();
|
|
@@ -82,6 +85,7 @@ export class RingBuffer {
|
|
|
82
85
|
}
|
|
83
86
|
const droppedBytes = lineBytes(rest);
|
|
84
87
|
this.linesArr = [...head, truncationMarker(Math.max(droppedBytes, 1)), ...tail];
|
|
88
|
+
this.tailStart = head.length + 1;
|
|
85
89
|
this.totalBytes = lineBytes(this.linesArr);
|
|
86
90
|
}
|
|
87
91
|
|
|
@@ -90,6 +94,31 @@ export class RingBuffer {
|
|
|
90
94
|
return this.capAware();
|
|
91
95
|
}
|
|
92
96
|
|
|
97
|
+
/** Complete lines ever pushed (lifetime — immune to cap shrinks). */
|
|
98
|
+
lifetimeLines(): number {
|
|
99
|
+
return this.lifetimeLineCount;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/**
|
|
103
|
+
* Visible lines pushed after lifetime line `seen` — the since:"last"
|
|
104
|
+
* cursor read. The cursor lives in lifetime space, so a cap shrink can
|
|
105
|
+
* never strand it above the window: unseen lines are the NEWEST ones,
|
|
106
|
+
* which the tail region (after the marker) always holds. When more lines
|
|
107
|
+
* arrived than the window kept, the whole recent region + marker returns
|
|
108
|
+
* instead of nothing; lines the cap dropped are simply gone.
|
|
109
|
+
*/
|
|
110
|
+
linesSince(seen: number): string[] {
|
|
111
|
+
const behind = this.lifetimeLineCount - Math.max(0, seen);
|
|
112
|
+
if (behind <= 0) return [];
|
|
113
|
+
const all = this.capAware();
|
|
114
|
+
const hasPartial = this.partial !== "";
|
|
115
|
+
const completeCount = all.length - (hasPartial ? 1 : 0);
|
|
116
|
+
const floor = this.capped ? this.tailStart - 1 : 0; // never re-show the dropped middle / marker
|
|
117
|
+
const start = Math.max(floor, completeCount - behind);
|
|
118
|
+
const fresh = all.slice(start, completeCount);
|
|
119
|
+
return hasPartial ? [...fresh, this.partial] : fresh;
|
|
120
|
+
}
|
|
121
|
+
|
|
93
122
|
/** Bytes written to this stream over its lifetime (pre-truncation). */
|
|
94
123
|
totalWritten(): number {
|
|
95
124
|
return this.lifetimeBytes;
|
|
@@ -106,7 +135,9 @@ export class RingBuffer {
|
|
|
106
135
|
}
|
|
107
136
|
|
|
108
137
|
private capAware(): string[] {
|
|
109
|
-
|
|
138
|
+
// The partial survives capping too: spinner/progress output that hasn't
|
|
139
|
+
// got its newline yet must stay visible once the head+tail split is on.
|
|
140
|
+
if (this.capped) return this.partial ? [...this.linesArr, this.partial] : [...this.linesArr];
|
|
110
141
|
const out = this.partial ? [...this.linesArr, this.partial] : [...this.linesArr];
|
|
111
142
|
return out;
|
|
112
143
|
}
|
|
@@ -124,8 +155,9 @@ export interface ShellSession {
|
|
|
124
155
|
exitCode?: number | null;
|
|
125
156
|
stdout: RingBuffer;
|
|
126
157
|
stderr: RingBuffer;
|
|
127
|
-
/**
|
|
128
|
-
|
|
158
|
+
/** Per-stream output cursors for `since: "last"` — lines already returned by an output call. */
|
|
159
|
+
lastStdoutOffset: number;
|
|
160
|
+
lastStderrOffset: number;
|
|
129
161
|
}
|
|
130
162
|
|
|
131
163
|
// ---------------------------------------------------------------------------
|
|
@@ -166,11 +198,17 @@ export function listSessionsLine(s: ShellSession): string {
|
|
|
166
198
|
export function resolveSession(store: SessionStore, idOrName: string): ShellSession {
|
|
167
199
|
const byId = store.get(idOrName);
|
|
168
200
|
if (byId) return byId;
|
|
169
|
-
|
|
170
|
-
|
|
201
|
+
// Prefer LIVE matches: restarting a session under the same name must not
|
|
202
|
+
// make the name ambiguous just because an old exited one lingers. Only
|
|
203
|
+
// when NO live match exists fall back to the full match list (original
|
|
204
|
+
// ambiguity semantics over exited sessions).
|
|
205
|
+
const all = store.list().filter((s) => s.name === idOrName);
|
|
206
|
+
const live = all.filter((s) => s.exitedAt === undefined);
|
|
207
|
+
const candidates = live.length > 0 ? live : all;
|
|
208
|
+
if (candidates.length === 1) return candidates[0]!;
|
|
171
209
|
const listing = store.list().map(listSessionsLine).join("\n") || "(no sessions)";
|
|
172
|
-
if (
|
|
173
|
-
throw new Error(`session name '${idOrName}' is ambiguous (${
|
|
210
|
+
if (candidates.length > 1) {
|
|
211
|
+
throw new Error(`session name '${idOrName}' is ambiguous (${candidates.length} sessions):\n${listing}`);
|
|
174
212
|
}
|
|
175
213
|
throw new Error(`no session '${idOrName}'. Active sessions:\n${listing}`);
|
|
176
214
|
}
|
|
@@ -214,6 +252,11 @@ export class SessionStore {
|
|
|
214
252
|
this.map.delete(id);
|
|
215
253
|
}
|
|
216
254
|
|
|
255
|
+
/** Drop every session (session_start: a fresh session can't reach old children). */
|
|
256
|
+
clear(): void {
|
|
257
|
+
this.map.clear();
|
|
258
|
+
}
|
|
259
|
+
|
|
217
260
|
/** Remove the OLDEST exited session if more than 5 have accumulated. */
|
|
218
261
|
evictOldestExited(): ShellSession | undefined {
|
|
219
262
|
const exited = this.list().filter((s) => s.exitedAt !== undefined);
|
|
@@ -246,6 +289,16 @@ function signalProcessGroup(s: ShellSession, signal: NodeJS.Signals): void {
|
|
|
246
289
|
// detached: true → the child leads its own process group; -pid signals the
|
|
247
290
|
// whole group (the shell AND any grandchildren). Fall back to child.kill
|
|
248
291
|
// when the group is gone (already reaped) or the call fails (Windows).
|
|
292
|
+
// pid 0 (spawn never succeeded) MUST NOT reach process.kill: kill(-0) ==
|
|
293
|
+
// kill(0) == SIGTERM for every process in pi's OWN group — host death.
|
|
294
|
+
if (s.pid <= 0) {
|
|
295
|
+
try {
|
|
296
|
+
s.child.kill(signal);
|
|
297
|
+
} catch {
|
|
298
|
+
// spawn never succeeded / already dead — exit handling deals with it
|
|
299
|
+
}
|
|
300
|
+
return;
|
|
301
|
+
}
|
|
249
302
|
try {
|
|
250
303
|
process.kill(-s.pid, signal);
|
|
251
304
|
} catch {
|
|
@@ -307,7 +360,8 @@ export function createSession(
|
|
|
307
360
|
startedAt: Date.now(),
|
|
308
361
|
stdout: new RingBuffer(),
|
|
309
362
|
stderr: new RingBuffer(),
|
|
310
|
-
|
|
363
|
+
lastStdoutOffset: 0,
|
|
364
|
+
lastStderrOffset: 0,
|
|
311
365
|
} as ShellSession); // placeholder so the live-cap check sees THIS session too
|
|
312
366
|
const placeholder = store.list().at(-1)!;
|
|
313
367
|
let child: ChildProcess;
|
|
@@ -333,11 +387,25 @@ export function createSession(
|
|
|
333
387
|
store.replace(placeholder.id, session);
|
|
334
388
|
child.stdout?.on("data", (d: Buffer) => session.stdout.push(d.toString()));
|
|
335
389
|
child.stderr?.on("data", (d: Buffer) => session.stderr.push(d.toString()));
|
|
390
|
+
// A stdin write that races child exit EPIPEs; with no listener Node turns
|
|
391
|
+
// that into an uncaughtException killing pi. Contain and record instead.
|
|
392
|
+
child.stdin?.on("error", () => {
|
|
393
|
+
session.stderr.push("[shells] stdin write failed (process exited)");
|
|
394
|
+
});
|
|
336
395
|
child.on("exit", (code) => {
|
|
337
396
|
session.exitedAt = Date.now();
|
|
338
397
|
session.exitCode = code;
|
|
339
398
|
});
|
|
340
399
|
child.on("error", (err: Error) => {
|
|
400
|
+
// Spawn failure (ENOENT cwd/binary) arrives as 'error' with pid undefined
|
|
401
|
+
// and NO 'exit'. Mark it exited so kill/killAll never signal a pid-0
|
|
402
|
+
// "process group" — which would hit pi's own group. Windows quirk:
|
|
403
|
+
// 'error' can also fire on a LIVE pid-carrying process (kill-EPIPE),
|
|
404
|
+
// so only the never-spawned case (no pid) counts as exit.
|
|
405
|
+
if (child.pid === undefined) {
|
|
406
|
+
session.exitedAt = Date.now();
|
|
407
|
+
session.exitCode = null;
|
|
408
|
+
}
|
|
341
409
|
session.stderr.push(`[shells] spawn error: ${err.message}`);
|
|
342
410
|
});
|
|
343
411
|
return session;
|