SaylorTwift HF Staff commited on
Commit
98077a8
·
verified ·
1 Parent(s): e49817d

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. packages/agent/docs/mobile-handoff/02-plugins/02-sandbox/README.md +162 -0
  2. packages/agent/docs/mobile-handoff/02-plugins/02-sandbox/package.json +13 -0
  3. packages/agent/docs/mobile-handoff/02-plugins/02-sandbox/src/bench.ts +48 -0
  4. packages/agent/docs/mobile-handoff/02-plugins/02-sandbox/src/demo-facet.ts +22 -0
  5. packages/agent/docs/mobile-handoff/02-plugins/02-sandbox/src/escape-audit.ts +63 -0
  6. packages/agent/docs/mobile-handoff/02-plugins/02-sandbox/src/facet-example.js +42 -0
  7. packages/agent/docs/mobile-handoff/02-plugins/02-sandbox/src/iso-vs-ctx.ts +34 -0
  8. packages/agent/docs/mobile-handoff/02-plugins/02-sandbox/src/leak.ts +27 -0
  9. packages/agent/docs/mobile-handoff/02-plugins/02-sandbox/src/markdown-bundle.js +0 -0
  10. packages/agent/docs/mobile-handoff/02-plugins/02-sandbox/src/membrane.ts +197 -0
  11. packages/agent/docs/mobile-handoff/02-plugins/02-sandbox/src/property-test.ts +137 -0
  12. packages/agent/test/harness/adaptive-publisher.test.ts +76 -0
  13. packages/agent/test/harness/branch-summarization.test.ts +71 -0
  14. packages/agent/test/harness/branch.test.ts +110 -0
  15. packages/agent/test/harness/compaction.test.ts +827 -0
  16. packages/agent/test/harness/context.test.ts +29 -0
  17. packages/agent/test/harness/execution-assistant.test.ts +343 -0
  18. packages/agent/test/harness/execution-primitives.test.ts +670 -0
  19. packages/agent/test/harness/execution-tools.test.ts +247 -0
  20. packages/agent/test/harness/gating-storage.test.ts +110 -0
  21. packages/agent/test/harness/instrumented-storage.test.ts +190 -0
  22. packages/agent/test/harness/jsonl-io.test.ts +108 -0
  23. packages/agent/test/harness/jsonl-session-repo-conformance.test.ts +65 -0
  24. packages/agent/test/harness/jsonl-session-repo.test.ts +199 -0
  25. packages/agent/test/harness/jsonl-storage-conformance.test.ts +48 -0
  26. packages/agent/test/harness/jsonl-storage.test.ts +248 -0
  27. packages/agent/test/harness/jsonl-v3-migration.test.ts +2013 -0
  28. packages/agent/test/harness/jsonl-v3-stream.test.ts +161 -0
  29. packages/agent/test/harness/memory-conformance.test.ts +101 -0
  30. packages/agent/test/harness/memory-session-repo.test.ts +77 -0
  31. packages/agent/test/harness/memory-storage.test.ts +36 -0
  32. packages/agent/test/harness/mutation-line.test.ts +66 -0
  33. packages/agent/test/harness/nodejs-env.test.ts +706 -0
  34. packages/agent/test/harness/output-capture.test.ts +151 -0
  35. packages/agent/test/harness/resource-formatting.test.ts +24 -0
  36. packages/agent/test/harness/session-context.test.ts +260 -0
  37. packages/agent/test/harness/session-test-utils.ts +20 -0
  38. packages/agent/test/harness/skills.test.ts +150 -0
  39. packages/agent/test/harness/storage-backed-session.test.ts +397 -0
  40. packages/agent/test/harness/system-prompt.test.ts +66 -0
  41. packages/agent/test/harness/telemetry.test.ts +204 -0
  42. packages/agent/test/harness/text-line-reader.test.ts +120 -0
  43. packages/agent/test/harness/tools.test.ts +782 -0
  44. packages/agent/test/harness/truncate.test.ts +178 -0
  45. packages/agent/test/harness/types.test.ts +523 -0
  46. packages/agent/test/harness/values.test.ts +183 -0
  47. packages/agent/test/utils/calculate.ts +40 -0
  48. packages/agent/test/utils/get-current-time.ts +46 -0
  49. packages/agent/test/utils/wait-for-tick.ts +3 -0
  50. packages/ai/src/api/openai-responses.ts +389 -0
packages/agent/docs/mobile-handoff/02-plugins/02-sandbox/README.md ADDED
@@ -0,0 +1,162 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Facet sandbox — isolated-vm
2
+
3
+ **Unmodified pi facet code running in a V8 isolate with no ambient authority.**
4
+ Full JIT, so ~1.8× native rather than the 8–17× a WASM interpreter costs.
5
+
6
+ ```bash
7
+ npm install
8
+ npm run demo # a facet: contributions, components, commands, callbacks
9
+ npm run audit # escape audit — the interesting one
10
+ npm run bench # crossing cost, isolate cost, 300 components
11
+ npm test # 412 property assertions
12
+ ```
13
+
14
+ Node 22+ (`--experimental-strip-types`). See `../facet-sandbox-poc` for the
15
+ QuickJS-WASM equivalent.
16
+
17
+ ## The safety claim, and why it is structural
18
+
19
+ isolated-vm **can** be used unsafely, and that is what `facets.md` §14.2 objected
20
+ to. The footgun is handing the guest a live handle to a host object — via
21
+ `derefInto()`, or by returning a `Reference` from a host call — after which the
22
+ guest walks that object's prototype chain into the host realm.
23
+
24
+ This membrane makes that impossible **by construction, not by care**:
25
+
26
+ 1. `encode()` is the only way a host value reaches the guest, and it is
27
+ `JSON.stringify` with a replacer. **Its output is a string.** A string cannot
28
+ carry a reference.
29
+ 2. Host callables never cross. They become an integer id into `hostTable`, which
30
+ lives entirely host-side. The guest receives a **number**.
31
+ 3. Exactly **one** `Reference` is ever given to the guest — `__invokeRef`, the
32
+ single call-in point.
33
+ 4. `derefInto()` is used exactly once, on the guest's **own** global. No host
34
+ object is ever its argument.
35
+
36
+ The guest's entire view of the host is `{ number, string }`. There is no object
37
+ graph, so there is nothing to walk.
38
+
39
+ ### Audit results (`npm run audit`)
40
+
41
+ ```
42
+ Ambient authority:
43
+ require / process / fetch ["undefined","undefined","undefined"]
44
+ global names visible 64 globals
45
+
46
+ Classic escape ladders:
47
+ Function('return process')() undefined
48
+ constructor walk on host data undefined
49
+
50
+ The isolated-vm Reference footgun:
51
+ __invokeRef.deref() blocked: TypeError ("Cannot dereference
52
+ this from current isolate")
53
+ __invokeRef.copySync() blocked: TypeError
54
+ __invokeRef.getSync('constructor') blocked: TypeError
55
+ derefInto() is callable? inert (object)
56
+ invoke derefInto() result blocked: TypeError
57
+ host globals via derefInto() no host globals
58
+
59
+ Resource bounds:
60
+ spinning guest interrupted after 205ms
61
+ isolate usable afterwards true
62
+ ```
63
+
64
+ One probe gave a **false positive** in a first draft: testing `f.deref === undefined`
65
+ to prove a returned host function is a Proxy rather than a Reference. The
66
+ membrane's proxy returns a proxy for *every* property, so `f.deref` is truthy.
67
+ That is not a leak — calling it routes to `hostFn["deref"]`, which does not exist
68
+ and throws host-side. The audit now calls it instead of checking for absence.
69
+
70
+ ## Performance
71
+
72
+ | | isolated-vm | QuickJS | native |
73
+ | --- | --- | --- | --- |
74
+ | 300 markdown components, small | **70 ms** | 494 ms | ~40 ms |
75
+ | 300 markdown components, typical | **108 ms** | 1118 ms | 64 ms |
76
+ | 300 markdown components, large | **419 ms** | 4260 ms | ~150 ms |
77
+ | 146 KB bundle load | **35 ms** | 104 ms | — |
78
+ | membrane crossing | **4.5 µs** | 7–17 µs | — |
79
+ | per compartment | 1080 KB, 5.5 ms | **77 KB, 0.8 ms** | — |
80
+
81
+ **~1.8× native at typical size.** QuickJS is 8–17× and gets worse with input size.
82
+
83
+ Isolates cost **14× more memory than a QuickJS runtime** (1080 KB vs 77 KB) and
84
+ are slower to create. For a handful of facets that is irrelevant; for hundreds it
85
+ would not be.
86
+
87
+ `Intl.Segmenter` **exists** here, which is the single hard blocker for reusing
88
+ `packages/tui` components under QuickJS. That alone may decide it.
89
+
90
+ ## Limitations
91
+
92
+ **Budgets do not nest.** A timeout bounds one `evalSync`. A guest function
93
+ re-entered *by the host* — a contributed callback, a component method — gets
94
+ `callGuestRef`'s own budget, not the outer one. Asserted explicitly in
95
+ `property-test.ts`; a runaway callback took 5005 ms under an outer budget of 50 ms.
96
+ Bounding total facet time needs separate accounting.
97
+
98
+ **Async is a settle-callback, not a native promise.** `applySync` is synchronous,
99
+ so a host Promise cannot cross. The host returns a token, the guest builds a real
100
+ Promise against it, and the host settles it by calling back in. Verified: two
101
+ sequential guest `await`s while the host event loop ticked 22 times.
102
+
103
+ **Native addon, and the ABI matrix is real.** `isolated-vm` ships prebuilds and
104
+ only falls back to `node-gyp rebuild` when none matches — which is why install
105
+ takes a second, not an hour. It is **not** building V8; V8 is already in the Node
106
+ binary. But coverage is narrow:
107
+
108
+ | version | engines | prebuilds |
109
+ | --- | --- | --- |
110
+ | **6.2.0** | `>=22.0.0` | linux-x64/arm64, darwin-arm64, win32-x64 — abi127, abi137 |
111
+ | 7.0.1 | `>=24.0.0` | — |
112
+ | 7.0.0 | `>=26.0.0` | — |
113
+
114
+ darwin-**x64** is absent everywhere. Installing `isolated-vm@7` on Node 22 falls
115
+ through to a source build and **fails without Python and a C++ toolchain** —
116
+ verified here. Note also that 6.2.0 is `latest` on npm despite 7.0.1 existing,
117
+ because it published one day later.
118
+
119
+ The project is **not abandonware** — 6.0.1 (Jul 2025) through 7.0.1 (Aug 2026),
120
+ actively released. §14.2's "maintenance mode" claim is out of date and should be
121
+ corrected. The real risk is different: adopting it couples your minimum Node
122
+ version to theirs, and they dropped Node 20 in 6.x and Node 22 in 7.x within a
123
+ year. Shipping SEA builds moves that from every user's install to your CI.
124
+
125
+ **Memory: references release, but lazily.** The `WeakRef` + `FinalizationRegistry`
126
+ interning table ports unchanged from the QuickJS membrane and works — 20 000
127
+ crossings went to **0 live refs**. But finalization is not prompt: 5 000 refs were
128
+ still live 200 ms after a forced GC. Under sustained churn refs accumulate faster
129
+ than the collector reclaims them, and a 32 MB isolate did hit its limit.
130
+
131
+ The consequence is an API rule, not a membrane fix: **do not create references in
132
+ a hot path.** `slots.claim(factory)` at construct is one reference forever; a
133
+ component method returning a fresh closure every frame is one per frame.
134
+
135
+ **Hitting `memoryLimit` kills the facet cleanly.** It throws a catchable
136
+ `"Isolate was disposed during execution due to memory limit"` and the host
137
+ survives — but the isolate is dead and unrecoverable, so teardown must tolerate
138
+ an already-disposed isolate. `dispose()` on it throws `"Isolate is already
139
+ disposed"`; the membrane guards this.
140
+
141
+ > **Do not call `isolate.getHeapStatisticsSync()` on a stressed isolate.** It
142
+ > **aborted the whole process** during testing — a hard crash, not an exception.
143
+ > A `heapMB()` helper was removed from the membrane rather than shipped.
144
+
145
+ **Still one process, one engine.** A separate isolate is a far stronger boundary
146
+ than SES, but Figma's argument for QuickJS was that a *different VM* cannot
147
+ confuse objects because the representations differ. Here the guarantee is V8's
148
+ isolate boundary plus the membrane's discipline — strong, and structurally
149
+ enforced above, but not the same category of claim.
150
+
151
+ ## Files
152
+
153
+ - `src/membrane.ts` — the membrane. The safety argument is in the header comment.
154
+ - `src/facet-example.js` — unmodified facet code: `ctx.use()`, `slots.claim()`
155
+ with a closure, a class instance returned to the host, a subscribe callback.
156
+ - `src/demo-facet.ts` — loads it and exercises four boundary crossings.
157
+ - `src/escape-audit.ts` — the audit above.
158
+ - `src/property-test.ts` — 412 assertions: random `JsonValue` round-trips both
159
+ directions, identity across crossings, callables, error propagation, reference
160
+ release under GC, prototype pollution both ways, budgets, async, disposal.
161
+ - `src/bench.ts` — the numbers above.
162
+ - `src/markdown-bundle.js` — the real pi `Markdown` component, esbuild-bundled.
packages/agent/docs/mobile-handoff/02-plugins/02-sandbox/package.json ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "name": "facet-sandbox-ivm",
3
+ "private": true,
4
+ "type": "module",
5
+ "description": "Running pi facets in an isolated-vm isolate: full JIT, no ambient authority.",
6
+ "scripts": {
7
+ "demo": "node --experimental-strip-types src/demo-facet.ts",
8
+ "audit": "node --experimental-strip-types src/escape-audit.ts",
9
+ "bench": "node --experimental-strip-types src/bench.ts",
10
+ "test": "node --experimental-strip-types --expose-gc src/property-test.ts"
11
+ },
12
+ "dependencies": { "isolated-vm": "6.2.0" }
13
+ }
packages/agent/docs/mobile-handoff/02-plugins/02-sandbox/src/bench.ts ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * Cost of the isolate, the membrane, and a real component at transcript scale.
3
+ * Compare against `../facet-sandbox-poc` (QuickJS) and native.
4
+ */
5
+ import ivm from "isolated-vm";
6
+ import { readFileSync } from "node:fs";
7
+ import { createCompartment } from "./membrane.ts";
8
+
9
+ // ── membrane crossing ─────────────────────────────────────────────────────
10
+ {
11
+ const c = await createCompartment();
12
+ await c.endow("__h", { echo: (v: unknown) => v });
13
+ c.load(`globalThis.spin = function (n) { for (var i = 0; i < n; i++) __h.echo("x"); };`);
14
+ c.load(`spin(2000);`);
15
+ const N = 20000, t = Date.now();
16
+ c.load(`spin(${N});`, 60000);
17
+ console.log(`membrane crossing: ${((Date.now() - t) * 1000 / N).toFixed(1)} µs`);
18
+ c.dispose();
19
+ }
20
+
21
+ // ── isolate creation ──────────────────────────────────────────────────────
22
+ {
23
+ const before = process.memoryUsage().rss, t = Date.now();
24
+ const held = Array.from({ length: 50 }, () => {
25
+ const iso = new ivm.Isolate({ memoryLimit: 32 });
26
+ const ctx = iso.createContextSync();
27
+ ctx.evalSync(`var c = { render: function () { return ["x"]; } };`);
28
+ return iso;
29
+ });
30
+ console.log(`50 isolates: ${(((process.memoryUsage().rss - before) / 50) / 1024).toFixed(0)} KB each, ${Date.now() - t} ms total`);
31
+ for (const i of held) i.dispose();
32
+ }
33
+
34
+ // ── real Markdown at transcript scale ─────────────────────────────────────
35
+ {
36
+ const iso = new ivm.Isolate({ memoryLimit: 512 });
37
+ const ctx = iso.createContextSync();
38
+ ctx.global.setSync("global", ctx.global.derefInto());
39
+ const t = Date.now();
40
+ ctx.evalSync(readFileSync(new URL("./markdown-bundle.js", import.meta.url), "utf8"), { timeout: 60000 });
41
+ console.log(`146 KB bundle load: ${Date.now() - t} ms`);
42
+ for (const [label, pts] of [["small", 2], ["typical", 8], ["large", 35]] as [string, number][]) {
43
+ ctx.evalSync(`__bench(${pts}, 20, 50)`, { timeout: 120000 }); // warm the JIT
44
+ const ms = ctx.evalSync(`__bench(${pts}, 300, 3)`, { timeout: 300000 });
45
+ console.log(`300 markdown components, ${label.padEnd(8)} ${ms.toFixed(0)} ms per full repaint`);
46
+ }
47
+ iso.dispose();
48
+ }
packages/agent/docs/mobile-handoff/02-plugins/02-sandbox/src/demo-facet.ts ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { readFileSync } from "node:fs";
2
+ import { createCompartment } from "./membrane.ts";
3
+ const mounted = new Map(), commands = new Map(), notifications = [], subs = [];
4
+ const Tui = {
5
+ slots: { claim: (s, f) => mounted.set(s, f) },
6
+ commands: { add: (n, h) => commands.set(n, h) },
7
+ notify: (m) => notifications.push(m),
8
+ };
9
+ const Transcript = { tail: { subscribe: (f) => subs.push(f) } };
10
+ const c = await createCompartment();
11
+ await c.endow("__host", { use: (t) => (t === "Tui" ? Tui : Transcript) });
12
+ c.load(readFileSync(new URL("./facet-example.js", import.meta.url), "utf8"));
13
+ c.load(`globalThis.__r = __facet.construct({ use: function (t) { return __host.use(t); } });`);
14
+ console.log("contributions:", { slots: [...mounted.keys()], commands: [...commands.keys()], subs: subs.length });
15
+ const comp = mounted.get("footer")({ label: "presses" });
16
+ console.log(comp.render(30).join("\n"));
17
+ comp.handleInput("abc");
18
+ console.log(comp.render(30).join("\n"));
19
+ console.log("command ->", commands.get("footer.reset")());
20
+ subs[0]({ entries: [1, 2, 3] });
21
+ console.log("notifications:", notifications);
22
+ c.dispose();
packages/agent/docs/mobile-handoff/02-plugins/02-sandbox/src/escape-audit.ts ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * Escape audit.
3
+ *
4
+ * The claim the membrane makes is that the guest's entire view of the host is
5
+ * `{ number, string }` — no object graph, so nothing to walk. This tries to
6
+ * break that, including the specific `Reference` footgun that makes isolated-vm
7
+ * dangerous when used naively.
8
+ */
9
+ import { createCompartment } from "./membrane.ts";
10
+
11
+ const c = await createCompartment();
12
+ const seen: string[] = [];
13
+ await c.endow("__h", {
14
+ sink: (v: string) => seen.push(v),
15
+ give: () => ({ nested: { a: 1 } }),
16
+ giveFn: () => () => "host function result",
17
+ });
18
+
19
+ const probe = (name: string, src: string) => {
20
+ c.load(`globalThis.__p = String(${src});`);
21
+ c.load(`__h.sink(__p);`);
22
+ const got = seen.pop();
23
+ const bad = got !== undefined && /GOT (?!undefined)|INVOKED|CALLABLE|^object$/.test(got) && !/blocked/.test(got);
24
+ console.log(` ${bad ? "!!" : "ok"} ${name.padEnd(34)} ${got}`);
25
+ return !bad;
26
+ };
27
+
28
+ console.log("Ambient authority:");
29
+ let ok = true;
30
+ ok = probe("require / process / fetch", `JSON.stringify([typeof require, typeof process, typeof fetch])`) && ok;
31
+ ok = probe("global names visible", `Object.getOwnPropertyNames(globalThis).length + " globals"`) && ok;
32
+
33
+ console.log("\nClassic escape ladders:");
34
+ ok = probe("Function('return process')()", `(function(){ try { return String((function(){}).constructor("return typeof process")()); } catch(e){ return "blocked: "+e.name; } })()`) && ok;
35
+ ok = probe("constructor walk on host data", `(function(){ try { var o = __h.give(); return String(o.constructor.constructor("return typeof process")()); } catch(e){ return "blocked: "+e.name; } })()`) && ok;
36
+
37
+ console.log("\nThe isolated-vm Reference footgun:");
38
+ ok = probe("__invokeRef.deref()", `(function(){ try { return "GOT " + typeof __invokeRef.deref(); } catch(e){ return "blocked: "+e.name; } })()`) && ok;
39
+ ok = probe("__invokeRef.copySync()", `(function(){ try { return "GOT " + typeof __invokeRef.copySync(); } catch(e){ return "blocked: "+e.name; } })()`) && ok;
40
+ ok = probe("__invokeRef.getSync('constructor')", `(function(){ try { return "GOT " + typeof __invokeRef.getSync("constructor"); } catch(e){ return "blocked: "+e.name; } })()`) && ok;
41
+ ok = probe("derefInto() is callable?", `(function(){ var d = __invokeRef.derefInto(); return typeof d === "function" ? "CALLABLE" : "inert (" + typeof d + ")"; })()`) && ok;
42
+ ok = probe("invoke derefInto() result", `(function(){ try { __invokeRef.derefInto()(); return "INVOKED"; } catch(e){ return "blocked: "+e.name; } })()`) && ok;
43
+ ok = probe("host globals via derefInto()", `(function(){ var d = __invokeRef.derefInto(); return String(d.process || d.global || "no host globals"); })()`) && ok;
44
+
45
+ console.log("\nWhat a host FUNCTION looks like to the guest:");
46
+ ok = probe("typeof a returned host fn", `(function(){ var f = __h.giveFn(); return typeof f; })()`) && ok;
47
+ // NOTE: `f.deref` is NOT undefined — the membrane's proxy returns a proxy for
48
+ // every property. That is not a leak: calling it routes to hostFn["deref"],
49
+ // which does not exist, and throws host-side. Testing for the property's
50
+ // absence gave a false positive in a first draft of this audit.
51
+ ok = probe("calling f.deref() reaches nothing", `(function(){ try { var f = __h.giveFn(); f.deref(); return "INVOKED"; } catch(e){ return "blocked: "+e.name; } })()`) && ok;
52
+ ok = probe("calling the host fn works", `(function(){ var f = __h.giveFn(); return String(f()); })()`) && ok;
53
+
54
+ console.log("\nResource bounds:");
55
+ const t0 = Date.now();
56
+ let interrupted = false;
57
+ try { c.load(`while(true){}`, 200); } catch { interrupted = true; }
58
+ console.log(` ${interrupted ? "ok" : "!!"} spinning guest interrupted after ${Date.now() - t0}ms`);
59
+ console.log(` ok isolate usable afterwards ${c.load(`1+1`) === 2}`);
60
+
61
+ c.dispose();
62
+ console.log(`\n${ok && interrupted ? "AUDIT PASSED" : "AUDIT FAILED"}`);
63
+ process.exit(ok && interrupted ? 0 : 1);
packages/agent/docs/mobile-handoff/02-plugins/02-sandbox/src/facet-example.js ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // ── REAL facet code. Nothing here knows it is sandboxed. ────────────────────
2
+ // No imports rewritten, no string marshalling, no __dispatch. It uses the
3
+ // host API exactly as facets.md §11.1 describes it.
4
+
5
+ class FooterComponent {
6
+ constructor(props) { this.label = props.label; this.count = 0; }
7
+ render(width) {
8
+ const text = ` ${this.label}: ${this.count} `;
9
+ const pad = Math.max(0, width - text.length - 2);
10
+ const bar = "\u2500".repeat(Math.max(0, width - 2));
11
+ return [`\u250c${bar}\u2510`, `\u2502${text}${" ".repeat(pad)}\u2502`, `\u2514${bar}\u2518`];
12
+ }
13
+ handleInput(data) { this.count += data.length; }
14
+ }
15
+
16
+ const facet = {
17
+ id: "@demo/footer:tui",
18
+ uses: ["Tui", "Transcript"],
19
+
20
+ construct(ctx) {
21
+ const tui = ctx.use("Tui");
22
+ const transcript = ctx.use("Transcript");
23
+
24
+ // A factory crossing guest → host, by reference.
25
+ tui.slots.claim("footer", (props) => new FooterComponent(props));
26
+
27
+ // A command handler, likewise.
28
+ tui.commands.add("footer.reset", () => {
29
+ tui.notify("footer reset");
30
+ return "ok";
31
+ });
32
+
33
+ // A subscription: host calls back into the guest.
34
+ transcript.tail.subscribe((tail) => {
35
+ tui.notify(`transcript now has ${tail.entries.length} entries`);
36
+ });
37
+
38
+ return [];
39
+ },
40
+ };
41
+
42
+ globalThis.__facet = facet;
packages/agent/docs/mobile-handoff/02-plugins/02-sandbox/src/iso-vs-ctx.ts ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import ivm from "isolated-vm";
2
+ const rss = () => process.memoryUsage().rss / 1024 / 1024;
3
+
4
+ // 1. Are two CONTEXTS in one isolate isolated from each other?
5
+ {
6
+ const iso = new ivm.Isolate({ memoryLimit: 64 });
7
+ const a = iso.createContextSync(), b = iso.createContextSync();
8
+ a.evalSync(`globalThis.secret = "from-A"`);
9
+ console.log("context B sees A's global:", b.evalSync(`typeof globalThis.secret`));
10
+ // Can a spin in A be timed out without harming B?
11
+ try { a.evalSync(`while(true){}`, { timeout: 100 }); } catch { /* expected */ }
12
+ console.log("B usable after A was interrupted:", b.evalSync(`1+1`) === 2);
13
+ // Does A's memory bomb kill B?
14
+ try { a.evalSync(`var x=[]; for(;;) x.push(new Array(50000).fill(1));`, { timeout: 15000 }); }
15
+ catch (e: any) { console.log("A bomb:", e.message.slice(0, 45)); }
16
+ try { console.log("B after A's bomb:", b.evalSync(`1+1`)); }
17
+ catch (e: any) { console.log("B after A's bomb: DEAD -", e.message.slice(0, 40)); }
18
+ try { iso.dispose(); } catch {}
19
+ }
20
+
21
+ // 2. Cost per facet, both ways.
22
+ for (const mode of ["one isolate, N contexts", "N isolates"]) {
23
+ const before = rss(), t = Date.now();
24
+ const held: any[] = [];
25
+ const shared = mode.startsWith("one") ? new ivm.Isolate({ memoryLimit: 512 }) : null;
26
+ for (let i = 0; i < 50; i++) {
27
+ const iso = shared ?? new ivm.Isolate({ memoryLimit: 32 });
28
+ const ctx = iso.createContextSync();
29
+ ctx.evalSync(`var c = { render: function () { return ["x"]; } };`);
30
+ held.push(iso);
31
+ }
32
+ console.log(`50 facets, ${mode.padEnd(24)}: ${(((rss() - before) / 50) * 1024).toFixed(0)} KB each, ${Date.now() - t} ms`);
33
+ if (shared) { try { shared.dispose(); } catch {} } else for (const i of held) { try { i.dispose(); } catch {} }
34
+ }
packages/agent/docs/mobile-handoff/02-plugins/02-sandbox/src/leak.ts ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { createCompartment } from "./membrane.ts";
2
+ const c = await createCompartment();
3
+ let seen = 0;
4
+ await c.endow("__l", { drop: (_fn: unknown) => { seen++; } });
5
+ c.load(`globalThis.churn = function (n) { for (var i = 0; i < n; i++) __l.drop(function () { return i; }); };`);
6
+
7
+ const rss = () => process.memoryUsage().rss / 1024 / 1024;
8
+ const before = rss();
9
+ c.load(`churn(20000);`, 60000);
10
+ const peak = c.debugRefCount();
11
+ const afterChurn = rss();
12
+
13
+ globalThis.gc?.(); await new Promise((r) => setTimeout(r, 100));
14
+ globalThis.gc?.(); await new Promise((r) => setTimeout(r, 100));
15
+ const settled = c.debugRefCount();
16
+
17
+ console.log(`20000 crossings: host called ${seen}x`);
18
+ console.log(` guest refs: ${peak.guestRefs} -> ${settled.guestRefs}`);
19
+ console.log(` host table: ${peak.hostTable} -> ${settled.hostTable}`);
20
+ console.log(` rss: ${before.toFixed(0)} -> ${afterChurn.toFixed(0)} -> ${rss().toFixed(0)} MB`);
21
+
22
+ // Cost of the release path: one evalSync crossing per finalized ref.
23
+ const t = Date.now();
24
+ c.load(`churn(5000);`, 60000);
25
+ globalThis.gc?.(); await new Promise((r) => setTimeout(r, 200));
26
+ console.log(` 5000 more + gc: ${Date.now() - t} ms, refs now ${c.debugRefCount().guestRefs}`);
27
+ c.dispose();
packages/agent/docs/mobile-handoff/02-plugins/02-sandbox/src/markdown-bundle.js ADDED
The diff for this file is too large to render. See raw diff
 
packages/agent/docs/mobile-handoff/02-plugins/02-sandbox/src/membrane.ts ADDED
@@ -0,0 +1,197 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import ivm from "isolated-vm";
2
+
3
+ /**
4
+ * A membrane between the host realm and an isolated-vm isolate.
5
+ *
6
+ * ── The safety argument, which is structural, not a convention ──────────────
7
+ *
8
+ * isolated-vm CAN be used unsafely. The documented footgun is handing the guest
9
+ * a live handle to a host object — via `derefInto()`, or by returning a
10
+ * `Reference` from a host call — after which the guest can walk that object's
11
+ * prototype chain into the host realm.
12
+ *
13
+ * This membrane makes that impossible by construction rather than by care:
14
+ *
15
+ * 1. `encode()` is the ONLY way a host value reaches the guest, and it is
16
+ * `JSON.stringify` with a replacer. Its output is a string. A string
17
+ * cannot carry a reference.
18
+ * 2. Host callables do not cross. They are replaced by an integer id into
19
+ * `hostTable`, which lives entirely host-side. The guest receives a number.
20
+ * 3. Exactly ONE `Reference` is ever given to the guest — `__invokeRef`, the
21
+ * single call-in point — and its `deref()` throws cross-isolate ("Cannot
22
+ * dereference this from current isolate"). Its `derefInto()` yields an
23
+ * inert `Dereference` marker: not callable, no host globals.
24
+ * 4. `derefInto()` is used exactly once, on the guest's OWN global. No host
25
+ * object is ever an argument to it.
26
+ *
27
+ * The consequence: the guest's entire view of the host is `{ number, string }`.
28
+ * There is no object graph to walk, so there is nothing to walk it into. This is
29
+ * the same property the QuickJS membrane has, and it is why the choice between
30
+ * them is about performance and packaging rather than about safety.
31
+ *
32
+ * Verified by `src/escape-audit.ts`.
33
+ */
34
+ export async function createCompartment({ memoryLimit = 256 } = {}) {
35
+ const isolate = new ivm.Isolate({ memoryLimit });
36
+ const ctx = await isolate.createContext();
37
+ await ctx.global.set("global", ctx.global.derefInto()); // guest's own global only
38
+
39
+ const hostTable = new Map();
40
+ let nextHostId = 1;
41
+ const exposeHost = (o) => { const id = nextHostId++; hostTable.set(id, o); return id; };
42
+
43
+ const guestProxies = new Map();
44
+ const finalizer = new FinalizationRegistry((id) => {
45
+ guestProxies.delete(id);
46
+ if (!released) ctx.evalSync(`delete __refs[${JSON.stringify(String(id))}]`);
47
+ });
48
+ let released = false;
49
+
50
+ // Async: `applySync` is synchronous, so a host Promise cannot itself cross.
51
+ // Instead the host returns a token, the guest builds a real Promise against
52
+ // it, and the host settles that Promise by calling back in when it resolves.
53
+ let nextPending = 1;
54
+ function encodePending(promise) {
55
+ const token = nextPending++;
56
+ promise.then(
57
+ (v) => settle(token, true, v === undefined ? "" : encode(v)),
58
+ (e) => settle(token, false, JSON.stringify(String(e?.message ?? e))),
59
+ );
60
+ return JSON.stringify({ __pending: token });
61
+ }
62
+ function settle(token, ok, json) {
63
+ if (released) return;
64
+ ctx.evalSync(`__settle(${token}, ${ok}, ${JSON.stringify(json)})`);
65
+ }
66
+
67
+ function encode(v) {
68
+ if (v && typeof v.then === "function") return encodePending(v);
69
+ return JSON.stringify(v, (_k, val) => {
70
+ if (typeof val === "function") return { __ref: exposeHost(val) };
71
+ if (val && typeof val === "object" && !Array.isArray(val) && hasMethods(val))
72
+ return { __obj: exposeHost(val), keys: methodNames(val) };
73
+ return val;
74
+ });
75
+ }
76
+ const decode = (json) => JSON.parse(json, (_k, v) => reviveGuest(v));
77
+
78
+ function intern(id, build) {
79
+ const hit = guestProxies.get(id)?.deref();
80
+ if (hit !== undefined) return hit;
81
+ const p = build();
82
+ guestProxies.set(id, new WeakRef(p));
83
+ finalizer.register(p, id);
84
+ return p;
85
+ }
86
+ function reviveGuest(v) {
87
+ if (!v || typeof v !== "object") return v;
88
+ if (typeof v.__guestRef === "number") { const r = v.__guestRef; return intern(r, () => (...a) => callGuestRef(r, a)); }
89
+ if (typeof v.__guestObj === "number") {
90
+ const r = v.__guestObj;
91
+ return intern(r, () => { const o = {}; for (const k of v.keys) o[k] = (...a) => callGuestRef(r, [k, a]); return o; });
92
+ }
93
+ return v;
94
+ }
95
+
96
+ function callGuestRef(ref, args, timeout = 5000) {
97
+ const out = ctx.evalSync(
98
+ `__refs[${JSON.stringify(String(ref))}](${JSON.stringify(JSON.stringify(args))})`,
99
+ { timeout },
100
+ );
101
+ return out === "" || out === undefined ? undefined : decode(out);
102
+ }
103
+
104
+ // The single host entry point. A Reference, applied synchronously with copied
105
+ // arguments — no host object graph is ever exposed.
106
+ const invoke = new ivm.Reference((idJson, pathJson, argsJson) => {
107
+ const path = JSON.parse(pathJson);
108
+ let target = hostTable.get(JSON.parse(idJson));
109
+ for (let i = 0; i < path.length - 1; i++) target = target[path[i]];
110
+ const result = path.length ? target[path[path.length - 1]](...decode(argsJson)) : target(...decode(argsJson));
111
+ return result === undefined ? "" : encode(result);
112
+ });
113
+ await ctx.global.set("__invokeRef", invoke);
114
+
115
+ await ctx.eval(`
116
+ globalThis.__refs = {}; globalThis.__nextRef = 1;
117
+ globalThis.__outgoing = new WeakMap();
118
+ globalThis.__methodNames = function (o) {
119
+ var out = [], p = o;
120
+ while (p && p !== Object.prototype) {
121
+ for (const k of Object.getOwnPropertyNames(p))
122
+ if (k !== "constructor" && typeof o[k] === "function" && out.indexOf(k) < 0) out.push(k);
123
+ p = Object.getPrototypeOf(p);
124
+ }
125
+ return out;
126
+ };
127
+ globalThis.__mkRef = function (fn) {
128
+ var prior = __outgoing.get(fn); if (prior !== undefined) return { __guestRef: prior };
129
+ var id = __nextRef++; __outgoing.set(fn, id);
130
+ __refs[String(id)] = function (j) { var r = fn.apply(null, JSON.parse(j)); return r === undefined ? "" : __encode(r); };
131
+ return { __guestRef: id };
132
+ };
133
+ globalThis.__mkObjRef = function (obj) {
134
+ var prior = __outgoing.get(obj);
135
+ if (prior !== undefined) return { __guestObj: prior, keys: __methodNames(obj) };
136
+ var id = __nextRef++; __outgoing.set(obj, id);
137
+ __refs[String(id)] = function (j) { var c = JSON.parse(j); var r = obj[c[0]].apply(obj, c[1]); return r === undefined ? "" : __encode(r); };
138
+ return { __guestObj: id, keys: __methodNames(obj) };
139
+ };
140
+ globalThis.__encode = function (v) {
141
+ return JSON.stringify(v, function (k, val) {
142
+ if (typeof val === "function") return __mkRef(val);
143
+ if (val && typeof val === "object" && !Array.isArray(val) && __methodNames(val).length) return __mkObjRef(val);
144
+ return val;
145
+ });
146
+ };
147
+ globalThis.__pending = {};
148
+ globalThis.__settle = function (token, ok, json) {
149
+ var d = __pending[token];
150
+ if (!d) return;
151
+ delete __pending[token];
152
+ var value = json === "" ? undefined : JSON.parse(json);
153
+ ok ? d.resolve(__revive(value)) : d.reject(new Error(value));
154
+ };
155
+ globalThis.__revive = function (v) {
156
+ if (v && typeof v === "object" && typeof v.__pending === "number") {
157
+ var token = v.__pending;
158
+ return new Promise(function (res, rej) { __pending[token] = { resolve: res, reject: rej }; });
159
+ }
160
+ if (v && typeof v === "object") {
161
+ if (typeof v.__ref === "number") return __wrap(v.__ref, []);
162
+ if (typeof v.__obj === "number") return __wrap(v.__obj, []);
163
+ for (var k in v) v[k] = __revive(v[k]);
164
+ }
165
+ return v;
166
+ };
167
+ globalThis.__wrap = function (id, path) {
168
+ return new Proxy(function () {}, {
169
+ get: function (t, prop) {
170
+ if (typeof prop !== "string") return undefined;
171
+ if (prop === "then" || prop === "toJSON" || prop === "inspect") return undefined;
172
+ if (prop === "length" || prop === "name") return t[prop];
173
+ return __wrap(id, path.concat([prop]));
174
+ },
175
+ apply: function (_t, _this, args) {
176
+ var out = __invokeRef.applySync(undefined, [JSON.stringify(id), JSON.stringify(path), __encode(args)]);
177
+ return out === "" ? undefined : __revive(JSON.parse(out));
178
+ },
179
+ });
180
+ };
181
+ `);
182
+
183
+ return {
184
+ async endow(name, obj) { await ctx.eval(`globalThis[${JSON.stringify(name)}] = __wrap(${exposeHost(obj)}, []);`); },
185
+ load: (src, timeout = 30000) => ctx.evalSync(src, { timeout }),
186
+ debugRefCount: () => ({ hostTable: hostTable.size, guestRefs: ctx.evalSync(`Object.keys(__refs).length`) }),
187
+ dispose() {
188
+ released = true;
189
+ // An isolate that hit its memory limit is already disposed, and calling
190
+ // dispose() again throws "Isolate is already disposed".
191
+ try { isolate.dispose(); } catch { /* already gone */ }
192
+ },
193
+ };
194
+ }
195
+ const RESERVED = new Set(["constructor"]);
196
+ const methodNames = (o) => { const out = []; for (let p = o; p && p !== Object.prototype; p = Object.getPrototypeOf(p)) for (const k of Object.getOwnPropertyNames(p)) if (!RESERVED.has(k) && typeof o[k] === "function" && !out.includes(k)) out.push(k); return out; };
197
+ const hasMethods = (o) => methodNames(o).length > 0;
packages/agent/docs/mobile-handoff/02-plugins/02-sandbox/src/property-test.ts ADDED
@@ -0,0 +1,137 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * Property tests for the membrane.
3
+ *
4
+ * Every bug found by hand while building it failed SILENTLY — wrong output, no
5
+ * throw. That is the worst possible failure mode for a boundary, and the reason
6
+ * these exist. Run with: node --experimental-strip-types --expose-gc property-test.ts
7
+ */
8
+ import { createCompartment } from "./membrane.ts";
9
+
10
+ let pass = 0;
11
+ const failures: string[] = [];
12
+ const check = (name: string, ok: boolean, detail = "") => {
13
+ if (ok) pass++;
14
+ else failures.push(`${name}${detail ? ` — ${detail}` : ""}`);
15
+ };
16
+
17
+ /** Random JsonValue. The membrane claims to round-trip exactly these. */
18
+ function randomJson(depth = 0): unknown {
19
+ const r = Math.random();
20
+ if (depth > 3 || r < 0.25) return Math.floor(Math.random() * 1000) - 500;
21
+ if (r < 0.35) return Math.random() * 1e6 - 5e5;
22
+ if (r < 0.45) return Math.random() < 0.5;
23
+ if (r < 0.5) return null;
24
+ if (r < 0.65) {
25
+ const alphabet = ['a', 'z', '0', ' ', '"', '\\', '\n', '\u00e9', '\u4e2d', '\u{1f600}'];
26
+ let s = "";
27
+ const n = Math.floor(Math.random() * 12);
28
+ for (let i = 0; i < n; i++) s += alphabet[Math.floor(Math.random() * alphabet.length)];
29
+ return s;
30
+ }
31
+ if (r < 0.8) return Array.from({ length: Math.floor(Math.random() * 5) }, () => randomJson(depth + 1));
32
+ const o: Record<string, unknown> = {};
33
+ for (const k of ["a", "b", "c", "d", "__proto__x", "0", "length"]) {
34
+ if (Math.random() < 0.5) o[k] = randomJson(depth + 1);
35
+ }
36
+ return o;
37
+ }
38
+
39
+ const c = await createCompartment();
40
+
41
+ // ── 1. Value round-trip, both directions ──────────────────────────────────
42
+ const echoed: unknown[] = [];
43
+ await c.endow("__h", { echo: (v: unknown) => v, sink: (v: unknown) => { echoed.push(v); } });
44
+ c.load(`globalThis.roundTrip = function (v) { return __h.echo(v); };
45
+ globalThis.sendBack = function (v) { __h.sink(v); };`);
46
+
47
+ for (let i = 0; i < 400; i++) {
48
+ const value = randomJson();
49
+ const json = JSON.stringify(value);
50
+ if (json === undefined) continue;
51
+ // host -> guest -> host
52
+ c.load(`globalThis.__t = roundTrip(${json});`);
53
+ c.load(`sendBack(__t);`);
54
+ const got = echoed.pop();
55
+ check("value round-trip", JSON.stringify(got) === json, `${json} became ${JSON.stringify(got)}`);
56
+ }
57
+
58
+ // ── 2. Identity: the same guest object must map to the same host proxy ────
59
+ const seen: unknown[] = [];
60
+ await c.endow("__id", { take: (o: unknown) => { seen.push(o); } });
61
+ c.load(`globalThis.shared = { m: function () { return 1; } };
62
+ globalThis.sendShared = function () { __id.take(shared); __id.take(shared); };`);
63
+ c.load(`sendShared();`);
64
+ check("identity preserved across crossings", seen[0] === seen[1]);
65
+ c.load(`sendShared();`);
66
+ check("identity stable across separate calls", seen[0] === seen[2]);
67
+
68
+ // ── 3. Callables survive and remain callable ──────────────────────────────
69
+ let held: any;
70
+ await c.endow("__f", { keep: (fn: unknown) => { held = fn; } });
71
+ c.load(`__f.keep(function (a, b) { return a + b; });`);
72
+ check("guest function callable from host", held(2, 3) === 5, `got ${held?.(2, 3)}`);
73
+
74
+ // ── 4. Errors cross with name and message ─────────────────────────────────
75
+ c.load(`__f.keep(function () { throw new TypeError("boom"); });`);
76
+ let msg = "";
77
+ try { held(); } catch (e: any) { msg = e.message; }
78
+ check("guest throw reaches host", msg.includes("boom"), `got "${msg}"`);
79
+
80
+ // ── 5. Reference release: crossings must not leak ─────────────────────────
81
+ await c.endow("__l", { drop: (_fn: unknown) => {} });
82
+ c.load(`globalThis.churn = function () { for (var i = 0; i < 500; i++) __l.drop(function () { return i; }); };`);
83
+ c.load(`churn();`);
84
+ const beforeGc = c.debugRefCount().guestRefs;
85
+ globalThis.gc?.();
86
+ await new Promise((r) => setTimeout(r, 60));
87
+ globalThis.gc?.();
88
+ await new Promise((r) => setTimeout(r, 60));
89
+ const afterGc = c.debugRefCount().guestRefs;
90
+ check("dropped references are released", afterGc < beforeGc / 2, `${beforeGc} -> ${afterGc}`);
91
+
92
+ // ── 5b. Prototype pollution must not cross ────────────────────────────────
93
+ // JSON.parse is safe (it makes __proto__ an own property), but a membrane that
94
+ // assigns parsed keys onto a fresh object is not.
95
+ const before = ({} as any).polluted;
96
+ c.load(`__h.sink(JSON.parse('{"__proto__":{"polluted":true}}'));`);
97
+ check("guest cannot pollute host Object.prototype", ({} as any).polluted === before);
98
+ await c.endow("__p", { give: () => JSON.parse('{"__proto__":{"hostPolluted":true}}') });
99
+ await c.endow("__q", { show: (v: string) => check("host cannot pollute guest prototype", v === "undefined", v) });
100
+ c.load(`var got = __p.give(); __q.show(String(({}).hostPolluted));`);
101
+
102
+ // ── 6. Interrupt budget, and the VM survives it ──────────────���────────────
103
+ // Direct: the budget on this call bounds it.
104
+ {
105
+ const t0 = Date.now();
106
+ try { c.load(`while (true) {}`, 100); } catch { /* expected */ }
107
+ check("runaway guest code is interrupted", Date.now() - t0 < 600, `took ${Date.now() - t0}ms`);
108
+ }
109
+ // Re-entrant: a guest function invoked BY THE HOST gets `callGuestRef`'s own
110
+ // budget, not the outer one. Budgets do not nest — see README "Limitations".
111
+ c.load(`globalThis.spin = function () { while (true) {} };`);
112
+ await c.endow("__s", { run: (fn: any) => { try { fn(); return "returned"; } catch { return "threw"; } } });
113
+ {
114
+ const t0 = Date.now();
115
+ try { c.load(`globalThis.__x = __s.run(spin);`, 50); } catch { /* expected */ }
116
+ const took = Date.now() - t0;
117
+ check("re-entrant call uses its OWN budget, not the outer one", took > 1000,
118
+ `took ${took}ms — if this is now <1s the nesting behaviour changed`);
119
+ }
120
+ c.load(`globalThis.__alive = 1 + 1;`);
121
+ check("VM usable after an interrupt", true);
122
+
123
+ // ── 7. Async, and clean teardown with a pending promise ───────────────────
124
+ await c.endow("__a", { never: () => new Promise(() => {}), soon: () => Promise.resolve("v") });
125
+ c.load(`globalThis.out = null; __a.soon().then(function (v) { out = v; });`);
126
+ await new Promise((r) => setTimeout(r, 30));
127
+ await c.endow("__o", { show: (v: string) => check("async host result reaches guest", v === '"v"', v) });
128
+ c.load(`__o.show(JSON.stringify(out));`);
129
+ c.load(`__a.never().then(function () {}, function () {});`); // deliberately unsettled
130
+
131
+ let disposeOk = true;
132
+ try { c.dispose(); } catch { disposeOk = false; }
133
+ check("dispose with a pending promise does not crash", disposeOk);
134
+
135
+ console.log(`\n${pass} passed, ${failures.length} failed`);
136
+ for (const f of failures.slice(0, 10)) console.log(" FAIL", f);
137
+ process.exit(failures.length === 0 ? 0 : 1);
packages/agent/test/harness/adaptive-publisher.test.ts ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { afterEach, describe, expect, it, vi } from "vitest";
2
+ import { AdaptivePublisher } from "../../src/harness/utils/adaptive-publisher.ts";
3
+
4
+ afterEach(() => {
5
+ vi.useRealTimers();
6
+ });
7
+
8
+ describe("AdaptivePublisher", () => {
9
+ it("bounds event count and spaces large publications by encoded size", () => {
10
+ vi.useFakeTimers();
11
+ vi.setSystemTime(0);
12
+ let value = "a";
13
+ const updates: string[] = [];
14
+ const publisher = new AdaptivePublisher({
15
+ snapshot: () => value,
16
+ update: (_previous, current) => current,
17
+ measure: (update) => update.length,
18
+ publish: (update) => updates.push(update),
19
+ onError: (error) => {
20
+ throw error;
21
+ },
22
+ minIntervalMs: 100,
23
+ targetBytesPerSecond: 100,
24
+ });
25
+
26
+ publisher.markDirty();
27
+ value = "x".repeat(100);
28
+ publisher.markDirty();
29
+ vi.advanceTimersByTime(100);
30
+ expect(updates).toEqual(["a", "x".repeat(100)]);
31
+
32
+ value = "held";
33
+ publisher.markDirty();
34
+ vi.advanceTimersByTime(999);
35
+ expect(updates).toHaveLength(2);
36
+ vi.advanceTimersByTime(1);
37
+ expect(updates).toEqual(["a", "x".repeat(100), "held"]);
38
+ });
39
+
40
+ it("commits its baseline before a consumer throws", () => {
41
+ vi.useFakeTimers();
42
+ vi.setSystemTime(0);
43
+ let value = "a";
44
+ const updates: Array<{ previous: string | undefined; current: string }> = [];
45
+ let throwAfterApply = false;
46
+ const publisher = new AdaptivePublisher({
47
+ snapshot: () => value,
48
+ update: (previous, current) => ({ previous, current }),
49
+ measure: () => 1,
50
+ publish: (update) => {
51
+ updates.push(update);
52
+ if (throwAfterApply) throw new Error("consumer failed after apply");
53
+ },
54
+ onError: () => {},
55
+ minIntervalMs: 100,
56
+ targetBytesPerSecond: 100,
57
+ });
58
+
59
+ publisher.markDirty();
60
+ vi.advanceTimersByTime(100);
61
+ value = "ab";
62
+ throwAfterApply = true;
63
+ expect(() => publisher.markDirty()).toThrow("consumer failed after apply");
64
+ publisher.flush(true);
65
+ expect(updates).toEqual([
66
+ { previous: undefined, current: "a" },
67
+ { previous: "a", current: "ab" },
68
+ ]);
69
+
70
+ throwAfterApply = false;
71
+ vi.advanceTimersByTime(100);
72
+ value = "abc";
73
+ publisher.markDirty();
74
+ expect(updates.at(-1)).toEqual({ previous: "ab", current: "abc" });
75
+ });
76
+ });
packages/agent/test/harness/branch-summarization.test.ts ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import type { AgentMessage } from "@earendil-works/pi-agent-core";
2
+ import { describe, expect, it } from "vitest";
3
+ import { collectEntriesForBranchSummary } from "../../src/harness/compaction/branch-summarization.ts";
4
+ import { BACKGROUND_CONTEXT } from "../../src/harness/context.ts";
5
+ import type { Branch, Entry, MessageEntry, Session } from "../../src/harness/session/index.ts";
6
+
7
+ function message(text: string): AgentMessage {
8
+ return { role: "user", content: [{ type: "text", text }], timestamp: 1 };
9
+ }
10
+
11
+ function messageEntry(id: string, parentId: string | null, text: string, seq: number): MessageEntry {
12
+ return { type: "message", id, parentId, message: message(text), seq, timestamp: seq };
13
+ }
14
+
15
+ function branchReader(entries: Entry[]): {
16
+ branch: Pick<Branch, "findEntries">;
17
+ session: Pick<Session, "getEntry">;
18
+ } {
19
+ const byId = new Map(entries.map((entry) => [entry.id, entry]));
20
+ return {
21
+ session: {
22
+ async getEntry(id) {
23
+ return byId.get(id);
24
+ },
25
+ },
26
+ branch: {
27
+ async findEntries(query = {}) {
28
+ const path: Entry[] = [];
29
+ let currentId = query.start ?? null;
30
+ while (currentId !== null) {
31
+ const entry = byId.get(currentId);
32
+ if (!entry) throw new Error(`Unknown entry ${currentId}`);
33
+ path.push(entry);
34
+ currentId = entry.parentId;
35
+ }
36
+ return path;
37
+ },
38
+ },
39
+ };
40
+ }
41
+
42
+ describe("v4 branch summarization", () => {
43
+ it("collects the abandoned side of a branch in chronological order", async () => {
44
+ const root = messageEntry("root", null, "root", 1);
45
+ const common = messageEntry("common", root.id, "common", 2);
46
+ const abandoned1 = messageEntry("abandoned-1", common.id, "abandoned 1", 3);
47
+ const abandoned2 = messageEntry("abandoned-2", abandoned1.id, "abandoned 2", 4);
48
+ const target = messageEntry("target", common.id, "target", 5);
49
+ const { branch, session } = branchReader([root, common, abandoned1, abandoned2, target]);
50
+
51
+ const result = await collectEntriesForBranchSummary(
52
+ branch,
53
+ session,
54
+ abandoned2.id,
55
+ target.id,
56
+ BACKGROUND_CONTEXT,
57
+ );
58
+ expect(result.commonAncestorId).toBe(common.id);
59
+ expect(result.entries.map((entry) => entry.id)).toEqual([abandoned1.id, abandoned2.id]);
60
+ expect(result.entries.some((entry) => entry.id === root.id)).toBe(false);
61
+ });
62
+
63
+ it("returns no entries when there was no previous leaf", async () => {
64
+ const target = messageEntry("target", null, "target", 1);
65
+ const { branch, session } = branchReader([target]);
66
+ expect(await collectEntriesForBranchSummary(branch, session, null, target.id, BACKGROUND_CONTEXT)).toEqual({
67
+ entries: [],
68
+ commonAncestorId: null,
69
+ });
70
+ });
71
+ });
packages/agent/test/harness/branch.test.ts ADDED
@@ -0,0 +1,110 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { describe, expect, it } from "vitest";
2
+ import { BACKGROUND_CONTEXT } from "../../src/harness/context.ts";
3
+ import { insertEntry } from "../../src/harness/session/commit.ts";
4
+ import { MemoryStorage } from "../../src/harness/session/memory.ts";
5
+ import { SessionPendingAssistantMessageError, StorageBackedSession } from "../../src/harness/session/session.ts";
6
+ import { branchTip, setValue } from "../../src/harness/session/values.ts";
7
+
8
+ function createSession(): StorageBackedSession {
9
+ return new StorageBackedSession(
10
+ { id: "session", createdAt: 1, storageVersion: 1 },
11
+ new MemoryStorage({ now: () => 10 }),
12
+ { idGenerator: { next: () => `entry-${nextId++}` } },
13
+ );
14
+ }
15
+
16
+ let nextId = 1;
17
+
18
+ describe("Branch", () => {
19
+ it("is absent until explicitly created and Session has no implicit Branch surface", async () => {
20
+ const session = createSession();
21
+ expect(await session.branch("main", BACKGROUND_CONTEXT)).toBeUndefined();
22
+ expect("getTipId" in session).toBe(false);
23
+ expect("appendMessage" in session).toBe(false);
24
+ expect("findEntriesOnBranch" in session).toBe(false);
25
+
26
+ const branch = await session.createBranch("main", null, BACKGROUND_CONTEXT);
27
+ expect(branch.name).toBe("main");
28
+ expect(await branch.getTipId(BACKGROUND_CONTEXT)).toBeNull();
29
+ await session.close(BACKGROUND_CONTEXT);
30
+ });
31
+
32
+ it("directly appends immutable entries and advances only its own tip", async () => {
33
+ nextId = 1;
34
+ const session = createSession();
35
+ const main = await session.createBranch("main", null, BACKGROUND_CONTEXT);
36
+ const review = await session.createBranch("review", null, BACKGROUND_CONTEXT);
37
+ const message = { role: "user" as const, content: "hello", timestamp: 1 };
38
+
39
+ const messageId = await main.appendMessage(message, BACKGROUND_CONTEXT);
40
+ const customId = await main.appendCustomEntry("note", { ok: true }, BACKGROUND_CONTEXT);
41
+ const reviewId = await review.appendCustomEntry("review", undefined, BACKGROUND_CONTEXT);
42
+
43
+ expect(await main.getTipId(BACKGROUND_CONTEXT)).toBe(customId);
44
+ expect(await review.getTipId(BACKGROUND_CONTEXT)).toBe(reviewId);
45
+ expect((await main.findEntries({ order: "oldestFirst" }, BACKGROUND_CONTEXT)).map(({ id }) => id)).toEqual([
46
+ messageId,
47
+ customId,
48
+ ]);
49
+ expect(await main.findEntry({ type: "message" }, BACKGROUND_CONTEXT)).toMatchObject({
50
+ id: messageId,
51
+ type: "message",
52
+ message,
53
+ });
54
+ await session.close(BACKGROUND_CONTEXT);
55
+ });
56
+
57
+ it("supports explicit starts without moving the Branch tip", async () => {
58
+ const session = createSession();
59
+ await session.mutate(
60
+ (mutator) =>
61
+ mutator.commit(
62
+ [
63
+ insertEntry({ id: "root", parentId: null, type: "custom", customType: "root" }),
64
+ insertEntry({ id: "left", parentId: "root", type: "custom", customType: "left" }),
65
+ insertEntry({ id: "right", parentId: "root", type: "custom", customType: "right" }),
66
+ setValue(branchTip("main"), "left"),
67
+ ],
68
+ BACKGROUND_CONTEXT,
69
+ ),
70
+ BACKGROUND_CONTEXT,
71
+ );
72
+ const branch = await session.branch("main", BACKGROUND_CONTEXT);
73
+ if (branch === undefined) throw new Error("Expected main Branch");
74
+
75
+ expect(
76
+ (await branch.findEntries({ start: "right", order: "oldestFirst" }, BACKGROUND_CONTEXT)).map(({ id }) => id),
77
+ ).toEqual(["root", "right"]);
78
+ expect(await branch.getTipId(BACKGROUND_CONTEXT)).toBe("left");
79
+ await session.close(BACKGROUND_CONTEXT);
80
+ });
81
+
82
+ it("rejects pending assistant messages before committing", async () => {
83
+ const session = createSession();
84
+ const branch = await session.createBranch("main", null, BACKGROUND_CONTEXT);
85
+ await expect(
86
+ branch.appendMessage(
87
+ {
88
+ role: "assistant",
89
+ content: [],
90
+ api: "test",
91
+ provider: "test",
92
+ model: "test",
93
+ usage: {
94
+ input: 0,
95
+ output: 0,
96
+ cacheRead: 0,
97
+ cacheWrite: 0,
98
+ totalTokens: 0,
99
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
100
+ },
101
+ stopReason: "pending",
102
+ timestamp: 1,
103
+ },
104
+ BACKGROUND_CONTEXT,
105
+ ),
106
+ ).rejects.toBeInstanceOf(SessionPendingAssistantMessageError);
107
+ expect(await branch.getTipId(BACKGROUND_CONTEXT)).toBeNull();
108
+ await session.close(BACKGROUND_CONTEXT);
109
+ });
110
+ });
packages/agent/test/harness/compaction.test.ts ADDED
@@ -0,0 +1,827 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import {
2
+ type Api,
3
+ type AssistantMessage,
4
+ createModels,
5
+ type FauxProviderHandle,
6
+ fauxAssistantMessage,
7
+ fauxProvider,
8
+ type Message,
9
+ type Model,
10
+ type Models,
11
+ type Usage,
12
+ } from "@earendil-works/pi-ai";
13
+ import { beforeEach, describe, expect, it } from "vitest";
14
+ import {
15
+ type CompactionPreparation,
16
+ type CompactionSettings,
17
+ calculateContextTokens,
18
+ compact,
19
+ DEFAULT_COMPACTION_SETTINGS,
20
+ estimateContextTokens,
21
+ estimateTokens,
22
+ findCutPoint,
23
+ findTurnStartIndex,
24
+ generateSummary,
25
+ generateSummaryWithUsage,
26
+ getLastAssistantUsage,
27
+ prepareCompaction,
28
+ serializeConversation,
29
+ shouldCompact,
30
+ } from "../../src/harness/compaction/compaction.ts";
31
+ import { BACKGROUND_CONTEXT } from "../../src/harness/context.ts";
32
+ import { buildSessionContext } from "../../src/harness/session/context.ts";
33
+ import type {
34
+ BranchSummaryEntry,
35
+ CompactionEntry,
36
+ CustomEntry,
37
+ Entry,
38
+ MessageEntry,
39
+ } from "../../src/harness/session/types.ts";
40
+ import { getOrThrow } from "../../src/harness/types.ts";
41
+ import type { AgentMessage } from "../../src/types.ts";
42
+
43
+ let nextId = 0;
44
+ function createId(): string {
45
+ return `entry-${nextId++}`;
46
+ }
47
+
48
+ function createMockUsage(input: number, output: number, cacheRead = 0, cacheWrite = 0): Usage {
49
+ return {
50
+ input,
51
+ output,
52
+ cacheRead,
53
+ cacheWrite,
54
+ totalTokens: input + output + cacheRead + cacheWrite,
55
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
56
+ };
57
+ }
58
+
59
+ function createUserMessage(text: string): AgentMessage {
60
+ return {
61
+ role: "user",
62
+ content: [{ type: "text", text }],
63
+ timestamp: Date.now(),
64
+ };
65
+ }
66
+
67
+ function createAssistantMessage(text: string, usage = createMockUsage(100, 50)): AssistantMessage {
68
+ return {
69
+ role: "assistant",
70
+ content: [{ type: "text", text }],
71
+ api: "anthropic-messages",
72
+ provider: "anthropic",
73
+ model: "claude-sonnet-4-5",
74
+ usage,
75
+ stopReason: "stop",
76
+ timestamp: Date.now(),
77
+ };
78
+ }
79
+
80
+ function createMessageEntry(message: AgentMessage, parentId: string | null = null): MessageEntry {
81
+ return {
82
+ type: "message",
83
+ id: createId(),
84
+ parentId,
85
+ seq: nextId,
86
+ timestamp: Date.now(),
87
+ message,
88
+ };
89
+ }
90
+
91
+ function createCompactionEntry(
92
+ summary: string,
93
+ parentId: string | null = null,
94
+ retainedTail?: AgentMessage[],
95
+ ): CompactionEntry {
96
+ return {
97
+ type: "compaction",
98
+ id: createId(),
99
+ parentId,
100
+ seq: nextId,
101
+ timestamp: Date.now(),
102
+ summary,
103
+ tokensBefore: 1234,
104
+ retainedTail: retainedTail ?? [],
105
+ fromHook: false,
106
+ };
107
+ }
108
+
109
+ function createCustomEntry(customType: string, parentId: string | null = null): CustomEntry {
110
+ return {
111
+ type: "custom",
112
+ customType,
113
+ id: createId(),
114
+ parentId,
115
+ seq: nextId,
116
+ timestamp: Date.now(),
117
+ };
118
+ }
119
+
120
+ /** Shared collection; each faux provider gets a unique id so coexisting fakes route correctly. */
121
+ const models = createModels();
122
+ let fauxCount = 0;
123
+
124
+ function createFauxModel(reasoning: boolean, maxTokens = 8192): { faux: FauxProviderHandle; model: Model<Api> } {
125
+ const faux = fauxProvider({
126
+ provider: `faux-${++fauxCount}`,
127
+ models: [
128
+ {
129
+ id: reasoning ? "reasoning-model" : "non-reasoning-model",
130
+ reasoning,
131
+ contextWindow: 200000,
132
+ maxTokens,
133
+ },
134
+ ],
135
+ });
136
+ models.setProvider(faux.provider);
137
+ return { faux, model: faux.getModel() };
138
+ }
139
+
140
+ function createModelsWithSimpleResponses(responses: AssistantMessage[]): Models {
141
+ const remaining = [...responses];
142
+ const stub = Object.create(models) as Models;
143
+ stub.completeSimple = async () => {
144
+ const response = remaining.shift();
145
+ if (!response) throw new Error("No faux completeSimple response queued");
146
+ return response;
147
+ };
148
+ return stub;
149
+ }
150
+
151
+ describe("harness compaction", () => {
152
+ beforeEach(() => {
153
+ nextId = 0;
154
+ });
155
+
156
+ it("calculates total context tokens from usage", () => {
157
+ expect(calculateContextTokens(createMockUsage(1000, 500, 200, 100))).toBe(1800);
158
+ expect(calculateContextTokens(createMockUsage(0, 0, 0, 0))).toBe(0);
159
+ });
160
+
161
+ it("checks compaction threshold", () => {
162
+ const settings: CompactionSettings = {
163
+ enabled: true,
164
+ reserveTokens: 10000,
165
+ keepRecentTokens: 20000,
166
+ };
167
+ expect(shouldCompact(95000, 100000, settings)).toBe(true);
168
+ expect(shouldCompact(89000, 100000, settings)).toBe(false);
169
+ expect(shouldCompact(95000, 100000, { ...settings, enabled: false })).toBe(false);
170
+ });
171
+
172
+ it("finds a cut point based on token differences", () => {
173
+ const entries: Entry[] = [];
174
+ let parentId: string | null = null;
175
+ for (let i = 0; i < 10; i++) {
176
+ const user = createMessageEntry(createUserMessage(`User ${i}`), parentId);
177
+ entries.push(user);
178
+ const assistant = createMessageEntry(
179
+ createAssistantMessage(`Assistant ${i}`, createMockUsage(0, 100, (i + 1) * 1000, 0)),
180
+ user.id,
181
+ );
182
+ entries.push(assistant);
183
+ parentId = assistant.id;
184
+ }
185
+
186
+ const result = findCutPoint(entries, 0, entries.length, 2500);
187
+ expect(entries[result.firstKeptEntryIndex]?.type).toBe("message");
188
+ });
189
+
190
+ it("covers cut-point and turn-start edge cases", () => {
191
+ const firstCustom = createCustomEntry("first");
192
+ const secondCustom = createCustomEntry("second", firstCustom.id);
193
+ expect(findCutPoint([firstCustom, secondCustom], 0, 2, 1)).toEqual({
194
+ firstKeptEntryIndex: 0,
195
+ turnStartIndex: -1,
196
+ isSplitTurn: false,
197
+ });
198
+
199
+ const branchSummary: BranchSummaryEntry = {
200
+ type: "branch_summary",
201
+ id: createId(),
202
+ parentId: secondCustom.id,
203
+ seq: nextId,
204
+ timestamp: Date.now(),
205
+ fromId: "branch",
206
+ summary: "branch summary",
207
+ fromHook: false,
208
+ };
209
+ expect(findTurnStartIndex([firstCustom, branchSummary], 1, 0)).toBe(1);
210
+ expect(findTurnStartIndex([firstCustom, secondCustom], 1, 0)).toBe(-1);
211
+
212
+ const result = findCutPoint([firstCustom, branchSummary], 0, 2, 1);
213
+ expect(result.firstKeptEntryIndex).toBe(0);
214
+
215
+ const toolResult = createMessageEntry({
216
+ role: "toolResult",
217
+ toolCallId: "call-1",
218
+ toolName: "read",
219
+ content: [{ type: "text", text: "tool output" }],
220
+ isError: false,
221
+ timestamp: Date.now(),
222
+ });
223
+ expect(findCutPoint([toolResult], 0, 1, 1)).toEqual({
224
+ firstKeptEntryIndex: 0,
225
+ turnStartIndex: -1,
226
+ isSplitTurn: false,
227
+ });
228
+
229
+ const user = createMessageEntry(createUserMessage("user"));
230
+ const compaction = createCompactionEntry("summary", user.id);
231
+ const assistant = createMessageEntry(createAssistantMessage("assistant"), compaction.id);
232
+ expect(findCutPoint([user, compaction, assistant], 0, 3, 1).firstKeptEntryIndex).toBe(2);
233
+ });
234
+
235
+ it("estimates tokens and context usage across supported message roles", () => {
236
+ const usage = createMockUsage(10, 5, 3, 2);
237
+ const assistant = createAssistantMessage("assistant", usage);
238
+ const assistantWithThinkingAndTool: AssistantMessage = {
239
+ ...assistant,
240
+ content: [
241
+ { type: "thinking", thinking: "thinking" },
242
+ { type: "toolCall", id: "call-1", name: "read", arguments: { path: "file.ts" } },
243
+ ],
244
+ };
245
+ const customString: AgentMessage = {
246
+ role: "custom",
247
+ customType: "note",
248
+ content: "custom text",
249
+ display: true,
250
+ timestamp: Date.now(),
251
+ };
252
+ const toolResultWithImage: AgentMessage = {
253
+ role: "toolResult",
254
+ toolCallId: "call-1",
255
+ toolName: "read",
256
+ content: [
257
+ { type: "text", text: "tool text" },
258
+ { type: "image", mimeType: "image/png", data: "abc" },
259
+ ],
260
+ isError: false,
261
+ timestamp: Date.now(),
262
+ };
263
+ const bashExecution: AgentMessage = {
264
+ role: "bashExecution",
265
+ command: "npm run check",
266
+ output: "ok",
267
+ exitCode: 0,
268
+ cancelled: false,
269
+ truncated: false,
270
+ timestamp: Date.now(),
271
+ };
272
+ const branchSummaryMessage: AgentMessage = {
273
+ role: "branchSummary",
274
+ summary: "branch",
275
+ fromId: "x",
276
+ timestamp: Date.now(),
277
+ };
278
+ const compactionSummaryMessage: AgentMessage = {
279
+ role: "compactionSummary",
280
+ summary: "compact",
281
+ tokensBefore: 123,
282
+ timestamp: Date.now(),
283
+ };
284
+
285
+ expect(estimateTokens({ role: "user", content: "plain user", timestamp: Date.now() })).toBeGreaterThan(0);
286
+ expect(estimateTokens(assistantWithThinkingAndTool)).toBeGreaterThan(0);
287
+ expect(estimateTokens(customString)).toBeGreaterThan(0);
288
+ expect(estimateTokens(toolResultWithImage)).toBeGreaterThan(1000);
289
+ expect(estimateTokens(bashExecution)).toBeGreaterThan(0);
290
+ expect(estimateTokens(branchSummaryMessage)).toBeGreaterThan(0);
291
+ expect(estimateTokens(compactionSummaryMessage)).toBeGreaterThan(0);
292
+ expect(estimateTokens({ role: "unknown", timestamp: Date.now() } as unknown as AgentMessage)).toBe(0);
293
+ expect(
294
+ getLastAssistantUsage([createMessageEntry(createUserMessage("user")), createMessageEntry(assistant)]),
295
+ ).toBe(usage);
296
+ expect(
297
+ getLastAssistantUsage([
298
+ createMessageEntry({ ...assistant, stopReason: "aborted" }),
299
+ createMessageEntry({ ...assistant, stopReason: "error" }),
300
+ ]),
301
+ ).toBeUndefined();
302
+ expect(
303
+ getLastAssistantUsage([
304
+ createMessageEntry(createUserMessage("user")),
305
+ createMessageEntry(assistant),
306
+ createMessageEntry(createAssistantMessage("partial", createMockUsage(0, 0))),
307
+ ]),
308
+ ).toBe(usage);
309
+ expect(estimateContextTokens([createUserMessage("no usage")]).lastUsageIndex).toBeNull();
310
+ expect(estimateContextTokens([assistant, createUserMessage("tail")])).toMatchObject({
311
+ usageTokens: 20,
312
+ lastUsageIndex: 0,
313
+ });
314
+ const estimate = estimateContextTokens([
315
+ createUserMessage("Hello"),
316
+ assistant,
317
+ createUserMessage("continue"),
318
+ createAssistantMessage("Partial thinking", createMockUsage(0, 0)),
319
+ ]);
320
+ expect(estimate.usageTokens).toBe(20);
321
+ expect(estimate.lastUsageIndex).toBe(1);
322
+ expect(estimate.trailingTokens).toBeGreaterThan(0);
323
+ expect(estimate.tokens).toBe(20 + estimate.trailingTokens);
324
+ });
325
+
326
+ it("builds session context with a compaction entry", async () => {
327
+ const u1 = createMessageEntry(createUserMessage("1"));
328
+ const a1 = createMessageEntry(createAssistantMessage("a"), u1.id);
329
+ const u2 = createMessageEntry(createUserMessage("2"), a1.id);
330
+ const a2 = createMessageEntry(createAssistantMessage("b"), u2.id);
331
+ const compaction = createCompactionEntry("Summary of 1,a,2,b", a2.id, [
332
+ createUserMessage("2"),
333
+ createAssistantMessage("b"),
334
+ ]);
335
+ const u3 = createMessageEntry(createUserMessage("3"), compaction.id);
336
+ const a3 = createMessageEntry(createAssistantMessage("c"), u3.id);
337
+ const loaded = await buildSessionContext([u1, a1, u2, a2, compaction, u3, a3], undefined, BACKGROUND_CONTEXT);
338
+ expect(loaded).toHaveLength(5);
339
+ expect(loaded[0]?.role).toBe("compactionSummary");
340
+ expect(loaded.map((message) => message.role)).toEqual([
341
+ "compactionSummary",
342
+ "user",
343
+ "assistant",
344
+ "user",
345
+ "assistant",
346
+ ]);
347
+ });
348
+
349
+ it("prepares compaction using the latest compaction summary as previousSummary", async () => {
350
+ const u1 = createMessageEntry(createUserMessage("user msg 1"));
351
+ const a1 = createMessageEntry(createAssistantMessage("assistant msg 1"), u1.id);
352
+ const u2 = createMessageEntry(createUserMessage("user msg 2"), a1.id);
353
+ const a2 = createMessageEntry(createAssistantMessage("assistant msg 2", createMockUsage(5000, 1000)), u2.id);
354
+ const compaction1 = createCompactionEntry("First summary", a2.id);
355
+ const u3 = createMessageEntry(createUserMessage("user msg 3"), compaction1.id);
356
+ const a3 = createMessageEntry(createAssistantMessage("assistant msg 3", createMockUsage(8000, 2000)), u3.id);
357
+ const pathEntries = [u1, a1, u2, a2, compaction1, u3, a3];
358
+ const preparation = getOrThrow(prepareCompaction(pathEntries, DEFAULT_COMPACTION_SETTINGS));
359
+ expect(preparation).toBeDefined();
360
+ expect(preparation?.previousSummary).toBe("First summary");
361
+ expect(preparation?.retainedTail.length).toBeGreaterThan(0);
362
+ expect(preparation?.tokensBefore).toBe(
363
+ estimateContextTokens(await buildSessionContext(pathEntries, undefined, BACKGROUND_CONTEXT)).tokens,
364
+ );
365
+ });
366
+
367
+ it("carries a previous compaction's retained tail into the next preparation", () => {
368
+ const retainedUser = createUserMessage("retained user");
369
+ const retainedAssistant = createAssistantMessage("retained assistant");
370
+ const compaction = createCompactionEntry("previous summary", null, [retainedUser, retainedAssistant]);
371
+ const user = createMessageEntry(createUserMessage("new user"), compaction.id);
372
+ const assistant = createMessageEntry(createAssistantMessage("new assistant"), user.id);
373
+
374
+ const preparation = getOrThrow(
375
+ prepareCompaction([compaction, user, assistant], {
376
+ enabled: true,
377
+ reserveTokens: 100,
378
+ keepRecentTokens: 1,
379
+ }),
380
+ );
381
+ expect(preparation?.previousSummary).toBe("previous summary");
382
+ expect([
383
+ ...(preparation?.messagesToSummarize ?? []),
384
+ ...(preparation?.turnPrefixMessages ?? []),
385
+ ...(preparation?.retainedTail ?? []),
386
+ ]).toEqual([retainedUser, retainedAssistant, user.message, assistant.message]);
387
+ });
388
+
389
+ it("prepares split-turn compaction with prior file-operation details", () => {
390
+ const u1 = createMessageEntry(createUserMessage("user msg 1"));
391
+ const assistantMessage: AssistantMessage = {
392
+ ...createAssistantMessage("assistant msg 1"),
393
+ content: [{ type: "toolCall", id: "tool-1", name: "write", arguments: { path: "written.ts" } }],
394
+ };
395
+ const a1 = createMessageEntry(assistantMessage, u1.id);
396
+ const compaction1: CompactionEntry = {
397
+ ...createCompactionEntry("First summary", a1.id),
398
+ details: { readFiles: ["old-read.ts"], modifiedFiles: ["old-edit.ts", "written.ts"] },
399
+ };
400
+ const u2 = createMessageEntry(createUserMessage("large turn"), compaction1.id);
401
+ const a2 = createMessageEntry(createAssistantMessage("large assistant message"), u2.id);
402
+ const preparation = getOrThrow(
403
+ prepareCompaction([u1, a1, compaction1, u2, a2], {
404
+ enabled: true,
405
+ reserveTokens: 100,
406
+ keepRecentTokens: 1,
407
+ }),
408
+ );
409
+
410
+ expect(preparation).toMatchObject({ previousSummary: "First summary", isSplitTurn: true });
411
+ expect(preparation?.turnPrefixMessages.map((message) => message.role)).toEqual(["user"]);
412
+ expect([...preparation!.fileOps.read]).toContain("old-read.ts");
413
+ expect([...preparation!.fileOps.edited]).toContain("old-edit.ts");
414
+ expect([...preparation!.fileOps.edited]).toContain("written.ts");
415
+ });
416
+
417
+ it("does not prepare compaction when there is nothing valid to compact", () => {
418
+ const compaction = createCompactionEntry("already compacted");
419
+ expect(getOrThrow(prepareCompaction([compaction], DEFAULT_COMPACTION_SETTINGS))).toBeUndefined();
420
+ expect(getOrThrow(prepareCompaction([], DEFAULT_COMPACTION_SETTINGS))).toBeUndefined();
421
+ });
422
+
423
+ it("serializes conversation with truncated tool results", () => {
424
+ const longContent = "x".repeat(5000);
425
+ const messages = convertMessages([
426
+ {
427
+ role: "toolResult",
428
+ toolCallId: "tc1",
429
+ toolName: "read",
430
+ content: [{ type: "text", text: longContent }],
431
+ isError: false,
432
+ timestamp: Date.now(),
433
+ },
434
+ ]);
435
+ const result = serializeConversation(messages);
436
+ expect(result).toContain("[Tool result]:");
437
+ expect(result).toContain("[... 3000 more characters truncated]");
438
+ });
439
+
440
+ it("passes reasoning through generateSummary only for reasoning models with thinking enabled", async () => {
441
+ const messages: AgentMessage[] = [createUserMessage("Summarize this.")];
442
+ const seenOptions: Array<Record<string, unknown> | undefined> = [];
443
+ const { faux: fauxReasoning, model: reasoningModel } = createFauxModel(true);
444
+ fauxReasoning.setResponses([
445
+ (_context, options) => {
446
+ seenOptions.push(options as Record<string, unknown> | undefined);
447
+ return fauxAssistantMessage("## Goal\nTest summary");
448
+ },
449
+ ]);
450
+ getOrThrow(
451
+ await generateSummary(
452
+ messages,
453
+ models,
454
+ reasoningModel,
455
+ 2000,
456
+ undefined,
457
+ undefined,
458
+ "medium",
459
+ undefined,
460
+ undefined,
461
+ BACKGROUND_CONTEXT,
462
+ ),
463
+ );
464
+ expect(seenOptions[0]).toMatchObject({ reasoning: "medium" });
465
+
466
+ const { faux: fauxOff, model: offModel } = createFauxModel(true);
467
+ fauxOff.setResponses([
468
+ (_context, options) => {
469
+ seenOptions.push(options as Record<string, unknown> | undefined);
470
+ return fauxAssistantMessage("## Goal\nTest summary");
471
+ },
472
+ ]);
473
+ getOrThrow(
474
+ await generateSummary(
475
+ messages,
476
+ models,
477
+ offModel,
478
+ 2000,
479
+ undefined,
480
+ undefined,
481
+ "off",
482
+ undefined,
483
+ undefined,
484
+ BACKGROUND_CONTEXT,
485
+ ),
486
+ );
487
+ expect(seenOptions[1]).not.toHaveProperty("reasoning");
488
+
489
+ const { faux: fauxNonReasoning, model: nonReasoningModel } = createFauxModel(false);
490
+ fauxNonReasoning.setResponses([
491
+ (_context, options) => {
492
+ seenOptions.push(options as Record<string, unknown> | undefined);
493
+ return fauxAssistantMessage("## Goal\nTest summary");
494
+ },
495
+ ]);
496
+ getOrThrow(
497
+ await generateSummary(
498
+ messages,
499
+ models,
500
+ nonReasoningModel,
501
+ 2000,
502
+ undefined,
503
+ undefined,
504
+ "medium",
505
+ undefined,
506
+ undefined,
507
+ BACKGROUND_CONTEXT,
508
+ ),
509
+ );
510
+ expect(seenOptions[2]).not.toHaveProperty("reasoning");
511
+ });
512
+
513
+ it("includes previous summaries and custom instructions in generateSummary prompts", async () => {
514
+ const messages: AgentMessage[] = [createUserMessage("Summarize this.")];
515
+ let promptText = "";
516
+ const { faux, model } = createFauxModel(false);
517
+ faux.setResponses([
518
+ (context) => {
519
+ const message = context.messages[0];
520
+ const content = message?.role === "user" ? message.content : [];
521
+ promptText = Array.isArray(content) && content[0]?.type === "text" ? content[0].text : "";
522
+ return fauxAssistantMessage("## Goal\nTest summary");
523
+ },
524
+ ]);
525
+
526
+ const summary = getOrThrow(
527
+ await generateSummaryWithUsage(
528
+ messages,
529
+ models,
530
+ model,
531
+ 2000,
532
+ "focus",
533
+ "old summary",
534
+ undefined,
535
+ undefined,
536
+ undefined,
537
+ BACKGROUND_CONTEXT,
538
+ ),
539
+ );
540
+
541
+ expect(summary.text).toContain("Test summary");
542
+ expect(summary.usage.input).toBeGreaterThan(0);
543
+ expect(summary.usage.output).toBeGreaterThan(0);
544
+ expect(summary.usage.totalTokens).toBe(
545
+ summary.usage.input + summary.usage.output + summary.usage.cacheRead + summary.usage.cacheWrite,
546
+ );
547
+ expect(promptText).toContain("<previous-summary>\nold summary\n</previous-summary>");
548
+ expect(promptText).toContain("Additional focus: focus");
549
+ });
550
+
551
+ it("preserves the string result from generateSummary", async () => {
552
+ const messages: AgentMessage[] = [createUserMessage("Summarize this.")];
553
+ const { faux, model } = createFauxModel(false);
554
+ faux.setResponses([fauxAssistantMessage("## Goal\nTest summary")]);
555
+
556
+ expect(
557
+ getOrThrow(
558
+ await generateSummary(
559
+ messages,
560
+ models,
561
+ model,
562
+ 2000,
563
+ undefined,
564
+ undefined,
565
+ undefined,
566
+ undefined,
567
+ undefined,
568
+ BACKGROUND_CONTEXT,
569
+ ),
570
+ ),
571
+ ).toBe("## Goal\nTest summary");
572
+ });
573
+
574
+ it("returns error results for failed or aborted summary generations", async () => {
575
+ const messages: AgentMessage[] = [createUserMessage("Summarize this.")];
576
+ const { faux: errorFaux, model: errorModel } = createFauxModel(false);
577
+ errorFaux.setResponses([fauxAssistantMessage("", { stopReason: "error", errorMessage: "boom" })]);
578
+ const errorResult = await generateSummary(
579
+ messages,
580
+ models,
581
+ errorModel,
582
+ 2000,
583
+ undefined,
584
+ undefined,
585
+ undefined,
586
+ undefined,
587
+ undefined,
588
+ BACKGROUND_CONTEXT,
589
+ );
590
+ expect(errorResult).toMatchObject({
591
+ ok: false,
592
+ error: { code: "summarization_failed", message: "Summarization failed: boom" },
593
+ });
594
+
595
+ const { faux: abortedFaux, model: abortedModel } = createFauxModel(false);
596
+ abortedFaux.setResponses([fauxAssistantMessage("", { stopReason: "aborted", errorMessage: "stopped" })]);
597
+ const abortedResult = await generateSummary(
598
+ messages,
599
+ models,
600
+ abortedModel,
601
+ 2000,
602
+ undefined,
603
+ undefined,
604
+ undefined,
605
+ undefined,
606
+ undefined,
607
+ BACKGROUND_CONTEXT,
608
+ );
609
+ expect(abortedResult).toMatchObject({ ok: false, error: { code: "aborted", message: "stopped" } });
610
+ });
611
+
612
+ it("clamps compaction summary maxTokens to the model output cap", async () => {
613
+ const messages: AgentMessage[] = [createUserMessage("Summarize this.")];
614
+ const seenOptions: Array<Record<string, unknown> | undefined> = [];
615
+ const { faux, model } = createFauxModel(false, 128000);
616
+ faux.setResponses([
617
+ (_context, options) => {
618
+ seenOptions.push(options as Record<string, unknown> | undefined);
619
+ return fauxAssistantMessage("## Goal\nTest summary");
620
+ },
621
+ (_context, options) => {
622
+ seenOptions.push(options as Record<string, unknown> | undefined);
623
+ return fauxAssistantMessage("## Goal\nTest summary");
624
+ },
625
+ ]);
626
+ const preparation: CompactionPreparation = {
627
+ messagesToSummarize: messages,
628
+ turnPrefixMessages: messages,
629
+ retainedTail: messages,
630
+ isSplitTurn: true,
631
+ tokensBefore: 600000,
632
+ fileOps: { read: new Set(), written: new Set(), edited: new Set() },
633
+ settings: { enabled: true, reserveTokens: 500000, keepRecentTokens: 20000 },
634
+ };
635
+
636
+ getOrThrow(
637
+ await compact(preparation, models, model, undefined, undefined, undefined, undefined, BACKGROUND_CONTEXT),
638
+ );
639
+
640
+ expect(seenOptions.map((options) => options?.maxTokens)).toEqual([128000, 128000]);
641
+ expect(seenOptions.map((options) => options?.cacheRetention)).toEqual(["none", "none"]);
642
+ const sessionIds = seenOptions.map((options) => options?.sessionId);
643
+ expect(sessionIds[0]).not.toBe(sessionIds[1]);
644
+ });
645
+
646
+ it("retains per-request retries for non-harness compaction callers", async () => {
647
+ const messages: AgentMessage[] = [createUserMessage("Summarize this.")];
648
+ const preparation: CompactionPreparation = {
649
+ messagesToSummarize: messages,
650
+ turnPrefixMessages: [],
651
+ retainedTail: messages,
652
+ isSplitTurn: false,
653
+ tokensBefore: 100,
654
+ fileOps: { read: new Set(), written: new Set(), edited: new Set() },
655
+ settings: { enabled: true, reserveTokens: 2_000, keepRecentTokens: 20 },
656
+ };
657
+ const { faux, model } = createFauxModel(false);
658
+ faux.setResponses([
659
+ fauxAssistantMessage("", { stopReason: "error", errorMessage: "rate limit exceeded" }),
660
+ fauxAssistantMessage("recovered summary"),
661
+ ]);
662
+
663
+ expect(
664
+ getOrThrow(
665
+ await compact(
666
+ preparation,
667
+ models,
668
+ model,
669
+ undefined,
670
+ undefined,
671
+ { enabled: true, maxRetries: 1, baseDelayMs: 0 },
672
+ undefined,
673
+ BACKGROUND_CONTEXT,
674
+ ),
675
+ ).summary,
676
+ ).toContain("recovered summary");
677
+ });
678
+
679
+ it("returns compaction error results without throwing", async () => {
680
+ const messages: AgentMessage[] = [createUserMessage("Summarize this.")];
681
+ const preparation: CompactionPreparation = {
682
+ messagesToSummarize: messages,
683
+ turnPrefixMessages: [],
684
+ retainedTail: messages,
685
+ isSplitTurn: false,
686
+ tokensBefore: 100,
687
+ fileOps: { read: new Set(), written: new Set(), edited: new Set() },
688
+ settings: { enabled: true, reserveTokens: 2000, keepRecentTokens: 20 },
689
+ };
690
+ const { faux: historyFaux, model: historyModel } = createFauxModel(false);
691
+ historyFaux.setResponses([fauxAssistantMessage("", { stopReason: "error", errorMessage: "history failed" })]);
692
+ expect(
693
+ await compact(
694
+ preparation,
695
+ models,
696
+ historyModel,
697
+ undefined,
698
+ undefined,
699
+ undefined,
700
+ undefined,
701
+ BACKGROUND_CONTEXT,
702
+ ),
703
+ ).toMatchObject({
704
+ ok: false,
705
+ error: { code: "summarization_failed", message: "Summarization failed: history failed" },
706
+ });
707
+ });
708
+
709
+ it("combines usage for split-turn compaction summaries", async () => {
710
+ const messages: AgentMessage[] = [createUserMessage("Summarize this.")];
711
+ const { model } = createFauxModel(false);
712
+ const historyUsage = createMockUsage(1, 2, 3, 4);
713
+ const turnPrefixUsage = createMockUsage(5, 6, 7, 8);
714
+ const usageModels = createModelsWithSimpleResponses([
715
+ { ...fauxAssistantMessage("history summary"), usage: historyUsage },
716
+ { ...fauxAssistantMessage("turn prefix summary"), usage: turnPrefixUsage },
717
+ ]);
718
+ const preparation: CompactionPreparation = {
719
+ messagesToSummarize: messages,
720
+ turnPrefixMessages: messages,
721
+ isSplitTurn: true,
722
+ tokensBefore: 100,
723
+ retainedTail: messages,
724
+ fileOps: { read: new Set(), written: new Set(), edited: new Set() },
725
+ settings: { enabled: true, reserveTokens: 2000, keepRecentTokens: 20 },
726
+ };
727
+
728
+ const result = getOrThrow(
729
+ await compact(preparation, usageModels, model, undefined, undefined, undefined, undefined, BACKGROUND_CONTEXT),
730
+ );
731
+
732
+ expect(result.usage).toEqual(createMockUsage(6, 8, 10, 12));
733
+ });
734
+
735
+ it("passes reasoning through turn-prefix summaries when enabled", async () => {
736
+ const messages: AgentMessage[] = [createUserMessage("Summarize this.")];
737
+ const seenOptions: Array<Record<string, unknown> | undefined> = [];
738
+ const { faux, model } = createFauxModel(true);
739
+ faux.setResponses([
740
+ (_context, options) => {
741
+ seenOptions.push(options as Record<string, unknown> | undefined);
742
+ return fauxAssistantMessage("## Original Request\nTest summary");
743
+ },
744
+ ]);
745
+ const preparation: CompactionPreparation = {
746
+ messagesToSummarize: [],
747
+ turnPrefixMessages: messages,
748
+ retainedTail: messages,
749
+ isSplitTurn: true,
750
+ tokensBefore: 100,
751
+ fileOps: { read: new Set(), written: new Set(), edited: new Set() },
752
+ settings: { enabled: true, reserveTokens: 2000, keepRecentTokens: 20 },
753
+ };
754
+
755
+ getOrThrow(
756
+ await compact(preparation, models, model, undefined, "high", undefined, undefined, BACKGROUND_CONTEXT),
757
+ );
758
+
759
+ expect(seenOptions[0]).toMatchObject({ reasoning: "high" });
760
+ });
761
+
762
+ it("returns turn-prefix compaction errors without throwing", async () => {
763
+ const messages: AgentMessage[] = [createUserMessage("Summarize this.")];
764
+ const preparation: CompactionPreparation = {
765
+ messagesToSummarize: [],
766
+ turnPrefixMessages: messages,
767
+ retainedTail: messages,
768
+ isSplitTurn: true,
769
+ tokensBefore: 100,
770
+ fileOps: { read: new Set(), written: new Set(), edited: new Set() },
771
+ settings: { enabled: true, reserveTokens: 2000, keepRecentTokens: 20 },
772
+ };
773
+ const { faux, model } = createFauxModel(false);
774
+ faux.setResponses([fauxAssistantMessage("", { stopReason: "error", errorMessage: "prefix failed" })]);
775
+
776
+ expect(
777
+ await compact(preparation, models, model, undefined, undefined, undefined, undefined, BACKGROUND_CONTEXT),
778
+ ).toMatchObject({
779
+ ok: false,
780
+ error: { code: "summarization_failed", message: "Turn prefix summarization failed: prefix failed" },
781
+ });
782
+
783
+ const { faux: abortedFaux, model: abortedModel } = createFauxModel(false);
784
+ abortedFaux.setResponses([fauxAssistantMessage("", { stopReason: "aborted", errorMessage: "prefix stopped" })]);
785
+ expect(
786
+ await compact(
787
+ preparation,
788
+ models,
789
+ abortedModel,
790
+ undefined,
791
+ undefined,
792
+ undefined,
793
+ undefined,
794
+ BACKGROUND_CONTEXT,
795
+ ),
796
+ ).toMatchObject({
797
+ ok: false,
798
+ error: { code: "aborted", message: "prefix stopped" },
799
+ });
800
+ });
801
+
802
+ it("returns a compaction result with file details", async () => {
803
+ const u1 = createMessageEntry(createUserMessage("read a file"));
804
+ const assistantMessage: AssistantMessage = {
805
+ ...createAssistantMessage("calling tool", createMockUsage(1000, 200)),
806
+ content: [{ type: "toolCall", id: "tool-1", name: "read", arguments: { path: "src/index.ts" } }],
807
+ };
808
+ const a1 = createMessageEntry(assistantMessage, u1.id);
809
+ const u2 = createMessageEntry(createUserMessage("continue"), a1.id);
810
+ const a2 = createMessageEntry(createAssistantMessage("done", createMockUsage(4000, 500)), u2.id);
811
+ const preparation = getOrThrow(prepareCompaction([u1, a1, u2, a2], DEFAULT_COMPACTION_SETTINGS));
812
+ expect(preparation).toBeDefined();
813
+ const { faux, model } = createFauxModel(false);
814
+ faux.setResponses([fauxAssistantMessage("## Goal\nTest summary")]);
815
+ const result = getOrThrow(
816
+ await compact(preparation!, models, model, undefined, undefined, undefined, undefined, BACKGROUND_CONTEXT),
817
+ );
818
+ expect(result.summary.length).toBeGreaterThan(0);
819
+ expect(result.usage?.totalTokens).toBeGreaterThan(0);
820
+ expect(result.retainedTail?.length).toBeGreaterThan(0);
821
+ expect(result.details).toBeDefined();
822
+ });
823
+ });
824
+
825
+ function convertMessages(messages: Message[]): Message[] {
826
+ return messages;
827
+ }
packages/agent/test/harness/context.test.ts ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { describe, expect, it } from "vitest";
2
+ import {
3
+ BACKGROUND_CONTEXT,
4
+ getTelemetryContext,
5
+ TODO_CONTEXT,
6
+ withTelemetryContext,
7
+ } from "../../src/harness/context.ts";
8
+ import { InMemoryTelemetryContext, NOOP_TELEMETRY_CONTEXT } from "../../src/index.ts";
9
+
10
+ describe("harness Context telemetry", () => {
11
+ it("uses no-op telemetry when none is attached", () => {
12
+ expect(getTelemetryContext(BACKGROUND_CONTEXT)).toBe(NOOP_TELEMETRY_CONTEXT);
13
+ expect(getTelemetryContext(TODO_CONTEXT)).toBe(NOOP_TELEMETRY_CONTEXT);
14
+ });
15
+
16
+ it("carries telemetry as an ordinary context value", async () => {
17
+ const telemetry = new InMemoryTelemetryContext();
18
+ const context = withTelemetryContext(telemetry, BACKGROUND_CONTEXT);
19
+
20
+ await getTelemetryContext(context).startSpan({ name: "parent" }, async (span) => {
21
+ const childContext = withTelemetryContext(span, context);
22
+ await getTelemetryContext(childContext).startSpan({ name: "child" }, () => undefined);
23
+ });
24
+
25
+ const spans = telemetry.getSpans();
26
+ expect(spans.map((span) => span.name)).toEqual(["parent", "child"]);
27
+ expect(spans[1]?.parentId).toBe(spans[0]?.id);
28
+ });
29
+ });
packages/agent/test/harness/execution-assistant.test.ts ADDED
@@ -0,0 +1,343 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import {
2
+ type Api,
3
+ type AssistantMessage,
4
+ createAssistantMessageEventStream,
5
+ fauxAssistantMessage,
6
+ fauxProvider,
7
+ type Message,
8
+ type Model,
9
+ type SimpleStreamOptions,
10
+ type UserMessage,
11
+ } from "@earendil-works/pi-ai";
12
+ import { NOOP_TELEMETRY_CONTEXT } from "@earendil-works/pi-telemetry";
13
+ import { describe, expect, it } from "vitest";
14
+ import { BACKGROUND_CONTEXT, withAbortSignal } from "../../src/harness/context.ts";
15
+ import { type AssistantResponseMetadata, streamHarnessAssistant } from "../../src/harness/execution/assistant.ts";
16
+ import { AbortRequested } from "../../src/harness/execution/effect-gate.ts";
17
+ import type { AgentMessage } from "../../src/types.ts";
18
+
19
+ function usage() {
20
+ return {
21
+ input: 1,
22
+ output: 2,
23
+ cacheRead: 3,
24
+ cacheWrite: 4,
25
+ totalTokens: 10,
26
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
27
+ };
28
+ }
29
+
30
+ function model(): Model<Api> {
31
+ return {
32
+ id: "model",
33
+ name: "Model",
34
+ api: "test",
35
+ provider: "provider",
36
+ baseUrl: "https://example.invalid",
37
+ reasoning: true,
38
+ input: ["text"],
39
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
40
+ contextWindow: 128_000,
41
+ maxTokens: 16_384,
42
+ };
43
+ }
44
+
45
+ function user(text: string): UserMessage {
46
+ return { role: "user", content: text, timestamp: 1 };
47
+ }
48
+
49
+ function assistant(
50
+ text: string,
51
+ stopReason: Exclude<AssistantMessage["stopReason"], "pending"> = "stop",
52
+ ): AssistantMessage & { stopReason: Exclude<AssistantMessage["stopReason"], "pending"> } {
53
+ return {
54
+ role: "assistant",
55
+ content: [{ type: "text", text }],
56
+ api: "test",
57
+ provider: "provider",
58
+ model: "model",
59
+ usage: usage(),
60
+ stopReason,
61
+ ...(stopReason === "error" ? { errorMessage: text } : {}),
62
+ timestamp: 2,
63
+ };
64
+ }
65
+
66
+ function toProviderMessages(messages: AgentMessage[]): Message[] {
67
+ return messages.filter(
68
+ (message): message is Message =>
69
+ message.role === "user" || message.role === "assistant" || message.role === "toolResult",
70
+ );
71
+ }
72
+
73
+ describe("streamHarnessAssistant", () => {
74
+ it("maps curated options and runs the assistant lifecycle without mutating input", async () => {
75
+ const input: AgentMessage[] = [user("original")];
76
+ const originalArray = input;
77
+ const requestModel = model();
78
+ const controller = new AbortController();
79
+ const order: string[] = [];
80
+ const starts: AssistantMessage[] = [];
81
+ const updates: AssistantMessage[] = [];
82
+ const ends: AssistantMessage[] = [];
83
+ let transformedInputWasCopy = false;
84
+ let convertedMessages: AgentMessage[] = [];
85
+ let requestContext: Parameters<NonNullable<SimpleStreamOptions["onPayload"]>>[0] | undefined;
86
+ let receivedContext: { systemPrompt?: string; messages: Message[]; tools?: unknown[] } | undefined;
87
+ let receivedOptions: SimpleStreamOptions | undefined;
88
+ let responseMetadata: AssistantResponseMetadata | undefined;
89
+ let startEventType: string | undefined;
90
+
91
+ const result = await streamHarnessAssistant(
92
+ input,
93
+ {
94
+ model: requestModel,
95
+ systemPrompt: "system",
96
+ thinkingLevel: "high",
97
+ streamOptions: {
98
+ transport: "websocket",
99
+ timeoutMs: 123,
100
+ maxRetries: 2,
101
+ maxRetryDelayMs: 456,
102
+ headers: { authorization: "test" },
103
+ metadata: { tenant: "one" },
104
+ cacheRetention: "long",
105
+ deferred: { window: "1h" },
106
+ },
107
+ transformContext: async (context) => {
108
+ order.push("transform_context");
109
+ transformedInputWasCopy = context.messages !== originalArray;
110
+ context.messages.push(user("injected"));
111
+ return { messages: context.messages, systemPrompt: "transformed system" };
112
+ },
113
+ toProviderMessages: (messages) => {
114
+ order.push("to_provider_messages");
115
+ convertedMessages = messages;
116
+ return toProviderMessages(messages);
117
+ },
118
+ beforePayload: (payload, seenModel) => {
119
+ order.push("before_payload");
120
+ expect(seenModel.id).toBe("resolved");
121
+ requestContext = payload;
122
+ return { replaced: true };
123
+ },
124
+ afterResponse: async (message, metadata) => {
125
+ order.push("after_response");
126
+ responseMetadata = metadata;
127
+ return { ...message, content: [{ type: "text", text: "transformed" }] };
128
+ },
129
+ request: async (context, options) => {
130
+ order.push("request");
131
+ receivedContext = context;
132
+ receivedOptions = options;
133
+ expect(await options.onPayload?.({ original: true }, { ...requestModel, id: "resolved" })).toEqual({
134
+ replaced: true,
135
+ });
136
+ await options.onResponse?.({ status: 201, headers: { "request-id": "r1" } }, requestModel);
137
+ const stream = createAssistantMessageEventStream();
138
+ queueMicrotask(() => {
139
+ const initial = { ...assistant(""), stopReason: "pending" as const };
140
+ const partial = { ...initial, content: [{ type: "text" as const, text: "raw" }] };
141
+ stream.push({ type: "start", partial: initial });
142
+ stream.push({ type: "text_delta", contentIndex: 0, delta: "raw", partial });
143
+ stream.push({ type: "done", reason: "stop", message: assistant("raw") });
144
+ });
145
+ return stream;
146
+ },
147
+ observer: {
148
+ start(message, event) {
149
+ order.push("observer_start");
150
+ starts.push(message);
151
+ startEventType = event.type;
152
+ },
153
+ update(message) {
154
+ order.push("observer_update");
155
+ updates.push(message);
156
+ },
157
+ end(message) {
158
+ order.push("observer_end");
159
+ ends.push(message);
160
+ },
161
+ },
162
+ },
163
+ withAbortSignal(controller.signal, BACKGROUND_CONTEXT),
164
+ );
165
+
166
+ expect(input).toEqual([user("original")]);
167
+ expect(transformedInputWasCopy).toBe(true);
168
+ expect(convertedMessages).toEqual([user("original"), user("injected")]);
169
+ expect(receivedContext).toMatchObject({
170
+ systemPrompt: "transformed system",
171
+ messages: [user("original"), user("injected")],
172
+ });
173
+ expect(requestContext).toEqual({ original: true });
174
+ expect(receivedOptions).toMatchObject({
175
+ transport: "websocket",
176
+ timeoutMs: 123,
177
+ maxRetries: 2,
178
+ maxRetryDelayMs: 456,
179
+ headers: { authorization: "test" },
180
+ metadata: { tenant: "one" },
181
+ cacheRetention: "long",
182
+ deferred: { window: "1h" },
183
+ reasoning: "high",
184
+ signal: controller.signal,
185
+ telemetryContext: NOOP_TELEMETRY_CONTEXT,
186
+ });
187
+ expect(responseMetadata).toEqual({ status: 201, headers: { "request-id": "r1" } });
188
+ expect(starts).toHaveLength(1);
189
+ expect(startEventType).toBe("start");
190
+ expect(starts[0]).not.toBe(updates[0]);
191
+ expect(updates).toHaveLength(1);
192
+ expect(ends[0]).toBe(result);
193
+ expect(result.content).toEqual([{ type: "text", text: "transformed" }]);
194
+ expect(order).toEqual([
195
+ "transform_context",
196
+ "to_provider_messages",
197
+ "request",
198
+ "before_payload",
199
+ "observer_start",
200
+ "observer_update",
201
+ "after_response",
202
+ "observer_end",
203
+ ]);
204
+ });
205
+
206
+ it("runs against the faux provider request boundary", async () => {
207
+ const faux = fauxProvider({ tokenSize: { min: 1, max: 1 } });
208
+ faux.setResponses([fauxAssistantMessage("hello")]);
209
+ const lifecycle: string[] = [];
210
+ let seenContext: Message[] = [];
211
+
212
+ const result = await streamHarnessAssistant(
213
+ [user("prompt")],
214
+ {
215
+ model: faux.getModel(),
216
+ systemPrompt: "system",
217
+ thinkingLevel: "off",
218
+ streamOptions: {},
219
+ toProviderMessages,
220
+ request: (context, options) => {
221
+ seenContext = context.messages;
222
+ return faux.provider.streamSimple(faux.getModel(), context, options);
223
+ },
224
+ observer: {
225
+ start() {
226
+ lifecycle.push("start");
227
+ },
228
+ update() {
229
+ lifecycle.push("update");
230
+ },
231
+ end() {
232
+ lifecycle.push("end");
233
+ },
234
+ },
235
+ },
236
+ BACKGROUND_CONTEXT,
237
+ );
238
+
239
+ expect(seenContext).toEqual([user("prompt")]);
240
+ expect(result.content).toEqual([{ type: "text", text: "hello" }]);
241
+ expect(lifecycle[0]).toBe("start");
242
+ expect(lifecycle.at(-1)).toBe("end");
243
+ expect(lifecycle.filter((event) => event === "update").length).toBeGreaterThan(0);
244
+ });
245
+
246
+ it("rejects a successful terminal event before start", async () => {
247
+ const final = assistant("complete");
248
+ let options: SimpleStreamOptions | undefined;
249
+ await expect(
250
+ streamHarnessAssistant(
251
+ [user("prompt")],
252
+ {
253
+ model: model(),
254
+ systemPrompt: "system",
255
+ thinkingLevel: "off",
256
+ streamOptions: {},
257
+ toProviderMessages,
258
+ request: (_context, requestOptions) => {
259
+ options = requestOptions;
260
+ const stream = createAssistantMessageEventStream();
261
+ queueMicrotask(() => stream.push({ type: "done", reason: "stop", message: final }));
262
+ return stream;
263
+ },
264
+ observer: { start() {}, update() {}, end() {} },
265
+ },
266
+ BACKGROUND_CONTEXT,
267
+ ),
268
+ ).rejects.toThrow("done before start");
269
+ expect(options).not.toHaveProperty("reasoning");
270
+ });
271
+
272
+ it("keeps the raw settlement when cancellation interrupts after_response", async () => {
273
+ const final = assistant("raw");
274
+ const ended: AssistantMessage[] = [];
275
+ const result = await streamHarnessAssistant(
276
+ [user("prompt")],
277
+ {
278
+ model: model(),
279
+ systemPrompt: "system",
280
+ thinkingLevel: "off",
281
+ streamOptions: {},
282
+ toProviderMessages,
283
+ request: () => {
284
+ const stream = createAssistantMessageEventStream();
285
+ queueMicrotask(() => {
286
+ stream.push({ type: "start", partial: { ...final, content: [], stopReason: "pending" } });
287
+ stream.push({ type: "done", reason: "stop", message: final });
288
+ });
289
+ return stream;
290
+ },
291
+ afterResponse: async () => {
292
+ throw new AbortRequested(Promise.resolve());
293
+ },
294
+ observer: {
295
+ start() {},
296
+ update() {},
297
+ end(message) {
298
+ ended.push(message);
299
+ },
300
+ },
301
+ },
302
+ BACKGROUND_CONTEXT,
303
+ );
304
+
305
+ expect(result).toBe(final);
306
+ expect(ended).toEqual([final]);
307
+ });
308
+
309
+ it("returns provider error settlements through the same lifecycle", async () => {
310
+ const final = assistant("provider failed", "error");
311
+ const events: string[] = [];
312
+ const result = await streamHarnessAssistant(
313
+ [user("prompt")],
314
+ {
315
+ model: model(),
316
+ systemPrompt: "system",
317
+ thinkingLevel: "off",
318
+ streamOptions: {},
319
+ toProviderMessages,
320
+ request: () => {
321
+ const stream = createAssistantMessageEventStream();
322
+ queueMicrotask(() => stream.push({ type: "error", reason: "error", error: final }));
323
+ return stream;
324
+ },
325
+ observer: {
326
+ start() {
327
+ throw new Error("pre-generation error must not synthesize start");
328
+ },
329
+ update() {
330
+ events.push("update");
331
+ },
332
+ end(message) {
333
+ events.push(`end:${message.stopReason}`);
334
+ },
335
+ },
336
+ },
337
+ BACKGROUND_CONTEXT,
338
+ );
339
+
340
+ expect(result).toBe(final);
341
+ expect(events).toEqual(["end:error"]);
342
+ });
343
+ });
packages/agent/test/harness/execution-primitives.test.ts ADDED
@@ -0,0 +1,670 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { fauxProvider } from "@earendil-works/pi-ai";
2
+ import { describe, expect, it, vi } from "vitest";
3
+ import {
4
+ BACKGROUND_CONTEXT,
5
+ createContextKey,
6
+ getTelemetryContext,
7
+ withAbortSignal,
8
+ withContextValue,
9
+ withTelemetryContext,
10
+ } from "../../src/harness/context.ts";
11
+ import { HarnessEventBus } from "../../src/harness/events.ts";
12
+ import { AbortRequested, createGate } from "../../src/harness/execution/effect-gate.ts";
13
+ import { HookRegistry } from "../../src/harness/hooks.ts";
14
+ import { InMemoryTelemetryContext } from "../../src/index.ts";
15
+
16
+ function deferred(): { promise: Promise<void>; resolve(): void } {
17
+ let resolvePromise: (() => void) | undefined;
18
+ const promise = new Promise<void>((resolve) => {
19
+ resolvePromise = resolve;
20
+ });
21
+ return { promise, resolve: () => resolvePromise?.() };
22
+ }
23
+
24
+ describe("createGate", () => {
25
+ it("closes starts synchronously and signals only after cancellation commits", async () => {
26
+ const { gate, control } = createGate();
27
+ const cancellation = deferred();
28
+ control.beginAbort(cancellation.promise);
29
+
30
+ let refusal: unknown;
31
+ try {
32
+ gate.admit(() => undefined);
33
+ } catch (error) {
34
+ refusal = error;
35
+ }
36
+ expect(refusal).toBeInstanceOf(AbortRequested);
37
+ expect((refusal as AbortRequested).cancellation).toBe(cancellation.promise);
38
+ expect(gate.signal.aborted).toBe(false);
39
+ cancellation.resolve();
40
+ await cancellation.promise;
41
+ control.signalAbort();
42
+ expect(gate.signal.aborted).toBe(true);
43
+ });
44
+
45
+ it("permanently closes and signals admitted work", () => {
46
+ const { gate, control } = createGate();
47
+ const error = new Error("closed");
48
+ control.close(error);
49
+ expect(() => gate.admit(() => undefined)).toThrow(error);
50
+ expect(gate.signal.aborted).toBe(true);
51
+ });
52
+ });
53
+
54
+ describe("HookRegistry", () => {
55
+ it("aggregates before_run messages in registration order with each handler seeing prior output", async () => {
56
+ const errors: Error[] = [];
57
+ const hooks = new HookRegistry((error) => {
58
+ errors.push(error);
59
+ });
60
+ const second = vi.fn((event: { prompt: Array<{ role: string }> }) => {
61
+ expect(event.prompt).toHaveLength(2);
62
+ return { messages: [{ role: "user" as const, content: "second", timestamp: 3 }] };
63
+ });
64
+ hooks.on("before_run", () => ({ messages: [{ role: "user", content: "first", timestamp: 2 }] }));
65
+ hooks.on("before_run", second);
66
+
67
+ const result = await hooks.runWithGate(
68
+ "before_run",
69
+ {
70
+ lane: "main",
71
+ runId: "run",
72
+ prompt: [{ role: "user", content: "prompt", timestamp: 1 }],
73
+ resources: {},
74
+ },
75
+ createGate().gate,
76
+ BACKGROUND_CONTEXT,
77
+ );
78
+
79
+ expect(result).toMatchObject({
80
+ messages: [
81
+ { role: "user", content: "first" },
82
+ { role: "user", content: "second" },
83
+ ],
84
+ });
85
+ expect(second).toHaveBeenCalledOnce();
86
+ expect(errors).toEqual([]);
87
+ });
88
+
89
+ it("checks the effect gate immediately before the complete before_run pipeline", async () => {
90
+ const hooks = new HookRegistry(() => {});
91
+ const calls: string[] = [];
92
+ const release = deferred();
93
+ hooks.on("before_run", async () => {
94
+ calls.push("first:start");
95
+ await release.promise;
96
+ calls.push("first:end");
97
+ return undefined;
98
+ });
99
+ hooks.on("before_run", () => {
100
+ calls.push("second");
101
+ return undefined;
102
+ });
103
+ const event = { lane: "main", runId: "run", prompt: [], resources: {} };
104
+ const closed = new Error("closed");
105
+ const closedGate = createGate();
106
+ closedGate.control.close(closed);
107
+ expect(() => hooks.runWithGate("before_run", event, closedGate.gate, BACKGROUND_CONTEXT)).toThrow(closed);
108
+ expect(calls).toEqual([]);
109
+
110
+ const running = hooks.runWithGate("before_run", event, createGate().gate, BACKGROUND_CONTEXT);
111
+ expect(calls).toEqual(["first:start"]);
112
+ hooks.on("before_run", () => {
113
+ calls.push("late");
114
+ return undefined;
115
+ });
116
+ hooks.close(closed);
117
+ release.resolve();
118
+ await running;
119
+ expect(calls).toEqual(["first:start", "first:end", "second"]);
120
+ });
121
+
122
+ it("rejects pre-aborted invocations and combines admitted hook cancellation with the effect gate", async () => {
123
+ const event = { operation: "run" as const, lane: "main", runId: "run" };
124
+ const preAbortedHooks = new HookRegistry(() => {});
125
+ const handler = vi.fn();
126
+ preAbortedHooks.on("before_drive", handler);
127
+ const preAbortedGate = createGate();
128
+ const invocationController = new AbortController();
129
+ const abortReason = new Error("invocation aborted");
130
+ invocationController.abort(abortReason);
131
+
132
+ expect(() =>
133
+ preAbortedHooks.runWithGate(
134
+ "before_drive",
135
+ event,
136
+ preAbortedGate.gate,
137
+ withAbortSignal(invocationController.signal, BACKGROUND_CONTEXT),
138
+ ),
139
+ ).toThrow(abortReason);
140
+ expect(handler).not.toHaveBeenCalled();
141
+ expect(() => preAbortedGate.gate.admit(() => undefined)).not.toThrow();
142
+
143
+ const admittedHooks = new HookRegistry(() => {});
144
+ const admittedGate = createGate();
145
+ let admittedSignal: AbortSignal | undefined;
146
+ admittedHooks.on("before_drive", (_event, context) => {
147
+ admittedSignal = context.abortSignal;
148
+ });
149
+ await admittedHooks.runWithGate("before_drive", event, admittedGate.gate, BACKGROUND_CONTEXT);
150
+ expect(admittedSignal?.aborted).toBe(false);
151
+
152
+ const gateReason = new Error("gate closed");
153
+ admittedGate.control.close(gateReason);
154
+ expect(admittedSignal?.aborted).toBe(true);
155
+ expect(admittedSignal?.reason).toBe(gateReason);
156
+ });
157
+
158
+ it("passes tool handlers a child context of the active hook span", async () => {
159
+ const telemetry = new InMemoryTelemetryContext();
160
+ const valueKey = createContextKey<string>("hook.test.value");
161
+ const hooks = new HookRegistry(() => {});
162
+ let receivedValue: string | undefined;
163
+ hooks.on("before_tool", async (_event, context) => {
164
+ receivedValue = context.value(valueKey);
165
+ await getTelemetryContext(context).startSpan({ name: "handler.child" }, () => undefined);
166
+ return undefined;
167
+ });
168
+
169
+ await telemetry.startSpan({ name: "invocation" }, (invocationSpan) =>
170
+ hooks.runToolWithGate(
171
+ "before_tool",
172
+ {
173
+ lane: "main",
174
+ runId: "run",
175
+ toolCallId: "call",
176
+ toolName: "tool",
177
+ args: {},
178
+ },
179
+ createGate().gate,
180
+ withContextValue(valueKey, "preserved", withTelemetryContext(invocationSpan, BACKGROUND_CONTEXT)),
181
+ ),
182
+ );
183
+
184
+ expect(receivedValue).toBe("preserved");
185
+ const spans = telemetry.getSpans();
186
+ const invocationSpan = spans.find((span) => span.name === "invocation");
187
+ const hookSpan = spans.find((span) => span.name === "pi.harness.hook");
188
+ const handlerSpan = spans.find((span) => span.name === "handler.child");
189
+ expect(hookSpan?.parentId).toBe(invocationSpan?.id);
190
+ expect(handlerSpan?.parentId).toBe(hookSpan?.id);
191
+ });
192
+
193
+ it("treats registration ids as optional metadata and fails before_drive closed", async () => {
194
+ const errors: Error[] = [];
195
+ const hooks = new HookRegistry((error) => {
196
+ errors.push(error);
197
+ });
198
+ const failure = new Error("prerequisite failed");
199
+ const later = vi.fn();
200
+ hooks.on(
201
+ "before_drive",
202
+ () => {
203
+ throw failure;
204
+ },
205
+ { id: "duplicate" },
206
+ );
207
+ hooks.on("before_drive", later, { id: "duplicate" });
208
+
209
+ await expect(
210
+ hooks.runWithGate(
211
+ "before_drive",
212
+ { lane: "main", runId: "run", operation: "run" },
213
+ createGate().gate,
214
+ BACKGROUND_CONTEXT,
215
+ ),
216
+ ).rejects.toBe(failure);
217
+ expect(later).not.toHaveBeenCalled();
218
+ expect(errors).toEqual([failure]);
219
+ });
220
+
221
+ it("chains transform_context output and isolates handler failures", async () => {
222
+ const errors: Error[] = [];
223
+ const hooks = new HookRegistry((error) => {
224
+ errors.push(error);
225
+ });
226
+ const messages = [{ role: "user" as const, content: "transformed", timestamp: 2 }];
227
+ hooks.on("transform_context", () => ({ messages, systemPrompt: "first" }));
228
+ hooks.on("transform_context", (event) => {
229
+ expect(event.messages).toBe(messages);
230
+ expect(event.systemPrompt).toBe("first");
231
+ throw new Error("ignored transform failure");
232
+ });
233
+ hooks.on("transform_context", (event) => {
234
+ expect(event.messages).toBe(messages);
235
+ expect(event.systemPrompt).toBe("first");
236
+ return { systemPrompt: "final" };
237
+ });
238
+
239
+ const result = await hooks.runWithGate(
240
+ "transform_context",
241
+ {
242
+ lane: "main",
243
+ runId: "run",
244
+ messages: [{ role: "user", content: "original", timestamp: 1 }],
245
+ systemPrompt: "base",
246
+ },
247
+ createGate().gate,
248
+ BACKGROUND_CONTEXT,
249
+ );
250
+
251
+ expect(result).toEqual({ messages, systemPrompt: "final" });
252
+ expect(errors).toHaveLength(1);
253
+ expect(errors[0]?.message).toBe("ignored transform failure");
254
+ });
255
+
256
+ it("preserves clear-all before_request patches across later handlers", async () => {
257
+ const hooks = new HookRegistry(() => {});
258
+ hooks.on("before_request", () => ({ streamOptions: { headers: undefined, metadata: undefined } }));
259
+ hooks.on("before_request", (event) => {
260
+ expect(event.streamOptions.headers).toBeUndefined();
261
+ expect(event.streamOptions.metadata).toBeUndefined();
262
+ return { streamOptions: { headers: { c: "3" }, metadata: { y: 2 } } };
263
+ });
264
+ const result = await hooks.runWithGate(
265
+ "before_request",
266
+ {
267
+ lane: "main",
268
+ runId: "run",
269
+ model: fauxProvider().getModel(),
270
+ step: "assistant",
271
+ attempt: 1,
272
+ streamOptions: { headers: { a: "1", b: "2" }, metadata: { x: 1 } },
273
+ },
274
+ createGate().gate,
275
+ BACKGROUND_CONTEXT,
276
+ );
277
+ expect(result).toEqual({
278
+ streamOptions: {
279
+ headers: { a: undefined, b: undefined, c: "3" },
280
+ metadata: { x: undefined, y: 2 },
281
+ },
282
+ });
283
+ });
284
+
285
+ it("preserves earlier after_tool fields when a later patch returns undefined", async () => {
286
+ const hooks = new HookRegistry(() => {});
287
+ hooks.on("after_tool", () => ({ content: [{ type: "text", text: "patched" }] }));
288
+ hooks.on("after_tool", () => ({ content: undefined, isError: false }));
289
+ const result = await hooks.runWithGate(
290
+ "after_tool",
291
+ {
292
+ lane: "main",
293
+ runId: "run",
294
+ toolCallId: "call",
295
+ toolName: "tool",
296
+ args: {},
297
+ content: [{ type: "text", text: "raw" }],
298
+ isError: true,
299
+ },
300
+ createGate().gate,
301
+ BACKGROUND_CONTEXT,
302
+ );
303
+ expect(result).toEqual({ content: [{ type: "text", text: "patched" }], isError: false });
304
+ });
305
+
306
+ it("accepts explicit false structural declines and rejects true conflicts", async () => {
307
+ const errors: Error[] = [];
308
+ const hooks = new HookRegistry((error) => {
309
+ errors.push(error);
310
+ });
311
+ const ignored = { summary: "ignored", readFiles: [], modifiedFiles: [] };
312
+ const selected = { summary: "selected", readFiles: [], modifiedFiles: [] };
313
+ hooks.on("before_navigation", () => ({ decline: true, summary: ignored }));
314
+ hooks.on("before_navigation", () => ({ decline: false, summary: selected }));
315
+
316
+ const result = await hooks.runWithGate(
317
+ "before_navigation",
318
+ {
319
+ lane: "main",
320
+ runId: "run",
321
+ targetId: "target",
322
+ preparation: {
323
+ messages: [],
324
+ fileOps: { read: new Set(), written: new Set(), edited: new Set() },
325
+ totalTokens: 0,
326
+ },
327
+ },
328
+ createGate().gate,
329
+ BACKGROUND_CONTEXT,
330
+ );
331
+ expect(result).toEqual({ decline: false, summary: selected });
332
+ expect(errors).toHaveLength(1);
333
+ expect(errors[0].message).toMatch(/cannot return both decline and summary/);
334
+ });
335
+
336
+ it("admits the complete before_drive pipeline as one gated effect", async () => {
337
+ const hooks = new HookRegistry(() => {});
338
+ const calls: string[] = [];
339
+ const release = deferred();
340
+ hooks.on("before_drive", async () => {
341
+ calls.push("first:start");
342
+ await release.promise;
343
+ calls.push("first:end");
344
+ });
345
+ hooks.on("before_drive", () => {
346
+ calls.push("second");
347
+ });
348
+ const event = { operation: "run" as const, lane: "main", runId: "run" };
349
+
350
+ const abortFirstGate = createGate();
351
+ const cancellation = Promise.resolve();
352
+ abortFirstGate.control.beginAbort(cancellation);
353
+ expect(() => hooks.runWithGate("before_drive", event, abortFirstGate.gate, BACKGROUND_CONTEXT)).toThrow(
354
+ AbortRequested,
355
+ );
356
+ expect(calls).toEqual([]);
357
+
358
+ const startFirstGate = createGate();
359
+ const running = hooks.runWithGate("before_drive", event, startFirstGate.gate, BACKGROUND_CONTEXT);
360
+ expect(calls).toEqual(["first:start"]);
361
+ startFirstGate.control.beginAbort(cancellation);
362
+ startFirstGate.control.signalAbort();
363
+ release.resolve();
364
+ await running;
365
+ expect(calls).toEqual(["first:start", "first:end", "second"]);
366
+ });
367
+ });
368
+
369
+ describe("HarnessEventBus", () => {
370
+ it("buffers between snapshot and start, then delivers each event once in order", async () => {
371
+ const bus = new HarnessEventBus();
372
+ const watcher = bus.watch({ tipId: null }, () => true, BACKGROUND_CONTEXT);
373
+ await bus.emit({ type: "run_start", runId: "one", startedAt: 1, lane: "main" }, BACKGROUND_CONTEXT);
374
+ const seen: string[] = [];
375
+ watcher.start((event) => {
376
+ seen.push(`${event.type}:${"runId" in event ? event.runId : ""}`);
377
+ });
378
+ await bus.emit({ type: "run_start", runId: "two", startedAt: 1, lane: "main" }, BACKGROUND_CONTEXT);
379
+ await new Promise((resolve) => setTimeout(resolve, 0));
380
+ expect(watcher.snapshot).toEqual({ tipId: null });
381
+ expect(seen).toEqual(["run_start:one", "run_start:two"]);
382
+ watcher.unsubscribe();
383
+ await bus.emit({ type: "run_start", runId: "three", startedAt: 1, lane: "main" }, BACKGROUND_CONTEXT);
384
+ expect(seen).toHaveLength(2);
385
+ });
386
+
387
+ it("drops pre-snapshot delivery and holds later events when resnapshotting inside a listener", async () => {
388
+ const bus = new HarnessEventBus();
389
+ const listenerStarted = deferred();
390
+ const releaseListener = deferred();
391
+ const resnapshotDone = deferred();
392
+ const watcher = bus.watch(
393
+ { version: "old" },
394
+ () => true,
395
+ BACKGROUND_CONTEXT,
396
+ async (_context, markBoundary) => {
397
+ markBoundary();
398
+ return { version: "fresh" };
399
+ },
400
+ );
401
+ const queueEvents: string[] = [];
402
+ watcher.start(async (event, context) => {
403
+ if (event.type === "run_start" && event.runId === "blocking") {
404
+ listenerStarted.resolve();
405
+ await releaseListener.promise;
406
+ } else if (event.type === "navigation_end") {
407
+ await watcher.resnapshot(context);
408
+ resnapshotDone.resolve();
409
+ } else if (event.type === "queue_update") {
410
+ queueEvents.push(event.queues[0]?.entryId ?? "empty");
411
+ }
412
+ });
413
+ await bus.emit({ type: "run_start", runId: "blocking", startedAt: 1, lane: "main" }, BACKGROUND_CONTEXT);
414
+ await listenerStarted.promise;
415
+ const queued = bus.emitBatch(
416
+ [
417
+ {
418
+ type: "navigation_end",
419
+ runId: "navigation",
420
+ status: "completed",
421
+ fromTipId: null,
422
+ tipId: null,
423
+ endedAt: 2,
424
+ lane: "main",
425
+ },
426
+ {
427
+ type: "queue_update",
428
+ queues: [
429
+ {
430
+ entryId: "stale",
431
+ kind: "nextRun",
432
+ type: "message",
433
+ message: { role: "user", content: "stale", timestamp: 2 },
434
+ },
435
+ ],
436
+ lane: "main",
437
+ },
438
+ ],
439
+ BACKGROUND_CONTEXT,
440
+ );
441
+ releaseListener.resolve();
442
+ await Promise.all([queued, resnapshotDone.promise]);
443
+
444
+ expect(watcher.snapshot).toEqual({ version: "fresh" });
445
+ expect(queueEvents).toEqual([]);
446
+ await bus.emit(
447
+ {
448
+ type: "queue_update",
449
+ queues: [
450
+ {
451
+ entryId: "later",
452
+ kind: "nextRun",
453
+ type: "message",
454
+ message: { role: "user", content: "later", timestamp: 3 },
455
+ },
456
+ ],
457
+ lane: "main",
458
+ },
459
+ BACKGROUND_CONTEXT,
460
+ );
461
+ await expect.poll(() => queueEvents).toEqual(["later"]);
462
+ });
463
+
464
+ it("isolates each listener from payload mutation", async () => {
465
+ const bus = new HarnessEventBus();
466
+ let observed: string[] = [];
467
+ bus.on("config_update", (event) => {
468
+ if (event.property === "activeTools") event.value.push("mutated");
469
+ });
470
+ bus.on("config_update", (event) => {
471
+ if (event.property === "activeTools") observed = event.value;
472
+ });
473
+ await bus.emit(
474
+ {
475
+ type: "config_update",
476
+ property: "activeTools",
477
+ value: ["read"],
478
+ previous: [],
479
+ lane: "main",
480
+ },
481
+ BACKGROUND_CONTEXT,
482
+ );
483
+ expect(observed).toEqual(["read"]);
484
+ });
485
+
486
+ it("serializes concurrent publications in process order", async () => {
487
+ const bus = new HarnessEventBus();
488
+ const started = deferred();
489
+ const release = deferred();
490
+ const seen: string[] = [];
491
+ bus.on("run_start", async (event) => {
492
+ seen.push(`${event.runId}:start`);
493
+ if (event.runId === "one") {
494
+ started.resolve();
495
+ await release.promise;
496
+ }
497
+ seen.push(`${event.runId}:end`);
498
+ });
499
+
500
+ const one = bus.emit({ type: "run_start", runId: "one", startedAt: 1, lane: "main" }, BACKGROUND_CONTEXT);
501
+ await started.promise;
502
+ const two = bus.emit({ type: "run_start", runId: "two", startedAt: 1, lane: "main" }, BACKGROUND_CONTEXT);
503
+ await new Promise((resolve) => setTimeout(resolve, 0));
504
+ expect(seen).toEqual(["one:start"]);
505
+ release.resolve();
506
+ await Promise.all([one, two]);
507
+ expect(seen).toEqual(["one:start", "one:end", "two:start", "two:end"]);
508
+ });
509
+
510
+ it("keeps concurrent batches contiguous with their emitting contexts", async () => {
511
+ const bus = new HarnessEventBus();
512
+ const sourceKey = createContextKey<string>("event.batch.source");
513
+ const firstContext = withContextValue(sourceKey, "first", BACKGROUND_CONTEXT);
514
+ const secondContext = withContextValue(sourceKey, "second", BACKGROUND_CONTEXT);
515
+ const seen: Array<{ runId: string; context: typeof firstContext }> = [];
516
+ bus.on("run_start", async (event, context) => {
517
+ seen.push({ runId: event.runId, context });
518
+ await Promise.resolve();
519
+ });
520
+
521
+ const first = bus.emitBatch(
522
+ [
523
+ { type: "run_start", runId: "a1", startedAt: 1, lane: "main" },
524
+ { type: "run_start", runId: "a2", startedAt: 1, lane: "main" },
525
+ ],
526
+ firstContext,
527
+ );
528
+ const second = bus.emitBatch(
529
+ [
530
+ { type: "run_start", runId: "b1", startedAt: 1, lane: "worker" },
531
+ { type: "run_start", runId: "b2", startedAt: 1, lane: "worker" },
532
+ ],
533
+ secondContext,
534
+ );
535
+
536
+ await Promise.all([first, second]);
537
+ expect(seen.map(({ runId }) => runId)).toEqual(["a1", "a2", "b1", "b2"]);
538
+ expect(seen.slice(0, 2).every(({ context }) => context === firstContext)).toBe(true);
539
+ expect(seen.slice(2).every(({ context }) => context === secondContext)).toBe(true);
540
+ });
541
+
542
+ it("binds listeners and watchers when a batch is emitted", async () => {
543
+ const bus = new HarnessEventBus();
544
+ const started = deferred();
545
+ const release = deferred();
546
+ bus.on("run_start", async (event) => {
547
+ if (event.runId !== "blocking") return;
548
+ started.resolve();
549
+ await release.promise;
550
+ });
551
+ const blocking = bus.emit(
552
+ { type: "run_start", runId: "blocking", startedAt: 1, lane: "main" },
553
+ BACKGROUND_CONTEXT,
554
+ );
555
+ await started.promise;
556
+
557
+ const queued = bus.emit({ type: "run_start", runId: "queued", startedAt: 1, lane: "main" }, BACKGROUND_CONTEXT);
558
+ const lateListenerEvents: string[] = [];
559
+ bus.on("run_start", (event) => {
560
+ lateListenerEvents.push(event.runId);
561
+ });
562
+ const lateWatcherEvents: string[] = [];
563
+ const lateWatcher = bus.watch({}, (event) => event.type === "run_start", BACKGROUND_CONTEXT);
564
+ lateWatcher.start((event) => {
565
+ if (event.type === "run_start") lateWatcherEvents.push(event.runId);
566
+ });
567
+
568
+ release.resolve();
569
+ await Promise.all([blocking, queued]);
570
+ expect(lateListenerEvents).toEqual([]);
571
+ expect(lateWatcherEvents).toEqual([]);
572
+
573
+ await bus.emit({ type: "run_start", runId: "later", startedAt: 1, lane: "main" }, BACKGROUND_CONTEXT);
574
+ expect(lateListenerEvents).toEqual(["later"]);
575
+ expect(lateWatcherEvents).toEqual(["later"]);
576
+ });
577
+
578
+ it("resolves an empty batch without delivery", async () => {
579
+ const bus = new HarnessEventBus();
580
+ const listener = vi.fn();
581
+ bus.on("run_start", listener);
582
+
583
+ await bus.emitBatch([], BACKGROUND_CONTEXT);
584
+
585
+ expect(listener).not.toHaveBeenCalled();
586
+ });
587
+
588
+ it("drains already emitted contiguous batches during close and ignores later publication", async () => {
589
+ const bus = new HarnessEventBus();
590
+ const started = deferred();
591
+ const release = deferred();
592
+ const seen: string[] = [];
593
+ bus.on("run_start", async (event) => {
594
+ seen.push(event.runId);
595
+ if (event.runId === "blocking") {
596
+ started.resolve();
597
+ await release.promise;
598
+ }
599
+ });
600
+ const blocking = bus.emit(
601
+ { type: "run_start", runId: "blocking", startedAt: 1, lane: "main" },
602
+ BACKGROUND_CONTEXT,
603
+ );
604
+ await started.promise;
605
+ const batch = bus.emitBatch(
606
+ [
607
+ { type: "run_start", runId: "one", startedAt: 1, lane: "main" },
608
+ { type: "run_start", runId: "two", startedAt: 1, lane: "main" },
609
+ ],
610
+ BACKGROUND_CONTEXT,
611
+ );
612
+
613
+ bus.close(new Error("closed"));
614
+ await bus.emit({ type: "run_start", runId: "late", startedAt: 1, lane: "main" }, BACKGROUND_CONTEXT);
615
+ release.resolve();
616
+ await Promise.all([blocking, batch]);
617
+
618
+ expect(seen).toEqual(["blocking", "one", "two"]);
619
+ });
620
+
621
+ it("continues watcher delivery after listener failure and reports it", async () => {
622
+ const bus = new HarnessEventBus();
623
+ const failures: string[] = [];
624
+ bus.on("handler_error", (event) => {
625
+ failures.push(event.error);
626
+ });
627
+ const watcher = bus.watch({}, (event) => event.type === "run_start", BACKGROUND_CONTEXT);
628
+ const seen: string[] = [];
629
+ watcher.start((event) => {
630
+ if (event.type !== "run_start") return;
631
+ if (event.runId === "one") throw new Error("watcher failed");
632
+ seen.push(event.runId);
633
+ });
634
+
635
+ await bus.emit({ type: "run_start", runId: "one", startedAt: 1, lane: "main" }, BACKGROUND_CONTEXT);
636
+ await bus.emit({ type: "run_start", runId: "two", startedAt: 1, lane: "main" }, BACKGROUND_CONTEXT);
637
+ await new Promise((resolve) => setTimeout(resolve, 0));
638
+ expect(seen).toEqual(["two"]);
639
+ expect(failures).toEqual(["watcher failed"]);
640
+ });
641
+
642
+ it("isolates listener failures and emits handler_error", async () => {
643
+ const bus = new HarnessEventBus();
644
+ const failures: string[] = [];
645
+ bus.on("run_start", () => {
646
+ throw new Error("listener failed");
647
+ });
648
+ bus.on("handler_error", (event) => {
649
+ failures.push(event.error);
650
+ });
651
+ await bus.emit({ type: "run_start", runId: "run", startedAt: 1, lane: "main" }, BACKGROUND_CONTEXT);
652
+ expect(failures).toEqual(["listener failed"]);
653
+ });
654
+
655
+ it("does not recurse when a handler_error listener fails", async () => {
656
+ const bus = new HarnessEventBus();
657
+ let handlerErrors = 0;
658
+ bus.on("run_start", () => {
659
+ throw new Error("listener failed");
660
+ });
661
+ bus.on("handler_error", () => {
662
+ handlerErrors += 1;
663
+ throw new Error("error listener failed");
664
+ });
665
+
666
+ await bus.emit({ type: "run_start", runId: "run", startedAt: 1, lane: "main" }, BACKGROUND_CONTEXT);
667
+
668
+ expect(handlerErrors).toBe(1);
669
+ });
670
+ });
packages/agent/test/harness/execution-tools.test.ts ADDED
@@ -0,0 +1,247 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { Type } from "typebox";
2
+ import { describe, expect, it, vi } from "vitest";
3
+ import { BACKGROUND_CONTEXT } from "../../src/harness/context.ts";
4
+ import { AbortRequested, createGate, type Gate } from "../../src/harness/execution/effect-gate.ts";
5
+ import {
6
+ applyBeforeToolDecision,
7
+ createToolResultMessage,
8
+ executeToolCall,
9
+ finalizeToolCall,
10
+ prepareToolCall,
11
+ } from "../../src/harness/execution/tools.ts";
12
+ import type { AgentHarnessTool } from "../../src/harness/types.ts";
13
+ import type { AgentToolCall, AgentToolResult } from "../../src/types.ts";
14
+
15
+ const parameters = Type.Object({ value: Type.String() });
16
+
17
+ function call(arguments_: Record<string, unknown> = { value: "input" }): AgentToolCall {
18
+ return { type: "toolCall", id: "call-1", name: "echo", arguments: arguments_ };
19
+ }
20
+
21
+ function tool(
22
+ overrides: Partial<AgentHarnessTool<undefined, typeof parameters, { value: string }>> = {},
23
+ ): AgentHarnessTool<undefined, typeof parameters, { value: string }> {
24
+ return {
25
+ name: "echo",
26
+ label: "Echo",
27
+ description: "Echo input",
28
+ parameters,
29
+ async execute(_toolCallId, args) {
30
+ return {
31
+ content: [{ type: "text", text: args.value }],
32
+ details: { value: args.value },
33
+ };
34
+ },
35
+ ...overrides,
36
+ };
37
+ }
38
+
39
+ function text(result: AgentToolResult<unknown>): string {
40
+ return result.content.flatMap((content) => (content.type === "text" ? [content.text] : [])).join("\n");
41
+ }
42
+
43
+ function isImmediate(
44
+ result: ReturnType<typeof prepareToolCall> | ReturnType<typeof applyBeforeToolDecision>,
45
+ ): result is Extract<ReturnType<typeof prepareToolCall>, { kind: "immediate" }> {
46
+ return "kind" in result;
47
+ }
48
+
49
+ function clearPrepared(callToClear: ReturnType<typeof prepareToolCall>) {
50
+ if (isImmediate(callToClear)) throw new Error("expected prepared call");
51
+ const cleared = applyBeforeToolDecision(callToClear, undefined);
52
+ if (isImmediate(cleared)) throw new Error("expected cleared call");
53
+ return cleared;
54
+ }
55
+
56
+ function effectGate(): Gate {
57
+ return createGate().gate;
58
+ }
59
+
60
+ const invocation = {
61
+ invocationId: "result-1",
62
+ operationId: "operation-1",
63
+ turnId: "turn-1",
64
+ getMemo: async () => undefined,
65
+ setMemo: async () => {},
66
+ };
67
+
68
+ describe("tool execution primitives", () => {
69
+ it("prepares arguments before validation and preserves the provider call", () => {
70
+ const providerCall = call({ legacy: "prepared" });
71
+ const prepared = prepareToolCall(providerCall, [
72
+ tool({
73
+ prepareArguments(args) {
74
+ return { value: (args as { legacy: string }).legacy };
75
+ },
76
+ }),
77
+ ]);
78
+
79
+ expect(isImmediate(prepared)).toBe(false);
80
+ if (isImmediate(prepared)) return;
81
+ expect(prepared.toolCall).toBe(providerCall);
82
+ expect(prepared.args).toEqual({ value: "prepared" });
83
+ expect(providerCall.arguments).toEqual({ legacy: "prepared" });
84
+ });
85
+
86
+ it("returns immediate errors for unknown tools, preparation throws, and invalid arguments", () => {
87
+ const unknown = prepareToolCall(call(), []);
88
+ const preparationFailure = prepareToolCall(call(), [
89
+ tool({
90
+ prepareArguments() {
91
+ throw new Error("cannot prepare");
92
+ },
93
+ }),
94
+ ]);
95
+ const invalid = prepareToolCall(call({}), [tool()]);
96
+
97
+ expect(isImmediate(unknown) ? text(unknown.result) : "").toBe('Tool "echo" is unavailable');
98
+ expect(isImmediate(unknown) ? unknown.result.details : null).toBeUndefined();
99
+ expect(isImmediate(preparationFailure) ? text(preparationFailure.result) : "").toBe("cannot prepare");
100
+ expect(isImmediate(invalid) ? text(invalid.result) : "").toContain('Validation failed for tool "echo"');
101
+ });
102
+
103
+ it("blocks calls and revalidates replacement arguments", () => {
104
+ const prepared = prepareToolCall(call(), [tool()]);
105
+ if (isImmediate(prepared)) throw new Error("expected prepared call");
106
+
107
+ const blocked = applyBeforeToolDecision(prepared, {
108
+ block: { reason: "denied", terminate: true },
109
+ });
110
+ const replaced = applyBeforeToolDecision(prepared, { args: { value: "replacement" } });
111
+ const invalid = applyBeforeToolDecision(prepared, { args: {} });
112
+
113
+ expect(blocked).toMatchObject({ kind: "immediate", isError: true, terminate: true });
114
+ expect(isImmediate(blocked) ? text(blocked.result) : "").toBe("denied");
115
+ expect(isImmediate(replaced) ? undefined : replaced.args).toEqual({ value: "replacement" });
116
+ expect(isImmediate(invalid)).toBe(true);
117
+ });
118
+
119
+ it("executes with updates, passes the signal, and ignores late updates", async () => {
120
+ const gate = effectGate();
121
+ let lateUpdate: ((partial: AgentToolResult<{ value: string }>) => void) | undefined;
122
+ const execute: AgentHarnessTool<undefined, typeof parameters, { value: string }>["execute"] = vi.fn(
123
+ async (_id, args, onUpdate, _toolContext, _invocation, context) => {
124
+ expect(context.abortSignal).toBe(gate.signal);
125
+ onUpdate?.({ content: [{ type: "text", text: "partial" }], details: { value: args.value } });
126
+ lateUpdate = onUpdate;
127
+ return { content: [{ type: "text" as const, text: "done" }], details: { value: args.value } };
128
+ },
129
+ );
130
+ const cleared = clearPrepared(prepareToolCall(call(), [tool({ execute })]));
131
+ const updates: AgentToolResult<unknown>[] = [];
132
+
133
+ const result = await executeToolCall(
134
+ cleared,
135
+ gate,
136
+ (update) => updates.push(update),
137
+ undefined,
138
+ invocation,
139
+ BACKGROUND_CONTEXT,
140
+ );
141
+ lateUpdate?.({ content: [{ type: "text", text: "late" }], details: { value: "late" } });
142
+
143
+ expect(vi.mocked(execute)).toHaveBeenCalledOnce();
144
+ expect(result.isError).toBe(false);
145
+ expect(text(result.result)).toBe("done");
146
+ expect(updates).toHaveLength(1);
147
+ expect(text(updates[0])).toBe("partial");
148
+ });
149
+
150
+ it.each([
151
+ [
152
+ "synchronous",
153
+ () => {
154
+ throw new Error("tool failed");
155
+ },
156
+ ],
157
+ [
158
+ "asynchronous",
159
+ async () => {
160
+ throw new Error("tool failed");
161
+ },
162
+ ],
163
+ ])("converts %s tool throws to error output", async (_kind, execute) => {
164
+ const cleared = clearPrepared(prepareToolCall(call(), [tool({ execute })]));
165
+
166
+ const result = await executeToolCall(cleared, effectGate(), () => {}, undefined, invocation, BACKGROUND_CONTEXT);
167
+
168
+ expect(result.isError).toBe(true);
169
+ expect(text(result.result)).toBe("tool failed");
170
+ });
171
+
172
+ it("lets abort-first gate refusal escape without invoking the tool", async () => {
173
+ const execute = vi.fn(tool().execute);
174
+ const cleared = clearPrepared(prepareToolCall(call(), [tool({ execute })]));
175
+ const { gate, control } = createGate();
176
+ control.beginAbort(Promise.resolve());
177
+
178
+ expect(() => executeToolCall(cleared, gate, () => {}, undefined, invocation, BACKGROUND_CONTEXT)).toThrow(
179
+ AbortRequested,
180
+ );
181
+ expect(execute).not.toHaveBeenCalled();
182
+ });
183
+
184
+ it("applies patches field by field and constructs the tool-result message", () => {
185
+ const cleared = clearPrepared(prepareToolCall(call(), [tool()]));
186
+ const originalUsage = {
187
+ input: 1,
188
+ output: 2,
189
+ cacheRead: 0,
190
+ cacheWrite: 0,
191
+ totalTokens: 3,
192
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
193
+ };
194
+ const replacementUsage = { ...originalUsage, input: 5, totalTokens: 7 };
195
+ const executed: AgentToolResult<unknown> = {
196
+ content: [{ type: "text", text: "original" }],
197
+ details: { original: true },
198
+ usage: originalUsage,
199
+ addedToolNames: ["new-tool"],
200
+ };
201
+
202
+ const finalized = finalizeToolCall(
203
+ cleared,
204
+ { result: executed, isError: true },
205
+ {
206
+ content: [{ type: "text", text: "patched" }],
207
+ details: { patched: true },
208
+ usage: replacementUsage,
209
+ isError: false,
210
+ terminate: true,
211
+ },
212
+ );
213
+ const before = Date.now();
214
+ const message = createToolResultMessage(finalized);
215
+
216
+ expect(finalized).toMatchObject({ isError: false, terminate: true });
217
+ expect(finalized.result).toMatchObject({
218
+ content: [{ type: "text", text: "patched" }],
219
+ details: { patched: true },
220
+ usage: replacementUsage,
221
+ addedToolNames: ["new-tool"],
222
+ terminate: true,
223
+ });
224
+ expect(message).toMatchObject({
225
+ role: "toolResult",
226
+ toolCallId: "call-1",
227
+ toolName: "echo",
228
+ content: [{ type: "text", text: "patched" }],
229
+ details: { patched: true },
230
+ usage: replacementUsage,
231
+ addedToolNames: ["new-tool"],
232
+ isError: false,
233
+ });
234
+ expect(message.timestamp).toBeGreaterThanOrEqual(before);
235
+ });
236
+
237
+ it("normalizes missing content from untyped tools", () => {
238
+ const cleared = clearPrepared(prepareToolCall(call(), [tool()]));
239
+ const finalized = finalizeToolCall(
240
+ cleared,
241
+ { result: { content: undefined, details: {} } as never, isError: false },
242
+ undefined,
243
+ );
244
+
245
+ expect(createToolResultMessage(finalized).content).toEqual([]);
246
+ });
247
+ });
packages/agent/test/harness/gating-storage.test.ts ADDED
@@ -0,0 +1,110 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { describe, expect, it } from "vitest";
2
+ import { BACKGROUND_CONTEXT, type Context } from "../../src/harness/context.ts";
3
+ import { MemoryStorage } from "../../src/harness/session/memory.ts";
4
+ import { CommitDiscarded, GatingStorage, InstrumentedStorage } from "../../src/harness/session/testing/index.ts";
5
+ import type { CommitResult, Write } from "../../src/harness/session/types.ts";
6
+ import * as storedValues from "../../src/harness/session/values.ts";
7
+ import { deferred } from "./runtime/test-utils.ts";
8
+
9
+ class ControlledLandingStorage extends MemoryStorage {
10
+ readonly started = deferred();
11
+ readonly release = deferred();
12
+
13
+ override async commit(writes: Write[], context: Context): Promise<CommitResult> {
14
+ this.started.resolve();
15
+ await this.release.promise;
16
+ return super.commit(writes, context);
17
+ }
18
+ }
19
+
20
+ describe("GatingStorage", () => {
21
+ it("bypasses setup writes until armed and waits for commits parked after waitPending", async () => {
22
+ const storage = new GatingStorage(new MemoryStorage({ now: () => 10 }));
23
+ await storage.commit([storedValues.setValue(storedValues.sessionName, "setup")], BACKGROUND_CONTEXT);
24
+ expect(storage.pending()).toBe(0);
25
+
26
+ storage.arm();
27
+ let waitingResolved = false;
28
+ const waiting = storage.waitPending().then(() => {
29
+ waitingResolved = true;
30
+ });
31
+ await Promise.resolve();
32
+ expect(waitingResolved).toBe(false);
33
+ const commit = storage.commit([storedValues.setValue(storedValues.sessionName, "parked")], BACKGROUND_CONTEXT);
34
+ await waiting;
35
+ expect(storage.pending()).toBe(1);
36
+ expect((await storage.getValue(storedValues.sessionName, BACKGROUND_CONTEXT))?.value).toBe("setup");
37
+
38
+ await storage.next();
39
+ await commit;
40
+ expect(storage.pending()).toBe(0);
41
+ expect((await storage.getValue(storedValues.sessionName, BACKGROUND_CONTEXT))?.value).toBe("parked");
42
+ await storage.close(BACKGROUND_CONTEXT);
43
+ });
44
+
45
+ it("releases in FIFO order and next resolves only after the backend write lands", async () => {
46
+ const delegate = new ControlledLandingStorage({ now: () => 10 });
47
+ const storage = new GatingStorage(delegate);
48
+ storage.arm();
49
+ const first = storage.commit([storedValues.setValue(storedValues.sessionName, "first")], BACKGROUND_CONTEXT);
50
+ const second = storage.commit([storedValues.setValue(storedValues.sessionName, "second")], BACKGROUND_CONTEXT);
51
+ await storage.waitPending(2);
52
+ expect(storage.pending()).toBe(2);
53
+
54
+ let released = false;
55
+ const next = storage.next().then(() => {
56
+ released = true;
57
+ });
58
+ await delegate.started.promise;
59
+ await Promise.resolve();
60
+ expect(released).toBe(false);
61
+ expect(storage.pending()).toBe(1);
62
+ delegate.release.resolve();
63
+ await next;
64
+ await first;
65
+ expect(released).toBe(true);
66
+ expect((await storage.getValue(storedValues.sessionName, BACKGROUND_CONTEXT))?.value).toBe("first");
67
+
68
+ await storage.next();
69
+ await second;
70
+ expect((await storage.getValue(storedValues.sessionName, BACKGROUND_CONTEXT))?.value).toBe("second");
71
+ await storage.close(BACKGROUND_CONTEXT);
72
+ });
73
+
74
+ it("permanently rejects parked, waiting, and later commits after discard", async () => {
75
+ const storage = new GatingStorage(new MemoryStorage());
76
+ storage.arm();
77
+ const waiting = storage.waitPending(2);
78
+ const parked = storage.commit([storedValues.setValue(storedValues.sessionName, "lost")], BACKGROUND_CONTEXT);
79
+ await storage.waitPending();
80
+ expect(storage.pending()).toBe(1);
81
+
82
+ storage.discard();
83
+ expect(storage.pending()).toBe(0);
84
+ await expect(parked).rejects.toBeInstanceOf(CommitDiscarded);
85
+ await expect(waiting).rejects.toBeInstanceOf(CommitDiscarded);
86
+ await expect(storage.next()).rejects.toBeInstanceOf(CommitDiscarded);
87
+ await expect(storage.commit([], BACKGROUND_CONTEXT)).rejects.toBeInstanceOf(CommitDiscarded);
88
+ await storage.close(BACKGROUND_CONTEXT);
89
+
90
+ const unarmed = new GatingStorage(new MemoryStorage());
91
+ unarmed.discard();
92
+ await expect(unarmed.commit([], BACKGROUND_CONTEXT)).rejects.toBeInstanceOf(CommitDiscarded);
93
+ await unarmed.close(BACKGROUND_CONTEXT);
94
+ });
95
+
96
+ it("records attempts before gating parks them", async () => {
97
+ const gating = new GatingStorage(new MemoryStorage());
98
+ const storage = new InstrumentedStorage(gating);
99
+ gating.arm();
100
+ const writes = [storedValues.setValue(storedValues.sessionName, "recorded")];
101
+
102
+ const commit = storage.commit(writes, BACKGROUND_CONTEXT);
103
+ expect(storage.getCommitAttempts()).toEqual([writes]);
104
+ await gating.waitPending();
105
+ expect(gating.pending()).toBe(1);
106
+ await gating.next();
107
+ await commit;
108
+ await storage.close(BACKGROUND_CONTEXT);
109
+ });
110
+ });
packages/agent/test/harness/instrumented-storage.test.ts ADDED
@@ -0,0 +1,190 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { describe, expect, it, vi } from "vitest";
2
+ import { BACKGROUND_CONTEXT } from "../../src/harness/context.ts";
3
+ import * as sessionWrites from "../../src/harness/session/commit.ts";
4
+ import { MemoryStorage } from "../../src/harness/session/memory.ts";
5
+ import { InstrumentedStorage } from "../../src/harness/session/testing/index.ts";
6
+ import type { CommitResult, SessionStats, Write } from "../../src/harness/session/types.ts";
7
+ import * as storedValues from "../../src/harness/session/values.ts";
8
+
9
+ const EMPTY_STATS: SessionStats = {
10
+ messageCount: 0,
11
+ usage: {
12
+ input: 0,
13
+ output: 0,
14
+ cacheRead: 0,
15
+ cacheWrite: 0,
16
+ totalTokens: 0,
17
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
18
+ },
19
+ };
20
+
21
+ class ControlledCommitStorage extends MemoryStorage {
22
+ private readonly pending: Array<{
23
+ resolve: (result: CommitResult) => void;
24
+ reject: (error: unknown) => void;
25
+ }> = [];
26
+ private latestCommit: Promise<CommitResult> | undefined;
27
+
28
+ override commit(_transaction: Write[]): Promise<CommitResult> {
29
+ this.latestCommit = new Promise((resolve, reject) => {
30
+ this.pending.push({ resolve, reject });
31
+ });
32
+ return this.latestCommit;
33
+ }
34
+
35
+ get admissionCount(): number {
36
+ return this.pending.length;
37
+ }
38
+
39
+ get lastCommit(): Promise<CommitResult> | undefined {
40
+ return this.latestCommit;
41
+ }
42
+
43
+ resolveNextCommit(result: CommitResult): void {
44
+ const pending = this.pending.shift();
45
+ if (pending === undefined) throw new Error("No pending commit");
46
+ pending.resolve(result);
47
+ }
48
+
49
+ rejectNextCommit(error: unknown): void {
50
+ const pending = this.pending.shift();
51
+ if (pending === undefined) throw new Error("No pending commit");
52
+ pending.reject(error);
53
+ }
54
+ }
55
+
56
+ describe("InstrumentedStorage", () => {
57
+ it("records commit attempts synchronously in admission order before settlement", async () => {
58
+ const delegate = new ControlledCommitStorage();
59
+ const storage = new InstrumentedStorage(delegate);
60
+ const firstTransaction: Write[] = [storedValues.setValue(storedValues.sessionName, "first")];
61
+ const secondTransaction: Write[] = [storedValues.setValue(storedValues.sessionName, "second")];
62
+
63
+ const firstCommit = storage.commit(firstTransaction, BACKGROUND_CONTEXT);
64
+ expect(firstCommit).toBe(delegate.lastCommit);
65
+ expect(storage.getCommitAttempts()).toEqual([firstTransaction]);
66
+ const secondCommit = storage.commit(secondTransaction, BACKGROUND_CONTEXT);
67
+ expect(secondCommit).toBe(delegate.lastCommit);
68
+ expect(storage.getCommitAttempts()).toEqual([firstTransaction, secondTransaction]);
69
+
70
+ const firstResult = { firstSeq: 1, seqs: [1], timestamp: 10, stats: EMPTY_STATS };
71
+ delegate.resolveNextCommit(firstResult);
72
+ expect(await firstCommit).toBe(firstResult);
73
+ expect(storage.getCommitAttempts()).toEqual([firstTransaction, secondTransaction]);
74
+ const secondResult = { firstSeq: 2, seqs: [2], timestamp: 20, stats: EMPTY_STATS };
75
+ delegate.resolveNextCommit(secondResult);
76
+ expect(await secondCommit).toBe(secondResult);
77
+ await storage.close(BACKGROUND_CONTEXT);
78
+ });
79
+ it("records the transaction reference passed to the delegate", async () => {
80
+ const delegate = new ControlledCommitStorage();
81
+ const storage = new InstrumentedStorage(delegate);
82
+ const transaction: Write[] = [storedValues.setValue(storedValues.sessionName, "value")];
83
+
84
+ const commit = storage.commit(transaction, BACKGROUND_CONTEXT);
85
+ expect(storage.getCommitAttempts()[0]).toBe(transaction);
86
+ delegate.resolveNextCommit({ firstSeq: 1, seqs: [1], timestamp: 10, stats: EMPTY_STATS });
87
+ await commit;
88
+ await storage.close(BACKGROUND_CONTEXT);
89
+ });
90
+
91
+ it("clears recorded attempts between phases without affecting the delegate", async () => {
92
+ const delegate = new MemoryStorage({ now: () => 100 });
93
+ const storage = new InstrumentedStorage(delegate);
94
+ await storage.commit([storedValues.setValue(storedValues.sessionName, "first")], BACKGROUND_CONTEXT);
95
+
96
+ storage.clearCommitAttempts();
97
+ expect(storage.getCommitAttempts()).toEqual([]);
98
+ expect(await storage.getValue(storedValues.sessionName, BACKGROUND_CONTEXT)).toMatchObject({ value: "first" });
99
+
100
+ const secondTransaction: Write[] = [storedValues.setValue(storedValues.sessionName, "second")];
101
+ await storage.commit(secondTransaction, BACKGROUND_CONTEXT);
102
+ expect(storage.getCommitAttempts()).toEqual([secondTransaction]);
103
+ await storage.close(BACKGROUND_CONTEXT);
104
+ });
105
+
106
+ it("delegates every read and query without recording synthetic writes", async () => {
107
+ const delegate = new MemoryStorage({ now: () => 100 });
108
+ const storage = new InstrumentedStorage(delegate);
109
+ const events = storedValues.list<string>("test.events");
110
+ await storage.commit(
111
+ [
112
+ sessionWrites.insertEntry({ id: "root", parentId: null, type: "custom", customType: "note" }),
113
+ storedValues.setValue(storedValues.sessionName, "session"),
114
+ storedValues.appendList(events, "event"),
115
+ sessionWrites.insertUsage({
116
+ id: "usage",
117
+ adjustment: false,
118
+ usage: {
119
+ input: 1,
120
+ output: 2,
121
+ cacheRead: 0,
122
+ cacheWrite: 0,
123
+ totalTokens: 3,
124
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
125
+ },
126
+ }),
127
+ ],
128
+ BACKGROUND_CONTEXT,
129
+ );
130
+
131
+ expect(await storage.getEntries(["root"], BACKGROUND_CONTEXT)).toEqual(
132
+ await delegate.getEntries(["root"], BACKGROUND_CONTEXT),
133
+ );
134
+ expect(await storage.getValue(storedValues.sessionName, BACKGROUND_CONTEXT)).toEqual(
135
+ await delegate.getValue(storedValues.sessionName, BACKGROUND_CONTEXT),
136
+ );
137
+ expect(await storage.scanValues(storedValues.sessionName, BACKGROUND_CONTEXT)).toEqual(
138
+ await delegate.scanValues(storedValues.sessionName, BACKGROUND_CONTEXT),
139
+ );
140
+ expect(await storage.readList(events, undefined, BACKGROUND_CONTEXT)).toEqual(
141
+ await delegate.readList(events, undefined, BACKGROUND_CONTEXT),
142
+ );
143
+ expect(await storage.scanBranch({ start: "root" }, BACKGROUND_CONTEXT)).toEqual(
144
+ await delegate.scanBranch({ start: "root" }, BACKGROUND_CONTEXT),
145
+ );
146
+ expect(await storage.scanBranchStructure({ start: "root" }, BACKGROUND_CONTEXT)).toEqual(
147
+ await delegate.scanBranchStructure({ start: "root" }, BACKGROUND_CONTEXT),
148
+ );
149
+ expect(await storage.scanEntries({ order: "asc" }, BACKGROUND_CONTEXT)).toEqual(
150
+ await delegate.scanEntries({ order: "asc" }, BACKGROUND_CONTEXT),
151
+ );
152
+ expect(await storage.scanUsage({ order: "asc" }, BACKGROUND_CONTEXT)).toEqual(
153
+ await delegate.scanUsage({ order: "asc" }, BACKGROUND_CONTEXT),
154
+ );
155
+ expect(await storage.getStats(BACKGROUND_CONTEXT)).toEqual(await delegate.getStats(BACKGROUND_CONTEXT));
156
+ expect(storage.getCommitAttempts()).toHaveLength(1);
157
+ await storage.close(BACKGROUND_CONTEXT);
158
+ });
159
+
160
+ it("records list appends without reading the target list", async () => {
161
+ const delegate = new MemoryStorage({ now: () => 100 });
162
+ const readList = vi.spyOn(delegate, "readList");
163
+ const storage = new InstrumentedStorage(delegate);
164
+ const events = storedValues.list<string>("test.events");
165
+
166
+ await storage.commit([storedValues.appendList(events, "event")], BACKGROUND_CONTEXT);
167
+
168
+ expect(readList).not.toHaveBeenCalled();
169
+ expect(storage.getCommitAttempts()).toEqual([
170
+ [{ kind: "list", op: "append", namespace: "test.events", key: "", value: "event" }],
171
+ ]);
172
+ await storage.close(BACKGROUND_CONTEXT);
173
+ });
174
+
175
+ it("delegates close idempotence and admitted commit draining", async () => {
176
+ const delegate = new MemoryStorage({ now: () => 100 });
177
+ const storage = new InstrumentedStorage(delegate);
178
+ const admitted = storage.commit(
179
+ [storedValues.setValue(storedValues.sessionName, "admitted")],
180
+ BACKGROUND_CONTEXT,
181
+ );
182
+
183
+ const firstClose = storage.close(BACKGROUND_CONTEXT);
184
+ const secondClose = storage.close(BACKGROUND_CONTEXT);
185
+ await admitted;
186
+ await Promise.all([firstClose, secondClose]);
187
+ await expect(storage.getStats(BACKGROUND_CONTEXT)).rejects.toThrow("MemoryStorage is closed");
188
+ expect(storage.getCommitAttempts()).toHaveLength(1);
189
+ });
190
+ });
packages/agent/test/harness/jsonl-io.test.ts ADDED
@@ -0,0 +1,108 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
2
+ import { tmpdir } from "node:os";
3
+ import { join } from "node:path";
4
+ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
5
+ import { BACKGROUND_CONTEXT } from "../../src/harness/context.ts";
6
+ import { NodeExecutionEnv } from "../../src/harness/env/nodejs.ts";
7
+ import { publishFileAtomically, publishJsonl } from "../../src/harness/session/jsonl/io.ts";
8
+ import type { JsonlStorageHeader } from "../../src/harness/session/jsonl/types.ts";
9
+ import { sessionName, setValue } from "../../src/harness/session/values.ts";
10
+ import { err, FileError } from "../../src/harness/types.ts";
11
+
12
+ let root: string;
13
+ let path: string;
14
+ let fileSystem: NodeExecutionEnv;
15
+
16
+ beforeEach(async () => {
17
+ root = await mkdtemp(join(tmpdir(), "pi-jsonl-io-"));
18
+ path = join(root, "session.jsonl");
19
+ fileSystem = new NodeExecutionEnv({ cwd: root });
20
+ });
21
+
22
+ afterEach(async () => {
23
+ vi.restoreAllMocks();
24
+ await rm(root, { recursive: true, force: true });
25
+ });
26
+
27
+ describe("atomic file publication", () => {
28
+ it("keeps the destination unchanged until all content has been written", async () => {
29
+ await writeFile(path, "original");
30
+
31
+ await publishFileAtomically(fileSystem, path, BACKGROUND_CONTEXT, async (append) => {
32
+ await append("first\n");
33
+ expect(await readFile(`${path}.tmp`, "utf8")).toBe("first\n");
34
+ expect(await readFile(path, "utf8")).toBe("original");
35
+ await append("second\n");
36
+ expect(await readFile(path, "utf8")).toBe("original");
37
+ });
38
+
39
+ expect(await readFile(path, "utf8")).toBe("first\nsecond\n");
40
+ await expect(readFile(`${path}.tmp`)).rejects.toMatchObject({ code: "ENOENT" });
41
+ });
42
+
43
+ it("discards partial content and preserves the original error when the callback fails", async () => {
44
+ await writeFile(path, "original");
45
+ const failure = new Error("content generation failed");
46
+
47
+ await expect(
48
+ publishFileAtomically(fileSystem, path, BACKGROUND_CONTEXT, async (append) => {
49
+ await append("partial");
50
+ throw failure;
51
+ }),
52
+ ).rejects.toBe(failure);
53
+
54
+ expect(await readFile(path, "utf8")).toBe("original");
55
+ await expect(readFile(`${path}.tmp`)).rejects.toMatchObject({ code: "ENOENT" });
56
+ });
57
+
58
+ it.each(["writeFile", "appendFile", "renameFile"] as const)(
59
+ "preserves the destination and allows retry after %s fails",
60
+ async (method) => {
61
+ await writeFile(path, "original");
62
+ const failure = new FileError("unknown", "injected I/O failure", path);
63
+ vi.spyOn(fileSystem, method).mockResolvedValueOnce(err(failure));
64
+
65
+ await expect(
66
+ publishFileAtomically(fileSystem, path, BACKGROUND_CONTEXT, (append) => append("replacement")),
67
+ ).rejects.toMatchObject({ cause: failure });
68
+
69
+ expect(await readFile(path, "utf8")).toBe("original");
70
+ await expect(readFile(`${path}.tmp`)).rejects.toMatchObject({ code: "ENOENT" });
71
+
72
+ await publishFileAtomically(fileSystem, path, BACKGROUND_CONTEXT, (append) => append("retry"));
73
+ expect(await readFile(path, "utf8")).toBe("retry");
74
+ },
75
+ );
76
+ });
77
+
78
+ describe("JSONL publication", () => {
79
+ const header: JsonlStorageHeader = {
80
+ v: 4,
81
+ kind: "header",
82
+ id: "session",
83
+ storageVersion: 1,
84
+ createdAt: 1_700_000_000_000,
85
+ cwd: "/workspace",
86
+ nextSeq: 4,
87
+ };
88
+
89
+ it("writes the header first and preserves single-write and multi-write transaction boundaries", async () => {
90
+ const first = { ...setValue(sessionName, "first"), seq: 1 };
91
+ const second = { ...setValue(sessionName, "second"), seq: 2 };
92
+ const third = { ...setValue(sessionName, "third"), seq: 3 };
93
+
94
+ await publishJsonl(fileSystem, path, header, BACKGROUND_CONTEXT, async (append) => {
95
+ await append([first]);
96
+ await append([second, third]);
97
+ });
98
+
99
+ expect(await readFile(path, "utf8")).toBe(
100
+ [JSON.stringify(header), JSON.stringify(first), JSON.stringify([second, third]), ""].join("\n"),
101
+ );
102
+ });
103
+
104
+ it("publishes a header-only file when the callback emits no transactions", async () => {
105
+ await publishJsonl(fileSystem, path, header, BACKGROUND_CONTEXT, async () => {});
106
+ expect(await readFile(path, "utf8")).toBe(`${JSON.stringify(header)}\n`);
107
+ });
108
+ });
packages/agent/test/harness/jsonl-session-repo-conformance.test.ts ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { describe, it } from "vitest";
2
+ import { BACKGROUND_CONTEXT } from "../../src/harness/context.ts";
3
+ import { NodeExecutionEnv } from "../../src/harness/env/nodejs.ts";
4
+ import { type JsonlSessionMetadata, JsonlSessionRepo } from "../../src/harness/session/jsonl/index.ts";
5
+ import {
6
+ type ConformanceCase,
7
+ createSessionRepoForkBehaviorConformance,
8
+ createSessionRepoForkSourceSnapshotConformance,
9
+ createSessionRepoLifecycleConformance,
10
+ createSessionRepoMessageConformance,
11
+ createSessionRepoOwnershipConformance,
12
+ createSessionRepoStreamingForkConformance,
13
+ } from "../../src/harness/session/testing/index.ts";
14
+ import type { ForkOptions } from "../../src/harness/session/types.ts";
15
+ import { createTempDir } from "./session-test-utils.ts";
16
+
17
+ const NOW = 1_700_000_000_000;
18
+ const CONFORMANCE_CWD = "/workspace";
19
+
20
+ function registerConformance(name: string, cases: readonly ConformanceCase[]): void {
21
+ describe(name, () => {
22
+ for (const group of new Set(cases.map((testCase) => testCase.group))) {
23
+ describe(group, () => {
24
+ for (const testCase of cases.filter((candidate) => candidate.group === group)) {
25
+ it(testCase.name, () => testCase.run());
26
+ }
27
+ });
28
+ }
29
+ });
30
+ }
31
+
32
+ let jsonlRepo: JsonlSessionRepo;
33
+ async function createConformanceRepo() {
34
+ const fileSystem = new NodeExecutionEnv({ cwd: createTempDir() });
35
+ jsonlRepo = new JsonlSessionRepo({ fileSystem, sessionsRoot: "sessions", now: () => NOW });
36
+ return {
37
+ create: (options: { id?: string; parentSessionId?: string }) =>
38
+ jsonlRepo.create({ ...options, cwd: CONFORMANCE_CWD }, BACKGROUND_CONTEXT),
39
+ open: (metadata: JsonlSessionMetadata) => jsonlRepo.open(metadata, BACKGROUND_CONTEXT),
40
+ list: () => jsonlRepo.list({ cwd: CONFORMANCE_CWD }, BACKGROUND_CONTEXT),
41
+ delete: (metadata: JsonlSessionMetadata) => jsonlRepo.delete(metadata, BACKGROUND_CONTEXT),
42
+ fork: (source: JsonlSessionMetadata, options: ForkOptions) => jsonlRepo.fork(source, options, BACKGROUND_CONTEXT),
43
+ };
44
+ }
45
+
46
+ registerConformance("JsonlSessionRepo conformance", [
47
+ ...createSessionRepoLifecycleConformance<JsonlSessionMetadata>(createConformanceRepo, () =>
48
+ jsonlRepo.close(BACKGROUND_CONTEXT),
49
+ ),
50
+ ...createSessionRepoOwnershipConformance<JsonlSessionMetadata>(createConformanceRepo, () =>
51
+ jsonlRepo.close(BACKGROUND_CONTEXT),
52
+ ),
53
+ ...createSessionRepoMessageConformance<JsonlSessionMetadata>(createConformanceRepo, () =>
54
+ jsonlRepo.close(BACKGROUND_CONTEXT),
55
+ ),
56
+ ...createSessionRepoForkBehaviorConformance<JsonlSessionMetadata>(createConformanceRepo, () =>
57
+ jsonlRepo.close(BACKGROUND_CONTEXT),
58
+ ),
59
+ ...createSessionRepoStreamingForkConformance<JsonlSessionMetadata>(createConformanceRepo, () =>
60
+ jsonlRepo.close(BACKGROUND_CONTEXT),
61
+ ),
62
+ ...createSessionRepoForkSourceSnapshotConformance<JsonlSessionMetadata>(createConformanceRepo, () =>
63
+ jsonlRepo.close(BACKGROUND_CONTEXT),
64
+ ),
65
+ ]);
packages/agent/test/harness/jsonl-session-repo.test.ts ADDED
@@ -0,0 +1,199 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { describe, expect, it } from "vitest";
2
+ import { BACKGROUND_CONTEXT, type Context } from "../../src/harness/context.ts";
3
+ import { NodeExecutionEnv } from "../../src/harness/env/nodejs.ts";
4
+ import { JSONL_STORAGE_VERSION, JsonlSessionRepo } from "../../src/harness/session/jsonl/index.ts";
5
+ import { sessionName, setValue } from "../../src/harness/session/values.ts";
6
+ import { getOrThrow } from "../../src/harness/types.ts";
7
+ import { createTempDir } from "./session-test-utils.ts";
8
+
9
+ const NOW = 1_700_000_000_000;
10
+
11
+ class AtomicPublicationNodeExecutionEnv extends NodeExecutionEnv {
12
+ publication:
13
+ | { sourcePath: string; destinationPath: string; destinationExisted: boolean; stagedContent: string }
14
+ | undefined;
15
+
16
+ override async renameFile(sourcePath: string, destinationPath: string, context: Context) {
17
+ const destinationExists = await super.exists(destinationPath, context);
18
+ const stagedContent = await super.readTextFile(sourcePath, context);
19
+ if (destinationExists.ok && stagedContent.ok) {
20
+ this.publication = {
21
+ sourcePath,
22
+ destinationPath,
23
+ destinationExisted: destinationExists.value,
24
+ stagedContent: stagedContent.value,
25
+ };
26
+ }
27
+ return super.renameFile(sourcePath, destinationPath, context);
28
+ }
29
+ }
30
+
31
+ describe("JsonlSessionRepo cwd-scoped lifecycle", () => {
32
+ it("persists metadata and filters discovery by cwd", async () => {
33
+ const fileSystem = new NodeExecutionEnv({ cwd: createTempDir() });
34
+ const repo = new JsonlSessionRepo({ fileSystem, sessionsRoot: "sessions", now: () => NOW });
35
+ const session = await repo.create(
36
+ { id: "child", cwd: "/workspace", parentSessionId: "parent" },
37
+ BACKGROUND_CONTEXT,
38
+ );
39
+ const metadata = session.metadata;
40
+
41
+ expect(metadata).toMatchObject({
42
+ id: "child",
43
+ createdAt: NOW,
44
+ storageVersion: JSONL_STORAGE_VERSION,
45
+ cwd: "/workspace",
46
+ parentSessionId: "parent",
47
+ });
48
+ expect(metadata.path).toContain("/sessions/--workspace--/");
49
+ expect(metadata.path.endsWith("_child.jsonl")).toBe(true);
50
+ expect(Number.isFinite(metadata.modifiedAt)).toBe(true);
51
+ await session.close(BACKGROUND_CONTEXT);
52
+
53
+ expect(await repo.list({ cwd: "/other" }, BACKGROUND_CONTEXT)).toEqual([]);
54
+ expect(await repo.list({ cwd: "/workspace" }, BACKGROUND_CONTEXT)).toEqual([metadata]);
55
+ const firstLine = getOrThrow(
56
+ await fileSystem.readTextLines(metadata.path, { maxLines: 1 }, BACKGROUND_CONTEXT),
57
+ )[0];
58
+ expect(JSON.parse(firstLine!)).toEqual({
59
+ v: 4,
60
+ kind: "header",
61
+ id: "child",
62
+ storageVersion: JSONL_STORAGE_VERSION,
63
+ createdAt: NOW,
64
+ cwd: "/workspace",
65
+ parentSessionId: "parent",
66
+ });
67
+ await repo.close(BACKGROUND_CONTEXT);
68
+ });
69
+
70
+ it("atomically publishes a branchless session header", async () => {
71
+ const fileSystem = new AtomicPublicationNodeExecutionEnv({ cwd: createTempDir() });
72
+ const repo = new JsonlSessionRepo({ fileSystem, sessionsRoot: "sessions", now: () => NOW });
73
+ const session = await repo.create({ id: "session", cwd: "/workspace" }, BACKGROUND_CONTEXT);
74
+
75
+ const publication = fileSystem.publication;
76
+ if (publication === undefined) throw new Error("Expected atomic session publication");
77
+ expect(publication.destinationPath).toBe(session.metadata.path);
78
+ expect(publication.destinationExisted).toBe(false);
79
+ const lines = publication.stagedContent.trimEnd().split("\n");
80
+ expect(lines).toHaveLength(1);
81
+ expect(JSON.parse(lines[0]!)).toMatchObject({ kind: "header", id: "session" });
82
+ expect(getOrThrow(await fileSystem.readTextFile(session.metadata.path, BACKGROUND_CONTEXT))).toBe(
83
+ publication.stagedContent,
84
+ );
85
+ expect(getOrThrow(await fileSystem.exists(publication.sourcePath, BACKGROUND_CONTEXT))).toBe(false);
86
+
87
+ await session.close(BACKGROUND_CONTEXT);
88
+ await repo.close(BACKGROUND_CONTEXT);
89
+ });
90
+
91
+ it("keeps an explicit Session mutation through commit until end", async () => {
92
+ const fileSystem = new NodeExecutionEnv({ cwd: createTempDir() });
93
+ const repo = new JsonlSessionRepo({ fileSystem, sessionsRoot: "sessions", now: () => NOW });
94
+ const session = await repo.create({ id: "session", cwd: "/workspace" }, BACKGROUND_CONTEXT);
95
+ const mutation = await session.beginMutation(BACKGROUND_CONTEXT);
96
+ let queuedStarted = false;
97
+ const queued = session.mutate(() => {
98
+ queuedStarted = true;
99
+ }, BACKGROUND_CONTEXT);
100
+
101
+ const result = await mutation.commit([setValue(sessionName, "explicit")], BACKGROUND_CONTEXT);
102
+ expect(result.seqs).toHaveLength(1);
103
+ expect(queuedStarted).toBe(false);
104
+ expect(await mutation.getValue(sessionName, BACKGROUND_CONTEXT)).toMatchObject({ value: "explicit" });
105
+ await mutation.end(BACKGROUND_CONTEXT);
106
+ await queued;
107
+ expect(queuedStarted).toBe(true);
108
+
109
+ await session.close(BACKGROUND_CONTEXT);
110
+ const reopened = await repo.open(session.metadata, BACKGROUND_CONTEXT);
111
+ expect(await reopened.getName(BACKGROUND_CONTEXT)).toBe("explicit");
112
+ await reopened.close(BACKGROUND_CONTEXT);
113
+ await repo.close(BACKGROUND_CONTEXT);
114
+ });
115
+
116
+ it("rejects unsupported storage versions without repairing a torn tail", async () => {
117
+ const fileSystem = new NodeExecutionEnv({ cwd: createTempDir() });
118
+ const repo = new JsonlSessionRepo({ fileSystem, sessionsRoot: "sessions", now: () => NOW });
119
+ const session = await repo.create({ id: "future", cwd: "/workspace" }, BACKGROUND_CONTEXT);
120
+ const metadata = session.metadata;
121
+ await session.close(BACKGROUND_CONTEXT);
122
+
123
+ const lines = getOrThrow(await fileSystem.readTextFile(metadata.path, BACKGROUND_CONTEXT))
124
+ .trimEnd()
125
+ .split("\n");
126
+ const unsupportedVersion = JSONL_STORAGE_VERSION + 1;
127
+ lines[0] = JSON.stringify({ ...JSON.parse(lines[0]!), storageVersion: unsupportedVersion });
128
+ const unsupportedContent = `${lines.join("\n")}\n{"kind":"entry"`;
129
+ getOrThrow(await fileSystem.writeFile(metadata.path, unsupportedContent, BACKGROUND_CONTEXT));
130
+
131
+ await expect(repo.open(metadata, BACKGROUND_CONTEXT)).rejects.toThrow(
132
+ `unsupported storage version ${unsupportedVersion}`,
133
+ );
134
+ expect(getOrThrow(await fileSystem.readTextFile(metadata.path, BACKGROUND_CONTEXT))).toBe(unsupportedContent);
135
+
136
+ await repo.close(BACKGROUND_CONTEXT);
137
+ });
138
+
139
+ it("keeps fork destinations claimed until close and rejects deleting open sessions", async () => {
140
+ const fileSystem = new NodeExecutionEnv({ cwd: createTempDir() });
141
+ const repo = new JsonlSessionRepo({ fileSystem, sessionsRoot: "sessions", now: () => NOW });
142
+ const source = await repo.create({ id: "source", cwd: "/workspace" }, BACKGROUND_CONTEXT);
143
+ const fork = await repo.fork(source.metadata, { id: "fork", scope: "tree" }, BACKGROUND_CONTEXT);
144
+
145
+ await expect(repo.open(fork.metadata, BACKGROUND_CONTEXT)).rejects.toThrow("already open");
146
+ await expect(repo.delete(fork.metadata, BACKGROUND_CONTEXT)).rejects.toThrow("open");
147
+ await fork.close(BACKGROUND_CONTEXT);
148
+
149
+ const reopened = await repo.open(fork.metadata, BACKGROUND_CONTEXT);
150
+ await reopened.close(BACKGROUND_CONTEXT);
151
+ await repo.delete(fork.metadata, BACKGROUND_CONTEXT);
152
+ await expect(repo.open(fork.metadata, BACKGROUND_CONTEXT)).rejects.toThrow("does not exist");
153
+
154
+ await source.close(BACKGROUND_CONTEXT);
155
+ await repo.close(BACKGROUND_CONTEXT);
156
+ });
157
+
158
+ it("rejects concurrent creates for the same working-directory id", async () => {
159
+ const fileSystem = new NodeExecutionEnv({ cwd: createTempDir() });
160
+ const repo = new JsonlSessionRepo({ fileSystem, sessionsRoot: "sessions", now: () => NOW });
161
+
162
+ const results = await Promise.allSettled([
163
+ repo.create({ id: "session", cwd: "/workspace" }, BACKGROUND_CONTEXT),
164
+ repo.create({ id: "session", cwd: "/workspace" }, BACKGROUND_CONTEXT),
165
+ ]);
166
+
167
+ expect(results.filter((result) => result.status === "fulfilled")).toHaveLength(1);
168
+ expect(results.filter((result) => result.status === "rejected")).toHaveLength(1);
169
+ expect(await repo.list({ cwd: "/workspace" }, BACKGROUND_CONTEXT)).toHaveLength(1);
170
+ for (const result of results) {
171
+ if (result.status === "fulfilled") await result.value.close(BACKGROUND_CONTEXT);
172
+ }
173
+ await repo.close(BACKGROUND_CONTEXT);
174
+ });
175
+
176
+ it("allows the same id to be active in different working directories", async () => {
177
+ const fileSystem = new NodeExecutionEnv({ cwd: createTempDir() });
178
+ const repo = new JsonlSessionRepo({ fileSystem, sessionsRoot: "sessions", now: () => NOW });
179
+ const first = await repo.create({ id: "shared", cwd: "/workspace-a" }, BACKGROUND_CONTEXT);
180
+ const second = await repo.create({ id: "shared", cwd: "/workspace-b" }, BACKGROUND_CONTEXT);
181
+
182
+ expect(first.metadata.path).not.toBe(second.metadata.path);
183
+ await expect(repo.create({ id: "shared", cwd: "/workspace-a" }, BACKGROUND_CONTEXT)).rejects.toThrow(
184
+ "already exists",
185
+ );
186
+ expect((await repo.list(undefined, BACKGROUND_CONTEXT)).map(({ cwd, id }) => ({ cwd, id }))).toEqual([
187
+ { cwd: "/workspace-a", id: "shared" },
188
+ { cwd: "/workspace-b", id: "shared" },
189
+ ]);
190
+
191
+ await Promise.all([first.close(BACKGROUND_CONTEXT), second.close(BACKGROUND_CONTEXT)]);
192
+ const reopened = await Promise.all([
193
+ repo.open(first.metadata, BACKGROUND_CONTEXT),
194
+ repo.open(second.metadata, BACKGROUND_CONTEXT),
195
+ ]);
196
+ await Promise.all(reopened.map((session) => session.close(BACKGROUND_CONTEXT)));
197
+ await repo.close(BACKGROUND_CONTEXT);
198
+ });
199
+ });
packages/agent/test/harness/jsonl-storage-conformance.test.ts ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { describe, it } from "vitest";
2
+ import { BACKGROUND_CONTEXT } from "../../src/harness/context.ts";
3
+ import { NodeExecutionEnv } from "../../src/harness/env/nodejs.ts";
4
+ import { JSONL_FORMAT_VERSION, JsonlStorage } from "../../src/harness/session/jsonl/index.ts";
5
+ import {
6
+ type ConformanceCase,
7
+ createStorageConformance,
8
+ type StorageFixture,
9
+ } from "../../src/harness/session/testing/index.ts";
10
+ import { createTempDir } from "./session-test-utils.ts";
11
+
12
+ const NOW = 1_700_000_000_000;
13
+
14
+ function registerConformance(name: string, cases: readonly ConformanceCase[]): void {
15
+ describe(name, () => {
16
+ for (const group of new Set(cases.map((testCase) => testCase.group))) {
17
+ describe(group, () => {
18
+ for (const testCase of cases.filter((candidate) => candidate.group === group)) {
19
+ it(testCase.name, () => testCase.run());
20
+ }
21
+ });
22
+ }
23
+ });
24
+ }
25
+
26
+ registerConformance(
27
+ "JsonlStorage conformance",
28
+ createStorageConformance(async () => {
29
+ const fileSystem = new NodeExecutionEnv({ cwd: createTempDir() });
30
+ const storage = await JsonlStorage.create(
31
+ { fileSystem, path: "session.jsonl", now: () => NOW },
32
+ {
33
+ v: JSONL_FORMAT_VERSION,
34
+ kind: "header",
35
+ id: "session",
36
+ storageVersion: 1,
37
+ createdAt: NOW,
38
+ cwd: "/workspace",
39
+ },
40
+ [],
41
+ BACKGROUND_CONTEXT,
42
+ );
43
+ return {
44
+ storage,
45
+ [Symbol.asyncDispose]: () => storage.close(BACKGROUND_CONTEXT),
46
+ } satisfies StorageFixture;
47
+ }),
48
+ );
packages/agent/test/harness/jsonl-storage.test.ts ADDED
@@ -0,0 +1,248 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { describe, expect, it } from "vitest";
2
+ import { BACKGROUND_CONTEXT } from "../../src/harness/context.ts";
3
+ import { NodeExecutionEnv } from "../../src/harness/env/nodejs.ts";
4
+ import * as sessionWrites from "../../src/harness/session/commit.ts";
5
+ import { JSONL_FORMAT_VERSION, JsonlStorage, type JsonlStorageHeader } from "../../src/harness/session/jsonl/index.ts";
6
+ import * as storedValues from "../../src/harness/session/values.ts";
7
+ import { getOrThrow } from "../../src/harness/types.ts";
8
+ import { createTempDir } from "./session-test-utils.ts";
9
+
10
+ const NOW = 1_700_000_000_000;
11
+
12
+ function header(id: string): JsonlStorageHeader {
13
+ return {
14
+ v: JSONL_FORMAT_VERSION,
15
+ kind: "header",
16
+ id,
17
+ storageVersion: 1,
18
+ createdAt: NOW,
19
+ cwd: "/workspace",
20
+ };
21
+ }
22
+
23
+ describe("JsonlStorage persistence", () => {
24
+ it("replays whole-list deletion without resurrecting earlier appends", async () => {
25
+ const fileSystem = new NodeExecutionEnv({ cwd: createTempDir() });
26
+ const options = { fileSystem, path: "list-delete.jsonl", now: () => NOW };
27
+ const events = storedValues.list<string>("test.events");
28
+ const storage = await JsonlStorage.create(options, header("list-delete"), [], BACKGROUND_CONTEXT);
29
+ await storage.commit(
30
+ [storedValues.appendList(events, "first"), storedValues.appendList(events, "second")],
31
+ BACKGROUND_CONTEXT,
32
+ );
33
+ await storage.commit([storedValues.deleteList(events)], BACKGROUND_CONTEXT);
34
+ await storage.close(BACKGROUND_CONTEXT);
35
+
36
+ const reopened = await JsonlStorage.open(options, BACKGROUND_CONTEXT);
37
+ expect(await reopened.readList(events, undefined, BACKGROUND_CONTEXT)).toEqual([]);
38
+ const recreated = await reopened.commit([storedValues.appendList(events, "after")], BACKGROUND_CONTEXT);
39
+ expect(recreated.firstSeq).toBe(4);
40
+ expect(await reopened.readList(events, undefined, BACKGROUND_CONTEXT)).toEqual([{ seq: 4, value: "after" }]);
41
+ await reopened.close(BACKGROUND_CONTEXT);
42
+ });
43
+
44
+ it("writes one line per transaction and replays stamped state", async () => {
45
+ const fileSystem = new NodeExecutionEnv({ cwd: createTempDir() });
46
+ const options = { fileSystem, path: "session.jsonl", now: () => NOW };
47
+ const storage = await JsonlStorage.create(options, header("round-trip"), [], BACKGROUND_CONTEXT);
48
+ const committed = await storage.commit(
49
+ [
50
+ sessionWrites.insertEntry({
51
+ id: "root",
52
+ parentId: null,
53
+ type: "message",
54
+ message: { role: "user", content: "hello", timestamp: 1 },
55
+ }),
56
+ storedValues.setValue(storedValues.branchTip("main"), "root"),
57
+ sessionWrites.insertUsage({
58
+ id: "usage",
59
+ entryId: "root",
60
+ adjustment: false,
61
+ usage: {
62
+ input: 1,
63
+ output: 2,
64
+ cacheRead: 0,
65
+ cacheWrite: 0,
66
+ totalTokens: 3,
67
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
68
+ },
69
+ }),
70
+ ],
71
+ BACKGROUND_CONTEXT,
72
+ );
73
+ await storage.commit([storedValues.setValue(storedValues.sessionName, "name")], BACKGROUND_CONTEXT);
74
+
75
+ const lines = getOrThrow(await fileSystem.readTextFile("session.jsonl", BACKGROUND_CONTEXT))
76
+ .trimEnd()
77
+ .split("\n");
78
+ expect(JSON.parse(lines[0]!)).toEqual(header("round-trip"));
79
+ expect(JSON.parse(lines[1]!)).toHaveLength(3);
80
+ expect(Array.isArray(JSON.parse(lines[2]!))).toBe(false);
81
+ await storage.close(BACKGROUND_CONTEXT);
82
+
83
+ const reopened = await JsonlStorage.open(options, BACKGROUND_CONTEXT);
84
+ expect((await reopened.getEntries(["root"], BACKGROUND_CONTEXT)).get("root")).toEqual({
85
+ id: "root",
86
+ parentId: null,
87
+ type: "message",
88
+ message: { role: "user", content: "hello", timestamp: 1 },
89
+ seq: committed.seqs[0],
90
+ timestamp: committed.timestamp,
91
+ });
92
+ expect(await reopened.getValue(storedValues.branchTip("main"), BACKGROUND_CONTEXT)).toEqual({
93
+ address: storedValues.branchTip("main"),
94
+ value: "root",
95
+ seq: committed.seqs[1],
96
+ });
97
+ expect(
98
+ (await reopened.scanUsage({ order: "asc" }, BACKGROUND_CONTEXT)).map(({ id, seq }) => ({ id, seq })),
99
+ ).toEqual([{ id: "usage", seq: committed.seqs[2] }]);
100
+ const historicalStats = {
101
+ messageCount: 1,
102
+ usage: {
103
+ input: 1,
104
+ output: 2,
105
+ cacheRead: 0,
106
+ cacheWrite: 0,
107
+ totalTokens: 3,
108
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
109
+ },
110
+ };
111
+ expect(await reopened.getStats(BACKGROUND_CONTEXT)).toEqual(historicalStats);
112
+ const next = await reopened.commit([], BACKGROUND_CONTEXT);
113
+ expect(next.firstSeq).toBe(5);
114
+ expect(next.stats).toEqual(historicalStats);
115
+ await reopened.close(BACKGROUND_CONTEXT);
116
+ });
117
+ });
118
+
119
+ describe("JsonlStorage torn tail", () => {
120
+ function entryWrite(id: string) {
121
+ return sessionWrites.insertEntry({
122
+ id,
123
+ parentId: null,
124
+ type: "message",
125
+ message: { role: "user", content: id, timestamp: 1 },
126
+ });
127
+ }
128
+
129
+ async function seed() {
130
+ const fileSystem = new NodeExecutionEnv({ cwd: createTempDir() });
131
+ const options = { fileSystem, path: "session.jsonl" as const, now: () => NOW };
132
+ const storage = await JsonlStorage.create(options, header("torn"), [], BACKGROUND_CONTEXT);
133
+ await storage.commit([entryWrite("kept")], BACKGROUND_CONTEXT);
134
+ await storage.close(BACKGROUND_CONTEXT);
135
+ const prefix = getOrThrow(await fileSystem.readTextFile("session.jsonl", BACKGROUND_CONTEXT));
136
+ return { fileSystem, options, prefix };
137
+ }
138
+
139
+ it("discards an unterminated final object line and truncates before admitting writes", async () => {
140
+ const { fileSystem, options, prefix } = await seed();
141
+ await fileSystem.appendFile(
142
+ "session.jsonl",
143
+ JSON.stringify({
144
+ kind: "entry",
145
+ id: "torn",
146
+ parentId: null,
147
+ type: "message",
148
+ message: { role: "user", content: "torn", timestamp: 1 },
149
+ seq: 2,
150
+ timestamp: NOW,
151
+ }),
152
+ BACKGROUND_CONTEXT,
153
+ );
154
+
155
+ const reopened = await JsonlStorage.open(options, BACKGROUND_CONTEXT);
156
+ expect((await reopened.getEntries(["kept", "torn"], BACKGROUND_CONTEXT)).has("torn")).toBe(false);
157
+ expect((await reopened.getEntries(["kept"], BACKGROUND_CONTEXT)).get("kept")?.id).toBe("kept");
158
+ expect(getOrThrow(await fileSystem.readTextFile("session.jsonl", BACKGROUND_CONTEXT))).toBe(prefix);
159
+ expect(getOrThrow(await fileSystem.exists("session.jsonl.tmp", BACKGROUND_CONTEXT))).toBe(false);
160
+
161
+ const next = await reopened.commit([entryWrite("after")], BACKGROUND_CONTEXT);
162
+ expect(next.firstSeq).toBe(2);
163
+ expect((await reopened.getEntries(["after"], BACKGROUND_CONTEXT)).get("after")?.seq).toBe(2);
164
+ await reopened.close(BACKGROUND_CONTEXT);
165
+ });
166
+
167
+ it("discards a torn array line wholly, including list elements", async () => {
168
+ const { fileSystem, options, prefix } = await seed();
169
+ const events = storedValues.list<string>("test.events");
170
+ await fileSystem.appendFile(
171
+ "session.jsonl",
172
+ JSON.stringify([
173
+ {
174
+ kind: "entry",
175
+ id: "torn-a",
176
+ parentId: null,
177
+ type: "message",
178
+ message: { role: "user", content: "torn-a", timestamp: 1 },
179
+ seq: 2,
180
+ timestamp: NOW,
181
+ },
182
+ storedValues.setValue(storedValues.sessionName, "lost"),
183
+ storedValues.appendList(events, "lost"),
184
+ ]),
185
+ BACKGROUND_CONTEXT,
186
+ );
187
+
188
+ const reopened = await JsonlStorage.open(options, BACKGROUND_CONTEXT);
189
+ expect((await reopened.getEntries(["torn-a"], BACKGROUND_CONTEXT)).has("torn-a")).toBe(false);
190
+ expect(await reopened.getValue(storedValues.sessionName, BACKGROUND_CONTEXT)).toBeUndefined();
191
+ expect(await reopened.readList(events, undefined, BACKGROUND_CONTEXT)).toEqual([]);
192
+ expect(getOrThrow(await fileSystem.readTextFile("session.jsonl", BACKGROUND_CONTEXT))).toBe(prefix);
193
+ await reopened.close(BACKGROUND_CONTEXT);
194
+ });
195
+
196
+ it("rejects a malformed interior line without rewriting", async () => {
197
+ const { fileSystem, options, prefix } = await seed();
198
+ const corrupted = `${prefix}not-json\n${JSON.stringify(storedValues.setValue(storedValues.sessionName, "after"))}\n`;
199
+ await fileSystem.writeFile("session.jsonl", corrupted, BACKGROUND_CONTEXT);
200
+
201
+ await expect(JsonlStorage.open(options, BACKGROUND_CONTEXT)).rejects.toThrow(/line 3/);
202
+ expect(getOrThrow(await fileSystem.readTextFile("session.jsonl", BACKGROUND_CONTEXT))).toBe(corrupted);
203
+ expect(getOrThrow(await fileSystem.exists("session.jsonl.tmp", BACKGROUND_CONTEXT))).toBe(false);
204
+ });
205
+
206
+ it("rejects the unsupported pre-WP01 scalar record spelling", async () => {
207
+ const { fileSystem, options, prefix } = await seed();
208
+ const legacyKind = ["reg", "ister"].join("");
209
+ const corrupted = `${prefix}${JSON.stringify({
210
+ kind: legacyKind,
211
+ op: "set",
212
+ seq: 2,
213
+ namespace: "legacy.value",
214
+ key: "state",
215
+ value: true,
216
+ })}\n`;
217
+ await fileSystem.writeFile("session.jsonl", corrupted, BACKGROUND_CONTEXT);
218
+
219
+ await expect(JsonlStorage.open(options, BACKGROUND_CONTEXT)).rejects.toThrow(/line 3/);
220
+ expect(getOrThrow(await fileSystem.readTextFile("session.jsonl", BACKGROUND_CONTEXT))).toBe(corrupted);
221
+ });
222
+
223
+ it("rejects a complete malformed final line without rewriting", async () => {
224
+ const { fileSystem, options, prefix } = await seed();
225
+ const corrupted = `${prefix}not-json\n`;
226
+ await fileSystem.writeFile("session.jsonl", corrupted, BACKGROUND_CONTEXT);
227
+
228
+ await expect(JsonlStorage.open(options, BACKGROUND_CONTEXT)).rejects.toThrow(/line 3/);
229
+ expect(getOrThrow(await fileSystem.readTextFile("session.jsonl", BACKGROUND_CONTEXT))).toBe(corrupted);
230
+ });
231
+
232
+ it("rejects a complete final line with invalid transaction framing", async () => {
233
+ const { fileSystem, options, prefix } = await seed();
234
+ const corrupted = `${prefix}${JSON.stringify({ kind: "nope", seq: 2 })}\n`;
235
+ await fileSystem.writeFile("session.jsonl", corrupted, BACKGROUND_CONTEXT);
236
+
237
+ await expect(JsonlStorage.open(options, BACKGROUND_CONTEXT)).rejects.toThrow(/line 3/);
238
+ expect(getOrThrow(await fileSystem.readTextFile("session.jsonl", BACKGROUND_CONTEXT))).toBe(corrupted);
239
+ });
240
+
241
+ it("rejects an unterminated header", async () => {
242
+ const fileSystem = new NodeExecutionEnv({ cwd: createTempDir() });
243
+ const options = { fileSystem, path: "session.jsonl", now: () => NOW };
244
+ await fileSystem.writeFile("session.jsonl", JSON.stringify(header("torn")).slice(0, -4), BACKGROUND_CONTEXT);
245
+
246
+ await expect(JsonlStorage.open(options, BACKGROUND_CONTEXT)).rejects.toThrow(/missing header/);
247
+ });
248
+ });
packages/agent/test/harness/jsonl-v3-migration.test.ts ADDED
@@ -0,0 +1,2013 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import type { Usage } from "@earendil-works/pi-ai";
2
+ import { afterEach, beforeEach, describe, expect, it } from "vitest";
3
+ import { BACKGROUND_CONTEXT, type Context } from "../../src/harness/context.ts";
4
+ import { NodeExecutionEnv } from "../../src/harness/env/nodejs.ts";
5
+ import {
6
+ JSONL_FORMAT_VERSION,
7
+ JSONL_STORAGE_VERSION,
8
+ type JsonlSessionMetadata,
9
+ JsonlSessionRepo,
10
+ JsonlStorage,
11
+ } from "../../src/harness/session/jsonl/index.ts";
12
+ import type { Entry, Session } from "../../src/harness/session/types.ts";
13
+ import * as storedValues from "../../src/harness/session/values.ts";
14
+ import { err, FileError, getOrThrow, type Result } from "../../src/harness/types.ts";
15
+ import type { AgentMessage } from "../../src/types.ts";
16
+ import { createTempDir } from "./session-test-utils.ts";
17
+
18
+ const NOW = 1_700_000_000_000;
19
+
20
+ class FailableRenameNodeExecutionEnv extends NodeExecutionEnv {
21
+ failRename = false;
22
+
23
+ override async renameFile(
24
+ sourcePath: string,
25
+ destinationPath: string,
26
+ context: Context,
27
+ ): Promise<Result<void, FileError>> {
28
+ if (this.failRename) {
29
+ return err(new FileError("unknown", "Injected rename failure", sourcePath));
30
+ }
31
+ return super.renameFile(sourcePath, destinationPath, context);
32
+ }
33
+ }
34
+
35
+ function uuidTimestamp(id: string): number {
36
+ return Number.parseInt(id.replaceAll("-", "").slice(0, 12), 16);
37
+ }
38
+
39
+ async function mainBranch(session: Session) {
40
+ const branch = await session.branch("main", BACKGROUND_CONTEXT);
41
+ if (branch === undefined) throw new Error("Expected imported main Branch");
42
+ return branch;
43
+ }
44
+
45
+ async function mainTip(session: Session): Promise<string | null> {
46
+ return (await mainBranch(session)).getTipId(BACKGROUND_CONTEXT);
47
+ }
48
+
49
+ describe("JSONL v3 migration", () => {
50
+ let fileSystem: FailableRenameNodeExecutionEnv;
51
+ let repo: JsonlSessionRepo;
52
+
53
+ beforeEach(() => {
54
+ fileSystem = new FailableRenameNodeExecutionEnv({ cwd: createTempDir() });
55
+ repo = new JsonlSessionRepo({
56
+ fileSystem,
57
+ sessionsRoot: "sessions",
58
+ now: () => NOW,
59
+ });
60
+ });
61
+
62
+ afterEach(async () => {
63
+ await repo.close(BACKGROUND_CONTEXT);
64
+ });
65
+
66
+ async function writeLegacyV3Fixture(
67
+ records: readonly unknown[],
68
+ headerOptions: { parentSession?: string } = {},
69
+ ): Promise<{ path: string; content: string }> {
70
+ const directory = getOrThrow(await fileSystem.joinPath(["sessions", "--workspace--"], BACKGROUND_CONTEXT));
71
+ getOrThrow(await fileSystem.createDir(directory, undefined, BACKGROUND_CONTEXT));
72
+ const relativePath = getOrThrow(await fileSystem.joinPath([directory, "legacy.jsonl"], BACKGROUND_CONTEXT));
73
+ const path = getOrThrow(await fileSystem.absolutePath(relativePath, BACKGROUND_CONTEXT));
74
+ const content = `${[
75
+ {
76
+ type: "session",
77
+ version: 3,
78
+ id: "legacy",
79
+ timestamp: new Date(NOW).toISOString(),
80
+ cwd: "/workspace",
81
+ ...headerOptions,
82
+ },
83
+ ...records,
84
+ ]
85
+ .map((record) => JSON.stringify(record))
86
+ .join("\n")}\n`;
87
+ getOrThrow(await fileSystem.writeFile(path, content, BACKGROUND_CONTEXT));
88
+ return { path, content };
89
+ }
90
+
91
+ it("discovers legacy v3 session files without rewriting them", async () => {
92
+ const { path, content } = await writeLegacyV3Fixture([], {
93
+ parentSession: "/old-session.jsonl",
94
+ });
95
+
96
+ const [metadata] = await repo.list({ cwd: "/workspace" }, BACKGROUND_CONTEXT);
97
+ const after = getOrThrow(await fileSystem.readTextFile(path, BACKGROUND_CONTEXT));
98
+
99
+ expect(metadata).toMatchObject({
100
+ id: "legacy",
101
+ createdAt: NOW,
102
+ storageVersion: JSONL_STORAGE_VERSION,
103
+ cwd: "/workspace",
104
+ path,
105
+ legacyParentSessionPath: "/old-session.jsonl",
106
+ });
107
+ expect(Number.isFinite(metadata?.modifiedAt)).toBe(true);
108
+ expect(after).toBe(content);
109
+ });
110
+
111
+ it.each([
112
+ {
113
+ format: "v3",
114
+ parentId: "legacy-parent",
115
+ header: {
116
+ type: "session",
117
+ version: 3,
118
+ id: "legacy-parent",
119
+ timestamp: new Date(NOW - 1_000).toISOString(),
120
+ cwd: "/workspace",
121
+ },
122
+ },
123
+ {
124
+ format: "v4",
125
+ parentId: "current-parent",
126
+ header: {
127
+ v: 4,
128
+ kind: "header",
129
+ id: "current-parent",
130
+ storageVersion: JSONL_STORAGE_VERSION,
131
+ createdAt: NOW - 1_000,
132
+ cwd: "/workspace",
133
+ },
134
+ },
135
+ ])("resolves an available $format parent path to its session id", async ({ format, parentId, header }) => {
136
+ const parentPath = getOrThrow(await fileSystem.absolutePath(`parent-${format}.jsonl`, BACKGROUND_CONTEXT));
137
+ getOrThrow(await fileSystem.writeFile(parentPath, `${JSON.stringify(header)}\n`, BACKGROUND_CONTEXT));
138
+ await writeLegacyV3Fixture([], { parentSession: parentPath });
139
+
140
+ const [metadata] = await repo.list({ cwd: "/workspace" }, BACKGROUND_CONTEXT);
141
+ if (metadata === undefined) throw new Error("Legacy fixture was not discovered");
142
+
143
+ expect(metadata).toMatchObject({
144
+ id: "legacy",
145
+ parentSessionId: parentId,
146
+ });
147
+ expect(metadata).not.toHaveProperty("legacyParentSessionPath");
148
+ const session = await repo.open(metadata, BACKGROUND_CONTEXT);
149
+ expect(session.metadata).toMatchObject({ parentSessionId: parentId });
150
+ expect(session.metadata).not.toHaveProperty("legacyParentSessionPath");
151
+ await session.close(BACKGROUND_CONTEXT);
152
+ });
153
+
154
+ it("preserves an invalid parent path as legacy metadata", async () => {
155
+ const parentPath = getOrThrow(await fileSystem.absolutePath("invalid-parent.jsonl", BACKGROUND_CONTEXT));
156
+ getOrThrow(await fileSystem.writeFile(parentPath, '{"not":"a session header"}\n', BACKGROUND_CONTEXT));
157
+ await writeLegacyV3Fixture([], { parentSession: parentPath });
158
+
159
+ const [metadata] = await repo.list({ cwd: "/workspace" }, BACKGROUND_CONTEXT);
160
+
161
+ expect(metadata).toMatchObject({
162
+ id: "legacy",
163
+ legacyParentSessionPath: parentPath,
164
+ });
165
+ expect(metadata).not.toHaveProperty("parentSessionId");
166
+ });
167
+
168
+ describe("forking legacy v3 sessions", () => {
169
+ const firstMessage = {
170
+ role: "user",
171
+ content: [{ type: "text", text: "fork me" }],
172
+ timestamp: NOW + 1_000,
173
+ } satisfies AgentMessage;
174
+ const usage = {
175
+ input: 10,
176
+ output: 5,
177
+ cacheRead: 2,
178
+ cacheWrite: 1,
179
+ totalTokens: 18,
180
+ cost: {
181
+ input: 0.1,
182
+ output: 0.05,
183
+ cacheRead: 0.02,
184
+ cacheWrite: 0.01,
185
+ total: 0.18,
186
+ },
187
+ } satisfies Usage;
188
+ const secondMessage = {
189
+ role: "assistant",
190
+ content: [{ type: "text", text: "forked" }],
191
+ api: "anthropic-messages",
192
+ provider: "anthropic",
193
+ model: "claude-sonnet-4-5",
194
+ usage,
195
+ stopReason: "stop",
196
+ timestamp: NOW + 4_000,
197
+ } satisfies AgentMessage;
198
+
199
+ async function writeForkFixture() {
200
+ const fixture = await writeLegacyV3Fixture([
201
+ {
202
+ type: "message",
203
+ id: "message-1",
204
+ parentId: null,
205
+ timestamp: new Date(NOW + 1_000).toISOString(),
206
+ message: firstMessage,
207
+ },
208
+ {
209
+ type: "label",
210
+ id: "label-1",
211
+ parentId: "message-1",
212
+ timestamp: new Date(NOW + 2_000).toISOString(),
213
+ targetId: "message-1",
214
+ label: "Fork point",
215
+ },
216
+ {
217
+ type: "session_info",
218
+ id: "session-info",
219
+ parentId: "label-1",
220
+ timestamp: new Date(NOW + 3_000).toISOString(),
221
+ name: "Imported fork",
222
+ },
223
+ {
224
+ type: "message",
225
+ id: "message-2",
226
+ parentId: "session-info",
227
+ timestamp: new Date(NOW + 4_000).toISOString(),
228
+ message: secondMessage,
229
+ },
230
+ ]);
231
+ const [metadata] = await repo.list({ cwd: "/workspace" }, BACKGROUND_CONTEXT);
232
+ if (metadata === undefined) throw new Error("Legacy fixture was not discovered");
233
+ return { ...fixture, metadata };
234
+ }
235
+
236
+ async function expectForkedState(fork: Session<JsonlSessionMetadata>): Promise<Entry[]> {
237
+ expect(fork.metadata).toMatchObject({
238
+ storageVersion: JSONL_STORAGE_VERSION,
239
+ parentSessionId: "legacy",
240
+ });
241
+ const entries = await fork.findEntries({ order: "asc" }, BACKGROUND_CONTEXT);
242
+ expect(entries).toHaveLength(2);
243
+ const [first, second] = entries;
244
+ if (first === undefined || second === undefined) throw new Error("Forked entries were not written");
245
+ expect(first).toMatchObject({
246
+ type: "message",
247
+ parentId: null,
248
+ message: firstMessage,
249
+ });
250
+ expect(second).toMatchObject({
251
+ type: "message",
252
+ parentId: first.id,
253
+ message: secondMessage,
254
+ });
255
+ expect(first.id).not.toBe("message-1");
256
+ expect(second.id).not.toBe("message-2");
257
+ expect(await mainTip(fork)).toBe(second.id);
258
+ expect(await fork.getName(BACKGROUND_CONTEXT)).toBe("Imported fork");
259
+ expect(await fork.getLabel(first.id, BACKGROUND_CONTEXT)).toBe("Fork point");
260
+ expect(await fork.getValue(storedValues.laneState("main"), BACKGROUND_CONTEXT)).toBeUndefined();
261
+ expect(await fork.getValue(storedValues.laneConfig("main"), BACKGROUND_CONTEXT)).toBeUndefined();
262
+ expect(await fork.getStats(BACKGROUND_CONTEXT)).toEqual({
263
+ messageCount: 2,
264
+ usage: {
265
+ input: 0,
266
+ output: 0,
267
+ cacheRead: 0,
268
+ cacheWrite: 0,
269
+ totalTokens: 0,
270
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
271
+ },
272
+ });
273
+ return entries;
274
+ }
275
+
276
+ it("forks a closed source into a complete v4 destination without rewriting it", async () => {
277
+ const { path, content, metadata } = await writeForkFixture();
278
+
279
+ const fork = await repo.fork(metadata, { id: "closed-fork", scope: "tree" }, BACKGROUND_CONTEXT);
280
+
281
+ expect(getOrThrow(await fileSystem.readTextFile(path, BACKGROUND_CONTEXT))).toBe(content);
282
+ expect(fork.metadata.id).toBe("closed-fork");
283
+ const [headerLine] = getOrThrow(
284
+ await fileSystem.readTextLines(fork.metadata.path, { maxLines: 1 }, BACKGROUND_CONTEXT),
285
+ );
286
+ if (headerLine === undefined) throw new Error("Fork header was not written");
287
+ expect(JSON.parse(headerLine)).toMatchObject({
288
+ v: 4,
289
+ kind: "header",
290
+ id: "closed-fork",
291
+ storageVersion: JSONL_STORAGE_VERSION,
292
+ parentSessionId: "legacy",
293
+ });
294
+ await expectForkedState(fork);
295
+
296
+ await fork.close(BACKGROUND_CONTEXT);
297
+ const destinationStorage = await JsonlStorage.open(
298
+ { fileSystem, path: fork.metadata.path, now: () => NOW },
299
+ BACKGROUND_CONTEXT,
300
+ );
301
+ expect(await destinationStorage.scanUsage({ order: "asc" }, BACKGROUND_CONTEXT)).toEqual([]);
302
+ await destinationStorage.close(BACKGROUND_CONTEXT);
303
+ expect(getOrThrow(await fileSystem.readTextFile(path, BACKGROUND_CONTEXT))).toBe(content);
304
+ });
305
+
306
+ it("forks a configured closed source at its main tip when entryId is omitted", async () => {
307
+ await writeLegacyV3Fixture([
308
+ {
309
+ type: "model_change",
310
+ id: "model",
311
+ parentId: null,
312
+ timestamp: new Date(NOW + 1_000).toISOString(),
313
+ provider: "anthropic",
314
+ modelId: "claude-sonnet-4-5",
315
+ },
316
+ {
317
+ type: "thinking_level_change",
318
+ id: "thinking",
319
+ parentId: "model",
320
+ timestamp: new Date(NOW + 2_000).toISOString(),
321
+ thinkingLevel: "high",
322
+ },
323
+ {
324
+ type: "message",
325
+ id: "tip",
326
+ parentId: "thinking",
327
+ timestamp: new Date(NOW + 3_000).toISOString(),
328
+ message: firstMessage,
329
+ },
330
+ ]);
331
+ const [metadata] = await repo.list({ cwd: "/workspace" }, BACKGROUND_CONTEXT);
332
+ if (metadata === undefined) throw new Error("Legacy fixture was not discovered");
333
+
334
+ const fork = await repo.fork(
335
+ metadata,
336
+ { id: "branch-fork", scope: "branch", branch: "main" },
337
+ BACKGROUND_CONTEXT,
338
+ );
339
+ const entries = await fork.findEntries({ order: "asc" }, BACKGROUND_CONTEXT);
340
+ expect(entries).toHaveLength(1);
341
+ expect(await mainTip(fork)).toBe(entries[0]!.id);
342
+ expect((await fork.getValue(storedValues.laneConfig("main"), BACKGROUND_CONTEXT))?.value).toEqual({
343
+ model: { provider: "anthropic", modelId: "claude-sonnet-4-5" },
344
+ thinkingLevel: "high",
345
+ activeToolNames: [],
346
+ });
347
+ expect((await fork.getValue(storedValues.laneState("main"), BACKGROUND_CONTEXT))?.value).toEqual({
348
+ currentOperationId: null,
349
+ lastOperationId: null,
350
+ inbox: [],
351
+ });
352
+ await fork.close(BACKGROUND_CONTEXT);
353
+ });
354
+
355
+ it("forks a configured closed source at an original legacy entry id", async () => {
356
+ await writeLegacyV3Fixture([
357
+ {
358
+ type: "model_change",
359
+ id: "model",
360
+ parentId: null,
361
+ timestamp: new Date(NOW + 1_000).toISOString(),
362
+ provider: "anthropic",
363
+ modelId: "claude-sonnet-4-5",
364
+ },
365
+ {
366
+ type: "thinking_level_change",
367
+ id: "thinking",
368
+ parentId: "model",
369
+ timestamp: new Date(NOW + 2_000).toISOString(),
370
+ thinkingLevel: "high",
371
+ },
372
+ {
373
+ type: "message",
374
+ id: "message-1",
375
+ parentId: "thinking",
376
+ timestamp: new Date(NOW + 3_000).toISOString(),
377
+ message: firstMessage,
378
+ },
379
+ {
380
+ type: "message",
381
+ id: "message-2",
382
+ parentId: "message-1",
383
+ timestamp: new Date(NOW + 4_000).toISOString(),
384
+ message: secondMessage,
385
+ },
386
+ {
387
+ type: "message",
388
+ id: "message-3",
389
+ parentId: "message-2",
390
+ timestamp: new Date(NOW + 5_000).toISOString(),
391
+ message: firstMessage,
392
+ },
393
+ ]);
394
+ const [metadata] = await repo.list({ cwd: "/workspace" }, BACKGROUND_CONTEXT);
395
+ if (metadata === undefined) throw new Error("Legacy fixture was not discovered");
396
+
397
+ const fork = await repo.fork(
398
+ metadata,
399
+ { id: "entry-fork", scope: "branch", branch: "main", entryId: "message-2" },
400
+ BACKGROUND_CONTEXT,
401
+ );
402
+ const entries = await fork.findEntries({ order: "asc" }, BACKGROUND_CONTEXT);
403
+ expect(entries).toHaveLength(2);
404
+ expect(entries[1]).toMatchObject({ parentId: entries[0]!.id, message: secondMessage });
405
+ expect(await mainTip(fork)).toBe(entries[1]!.id);
406
+ await fork.close(BACKGROUND_CONTEXT);
407
+ });
408
+
409
+ it("rejects an open v3 source until a non-empty commit persists its format-4 ids", async () => {
410
+ const { path, content, metadata } = await writeForkFixture();
411
+ const source = await repo.open(metadata, BACKGROUND_CONTEXT);
412
+ const sourceEntries = await source.findEntries({ order: "asc" }, BACKGROUND_CONTEXT);
413
+
414
+ await expect(repo.fork(metadata, { id: "open-fork", scope: "tree" }, BACKGROUND_CONTEXT)).rejects.toThrow(
415
+ "Cannot fork an open legacy v3 JSONL session",
416
+ );
417
+ expect(getOrThrow(await fileSystem.readTextFile(path, BACKGROUND_CONTEXT))).toBe(content);
418
+
419
+ await source.setName("Upgraded source", BACKGROUND_CONTEXT);
420
+ const fork = await repo.fork(metadata, { id: "open-fork", scope: "tree" }, BACKGROUND_CONTEXT);
421
+
422
+ expect(fork.metadata.id).toBe("open-fork");
423
+ expect(await fork.findEntries({ order: "asc" }, BACKGROUND_CONTEXT)).toEqual(sourceEntries);
424
+ expect(await fork.getName(BACKGROUND_CONTEXT)).toBe("Upgraded source");
425
+ await Promise.all([source.close(BACKGROUND_CONTEXT), fork.close(BACKGROUND_CONTEXT)]);
426
+ });
427
+ });
428
+
429
+ it("opens an empty legacy session with a data-only main Branch", async () => {
430
+ await writeLegacyV3Fixture([]);
431
+ const [metadata] = await repo.list({ cwd: "/workspace" }, BACKGROUND_CONTEXT);
432
+ if (metadata === undefined) throw new Error("Legacy fixture was not discovered");
433
+
434
+ const session = await repo.open(metadata, BACKGROUND_CONTEXT);
435
+ expect(await session.findEntries(undefined, BACKGROUND_CONTEXT)).toEqual([]);
436
+ expect(await mainTip(session)).toBeNull();
437
+ expect(await session.getValue(storedValues.laneState("main"), BACKGROUND_CONTEXT)).toBeUndefined();
438
+ expect(await session.getValue(storedValues.laneConfig("main"), BACKGROUND_CONTEXT)).toBeUndefined();
439
+ await session.close(BACKGROUND_CONTEXT);
440
+ });
441
+
442
+ it("reports embedded legacy usage without creating usage rows or rewriting the source", async () => {
443
+ const usage = (factor: number): Usage => ({
444
+ input: factor,
445
+ output: factor * 2,
446
+ cacheRead: factor * 3,
447
+ cacheWrite: factor * 4,
448
+ cacheWrite1h: factor * 5,
449
+ reasoning: factor * 6,
450
+ totalTokens: factor * 10,
451
+ cost: {
452
+ input: factor,
453
+ output: factor * 2,
454
+ cacheRead: factor * 3,
455
+ cacheWrite: factor * 4,
456
+ total: factor * 10,
457
+ },
458
+ });
459
+ const assistantUsage = usage(1);
460
+ const toolUsage = usage(10);
461
+ const compactionUsage = usage(100);
462
+ const branchSummaryUsage = usage(1_000);
463
+ const { path, content } = await writeLegacyV3Fixture([
464
+ {
465
+ type: "message",
466
+ id: "assistant",
467
+ parentId: null,
468
+ timestamp: new Date(NOW + 1_000).toISOString(),
469
+ message: {
470
+ role: "assistant",
471
+ content: [{ type: "text", text: "answer" }],
472
+ api: "anthropic-messages",
473
+ provider: "anthropic",
474
+ model: "claude-sonnet-4-5",
475
+ usage: assistantUsage,
476
+ stopReason: "stop",
477
+ timestamp: NOW + 1_000,
478
+ } satisfies AgentMessage,
479
+ },
480
+ {
481
+ type: "message",
482
+ id: "tool-result",
483
+ parentId: "assistant",
484
+ timestamp: new Date(NOW + 2_000).toISOString(),
485
+ message: {
486
+ role: "toolResult",
487
+ toolCallId: "call-1",
488
+ toolName: "test",
489
+ content: [{ type: "text", text: "result" }],
490
+ usage: toolUsage,
491
+ isError: false,
492
+ timestamp: NOW + 2_000,
493
+ } satisfies AgentMessage,
494
+ },
495
+ {
496
+ type: "compaction",
497
+ id: "compaction",
498
+ parentId: "tool-result",
499
+ timestamp: new Date(NOW + 3_000).toISOString(),
500
+ summary: "Earlier context",
501
+ firstKeptEntryId: "assistant",
502
+ tokensBefore: 1_000,
503
+ usage: compactionUsage,
504
+ },
505
+ {
506
+ type: "branch_summary",
507
+ id: "branch-summary",
508
+ parentId: "compaction",
509
+ timestamp: new Date(NOW + 4_000).toISOString(),
510
+ fromId: "assistant",
511
+ summary: "Abandoned branch",
512
+ usage: branchSummaryUsage,
513
+ },
514
+ ]);
515
+
516
+ const storage = await JsonlStorage.open({ fileSystem, path, now: () => NOW }, BACKGROUND_CONTEXT);
517
+
518
+ expect(await storage.getStats(BACKGROUND_CONTEXT)).toEqual({
519
+ messageCount: 2,
520
+ usage: usage(1_111),
521
+ });
522
+ expect(await storage.scanUsage({ order: "asc" }, BACKGROUND_CONTEXT)).toEqual([]);
523
+ await storage.close(BACKGROUND_CONTEXT);
524
+ expect(getOrThrow(await fileSystem.readTextFile(path, BACKGROUND_CONTEXT))).toBe(content);
525
+ });
526
+
527
+ describe("upgrading legacy v3 sessions to v4", () => {
528
+ const importedUsage = {
529
+ input: 10,
530
+ output: 5,
531
+ cacheRead: 2,
532
+ cacheWrite: 1,
533
+ totalTokens: 18,
534
+ cost: {
535
+ input: 0.1,
536
+ output: 0.05,
537
+ cacheRead: 0.02,
538
+ cacheWrite: 0.01,
539
+ total: 0.18,
540
+ },
541
+ } satisfies Usage;
542
+ const importedMessage = {
543
+ role: "assistant",
544
+ content: [{ type: "text", text: "imported answer" }],
545
+ api: "anthropic-messages",
546
+ provider: "anthropic",
547
+ model: "claude-sonnet-4-5",
548
+ usage: importedUsage,
549
+ stopReason: "stop",
550
+ timestamp: NOW + 1_000,
551
+ } satisfies AgentMessage;
552
+
553
+ function writeUsageFixture() {
554
+ return writeLegacyV3Fixture([
555
+ {
556
+ type: "message",
557
+ id: "assistant",
558
+ parentId: null,
559
+ timestamp: new Date(NOW + 1_000).toISOString(),
560
+ message: importedMessage,
561
+ },
562
+ ]);
563
+ }
564
+
565
+ it("writes one zero-valued usage adjustment when converting a session without imported usage", async () => {
566
+ const { path } = await writeLegacyV3Fixture([]);
567
+ const storage = await JsonlStorage.open({ fileSystem, path, now: () => NOW }, BACKGROUND_CONTEXT);
568
+
569
+ await storage.commit(
570
+ [storedValues.setValue(storedValues.sessionName, "Converted session")],
571
+ BACKGROUND_CONTEXT,
572
+ );
573
+
574
+ const usageRows = await storage.scanUsage({ order: "asc" }, BACKGROUND_CONTEXT);
575
+ expect(usageRows).toHaveLength(1);
576
+ expect(usageRows[0]).toMatchObject({
577
+ usage: {
578
+ input: 0,
579
+ output: 0,
580
+ cacheRead: 0,
581
+ cacheWrite: 0,
582
+ totalTokens: 0,
583
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
584
+ },
585
+ adjustment: true,
586
+ details: { source: "v3-import" },
587
+ });
588
+ expect(usageRows[0]).not.toHaveProperty("entryId");
589
+ await storage.close(BACKGROUND_CONTEXT);
590
+ });
591
+
592
+ it("converts to v4 and preserves the first caller transaction with one usage adjustment", async () => {
593
+ // Seed a v3 session whose embedded usage must become a durable v4 ledger adjustment.
594
+ const { path } = await writeUsageFixture();
595
+ // Capture the normalized read-only view so conversion can be checked for identity and stats stability.
596
+ const options = { fileSystem, path, now: () => NOW };
597
+ const storage = await JsonlStorage.open(options, BACKGROUND_CONTEXT);
598
+ const importedEntries = await storage.scanEntries({ order: "asc" }, BACKGROUND_CONTEXT);
599
+ const statsBefore = await storage.getStats(BACKGROUND_CONTEXT);
600
+
601
+ // The first caller write triggers conversion and must not expose the internal adjustment sequence.
602
+ const committed = await storage.commit(
603
+ [storedValues.setValue(storedValues.sessionName, "Converted session")],
604
+ BACKGROUND_CONTEXT,
605
+ );
606
+
607
+ expect(committed.seqs).toHaveLength(1);
608
+ expect(committed.firstSeq).toBe(committed.seqs[0]);
609
+ expect((await storage.getValue(storedValues.sessionName, BACKGROUND_CONTEXT))?.seq).toBe(committed.seqs[0]);
610
+ const usageRows = await storage.scanUsage({ order: "asc" }, BACKGROUND_CONTEXT);
611
+ expect(usageRows).toHaveLength(1);
612
+ const [adjustment] = usageRows;
613
+ if (adjustment === undefined) throw new Error("Import usage adjustment was not committed");
614
+ expect(adjustment).toMatchObject({
615
+ usage: importedUsage,
616
+ adjustment: true,
617
+ details: { source: "v3-import" },
618
+ });
619
+ expect(adjustment).not.toHaveProperty("entryId");
620
+ expect(committed.seqs).not.toContain(adjustment.seq);
621
+ expect(committed.stats).toEqual(statsBefore);
622
+ expect(await storage.getStats(BACKGROUND_CONTEXT)).toEqual(statsBefore);
623
+
624
+ // Conversion replaces the legacy file and retains the adjustment and caller writes as its first transaction.
625
+ const convertedLines = getOrThrow(await fileSystem.readTextFile(path, BACKGROUND_CONTEXT))
626
+ .trimEnd()
627
+ .split("\n");
628
+ const headerLine = convertedLines[0];
629
+ const transactionLine = convertedLines.at(-1);
630
+ if (headerLine === undefined || transactionLine === undefined)
631
+ throw new Error("Converted file was not written");
632
+ expect(JSON.parse(headerLine)).toMatchObject({
633
+ v: JSONL_FORMAT_VERSION,
634
+ kind: "header",
635
+ id: "legacy",
636
+ storageVersion: JSONL_STORAGE_VERSION,
637
+ createdAt: NOW,
638
+ cwd: "/workspace",
639
+ });
640
+ expect(JSON.parse(transactionLine)).toEqual([
641
+ { kind: "usage", ...adjustment },
642
+ {
643
+ kind: "value",
644
+ op: "set",
645
+ seq: committed.seqs[0],
646
+ namespace: storedValues.sessionName.namespace,
647
+ key: storedValues.sessionName.key,
648
+ value: "Converted session",
649
+ },
650
+ ]);
651
+ await storage.close(BACKGROUND_CONTEXT);
652
+
653
+ // Reopening through the ordinary v4 path must recover the complete normalized and newly committed state.
654
+ const reopened = await JsonlStorage.open(options, BACKGROUND_CONTEXT);
655
+ expect(await reopened.scanEntries({ order: "asc" }, BACKGROUND_CONTEXT)).toEqual(importedEntries);
656
+ const [importedEntry] = importedEntries;
657
+ if (importedEntry === undefined) throw new Error("Legacy message was not imported");
658
+ expect((await reopened.getValue(storedValues.branchTip("main"), BACKGROUND_CONTEXT))?.value).toBe(
659
+ importedEntry.id,
660
+ );
661
+ expect(await reopened.getValue(storedValues.laneState("main"), BACKGROUND_CONTEXT)).toBeUndefined();
662
+ expect((await reopened.getValue(storedValues.sessionName, BACKGROUND_CONTEXT))?.value).toBe(
663
+ "Converted session",
664
+ );
665
+ expect(await reopened.scanUsage({ order: "asc" }, BACKGROUND_CONTEXT)).toEqual([adjustment]);
666
+ expect(await reopened.getStats(BACKGROUND_CONTEXT)).toEqual(statsBefore);
667
+ await reopened.close(BACKGROUND_CONTEXT);
668
+ });
669
+
670
+ it("leaves the v3 source and live state unchanged when atomic publication fails", async () => {
671
+ const { path, content } = await writeUsageFixture();
672
+ const options = { fileSystem, path, now: () => NOW };
673
+ const storage = await JsonlStorage.open(options, BACKGROUND_CONTEXT);
674
+ const entriesBefore = await storage.scanEntries({ order: "asc" }, BACKGROUND_CONTEXT);
675
+ const leafBefore = await storage.getValue(storedValues.branchTip("main"), BACKGROUND_CONTEXT);
676
+ const laneStateBefore = await storage.getValue(storedValues.laneState("main"), BACKGROUND_CONTEXT);
677
+ const nameBefore = await storage.getValue(storedValues.sessionName, BACKGROUND_CONTEXT);
678
+ const statsBefore = await storage.getStats(BACKGROUND_CONTEXT);
679
+ const usageBefore = await storage.scanUsage({ order: "asc" }, BACKGROUND_CONTEXT);
680
+ if (leafBefore === undefined) throw new Error("Normalized main Branch tip is missing");
681
+ expect(laneStateBefore).toBeUndefined();
682
+
683
+ fileSystem.failRename = true;
684
+ await expect(
685
+ storage.commit([storedValues.setValue(storedValues.sessionName, "Converted session")], BACKGROUND_CONTEXT),
686
+ ).rejects.toThrow(`Failed to publish JSONL storage ${path}`);
687
+ fileSystem.failRename = false;
688
+
689
+ expect(getOrThrow(await fileSystem.readTextFile(path, BACKGROUND_CONTEXT))).toBe(content);
690
+ expect(await storage.scanEntries({ order: "asc" }, BACKGROUND_CONTEXT)).toEqual(entriesBefore);
691
+ expect(await storage.getValue(storedValues.branchTip("main"), BACKGROUND_CONTEXT)).toEqual(leafBefore);
692
+ expect(await storage.getValue(storedValues.laneState("main"), BACKGROUND_CONTEXT)).toEqual(laneStateBefore);
693
+ expect(await storage.getValue(storedValues.sessionName, BACKGROUND_CONTEXT)).toEqual(nameBefore);
694
+ expect(await storage.getStats(BACKGROUND_CONTEXT)).toEqual(statsBefore);
695
+ expect(await storage.scanUsage({ order: "asc" }, BACKGROUND_CONTEXT)).toEqual(usageBefore);
696
+
697
+ const committed = await storage.commit(
698
+ [storedValues.setValue(storedValues.sessionName, "Converted session")],
699
+ BACKGROUND_CONTEXT,
700
+ );
701
+
702
+ expect(committed.firstSeq).toBe(leafBefore.seq + 2);
703
+ expect(committed.seqs).toEqual([committed.firstSeq]);
704
+ expect(await storage.getValue(storedValues.sessionName, BACKGROUND_CONTEXT)).toMatchObject({
705
+ seq: committed.firstSeq,
706
+ value: "Converted session",
707
+ });
708
+ const usageRows = await storage.scanUsage({ order: "asc" }, BACKGROUND_CONTEXT);
709
+ expect(usageRows).toHaveLength(1);
710
+ expect(usageRows[0]).toMatchObject({
711
+ usage: importedUsage,
712
+ adjustment: true,
713
+ details: { source: "v3-import" },
714
+ });
715
+ expect(await storage.getStats(BACKGROUND_CONTEXT)).toEqual(statsBefore);
716
+ await storage.close(BACKGROUND_CONTEXT);
717
+ });
718
+ });
719
+
720
+ describe("reconstructing legacy lane configuration", () => {
721
+ const firstTimestamp = NOW + 1_000;
722
+ const modelChangeTimestamp = NOW + 2_000;
723
+ const thinkingChangeTimestamp = NOW + 3_000;
724
+ const activeToolsChangeTimestamp = NOW + 4_000;
725
+ const secondTimestamp = NOW + 5_000;
726
+ const firstMessage = {
727
+ role: "user",
728
+ content: [{ type: "text", text: "first" }],
729
+ timestamp: firstTimestamp,
730
+ } satisfies AgentMessage;
731
+ const secondMessage = {
732
+ role: "user",
733
+ content: [{ type: "text", text: "second" }],
734
+ timestamp: secondTimestamp,
735
+ } satisfies AgentMessage;
736
+ const configurationChanges = [
737
+ {
738
+ type: "model_change",
739
+ id: "model-change",
740
+ parentId: "message-1",
741
+ timestamp: new Date(modelChangeTimestamp).toISOString(),
742
+ provider: "anthropic",
743
+ modelId: "claude-sonnet-4-5",
744
+ },
745
+ {
746
+ type: "thinking_level_change",
747
+ id: "thinking-change",
748
+ parentId: "model-change",
749
+ timestamp: new Date(thinkingChangeTimestamp).toISOString(),
750
+ thinkingLevel: "high",
751
+ },
752
+ {
753
+ type: "active_tools_change",
754
+ id: "active-tools-change",
755
+ parentId: "thinking-change",
756
+ timestamp: new Date(activeToolsChangeTimestamp).toISOString(),
757
+ activeToolNames: ["read", "bash"],
758
+ },
759
+ ] as const;
760
+
761
+ it("reparents a retained child through configuration changes", async () => {
762
+ await writeLegacyV3Fixture([
763
+ {
764
+ type: "message",
765
+ id: "message-1",
766
+ parentId: null,
767
+ timestamp: new Date(firstTimestamp).toISOString(),
768
+ message: firstMessage,
769
+ },
770
+ ...configurationChanges,
771
+ {
772
+ type: "message",
773
+ id: "message-2",
774
+ parentId: "active-tools-change",
775
+ timestamp: new Date(secondTimestamp).toISOString(),
776
+ message: secondMessage,
777
+ },
778
+ ]);
779
+ const [metadata] = await repo.list({ cwd: "/workspace" }, BACKGROUND_CONTEXT);
780
+ if (metadata === undefined) throw new Error("Legacy fixture was not discovered");
781
+
782
+ const session = await repo.open(metadata, BACKGROUND_CONTEXT);
783
+ const entries = await session.findEntries({ order: "asc" }, BACKGROUND_CONTEXT);
784
+ expect(entries).toHaveLength(2);
785
+ const [first, second] = entries;
786
+ if (first === undefined || second === undefined) {
787
+ throw new Error("Legacy configuration-change chain was not imported");
788
+ }
789
+ expect(first).toMatchObject({
790
+ type: "message",
791
+ parentId: null,
792
+ message: firstMessage,
793
+ });
794
+ expect(second).toMatchObject({
795
+ type: "message",
796
+ parentId: first.id,
797
+ message: secondMessage,
798
+ });
799
+ expect(second.seq).toBeGreaterThan(first.seq);
800
+ expect(await mainTip(session)).toBe(second.id);
801
+ expect((await session.getValue(storedValues.laneConfig("main"), BACKGROUND_CONTEXT))?.value).toEqual({
802
+ model: { provider: "anthropic", modelId: "claude-sonnet-4-5" },
803
+ thinkingLevel: "high",
804
+ activeToolNames: ["read", "bash"],
805
+ });
806
+ expect((await session.getValue(storedValues.laneState("main"), BACKGROUND_CONTEXT))?.value).toEqual({
807
+ currentOperationId: null,
808
+ lastOperationId: null,
809
+ inbox: [],
810
+ });
811
+ await session.close(BACKGROUND_CONTEXT);
812
+ });
813
+
814
+ it("retains only configuration changes on the selected physical branch", async () => {
815
+ await writeLegacyV3Fixture([
816
+ {
817
+ type: "message",
818
+ id: "root",
819
+ parentId: null,
820
+ timestamp: new Date(firstTimestamp).toISOString(),
821
+ message: firstMessage,
822
+ },
823
+ {
824
+ type: "model_change",
825
+ id: "selected-model",
826
+ parentId: "root",
827
+ timestamp: new Date(modelChangeTimestamp).toISOString(),
828
+ provider: "anthropic",
829
+ modelId: "selected",
830
+ },
831
+ {
832
+ type: "thinking_level_change",
833
+ id: "selected-thinking",
834
+ parentId: "selected-model",
835
+ timestamp: new Date(thinkingChangeTimestamp).toISOString(),
836
+ thinkingLevel: "high",
837
+ },
838
+ {
839
+ type: "model_change",
840
+ id: "abandoned-model",
841
+ parentId: "root",
842
+ timestamp: new Date(activeToolsChangeTimestamp).toISOString(),
843
+ provider: "openai",
844
+ modelId: "abandoned",
845
+ },
846
+ {
847
+ type: "message",
848
+ id: "selected-tip",
849
+ parentId: "selected-thinking",
850
+ timestamp: new Date(secondTimestamp).toISOString(),
851
+ message: secondMessage,
852
+ },
853
+ ]);
854
+ const [metadata] = await repo.list({ cwd: "/workspace" }, BACKGROUND_CONTEXT);
855
+ if (metadata === undefined) throw new Error("Legacy fixture was not discovered");
856
+
857
+ const session = await repo.open(metadata, BACKGROUND_CONTEXT);
858
+ expect((await session.getValue(storedValues.laneConfig("main"), BACKGROUND_CONTEXT))?.value).toEqual({
859
+ model: { provider: "anthropic", modelId: "selected" },
860
+ thinkingLevel: "high",
861
+ activeToolNames: [],
862
+ });
863
+ expect((await session.getValue(storedValues.laneState("main"), BACKGROUND_CONTEXT))?.value).toEqual({
864
+ currentOperationId: null,
865
+ lastOperationId: null,
866
+ inbox: [],
867
+ });
868
+ await session.close(BACKGROUND_CONTEXT);
869
+ });
870
+
871
+ it.each([
872
+ {
873
+ name: "missing model",
874
+ changes: [
875
+ {
876
+ type: "thinking_level_change",
877
+ id: "thinking",
878
+ parentId: "root",
879
+ timestamp: new Date(thinkingChangeTimestamp).toISOString(),
880
+ thinkingLevel: "high",
881
+ },
882
+ ],
883
+ },
884
+ {
885
+ name: "missing thinking level",
886
+ changes: [
887
+ {
888
+ type: "model_change",
889
+ id: "model",
890
+ parentId: "root",
891
+ timestamp: new Date(modelChangeTimestamp).toISOString(),
892
+ provider: "anthropic",
893
+ modelId: "selected",
894
+ },
895
+ ],
896
+ },
897
+ ])("leaves main data-only for $name", async ({ changes }) => {
898
+ await writeLegacyV3Fixture([
899
+ {
900
+ type: "message",
901
+ id: "root",
902
+ parentId: null,
903
+ timestamp: new Date(firstTimestamp).toISOString(),
904
+ message: firstMessage,
905
+ },
906
+ ...changes,
907
+ {
908
+ type: "message",
909
+ id: "tip",
910
+ parentId: changes.at(-1)?.id ?? "root",
911
+ timestamp: new Date(secondTimestamp).toISOString(),
912
+ message: secondMessage,
913
+ },
914
+ ]);
915
+ const [metadata] = await repo.list({ cwd: "/workspace" }, BACKGROUND_CONTEXT);
916
+ if (metadata === undefined) throw new Error("Legacy fixture was not discovered");
917
+
918
+ const session = await repo.open(metadata, BACKGROUND_CONTEXT);
919
+ expect(await session.getValue(storedValues.laneConfig("main"), BACKGROUND_CONTEXT)).toBeUndefined();
920
+ expect(await session.getValue(storedValues.laneState("main"), BACKGROUND_CONTEXT)).toBeUndefined();
921
+ await session.close(BACKGROUND_CONTEXT);
922
+ });
923
+
924
+ it("resolves the main tip through trailing configuration changes", async () => {
925
+ await writeLegacyV3Fixture([
926
+ {
927
+ type: "message",
928
+ id: "message-1",
929
+ parentId: null,
930
+ timestamp: new Date(firstTimestamp).toISOString(),
931
+ message: firstMessage,
932
+ },
933
+ ...configurationChanges,
934
+ ]);
935
+ const [metadata] = await repo.list({ cwd: "/workspace" }, BACKGROUND_CONTEXT);
936
+ if (metadata === undefined) throw new Error("Legacy fixture was not discovered");
937
+
938
+ const session = await repo.open(metadata, BACKGROUND_CONTEXT);
939
+ const entries = await session.findEntries({ order: "asc" }, BACKGROUND_CONTEXT);
940
+ expect(entries).toHaveLength(1);
941
+ const [message] = entries;
942
+ if (message === undefined) throw new Error("Legacy message was not imported");
943
+ expect(await mainTip(session)).toBe(message.id);
944
+ expect((await session.getValue(storedValues.laneConfig("main"), BACKGROUND_CONTEXT))?.value).toEqual({
945
+ model: { provider: "anthropic", modelId: "claude-sonnet-4-5" },
946
+ thinkingLevel: "high",
947
+ activeToolNames: ["read", "bash"],
948
+ });
949
+ expect((await session.getValue(storedValues.laneState("main"), BACKGROUND_CONTEXT))?.value).toEqual({
950
+ currentOperationId: null,
951
+ lastOperationId: null,
952
+ inbox: [],
953
+ });
954
+ await session.close(BACKGROUND_CONTEXT);
955
+ });
956
+ });
957
+
958
+ it("imports session info as the current name without retaining a tree entry", async () => {
959
+ await writeLegacyV3Fixture([
960
+ {
961
+ type: "session_info",
962
+ id: "session-info",
963
+ parentId: null,
964
+ timestamp: new Date(NOW + 1_000).toISOString(),
965
+ name: "Imported session",
966
+ },
967
+ ]);
968
+ const [metadata] = await repo.list({ cwd: "/workspace" }, BACKGROUND_CONTEXT);
969
+ if (metadata === undefined) throw new Error("Legacy fixture was not discovered");
970
+
971
+ const session = await repo.open(metadata, BACKGROUND_CONTEXT);
972
+ expect(await session.getName(BACKGROUND_CONTEXT)).toBe("Imported session");
973
+ expect(await session.findEntries(undefined, BACKGROUND_CONTEXT)).toEqual([]);
974
+ expect(await mainTip(session)).toBeNull();
975
+ await session.close(BACKGROUND_CONTEXT);
976
+ });
977
+
978
+ it("uses the latest session info and resolves tree structure through discarded records", async () => {
979
+ const firstMessage = {
980
+ role: "user",
981
+ content: [{ type: "text", text: "first" }],
982
+ timestamp: NOW + 1_000,
983
+ } satisfies AgentMessage;
984
+ const secondMessage = {
985
+ role: "user",
986
+ content: [{ type: "text", text: "second" }],
987
+ timestamp: NOW + 3_000,
988
+ } satisfies AgentMessage;
989
+ await writeLegacyV3Fixture([
990
+ {
991
+ type: "message",
992
+ id: "message-1",
993
+ parentId: null,
994
+ timestamp: new Date(NOW + 1_000).toISOString(),
995
+ message: firstMessage,
996
+ },
997
+ {
998
+ type: "session_info",
999
+ id: "session-info-1",
1000
+ parentId: "message-1",
1001
+ timestamp: new Date(NOW + 2_000).toISOString(),
1002
+ name: "Earlier name",
1003
+ },
1004
+ {
1005
+ type: "message",
1006
+ id: "message-2",
1007
+ parentId: "session-info-1",
1008
+ timestamp: new Date(NOW + 3_000).toISOString(),
1009
+ message: secondMessage,
1010
+ },
1011
+ {
1012
+ type: "session_info",
1013
+ id: "session-info-2",
1014
+ parentId: "message-2",
1015
+ timestamp: new Date(NOW + 4_000).toISOString(),
1016
+ name: "Latest name",
1017
+ },
1018
+ ]);
1019
+ const [metadata] = await repo.list({ cwd: "/workspace" }, BACKGROUND_CONTEXT);
1020
+ if (metadata === undefined) throw new Error("Legacy fixture was not discovered");
1021
+
1022
+ const session = await repo.open(metadata, BACKGROUND_CONTEXT);
1023
+ const entries = await session.findEntries({ order: "asc" }, BACKGROUND_CONTEXT);
1024
+ expect(entries).toHaveLength(2);
1025
+ const [first, second] = entries;
1026
+ if (first === undefined || second === undefined) throw new Error("Legacy message chain was not imported");
1027
+ expect(second.parentId).toBe(first.id);
1028
+ expect(await session.getName(BACKGROUND_CONTEXT)).toBe("Latest name");
1029
+ expect(await mainTip(session)).toBe(second.id);
1030
+ await session.close(BACKGROUND_CONTEXT);
1031
+ });
1032
+
1033
+ it.each([{ name: undefined }, { name: "" }])("clears the session name with $name", async ({ name }) => {
1034
+ await writeLegacyV3Fixture([
1035
+ {
1036
+ type: "session_info",
1037
+ id: "session-info-1",
1038
+ parentId: null,
1039
+ timestamp: new Date(NOW + 1_000).toISOString(),
1040
+ name: "Earlier name",
1041
+ },
1042
+ {
1043
+ type: "session_info",
1044
+ id: "session-info-2",
1045
+ parentId: "session-info-1",
1046
+ timestamp: new Date(NOW + 2_000).toISOString(),
1047
+ ...(name === undefined ? {} : { name }),
1048
+ },
1049
+ ]);
1050
+ const [metadata] = await repo.list({ cwd: "/workspace" }, BACKGROUND_CONTEXT);
1051
+ if (metadata === undefined) throw new Error("Legacy fixture was not discovered");
1052
+
1053
+ const session = await repo.open(metadata, BACKGROUND_CONTEXT);
1054
+ expect(await session.getValue(storedValues.sessionName, BACKGROUND_CONTEXT)).toBeUndefined();
1055
+ await session.close(BACKGROUND_CONTEXT);
1056
+ });
1057
+
1058
+ it("imports a label for its remapped entry without retaining a tree node", async () => {
1059
+ const message = {
1060
+ role: "user",
1061
+ content: [{ type: "text", text: "label me" }],
1062
+ timestamp: NOW + 1_000,
1063
+ } satisfies AgentMessage;
1064
+ await writeLegacyV3Fixture([
1065
+ {
1066
+ type: "message",
1067
+ id: "message-1",
1068
+ parentId: null,
1069
+ timestamp: new Date(NOW + 1_000).toISOString(),
1070
+ message,
1071
+ },
1072
+ {
1073
+ type: "label",
1074
+ id: "label-1",
1075
+ parentId: "message-1",
1076
+ timestamp: new Date(NOW + 2_000).toISOString(),
1077
+ targetId: "message-1",
1078
+ label: "Important",
1079
+ },
1080
+ ]);
1081
+ const [metadata] = await repo.list({ cwd: "/workspace" }, BACKGROUND_CONTEXT);
1082
+ if (metadata === undefined) throw new Error("Legacy fixture was not discovered");
1083
+
1084
+ const session = await repo.open(metadata, BACKGROUND_CONTEXT);
1085
+ const entries = await session.findEntries({ order: "asc" }, BACKGROUND_CONTEXT);
1086
+ expect(entries).toHaveLength(1);
1087
+ const [entry] = entries;
1088
+ if (entry === undefined) throw new Error("Legacy message was not imported");
1089
+ expect((await session.getValue(storedValues.entryLabel(entry.id), BACKGROUND_CONTEXT))?.value).toBe("Important");
1090
+ expect(await mainTip(session)).toBe(entry.id);
1091
+ await session.close(BACKGROUND_CONTEXT);
1092
+ });
1093
+
1094
+ it("skips a label whose target has no retained ancestor", async () => {
1095
+ const message = {
1096
+ role: "user",
1097
+ content: [{ type: "text", text: "retained message" }],
1098
+ timestamp: NOW + 3_000,
1099
+ } satisfies AgentMessage;
1100
+ await writeLegacyV3Fixture([
1101
+ {
1102
+ type: "session_info",
1103
+ id: "root-session-info",
1104
+ parentId: null,
1105
+ timestamp: new Date(NOW + 1_000).toISOString(),
1106
+ },
1107
+ {
1108
+ type: "label",
1109
+ id: "root-label",
1110
+ parentId: "root-session-info",
1111
+ timestamp: new Date(NOW + 2_000).toISOString(),
1112
+ targetId: "root-session-info",
1113
+ label: "Skipped label",
1114
+ },
1115
+ {
1116
+ type: "message",
1117
+ id: "message-1",
1118
+ parentId: "root-label",
1119
+ timestamp: new Date(NOW + 3_000).toISOString(),
1120
+ message,
1121
+ },
1122
+ ]);
1123
+ const [metadata] = await repo.list({ cwd: "/workspace" }, BACKGROUND_CONTEXT);
1124
+ if (metadata === undefined) throw new Error("Legacy fixture was not discovered");
1125
+
1126
+ const session = await repo.open(metadata, BACKGROUND_CONTEXT);
1127
+ const entries = await session.findEntries({ order: "asc" }, BACKGROUND_CONTEXT);
1128
+ expect(entries).toHaveLength(1);
1129
+ const [entry] = entries;
1130
+ if (entry === undefined) throw new Error("Legacy message was not imported");
1131
+ expect(entry.parentId).toBeNull();
1132
+ expect(await session.getLabel(entry.id, BACKGROUND_CONTEXT)).toBeUndefined();
1133
+ expect(await mainTip(session)).toBe(entry.id);
1134
+ await session.close(BACKGROUND_CONTEXT);
1135
+ });
1136
+
1137
+ it("uses the latest label after remapping discarded targets", async () => {
1138
+ const firstMessage = {
1139
+ role: "user",
1140
+ content: [{ type: "text", text: "first" }],
1141
+ timestamp: NOW + 1_000,
1142
+ } satisfies AgentMessage;
1143
+ const secondMessage = {
1144
+ role: "user",
1145
+ content: [{ type: "text", text: "second" }],
1146
+ timestamp: NOW + 5_000,
1147
+ } satisfies AgentMessage;
1148
+ await writeLegacyV3Fixture([
1149
+ {
1150
+ type: "message",
1151
+ id: "message-1",
1152
+ parentId: null,
1153
+ timestamp: new Date(NOW + 1_000).toISOString(),
1154
+ message: firstMessage,
1155
+ },
1156
+ {
1157
+ type: "session_info",
1158
+ id: "session-info",
1159
+ parentId: "message-1",
1160
+ timestamp: new Date(NOW + 2_000).toISOString(),
1161
+ },
1162
+ {
1163
+ type: "label",
1164
+ id: "label-1",
1165
+ parentId: "session-info",
1166
+ timestamp: new Date(NOW + 3_000).toISOString(),
1167
+ targetId: "session-info",
1168
+ label: "Earlier label",
1169
+ },
1170
+ {
1171
+ type: "label",
1172
+ id: "label-2",
1173
+ parentId: "label-1",
1174
+ timestamp: new Date(NOW + 4_000).toISOString(),
1175
+ targetId: "message-1",
1176
+ label: "Latest label",
1177
+ },
1178
+ {
1179
+ type: "message",
1180
+ id: "message-2",
1181
+ parentId: "label-2",
1182
+ timestamp: new Date(NOW + 5_000).toISOString(),
1183
+ message: secondMessage,
1184
+ },
1185
+ ]);
1186
+ const [metadata] = await repo.list({ cwd: "/workspace" }, BACKGROUND_CONTEXT);
1187
+ if (metadata === undefined) throw new Error("Legacy fixture was not discovered");
1188
+
1189
+ const session = await repo.open(metadata, BACKGROUND_CONTEXT);
1190
+ const entries = await session.findEntries({ order: "asc" }, BACKGROUND_CONTEXT);
1191
+ expect(entries).toHaveLength(2);
1192
+ const [first, second] = entries;
1193
+ if (first === undefined || second === undefined) throw new Error("Legacy message chain was not imported");
1194
+ expect(second.parentId).toBe(first.id);
1195
+ expect(await session.getLabel(first.id, BACKGROUND_CONTEXT)).toBe("Latest label");
1196
+ expect(await mainTip(session)).toBe(second.id);
1197
+ await session.close(BACKGROUND_CONTEXT);
1198
+ });
1199
+
1200
+ it.each([{ label: undefined }, { label: "" }])("clears a label with $label", async ({ label }) => {
1201
+ const message = {
1202
+ role: "user",
1203
+ content: [{ type: "text", text: "clear my label" }],
1204
+ timestamp: NOW + 1_000,
1205
+ } satisfies AgentMessage;
1206
+ await writeLegacyV3Fixture([
1207
+ {
1208
+ type: "message",
1209
+ id: "message-1",
1210
+ parentId: null,
1211
+ timestamp: new Date(NOW + 1_000).toISOString(),
1212
+ message,
1213
+ },
1214
+ {
1215
+ type: "label",
1216
+ id: "label-1",
1217
+ parentId: "message-1",
1218
+ timestamp: new Date(NOW + 2_000).toISOString(),
1219
+ targetId: "message-1",
1220
+ label: "Earlier label",
1221
+ },
1222
+ {
1223
+ type: "label",
1224
+ id: "label-2",
1225
+ parentId: "label-1",
1226
+ timestamp: new Date(NOW + 3_000).toISOString(),
1227
+ targetId: "message-1",
1228
+ ...(label === undefined ? {} : { label }),
1229
+ },
1230
+ ]);
1231
+ const [metadata] = await repo.list({ cwd: "/workspace" }, BACKGROUND_CONTEXT);
1232
+ if (metadata === undefined) throw new Error("Legacy fixture was not discovered");
1233
+
1234
+ const session = await repo.open(metadata, BACKGROUND_CONTEXT);
1235
+ const entries = await session.findEntries(undefined, BACKGROUND_CONTEXT);
1236
+ const [entry] = entries;
1237
+ if (entry === undefined) throw new Error("Legacy message was not imported");
1238
+ expect(await session.getLabel(entry.id, BACKGROUND_CONTEXT)).toBeUndefined();
1239
+ expect(await mainTip(session)).toBe(entry.id);
1240
+ await session.close(BACKGROUND_CONTEXT);
1241
+ });
1242
+
1243
+ it("imports a custom entry without rewriting opaque data references", async () => {
1244
+ const messageTimestamp = NOW + 1_000;
1245
+ const customTimestamp = NOW + 2_000;
1246
+ const message = {
1247
+ role: "user",
1248
+ content: [{ type: "text", text: "first" }],
1249
+ timestamp: messageTimestamp,
1250
+ } satisfies AgentMessage;
1251
+ const data = {
1252
+ legacyReference: "message-1",
1253
+ nested: { legacyReference: "custom-1" },
1254
+ };
1255
+ await writeLegacyV3Fixture([
1256
+ {
1257
+ type: "message",
1258
+ id: "message-1",
1259
+ parentId: null,
1260
+ timestamp: new Date(messageTimestamp).toISOString(),
1261
+ message,
1262
+ },
1263
+ {
1264
+ type: "custom",
1265
+ id: "custom-1",
1266
+ parentId: "message-1",
1267
+ timestamp: new Date(customTimestamp).toISOString(),
1268
+ customType: "checkpoint",
1269
+ data,
1270
+ },
1271
+ ]);
1272
+ const [metadata] = await repo.list({ cwd: "/workspace" }, BACKGROUND_CONTEXT);
1273
+ if (metadata === undefined) throw new Error("Legacy fixture was not discovered");
1274
+
1275
+ const session = await repo.open(metadata, BACKGROUND_CONTEXT);
1276
+ const entries = await session.findEntries({ order: "asc" }, BACKGROUND_CONTEXT);
1277
+ expect(entries).toHaveLength(2);
1278
+ const [messageEntry, customEntry] = entries;
1279
+ if (messageEntry === undefined || customEntry === undefined) {
1280
+ throw new Error("Legacy custom chain was not imported");
1281
+ }
1282
+ expect(messageEntry.seq).toBe(1);
1283
+ expect(customEntry).toMatchObject({
1284
+ type: "custom",
1285
+ parentId: messageEntry.id,
1286
+ seq: 2,
1287
+ timestamp: customTimestamp,
1288
+ customType: "checkpoint",
1289
+ data,
1290
+ });
1291
+ expect(customEntry.id).toMatch(/^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/);
1292
+ expect(uuidTimestamp(customEntry.id)).toBe(customTimestamp);
1293
+ expect(await mainTip(session)).toBe(customEntry.id);
1294
+ await session.close(BACKGROUND_CONTEXT);
1295
+ });
1296
+
1297
+ it("imports a custom message as a current message entry", async () => {
1298
+ const parentTimestamp = NOW + 1_000;
1299
+ const customMessageTimestamp = NOW + 2_000;
1300
+ const parentMessage = {
1301
+ role: "user",
1302
+ content: [{ type: "text", text: "first" }],
1303
+ timestamp: parentTimestamp,
1304
+ } satisfies AgentMessage;
1305
+ const content = [{ type: "text", text: "legacy custom message" }];
1306
+ const details = { status: "complete" };
1307
+ await writeLegacyV3Fixture([
1308
+ {
1309
+ type: "message",
1310
+ id: "message-1",
1311
+ parentId: null,
1312
+ timestamp: new Date(parentTimestamp).toISOString(),
1313
+ message: parentMessage,
1314
+ },
1315
+ {
1316
+ type: "custom_message",
1317
+ id: "custom-message-1",
1318
+ parentId: "message-1",
1319
+ timestamp: new Date(customMessageTimestamp).toISOString(),
1320
+ customType: "status",
1321
+ content,
1322
+ details,
1323
+ display: false,
1324
+ },
1325
+ ]);
1326
+ const [metadata] = await repo.list({ cwd: "/workspace" }, BACKGROUND_CONTEXT);
1327
+ if (metadata === undefined) throw new Error("Legacy fixture was not discovered");
1328
+
1329
+ const session = await repo.open(metadata, BACKGROUND_CONTEXT);
1330
+ const entries = await session.findEntries({ order: "asc" }, BACKGROUND_CONTEXT);
1331
+ expect(entries).toHaveLength(2);
1332
+ const [parentEntry, customMessageEntry] = entries;
1333
+ if (parentEntry === undefined || customMessageEntry === undefined) {
1334
+ throw new Error("Legacy custom message chain was not imported");
1335
+ }
1336
+ expect(parentEntry.seq).toBe(1);
1337
+ expect(customMessageEntry).toMatchObject({
1338
+ type: "message",
1339
+ parentId: parentEntry.id,
1340
+ seq: 2,
1341
+ timestamp: customMessageTimestamp,
1342
+ message: {
1343
+ role: "custom",
1344
+ customType: "status",
1345
+ content,
1346
+ details,
1347
+ display: false,
1348
+ timestamp: customMessageTimestamp,
1349
+ },
1350
+ });
1351
+ expect(customMessageEntry.id).toMatch(/^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/);
1352
+ expect(uuidTimestamp(customMessageEntry.id)).toBe(customMessageTimestamp);
1353
+ expect(await mainTip(session)).toBe(customMessageEntry.id);
1354
+ expect((await session.getStats(BACKGROUND_CONTEXT)).messageCount).toBe(2);
1355
+ await session.close(BACKGROUND_CONTEXT);
1356
+ });
1357
+
1358
+ describe("importing branch summaries", () => {
1359
+ const branchPointTimestamp = NOW + 1_000;
1360
+ const abandonedResponseTimestamp = NOW + 2_000;
1361
+ const summaryTimestamp = NOW + 3_000;
1362
+ const details = { reason: "navigation" };
1363
+ const usage = {
1364
+ input: 11,
1365
+ output: 7,
1366
+ cacheRead: 3,
1367
+ cacheWrite: 2,
1368
+ totalTokens: 23,
1369
+ cost: {
1370
+ input: 0.11,
1371
+ output: 0.07,
1372
+ cacheRead: 0.03,
1373
+ cacheWrite: 0.02,
1374
+ total: 0.23,
1375
+ },
1376
+ } satisfies Usage;
1377
+ const branchPointMessage = {
1378
+ role: "user",
1379
+ content: [{ type: "text", text: "Try the first approach" }],
1380
+ timestamp: branchPointTimestamp,
1381
+ } satisfies AgentMessage;
1382
+ const abandonedResponse = {
1383
+ role: "assistant",
1384
+ content: [{ type: "text", text: "Implemented the first approach" }],
1385
+ api: "anthropic-messages",
1386
+ provider: "anthropic",
1387
+ model: "claude-sonnet-4-5",
1388
+ usage: {
1389
+ input: 20,
1390
+ output: 10,
1391
+ cacheRead: 0,
1392
+ cacheWrite: 0,
1393
+ totalTokens: 30,
1394
+ cost: {
1395
+ input: 0.2,
1396
+ output: 0.1,
1397
+ cacheRead: 0,
1398
+ cacheWrite: 0,
1399
+ total: 0.3,
1400
+ },
1401
+ },
1402
+ stopReason: "stop",
1403
+ timestamp: abandonedResponseTimestamp,
1404
+ } satisfies AgentMessage;
1405
+
1406
+ async function openFixture(fromHook?: true) {
1407
+ await writeLegacyV3Fixture([
1408
+ {
1409
+ type: "message",
1410
+ id: "branch-point",
1411
+ parentId: null,
1412
+ timestamp: new Date(branchPointTimestamp).toISOString(),
1413
+ message: branchPointMessage,
1414
+ },
1415
+ {
1416
+ type: "message",
1417
+ id: "abandoned-response",
1418
+ parentId: "branch-point",
1419
+ timestamp: new Date(abandonedResponseTimestamp).toISOString(),
1420
+ message: abandonedResponse,
1421
+ },
1422
+ {
1423
+ type: "branch_summary",
1424
+ id: "summary",
1425
+ parentId: "branch-point",
1426
+ timestamp: new Date(summaryTimestamp).toISOString(),
1427
+ fromId: "branch-point",
1428
+ summary: "Summary of the abandoned branch",
1429
+ details,
1430
+ usage,
1431
+ ...(fromHook === undefined ? {} : { fromHook }),
1432
+ },
1433
+ ]);
1434
+ const [metadata] = await repo.list({ cwd: "/workspace" }, BACKGROUND_CONTEXT);
1435
+ if (metadata === undefined) throw new Error("Legacy fixture was not discovered");
1436
+
1437
+ const session = await repo.open(metadata, BACKGROUND_CONTEXT);
1438
+ const entries = await session.findEntries({ order: "asc" }, BACKGROUND_CONTEXT);
1439
+ expect(entries).toHaveLength(3);
1440
+ const [branchPoint, abandoned, branchSummary] = entries;
1441
+ if (branchPoint === undefined || abandoned === undefined || branchSummary === undefined) {
1442
+ throw new Error("Legacy branch summary chain was not imported");
1443
+ }
1444
+ return { session, branchPoint, abandoned, branchSummary };
1445
+ }
1446
+
1447
+ it("preserves payload and remaps references", async () => {
1448
+ const { session, branchPoint, abandoned, branchSummary } = await openFixture();
1449
+
1450
+ expect(abandoned.parentId).toBe(branchPoint.id);
1451
+ expect(branchSummary).toMatchObject({
1452
+ type: "branch_summary",
1453
+ parentId: branchPoint.id,
1454
+ seq: 3,
1455
+ timestamp: summaryTimestamp,
1456
+ fromId: branchPoint.id,
1457
+ summary: "Summary of the abandoned branch",
1458
+ details,
1459
+ usage,
1460
+ fromHook: false,
1461
+ });
1462
+ expect(branchSummary.id).toMatch(/^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/);
1463
+ expect(uuidTimestamp(branchSummary.id)).toBe(summaryTimestamp);
1464
+ expect(await mainTip(session)).toBe(branchSummary.id);
1465
+ await session.close(BACKGROUND_CONTEXT);
1466
+ });
1467
+
1468
+ it("preserves an explicit fromHook flag", async () => {
1469
+ const { session, branchSummary } = await openFixture(true);
1470
+
1471
+ expect(branchSummary).toMatchObject({
1472
+ type: "branch_summary",
1473
+ fromHook: true,
1474
+ });
1475
+ await session.close(BACKGROUND_CONTEXT);
1476
+ });
1477
+
1478
+ it('normalizes fromId "root" to null', async () => {
1479
+ await writeLegacyV3Fixture([
1480
+ {
1481
+ type: "branch_summary",
1482
+ id: "summary",
1483
+ parentId: null,
1484
+ timestamp: new Date(summaryTimestamp).toISOString(),
1485
+ fromId: "root",
1486
+ summary: "Summary from the root",
1487
+ },
1488
+ ]);
1489
+ const [metadata] = await repo.list({ cwd: "/workspace" }, BACKGROUND_CONTEXT);
1490
+ if (metadata === undefined) throw new Error("Legacy fixture was not discovered");
1491
+
1492
+ const session = await repo.open(metadata, BACKGROUND_CONTEXT);
1493
+ const entries = await session.findEntries({ order: "asc" }, BACKGROUND_CONTEXT);
1494
+ expect(entries).toHaveLength(1);
1495
+ expect(entries[0]).toMatchObject({
1496
+ type: "branch_summary",
1497
+ fromId: null,
1498
+ });
1499
+ await session.close(BACKGROUND_CONTEXT);
1500
+ });
1501
+
1502
+ it("rejects a missing fromId", async () => {
1503
+ await writeLegacyV3Fixture([
1504
+ {
1505
+ type: "branch_summary",
1506
+ id: "summary",
1507
+ parentId: null,
1508
+ timestamp: new Date(summaryTimestamp).toISOString(),
1509
+ fromId: "missing-legacy-entry",
1510
+ summary: "Summary from a missing source",
1511
+ },
1512
+ ]);
1513
+ const [metadata] = await repo.list({ cwd: "/workspace" }, BACKGROUND_CONTEXT);
1514
+ if (metadata === undefined) throw new Error("Legacy fixture was not discovered");
1515
+
1516
+ await expect(repo.open(metadata, BACKGROUND_CONTEXT)).rejects.toThrow(
1517
+ "Missing legacy v3 entry reference: missing-legacy-entry",
1518
+ );
1519
+ });
1520
+
1521
+ it("keeps fromId null when a discarded source has no retained ancestor", async () => {
1522
+ await writeLegacyV3Fixture([
1523
+ {
1524
+ type: "model_change",
1525
+ id: "model-change",
1526
+ parentId: null,
1527
+ timestamp: new Date(branchPointTimestamp).toISOString(),
1528
+ provider: "anthropic",
1529
+ modelId: "claude-sonnet-4-5",
1530
+ },
1531
+ {
1532
+ type: "branch_summary",
1533
+ id: "summary",
1534
+ parentId: "model-change",
1535
+ timestamp: new Date(summaryTimestamp).toISOString(),
1536
+ fromId: "model-change",
1537
+ summary: "Summary from the root",
1538
+ },
1539
+ ]);
1540
+ const [metadata] = await repo.list({ cwd: "/workspace" }, BACKGROUND_CONTEXT);
1541
+ if (metadata === undefined) throw new Error("Legacy fixture was not discovered");
1542
+
1543
+ const session = await repo.open(metadata, BACKGROUND_CONTEXT);
1544
+ const entries = await session.findEntries({ order: "asc" }, BACKGROUND_CONTEXT);
1545
+ expect(entries).toHaveLength(1);
1546
+ expect(entries[0]).toMatchObject({
1547
+ type: "branch_summary",
1548
+ parentId: null,
1549
+ fromId: null,
1550
+ });
1551
+ await session.close(BACKGROUND_CONTEXT);
1552
+ });
1553
+ });
1554
+
1555
+ describe("importing compactions", () => {
1556
+ const excludedTimestamp = NOW + 1_000;
1557
+ const retainedTimestamp = NOW + 2_000;
1558
+ const compactionTimestamp = NOW + 3_000;
1559
+ const excludedMessage = {
1560
+ role: "user",
1561
+ content: [{ type: "text", text: "old context" }],
1562
+ timestamp: excludedTimestamp,
1563
+ } satisfies AgentMessage;
1564
+ const retainedMessage = {
1565
+ role: "user",
1566
+ content: [{ type: "text", text: "retain this context" }],
1567
+ timestamp: retainedTimestamp,
1568
+ } satisfies AgentMessage;
1569
+ const details = { strategy: "default" };
1570
+ const usage = {
1571
+ input: 120,
1572
+ output: 30,
1573
+ cacheRead: 10,
1574
+ cacheWrite: 5,
1575
+ totalTokens: 165,
1576
+ cost: {
1577
+ input: 1.2,
1578
+ output: 0.3,
1579
+ cacheRead: 0.1,
1580
+ cacheWrite: 0.05,
1581
+ total: 1.65,
1582
+ },
1583
+ } satisfies Usage;
1584
+
1585
+ async function openFixture(fromHook?: true) {
1586
+ await writeLegacyV3Fixture([
1587
+ {
1588
+ type: "message",
1589
+ id: "excluded-message",
1590
+ parentId: null,
1591
+ timestamp: new Date(excludedTimestamp).toISOString(),
1592
+ message: excludedMessage,
1593
+ },
1594
+ {
1595
+ type: "message",
1596
+ id: "retained-message",
1597
+ parentId: "excluded-message",
1598
+ timestamp: new Date(retainedTimestamp).toISOString(),
1599
+ message: retainedMessage,
1600
+ },
1601
+ {
1602
+ type: "compaction",
1603
+ id: "compaction",
1604
+ parentId: "retained-message",
1605
+ timestamp: new Date(compactionTimestamp).toISOString(),
1606
+ summary: "Summary of the earlier context",
1607
+ firstKeptEntryId: "retained-message",
1608
+ tokensBefore: 12_000,
1609
+ details,
1610
+ usage,
1611
+ ...(fromHook === undefined ? {} : { fromHook }),
1612
+ },
1613
+ ]);
1614
+ const [metadata] = await repo.list({ cwd: "/workspace" }, BACKGROUND_CONTEXT);
1615
+ if (metadata === undefined) throw new Error("Legacy fixture was not discovered");
1616
+
1617
+ const session = await repo.open(metadata, BACKGROUND_CONTEXT);
1618
+ const entries = await session.findEntries({ order: "asc" }, BACKGROUND_CONTEXT);
1619
+ expect(entries).toHaveLength(3);
1620
+ const [excluded, retained, compaction] = entries;
1621
+ if (excluded === undefined || retained === undefined || compaction === undefined) {
1622
+ throw new Error("Legacy compaction chain was not imported");
1623
+ }
1624
+ return { session, excluded, retained, compaction };
1625
+ }
1626
+
1627
+ it("materializes the retained tail and preserves the payload", async () => {
1628
+ const { session, excluded, retained, compaction } = await openFixture();
1629
+
1630
+ expect(retained).toMatchObject({ parentId: excluded.id, seq: 2 });
1631
+ expect(compaction).toMatchObject({
1632
+ type: "compaction",
1633
+ parentId: retained.id,
1634
+ seq: 3,
1635
+ timestamp: compactionTimestamp,
1636
+ summary: "Summary of the earlier context",
1637
+ retainedTail: [retainedMessage],
1638
+ tokensBefore: 12_000,
1639
+ details,
1640
+ usage,
1641
+ fromHook: false,
1642
+ });
1643
+ expect(compaction).not.toHaveProperty("firstKeptEntryId");
1644
+ expect(compaction.id).toMatch(/^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/);
1645
+ expect(uuidTimestamp(compaction.id)).toBe(compactionTimestamp);
1646
+ expect(await mainTip(session)).toBe(compaction.id);
1647
+ await session.close(BACKGROUND_CONTEXT);
1648
+ });
1649
+
1650
+ it("builds the retained tail from the compaction branch rather than physical order", async () => {
1651
+ const firstMainMessage = {
1652
+ role: "user",
1653
+ content: [{ type: "text", text: "first main-branch message" }],
1654
+ timestamp: NOW + 10_000,
1655
+ } satisfies AgentMessage;
1656
+ const firstOtherBranchMessage = {
1657
+ role: "user",
1658
+ content: [{ type: "text", text: "first unrelated-branch message" }],
1659
+ timestamp: NOW + 11_000,
1660
+ } satisfies AgentMessage;
1661
+ const secondMainMessage = {
1662
+ role: "user",
1663
+ content: [{ type: "text", text: "second main-branch message" }],
1664
+ timestamp: NOW + 12_000,
1665
+ } satisfies AgentMessage;
1666
+ const secondOtherBranchMessage = {
1667
+ role: "user",
1668
+ content: [{ type: "text", text: "second unrelated-branch message" }],
1669
+ timestamp: NOW + 13_000,
1670
+ } satisfies AgentMessage;
1671
+ await writeLegacyV3Fixture([
1672
+ {
1673
+ type: "message",
1674
+ id: "main-1",
1675
+ parentId: null,
1676
+ timestamp: new Date(NOW + 10_000).toISOString(),
1677
+ message: firstMainMessage,
1678
+ },
1679
+ {
1680
+ type: "message",
1681
+ id: "other-1",
1682
+ parentId: "main-1",
1683
+ timestamp: new Date(NOW + 11_000).toISOString(),
1684
+ message: firstOtherBranchMessage,
1685
+ },
1686
+ {
1687
+ type: "message",
1688
+ id: "main-2",
1689
+ parentId: "main-1",
1690
+ timestamp: new Date(NOW + 12_000).toISOString(),
1691
+ message: secondMainMessage,
1692
+ },
1693
+ {
1694
+ type: "message",
1695
+ id: "other-2",
1696
+ parentId: "other-1",
1697
+ timestamp: new Date(NOW + 13_000).toISOString(),
1698
+ message: secondOtherBranchMessage,
1699
+ },
1700
+ {
1701
+ type: "compaction",
1702
+ id: "compaction",
1703
+ parentId: "main-2",
1704
+ timestamp: new Date(NOW + 14_000).toISOString(),
1705
+ summary: "Summary before the retained main branch",
1706
+ firstKeptEntryId: "main-1",
1707
+ tokensBefore: 8_000,
1708
+ },
1709
+ ]);
1710
+ const [metadata] = await repo.list({ cwd: "/workspace" }, BACKGROUND_CONTEXT);
1711
+ if (metadata === undefined) throw new Error("Legacy fixture was not discovered");
1712
+
1713
+ const session = await repo.open(metadata, BACKGROUND_CONTEXT);
1714
+ const entries = await session.findEntries({ order: "asc" }, BACKGROUND_CONTEXT);
1715
+ const compaction = entries.find((entry) => entry.type === "compaction");
1716
+
1717
+ expect(compaction).toMatchObject({
1718
+ type: "compaction",
1719
+ retainedTail: [firstMainMessage, secondMainMessage],
1720
+ });
1721
+ await session.close(BACKGROUND_CONTEXT);
1722
+ });
1723
+
1724
+ it("projects every supported legacy node in a retained tail", async () => {
1725
+ const ordinaryTimestamp = NOW + 30_000;
1726
+ const customMessageTimestamp = NOW + 31_000;
1727
+ const customEntryTimestamp = NOW + 32_000;
1728
+ const branchSummaryTimestamp = NOW + 33_000;
1729
+ const olderCompactionTimestamp = NOW + 34_000;
1730
+ const finalCompactionTimestamp = NOW + 35_000;
1731
+ const ordinaryMessage = {
1732
+ role: "user",
1733
+ content: [{ type: "text", text: "ordinary retained message" }],
1734
+ timestamp: ordinaryTimestamp,
1735
+ } satisfies AgentMessage;
1736
+ const customContent = [{ type: "text" as const, text: "custom retained message" }];
1737
+ const customDetails = { status: "complete" };
1738
+ await writeLegacyV3Fixture([
1739
+ {
1740
+ type: "message",
1741
+ id: "ordinary-message",
1742
+ parentId: null,
1743
+ timestamp: new Date(ordinaryTimestamp).toISOString(),
1744
+ message: ordinaryMessage,
1745
+ },
1746
+ {
1747
+ type: "custom_message",
1748
+ id: "custom-message",
1749
+ parentId: "ordinary-message",
1750
+ timestamp: new Date(customMessageTimestamp).toISOString(),
1751
+ customType: "notice",
1752
+ content: customContent,
1753
+ details: customDetails,
1754
+ display: false,
1755
+ },
1756
+ {
1757
+ type: "custom",
1758
+ id: "plain-custom",
1759
+ parentId: "custom-message",
1760
+ timestamp: new Date(customEntryTimestamp).toISOString(),
1761
+ customType: "checkpoint",
1762
+ data: { ignored: true },
1763
+ },
1764
+ {
1765
+ type: "branch_summary",
1766
+ id: "branch-summary",
1767
+ parentId: "plain-custom",
1768
+ timestamp: new Date(branchSummaryTimestamp).toISOString(),
1769
+ fromId: "ordinary-message",
1770
+ summary: "Earlier branch work",
1771
+ },
1772
+ {
1773
+ type: "compaction",
1774
+ id: "older-compaction",
1775
+ parentId: "branch-summary",
1776
+ timestamp: new Date(olderCompactionTimestamp).toISOString(),
1777
+ summary: "Older compacted context",
1778
+ firstKeptEntryId: "ordinary-message",
1779
+ tokensBefore: 4_000,
1780
+ },
1781
+ {
1782
+ type: "compaction",
1783
+ id: "final-compaction",
1784
+ parentId: "older-compaction",
1785
+ timestamp: new Date(finalCompactionTimestamp).toISOString(),
1786
+ summary: "Final compacted context",
1787
+ firstKeptEntryId: "ordinary-message",
1788
+ tokensBefore: 8_000,
1789
+ },
1790
+ ]);
1791
+ const [metadata] = await repo.list({ cwd: "/workspace" }, BACKGROUND_CONTEXT);
1792
+ if (metadata === undefined) throw new Error("Legacy fixture was not discovered");
1793
+
1794
+ const session = await repo.open(metadata, BACKGROUND_CONTEXT);
1795
+ const entries = await session.findEntries({ order: "asc" }, BACKGROUND_CONTEXT);
1796
+ expect(entries).toHaveLength(6);
1797
+ const ordinary = entries.at(0);
1798
+ const finalCompaction = entries.at(-1);
1799
+ if (ordinary === undefined || finalCompaction?.type !== "compaction") {
1800
+ throw new Error("Legacy retained-tail fixture was not imported");
1801
+ }
1802
+
1803
+ expect(uuidTimestamp(ordinary.id)).toBe(ordinaryTimestamp);
1804
+ expect(finalCompaction.retainedTail).toEqual([
1805
+ ordinaryMessage,
1806
+ {
1807
+ role: "custom",
1808
+ customType: "notice",
1809
+ content: customContent,
1810
+ details: customDetails,
1811
+ display: false,
1812
+ timestamp: customMessageTimestamp,
1813
+ },
1814
+ {
1815
+ role: "branchSummary",
1816
+ summary: "Earlier branch work",
1817
+ fromId: ordinary.id,
1818
+ timestamp: branchSummaryTimestamp,
1819
+ },
1820
+ {
1821
+ role: "compactionSummary",
1822
+ summary: "Older compacted context",
1823
+ tokensBefore: 4_000,
1824
+ timestamp: olderCompactionTimestamp,
1825
+ },
1826
+ ]);
1827
+ await session.close(BACKGROUND_CONTEXT);
1828
+ });
1829
+
1830
+ it.each([
1831
+ { boundary: "missing", firstKeptEntryId: "missing-entry" },
1832
+ { boundary: "off-branch", firstKeptEntryId: "other-branch" },
1833
+ ])("rejects a $boundary firstKeptEntryId", async ({ firstKeptEntryId }) => {
1834
+ await writeLegacyV3Fixture([
1835
+ {
1836
+ type: "message",
1837
+ id: "root",
1838
+ parentId: null,
1839
+ timestamp: new Date(NOW + 20_000).toISOString(),
1840
+ message: excludedMessage,
1841
+ },
1842
+ {
1843
+ type: "message",
1844
+ id: "main-branch",
1845
+ parentId: "root",
1846
+ timestamp: new Date(NOW + 21_000).toISOString(),
1847
+ message: retainedMessage,
1848
+ },
1849
+ {
1850
+ type: "message",
1851
+ id: "other-branch",
1852
+ parentId: "root",
1853
+ timestamp: new Date(NOW + 22_000).toISOString(),
1854
+ message: excludedMessage,
1855
+ },
1856
+ {
1857
+ type: "compaction",
1858
+ id: "compaction",
1859
+ parentId: "main-branch",
1860
+ timestamp: new Date(NOW + 23_000).toISOString(),
1861
+ summary: "Summary before the retained main branch",
1862
+ firstKeptEntryId,
1863
+ tokensBefore: 8_000,
1864
+ },
1865
+ ]);
1866
+ const [metadata] = await repo.list({ cwd: "/workspace" }, BACKGROUND_CONTEXT);
1867
+ if (metadata === undefined) throw new Error("Legacy fixture was not discovered");
1868
+
1869
+ await expect(repo.open(metadata, BACKGROUND_CONTEXT)).rejects.toThrow(
1870
+ "firstKeptEntryId is not on its parent branch",
1871
+ );
1872
+ });
1873
+
1874
+ it("preserves an explicit fromHook flag", async () => {
1875
+ const { session, compaction } = await openFixture(true);
1876
+
1877
+ expect(compaction).toMatchObject({ type: "compaction", fromHook: true });
1878
+ await session.close(BACKGROUND_CONTEXT);
1879
+ });
1880
+ });
1881
+
1882
+ it("remaps a legacy message chain and exposes it through current APIs", async () => {
1883
+ const firstTimestamp = NOW + 1_000;
1884
+ const secondTimestamp = NOW + 2_000;
1885
+ const firstMessage = {
1886
+ role: "user",
1887
+ content: [{ type: "text", text: "first" }],
1888
+ timestamp: firstTimestamp,
1889
+ } satisfies AgentMessage;
1890
+ const secondMessage = {
1891
+ role: "user",
1892
+ content: [{ type: "text", text: "second" }],
1893
+ timestamp: secondTimestamp,
1894
+ } satisfies AgentMessage;
1895
+ await writeLegacyV3Fixture([
1896
+ {
1897
+ type: "message",
1898
+ id: "message-1",
1899
+ parentId: null,
1900
+ timestamp: new Date(firstTimestamp).toISOString(),
1901
+ message: firstMessage,
1902
+ },
1903
+ {
1904
+ type: "message",
1905
+ id: "message-2",
1906
+ parentId: "message-1",
1907
+ timestamp: new Date(secondTimestamp).toISOString(),
1908
+ message: secondMessage,
1909
+ },
1910
+ ]);
1911
+ const [metadata] = await repo.list({ cwd: "/workspace" }, BACKGROUND_CONTEXT);
1912
+ if (metadata === undefined) throw new Error("Legacy fixture was not discovered");
1913
+
1914
+ const session = await repo.open(metadata, BACKGROUND_CONTEXT);
1915
+ const entries = await session.findEntries({ order: "asc" }, BACKGROUND_CONTEXT);
1916
+ expect(entries).toHaveLength(2);
1917
+ const [first, second] = entries;
1918
+ if (first === undefined || second === undefined) throw new Error("Legacy message chain was not imported");
1919
+ expect(first).toMatchObject({
1920
+ parentId: null,
1921
+ seq: 1,
1922
+ timestamp: firstTimestamp,
1923
+ message: firstMessage,
1924
+ });
1925
+ expect(second).toMatchObject({
1926
+ parentId: first.id,
1927
+ seq: 2,
1928
+ timestamp: secondTimestamp,
1929
+ message: secondMessage,
1930
+ });
1931
+ expect(await mainTip(session)).toBe(second.id);
1932
+ expect(
1933
+ (await (await mainBranch(session)).findEntries({ order: "oldestFirst" }, BACKGROUND_CONTEXT)).map(
1934
+ (entry) => entry.id,
1935
+ ),
1936
+ ).toEqual([first.id, second.id]);
1937
+ expect((await session.getStats(BACKGROUND_CONTEXT)).messageCount).toBe(2);
1938
+ await session.close(BACKGROUND_CONTEXT);
1939
+ });
1940
+
1941
+ describe("opening a legacy v3 message session", () => {
1942
+ const entryTimestamp = NOW + 1_234;
1943
+ const message = {
1944
+ role: "user",
1945
+ content: [{ type: "text", text: "hello" }],
1946
+ timestamp: NOW + 1_000,
1947
+ } satisfies AgentMessage;
1948
+ let session: Session<JsonlSessionMetadata>;
1949
+ let path: string;
1950
+ let content: string;
1951
+ let beforeMtime: number;
1952
+
1953
+ beforeEach(async () => {
1954
+ ({ path, content } = await writeLegacyV3Fixture([
1955
+ {
1956
+ type: "message",
1957
+ id: "message-1",
1958
+ parentId: null,
1959
+ timestamp: new Date(entryTimestamp).toISOString(),
1960
+ message,
1961
+ },
1962
+ ]));
1963
+ beforeMtime = getOrThrow(await fileSystem.fileInfo(path, BACKGROUND_CONTEXT)).mtimeMs;
1964
+ const [metadata] = await repo.list({ cwd: "/workspace" }, BACKGROUND_CONTEXT);
1965
+ if (metadata === undefined) throw new Error("Legacy fixture was not discovered");
1966
+ session = await repo.open(metadata, BACKGROUND_CONTEXT);
1967
+ });
1968
+
1969
+ afterEach(async () => {
1970
+ await session?.close(BACKGROUND_CONTEXT);
1971
+ });
1972
+
1973
+ async function importedEntry(): Promise<Entry> {
1974
+ const entries = await session.findEntries({ order: "asc" }, BACKGROUND_CONTEXT);
1975
+ expect(entries).toHaveLength(1);
1976
+ const [entry] = entries;
1977
+ if (entry === undefined) throw new Error("Legacy message was not imported");
1978
+ return entry;
1979
+ }
1980
+
1981
+ it("exposes the legacy message through the current entry API", async () => {
1982
+ expect(await importedEntry()).toMatchObject({
1983
+ type: "message",
1984
+ parentId: null,
1985
+ seq: 1,
1986
+ timestamp: entryTimestamp,
1987
+ message,
1988
+ });
1989
+ });
1990
+
1991
+ it("remints the entry id as a UUIDv7 with the legacy timestamp", async () => {
1992
+ const entry = await importedEntry();
1993
+
1994
+ expect(entry.id).toMatch(/^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/);
1995
+ expect(uuidTimestamp(entry.id)).toBe(entryTimestamp);
1996
+ });
1997
+
1998
+ it("initializes a data-only main Branch at the imported entry", async () => {
1999
+ const entry = await importedEntry();
2000
+
2001
+ expect(await mainTip(session)).toBe(entry.id);
2002
+ expect(await session.getValue(storedValues.laneState("main"), BACKGROUND_CONTEXT)).toBeUndefined();
2003
+ expect(await session.getValue(storedValues.laneConfig("main"), BACKGROUND_CONTEXT)).toBeUndefined();
2004
+ });
2005
+
2006
+ it("leaves the legacy source untouched after open and close", async () => {
2007
+ await session.close(BACKGROUND_CONTEXT);
2008
+
2009
+ expect(getOrThrow(await fileSystem.readTextFile(path, BACKGROUND_CONTEXT))).toBe(content);
2010
+ expect(getOrThrow(await fileSystem.fileInfo(path, BACKGROUND_CONTEXT)).mtimeMs).toBe(beforeMtime);
2011
+ });
2012
+ });
2013
+ });
packages/agent/test/harness/jsonl-v3-stream.test.ts ADDED
@@ -0,0 +1,161 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { beforeEach, describe, expect, it } from "vitest";
2
+ import { BACKGROUND_CONTEXT, type Context } from "../../src/harness/context.ts";
3
+ import { NodeExecutionEnv } from "../../src/harness/env/nodejs.ts";
4
+ import type { CommittedEntryWrite, CommittedValueSetWrite } from "../../src/harness/session/commit.ts";
5
+ import type { LegacyV3SessionHeader } from "../../src/harness/session/jsonl/codec.ts";
6
+ import { LegacyV3Source } from "../../src/harness/session/jsonl/legacy-v3.ts";
7
+ import { type FileError, getOrThrow, ok, type Result, type TextLineReader } from "../../src/harness/types.ts";
8
+ import { createTempDir } from "./session-test-utils.ts";
9
+
10
+ const NOW = 1_700_000_000_000;
11
+ const HEADER: LegacyV3SessionHeader = {
12
+ type: "session",
13
+ version: 3,
14
+ id: "legacy",
15
+ timestamp: new Date(NOW).toISOString(),
16
+ cwd: "/workspace",
17
+ };
18
+ type OutputWrite = CommittedEntryWrite | CommittedValueSetWrite;
19
+
20
+ function entry(type: string, id: string, parentId: string | null, fields: Record<string, unknown> = {}) {
21
+ return { type, id, parentId, timestamp: new Date(NOW).toISOString(), ...fields };
22
+ }
23
+
24
+ function message(id: string, parentId: string | null, content = id) {
25
+ return entry("message", id, parentId, { message: { role: "user", content, timestamp: NOW } });
26
+ }
27
+
28
+ async function collect(source: LegacyV3Source, selected?: (id: string) => boolean): Promise<OutputWrite[]> {
29
+ const writes: OutputWrite[] = [];
30
+ for await (const write of source.writes(BACKGROUND_CONTEXT, selected)) writes.push(write);
31
+ return writes;
32
+ }
33
+
34
+ class ObservedEnv extends NodeExecutionEnv {
35
+ lineReads = 0;
36
+ opens = 0;
37
+ closes = 0;
38
+
39
+ override async openTextLineReader(path: string, context: Context): Promise<Result<TextLineReader, FileError>> {
40
+ const opened = await super.openTextLineReader(path, context);
41
+ if (!opened.ok) return opened;
42
+ this.opens++;
43
+ return ok({
44
+ readLine: (readContext: Context) => {
45
+ this.lineReads++;
46
+ return opened.value.readLine(readContext);
47
+ },
48
+ close: async (closeContext: Context) => {
49
+ this.closes++;
50
+ await opened.value.close(closeContext);
51
+ },
52
+ });
53
+ }
54
+ }
55
+
56
+ describe("streaming legacy v3 normalization", () => {
57
+ let fileSystem: ObservedEnv;
58
+ let fixtureId = 0;
59
+
60
+ beforeEach(() => {
61
+ fileSystem = new ObservedEnv({ cwd: createTempDir() });
62
+ });
63
+
64
+ async function fixture(records: readonly unknown[], suffix = "") {
65
+ const path = `legacy-${fixtureId++}.jsonl`;
66
+ const content = `${[HEADER, ...records].map((record) => JSON.stringify(record)).join("\n")}\n${suffix}`;
67
+ getOrThrow(await fileSystem.writeFile(path, content, BACKGROUND_CONTEXT));
68
+ return {
69
+ path,
70
+ content,
71
+ reader: fileSystem,
72
+ read: () => LegacyV3Source.read(fileSystem, path, BACKGROUND_CONTEXT),
73
+ };
74
+ }
75
+
76
+ it("materializes a selected compaction with its branch-local tail", async () => {
77
+ const { read, reader } = await fixture([
78
+ message("before", null),
79
+ entry("session_info", "boundary", "before"),
80
+ message("kept", "boundary", "Unicode é漢字"),
81
+ message("other", "before", "not on this branch"),
82
+ entry("compaction", "selected", "kept", {
83
+ summary: "selected",
84
+ firstKeptEntryId: "boundary",
85
+ tokensBefore: 20,
86
+ fromHook: true,
87
+ details: { a: 2 },
88
+ }),
89
+ ]);
90
+ const source = await read();
91
+ const selectedId = [...source.entryStructures()].at(-1)!.id;
92
+ expect(await collect(source, () => false)).toEqual(source.values);
93
+ reader.lineReads = 0;
94
+ const writes = await collect(source, (id) => id === selectedId);
95
+ expect(writes).toHaveLength(2);
96
+ expect(writes[0]).toMatchObject({
97
+ type: "compaction",
98
+ id: selectedId,
99
+ seq: 4,
100
+ fromHook: true,
101
+ details: { a: 2 },
102
+ retainedTail: [{ role: "user", content: "Unicode é漢字", timestamp: NOW }],
103
+ });
104
+ expect(reader.lineReads).toBe(6); // Header plus each captured physical record, read once.
105
+ });
106
+
107
+ it("reuses an earlier cached message in selected compaction tails on different branches", async () => {
108
+ const { read, reader } = await fixture([
109
+ message("root", null),
110
+ message("left", "root"),
111
+ entry("compaction", "left-compaction", "left", {
112
+ summary: "left summary",
113
+ firstKeptEntryId: "root",
114
+ tokensBefore: 10,
115
+ }),
116
+ message("right", "root"),
117
+ entry("compaction", "right-compaction", "right", {
118
+ summary: "right summary",
119
+ firstKeptEntryId: "root",
120
+ tokensBefore: 20,
121
+ }),
122
+ ]);
123
+ const source = await read();
124
+ const structures = [...source.entryStructures()];
125
+ const selected = new Set([structures[2]!.id, structures[4]!.id]);
126
+ reader.lineReads = 0;
127
+ const writes = await collect(source, (id) => selected.has(id));
128
+ expect(writes).toHaveLength(3);
129
+ expect(writes[0]).toMatchObject({
130
+ type: "compaction",
131
+ summary: "left summary",
132
+ retainedTail: [
133
+ { role: "user", content: "root", timestamp: NOW },
134
+ { role: "user", content: "left", timestamp: NOW },
135
+ ],
136
+ });
137
+ expect(writes[1]).toMatchObject({
138
+ type: "compaction",
139
+ summary: "right summary",
140
+ retainedTail: [
141
+ { role: "user", content: "root", timestamp: NOW },
142
+ { role: "user", content: "right", timestamp: NOW },
143
+ ],
144
+ });
145
+ expect(reader.lineReads).toBe(6);
146
+ expect(await collect(source, (id) => selected.has(id))).toEqual(writes);
147
+ });
148
+
149
+ it("ignores a torn tail and emits only the captured complete records after later appends", async () => {
150
+ const { path, read, reader } = await fixture([message("a", null)], JSON.stringify(message("torn", "a")));
151
+ const source = await read();
152
+ getOrThrow(
153
+ await fileSystem.appendFile(path, `\n${JSON.stringify(message("later", "torn"))}\n`, BACKGROUND_CONTEXT),
154
+ );
155
+ reader.lineReads = 0;
156
+ const writes = await collect(source);
157
+ expect(writes).toHaveLength(2);
158
+ expect(reader.lineReads).toBe(2); // Header plus the single captured complete record.
159
+ expect(source.nextSeq).toBe(3);
160
+ });
161
+ });
packages/agent/test/harness/memory-conformance.test.ts ADDED
@@ -0,0 +1,101 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { describe, expect, it } from "vitest";
2
+ import { BACKGROUND_CONTEXT } from "../../src/harness/context.ts";
3
+ import * as sessionWrites from "../../src/harness/session/commit.ts";
4
+ import { MemorySessionRepo } from "../../src/harness/session/index.ts";
5
+ import { MemoryStorage } from "../../src/harness/session/memory.ts";
6
+ import {
7
+ type ConformanceCase,
8
+ createSessionRepoConformance,
9
+ createSessionRepoStreamingForkConformance,
10
+ createStorageConformance,
11
+ type StorageFixture,
12
+ } from "../../src/harness/session/testing/index.ts";
13
+ import * as storedValues from "../../src/harness/session/values.ts";
14
+
15
+ const NOW = 1_700_000_000_000;
16
+
17
+ function registerConformance(name: string, cases: readonly ConformanceCase[]): void {
18
+ describe(name, () => {
19
+ for (const group of new Set(cases.map((testCase) => testCase.group))) {
20
+ describe(group, () => {
21
+ for (const testCase of cases.filter((candidate) => candidate.group === group)) {
22
+ it(testCase.name, () => testCase.run());
23
+ }
24
+ });
25
+ }
26
+ });
27
+ }
28
+
29
+ registerConformance(
30
+ "MemoryStorage conformance",
31
+ createStorageConformance(() => {
32
+ const storage = new MemoryStorage({ now: () => NOW });
33
+ return Promise.resolve<StorageFixture>({
34
+ storage,
35
+ [Symbol.asyncDispose]: () => storage.close(BACKGROUND_CONTEXT),
36
+ });
37
+ }),
38
+ );
39
+
40
+ describe("MemoryStorage commit statistics", () => {
41
+ it("includes historical totals in the first commit after session reopen", async () => {
42
+ const repo = new MemorySessionRepo({ now: () => NOW });
43
+ const session = await repo.create({}, BACKGROUND_CONTEXT);
44
+ const usage = {
45
+ input: 1,
46
+ output: 2,
47
+ cacheRead: 0,
48
+ cacheWrite: 0,
49
+ totalTokens: 3,
50
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
51
+ };
52
+ try {
53
+ await session.mutate(
54
+ (mutator) =>
55
+ mutator.commit(
56
+ [
57
+ sessionWrites.insertEntry({
58
+ id: "history",
59
+ parentId: null,
60
+ type: "message",
61
+ message: { role: "user", content: "history", timestamp: NOW },
62
+ }),
63
+ sessionWrites.insertUsage({ id: "usage", usage, adjustment: false }),
64
+ ],
65
+ BACKGROUND_CONTEXT,
66
+ ),
67
+ BACKGROUND_CONTEXT,
68
+ );
69
+ await session.close(BACKGROUND_CONTEXT);
70
+ const reopened = await repo.open(session.metadata, BACKGROUND_CONTEXT);
71
+ const result = await reopened.mutate(
72
+ (mutator) =>
73
+ mutator.commit([storedValues.setValue(storedValues.sessionName, "reopened")], BACKGROUND_CONTEXT),
74
+ BACKGROUND_CONTEXT,
75
+ );
76
+ expect(result.stats).toEqual({ messageCount: 1, usage });
77
+ expect(result.stats).toEqual(await reopened.getStats(BACKGROUND_CONTEXT));
78
+ await reopened.close(BACKGROUND_CONTEXT);
79
+ } finally {
80
+ await repo.close(BACKGROUND_CONTEXT);
81
+ }
82
+ });
83
+ });
84
+
85
+ let memoryRepo: MemorySessionRepo;
86
+ registerConformance("MemorySessionRepo conformance", [
87
+ ...createSessionRepoConformance(
88
+ () => {
89
+ memoryRepo = new MemorySessionRepo({ now: () => NOW });
90
+ return Promise.resolve(memoryRepo);
91
+ },
92
+ () => memoryRepo.close(BACKGROUND_CONTEXT),
93
+ ),
94
+ ...createSessionRepoStreamingForkConformance(
95
+ () => {
96
+ memoryRepo = new MemorySessionRepo({ now: () => NOW });
97
+ return Promise.resolve(memoryRepo);
98
+ },
99
+ () => memoryRepo.close(BACKGROUND_CONTEXT),
100
+ ),
101
+ ]);
packages/agent/test/harness/memory-session-repo.test.ts ADDED
@@ -0,0 +1,77 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { describe, expect, it } from "vitest";
2
+ import { BACKGROUND_CONTEXT } from "../../src/harness/context.ts";
3
+ import { MemorySessionRepo } from "../../src/harness/session/index.ts";
4
+
5
+ const NOW = 1_700_000_000_000;
6
+ function uuidTimestamp(id: string): number {
7
+ return Number.parseInt(id.replaceAll("-", "").slice(0, 12), 16);
8
+ }
9
+
10
+ describe("MemorySessionRepo metadata", () => {
11
+ it("uses its injected clock for generated session identity and metadata", async () => {
12
+ const repo = new MemorySessionRepo({ now: () => NOW });
13
+ const session = await repo.create({}, BACKGROUND_CONTEXT);
14
+
15
+ expect(session.metadata.createdAt).toBe(NOW);
16
+ expect(uuidTimestamp(session.metadata.id)).toBe(NOW);
17
+ await Promise.all([session.close(BACKGROUND_CONTEXT), repo.close(BACKGROUND_CONTEXT)]);
18
+ });
19
+
20
+ it("returns a fresh facade after close while retaining one session and storage", async () => {
21
+ const repo = new MemorySessionRepo({ now: () => NOW });
22
+ const first = await repo.create({ id: "session" }, BACKGROUND_CONTEXT);
23
+ const firstBranch = await first.createBranch("main", null, BACKGROUND_CONTEXT);
24
+ const admittedWrite = first.setName("preserved", BACKGROUND_CONTEXT);
25
+
26
+ await expect(repo.open(first.metadata, BACKGROUND_CONTEXT)).rejects.toThrow("already open");
27
+ await Promise.all([admittedWrite, first.close(BACKGROUND_CONTEXT)]);
28
+ await expect(first.getName(BACKGROUND_CONTEXT)).rejects.toThrow("Session is closed");
29
+ await expect(first.scanBranch({ start: "entry" }, BACKGROUND_CONTEXT)).rejects.toThrow("Session is closed");
30
+ await expect(firstBranch.getTipId(BACKGROUND_CONTEXT)).rejects.toThrow("Session is closed");
31
+
32
+ const second = await repo.open(first.metadata, BACKGROUND_CONTEXT);
33
+ expect(second).not.toBe(first);
34
+ expect(await second.getName(BACKGROUND_CONTEXT)).toBe("preserved");
35
+ await second.close(BACKGROUND_CONTEXT);
36
+ await repo.close(BACKGROUND_CONTEXT);
37
+ });
38
+
39
+ it("waits for an explicit mutation before closing its facade", async () => {
40
+ const repo = new MemorySessionRepo({ now: () => NOW });
41
+ const session = await repo.create({ id: "session" }, BACKGROUND_CONTEXT);
42
+ const mutation = await session.beginMutation(BACKGROUND_CONTEXT);
43
+ let closed = false;
44
+ const closing = session.close(BACKGROUND_CONTEXT).then(() => {
45
+ closed = true;
46
+ });
47
+
48
+ await Promise.resolve();
49
+ expect(closed).toBe(false);
50
+ await mutation.end(BACKGROUND_CONTEXT);
51
+ await closing;
52
+ expect(closed).toBe(true);
53
+
54
+ const reopened = await repo.open(session.metadata, BACKGROUND_CONTEXT);
55
+ await Promise.all([reopened.close(BACKGROUND_CONTEXT), repo.close(BACKGROUND_CONTEXT)]);
56
+ });
57
+
58
+ it("rejects an explicit scope that had not acquired before facade close", async () => {
59
+ const repo = new MemorySessionRepo({ now: () => NOW });
60
+ const session = await repo.create({ id: "session" }, BACKGROUND_CONTEXT);
61
+ const first = await session.beginMutation(BACKGROUND_CONTEXT);
62
+ const secondPromise = session.beginMutation(BACKGROUND_CONTEXT);
63
+ void secondPromise.catch(() => {});
64
+ let closed = false;
65
+ const closing = session.close(BACKGROUND_CONTEXT).then(() => {
66
+ closed = true;
67
+ });
68
+
69
+ await first.end(BACKGROUND_CONTEXT);
70
+ await expect(secondPromise).rejects.toThrow("Session is closed");
71
+ await closing;
72
+ expect(closed).toBe(true);
73
+
74
+ const reopened = await repo.open(session.metadata, BACKGROUND_CONTEXT);
75
+ await Promise.all([reopened.close(BACKGROUND_CONTEXT), repo.close(BACKGROUND_CONTEXT)]);
76
+ });
77
+ });
packages/agent/test/harness/memory-storage.test.ts ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { describe, expect, it } from "vitest";
2
+ import { BACKGROUND_CONTEXT } from "../../src/harness/context.ts";
3
+ import * as sessionWrites from "../../src/harness/session/commit.ts";
4
+ import { MemoryStorage } from "../../src/harness/session/memory.ts";
5
+ import * as storedValues from "../../src/harness/session/values.ts";
6
+
7
+ const NOW = 1_700_000_000_000;
8
+
9
+ describe("MemoryStorage", () => {
10
+ it("uses the injected clock once per transaction", async () => {
11
+ let timestamp = NOW;
12
+ const storage = new MemoryStorage({ now: () => timestamp++ });
13
+
14
+ const first = await storage.commit(
15
+ [
16
+ sessionWrites.insertEntry({
17
+ id: "first",
18
+ parentId: null,
19
+ type: "custom",
20
+ customType: "note",
21
+ }),
22
+ storedValues.setValue(storedValues.sessionName, "first"),
23
+ ],
24
+ BACKGROUND_CONTEXT,
25
+ );
26
+ const second = await storage.commit(
27
+ [storedValues.setValue(storedValues.sessionName, "second")],
28
+ BACKGROUND_CONTEXT,
29
+ );
30
+
31
+ expect(first.timestamp).toBe(NOW);
32
+ expect(second.timestamp).toBe(NOW + 1);
33
+ expect((await storage.getEntries(["first"], BACKGROUND_CONTEXT)).get("first")?.timestamp).toBe(first.timestamp);
34
+ await storage.close(BACKGROUND_CONTEXT);
35
+ });
36
+ });
packages/agent/test/harness/mutation-line.test.ts ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { describe, expect, it } from "vitest";
2
+ import { MutationLine } from "../../src/harness/session/mutation-line.ts";
3
+
4
+ function deferred(): { promise: Promise<void>; resolve(): void } {
5
+ let resolvePromise!: () => void;
6
+ const promise = new Promise<void>((resolve) => {
7
+ resolvePromise = resolve;
8
+ });
9
+ return { promise, resolve: resolvePromise };
10
+ }
11
+
12
+ describe("MutationLine", () => {
13
+ it("serializes every Session mutation", async () => {
14
+ const line = new MutationLine();
15
+ const gate = deferred();
16
+ const order: string[] = [];
17
+ const first = line.run(async () => {
18
+ order.push("first:start");
19
+ await gate.promise;
20
+ order.push("first:end");
21
+ return "first";
22
+ });
23
+ const second = line.run(() => {
24
+ order.push("second");
25
+ return "second";
26
+ });
27
+
28
+ await Promise.resolve();
29
+ expect(order).toEqual(["first:start"]);
30
+ gate.resolve();
31
+ await expect(first).resolves.toBe("first");
32
+ await expect(second).resolves.toBe("second");
33
+ expect(order).toEqual(["first:start", "first:end", "second"]);
34
+ });
35
+
36
+ it("continues after a failed job while preserving the original failure", async () => {
37
+ const line = new MutationLine();
38
+ const rejection = new Error("mutation failed");
39
+
40
+ await expect(
41
+ line.run(() => {
42
+ throw rejection;
43
+ }),
44
+ ).rejects.toBe(rejection);
45
+ await expect(line.run(() => "next")).resolves.toBe("next");
46
+ });
47
+
48
+ it("seals queued and future jobs while draining the running job", async () => {
49
+ const line = new MutationLine();
50
+ const gate = deferred();
51
+ const running = line.run(async () => {
52
+ await gate.promise;
53
+ return "running";
54
+ });
55
+ await Promise.resolve();
56
+ const queued = line.run(() => "queued");
57
+ const closed = new Error("closed");
58
+
59
+ const drained = line.seal(closed);
60
+ await expect(line.run(() => "late")).rejects.toBe(closed);
61
+ gate.resolve();
62
+ await expect(running).resolves.toBe("running");
63
+ await expect(queued).rejects.toBe(closed);
64
+ await drained;
65
+ });
66
+ });
packages/agent/test/harness/nodejs-env.test.ts ADDED
@@ -0,0 +1,706 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { execFileSync } from "node:child_process";
2
+ import { existsSync, readFileSync } from "node:fs";
3
+ import { access, chmod, realpath, symlink } from "node:fs/promises";
4
+ import { homedir } from "node:os";
5
+ import { delimiter, join } from "node:path";
6
+ import { pathToFileURL } from "node:url";
7
+ import { afterEach, describe, expect, it } from "vitest";
8
+ import { BACKGROUND_CONTEXT, withAbortSignal } from "../../src/harness/context.ts";
9
+ import { NodeExecutionEnv } from "../../src/harness/env/nodejs.ts";
10
+ import { FileError, getOrThrow, type ShellExecOptions, type ShellOutputView } from "../../src/harness/types.ts";
11
+ import { applyShellOutputUpdate } from "../../src/harness/utils/output-capture.ts";
12
+ import { executeShellWithCapture } from "../../src/harness/utils/shell-output.ts";
13
+ import { createTempDir } from "./session-test-utils.ts";
14
+
15
+ const chmodRestorePaths: string[] = [];
16
+
17
+ function withTimeout<T>(promise: Promise<T>, ms: number, onTimeout?: () => void): Promise<T> {
18
+ return new Promise<T>((resolve, reject) => {
19
+ const timeoutId = setTimeout(() => {
20
+ onTimeout?.();
21
+ reject(new Error(`Timed out after ${ms}ms`));
22
+ }, ms);
23
+ promise.then(
24
+ (value) => {
25
+ clearTimeout(timeoutId);
26
+ resolve(value);
27
+ },
28
+ (error: unknown) => {
29
+ clearTimeout(timeoutId);
30
+ reject(error);
31
+ },
32
+ );
33
+ });
34
+ }
35
+
36
+ async function collectShellOutput(
37
+ env: NodeExecutionEnv,
38
+ command: string,
39
+ options: ShellExecOptions | undefined,
40
+ context: Parameters<NodeExecutionEnv["exec"]>[2],
41
+ ): Promise<{ result: Awaited<ReturnType<NodeExecutionEnv["exec"]>>; output: ShellOutputView | undefined }> {
42
+ let output: ShellOutputView | undefined;
43
+ const result = await env.exec(
44
+ command,
45
+ {
46
+ ...options,
47
+ onUpdate: (update) => {
48
+ output = applyShellOutputUpdate(output, update);
49
+ },
50
+ },
51
+ context,
52
+ );
53
+ return { result, output };
54
+ }
55
+
56
+ function toBashSingleQuotedArg(value: string): string {
57
+ return `'${value.replace(/\\/g, "/").replace(/'/g, `'"'"'`)}'`;
58
+ }
59
+
60
+ function createInheritedStdioCommand(pidFile: string): string {
61
+ return (
62
+ 'node -e "' +
63
+ "const fs=require('fs');" +
64
+ "const {spawn}=require('child_process');" +
65
+ "const child=spawn(process.execPath,['-e','setTimeout(()=>{},60000)'],{stdio:'inherit',detached:true});" +
66
+ "fs.writeFileSync(process.argv[1], String(child.pid));" +
67
+ "child.unref();" +
68
+ "console.log('child-exiting');" +
69
+ '" ' +
70
+ toBashSingleQuotedArg(pidFile)
71
+ );
72
+ }
73
+
74
+ function cleanupDetachedChild(pidFile: string): void {
75
+ if (!existsSync(pidFile)) return;
76
+ const pid = Number.parseInt(readFileSync(pidFile, "utf8").trim(), 10);
77
+ if (!Number.isFinite(pid) || pid <= 0) return;
78
+ try {
79
+ execFileSync("taskkill", ["/F", "/T", "/PID", String(pid)], { stdio: "ignore" });
80
+ } catch {}
81
+ }
82
+
83
+ class FailingSpillExecutionEnv extends NodeExecutionEnv {
84
+ override async createTempFile(
85
+ options: Parameters<NodeExecutionEnv["createTempFile"]>[0],
86
+ context: Parameters<NodeExecutionEnv["createTempFile"]>[1],
87
+ ) {
88
+ if (options?.prefix === "pi-output-") {
89
+ return { ok: true as const, value: join(this.cwd, "missing", "spill.log") };
90
+ }
91
+ return super.createTempFile(options, context);
92
+ }
93
+ }
94
+
95
+ afterEach(async () => {
96
+ for (const path of chmodRestorePaths.splice(0)) {
97
+ try {
98
+ await access(path);
99
+ await chmod(path, 0o700);
100
+ } catch {}
101
+ }
102
+ });
103
+
104
+ describe("NodeExecutionEnv", () => {
105
+ it("reads, writes, lists, and removes files and directories", async () => {
106
+ const root = createTempDir();
107
+ const env = new NodeExecutionEnv({ cwd: root });
108
+ expect(getOrThrow(await env.absolutePath("nested/child", BACKGROUND_CONTEXT))).toBe(join(root, "nested/child"));
109
+ expect(getOrThrow(await env.joinPath([root, "nested", "child"], BACKGROUND_CONTEXT))).toBe(
110
+ join(root, "nested", "child"),
111
+ );
112
+ getOrThrow(await env.createDir("nested/child", undefined, BACKGROUND_CONTEXT));
113
+ getOrThrow(await env.writeFile("nested/child/file.txt", "hel", BACKGROUND_CONTEXT));
114
+ getOrThrow(await env.appendFile("nested/child/file.txt", "lo", BACKGROUND_CONTEXT));
115
+ expect(getOrThrow(await env.readTextFile("nested/child/file.txt", BACKGROUND_CONTEXT))).toBe("hello");
116
+ expect(getOrThrow(await env.readTextLines("nested/child/file.txt", { maxLines: 1 }, BACKGROUND_CONTEXT))).toEqual(
117
+ ["hello"],
118
+ );
119
+ expect(
120
+ Buffer.from(getOrThrow(await env.readBinaryFile("nested/child/file.txt", BACKGROUND_CONTEXT))).toString(
121
+ "utf8",
122
+ ),
123
+ ).toBe("hello");
124
+
125
+ const entries = getOrThrow(await env.listDir("nested/child", BACKGROUND_CONTEXT));
126
+ expect(entries).toHaveLength(1);
127
+ expect(entries[0]).toMatchObject({
128
+ name: "file.txt",
129
+ path: join(root, "nested/child/file.txt"),
130
+ kind: "file",
131
+ size: 5,
132
+ });
133
+ expect(typeof entries[0]!.mtimeMs).toBe("number");
134
+
135
+ expect(getOrThrow(await env.exists("nested/child/file.txt", BACKGROUND_CONTEXT))).toBe(true);
136
+ getOrThrow(await env.remove("nested/child/file.txt", undefined, BACKGROUND_CONTEXT));
137
+ expect(getOrThrow(await env.exists("nested/child/file.txt", BACKGROUND_CONTEXT))).toBe(false);
138
+ });
139
+
140
+ it("expands home-relative paths and file URLs", async () => {
141
+ const root = createTempDir();
142
+ const env = new NodeExecutionEnv({ cwd: root });
143
+ expect(getOrThrow(await env.absolutePath("~/pi-node-env-test", BACKGROUND_CONTEXT))).toBe(
144
+ join(homedir(), "pi-node-env-test"),
145
+ );
146
+ const filePath = join(root, "file with spaces.txt");
147
+ expect(getOrThrow(await env.absolutePath(pathToFileURL(filePath).href, BACKGROUND_CONTEXT))).toBe(filePath);
148
+ });
149
+
150
+ it("returns fileInfo for files, directories, and symlinks without following symlinks", async () => {
151
+ const root = createTempDir();
152
+ const env = new NodeExecutionEnv({ cwd: root });
153
+ getOrThrow(await env.createDir("dir", { recursive: true }, BACKGROUND_CONTEXT));
154
+ getOrThrow(await env.writeFile("dir/file.txt", "hello", BACKGROUND_CONTEXT));
155
+ await symlink(join(root, "dir/file.txt"), join(root, "file-link"));
156
+ await symlink(join(root, "dir"), join(root, "dir-link"));
157
+
158
+ expect(getOrThrow(await env.fileInfo("dir", BACKGROUND_CONTEXT))).toMatchObject({
159
+ name: "dir",
160
+ path: join(root, "dir"),
161
+ kind: "directory",
162
+ });
163
+ expect(getOrThrow(await env.fileInfo("dir/file.txt", BACKGROUND_CONTEXT))).toMatchObject({
164
+ name: "file.txt",
165
+ path: join(root, "dir/file.txt"),
166
+ kind: "file",
167
+ size: 5,
168
+ });
169
+ expect(getOrThrow(await env.fileInfo("file-link", BACKGROUND_CONTEXT))).toMatchObject({
170
+ name: "file-link",
171
+ path: join(root, "file-link"),
172
+ kind: "symlink",
173
+ });
174
+ expect(getOrThrow(await env.fileInfo("dir-link", BACKGROUND_CONTEXT))).toMatchObject({
175
+ name: "dir-link",
176
+ path: join(root, "dir-link"),
177
+ kind: "symlink",
178
+ });
179
+ expect(getOrThrow(await env.canonicalPath("file-link", BACKGROUND_CONTEXT))).toBe(
180
+ await realpath(join(root, "dir/file.txt")),
181
+ );
182
+ });
183
+
184
+ it("lists symlinks as symlinks", async () => {
185
+ const root = createTempDir();
186
+ const env = new NodeExecutionEnv({ cwd: root });
187
+ getOrThrow(await env.writeFile("target.txt", "hello", BACKGROUND_CONTEXT));
188
+ await symlink(join(root, "target.txt"), join(root, "link.txt"));
189
+
190
+ const entries = getOrThrow(await env.listDir(".", BACKGROUND_CONTEXT));
191
+ expect(
192
+ entries.map((entry) => ({ name: entry.name, kind: entry.kind })).sort((a, b) => a.name.localeCompare(b.name)),
193
+ ).toEqual([
194
+ { name: "link.txt", kind: "symlink" },
195
+ { name: "target.txt", kind: "file" },
196
+ ]);
197
+ });
198
+
199
+ it("stops reading text lines at the requested limit", async () => {
200
+ const root = createTempDir();
201
+ const env = new NodeExecutionEnv({ cwd: root });
202
+ getOrThrow(await env.writeFile("file.txt", "one\ntwo\nthree", BACKGROUND_CONTEXT));
203
+ expect(getOrThrow(await env.readTextLines("file.txt", { maxLines: 1 }, BACKGROUND_CONTEXT))).toEqual(["one"]);
204
+ });
205
+
206
+ it("returns FileError for missing paths and keeps exists false for missing paths", async () => {
207
+ const root = createTempDir();
208
+ const env = new NodeExecutionEnv({ cwd: root });
209
+ const info = await env.fileInfo("missing.txt", BACKGROUND_CONTEXT);
210
+ expect(info.ok).toBe(false);
211
+ if (!info.ok) {
212
+ expect(info.error).toBeInstanceOf(FileError);
213
+ expect(info.error).toMatchObject({
214
+ name: "FileError",
215
+ code: "not_found",
216
+ path: join(root, "missing.txt"),
217
+ });
218
+ }
219
+ expect(getOrThrow(await env.exists("missing.txt", BACKGROUND_CONTEXT))).toBe(false);
220
+ });
221
+
222
+ it("returns FileError for listing non-directories", async () => {
223
+ const root = createTempDir();
224
+ const env = new NodeExecutionEnv({ cwd: root });
225
+ getOrThrow(await env.writeFile("file.txt", "hello", BACKGROUND_CONTEXT));
226
+ const result = await env.listDir("file.txt", BACKGROUND_CONTEXT);
227
+ expect(result.ok).toBe(false);
228
+ if (!result.ok) {
229
+ expect(result.error).toBeInstanceOf(FileError);
230
+ expect(result.error).toMatchObject({ code: "not_directory" });
231
+ }
232
+ });
233
+
234
+ it("appends to new files and creates parent directories", async () => {
235
+ const root = createTempDir();
236
+ const env = new NodeExecutionEnv({ cwd: root });
237
+ getOrThrow(await env.appendFile("new/nested/file.txt", "a", BACKGROUND_CONTEXT));
238
+ getOrThrow(await env.appendFile("new/nested/file.txt", "b", BACKGROUND_CONTEXT));
239
+ expect(getOrThrow(await env.readTextFile("new/nested/file.txt", BACKGROUND_CONTEXT))).toBe("ab");
240
+ });
241
+
242
+ it("atomically renames a file and replaces the destination", async () => {
243
+ const root = createTempDir();
244
+ const env = new NodeExecutionEnv({ cwd: root });
245
+ getOrThrow(await env.writeFile("source.txt", "new", BACKGROUND_CONTEXT));
246
+ getOrThrow(await env.writeFile("destination.txt", "old", BACKGROUND_CONTEXT));
247
+
248
+ getOrThrow(await env.renameFile("source.txt", "destination.txt", BACKGROUND_CONTEXT));
249
+
250
+ expect(getOrThrow(await env.exists("source.txt", BACKGROUND_CONTEXT))).toBe(false);
251
+ expect(getOrThrow(await env.readTextFile("destination.txt", BACKGROUND_CONTEXT))).toBe("new");
252
+ });
253
+
254
+ it("reports the source path when rename fails because the source is missing", async () => {
255
+ const root = createTempDir();
256
+ const env = new NodeExecutionEnv({ cwd: root });
257
+ getOrThrow(await env.writeFile("destination.txt", "unchanged", BACKGROUND_CONTEXT));
258
+
259
+ const result = await env.renameFile("missing-source.txt", "destination.txt", BACKGROUND_CONTEXT);
260
+
261
+ expect(result).toMatchObject({
262
+ ok: false,
263
+ error: {
264
+ code: "not_found",
265
+ path: join(root, "missing-source.txt"),
266
+ },
267
+ });
268
+ expect(getOrThrow(await env.readTextFile("destination.txt", BACKGROUND_CONTEXT))).toBe("unchanged");
269
+ });
270
+
271
+ it("creates temporary directories and files", async () => {
272
+ const root = createTempDir();
273
+ const env = new NodeExecutionEnv({ cwd: root });
274
+ const tempDir = getOrThrow(await env.createTempDir("node-env-test-", BACKGROUND_CONTEXT));
275
+ await expect(access(tempDir)).resolves.toBeUndefined();
276
+ const tempFile = getOrThrow(await env.createTempFile({ prefix: "prefix-", suffix: ".txt" }, BACKGROUND_CONTEXT));
277
+ await expect(access(tempFile)).resolves.toBeUndefined();
278
+ expect(tempFile.endsWith(".txt")).toBe(true);
279
+ });
280
+
281
+ it("honors createDir recursive false and remove recursive/force options", async () => {
282
+ const root = createTempDir();
283
+ const env = new NodeExecutionEnv({ cwd: root });
284
+ const createResult = await env.createDir("missing/child", { recursive: false }, BACKGROUND_CONTEXT);
285
+ expect(createResult.ok).toBe(false);
286
+ if (!createResult.ok) expect(createResult.error).toMatchObject({ code: "not_found" });
287
+
288
+ getOrThrow(await env.writeFile("dir/child/file.txt", "hello", BACKGROUND_CONTEXT));
289
+ const removeDirectory = await env.remove("dir", { recursive: false }, BACKGROUND_CONTEXT);
290
+ expect(removeDirectory.ok).toBe(false);
291
+ getOrThrow(await env.remove("dir", { recursive: true }, BACKGROUND_CONTEXT));
292
+ expect(getOrThrow(await env.exists("dir", BACKGROUND_CONTEXT))).toBe(false);
293
+
294
+ const removeMissing = await env.remove("missing", { force: false }, BACKGROUND_CONTEXT);
295
+ expect(removeMissing.ok).toBe(false);
296
+ getOrThrow(await env.remove("missing", { force: true }, BACKGROUND_CONTEXT));
297
+ });
298
+
299
+ it("returns aborted results for pre-aborted cancellable file operations", async () => {
300
+ const root = createTempDir();
301
+ const env = new NodeExecutionEnv({ cwd: root });
302
+ getOrThrow(await env.writeFile("file.txt", "hello", BACKGROUND_CONTEXT));
303
+ const controller = new AbortController();
304
+ controller.abort();
305
+ const context = withAbortSignal(controller.signal, BACKGROUND_CONTEXT);
306
+
307
+ const results = await Promise.all([
308
+ env.readTextFile("file.txt", context),
309
+ env.readTextLines("file.txt", undefined, context),
310
+ env.readBinaryFile("file.txt", context),
311
+ env.writeFile("other.txt", "hello", context),
312
+ env.renameFile("file.txt", "renamed.txt", context),
313
+ env.listDir(".", context),
314
+ ]);
315
+ for (const result of results) {
316
+ expect(result.ok).toBe(false);
317
+ if (!result.ok) expect(result.error).toMatchObject({ code: "aborted" });
318
+ }
319
+ });
320
+
321
+ it("cleanup is best-effort", async () => {
322
+ const root = createTempDir();
323
+ const env = new NodeExecutionEnv({ cwd: root });
324
+ await expect(env.cleanup(BACKGROUND_CONTEXT)).resolves.toBeUndefined();
325
+ });
326
+
327
+ it("executes commands in cwd with env overrides", async () => {
328
+ const root = createTempDir();
329
+ const env = new NodeExecutionEnv({ cwd: root });
330
+ const collected = await collectShellOutput(
331
+ env,
332
+ 'printf \'%s:%s\' "$PWD" "$NODE_ENV_TEST"',
333
+ { env: { NODE_ENV_TEST: "ok" } },
334
+ BACKGROUND_CONTEXT,
335
+ );
336
+ const result = getOrThrow(collected.result);
337
+ expect(collected.output?.text).toBe(`${await realpath(root)}:ok`);
338
+ expect(result.exitCode).toBe(0);
339
+ });
340
+
341
+ it.each([
342
+ ["a missing override preserves the base value", undefined, "x:/stale/parent.jsonl"],
343
+ ["an empty override shadows the base value", { PI_SESSION_FILE: "" }, "x:"],
344
+ [
345
+ "a string override replaces the base value",
346
+ { PI_SESSION_FILE: "/sessions/current.jsonl" },
347
+ "x:/sessions/current.jsonl",
348
+ ],
349
+ ] as const)(
350
+ "applies string shell environment overrides when %s",
351
+ async (_description, overrides, expectedSessionFile) => {
352
+ const root = createTempDir();
353
+ const env = new NodeExecutionEnv({
354
+ cwd: root,
355
+ shellEnv: {
356
+ PI_SESSION_FILE: "/stale/parent.jsonl",
357
+ PI_CODING_AGENT: "true",
358
+ PI_NODE_ENV_PRESERVED_TEST: "preserved",
359
+ },
360
+ });
361
+ const collected = await collectShellOutput(
362
+ env,
363
+ `printf '%s:%s|%s|%s' "\${PI_SESSION_FILE+x}" "\${PI_SESSION_FILE-}" "$PI_CODING_AGENT" "$PI_NODE_ENV_PRESERVED_TEST"`,
364
+ { env: overrides },
365
+ BACKGROUND_CONTEXT,
366
+ );
367
+ getOrThrow(collected.result);
368
+ expect(collected.output?.text).toBe(`${expectedSessionFile}|true|preserved`);
369
+ },
370
+ );
371
+
372
+ it("can replace rather than inherit the default shell environment", async () => {
373
+ const root = createTempDir();
374
+ const inheritedKey = "PI_NODE_ENV_INHERITED_TEST";
375
+ const configuredKey = "PI_NODE_ENV_CONFIGURED_TEST";
376
+ const explicitKey = "PI_NODE_ENV_EXPLICIT_TEST";
377
+ const previousInherited = process.env[inheritedKey];
378
+ process.env[inheritedKey] = "host";
379
+ try {
380
+ const env = new NodeExecutionEnv({ cwd: root, shellEnv: { [configuredKey]: "configured" } });
381
+ const collected = await collectShellOutput(
382
+ env,
383
+ `printf '%s:%s:%s' "\${${inheritedKey}-}" "\${${configuredKey}-}" "\${${explicitKey}-}"`,
384
+ { inheritEnv: false, env: { [explicitKey]: "explicit" } },
385
+ BACKGROUND_CONTEXT,
386
+ );
387
+ getOrThrow(collected.result);
388
+ expect(collected.output?.text).toBe("::explicit");
389
+ } finally {
390
+ if (previousInherited === undefined) delete process.env[inheritedKey];
391
+ else process.env[inheritedKey] = previousInherited;
392
+ }
393
+ });
394
+
395
+ it("uses stdin command transport for legacy WSL bash paths", async () => {
396
+ if (process.platform === "win32") return;
397
+ const root = createTempDir();
398
+ const shellPath = "C:\\Windows\\System32\\bash.exe";
399
+ const env = new NodeExecutionEnv({ cwd: root });
400
+ getOrThrow(
401
+ await env.writeFile(
402
+ shellPath,
403
+ '#!/bin/sh\nprintf \'args:%s\\n\' "$*" >&2\nexec /bin/bash "$@"\n',
404
+ BACKGROUND_CONTEXT,
405
+ ),
406
+ );
407
+ await chmod(join(root, shellPath), 0o755);
408
+
409
+ const originalCwd = process.cwd();
410
+ const originalPath = process.env.PATH;
411
+ const platformDescriptor = Object.getOwnPropertyDescriptor(process, "platform");
412
+ try {
413
+ process.chdir(root);
414
+ process.env.PATH = `${root}${delimiter}${originalPath ?? ""}`;
415
+ Object.defineProperty(process, "platform", {
416
+ configurable: true,
417
+ value: "win32",
418
+ });
419
+
420
+ const wslEnv = new NodeExecutionEnv({ cwd: root, shellPath });
421
+ const nameExpansion = "$" + "{name}";
422
+ const collected = await collectShellOutput(
423
+ wslEnv,
424
+ `name='World'; echo "Hello, ${nameExpansion}!"`,
425
+ undefined,
426
+ BACKGROUND_CONTEXT,
427
+ );
428
+ const result = getOrThrow(collected.result);
429
+ expect(collected.output?.text).toContain("Hello, World!");
430
+ expect(collected.output?.text).toContain("args:-s");
431
+ expect(result.exitCode).toBe(0);
432
+ } finally {
433
+ process.chdir(originalCwd);
434
+ process.env.PATH = originalPath;
435
+ if (platformDescriptor) {
436
+ Object.defineProperty(process, "platform", platformDescriptor);
437
+ }
438
+ }
439
+ });
440
+
441
+ it.skipIf(process.platform !== "win32")(
442
+ "settles after the shell exits when a detached descendant retains inherited stdio",
443
+ async () => {
444
+ const root = createTempDir();
445
+ const pidFile = join(root, "grandchild.pid");
446
+ const env = new NodeExecutionEnv({ cwd: root });
447
+ const controller = new AbortController();
448
+ try {
449
+ const collected = await withTimeout(
450
+ collectShellOutput(
451
+ env,
452
+ createInheritedStdioCommand(pidFile),
453
+ undefined,
454
+ withAbortSignal(controller.signal, BACKGROUND_CONTEXT),
455
+ ),
456
+ 3000,
457
+ () => controller.abort(),
458
+ );
459
+ getOrThrow(collected.result);
460
+ expect(collected.output?.text).toContain("child-exiting");
461
+ } finally {
462
+ controller.abort();
463
+ cleanupDetachedChild(pidFile);
464
+ }
465
+ },
466
+ );
467
+
468
+ it("cleanup terminates active shell processes", async () => {
469
+ const root = createTempDir();
470
+ const env = new NodeExecutionEnv({ cwd: root });
471
+ const execution = env.exec("touch started; sleep 60", undefined, BACKGROUND_CONTEXT);
472
+ for (let attempt = 0; attempt < 100 && !getOrThrow(await env.exists("started", BACKGROUND_CONTEXT)); attempt++) {
473
+ await new Promise((resolve) => setTimeout(resolve, 10));
474
+ }
475
+ expect(getOrThrow(await env.exists("started", BACKGROUND_CONTEXT))).toBe(true);
476
+ await env.cleanup(BACKGROUND_CONTEXT);
477
+ await expect(withTimeout(execution, 3000)).resolves.toMatchObject({ ok: true });
478
+ });
479
+
480
+ it("combines stdout and stderr into one bounded view", async () => {
481
+ const root = createTempDir();
482
+ const env = new NodeExecutionEnv({ cwd: root });
483
+ const updates: string[] = [];
484
+ let output: ShellOutputView | undefined;
485
+ const result = getOrThrow(
486
+ await env.exec(
487
+ "printf out; printf err >&2",
488
+ {
489
+ onUpdate: (update) => {
490
+ updates.push(update.kind);
491
+ output = applyShellOutputUpdate(output, update);
492
+ },
493
+ },
494
+ BACKGROUND_CONTEXT,
495
+ ),
496
+ );
497
+ expect(result.exitCode).toBe(0);
498
+ expect(output?.text).toContain("out");
499
+ expect(output?.text).toContain("err");
500
+ expect(updates[0]).toBe("replace");
501
+ });
502
+
503
+ it("reports a missing working directory before spawning", async () => {
504
+ const root = createTempDir();
505
+ const env = new NodeExecutionEnv({ cwd: join(root, "missing") });
506
+ const result = await env.exec("printf ok", undefined, BACKGROUND_CONTEXT);
507
+
508
+ expect(result).toMatchObject({
509
+ ok: false,
510
+ error: { code: "spawn_error", message: expect.stringContaining("Working directory does not exist") },
511
+ });
512
+ });
513
+
514
+ it("returns non-zero command exit codes as successful execution results", async () => {
515
+ const root = createTempDir();
516
+ const env = new NodeExecutionEnv({ cwd: root });
517
+ const result = getOrThrow(await env.exec("exit 7", undefined, BACKGROUND_CONTEXT));
518
+ expect(result.exitCode).toBe(7);
519
+ expect(result.truncation.totalBytes).toBe(0);
520
+ });
521
+
522
+ // Regression test for https://github.com/earendil-works/pi/issues/8992
523
+ it.skipIf(process.platform === "win32")("maps signal-killed processes to a non-zero exit code", async () => {
524
+ const root = createTempDir();
525
+ const env = new NodeExecutionEnv({ cwd: root });
526
+ const result = getOrThrow(await env.exec("kill -9 $$", undefined, BACKGROUND_CONTEXT));
527
+ expect(result.exitCode).toBe(128 + 9);
528
+ });
529
+
530
+ it("returns timeout errors for commands exceeding the timeout", async () => {
531
+ const root = createTempDir();
532
+ const env = new NodeExecutionEnv({ cwd: root });
533
+ const result = await env.exec("sleep 5", { timeout: 0.01 }, BACKGROUND_CONTEXT);
534
+ expect(result.ok).toBe(false);
535
+ if (!result.ok) expect(result.error).toMatchObject({ code: "timeout" });
536
+ });
537
+
538
+ it("returns callback errors from exec stream handlers", async () => {
539
+ const root = createTempDir();
540
+ const env = new NodeExecutionEnv({ cwd: root });
541
+ const result = await env.exec(
542
+ "printf out",
543
+ {
544
+ onUpdate: () => {
545
+ throw new Error("callback failed");
546
+ },
547
+ },
548
+ BACKGROUND_CONTEXT,
549
+ );
550
+ expect(result.ok).toBe(false);
551
+ if (!result.ok) expect(result.error).toMatchObject({ code: "callback_error", message: "callback failed" });
552
+ });
553
+
554
+ it("returns shell unavailable and spawn errors", async () => {
555
+ const root = createTempDir();
556
+ const missingShellEnv = new NodeExecutionEnv({ cwd: root, shellPath: join(root, "missing-shell") });
557
+ const missingShell = await missingShellEnv.exec("printf ok", undefined, BACKGROUND_CONTEXT);
558
+ expect(missingShell.ok).toBe(false);
559
+ if (!missingShell.ok) expect(missingShell.error).toMatchObject({ code: "shell_unavailable" });
560
+
561
+ const shellPath = join(root, "not-executable-shell");
562
+ const env = new NodeExecutionEnv({ cwd: root });
563
+ getOrThrow(await env.writeFile(shellPath, "not executable", BACKGROUND_CONTEXT));
564
+ const spawnErrorEnv = new NodeExecutionEnv({ cwd: root, shellPath });
565
+ const spawnError = await spawnErrorEnv.exec("printf ok", undefined, BACKGROUND_CONTEXT);
566
+ expect(spawnError.ok).toBe(false);
567
+ if (!spawnError.ok) expect(spawnError.error).toMatchObject({ code: "spawn_error" });
568
+ });
569
+
570
+ it("returns an aborted result for aborted commands", async () => {
571
+ const root = createTempDir();
572
+ const env = new NodeExecutionEnv({ cwd: root });
573
+ const controller = new AbortController();
574
+ const promise = env.exec("sleep 5", undefined, withAbortSignal(controller.signal, BACKGROUND_CONTEXT));
575
+ controller.abort();
576
+ const result = await promise;
577
+ expect(result.ok).toBe(false);
578
+ if (!result.ok) expect(result.error).toMatchObject({ code: "aborted" });
579
+ });
580
+
581
+ it.skipIf(process.platform === "win32")("ignores asynchronous taskkill spawn errors during abort", async () => {
582
+ const root = createTempDir();
583
+ const pidFile = join(root, "shell.pid");
584
+ const controller = new AbortController();
585
+ const env = new NodeExecutionEnv({ cwd: root, shellPath: "/bin/bash" });
586
+ const platformDescriptor = Object.getOwnPropertyDescriptor(process, "platform");
587
+ const previousSystemRoot = process.env.SystemRoot;
588
+ process.env.SystemRoot = "/definitely/missing/windows";
589
+ Object.defineProperty(process, "platform", { configurable: true, value: "win32" });
590
+
591
+ let pid: number | undefined;
592
+ try {
593
+ const execution = env.exec(
594
+ `echo $$ > ${toBashSingleQuotedArg(pidFile)}; exec sleep 60`,
595
+ undefined,
596
+ withAbortSignal(controller.signal, BACKGROUND_CONTEXT),
597
+ );
598
+ for (let attempt = 0; attempt < 100 && !existsSync(pidFile); attempt++) {
599
+ await new Promise((resolve) => setTimeout(resolve, 10));
600
+ }
601
+ expect(existsSync(pidFile)).toBe(true);
602
+
603
+ controller.abort();
604
+ await new Promise((resolve) => setTimeout(resolve, 0));
605
+ pid = Number.parseInt(readFileSync(pidFile, "utf8"), 10);
606
+ process.kill(pid, "SIGKILL");
607
+
608
+ const result = await execution;
609
+ expect(result).toMatchObject({ ok: false, error: { code: "aborted" } });
610
+ } finally {
611
+ if (pid === undefined && existsSync(pidFile)) {
612
+ pid = Number.parseInt(readFileSync(pidFile, "utf8"), 10);
613
+ }
614
+ if (pid !== undefined && Number.isFinite(pid)) {
615
+ try {
616
+ process.kill(pid, "SIGKILL");
617
+ } catch {}
618
+ }
619
+ if (previousSystemRoot === undefined) delete process.env.SystemRoot;
620
+ else process.env.SystemRoot = previousSystemRoot;
621
+ if (platformDescriptor) Object.defineProperty(process, "platform", platformDescriptor);
622
+ }
623
+ });
624
+
625
+ it("does not create a spill before bounded output crosses its limits", async () => {
626
+ const root = createTempDir();
627
+ const env = new NodeExecutionEnv({ cwd: root });
628
+ const result = getOrThrow(
629
+ await env.exec(
630
+ "printf short",
631
+ {
632
+ capture: { limits: { maxBytes: 100, maxLines: 10, retain: "tail" }, spill: true },
633
+ onUpdate: () => {},
634
+ },
635
+ BACKGROUND_CONTEXT,
636
+ ),
637
+ );
638
+ expect(result.spillPath).toBeUndefined();
639
+ });
640
+
641
+ it("preserves exact raw bytes in the spill while decoding a bounded text view", async () => {
642
+ const root = createTempDir();
643
+ const env = new NodeExecutionEnv({ cwd: root });
644
+ const expected = [0x66, 0x80, 0x00, 0x6f];
645
+ const result = getOrThrow(
646
+ await env.exec(
647
+ `${JSON.stringify(process.execPath)} -e "process.stdout.write(Buffer.from([${expected.join(",")}]))"`,
648
+ {
649
+ capture: { limits: { maxBytes: 1, maxLines: 10, retain: "tail" }, spill: true },
650
+ onUpdate: () => {},
651
+ },
652
+ BACKGROUND_CONTEXT,
653
+ ),
654
+ );
655
+ expect(result.spillPath).toBeDefined();
656
+ expect([...getOrThrow(await env.readBinaryFile(result.spillPath!, BACKGROUND_CONTEXT))]).toEqual(expected);
657
+ });
658
+
659
+ it("fails rather than silently losing a requested spill", async () => {
660
+ const root = createTempDir();
661
+ const env = new FailingSpillExecutionEnv({ cwd: root });
662
+ const result = await env.exec(
663
+ "printf 12345678901234567890",
664
+ {
665
+ capture: { limits: { maxBytes: 10, maxLines: 10, retain: "tail" }, spill: true },
666
+ onUpdate: () => {},
667
+ },
668
+ BACKGROUND_CONTEXT,
669
+ );
670
+ expect(result).toMatchObject({
671
+ ok: false,
672
+ error: { code: "unknown", message: expect.stringContaining("Failed to preserve complete shell output") },
673
+ });
674
+ });
675
+
676
+ it("preserves complete output when spill-stream backpressure pauses a process that exits quickly", async () => {
677
+ const root = createTempDir();
678
+ const env = new NodeExecutionEnv({ cwd: root });
679
+ const size = 500_000;
680
+ const result = getOrThrow(
681
+ await env.exec(
682
+ `${JSON.stringify(process.execPath)} -e "process.stdout.write('x'.repeat(${size}))"`,
683
+ {
684
+ capture: { limits: { maxBytes: 10, maxLines: 10, retain: "tail" }, spill: true },
685
+ onUpdate: () => {},
686
+ },
687
+ BACKGROUND_CONTEXT,
688
+ ),
689
+ );
690
+ expect(result.spillPath).toBeDefined();
691
+ expect(getOrThrow(await env.readTextFile(result.spillPath!, BACKGROUND_CONTEXT))).toHaveLength(size);
692
+ });
693
+
694
+ it("captures large shell output to a full output file through the execution env", async () => {
695
+ const root = createTempDir();
696
+ const env = new NodeExecutionEnv({ cwd: root });
697
+ const result = getOrThrow(
698
+ await executeShellWithCapture(env, "yes line | head -n 15000", undefined, BACKGROUND_CONTEXT),
699
+ );
700
+ expect(result.truncated).toBe(true);
701
+ expect(result.fullOutputPath).toBeDefined();
702
+ const fullOutput = getOrThrow(await env.readTextFile(result.fullOutputPath!, BACKGROUND_CONTEXT));
703
+ expect(fullOutput.split("\n").length).toBeGreaterThan(10000);
704
+ expect(result.output.length).toBeLessThan(fullOutput.length);
705
+ });
706
+ });
packages/agent/test/harness/output-capture.test.ts ADDED
@@ -0,0 +1,151 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { afterEach, describe, expect, it, vi } from "vitest";
2
+ import { BACKGROUND_CONTEXT } from "../../src/harness/context.ts";
3
+ import type { ShellOutputUpdate, ShellOutputView } from "../../src/harness/types.ts";
4
+ import { applyShellOutputUpdate, OutputCapture, sanitizeShellOutput } from "../../src/harness/utils/output-capture.ts";
5
+
6
+ function createCapture(options?: { maxBytes?: number; maxLines?: number; retain?: "head" | "tail" }) {
7
+ const updates: ShellOutputUpdate[] = [];
8
+ const errors: unknown[] = [];
9
+ const capture = new OutputCapture(
10
+ {
11
+ limits: {
12
+ maxBytes: options?.maxBytes ?? 50,
13
+ maxLines: options?.maxLines ?? 100,
14
+ retain: options?.retain ?? "tail",
15
+ },
16
+ },
17
+ BACKGROUND_CONTEXT,
18
+ {
19
+ onUpdate: (update) => updates.push(update),
20
+ onError: (error) => errors.push(error),
21
+ },
22
+ );
23
+ return { capture, updates, errors };
24
+ }
25
+
26
+ function fold(updates: ShellOutputUpdate[]): ShellOutputView | undefined {
27
+ let output: ShellOutputView | undefined;
28
+ for (const update of updates) output = applyShellOutputUpdate(output, update);
29
+ return output;
30
+ }
31
+
32
+ afterEach(() => {
33
+ vi.useRealTimers();
34
+ });
35
+
36
+ describe("OutputCapture", () => {
37
+ it("removes invalid control characters without changing text or line boundaries", () => {
38
+ const input = "a\0b\tc\nd\re\u0007f\ufff9g\ufffbh😀";
39
+ expect(sanitizeShellOutput(input)).toBe("ab\tc\ndefgh😀");
40
+ const { capture } = createCapture();
41
+ capture.push(input);
42
+ expect(capture.snapshot().text).toBe("ab\tc\ndefgh😀");
43
+ });
44
+ it("decodes UTF-8 split across raw process chunks", () => {
45
+ const { capture } = createCapture();
46
+ const bytes = new TextEncoder().encode("😀");
47
+ capture.push(bytes.subarray(0, 2));
48
+ expect(capture.snapshot().text).toBe("");
49
+ capture.push(bytes.subarray(2));
50
+ capture.finish();
51
+ expect(capture.snapshot().text).toBe("😀");
52
+ });
53
+
54
+ it("publishes the first bounded view immediately and trickling appends responsively", () => {
55
+ vi.useFakeTimers();
56
+ vi.setSystemTime(0);
57
+ const { capture, updates } = createCapture();
58
+
59
+ capture.push("one");
60
+ expect(updates).toHaveLength(1);
61
+ expect(updates[0]?.kind).toBe("replace");
62
+
63
+ vi.advanceTimersByTime(150);
64
+ capture.push(" two");
65
+ expect(updates).toHaveLength(2);
66
+ expect(updates[1]).toMatchObject({ kind: "append", text: " two" });
67
+ expect(fold(updates)?.text).toBe("one two");
68
+ });
69
+
70
+ it("collapses a burst into one trailing update", () => {
71
+ vi.useFakeTimers();
72
+ vi.setSystemTime(0);
73
+ const { capture, updates } = createCapture();
74
+ capture.push("a");
75
+ capture.push("b");
76
+ capture.push("c");
77
+ expect(updates).toHaveLength(1);
78
+
79
+ vi.advanceTimersByTime(100);
80
+ expect(updates).toHaveLength(2);
81
+ expect(updates[1]).toMatchObject({ kind: "append", text: "bc" });
82
+ expect(fold(updates)?.text).toBe("abc");
83
+ });
84
+
85
+ it("publishes a small slide for post-cap trickle", () => {
86
+ vi.useFakeTimers();
87
+ vi.setSystemTime(0);
88
+ const { capture, updates } = createCapture({ maxBytes: 10 });
89
+ capture.push("abcdefghij");
90
+ vi.advanceTimersByTime(150);
91
+ capture.push("k");
92
+
93
+ expect(updates[1]).toMatchObject({ kind: "slide", drop: 1, text: "k" });
94
+ expect(fold(updates)?.text).toBe("bcdefghijk");
95
+ expect(fold(updates)?.truncation.totalBytes).toBe(11);
96
+ });
97
+
98
+ it("keeps the exact byte count for a single line larger than its working buffer", () => {
99
+ vi.useFakeTimers();
100
+ const { capture } = createCapture({ maxBytes: 10 });
101
+ capture.push("x".repeat(100));
102
+ expect(capture.snapshot()).toMatchObject({
103
+ text: "x".repeat(10),
104
+ lastLineBytes: 100,
105
+ truncation: { lastLinePartial: true },
106
+ });
107
+ });
108
+
109
+ it("uses a cap-bounded replacement after complete turnover", () => {
110
+ vi.useFakeTimers();
111
+ vi.setSystemTime(0);
112
+ const { capture, updates } = createCapture({ maxBytes: 10 });
113
+ capture.push("abcdefghij");
114
+ capture.push("x".repeat(100));
115
+ vi.advanceTimersByTime(100);
116
+
117
+ expect(updates[1]?.kind).toBe("replace");
118
+ expect(fold(updates)?.text).toHaveLength(10);
119
+ expect(fold(updates)?.truncation.totalBytes).toBe(110);
120
+ });
121
+
122
+ it("forces held state and cancels its trailing timer on dispose", () => {
123
+ vi.useFakeTimers();
124
+ vi.setSystemTime(0);
125
+ const { capture, updates } = createCapture();
126
+ capture.push("a");
127
+ capture.push("b");
128
+ capture.flush();
129
+ expect(fold(updates)?.text).toBe("ab");
130
+ capture.dispose();
131
+ vi.advanceTimersByTime(1_000);
132
+ expect(updates).toHaveLength(2);
133
+ });
134
+
135
+ it("preserves the original head after its raw guard is crossed", () => {
136
+ vi.useFakeTimers();
137
+ const { capture } = createCapture({ maxBytes: 100, maxLines: 2, retain: "head" });
138
+ capture.push(`first\nsecond\n${"tail".repeat(100)}`);
139
+ expect(capture.snapshot().text).toBe("first\nsecond");
140
+ });
141
+
142
+ it("publishes spill metadata without resending text", () => {
143
+ vi.useFakeTimers();
144
+ const { capture, updates, errors } = createCapture();
145
+ capture.push("output");
146
+ capture.setSpillPath("/tmp/output.log");
147
+ expect(updates.at(-1)).toMatchObject({ kind: "metadata", metadata: { spillPath: "/tmp/output.log" } });
148
+ expect(fold(updates)?.spillPath).toBe("/tmp/output.log");
149
+ expect(errors).toEqual([]);
150
+ });
151
+ });
packages/agent/test/harness/resource-formatting.test.ts ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { describe, expect, it } from "vitest";
2
+ import { formatPromptTemplateInvocation } from "../../src/harness/prompt-templates.ts";
3
+ import { formatSkillInvocation } from "../../src/harness/skills.ts";
4
+
5
+ describe("resource formatting helpers", () => {
6
+ it("formats skill invocations with additional instructions", () => {
7
+ const skill = {
8
+ name: "inspect",
9
+ description: "Inspect things",
10
+ content: "Use inspection tools.",
11
+ filePath: "/project/.pi/skills/inspect/SKILL.md",
12
+ };
13
+
14
+ expect(formatSkillInvocation(skill, "Check errors.")).toBe(
15
+ '<skill name="inspect" location="/project/.pi/skills/inspect/SKILL.md">\nReferences are relative to /project/.pi/skills/inspect.\n\nUse inspection tools.\n</skill>\n\nCheck errors.',
16
+ );
17
+ });
18
+
19
+ it("formats prompt template invocations with positional arguments", () => {
20
+ expect(
21
+ formatPromptTemplateInvocation({ name: "review", content: "Review $1 with $ARGUMENTS" }, ["a.ts", "care"]),
22
+ ).toBe("Review a.ts with a.ts care");
23
+ });
24
+ });
packages/agent/test/harness/session-context.test.ts ADDED
@@ -0,0 +1,260 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import type { AssistantMessage } from "@earendil-works/pi-ai";
2
+ import { describe, expect, it } from "vitest";
3
+ import { BACKGROUND_CONTEXT } from "../../src/harness/context.ts";
4
+ import { buildSessionContext } from "../../src/harness/session/context.ts";
5
+ import type {
6
+ BranchSummaryEntry,
7
+ CompactionEntry,
8
+ CustomEntry,
9
+ MessageEntry,
10
+ } from "../../src/harness/session/types.ts";
11
+ import type { AgentMessage } from "../../src/types.ts";
12
+
13
+ const NOW = 1_700_000_000_000;
14
+ const usage = {
15
+ input: 0,
16
+ output: 0,
17
+ cacheRead: 0,
18
+ cacheWrite: 0,
19
+ totalTokens: 0,
20
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
21
+ };
22
+
23
+ function userMessage(text: string): AgentMessage {
24
+ return { role: "user", content: [{ type: "text", text }], timestamp: NOW };
25
+ }
26
+
27
+ function assistantMessage(stopReason: AssistantMessage["stopReason"], text: string): AssistantMessage {
28
+ return {
29
+ role: "assistant",
30
+ content:
31
+ stopReason === "toolUse"
32
+ ? [{ type: "toolCall", id: "call", name: "read", arguments: {} }]
33
+ : [{ type: "text", text }],
34
+ api: "anthropic-messages",
35
+ provider: "anthropic",
36
+ model: "claude-sonnet-4-5",
37
+ usage,
38
+ stopReason,
39
+ ...(stopReason === "deferred"
40
+ ? { deferred: { provider: "anthropic", modelId: "claude-sonnet-4-5", api: "anthropic-messages", id: "job" } }
41
+ : {}),
42
+ timestamp: NOW,
43
+ };
44
+ }
45
+
46
+ function messageEntry(id: string, parentId: string | null, seq: number, message: AgentMessage): MessageEntry {
47
+ return { id, parentId, seq, timestamp: NOW, type: "message", message };
48
+ }
49
+
50
+ describe("session context projection", () => {
51
+ it("filters non-context assistant response entries while preserving valid messages", async () => {
52
+ const user = userMessage("question");
53
+ const stopped = assistantMessage("stop", "answer");
54
+ const length = assistantMessage("length", "truncated answer");
55
+ const toolUse = assistantMessage("toolUse", "");
56
+ const failed = assistantMessage("error", "failed");
57
+ const aborted = assistantMessage("aborted", "aborted");
58
+ const deferred = assistantMessage("deferred", "");
59
+ const entries = [
60
+ messageEntry("user", null, 1, user),
61
+ messageEntry("failed", "user", 2, failed),
62
+ messageEntry("stopped", "failed", 3, stopped),
63
+ messageEntry("aborted", "stopped", 4, aborted),
64
+ messageEntry("tool-use", "aborted", 5, toolUse),
65
+ messageEntry("deferred", "tool-use", 6, deferred),
66
+ messageEntry("length", "deferred", 7, length),
67
+ ];
68
+
69
+ expect(await buildSessionContext(entries, undefined, BACKGROUND_CONTEXT)).toEqual([
70
+ user,
71
+ stopped,
72
+ toolUse,
73
+ length,
74
+ ]);
75
+ });
76
+
77
+ it("projects branch summaries in branch order", async () => {
78
+ const before = messageEntry("before", null, 1, userMessage("before summary"));
79
+ const summary: BranchSummaryEntry = {
80
+ id: "branch-summary",
81
+ parentId: before.id,
82
+ seq: 2,
83
+ timestamp: NOW,
84
+ type: "branch_summary",
85
+ fromId: "source-leaf",
86
+ summary: "work on the abandoned branch",
87
+ fromHook: false,
88
+ };
89
+ const after = messageEntry("after", summary.id, 3, userMessage("after summary"));
90
+
91
+ expect(await buildSessionContext([before, summary, after], undefined, BACKGROUND_CONTEXT)).toEqual([
92
+ userMessage("before summary"),
93
+ {
94
+ role: "branchSummary",
95
+ summary: "work on the abandoned branch",
96
+ fromId: "source-leaf",
97
+ timestamp: NOW,
98
+ },
99
+ userMessage("after summary"),
100
+ ]);
101
+ });
102
+
103
+ it("filters retained-tail responses without hiding the compaction summary", async () => {
104
+ const user = userMessage("kept user");
105
+ const stopped = assistantMessage("stop", "kept answer");
106
+ const toolUse = assistantMessage("toolUse", "");
107
+ const length = assistantMessage("length", "kept truncated answer");
108
+ const failed = assistantMessage("error", "failed");
109
+ const aborted = assistantMessage("aborted", "aborted");
110
+ const deferred = assistantMessage("deferred", "");
111
+ const compaction: CompactionEntry = {
112
+ id: "compaction",
113
+ parentId: null,
114
+ seq: 1,
115
+ timestamp: NOW,
116
+ type: "compaction",
117
+ summary: "summary",
118
+ retainedTail: [failed, user, aborted, stopped, deferred, toolUse, length],
119
+ tokensBefore: 100,
120
+ fromHook: false,
121
+ };
122
+
123
+ expect(await buildSessionContext([compaction], undefined, BACKGROUND_CONTEXT)).toEqual([
124
+ { role: "compactionSummary", summary: "summary", tokensBefore: 100, timestamp: NOW },
125
+ user,
126
+ stopped,
127
+ toolUse,
128
+ length,
129
+ ]);
130
+ });
131
+ it("uses only the latest compaction checkpoint and entries after it", async () => {
132
+ const beforeFirst = messageEntry("before-first", null, 1, userMessage("before first"));
133
+ const first: CompactionEntry = {
134
+ id: "first-compaction",
135
+ parentId: beforeFirst.id,
136
+ seq: 2,
137
+ timestamp: NOW,
138
+ type: "compaction",
139
+ summary: "stale summary",
140
+ retainedTail: [userMessage("stale tail")],
141
+ tokensBefore: 100,
142
+ fromHook: false,
143
+ };
144
+ const between = messageEntry("between", first.id, 3, userMessage("between compactions"));
145
+ const latest: CompactionEntry = {
146
+ id: "latest-compaction",
147
+ parentId: between.id,
148
+ seq: 4,
149
+ timestamp: NOW,
150
+ type: "compaction",
151
+ summary: "latest summary",
152
+ retainedTail: [userMessage("latest tail")],
153
+ tokensBefore: 200,
154
+ fromHook: false,
155
+ };
156
+ const after = messageEntry("after", latest.id, 5, userMessage("after latest"));
157
+
158
+ expect(
159
+ await buildSessionContext([beforeFirst, first, between, latest, after], undefined, BACKGROUND_CONTEXT),
160
+ ).toEqual([
161
+ { role: "compactionSummary", summary: "latest summary", tokensBefore: 200, timestamp: NOW },
162
+ userMessage("latest tail"),
163
+ userMessage("after latest"),
164
+ ]);
165
+ });
166
+
167
+ it("projects custom entries through synchronous and asynchronous canonical projectors in branch order", async () => {
168
+ const oldCustom: CustomEntry = {
169
+ id: "old-custom",
170
+ parentId: null,
171
+ seq: 1,
172
+ timestamp: NOW,
173
+ type: "custom",
174
+ customType: "sync",
175
+ };
176
+ const compaction: CompactionEntry = {
177
+ id: "compaction",
178
+ parentId: oldCustom.id,
179
+ seq: 2,
180
+ timestamp: NOW,
181
+ type: "compaction",
182
+ summary: "summary",
183
+ retainedTail: [],
184
+ tokensBefore: 100,
185
+ fromHook: false,
186
+ };
187
+ const syncCustom: CustomEntry = {
188
+ id: "sync-custom",
189
+ parentId: compaction.id,
190
+ seq: 3,
191
+ timestamp: NOW,
192
+ type: "custom",
193
+ customType: "sync",
194
+ };
195
+ const omittedCustom: CustomEntry = {
196
+ id: "omitted-custom",
197
+ parentId: syncCustom.id,
198
+ seq: 4,
199
+ timestamp: NOW,
200
+ type: "custom",
201
+ customType: "omitted",
202
+ };
203
+ const asyncCustom: CustomEntry = {
204
+ id: "async-custom",
205
+ parentId: omittedCustom.id,
206
+ seq: 5,
207
+ timestamp: NOW,
208
+ type: "custom",
209
+ customType: "async",
210
+ };
211
+ const projectedIds: string[] = [];
212
+
213
+ const messages = await buildSessionContext(
214
+ [oldCustom, compaction, syncCustom, omittedCustom, asyncCustom],
215
+ {
216
+ entryProjectors: {
217
+ sync: (entry) => {
218
+ projectedIds.push(entry.id);
219
+ return [userMessage(`projected:${entry.id}`)];
220
+ },
221
+ async: async (entry) => {
222
+ await Promise.resolve();
223
+ projectedIds.push(entry.id);
224
+ return [userMessage(`projected:${entry.id}`)];
225
+ },
226
+ },
227
+ },
228
+ BACKGROUND_CONTEXT,
229
+ );
230
+
231
+ expect(projectedIds).toEqual([syncCustom.id, asyncCustom.id]);
232
+ expect(messages).toEqual([
233
+ { role: "compactionSummary", summary: "summary", tokensBefore: 100, timestamp: NOW },
234
+ userMessage(`projected:${syncCustom.id}`),
235
+ userMessage(`projected:${asyncCustom.id}`),
236
+ ]);
237
+ });
238
+
239
+ it("propagates custom projector failures", async () => {
240
+ const custom: CustomEntry = {
241
+ id: "custom",
242
+ parentId: null,
243
+ seq: 1,
244
+ timestamp: NOW,
245
+ type: "custom",
246
+ customType: "broken",
247
+ };
248
+ const failure = new Error("projector failed");
249
+
250
+ await expect(
251
+ buildSessionContext(
252
+ [custom],
253
+ {
254
+ entryProjectors: { broken: async () => Promise.reject(failure) },
255
+ },
256
+ BACKGROUND_CONTEXT,
257
+ ),
258
+ ).rejects.toBe(failure);
259
+ });
260
+ });
packages/agent/test/harness/session-test-utils.ts ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { existsSync, mkdirSync, rmSync } from "node:fs";
2
+ import { tmpdir } from "node:os";
3
+ import { join } from "node:path";
4
+ import { afterEach } from "vitest";
5
+
6
+ const tempDirs: string[] = [];
7
+
8
+ export function createTempDir(): string {
9
+ const dir = join(tmpdir(), `pi-agent-session-${Date.now()}-${Math.random().toString(36).slice(2)}`);
10
+ mkdirSync(dir, { recursive: true });
11
+ tempDirs.push(dir);
12
+ return dir;
13
+ }
14
+
15
+ afterEach(() => {
16
+ while (tempDirs.length > 0) {
17
+ const dir = tempDirs.pop()!;
18
+ if (existsSync(dir)) rmSync(dir, { recursive: true, force: true });
19
+ }
20
+ });
packages/agent/test/harness/skills.test.ts ADDED
@@ -0,0 +1,150 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { symlink } from "node:fs/promises";
2
+ import { join } from "node:path";
3
+ import { describe, expect, it } from "vitest";
4
+ import { BACKGROUND_CONTEXT } from "../../src/harness/context.ts";
5
+ import { NodeExecutionEnv } from "../../src/harness/env/nodejs.ts";
6
+ import { loadSkills, loadSourcedSkills } from "../../src/harness/skills.ts";
7
+ import { createTempDir } from "./session-test-utils.ts";
8
+
9
+ describe("loadSkills", () => {
10
+ it("loads SKILL.md files through the execution environment", async () => {
11
+ const root = createTempDir();
12
+ const env = new NodeExecutionEnv({ cwd: root });
13
+ await env.createDir(".agents/skills/example", { recursive: true }, BACKGROUND_CONTEXT);
14
+ await env.writeFile(
15
+ ".agents/skills/example/SKILL.md",
16
+ `---
17
+ name: example
18
+ description: Example skill
19
+ disable-model-invocation: true
20
+ ---
21
+ Use this skill.
22
+ `,
23
+ BACKGROUND_CONTEXT,
24
+ );
25
+
26
+ const { skills, diagnostics } = await loadSkills(env, ".agents/skills", BACKGROUND_CONTEXT);
27
+
28
+ expect(diagnostics).toEqual([]);
29
+ expect(skills).toEqual([
30
+ {
31
+ name: "example",
32
+ description: "Example skill",
33
+ content: "Use this skill.",
34
+ filePath: join(root, ".agents/skills/example/SKILL.md"),
35
+ disableModelInvocation: true,
36
+ },
37
+ ]);
38
+ });
39
+
40
+ it("loads skills through symlinked directories", async () => {
41
+ const root = createTempDir();
42
+ const env = new NodeExecutionEnv({ cwd: root });
43
+ await env.createDir("actual/example", { recursive: true }, BACKGROUND_CONTEXT);
44
+ await env.writeFile(
45
+ "actual/example/SKILL.md",
46
+ "---\nname: example\ndescription: Example skill\n---\nUse this skill.",
47
+ BACKGROUND_CONTEXT,
48
+ );
49
+ await symlink(join(root, "actual"), join(root, "skills-link"));
50
+
51
+ const { skills } = await loadSkills(env, "skills-link", BACKGROUND_CONTEXT);
52
+
53
+ expect(skills.map((skill) => skill.name)).toEqual(["example"]);
54
+ expect(skills[0]?.filePath).toBe(join(root, "skills-link/example/SKILL.md"));
55
+ });
56
+
57
+ it("preserves source info for sourced skills", async () => {
58
+ const root = createTempDir();
59
+ const env = new NodeExecutionEnv({ cwd: root });
60
+ await env.createDir("user/example", { recursive: true }, BACKGROUND_CONTEXT);
61
+ await env.writeFile(
62
+ "user/example/SKILL.md",
63
+ "---\nname: example\ndescription: Example skill\n---\nUse this skill.",
64
+ BACKGROUND_CONTEXT,
65
+ );
66
+
67
+ const { skills, diagnostics } = await loadSourcedSkills(
68
+ env,
69
+ [{ path: "user", source: { type: "user" as const } }],
70
+ undefined,
71
+ BACKGROUND_CONTEXT,
72
+ );
73
+
74
+ expect(diagnostics).toEqual([]);
75
+ expect(skills).toEqual([
76
+ {
77
+ skill: {
78
+ name: "example",
79
+ description: "Example skill",
80
+ content: "Use this skill.",
81
+ filePath: join(root, "user/example/SKILL.md"),
82
+ disableModelInvocation: false,
83
+ },
84
+ source: { type: "user" },
85
+ },
86
+ ]);
87
+ });
88
+
89
+ it("attaches source info to diagnostics", async () => {
90
+ const root = createTempDir();
91
+ const env = new NodeExecutionEnv({ cwd: root });
92
+ await env.createDir("user/broken", { recursive: true }, BACKGROUND_CONTEXT);
93
+ await env.writeFile("user/broken/SKILL.md", "---\nname: broken\n---\nMissing description.", BACKGROUND_CONTEXT);
94
+
95
+ const { skills, diagnostics } = await loadSourcedSkills(
96
+ env,
97
+ [{ path: "user", source: { type: "user" as const } }],
98
+ undefined,
99
+ BACKGROUND_CONTEXT,
100
+ );
101
+
102
+ expect(skills).toEqual([]);
103
+ expect(diagnostics).toEqual([
104
+ {
105
+ type: "warning",
106
+ code: "invalid_metadata",
107
+ message: "description is required",
108
+ path: join(root, "user/broken/SKILL.md"),
109
+ source: { type: "user" },
110
+ },
111
+ ]);
112
+ });
113
+
114
+ it("loads direct markdown children only from the root directory", async () => {
115
+ const root = createTempDir();
116
+ const env = new NodeExecutionEnv({ cwd: root });
117
+ await env.createDir("skills/nested", { recursive: true }, BACKGROUND_CONTEXT);
118
+ await env.writeFile("skills/root.md", "---\ndescription: Root skill\n---\nRoot content", BACKGROUND_CONTEXT);
119
+ await env.writeFile(
120
+ "skills/nested/ignored.md",
121
+ "---\ndescription: Ignored\n---\nIgnored content",
122
+ BACKGROUND_CONTEXT,
123
+ );
124
+
125
+ const { skills } = await loadSkills(env, "skills", BACKGROUND_CONTEXT);
126
+
127
+ expect(skills.map((skill) => skill.name)).toEqual(["skills"]);
128
+ expect(skills[0]?.content).toBe("Root content");
129
+ });
130
+
131
+ it("ignores root markdown docs that do not declare skills", async () => {
132
+ const root = createTempDir();
133
+ const env = new NodeExecutionEnv({ cwd: root });
134
+ await env.createDir("skills/nested-skill", { recursive: true }, BACKGROUND_CONTEXT);
135
+ await env.writeFile("skills/README.md", "# Shared skills\n\nDocumentation.", BACKGROUND_CONTEXT);
136
+ await env.writeFile("skills/AGENTS.md", "# Agent notes\n\nDocumentation.", BACKGROUND_CONTEXT);
137
+ await env.writeFile("skills/CLAUDE.md", "---\ndescription: [invalid\n---\n\nDocumentation.", BACKGROUND_CONTEXT);
138
+ await env.writeFile("skills/root.md", "---\ndescription: Root skill\n---\nRoot content", BACKGROUND_CONTEXT);
139
+ await env.writeFile(
140
+ "skills/nested-skill/SKILL.md",
141
+ "---\nname: nested-skill\ndescription: Nested skill\n---\nNested content",
142
+ BACKGROUND_CONTEXT,
143
+ );
144
+
145
+ const { skills, diagnostics } = await loadSkills(env, "skills", BACKGROUND_CONTEXT);
146
+
147
+ expect(diagnostics).toEqual([]);
148
+ expect(skills.map((skill) => skill.name).sort()).toEqual(["nested-skill", "skills"]);
149
+ });
150
+ });
packages/agent/test/harness/storage-backed-session.test.ts ADDED
@@ -0,0 +1,397 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import type { AssistantMessage } from "@earendil-works/pi-ai";
2
+ import { describe, expect, it } from "vitest";
3
+ import { BACKGROUND_CONTEXT } from "../../src/harness/context.ts";
4
+ import type { CustomMessage } from "../../src/harness/messages.ts";
5
+ import * as sessionWrites from "../../src/harness/session/commit.ts";
6
+ import { MemoryStorage } from "../../src/harness/session/memory.ts";
7
+ import { StorageBackedSession } from "../../src/harness/session/session.ts";
8
+ import { GatingStorage, InstrumentedStorage } from "../../src/harness/session/testing/index.ts";
9
+ import type {
10
+ MessageEntry,
11
+ NewEntry,
12
+ Session,
13
+ SessionMetadata,
14
+ SessionMutator,
15
+ Write,
16
+ } from "../../src/harness/session/types.ts";
17
+ import * as storedValues from "../../src/harness/session/values.ts";
18
+ import { deferred } from "./runtime/test-utils.ts";
19
+
20
+ const NOW = 1_700_000_000_000;
21
+ const ENTRY_ID = "00000000-0000-7000-8000-000000000001";
22
+ const metadata = {
23
+ id: "session",
24
+ createdAt: NOW,
25
+ storageVersion: 1,
26
+ cwd: "/workspace",
27
+ } satisfies SessionMetadata;
28
+
29
+ function commitSession(session: Session, transaction: Write[]) {
30
+ return session.mutate((mutator) => mutator.commit(transaction, BACKGROUND_CONTEXT), BACKGROUND_CONTEXT);
31
+ }
32
+
33
+ describe("StorageBackedSession", () => {
34
+ it("delegates typed values directly without validation or cloning", async () => {
35
+ const storage = new InstrumentedStorage(new MemoryStorage({ now: () => NOW }));
36
+ const session = new StorageBackedSession(metadata, storage);
37
+ const data = { nested: ["original"] };
38
+ const transaction: Write[] = [
39
+ sessionWrites.insertEntry({ id: ENTRY_ID, parentId: null, type: "custom", customType: "note", data }),
40
+ storedValues.setValue(storedValues.value<unknown>("test.value", "state"), data),
41
+ ];
42
+
43
+ const result = await commitSession(session, transaction);
44
+
45
+ expect(storage.getCommitAttempts()[0]).toBe(transaction);
46
+ const entry = (await session.getEntries([ENTRY_ID], BACKGROUND_CONTEXT)).get(ENTRY_ID);
47
+ expect(entry).toMatchObject({ seq: result.seqs[0], timestamp: NOW });
48
+ if (entry?.type !== "custom") throw new Error("Expected custom entry");
49
+ expect(entry.data).toBe(data);
50
+ expect(
51
+ (await session.getValue(storedValues.value<unknown>("test.value", "state"), BACKGROUND_CONTEXT))?.value,
52
+ ).toBe(data);
53
+ await session.close(BACKGROUND_CONTEXT);
54
+ });
55
+
56
+ it("composes bound values and lists atomically with entries and usage", async () => {
57
+ const storage = new InstrumentedStorage(new MemoryStorage({ now: () => NOW }));
58
+ const session = new StorageBackedSession(metadata, storage);
59
+ const scalar = storedValues.value<string>("test.application.scalar");
60
+ const events = storedValues.list<string>("test.application.events");
61
+
62
+ const result = await session.mutate(
63
+ (mutator) =>
64
+ mutator.commit(
65
+ [
66
+ sessionWrites.insertEntry({ id: ENTRY_ID, parentId: null, type: "custom", customType: "note" }),
67
+ storedValues.setValue(scalar, "state"),
68
+ storedValues.appendList(events, "event"),
69
+ sessionWrites.insertUsage({
70
+ id: "usage",
71
+ adjustment: false,
72
+ usage: {
73
+ input: 1,
74
+ output: 1,
75
+ cacheRead: 0,
76
+ cacheWrite: 0,
77
+ totalTokens: 2,
78
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
79
+ },
80
+ }),
81
+ ],
82
+ BACKGROUND_CONTEXT,
83
+ ),
84
+ BACKGROUND_CONTEXT,
85
+ );
86
+
87
+ expect(result.seqs).toHaveLength(4);
88
+ expect((await session.getValue(scalar, BACKGROUND_CONTEXT))?.seq).toBe(result.seqs[1]);
89
+ expect(await session.readList(events, undefined, BACKGROUND_CONTEXT)).toEqual([
90
+ { seq: result.seqs[2], value: "event" },
91
+ ]);
92
+ expect(storage.getCommitAttempts()).toHaveLength(1);
93
+ await session.close(BACKGROUND_CONTEXT);
94
+ });
95
+
96
+ it("serializes read-modify-write callbacks on the single Session line", async () => {
97
+ const session = new StorageBackedSession(metadata, new MemoryStorage({ now: () => NOW }));
98
+ const counter = storedValues.value<number>("test.counter");
99
+ const increment = () =>
100
+ session.mutate(async (mutator) => {
101
+ const next = ((await mutator.getValue(counter, BACKGROUND_CONTEXT))?.value ?? 0) + 1;
102
+ await mutator.commit([storedValues.setValue(counter, next)], BACKGROUND_CONTEXT);
103
+ return next;
104
+ }, BACKGROUND_CONTEXT);
105
+
106
+ await expect(Promise.all([increment(), increment()])).resolves.toEqual([1, 2]);
107
+ expect((await session.getValue(counter, BACKGROUND_CONTEXT))?.value).toBe(2);
108
+ await session.close(BACKGROUND_CONTEXT);
109
+ });
110
+
111
+ it("keeps separate direct reads and writes deliberately non-atomic", async () => {
112
+ const session = new StorageBackedSession(metadata, new MemoryStorage({ now: () => NOW }));
113
+ const counter = storedValues.value<number>("test.counter");
114
+ const bothRead = deferred();
115
+ let readers = 0;
116
+ const increment = async () => {
117
+ const next = ((await session.getValue(counter, BACKGROUND_CONTEXT))?.value ?? 0) + 1;
118
+ readers++;
119
+ if (readers === 2) bothRead.resolve();
120
+ await bothRead.promise;
121
+ await session.setValue(counter, next, BACKGROUND_CONTEXT);
122
+ };
123
+
124
+ await Promise.all([increment(), increment()]);
125
+ expect((await session.getValue(counter, BACKGROUND_CONTEXT))?.value).toBe(1);
126
+ await session.close(BACKGROUND_CONTEXT);
127
+ });
128
+
129
+ it("queues a nested public writer until its owning callback returns", async () => {
130
+ const session = new StorageBackedSession(metadata, new MemoryStorage({ now: () => NOW }));
131
+ let nested: Promise<void> | undefined;
132
+ await session.mutate(async () => {
133
+ nested = session.setValue(storedValues.sessionName, "nested", BACKGROUND_CONTEXT);
134
+ let settled = false;
135
+ void nested.finally(() => {
136
+ settled = true;
137
+ });
138
+ await Promise.resolve();
139
+ expect(settled).toBe(false);
140
+ }, BACKGROUND_CONTEXT);
141
+ if (nested === undefined) throw new Error("Expected nested writer");
142
+ await nested;
143
+ expect(await session.getName(BACKGROUND_CONTEXT)).toBe("nested");
144
+ await session.close(BACKGROUND_CONTEXT);
145
+ });
146
+
147
+ it("exposes either side of an atomic multi-write commit to direct reads", async () => {
148
+ const first = storedValues.value<string>("test.atomic", "first");
149
+ const second = storedValues.value<string>("test.atomic", "second");
150
+ const storage = new GatingStorage(new MemoryStorage({ now: () => NOW }));
151
+ await storage.commit(
152
+ [storedValues.setValue(first, "old"), storedValues.setValue(second, "old")],
153
+ BACKGROUND_CONTEXT,
154
+ );
155
+ storage.arm();
156
+ const session = new StorageBackedSession(metadata, storage);
157
+ const committing = commitSession(session, [
158
+ storedValues.setValue(first, "new"),
159
+ storedValues.setValue(second, "new"),
160
+ ]);
161
+ await storage.waitPending();
162
+
163
+ expect((await session.getValue(first, BACKGROUND_CONTEXT))?.value).toBe("old");
164
+ expect((await session.getValue(second, BACKGROUND_CONTEXT))?.value).toBe("old");
165
+ await storage.next();
166
+ await committing;
167
+ expect((await session.getValue(first, BACKGROUND_CONTEXT))?.value).toBe("new");
168
+ expect((await session.getValue(second, BACKGROUND_CONTEXT))?.value).toBe("new");
169
+ await session.close(BACKGROUND_CONTEXT);
170
+ });
171
+
172
+ it("holds the explicit Session barrier through commit until end", async () => {
173
+ const storage = new InstrumentedStorage(new MemoryStorage({ now: () => NOW }));
174
+ const session = new StorageBackedSession(metadata, storage);
175
+ const mutation = await session.beginMutation(BACKGROUND_CONTEXT);
176
+ let queuedStarted = false;
177
+ const queued = session.mutate(() => {
178
+ queuedStarted = true;
179
+ }, BACKGROUND_CONTEXT);
180
+
181
+ await Promise.resolve();
182
+ expect(queuedStarted).toBe(false);
183
+ expect(await mutation.getValue(storedValues.sessionName, BACKGROUND_CONTEXT)).toBeUndefined();
184
+ const result = await mutation.commit([], BACKGROUND_CONTEXT);
185
+ expect(result.seqs).toEqual([]);
186
+ expect(queuedStarted).toBe(false);
187
+ expect(await mutation.getValue(storedValues.sessionName, BACKGROUND_CONTEXT)).toBeUndefined();
188
+ await mutation.end(BACKGROUND_CONTEXT);
189
+ await queued;
190
+ expect(queuedStarted).toBe(true);
191
+ expect(storage.getCommitAttempts()).toEqual([[]]);
192
+ expect(() => mutation.getEntries([], BACKGROUND_CONTEXT)).toThrow("outside its mutation callback");
193
+ expect(() => mutation.commit([], BACKGROUND_CONTEXT)).toThrow("outside its mutation callback");
194
+ await expect(mutation.end(BACKGROUND_CONTEXT)).resolves.toBeUndefined();
195
+ await session.close(BACKGROUND_CONTEXT);
196
+ });
197
+
198
+ it("allows direct reads to observe a committed value before the mutation scope ends", async () => {
199
+ const session = new StorageBackedSession(metadata, new MemoryStorage({ now: () => NOW }));
200
+ const mutation = await session.beginMutation(BACKGROUND_CONTEXT);
201
+ expect(await session.getValue(storedValues.sessionName, BACKGROUND_CONTEXT)).toBeUndefined();
202
+ await mutation.commit([storedValues.setValue(storedValues.sessionName, "visible")], BACKGROUND_CONTEXT);
203
+ let queuedStarted = false;
204
+ const queued = session.mutate(() => {
205
+ queuedStarted = true;
206
+ }, BACKGROUND_CONTEXT);
207
+
208
+ expect((await session.getValue(storedValues.sessionName, BACKGROUND_CONTEXT))?.value).toBe("visible");
209
+ expect(queuedStarted).toBe(false);
210
+ await mutation.end(BACKGROUND_CONTEXT);
211
+ await queued;
212
+ expect(queuedStarted).toBe(true);
213
+ await session.close(BACKGROUND_CONTEXT);
214
+ });
215
+
216
+ it("ends an explicit mutation without committing and lets close finish", async () => {
217
+ const storage = new InstrumentedStorage(new MemoryStorage({ now: () => NOW }));
218
+ const session = new StorageBackedSession(metadata, storage);
219
+ const mutation = await session.beginMutation(BACKGROUND_CONTEXT);
220
+ let closed = false;
221
+ const closing = session.close(BACKGROUND_CONTEXT).then(() => {
222
+ closed = true;
223
+ });
224
+
225
+ await Promise.resolve();
226
+ expect(closed).toBe(false);
227
+ await mutation.end(BACKGROUND_CONTEXT);
228
+ await closing;
229
+ expect(closed).toBe(true);
230
+ expect(storage.getCommitAttempts()).toEqual([]);
231
+ });
232
+
233
+ it("exposes explicit branch scans through the Session and callback-scoped mutator", async () => {
234
+ const storage = new MemoryStorage({ now: () => NOW });
235
+ const session = new StorageBackedSession(metadata, storage);
236
+ const childId = "00000000-0000-7000-8000-000000000002";
237
+ await commitSession(session, [
238
+ sessionWrites.insertEntry({ id: ENTRY_ID, parentId: null, type: "custom", customType: "root" }),
239
+ sessionWrites.insertEntry({ id: childId, parentId: ENTRY_ID, type: "custom", customType: "child" }),
240
+ ]);
241
+
242
+ await expect(
243
+ session.scanBranch({ start: childId, order: "oldestFirst" }, BACKGROUND_CONTEXT),
244
+ ).resolves.toMatchObject([{ id: ENTRY_ID }, { id: childId }]);
245
+ let captured: SessionMutator | undefined;
246
+ await session.mutate(async (mutator) => {
247
+ captured = mutator;
248
+ await expect(mutator.scanBranch({ start: childId, limit: 1 }, BACKGROUND_CONTEXT)).resolves.toMatchObject([
249
+ { id: childId },
250
+ ]);
251
+ }, BACKGROUND_CONTEXT);
252
+ const invalidated = captured;
253
+ if (invalidated === undefined) throw new Error("Expected captured mutator");
254
+ expect(() => invalidated.scanBranch({ start: childId }, BACKGROUND_CONTEXT)).toThrow(
255
+ "outside its mutation callback",
256
+ );
257
+ await session.close(BACKGROUND_CONTEXT);
258
+ });
259
+
260
+ it("rejects pending assistant entries at the durable session write boundary", async () => {
261
+ const storage = new InstrumentedStorage(new MemoryStorage({ now: () => NOW }));
262
+ const session = new StorageBackedSession(metadata, storage);
263
+ const pending: AssistantMessage = {
264
+ role: "assistant",
265
+ content: [],
266
+ api: "anthropic-messages",
267
+ provider: "anthropic",
268
+ model: "claude-sonnet-4-5",
269
+ usage: {
270
+ input: 0,
271
+ output: 0,
272
+ cacheRead: 0,
273
+ cacheWrite: 0,
274
+ totalTokens: 0,
275
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
276
+ },
277
+ stopReason: "pending",
278
+ timestamp: NOW,
279
+ };
280
+
281
+ await expect(
282
+ commitSession(session, [
283
+ sessionWrites.insertEntry({ id: ENTRY_ID, parentId: null, type: "message", message: pending }),
284
+ ]),
285
+ ).rejects.toThrow("Cannot persist a pending assistant message");
286
+ expect(storage.getCommitAttempts()).toEqual([]);
287
+ expect(await session.getEntries([ENTRY_ID], BACKGROUND_CONTEXT)).toEqual(new Map());
288
+ await session.close(BACKGROUND_CONTEXT);
289
+ });
290
+
291
+ it("trusts typed custom messages without repository schema registration", async () => {
292
+ const storage = new MemoryStorage({ now: () => NOW });
293
+ const session = new StorageBackedSession(metadata, storage);
294
+ const message: CustomMessage = {
295
+ role: "custom",
296
+ customType: "notice",
297
+ content: "maintenance",
298
+ display: true,
299
+ timestamp: NOW,
300
+ };
301
+ const entry: NewEntry<MessageEntry> = { id: ENTRY_ID, parentId: null, type: "message", message };
302
+
303
+ const result = await commitSession(session, [sessionWrites.insertEntry(entry)]);
304
+
305
+ expect((await session.getEntries([ENTRY_ID], BACKGROUND_CONTEXT)).get(ENTRY_ID)).toEqual({
306
+ ...entry,
307
+ seq: result.firstSeq,
308
+ timestamp: result.timestamp,
309
+ });
310
+ await session.close(BACKGROUND_CONTEXT);
311
+ });
312
+
313
+ it("serializes mutations, permits one commit attempt, and invalidates the mutator", async () => {
314
+ const storage = new InstrumentedStorage(new MemoryStorage({ now: () => NOW }));
315
+ const session = new StorageBackedSession(metadata, storage);
316
+ let captured: SessionMutator | undefined;
317
+
318
+ await session.mutate(async (mutator) => {
319
+ captured = mutator;
320
+ expect(await mutator.getValue(storedValues.sessionName, BACKGROUND_CONTEXT)).toBeUndefined();
321
+ await mutator.commit([storedValues.setValue(storedValues.sessionName, "committed")], BACKGROUND_CONTEXT);
322
+ await expect(mutator.commit([], BACKGROUND_CONTEXT)).rejects.toThrow("commit already attempted");
323
+ }, BACKGROUND_CONTEXT);
324
+
325
+ expect(storage.getCommitAttempts()).toHaveLength(1);
326
+ expect(await session.getName(BACKGROUND_CONTEXT)).toBe("committed");
327
+ const invalidated = captured;
328
+ if (invalidated === undefined) throw new Error("Expected captured mutator");
329
+ expect(() => invalidated.getEntries([], BACKGROUND_CONTEXT)).toThrow("outside its mutation callback");
330
+ await session.close(BACKGROUND_CONTEXT);
331
+ });
332
+
333
+ it("consumes the commit guard when the first commit fails", async () => {
334
+ const storage = new InstrumentedStorage(new MemoryStorage({ now: () => NOW }));
335
+ const session = new StorageBackedSession(metadata, storage);
336
+ const transaction = [
337
+ sessionWrites.insertEntry({ id: ENTRY_ID, parentId: "missing", type: "custom", customType: "note" }),
338
+ ] satisfies Write[];
339
+
340
+ await expect(
341
+ session.mutate(async (mutator) => {
342
+ await expect(mutator.commit(transaction, BACKGROUND_CONTEXT)).rejects.toThrow("Missing parent entry");
343
+ await expect(mutator.commit([], BACKGROUND_CONTEXT)).rejects.toThrow("commit already attempted");
344
+ }, BACKGROUND_CONTEXT),
345
+ ).resolves.toBeUndefined();
346
+ expect(storage.getCommitAttempts()).toHaveLength(1);
347
+ await session.close(BACKGROUND_CONTEXT);
348
+ });
349
+
350
+ it("mints distinct follower ids with the leader timestamp", async () => {
351
+ const session = new StorageBackedSession(metadata, new MemoryStorage({ now: () => NOW }));
352
+ const leaderTimestamp = 0x0123456789ab;
353
+ const leader = session.idGenerator.next(leaderTimestamp);
354
+ const followers = [session.idGenerator.next(leaderTimestamp), session.idGenerator.next(leaderTimestamp)];
355
+ const decodeTimestamp = (id: string): number => Number.parseInt(id.replaceAll("-", "").slice(0, 12), 16);
356
+
357
+ expect([leader, ...followers].map(decodeTimestamp)).toEqual([leaderTimestamp, leaderTimestamp, leaderTimestamp]);
358
+ expect(new Set([leader, ...followers])).toHaveLength(3);
359
+ await session.close(BACKGROUND_CONTEXT);
360
+ });
361
+
362
+ it("accepts an injected id generator for deterministic execution tests", async () => {
363
+ let next = 0;
364
+ const idGenerator = { next: (timestampMs?: number) => `${timestampMs ?? "now"}:${++next}` };
365
+ const session = new StorageBackedSession(metadata, new MemoryStorage({ now: () => NOW }), { idGenerator });
366
+
367
+ expect(session.idGenerator).toBe(idGenerator);
368
+ expect(session.idGenerator.next(7)).toBe("7:1");
369
+ expect(session.idGenerator.next()).toBe("now:2");
370
+ await session.close(BACKGROUND_CONTEXT);
371
+ });
372
+
373
+ it("exposes metadata directly and the shared UUIDv7 id generator", async () => {
374
+ const sourceMetadata = { ...metadata };
375
+ const session = new StorageBackedSession(sourceMetadata, new MemoryStorage({ now: () => NOW }));
376
+
377
+ expect(session.metadata).toBe(sourceMetadata);
378
+ expect(session.idGenerator.next()).toMatch(
379
+ /^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,
380
+ );
381
+ await session.close(BACKGROUND_CONTEXT);
382
+ });
383
+
384
+ it("closes idempotently and rejects operations not admitted before close", async () => {
385
+ const storage = new MemoryStorage({ now: () => NOW });
386
+ const session = new StorageBackedSession(metadata, storage);
387
+
388
+ await Promise.all([session.close(BACKGROUND_CONTEXT), session.close(BACKGROUND_CONTEXT)]);
389
+ await expect(session.mutate(() => undefined, BACKGROUND_CONTEXT)).rejects.toThrow("Session is closed");
390
+ await expect(session.getEntries([], BACKGROUND_CONTEXT)).rejects.toThrow("Session is closed");
391
+ await expect(session.getValue(storedValues.sessionName, BACKGROUND_CONTEXT)).rejects.toThrow("Session is closed");
392
+ await expect(session.scanValues(storedValues.sessionName, BACKGROUND_CONTEXT)).rejects.toThrow(
393
+ "Session is closed",
394
+ );
395
+ await expect(session.scanBranch({ start: ENTRY_ID }, BACKGROUND_CONTEXT)).rejects.toThrow("Session is closed");
396
+ });
397
+ });
packages/agent/test/harness/system-prompt.test.ts ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { describe, expect, it } from "vitest";
2
+ import { formatSkillsForSystemPrompt } from "../../src/harness/system-prompt.ts";
3
+
4
+ const visibleSkill = {
5
+ name: "visible",
6
+ description: "Use <this> & that",
7
+ content: "visible content",
8
+ filePath: "/skills/visible/SKILL.md",
9
+ };
10
+
11
+ const secondSkill = {
12
+ name: "second",
13
+ description: "Second skill",
14
+ content: "second content",
15
+ filePath: "/skills/second/SKILL.md",
16
+ };
17
+
18
+ const disabledSkill = {
19
+ name: "hidden",
20
+ description: "Hidden",
21
+ content: "hidden content",
22
+ filePath: "/skills/hidden/SKILL.md",
23
+ disableModelInvocation: true,
24
+ };
25
+
26
+ describe("formatSkillsForSystemPrompt", () => {
27
+ it("formats visible skills in order and skips model-disabled skills", () => {
28
+ expect(formatSkillsForSystemPrompt([visibleSkill, disabledSkill, secondSkill])).toBe(
29
+ `The following skills provide specialized instructions for specific tasks.
30
+ Read the full skill file when the task matches its description.
31
+ When a skill file references a relative path, resolve it against the skill directory (parent of SKILL.md / dirname of the path) and use that absolute path in tool commands.
32
+
33
+ <available_skills>
34
+ <skill>
35
+ <name>visible</name>
36
+ <description>Use &lt;this&gt; &amp; that</description>
37
+ <location>/skills/visible/SKILL.md</location>
38
+ </skill>
39
+ <skill>
40
+ <name>second</name>
41
+ <description>Second skill</description>
42
+ <location>/skills/second/SKILL.md</location>
43
+ </skill>
44
+ </available_skills>`,
45
+ );
46
+ });
47
+
48
+ it("returns an empty string when no skills are model-visible", () => {
49
+ expect(formatSkillsForSystemPrompt([disabledSkill])).toBe("");
50
+ });
51
+
52
+ it("escapes XML in all model-visible skill fields", () => {
53
+ expect(
54
+ formatSkillsForSystemPrompt([
55
+ {
56
+ name: "a&b",
57
+ description: `Quote "double" and 'single'`,
58
+ content: "content",
59
+ filePath: '/skills/<bad>&"quote"/SKILL.md',
60
+ },
61
+ ]),
62
+ ).toContain(
63
+ "<name>a&amp;b</name>\n <description>Quote &quot;double&quot; and &apos;single&apos;</description>\n <location>/skills/&lt;bad&gt;&amp;&quot;quote&quot;/SKILL.md</location>",
64
+ );
65
+ });
66
+ });
packages/agent/test/harness/telemetry.test.ts ADDED
@@ -0,0 +1,204 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { readFileSync } from "node:fs";
2
+ import { resolve } from "node:path";
3
+ import { createTypedSpanStarter, NOOP_TELEMETRY_CONTEXT, type TelemetryContext } from "@earendil-works/pi-telemetry";
4
+ import { describe, expect, expectTypeOf, it } from "vitest";
5
+ import { renderAgentTelemetrySchemaMarkdown } from "../../scripts/generate-telemetry-docs.ts";
6
+ import { BACKGROUND_CONTEXT, withTelemetryContext } from "../../src/harness/context.ts";
7
+ import {
8
+ AGENT_TELEMETRY_SCHEMAS,
9
+ AI_TELEMETRY_SCHEMA,
10
+ type AiSpanEndAttributes,
11
+ type AiSpanStartAttributes,
12
+ HARNESS_TELEMETRY_SCHEMA,
13
+ type HarnessSpanEndAttributes,
14
+ type HarnessSpanStartAttributes,
15
+ startAiSpan,
16
+ startHarnessSpan,
17
+ } from "../../src/harness/telemetry.ts";
18
+
19
+ describe("agent telemetry schemas", () => {
20
+ it("serializes both schemas and generates the checked-in reference", () => {
21
+ expect(() => JSON.stringify(AI_TELEMETRY_SCHEMA)).not.toThrow();
22
+ expect(() => JSON.stringify(HARNESS_TELEMETRY_SCHEMA)).not.toThrow();
23
+ expect(AGENT_TELEMETRY_SCHEMAS).toEqual([AI_TELEMETRY_SCHEMA, HARNESS_TELEMETRY_SCHEMA]);
24
+ expect(Object.keys(HARNESS_TELEMETRY_SCHEMA.spans)).toEqual([
25
+ "pi.harness.run",
26
+ "pi.harness.compaction",
27
+ "pi.harness.navigation",
28
+ "pi.harness.checkpoint",
29
+ "pi.harness.turn",
30
+ "pi.harness.step",
31
+ "pi.harness.tool",
32
+ "pi.harness.hook",
33
+ "pi.harness.sleep",
34
+ "pi.harness.event_handler",
35
+ "pi.session.write",
36
+ ]);
37
+ const actual = readFileSync(resolve(import.meta.dirname, "../../docs/telemetry-schema.md"), "utf8");
38
+ expect(actual).toBe(renderAgentTelemetrySchemaMarkdown());
39
+ });
40
+
41
+ it("starts AI-request and harness spans through one composed typed starter", async () => {
42
+ const startSpan = createTypedSpanStarter(NOOP_TELEMETRY_CONTEXT, AGENT_TELEMETRY_SCHEMAS);
43
+ await startSpan(
44
+ "pi.harness.step",
45
+ {
46
+ "pi.lane.name": "main",
47
+ "pi.operation.id": "operation",
48
+ "pi.step.kind": "assistant",
49
+ "pi.step.attempt": 1,
50
+ },
51
+ async (stepSpan, startChildSpan) => {
52
+ stepSpan.setAttributes({ "pi.step.outcome": "succeeded" });
53
+ await startChildSpan(
54
+ "pi.ai.request",
55
+ {
56
+ "pi.ai.operation": "stream",
57
+ "pi.ai.provider": "provider",
58
+ "pi.ai.model": "model",
59
+ "pi.ai.api": "api",
60
+ "pi.ai.streaming": true,
61
+ },
62
+ (requestSpan) => {
63
+ requestSpan.setAttributes({ "pi.ai.response.stop_reason": "stop" });
64
+ },
65
+ );
66
+ },
67
+ );
68
+ });
69
+
70
+ it("infers exact AI start and optional end attributes", async () => {
71
+ type Start = AiSpanStartAttributes<"pi.ai.request">;
72
+ type End = AiSpanEndAttributes<"pi.ai.request">;
73
+ expectTypeOf<Start>().toMatchTypeOf<{
74
+ "pi.ai.operation": "stream" | "fetch_deferred" | "cancel_deferred" | "generate_images";
75
+ "pi.ai.provider": string;
76
+ "pi.ai.model": string;
77
+ "pi.ai.api": string;
78
+ "pi.ai.streaming": boolean;
79
+ "pi.ai.deferred"?: boolean;
80
+ }>();
81
+ expectTypeOf<End["pi.ai.response.stop_reason"]>().toEqualTypeOf<
82
+ "stop" | "length" | "tool_use" | "error" | "aborted" | "deferred" | undefined
83
+ >();
84
+
85
+ const telemetryContext: TelemetryContext = NOOP_TELEMETRY_CONTEXT;
86
+ const context = withTelemetryContext(telemetryContext, BACKGROUND_CONTEXT);
87
+ await startAiSpan(
88
+ "pi.ai.request",
89
+ {
90
+ "pi.ai.operation": "stream",
91
+ "pi.ai.provider": "provider",
92
+ "pi.ai.model": "model",
93
+ "pi.ai.api": "api",
94
+ "pi.ai.streaming": true,
95
+ },
96
+ (span) => {
97
+ span.setAttributes({ "pi.ai.response.stop_reason": "tool_use" });
98
+ // @ts-expect-error pi.ai.request declares no span events
99
+ span.addEvent("chunk");
100
+ },
101
+ context,
102
+ );
103
+
104
+ const compileTimeFailures = () => {
105
+ const extraAttributes = {
106
+ "pi.ai.operation": "stream",
107
+ "pi.ai.provider": "provider",
108
+ "pi.ai.model": "model",
109
+ "pi.ai.api": "api",
110
+ "pi.ai.streaming": true,
111
+ "pi.ai.unknown": true,
112
+ } as const;
113
+ // @ts-expect-error variables with unknown attributes are rejected
114
+ void startAiSpan("pi.ai.request", extraAttributes, () => {}, context);
115
+ // @ts-expect-error missing required start attributes
116
+ void startAiSpan("pi.ai.request", { "pi.ai.operation": "stream" }, () => {}, context);
117
+ };
118
+ expectTypeOf(compileTimeFailures).toBeFunction();
119
+ });
120
+
121
+ it("infers per-span harness literals and optional completion enrichment", async () => {
122
+ type RunStart = HarnessSpanStartAttributes<"pi.harness.run">;
123
+ type RunEnd = HarnessSpanEndAttributes<"pi.harness.run">;
124
+ type WriteStart = HarnessSpanStartAttributes<"pi.session.write">;
125
+ type WriteEnd = HarnessSpanEndAttributes<"pi.session.write">;
126
+ expectTypeOf<RunStart["pi.operation.kind"]>().toEqualTypeOf<"run">();
127
+ expectTypeOf<RunEnd["pi.operation.outcome"]>().toEqualTypeOf<
128
+ "completed" | "aborted" | "failed" | "suspended" | undefined
129
+ >();
130
+ const writeStart = {
131
+ "pi.session.id": "session",
132
+ "pi.session.item_count": 2,
133
+ "pi.session.item_kinds": ["entry", "value", "list"],
134
+ } satisfies WriteStart;
135
+ const writeEnd = {
136
+ "pi.session.first_seq": 1,
137
+ "pi.session.last_seq": 2,
138
+ } satisfies WriteEnd;
139
+ expectTypeOf(writeStart["pi.session.item_count"]).toEqualTypeOf<number>();
140
+ expectTypeOf(writeEnd["pi.session.last_seq"]).toEqualTypeOf<number>();
141
+
142
+ const telemetryContext: TelemetryContext = NOOP_TELEMETRY_CONTEXT;
143
+ const context = withTelemetryContext(telemetryContext, BACKGROUND_CONTEXT);
144
+ await startHarnessSpan(
145
+ "pi.harness.run",
146
+ {
147
+ "pi.session.id": "session",
148
+ "pi.lane.name": "main",
149
+ "pi.operation.id": "operation",
150
+ "pi.operation.kind": "run",
151
+ "pi.operation.recovery": false,
152
+ },
153
+ (span) => {
154
+ span.setAttributes({ "pi.operation.outcome": "completed" });
155
+ span.setAttributes({});
156
+ // @ts-expect-error the harness schema declares no span events
157
+ span.addEvent("result");
158
+ },
159
+ context,
160
+ );
161
+
162
+ const compileTimeFailures = () => {
163
+ const extraRunAttributes = {
164
+ "pi.session.id": "session",
165
+ "pi.lane.name": "main",
166
+ "pi.operation.id": "operation",
167
+ "pi.operation.kind": "run",
168
+ "pi.operation.recovery": false,
169
+ "pi.unknown": true,
170
+ } as const;
171
+ // @ts-expect-error variables with unknown attributes are rejected
172
+ void startHarnessSpan("pi.harness.run", extraRunAttributes, () => {}, context);
173
+ void startHarnessSpan(
174
+ "pi.harness.checkpoint",
175
+ {
176
+ "pi.lane.name": "main",
177
+ "pi.operation.id": "operation",
178
+ "pi.checkpoint.kind": "normal",
179
+ },
180
+ (span) => {
181
+ // @ts-expect-error empty end schemas reject every attribute
182
+ span.setAttributes({ "pi.unknown": true });
183
+ },
184
+ context,
185
+ );
186
+ void startHarnessSpan(
187
+ "pi.harness.run",
188
+ {
189
+ "pi.session.id": "session",
190
+ "pi.lane.name": "main",
191
+ "pi.operation.id": "operation",
192
+ // @ts-expect-error run spans accept only the run operation kind
193
+ "pi.operation.kind": "navigation",
194
+ "pi.operation.recovery": false,
195
+ },
196
+ () => {},
197
+ context,
198
+ );
199
+ // @ts-expect-error missing required run start attributes
200
+ void startHarnessSpan("pi.harness.run", {}, () => {}, context);
201
+ };
202
+ expectTypeOf(compileTimeFailures).toBeFunction();
203
+ });
204
+ });
packages/agent/test/harness/text-line-reader.test.ts ADDED
@@ -0,0 +1,120 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { mkdtemp, rm, writeFile } from "node:fs/promises";
2
+ import { tmpdir } from "node:os";
3
+ import { join } from "node:path";
4
+ import { afterEach, beforeEach, describe, expect, it } from "vitest";
5
+ import { BACKGROUND_CONTEXT, withAbortSignal } from "../../src/harness/context.ts";
6
+ import { NodeExecutionEnv } from "../../src/harness/env/nodejs.ts";
7
+ import { getOrThrow, type TextLine, type TextLineReader } from "../../src/harness/types.ts";
8
+
9
+ let root: string;
10
+ let env: NodeExecutionEnv;
11
+ const readers: TextLineReader[] = [];
12
+
13
+ beforeEach(async () => {
14
+ root = await mkdtemp(join(tmpdir(), "pi-text-line-reader-"));
15
+ env = new NodeExecutionEnv({ cwd: root });
16
+ });
17
+
18
+ afterEach(async () => {
19
+ await Promise.all(readers.splice(0).map((reader) => reader.close(BACKGROUND_CONTEXT)));
20
+ await rm(root, { recursive: true, force: true });
21
+ });
22
+
23
+ async function openReader(content: string | Uint8Array): Promise<TextLineReader> {
24
+ await writeFile(join(root, "text.txt"), content);
25
+ const reader = getOrThrow(await env.openTextLineReader("text.txt", BACKGROUND_CONTEXT));
26
+ readers.push(reader);
27
+ return reader;
28
+ }
29
+
30
+ async function readLines(reader: TextLineReader): Promise<TextLine[]> {
31
+ const lines: TextLine[] = [];
32
+ while (true) {
33
+ const line = getOrThrow(await reader.readLine(BACKGROUND_CONTEXT));
34
+ if (line === undefined) return lines;
35
+ lines.push(line);
36
+ }
37
+ }
38
+
39
+ describe("TextLineReader", () => {
40
+ it("decodes Unicode, blank lines, and a torn final line", async () => {
41
+ const reader = await openReader("hé🙂\n\n\n終\ntorn");
42
+ expect(await readLines(reader)).toEqual([
43
+ { text: "hé🙂", terminated: true },
44
+ { text: "", terminated: true },
45
+ { text: "", terminated: true },
46
+ { text: "終", terminated: true },
47
+ { text: "torn", terminated: false },
48
+ ]);
49
+ expect(getOrThrow(await reader.readLine(BACKGROUND_CONTEXT))).toBeUndefined();
50
+ });
51
+
52
+ it("reads an empty file", async () => {
53
+ const reader = await openReader("");
54
+ expect(await readLines(reader)).toEqual([]);
55
+ });
56
+
57
+ it("decodes multibyte characters split across 64 KiB chunks", async () => {
58
+ const first = `${"a".repeat(64 * 1024 - 1)}🙂${"é".repeat(40_000)}\n`;
59
+ const reader = await openReader(`${first}終`);
60
+ expect(await readLines(reader)).toEqual([
61
+ { text: first.slice(0, -1), terminated: true },
62
+ { text: "終", terminated: false },
63
+ ]);
64
+ });
65
+
66
+ it("replaces malformed and incomplete UTF-8", async () => {
67
+ const reader = await openReader(new Uint8Array([0xff, 0x0a, 0xe2, 0x82]));
68
+ expect(await readLines(reader)).toEqual([
69
+ { text: "�", terminated: true },
70
+ { text: "�", terminated: false },
71
+ ]);
72
+ });
73
+
74
+ it("rejects an open with a pre-aborted context", async () => {
75
+ await writeFile(join(root, "text.txt"), "one\n");
76
+ const controller = new AbortController();
77
+ controller.abort();
78
+ const context = withAbortSignal(controller.signal, BACKGROUND_CONTEXT);
79
+ expect(await env.openTextLineReader("text.txt", context)).toMatchObject({
80
+ ok: false,
81
+ error: { code: "aborted" },
82
+ });
83
+ });
84
+
85
+ it("does not consume a buffered line when its context is pre-aborted", async () => {
86
+ const reader = await openReader("one\ntwo\n");
87
+ getOrThrow(await reader.readLine(BACKGROUND_CONTEXT));
88
+ const controller = new AbortController();
89
+ controller.abort();
90
+ const context = withAbortSignal(controller.signal, BACKGROUND_CONTEXT);
91
+ expect(await reader.readLine(context)).toMatchObject({ ok: false, error: { code: "aborted" } });
92
+ expect(getOrThrow(await reader.readLine(BACKGROUND_CONTEXT))?.text).toBe("two");
93
+ });
94
+
95
+ it("honors cancellation during a read and allows retry", async () => {
96
+ const reader = await openReader(`${"é".repeat(70_000)}\nlast`);
97
+ const controller = new AbortController();
98
+ const pending = reader.readLine(withAbortSignal(controller.signal, BACKGROUND_CONTEXT));
99
+ controller.abort();
100
+ expect(await pending).toMatchObject({ ok: false, error: { code: "aborted" } });
101
+ expect((await readLines(reader)).map((line) => line.text)).toEqual(["é".repeat(70_000), "last"]);
102
+ });
103
+
104
+ it("closes idempotently even with an aborted context and rejects later reads", async () => {
105
+ const reader = await openReader("one\ntwo\n");
106
+ getOrThrow(await reader.readLine(BACKGROUND_CONTEXT));
107
+ const controller = new AbortController();
108
+ controller.abort();
109
+ await expect(reader.close(withAbortSignal(controller.signal, BACKGROUND_CONTEXT))).resolves.toBeUndefined();
110
+ await expect(reader.close(BACKGROUND_CONTEXT)).resolves.toBeUndefined();
111
+ expect(await reader.readLine(BACKGROUND_CONTEXT)).toMatchObject({ ok: false, error: { code: "invalid" } });
112
+ });
113
+
114
+ it("returns a FileError for a missing file", async () => {
115
+ expect(await env.openTextLineReader("missing.txt", BACKGROUND_CONTEXT)).toMatchObject({
116
+ ok: false,
117
+ error: { code: "not_found", path: join(root, "missing.txt") },
118
+ });
119
+ });
120
+ });
packages/agent/test/harness/tools.test.ts ADDED
@@ -0,0 +1,782 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { symlink } from "node:fs/promises";
2
+ import { applyPatch } from "diff";
3
+ import { describe, expect, it, vi } from "vitest";
4
+ import { BACKGROUND_CONTEXT, type Context, withAbortSignal } from "../../src/harness/context.ts";
5
+ import { NodeExecutionEnv } from "../../src/harness/env/nodejs.ts";
6
+ import { type BashToolDetails, createBashTool } from "../../src/harness/tools/bash.ts";
7
+ import { createEditTool } from "../../src/harness/tools/edit.ts";
8
+ import { createReadTool } from "../../src/harness/tools/read.ts";
9
+ import { createWriteTool } from "../../src/harness/tools/write.ts";
10
+ import {
11
+ ExecutionError,
12
+ err,
13
+ type FileError,
14
+ getOrThrow,
15
+ ok,
16
+ type Result,
17
+ type ShellExecOptions,
18
+ type ShellExecResult,
19
+ } from "../../src/harness/types.ts";
20
+ import { DEFAULT_MAX_BYTES, DEFAULT_MAX_LINES, truncateTail } from "../../src/harness/utils/truncate.ts";
21
+ import { createTempDir } from "./session-test-utils.ts";
22
+
23
+ const noUpdate = () => {};
24
+
25
+ function textOutput(result: { content: Array<{ type: string; text?: string }> }): string {
26
+ return result.content.flatMap((part) => (part.type === "text" ? [part.text ?? ""] : [])).join("\n");
27
+ }
28
+
29
+ function createContext() {
30
+ const env = new NodeExecutionEnv({ cwd: createTempDir() });
31
+ return { env };
32
+ }
33
+
34
+ function deferred(): { promise: Promise<void>; resolve: () => void } {
35
+ let resolve = () => {};
36
+ const promise = new Promise<void>((resolvePromise) => {
37
+ resolve = resolvePromise;
38
+ });
39
+ return { promise, resolve };
40
+ }
41
+
42
+ function delay(ms: number): Promise<void> {
43
+ return new Promise((resolve) => setTimeout(resolve, ms));
44
+ }
45
+
46
+ class SlowReadExecutionEnv extends NodeExecutionEnv {
47
+ override async readTextFile(path: string, context: Context): Promise<Result<string, FileError>> {
48
+ await delay(20);
49
+ return super.readTextFile(path, context);
50
+ }
51
+ }
52
+
53
+ class BlockingWriteExecutionEnv extends NodeExecutionEnv {
54
+ readonly firstWriteStarted = deferred();
55
+ readonly finishFirstWrite = deferred();
56
+ secondWriteStarted = false;
57
+
58
+ override async writeFile(
59
+ path: string,
60
+ content: string | Uint8Array,
61
+ context: Context,
62
+ ): Promise<Result<void, FileError>> {
63
+ if (content === "first\n") {
64
+ this.firstWriteStarted.resolve();
65
+ await this.finishFirstWrite.promise;
66
+ } else if (content === "second\n") {
67
+ this.secondWriteStarted = true;
68
+ }
69
+ return super.writeFile(path, content, context);
70
+ }
71
+ }
72
+
73
+ class BlockingEditExecutionEnv extends NodeExecutionEnv {
74
+ readonly firstEditWriteStarted = deferred();
75
+ readonly finishFirstEditWrite = deferred();
76
+ firstEditWriteSettled = false;
77
+ secondEditWriteStarted = false;
78
+
79
+ override async writeFile(
80
+ path: string,
81
+ content: string | Uint8Array,
82
+ context: Context,
83
+ ): Promise<Result<void, FileError>> {
84
+ if (content === "ALPHA\nbeta\n") {
85
+ this.firstEditWriteStarted.resolve();
86
+ await this.finishFirstEditWrite.promise;
87
+ const result = await super.writeFile(path, content, BACKGROUND_CONTEXT);
88
+ this.firstEditWriteSettled = true;
89
+ return result;
90
+ }
91
+ if (content === "ALPHA\nBETA\n" || content === "alpha\nBETA\n") {
92
+ this.secondEditWriteStarted = true;
93
+ }
94
+ return super.writeFile(path, content, context);
95
+ }
96
+ }
97
+
98
+ function fakeShellOutput(text: string, options: ShellExecOptions | undefined, spillPath?: string): ShellExecResult {
99
+ const limits = options?.capture?.limits ?? {
100
+ maxBytes: DEFAULT_MAX_BYTES,
101
+ maxLines: DEFAULT_MAX_LINES,
102
+ retain: "tail" as const,
103
+ };
104
+ const truncated = truncateTail(text, limits);
105
+ const { content, ...truncation } = truncated;
106
+ options?.onUpdate?.(
107
+ {
108
+ kind: "replace",
109
+ output: { text: content, truncation, ...(spillPath === undefined ? {} : { spillPath }) },
110
+ },
111
+ BACKGROUND_CONTEXT,
112
+ );
113
+ return { exitCode: 0, truncation, ...(spillPath === undefined ? {} : { spillPath }) };
114
+ }
115
+
116
+ class LateOutputExecutionEnv extends NodeExecutionEnv {
117
+ override async exec(
118
+ _command: string,
119
+ options: ShellExecOptions | undefined,
120
+ context: Context,
121
+ ): Promise<Result<ShellExecResult, ExecutionError>> {
122
+ const result = fakeShellOutput("before\n", options);
123
+ setTimeout(() => {
124
+ const truncation = truncateTail("before\nlate\n", options?.capture?.limits);
125
+ options?.onUpdate?.({ kind: "replace", output: { text: truncation.content, truncation } }, context);
126
+ }, 0);
127
+ return ok(result);
128
+ }
129
+ }
130
+
131
+ const TRUNCATED_OUTPUT_LINES = DEFAULT_MAX_LINES + 1;
132
+ const invocation = {
133
+ invocationId: "test-result",
134
+ operationId: "test-operation",
135
+ turnId: "test-turn",
136
+ getMemo: async () => undefined,
137
+ setMemo: async () => {},
138
+ };
139
+
140
+ class CheckpointOutputExecutionEnv extends NodeExecutionEnv {
141
+ override async exec(
142
+ _command: string,
143
+ options: ShellExecOptions | undefined,
144
+ _context: Context,
145
+ ): Promise<Result<ShellExecResult, ExecutionError>> {
146
+ fakeShellOutput("one\n", options);
147
+ await delay(2_100);
148
+ fakeShellOutput("one\ntwo\n", options);
149
+ await delay(100);
150
+ fakeShellOutput("one\ntwo\nthree\n", options);
151
+ await delay(2_000);
152
+ return ok(fakeShellOutput("one\ntwo\nthree\nfour\n", options));
153
+ }
154
+ }
155
+
156
+ class TimeoutOutputExecutionEnv extends NodeExecutionEnv {
157
+ override async exec(
158
+ _command: string,
159
+ options: ShellExecOptions | undefined,
160
+ context: Context,
161
+ ): Promise<Result<ShellExecResult, ExecutionError>> {
162
+ const output = `${Array.from({ length: TRUNCATED_OUTPUT_LINES }, (_, index) => `line-${index + 1}`).join("\n")}\n`;
163
+ const spillPath = getOrThrow(await this.createTempFile({ prefix: "timeout-", suffix: ".log" }, context));
164
+ getOrThrow(await this.writeFile(spillPath, output, context));
165
+ fakeShellOutput(output, options, spillPath);
166
+ return err(new ExecutionError("timeout", `timeout:${options?.timeout}`));
167
+ }
168
+ }
169
+
170
+ function createTinyBmp(): Uint8Array {
171
+ const bytes = new Uint8Array(58);
172
+ const view = new DataView(bytes.buffer);
173
+ bytes[0] = 0x42;
174
+ bytes[1] = 0x4d;
175
+ view.setUint32(2, bytes.length, true);
176
+ view.setUint32(10, 54, true);
177
+ view.setUint32(14, 40, true);
178
+ view.setInt32(18, 1, true);
179
+ view.setInt32(22, 1, true);
180
+ view.setUint16(26, 1, true);
181
+ view.setUint16(28, 24, true);
182
+ view.setUint32(34, 4, true);
183
+ return bytes;
184
+ }
185
+
186
+ describe("AgentHarness tools", () => {
187
+ describe("read", () => {
188
+ it("reads text with offsets, limits, and continuation notices", async () => {
189
+ const context = createContext();
190
+ getOrThrow(
191
+ await context.env.writeFile(
192
+ "test.txt",
193
+ Array.from({ length: 100 }, (_, index) => `Line ${index + 1}`).join("\n"),
194
+ BACKGROUND_CONTEXT,
195
+ ),
196
+ );
197
+
198
+ const result = await createReadTool().execute(
199
+ "read-1",
200
+ { path: "test.txt", offset: 41, limit: 20 },
201
+ noUpdate,
202
+ context,
203
+ invocation,
204
+ BACKGROUND_CONTEXT,
205
+ );
206
+ const output = textOutput(result);
207
+
208
+ expect(output).not.toContain("Line 40");
209
+ expect(output).toContain("Line 41");
210
+ expect(output).toContain("Line 60");
211
+ expect(output).not.toContain("Line 61");
212
+ expect(output).toContain("[40 more lines in file. Use offset=61 to continue.]");
213
+ });
214
+
215
+ it("truncates large text by line count", async () => {
216
+ const context = createContext();
217
+ getOrThrow(
218
+ await context.env.writeFile(
219
+ "large.txt",
220
+ Array.from({ length: 2500 }, (_, index) => `Line ${index + 1}`).join("\n"),
221
+ BACKGROUND_CONTEXT,
222
+ ),
223
+ );
224
+
225
+ const result = await createReadTool().execute(
226
+ "read-2",
227
+ { path: "large.txt" },
228
+ noUpdate,
229
+ context,
230
+ invocation,
231
+ BACKGROUND_CONTEXT,
232
+ );
233
+
234
+ expect(textOutput(result)).toContain("[Showing lines 1-2000 of 2500. Use offset=2001 to continue.]");
235
+ expect(result.details?.truncation).toMatchObject({
236
+ truncated: true,
237
+ truncatedBy: "lines",
238
+ totalLines: 2500,
239
+ outputLines: 2000,
240
+ });
241
+ });
242
+
243
+ it("does not count a trailing newline as an extra line at the truncation limit", async () => {
244
+ const context = createContext();
245
+ getOrThrow(
246
+ await context.env.writeFile(
247
+ "exact.txt",
248
+ `${Array.from({ length: 2000 }, () => "x").join("\n")}\n`,
249
+ BACKGROUND_CONTEXT,
250
+ ),
251
+ );
252
+
253
+ const result = await createReadTool().execute(
254
+ "read-exact",
255
+ { path: "exact.txt" },
256
+ noUpdate,
257
+ context,
258
+ invocation,
259
+ BACKGROUND_CONTEXT,
260
+ );
261
+
262
+ expect(result.details).toBeUndefined();
263
+ expect(textOutput(result)).not.toContain("Use offset=");
264
+ });
265
+
266
+ it("rejects offsets beyond the file", async () => {
267
+ const context = createContext();
268
+ getOrThrow(await context.env.writeFile("short.txt", "one\ntwo\nthree", BACKGROUND_CONTEXT));
269
+
270
+ await expect(
271
+ createReadTool().execute(
272
+ "read-3",
273
+ { path: "short.txt", offset: 100 },
274
+ noUpdate,
275
+ context,
276
+ invocation,
277
+ BACKGROUND_CONTEXT,
278
+ ),
279
+ ).rejects.toThrow("Offset 100 is beyond end of file (3 lines total)");
280
+ });
281
+
282
+ it("detects supported images by content", async () => {
283
+ const context = createContext();
284
+ const png = Uint8Array.from(
285
+ Buffer.from(
286
+ "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR4nGNgYGD4DwABBAEAX+XDSwAAAABJRU5ErkJggg==",
287
+ "base64",
288
+ ),
289
+ );
290
+ getOrThrow(await context.env.writeFile("image.txt", png, BACKGROUND_CONTEXT));
291
+
292
+ const result = await createReadTool().execute(
293
+ "read-4",
294
+ { path: "image.txt" },
295
+ noUpdate,
296
+ context,
297
+ invocation,
298
+ BACKGROUND_CONTEXT,
299
+ );
300
+
301
+ expect(textOutput(result)).toContain("Read image file [image/png]");
302
+ expect(result.content).toContainEqual({
303
+ type: "image",
304
+ data: Buffer.from(png).toString("base64"),
305
+ mimeType: "image/png",
306
+ });
307
+ });
308
+
309
+ it("delegates image conversion and resizing to an injected processor", async () => {
310
+ const context = createContext();
311
+ const bmp = createTinyBmp();
312
+ getOrThrow(await context.env.writeFile("image.bmp", bmp, BACKGROUND_CONTEXT));
313
+ let received: { bytes: Uint8Array; mimeType: string; autoResizeImages: boolean } | undefined;
314
+ const tool = createReadTool({
315
+ autoResizeImages: false,
316
+ imageProcessor: async (bytes, mimeType, options) => {
317
+ received = { bytes, mimeType, autoResizeImages: options.autoResizeImages };
318
+ return {
319
+ ok: true,
320
+ data: "converted",
321
+ mimeType: "image/png",
322
+ hints: ["[Image converted from image/bmp to image/png.]"],
323
+ };
324
+ },
325
+ });
326
+
327
+ const result = await tool.execute(
328
+ "read-bmp",
329
+ { path: "image.bmp" },
330
+ noUpdate,
331
+ context,
332
+ invocation,
333
+ BACKGROUND_CONTEXT,
334
+ );
335
+
336
+ expect(received).toMatchObject({ mimeType: "image/bmp", autoResizeImages: false });
337
+ expect(Array.from(received?.bytes ?? [])).toEqual(Array.from(bmp));
338
+ expect(textOutput(result)).toContain("[Image converted from image/bmp to image/png.]");
339
+ expect(result.content).toContainEqual({ type: "image", data: "converted", mimeType: "image/png" });
340
+ });
341
+ });
342
+
343
+ describe("write", () => {
344
+ it("writes files and creates parent directories", async () => {
345
+ const context = createContext();
346
+ const result = await createWriteTool().execute(
347
+ "write-1",
348
+ { path: "nested/dir/file.txt", content: "hello" },
349
+ noUpdate,
350
+ context,
351
+ invocation,
352
+ BACKGROUND_CONTEXT,
353
+ );
354
+
355
+ expect(textOutput(result)).toBe("Successfully wrote to nested/dir/file.txt");
356
+ expect(getOrThrow(await context.env.readTextFile("nested/dir/file.txt", BACKGROUND_CONTEXT))).toBe("hello");
357
+ });
358
+
359
+ it("keeps the mutation queue locked until an aborted write settles", async () => {
360
+ const env = new BlockingWriteExecutionEnv({ cwd: createTempDir() });
361
+ const tool = createWriteTool();
362
+ const controller = new AbortController();
363
+ const firstWrite = tool.execute(
364
+ "write-first",
365
+ { path: "file.txt", content: "first\n" },
366
+ noUpdate,
367
+ {
368
+ env,
369
+ },
370
+ invocation,
371
+ withAbortSignal(controller.signal, BACKGROUND_CONTEXT),
372
+ );
373
+ await env.firstWriteStarted.promise;
374
+ controller.abort();
375
+ const secondWrite = tool.execute(
376
+ "write-second",
377
+ { path: "file.txt", content: "second\n" },
378
+ noUpdate,
379
+ { env },
380
+ invocation,
381
+ BACKGROUND_CONTEXT,
382
+ );
383
+
384
+ await delay(20);
385
+ expect(env.secondWriteStarted).toBe(false);
386
+ env.finishFirstWrite.resolve();
387
+ await expect(firstWrite).rejects.toThrow();
388
+ await secondWrite;
389
+ expect(getOrThrow(await env.readTextFile("file.txt", BACKGROUND_CONTEXT))).toBe("second\n");
390
+ });
391
+ });
392
+
393
+ describe("edit", () => {
394
+ it("applies disjoint edits and returns both diff formats", async () => {
395
+ const context = createContext();
396
+ const original = "alpha\nbeta\ngamma\ndelta\n";
397
+ getOrThrow(await context.env.writeFile("edit.txt", original, BACKGROUND_CONTEXT));
398
+
399
+ const result = await createEditTool().execute(
400
+ "edit-1",
401
+ {
402
+ path: "edit.txt",
403
+ edits: [
404
+ { oldText: "alpha\n", newText: "ALPHA\n" },
405
+ { oldText: "gamma\n", newText: "GAMMA\n" },
406
+ ],
407
+ },
408
+ noUpdate,
409
+ context,
410
+ invocation,
411
+ BACKGROUND_CONTEXT,
412
+ );
413
+
414
+ expect(textOutput(result)).toBe("Successfully replaced 2 block(s) in edit.txt.");
415
+ expect(result.details?.diff).toContain("ALPHA");
416
+ expect(result.details?.diff).toContain("GAMMA");
417
+ expect(applyPatch(original, result.details?.patch ?? "")).toBe("ALPHA\nbeta\nGAMMA\ndelta\n");
418
+ expect(getOrThrow(await context.env.readTextFile("edit.txt", BACKGROUND_CONTEXT))).toBe(
419
+ "ALPHA\nbeta\nGAMMA\ndelta\n",
420
+ );
421
+ });
422
+
423
+ it("matches all edits against the original and rejects overlaps", async () => {
424
+ const context = createContext();
425
+ getOrThrow(await context.env.writeFile("edit.txt", "one\ntwo\nthree\n", BACKGROUND_CONTEXT));
426
+
427
+ await expect(
428
+ createEditTool().execute(
429
+ "edit-2",
430
+ {
431
+ path: "edit.txt",
432
+ edits: [
433
+ { oldText: "one\ntwo\n", newText: "ONE\nTWO\n" },
434
+ { oldText: "two\nthree\n", newText: "TWO\nTHREE\n" },
435
+ ],
436
+ },
437
+ noUpdate,
438
+ context,
439
+ invocation,
440
+ BACKGROUND_CONTEXT,
441
+ ),
442
+ ).rejects.toThrow(/overlap/);
443
+ expect(getOrThrow(await context.env.readTextFile("edit.txt", BACKGROUND_CONTEXT))).toBe("one\ntwo\nthree\n");
444
+ });
445
+
446
+ it("rejects missing and duplicate target text", async () => {
447
+ const context = createContext();
448
+ getOrThrow(await context.env.writeFile("edit.txt", "foo foo foo", BACKGROUND_CONTEXT));
449
+ const tool = createEditTool();
450
+
451
+ await expect(
452
+ tool.execute(
453
+ "edit-3",
454
+ { path: "edit.txt", edits: [{ oldText: "bar", newText: "baz" }] },
455
+ noUpdate,
456
+ context,
457
+ invocation,
458
+ BACKGROUND_CONTEXT,
459
+ ),
460
+ ).rejects.toThrow(/Could not find the exact text/);
461
+ await expect(
462
+ tool.execute(
463
+ "edit-4",
464
+ { path: "edit.txt", edits: [{ oldText: "foo", newText: "bar" }] },
465
+ noUpdate,
466
+ context,
467
+ invocation,
468
+ BACKGROUND_CONTEXT,
469
+ ),
470
+ ).rejects.toThrow(/Found 3 occurrences/);
471
+ });
472
+
473
+ it("keeps the mutation queue locked until an aborted edit write settles", async () => {
474
+ const env = new BlockingEditExecutionEnv({ cwd: createTempDir() });
475
+ getOrThrow(await env.writeFile("file.txt", "alpha\nbeta\n", BACKGROUND_CONTEXT));
476
+ const tool = createEditTool();
477
+ const controller = new AbortController();
478
+ const firstEdit = tool.execute(
479
+ "edit-first",
480
+ { path: "file.txt", edits: [{ oldText: "alpha", newText: "ALPHA" }] },
481
+ noUpdate,
482
+ { env },
483
+ invocation,
484
+ withAbortSignal(controller.signal, BACKGROUND_CONTEXT),
485
+ );
486
+ await env.firstEditWriteStarted.promise;
487
+ controller.abort();
488
+ const secondEdit = tool.execute(
489
+ "edit-second",
490
+ { path: "file.txt", edits: [{ oldText: "beta", newText: "BETA" }] },
491
+ noUpdate,
492
+ { env },
493
+ invocation,
494
+ BACKGROUND_CONTEXT,
495
+ );
496
+
497
+ await delay(20);
498
+ expect(env.secondEditWriteStarted).toBe(false);
499
+ env.finishFirstEditWrite.resolve();
500
+ await expect(firstEdit).rejects.toThrow("Operation aborted");
501
+ await secondEdit;
502
+ expect(env.firstEditWriteSettled).toBe(true);
503
+ expect(getOrThrow(await env.readTextFile("file.txt", BACKGROUND_CONTEXT))).toBe("ALPHA\nBETA\n");
504
+ });
505
+
506
+ it("serializes concurrent edits through canonical and symlink paths", async () => {
507
+ const env = new SlowReadExecutionEnv({ cwd: createTempDir() });
508
+ getOrThrow(await env.writeFile("target.txt", "alpha\nbeta\ngamma\n", BACKGROUND_CONTEXT));
509
+ await symlink("target.txt", `${env.cwd}/link.txt`);
510
+ const tool = createEditTool();
511
+
512
+ await Promise.all([
513
+ tool.execute(
514
+ "edit-target",
515
+ { path: "target.txt", edits: [{ oldText: "alpha", newText: "ALPHA" }] },
516
+ noUpdate,
517
+ { env },
518
+ invocation,
519
+ BACKGROUND_CONTEXT,
520
+ ),
521
+ tool.execute(
522
+ "edit-link",
523
+ { path: "link.txt", edits: [{ oldText: "beta", newText: "BETA" }] },
524
+ noUpdate,
525
+ { env },
526
+ invocation,
527
+ BACKGROUND_CONTEXT,
528
+ ),
529
+ ]);
530
+
531
+ expect(getOrThrow(await env.readTextFile("target.txt", BACKGROUND_CONTEXT))).toBe("ALPHA\nBETA\ngamma\n");
532
+ });
533
+
534
+ it("edits regular files through symlinks", async () => {
535
+ const context = createContext();
536
+ getOrThrow(await context.env.writeFile("target.txt", "before\n", BACKGROUND_CONTEXT));
537
+ await symlink("target.txt", `${context.env.cwd}/link.txt`);
538
+
539
+ await createEditTool().execute(
540
+ "edit-symlink",
541
+ { path: "link.txt", edits: [{ oldText: "before", newText: "after" }] },
542
+ noUpdate,
543
+ context,
544
+ invocation,
545
+ BACKGROUND_CONTEXT,
546
+ );
547
+
548
+ expect(getOrThrow(await context.env.readTextFile("target.txt", BACKGROUND_CONTEXT))).toBe("after\n");
549
+ });
550
+
551
+ it("preserves BOM and CRLF line endings", async () => {
552
+ const context = createContext();
553
+ getOrThrow(await context.env.writeFile("edit.txt", "\uFEFFone\r\ntwo\r\n", BACKGROUND_CONTEXT));
554
+
555
+ await createEditTool().execute(
556
+ "edit-5",
557
+ { path: "edit.txt", edits: [{ oldText: "two", newText: "TWO" }] },
558
+ noUpdate,
559
+ context,
560
+ invocation,
561
+ BACKGROUND_CONTEXT,
562
+ );
563
+
564
+ expect(getOrThrow(await context.env.readTextFile("edit.txt", BACKGROUND_CONTEXT))).toBe(
565
+ "\uFEFFone\r\nTWO\r\n",
566
+ );
567
+ });
568
+ });
569
+
570
+ describe("bash", () => {
571
+ it("executes commands and combines stdout and stderr", async () => {
572
+ const context = createContext();
573
+ const result = await createBashTool().execute(
574
+ "bash-1",
575
+ { command: "printf out; printf err >&2" },
576
+ noUpdate,
577
+ context,
578
+ invocation,
579
+ BACKGROUND_CONTEXT,
580
+ );
581
+
582
+ expect(textOutput(result)).toContain("out");
583
+ expect(textOutput(result)).toContain("err");
584
+ });
585
+
586
+ it("reports nonzero exits and timeouts", async () => {
587
+ const context = createContext();
588
+ const tool = createBashTool();
589
+
590
+ await expect(
591
+ tool.execute(
592
+ "bash-2",
593
+ { command: "printf failed; exit 7" },
594
+ noUpdate,
595
+ context,
596
+ invocation,
597
+ BACKGROUND_CONTEXT,
598
+ ),
599
+ ).rejects.toThrow(/failed[\s\S]*Command exited with code 7/);
600
+ await expect(
601
+ tool.execute(
602
+ "bash-3",
603
+ { command: "sleep 2", timeout: 0.01 },
604
+ noUpdate,
605
+ context,
606
+ invocation,
607
+ BACKGROUND_CONTEXT,
608
+ ),
609
+ ).rejects.toThrow(/Command timed out after 0.01 seconds/);
610
+ });
611
+
612
+ it("preserves truncated output when a command times out", async () => {
613
+ const context = { env: new TimeoutOutputExecutionEnv({ cwd: createTempDir() }) };
614
+ let error: unknown;
615
+ try {
616
+ await createBashTool().execute(
617
+ "bash-timeout-output",
618
+ { command: "emit-output-then-time-out", timeout: 0.05 },
619
+ noUpdate,
620
+ context,
621
+ invocation,
622
+ BACKGROUND_CONTEXT,
623
+ );
624
+ } catch (cause) {
625
+ error = cause;
626
+ }
627
+
628
+ expect(error).toBeInstanceOf(Error);
629
+ const message = (error as Error).message;
630
+ expect(message).toContain("Command timed out after 0.05 seconds");
631
+ const fullOutputPath = message.match(/Full output: ([^\]\n]+)/)?.[1];
632
+ expect(fullOutputPath).toBeDefined();
633
+ const fullOutput = getOrThrow(await context.env.readTextFile(fullOutputPath!, BACKGROUND_CONTEXT));
634
+ expect(fullOutput).toContain("line-1\nline-2");
635
+ expect(fullOutput).toContain(`line-${DEFAULT_MAX_LINES}\nline-${TRUNCATED_OUTPUT_LINES}`);
636
+ });
637
+
638
+ it("ignores output callbacks after execution settles", async () => {
639
+ const env = new LateOutputExecutionEnv({ cwd: createTempDir() });
640
+ const updates: string[] = [];
641
+ const result = await createBashTool().execute(
642
+ "bash-late",
643
+ { command: "late" },
644
+ (update) => updates.push(textOutput(update)),
645
+ { env },
646
+ invocation,
647
+ BACKGROUND_CONTEXT,
648
+ );
649
+ await new Promise((resolve) => setTimeout(resolve, 20));
650
+
651
+ expect(textOutput(result)).toBe("before\n");
652
+ expect(updates.some((update) => update.includes("late"))).toBe(false);
653
+ });
654
+
655
+ it("reports the total size of an oversized final line", async () => {
656
+ const context = createContext();
657
+ const result = await createBashTool().execute(
658
+ "bash-long-line",
659
+ { command: "printf '%060000d' 0" },
660
+ noUpdate,
661
+ context,
662
+ invocation,
663
+ BACKGROUND_CONTEXT,
664
+ );
665
+
666
+ expect(textOutput(result)).toMatch(/Showing last 50\.0KB of line 1 \(line is 58\.6KB\)\. Full output:/);
667
+ });
668
+
669
+ it("prepares command, cwd, and an explicit environment with the turn context", async () => {
670
+ const env = new NodeExecutionEnv({
671
+ cwd: createTempDir(),
672
+ shellEnv: { PI_BASH_PREPARE_INHERITED: "inherited" },
673
+ });
674
+ getOrThrow(await env.createDir("workspace", undefined, BACKGROUND_CONTEXT));
675
+ const context = { env, workspace: `${env.cwd}/workspace` };
676
+ const controller = new AbortController();
677
+ let receivedContext: typeof context | undefined;
678
+ let receivedSignal: AbortSignal | undefined;
679
+ const tool = createBashTool<typeof context>({
680
+ commandPrefix: "prefix=ready",
681
+ prepare: async (execution, turnContext, callContext) => {
682
+ receivedContext = turnContext;
683
+ receivedSignal = callContext.abortSignal;
684
+ execution.cwd = turnContext.workspace;
685
+ execution.env = { PI_BASH_PREPARE_EXPLICIT: "explicit" };
686
+ execution.inheritEnv = false;
687
+ execution.command += `\nprintf '%s:%s:%s:%s' "$prefix" "\${PI_BASH_PREPARE_INHERITED-}" "$PI_BASH_PREPARE_EXPLICIT" "$PWD"`;
688
+ },
689
+ });
690
+
691
+ const result = await tool.execute(
692
+ "bash-prepare",
693
+ { command: ":" },
694
+ noUpdate,
695
+ context,
696
+ invocation,
697
+ withAbortSignal(controller.signal, BACKGROUND_CONTEXT),
698
+ );
699
+
700
+ expect(receivedContext).toBe(context);
701
+ expect(receivedSignal).toBe(controller.signal);
702
+ expect(textOutput(result)).toBe(
703
+ `ready::explicit:${getOrThrow(await env.canonicalPath(context.workspace, BACKGROUND_CONTEXT))}`,
704
+ );
705
+ });
706
+
707
+ it("supports command prefixes", async () => {
708
+ const context = createContext();
709
+ const result = await createBashTool({ commandPrefix: "value=hello" }).execute(
710
+ "bash-4",
711
+ { command: "printf $value" },
712
+ noUpdate,
713
+ context,
714
+ invocation,
715
+ BACKGROUND_CONTEXT,
716
+ );
717
+
718
+ expect(textOutput(result)).toBe("hello");
719
+ });
720
+
721
+ it("requests distinct bounded checkpoints at most every two seconds", async () => {
722
+ vi.useFakeTimers({ now: 0 });
723
+ try {
724
+ const env = new CheckpointOutputExecutionEnv({ cwd: createTempDir() });
725
+ const checkpoints: string[] = [];
726
+ const execution = createBashTool().execute(
727
+ "bash-checkpoints",
728
+ { command: "controlled" },
729
+ (update, options) => {
730
+ if (options?.checkpoint === true) checkpoints.push(textOutput(update));
731
+ },
732
+ { env },
733
+ invocation,
734
+ BACKGROUND_CONTEXT,
735
+ );
736
+ await vi.advanceTimersByTimeAsync(4_500);
737
+ await execution;
738
+
739
+ expect(checkpoints).toEqual(["one\ntwo\n", "one\ntwo\nthree\nfour\n"]);
740
+ } finally {
741
+ vi.useRealTimers();
742
+ }
743
+ });
744
+
745
+ it("coalesces updates and persists truncated full output", async () => {
746
+ const context = createContext();
747
+ const updates: Array<{
748
+ content: Array<{ type: "text"; text: string } | { type: "image"; data: string; mimeType: string }>;
749
+ details?: BashToolDetails;
750
+ }> = [];
751
+ const result = await createBashTool().execute(
752
+ "bash-5",
753
+ { command: "i=1; while [ $i -le 3000 ]; do echo line-$i; i=$((i + 1)); done" },
754
+ (update) => updates.push(update),
755
+ context,
756
+ invocation,
757
+ BACKGROUND_CONTEXT,
758
+ );
759
+
760
+ expect(updates.length).toBeLessThan(25);
761
+ expect(result.details?.truncation).toMatchObject({
762
+ truncated: true,
763
+ truncatedBy: "lines",
764
+ totalLines: 3000,
765
+ outputLines: 2000,
766
+ });
767
+ expect(textOutput(result)).toContain("line-3000");
768
+ expect(result.details?.fullOutputPath).toBeDefined();
769
+ const finalUpdate = updates.at(-1);
770
+ expect(finalUpdate ? textOutput(finalUpdate) : "").toContain("line-3000");
771
+ expect(finalUpdate?.details).toMatchObject({
772
+ truncation: { totalLines: 3000, totalBytes: expect.any(Number) },
773
+ fullOutputPath: result.details?.fullOutputPath,
774
+ });
775
+ const fullOutput = getOrThrow(
776
+ await context.env.readTextFile(result.details!.fullOutputPath!, BACKGROUND_CONTEXT),
777
+ );
778
+ expect(fullOutput).toContain("line-1\nline-2");
779
+ expect(fullOutput).toContain("line-2999\nline-3000");
780
+ });
781
+ });
782
+ });
packages/agent/test/harness/truncate.test.ts ADDED
@@ -0,0 +1,178 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { describe, expect, it } from "vitest";
2
+ import { truncateHead, truncateTail } from "../../src/harness/utils/truncate.ts";
3
+
4
+ const encoder = new TextEncoder();
5
+
6
+ function byteLength(content: string): number {
7
+ return encoder.encode(content).length;
8
+ }
9
+
10
+ function bufferTail(content: string, maxBytes: number): string {
11
+ const bytes = Buffer.from(content, "utf8");
12
+ if (bytes.length <= maxBytes) return content;
13
+ let start = bytes.length - maxBytes;
14
+ while (start < bytes.length && (bytes[start] & 0xc0) === 0x80) start++;
15
+ return bytes.subarray(start).toString("utf8");
16
+ }
17
+
18
+ function assertMatchesBufferTail(input: string, maxByteValues?: readonly number[]): void {
19
+ const totalBytes = Buffer.byteLength(input, "utf8");
20
+ const values = maxByteValues ?? Array.from({ length: totalBytes + 5 }, (_, maxBytes) => maxBytes);
21
+ for (const maxBytes of values) {
22
+ const result = truncateTail(input, { maxBytes, maxLines: 10 });
23
+ const expected = bufferTail(input, maxBytes);
24
+ if (result.content !== expected) {
25
+ throw new Error(
26
+ `tail mismatch input=${JSON.stringify(input)} maxBytes=${maxBytes} expected=${JSON.stringify(expected)} actual=${JSON.stringify(result.content)}`,
27
+ );
28
+ }
29
+ const outputBytes = Buffer.byteLength(result.content, "utf8");
30
+ if (outputBytes > maxBytes) {
31
+ throw new Error(
32
+ `tail output exceeded byte limit input=${JSON.stringify(input)} maxBytes=${maxBytes} outputBytes=${outputBytes}`,
33
+ );
34
+ }
35
+ }
36
+ }
37
+
38
+ function sampledByteLimits(input: string): number[] {
39
+ const totalBytes = Buffer.byteLength(input, "utf8");
40
+ const candidates = [
41
+ 0,
42
+ 1,
43
+ 2,
44
+ 3,
45
+ 4,
46
+ 5,
47
+ 8,
48
+ Math.floor(totalBytes / 2) - 1,
49
+ Math.floor(totalBytes / 2),
50
+ Math.floor(totalBytes / 2) + 1,
51
+ totalBytes - 8,
52
+ totalBytes - 5,
53
+ totalBytes - 4,
54
+ totalBytes - 3,
55
+ totalBytes - 2,
56
+ totalBytes - 1,
57
+ totalBytes,
58
+ totalBytes + 1,
59
+ totalBytes + 4,
60
+ ];
61
+ return [...new Set(candidates.filter((value) => value >= 0))].sort((a, b) => a - b);
62
+ }
63
+
64
+ describe("truncate utilities", () => {
65
+ it("counts UTF-8 bytes without Node Buffer", () => {
66
+ const content = "aé🙂\nb";
67
+ const result = truncateHead(content, { maxBytes: 100, maxLines: 10 });
68
+
69
+ expect(result.truncated).toBe(false);
70
+ expect(result.totalBytes).toBe(byteLength(content));
71
+ expect(result.outputBytes).toBe(byteLength(content));
72
+ expect(result.totalBytes).toBe(9);
73
+ });
74
+
75
+ it("does not count a trailing newline as an extra line", () => {
76
+ const content = `${Array.from({ length: 3 }, () => "line").join("\n")}\n`;
77
+ const head = truncateHead(content, { maxBytes: 100, maxLines: 3 });
78
+ const tail = truncateTail(content, { maxBytes: 100, maxLines: 3 });
79
+
80
+ expect(head).toMatchObject({ truncated: false, totalLines: 3, outputLines: 3 });
81
+ expect(tail).toMatchObject({ truncated: false, totalLines: 3, outputLines: 3 });
82
+ });
83
+
84
+ it("truncates head on UTF-8 byte limits without partial lines", () => {
85
+ const content = "éé\nabc";
86
+ const result = truncateHead(content, { maxBytes: 4, maxLines: 10 });
87
+
88
+ expect(result.content).toBe("éé");
89
+ expect(result.truncated).toBe(true);
90
+ expect(result.truncatedBy).toBe("bytes");
91
+ expect(result.outputBytes).toBe(4);
92
+ expect(result.firstLineExceedsLimit).toBe(false);
93
+ });
94
+
95
+ it("reports head truncation when the first line exceeds the byte limit", () => {
96
+ const result = truncateHead("éé\nabc", { maxBytes: 3, maxLines: 10 });
97
+
98
+ expect(result.content).toBe("");
99
+ expect(result.truncated).toBe(true);
100
+ expect(result.truncatedBy).toBe("bytes");
101
+ expect(result.firstLineExceedsLimit).toBe(true);
102
+ });
103
+
104
+ it("truncates tail on UTF-8 boundaries when only a partial last line fits", () => {
105
+ const result = truncateTail("aé🙂b", { maxBytes: 5, maxLines: 10 });
106
+
107
+ expect(result.content).toBe("🙂b");
108
+ expect(result.truncated).toBe(true);
109
+ expect(result.truncatedBy).toBe("bytes");
110
+ expect(result.lastLinePartial).toBe(true);
111
+ expect(result.outputBytes).toBe(5);
112
+ });
113
+
114
+ it("truncates an oversized single line with a trailing newline", () => {
115
+ const input = `${"X".repeat(300_000)}\n`;
116
+ const result = truncateTail(input, { maxBytes: 1024, maxLines: 100 });
117
+
118
+ expect(result.content).toBe("X".repeat(1024));
119
+ expect(result.outputBytes).toBe(1024);
120
+ expect(result.outputLines).toBe(1);
121
+ expect(result.lastLinePartial).toBe(true);
122
+ expect(result.truncatedBy).toBe("bytes");
123
+ });
124
+
125
+ it("drops an oversized trailing character when it cannot fit in tail byte limit", () => {
126
+ const result = truncateTail("abc🙂", { maxBytes: 3, maxLines: 10 });
127
+
128
+ expect(result.content).toBe("");
129
+ expect(result.truncated).toBe(true);
130
+ expect(result.truncatedBy).toBe("bytes");
131
+ expect(result.lastLinePartial).toBe(true);
132
+ expect(result.outputBytes).toBe(0);
133
+ });
134
+
135
+ it("matches Buffer tail truncation semantics for surrogate edge cases", () => {
136
+ const inputs = ["a\ud83d", "\ude42b", "a\ude42b", "\ud83d\ud83d\ude42", "\ud83d\ude42\ude42", "👩‍💻"];
137
+ for (const input of inputs) assertMatchesBufferTail(input);
138
+ });
139
+
140
+ it("matches Buffer tail truncation semantics across deterministic fuzz cases", () => {
141
+ const alphabet = [
142
+ "a",
143
+ "\u007f",
144
+ "\u0080",
145
+ "é",
146
+ "\u07ff",
147
+ "\u0800",
148
+ "中",
149
+ "\ud7ff",
150
+ "\ud800",
151
+ "\ud83d",
152
+ "\udc00",
153
+ "\ude42",
154
+ "🙂",
155
+ "\ue000",
156
+ "\uffff",
157
+ ];
158
+
159
+ function checkExhaustive(prefix: string, depth: number): void {
160
+ assertMatchesBufferTail(prefix, sampledByteLimits(prefix));
161
+ if (depth === 0) return;
162
+ for (const character of alphabet) checkExhaustive(prefix + character, depth - 1);
163
+ }
164
+ checkExhaustive("", 3);
165
+
166
+ let seed = 0x12345678;
167
+ function random(): number {
168
+ seed = (seed * 1664525 + 1013904223) >>> 0;
169
+ return seed / 0x100000000;
170
+ }
171
+ for (let i = 0; i < 1_000; i++) {
172
+ let input = "";
173
+ const length = Math.floor(random() * 80);
174
+ for (let j = 0; j < length; j++) input += alphabet[Math.floor(random() * alphabet.length)];
175
+ assertMatchesBufferTail(input, sampledByteLimits(input));
176
+ }
177
+ });
178
+ });
packages/agent/test/harness/types.test.ts ADDED
@@ -0,0 +1,523 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import type { AssistantMessage, AssistantMessageFrame, DeferredHandle, Usage } from "@earendil-works/pi-ai";
2
+ import { expectTypeOf, it } from "vitest";
3
+ import * as storedValues from "../../src/harness/session/values.ts";
4
+ import type {
5
+ AgentHarness,
6
+ AgentHarnessOptions,
7
+ AgentHarnessStreamOptions,
8
+ AgentHarnessTool,
9
+ AgentHarnessToolInvocation,
10
+ AgentLane,
11
+ AgentMessage,
12
+ AgentTool,
13
+ Branch,
14
+ BranchScan,
15
+ CancelQueuedResult,
16
+ CheckpointData,
17
+ Context,
18
+ Control,
19
+ CustomEntry,
20
+ DriveOptions,
21
+ DriveOutcome,
22
+ DriveResult,
23
+ Entry,
24
+ EntryProjector,
25
+ EntryWrite,
26
+ GenerationContext,
27
+ HarnessEvent,
28
+ HookHandler,
29
+ HookMap,
30
+ HookName,
31
+ IdGenerator,
32
+ InboxItem,
33
+ LaneConfiguration,
34
+ LaneExecutionInfo,
35
+ LaneSnapshot,
36
+ LaneSnapshotTool,
37
+ NewEntry,
38
+ OperationAdmissionResult,
39
+ OperationAt,
40
+ OperationMeta,
41
+ OperationRequest,
42
+ OperationResultRecord,
43
+ OperationScope,
44
+ OperationState,
45
+ RunResult,
46
+ SearchQuery,
47
+ Session,
48
+ SessionCreateOptions,
49
+ SessionMetadata,
50
+ SessionMutation,
51
+ SessionMutator,
52
+ SessionReader,
53
+ SessionRepo,
54
+ SessionSearchHit,
55
+ SessionSearchService,
56
+ SessionSnapshot,
57
+ SessionStats,
58
+ SettledAssistantMessage,
59
+ Storage,
60
+ StorageBranchScan,
61
+ SummaryContext,
62
+ SuspendedRun,
63
+ TerminalStatus,
64
+ ToolCall,
65
+ UsageRow,
66
+ UsageWrite,
67
+ ValueSetWrite,
68
+ Write,
69
+ } from "../../src/index.ts";
70
+ import { insertEntry, insertUsage } from "../../src/index.ts";
71
+
72
+ const configuration = {
73
+ model: { provider: "provider", modelId: "model" },
74
+ thinkingLevel: "off",
75
+ activeToolNames: ["read"],
76
+ } satisfies LaneConfiguration;
77
+
78
+ const retryPolicy = { maxAttempts: 3, baseDelayMs: 100, maxAgentDelayMs: 30_000 } as const;
79
+ const generationContext = {
80
+ stepId: "step",
81
+ triggerEntryId: "trigger",
82
+ configuration,
83
+ streamOptions: { deferred: { window: "1h" } },
84
+ retryPolicy,
85
+ overflowRecoveryUsed: false,
86
+ } satisfies GenerationContext;
87
+ const summaryContext = {
88
+ resultEntryId: "summary",
89
+ configuration,
90
+ streamOptions: {},
91
+ retryPolicy,
92
+ } satisfies SummaryContext;
93
+ const checkpoint = {
94
+ continuation: { kind: "need_assistant", overflowRecoveryUsed: false },
95
+ triggerEntryId: "trigger",
96
+ } satisfies CheckpointData;
97
+
98
+ const runningControl = { status: "running" } satisfies Control;
99
+ const toolCalls = [
100
+ { status: "planned", sourceIndex: 0, resultEntryId: "result-0" },
101
+ { status: "effect_pending", sourceIndex: 1, resultEntryId: "result-1", replay: "safe" },
102
+ { status: "outcome_ready", sourceIndex: 2, resultEntryId: "result-2", terminate: true },
103
+ { status: "completed", sourceIndex: 3, resultEntryId: "result-3", terminate: false },
104
+ ] satisfies ToolCall[];
105
+
106
+ const runScope = {
107
+ control: runningControl,
108
+ settings: {
109
+ compaction: { enabled: true, reserveTokens: 1000, keepRecentTokens: 2000 },
110
+ steeringMode: "all",
111
+ followUpMode: "one-at-a-time",
112
+ toolExecution: "parallel",
113
+ },
114
+ latestAssistantEntryId: null,
115
+ } satisfies OperationScope;
116
+
117
+ const runState = { ...runScope, at: "starting" } satisfies OperationState;
118
+ // One value fixture per flat leaf; `satisfies OperationState[]` keeps every discriminant checked.
119
+ const operationStates = [
120
+ runState,
121
+ { ...runScope, at: "checkpoint", ...checkpoint },
122
+ { ...runScope, at: "assistant.ready", generationContext, nextAttempt: 1 },
123
+ {
124
+ ...runScope,
125
+ at: "assistant.effect_pending",
126
+ generationContext,
127
+ attempt: 1,
128
+ responseEntryId: "response",
129
+ usageId: "usage",
130
+ intendedOutputLimit: 4096,
131
+ contextWindow: 128000,
132
+ },
133
+ {
134
+ ...runScope,
135
+ at: "assistant.retry_wait",
136
+ generationContext,
137
+ nextAttempt: 2,
138
+ notBefore: 10,
139
+ errorMessage: "retry",
140
+ },
141
+ {
142
+ ...runScope,
143
+ at: "tools",
144
+ batch: { assistantEntryId: "assistant", configuration, turnId: "turn", calls: toolCalls },
145
+ },
146
+ {
147
+ ...runScope,
148
+ at: "deferred.suspended",
149
+ stepId: "step",
150
+ sourceEntryId: "source",
151
+ poll: 0,
152
+ configuration,
153
+ streamOptions: {},
154
+ },
155
+ {
156
+ ...runScope,
157
+ at: "deferred.effect_pending",
158
+ stepId: "step",
159
+ sourceEntryId: "source",
160
+ poll: 1,
161
+ responseEntryId: "response",
162
+ usageId: "usage",
163
+ configuration,
164
+ streamOptions: {},
165
+ },
166
+ {
167
+ ...runScope,
168
+ at: "summary.deciding",
169
+ task: { taskId: "task", reason: "threshold", boundary: { kind: "resume_checkpoint", resumeAfter: checkpoint } },
170
+ },
171
+ {
172
+ ...runScope,
173
+ at: "summary.ready",
174
+ task: { taskId: "task", reason: "manual", customInstructions: "compact", boundary: { kind: "finish" } },
175
+ summaryContext,
176
+ nextAttempt: 1,
177
+ },
178
+ {
179
+ ...runScope,
180
+ at: "summary.effect_pending",
181
+ task: {
182
+ taskId: "task",
183
+ boundary: { kind: "commit_navigation", targetId: "target", label: "target" },
184
+ },
185
+ summaryContext,
186
+ attempt: 1,
187
+ request: { index: 0, usageId: "usage" },
188
+ usageIds: [],
189
+ },
190
+ {
191
+ ...runScope,
192
+ at: "summary.retry_wait",
193
+ task: { taskId: "task", reason: "overflow", boundary: { kind: "resume_checkpoint", resumeAfter: checkpoint } },
194
+ summaryContext,
195
+ nextAttempt: 2,
196
+ notBefore: 10,
197
+ errorMessage: "retry",
198
+ },
199
+ { ...runScope, at: "navigation.ready_to_commit", targetId: null },
200
+ ] satisfies OperationState[];
201
+ const operations = [
202
+ {
203
+ operationId: "run",
204
+ lane: "main",
205
+ sourceTipId: null,
206
+ startedAt: 1,
207
+ intent: { kind: "run", promptEntryIds: ["prompt"] },
208
+ },
209
+ {
210
+ operationId: "compaction",
211
+ lane: "main",
212
+ sourceTipId: "source",
213
+ startedAt: 2,
214
+ intent: { kind: "compaction", customInstructions: "compact" },
215
+ },
216
+ {
217
+ operationId: "navigation",
218
+ lane: "main",
219
+ sourceTipId: "source",
220
+ startedAt: 3,
221
+ intent: { kind: "navigation", targetId: "target", summarize: true, label: "target" },
222
+ },
223
+ ] satisfies OperationMeta[];
224
+
225
+ const operationResult = {
226
+ operationId: "run",
227
+ kind: "run",
228
+ status: "completed",
229
+ fromTipId: null,
230
+ tipId: "leaf",
231
+ startedAt: 1,
232
+ endedAt: 2,
233
+ } satisfies OperationResultRecord;
234
+ const valueWrites: ValueSetWrite[] = [
235
+ storedValues.setValue(storedValues.branchTip("main"), "leaf"),
236
+ storedValues.setValue(storedValues.laneConfig("main"), configuration),
237
+ storedValues.setValue(storedValues.laneState("main"), {
238
+ currentOperationId: "run",
239
+ lastOperationId: null,
240
+ inbox: [],
241
+ }),
242
+ storedValues.setValue(storedValues.operationResult("run"), operationResult),
243
+ storedValues.setValue(storedValues.operationMeta("run"), operations[0]),
244
+ storedValues.setValue(storedValues.operationState("run"), runState),
245
+ storedValues.setValue(storedValues.operationToolArgs("run", "step", 0), { path: "file" }),
246
+ storedValues.setValue(storedValues.operationPreparation("run", "task"), {
247
+ kind: "compaction",
248
+ messagesToSummarize: [],
249
+ turnPrefixMessages: [],
250
+ retainedTail: [],
251
+ isSplitTurn: false,
252
+ tokensBefore: 100,
253
+ fileOps: { read: [], written: [], edited: [] },
254
+ settings: { enabled: true, reserveTokens: 1000, keepRecentTokens: 2000 },
255
+ }),
256
+ storedValues.setValue(storedValues.pendingEntry("pending"), {
257
+ type: "custom",
258
+ customType: "note",
259
+ payload: { text: "pending" },
260
+ }),
261
+ storedValues.setValue(storedValues.sessionName, "session"),
262
+ storedValues.setValue(storedValues.entryLabel("entry"), "label"),
263
+ storedValues.setValue(storedValues.value<unknown>("test.value", "state"), null),
264
+ ];
265
+
266
+ const usage = {
267
+ input: 1,
268
+ output: 2,
269
+ cacheRead: 3,
270
+ cacheWrite: 4,
271
+ totalTokens: 10,
272
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
273
+ } satisfies Usage;
274
+ const usageRow = {
275
+ id: "usage",
276
+ seq: 2,
277
+ usage,
278
+ entryId: "entry",
279
+ adjustment: false,
280
+ details: { attempt: 1 },
281
+ } satisfies UsageRow;
282
+ const entryWrite = insertEntry({
283
+ id: "entry",
284
+ parentId: null,
285
+ type: "message",
286
+ message: { role: "user", content: "hello", timestamp: 1 },
287
+ });
288
+ const usageWrite = insertUsage({
289
+ id: usageRow.id,
290
+ usage,
291
+ adjustment: false,
292
+ entryId: "entry",
293
+ });
294
+ const writes = [
295
+ entryWrite,
296
+ usageWrite,
297
+ valueWrites[0]!,
298
+ storedValues.deleteValue(storedValues.entryLabel("entry")),
299
+ ] satisfies Write[];
300
+ const transaction = writes satisfies Write[];
301
+
302
+ it("covers the complete durable storage and Part 3 discriminants", () => {
303
+ expectTypeOf(entryWrite).toEqualTypeOf<EntryWrite>();
304
+ expectTypeOf(usageWrite).toEqualTypeOf<UsageWrite>();
305
+ expectTypeOf(storedValues.laneConfig("main")).toEqualTypeOf<storedValues.Value<LaneConfiguration>>();
306
+ expectTypeOf(storedValues.pendingAssistantFrames("operation", "response")).toEqualTypeOf<
307
+ storedValues.ValueList<AssistantMessageFrame>
308
+ >();
309
+ expectTypeOf<OperationMeta["intent"]["kind"]>().toEqualTypeOf<"run" | "compaction" | "navigation">();
310
+ expectTypeOf<Control["status"]>().toEqualTypeOf<"running" | "cancel_requested">();
311
+ expectTypeOf<ToolCall["status"]>().toEqualTypeOf<"planned" | "effect_pending" | "outcome_ready" | "completed">();
312
+ expectTypeOf<OperationAt>().toEqualTypeOf<
313
+ | "starting"
314
+ | "checkpoint"
315
+ | "assistant.ready"
316
+ | "assistant.effect_pending"
317
+ | "assistant.retry_wait"
318
+ | "tools"
319
+ | "deferred.suspended"
320
+ | "deferred.effect_pending"
321
+ | "summary.deciding"
322
+ | "summary.ready"
323
+ | "summary.effect_pending"
324
+ | "summary.retry_wait"
325
+ | "summary.deciding"
326
+ | "summary.ready"
327
+ | "summary.effect_pending"
328
+ | "summary.retry_wait"
329
+ | "navigation.ready_to_commit"
330
+ | "summary.deciding"
331
+ | "summary.ready"
332
+ | "summary.effect_pending"
333
+ | "summary.retry_wait"
334
+ >();
335
+ expectTypeOf<InboxItem["kind"]>().toEqualTypeOf<"steer" | "followUp" | "nextRun" | "write">();
336
+ expectTypeOf<TerminalStatus>().toEqualTypeOf<"completed" | "declined" | "aborted" | "failed">();
337
+ expectTypeOf<NewEntry["type"]>().toEqualTypeOf<"message" | "compaction" | "branch_summary" | "custom">();
338
+ void transaction;
339
+ void operationStates;
340
+
341
+ const compileTimeFailures = () => {
342
+ // @ts-expect-error lane.config requires a complete LaneConfiguration
343
+ const invalidValue: ValueSetWrite = storedValues.setValue(storedValues.laneConfig("main"), "model");
344
+ // @ts-expect-error response entries require settled assistant content at runtime, not a pending settlement type
345
+ const invalidSettled: SettledAssistantMessage = { stopReason: "pending" } as AssistantMessage;
346
+ void invalidValue;
347
+ void invalidSettled;
348
+ };
349
+ expectTypeOf(compileTimeFailures).toBeFunction();
350
+ });
351
+
352
+ it("covers storage, session, repository, search, and identity signatures", () => {
353
+ expectTypeOf<SessionMetadata["storageVersion"]>().toEqualTypeOf<number>();
354
+ expectTypeOf<IdGenerator["next"]>().toEqualTypeOf<(timestampMs?: number) => string>();
355
+ expectTypeOf<Parameters<Storage["scanBranch"]>[0]["start"]>().toEqualTypeOf<string>();
356
+ expectTypeOf<BranchScan["start"]>().toEqualTypeOf<string | undefined>();
357
+ expectTypeOf<Storage["commit"]>().toEqualTypeOf<
358
+ (
359
+ transactionToCommit: Write[],
360
+ context: Context,
361
+ ) => Promise<{ firstSeq: number; seqs: number[]; timestamp: number; stats: SessionStats }>
362
+ >();
363
+ expectTypeOf<Session["beginMutation"]>().toEqualTypeOf<(context: Context) => Promise<SessionMutation>>();
364
+ expectTypeOf<SessionMutation["commit"]>().toEqualTypeOf<SessionMutator["commit"]>();
365
+ expectTypeOf<SessionMutation["end"]>().toEqualTypeOf<(context: Context) => Promise<void>>();
366
+ expectTypeOf<Session["mutate"]>().toEqualTypeOf<
367
+ <T>(mutation: (mutator: SessionMutator, context: Context) => T | Promise<T>, context: Context) => Promise<T>
368
+ >();
369
+ expectTypeOf<SessionMutator["commit"]>().toEqualTypeOf<
370
+ (
371
+ transactionToCommit: Write[],
372
+ context: Context,
373
+ ) => Promise<{ firstSeq: number; seqs: number[]; timestamp: number; stats: SessionStats }>
374
+ >();
375
+ expectTypeOf<SessionReader["scanBranch"]>().toEqualTypeOf<
376
+ (query: StorageBranchScan, context: Context) => Promise<Entry[]>
377
+ >();
378
+ expectTypeOf<Session["createBranch"]>().toEqualTypeOf<
379
+ (name: string, at: string | null, context: Context) => Promise<Branch>
380
+ >();
381
+ expectTypeOf<SessionRepo["create"]>().toEqualTypeOf<
382
+ (options: SessionCreateOptions, context: Context) => Promise<Session>
383
+ >();
384
+ expectTypeOf<SessionSearchService["searchSessions"]>().toEqualTypeOf<
385
+ (query: SearchQuery) => Promise<SessionSearchHit[]>
386
+ >();
387
+ expectTypeOf<SessionSearchService["notify"]>().toEqualTypeOf<(sessionId: string) => void>();
388
+ });
389
+
390
+ it("covers Part 5 results, events, hooks, snapshots, tools, and stream options", () => {
391
+ type RunErrorTag = Extract<RunResult, { ok: false }>["error"]["_tag"];
392
+ type CancelKind = Extract<CancelQueuedResult, { ok: true }>["value"]["kind"];
393
+ expectTypeOf<RunErrorTag>().toEqualTypeOf<
394
+ "LaneBusy" | "InvalidMessage" | "UnknownSkill" | "UnknownTemplate" | "Closed"
395
+ >();
396
+ expectTypeOf<CancelKind>().toEqualTypeOf<"cancelled" | "already_consumed" | "not_found">();
397
+ expectTypeOf<HarnessEvent["type"]>().toEqualTypeOf<
398
+ | "run_start"
399
+ | "run_resume"
400
+ | "run_suspend"
401
+ | "operation_abort"
402
+ | "run_end"
403
+ | "fault"
404
+ | "handler_error"
405
+ | "turn_start"
406
+ | "turn_end"
407
+ | "retry_scheduled"
408
+ | "retry_start"
409
+ | "retry_end"
410
+ | "message_start"
411
+ | "message_update"
412
+ | "message_end"
413
+ | "tool_start"
414
+ | "tool_update"
415
+ | "tool_end"
416
+ | "entry_added"
417
+ | "queue_update"
418
+ | "value_update"
419
+ | "config_update"
420
+ | "compaction_start"
421
+ | "compaction_end"
422
+ | "navigation_start"
423
+ | "navigation_end"
424
+ | "lane_created"
425
+ | "usage"
426
+ >();
427
+ expectTypeOf<HookName>().toEqualTypeOf<
428
+ | "before_run"
429
+ | "before_drive"
430
+ | "before_run_end"
431
+ | "transform_context"
432
+ | "before_request"
433
+ | "before_payload"
434
+ | "after_response"
435
+ | "before_tool"
436
+ | "after_tool"
437
+ | "before_compaction"
438
+ | "before_navigation"
439
+ >();
440
+ expectTypeOf<HookMap["before_drive"]["result"]>().toEqualTypeOf<void>();
441
+ expectTypeOf<HookHandler<"before_drive">>().returns.toEqualTypeOf<void | Promise<void>>();
442
+ expectTypeOf<HookMap["transform_context"]["event"]>().toEqualTypeOf<{
443
+ messages: AgentMessage[];
444
+ systemPrompt: string;
445
+ }>();
446
+ expectTypeOf<LaneSnapshot["operation"]>().not.toEqualTypeOf<SessionSnapshot>();
447
+ expectTypeOf<LaneSnapshotTool["status"]>().toEqualTypeOf<"running" | "settled">();
448
+ expectTypeOf<AgentLane["getResult"]>().returns.toEqualTypeOf<Promise<OperationResultRecord | undefined>>();
449
+ expectTypeOf<SuspendedRun>().toEqualTypeOf<{
450
+ operationId: string;
451
+ status: "suspended";
452
+ deferred: DeferredHandle;
453
+ }>();
454
+ expectTypeOf<AgentLane["accept"]>().returns.toEqualTypeOf<Promise<OperationAdmissionResult>>();
455
+ expectTypeOf<AgentLane["drive"]>().returns.toEqualTypeOf<Promise<DriveResult>>();
456
+ expectTypeOf<keyof DriveOptions>().toEqualTypeOf<"operationId" | "waitForRetry" | "pollDeferred">();
457
+ expectTypeOf<DriveOutcome["kind"]>().toEqualTypeOf<"settled" | "waiting">();
458
+ expectTypeOf<AgentLane["inspectExecution"]>().returns.toEqualTypeOf<Promise<LaneExecutionInfo>>();
459
+ expectTypeOf<AgentLane["getTipId"]>().returns.toEqualTypeOf<Promise<string | null>>();
460
+ expectTypeOf<Extract<keyof AgentLane, "sessionTree">>().toEqualTypeOf<never>();
461
+ expectTypeOf<Extract<keyof AgentHarness, keyof AgentLane>>().toEqualTypeOf<never>();
462
+ expectTypeOf<
463
+ Extract<
464
+ keyof AgentLane,
465
+ | "session"
466
+ | "models"
467
+ | "hooks"
468
+ | "activeDrive"
469
+ | "command"
470
+ | "settleOperation"
471
+ | "continueOperation"
472
+ | "readConfig"
473
+ | "mismatch"
474
+ >
475
+ >().toEqualTypeOf<never>();
476
+ expectTypeOf<
477
+ Extract<
478
+ keyof AgentHarness,
479
+ | "session"
480
+ | "models"
481
+ | "activeDrive"
482
+ | "command"
483
+ | "settleOperation"
484
+ | "continueOperation"
485
+ | "readConfig"
486
+ | "mismatch"
487
+ >
488
+ >().toEqualTypeOf<never>();
489
+ expectTypeOf<OperationRequest["kind"]>().toEqualTypeOf<
490
+ "prompt" | "skill" | "prompt_template" | "compaction" | "navigation"
491
+ >();
492
+ expectTypeOf<Parameters<AgentHarnessTool<object>["execute"]>[4]>().toEqualTypeOf<AgentHarnessToolInvocation>();
493
+ expectTypeOf<Parameters<AgentHarnessTool<object>["execute"]>[5]>().toEqualTypeOf<Context>();
494
+ expectTypeOf<AgentTool["replay"]>().toEqualTypeOf<"never" | "safe" | undefined>();
495
+ expectTypeOf<AgentHarnessStreamOptions["deferred"]>().toEqualTypeOf<
496
+ boolean | { window?: "15m" | "1h" | "24h" } | undefined
497
+ >();
498
+ expectTypeOf<EntryProjector>().toEqualTypeOf<
499
+ (entry: CustomEntry, context: Context) => AgentMessage[] | undefined | Promise<AgentMessage[] | undefined>
500
+ >();
501
+ expectTypeOf<NonNullable<AgentHarnessOptions["entryProjectors"]>>().toEqualTypeOf<Record<string, EntryProjector>>();
502
+
503
+ const compileTimeFailures = () => {
504
+ // @ts-expect-error callers cannot supply the harness-owned abort signal
505
+ const invalidOptions: AgentHarnessStreamOptions = { signal: new AbortController().signal };
506
+ const invalidDriveOptions: DriveOptions = {
507
+ operationId: "run",
508
+ // @ts-expect-error drive has no wall-clock deadline
509
+ deadline: Date.now(),
510
+ };
511
+ const invalidValueEvent: Extract<HarnessEvent, { type: "value_update" }> = {
512
+ type: "value_update",
513
+ value: "session_name",
514
+ name: "session",
515
+ // @ts-expect-error value events are harness-global and cannot carry a lane
516
+ lane: "main",
517
+ };
518
+ void invalidOptions;
519
+ void invalidDriveOptions;
520
+ void invalidValueEvent;
521
+ };
522
+ expectTypeOf(compileTimeFailures).toBeFunction();
523
+ });
packages/agent/test/harness/values.test.ts ADDED
@@ -0,0 +1,183 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import type { AssistantMessageFrame } from "@earendil-works/pi-ai";
2
+ import { describe, expect, expectTypeOf, it } from "vitest";
3
+ import { BACKGROUND_CONTEXT } from "../../src/harness/context.ts";
4
+ import { MemoryStorage } from "../../src/harness/session/memory.ts";
5
+ import type {
6
+ DurableStructuralPreparation,
7
+ JsonValue,
8
+ LaneConfiguration,
9
+ LaneState,
10
+ OperationMeta,
11
+ OperationResultRecord,
12
+ OperationState,
13
+ PendingEntry,
14
+ SessionReader,
15
+ } from "../../src/harness/session/types.ts";
16
+ import {
17
+ appendList,
18
+ branchTip,
19
+ branchTipInventoryPrefix,
20
+ deleteList,
21
+ deleteValue,
22
+ entryLabel,
23
+ type ListElement,
24
+ laneConfig,
25
+ laneState,
26
+ list,
27
+ operationMeta,
28
+ operationPreparation,
29
+ operationPreparationPrefix,
30
+ operationResult,
31
+ operationState,
32
+ operationToolArgs,
33
+ operationToolArgsPrefix,
34
+ operationToolMemo,
35
+ operationToolMemoPrefix,
36
+ pendingAssistantFrames,
37
+ pendingEntry,
38
+ pendingToolOutput,
39
+ pendingToolOutputPrefix,
40
+ type StoredValue,
41
+ sessionName,
42
+ setValue,
43
+ type Value,
44
+ type ValueList,
45
+ value,
46
+ } from "../../src/harness/session/values.ts";
47
+
48
+ describe("bound value addresses", () => {
49
+ it("binds immutable scalar and list addresses with validated components", () => {
50
+ expect(value<string>("app.state")).toEqual({ kind: "value", namespace: "app.state", key: "" });
51
+ expect(list<number>("app.events", "workspace")).toEqual({
52
+ kind: "list",
53
+ namespace: "app.events",
54
+ key: "workspace",
55
+ });
56
+ expect(Object.isFrozen(value<string>("app.state"))).toBe(true);
57
+ expect(() => value<unknown>("")).toThrow("must not be empty");
58
+ expect(() => value<unknown>("app\0state")).toThrow("must not contain");
59
+ expect(() => list<unknown>("app.events", "bad\0key")).toThrow("must not contain");
60
+ expect(value<unknown>("pi.application")).toEqual({ kind: "value", namespace: "pi.application", key: "" });
61
+ });
62
+
63
+ it("preserves invariant address and helper types", () => {
64
+ const scalar = value<{ count: number }>("app.state");
65
+ const events = list<{ name: string }>("app.events");
66
+ expectTypeOf(scalar).toEqualTypeOf<Value<{ count: number }>>();
67
+ expectTypeOf(events).toEqualTypeOf<ValueList<{ name: string }>>();
68
+ expectTypeOf(setValue(scalar, { count: 1 }).value).toEqualTypeOf<unknown>();
69
+ expectTypeOf(appendList(events, { name: "created" }).value).toEqualTypeOf<unknown>();
70
+
71
+ const compileTimeFailures = () => {
72
+ // @ts-expect-error Value is invariant in its stored type
73
+ const widenedScalar: Value<unknown> = scalar;
74
+ // @ts-expect-error ValueList is invariant in its element type
75
+ const widenedList: ValueList<unknown> = events;
76
+ // @ts-expect-error the bound scalar address controls the write type
77
+ setValue(scalar, { count: "wrong" });
78
+ // @ts-expect-error the bound list address controls the element type
79
+ appendList(events, { name: 1 });
80
+ // @ts-expect-error scalar helpers reject list addresses
81
+ deleteValue(events);
82
+ // @ts-expect-error list helpers reject scalar addresses
83
+ deleteList(scalar);
84
+ void widenedScalar;
85
+ void widenedList;
86
+ };
87
+ expectTypeOf(compileTimeFailures).toBeFunction();
88
+ });
89
+
90
+ it("infers list element types through Storage and SessionReader", async () => {
91
+ const storage = new MemoryStorage({ now: () => 1 });
92
+ const events = list<{ name: string }>("app.events");
93
+ const reader: SessionReader = storage;
94
+ const storageElements = await storage.readList(events, undefined, BACKGROUND_CONTEXT);
95
+ const readerElements = await reader.readList(events, undefined, BACKGROUND_CONTEXT);
96
+ expectTypeOf(storageElements).toEqualTypeOf<ListElement<{ name: string }>[]>();
97
+ expectTypeOf(readerElements).toEqualTypeOf<ListElement<{ name: string }>[]>();
98
+ await storage.close(BACKGROUND_CONTEXT);
99
+ });
100
+
101
+ it("uses separately constructed equal addresses for one durable location", async () => {
102
+ const storage = new MemoryStorage({ now: () => 1 });
103
+ const first = value<{ ready: boolean }>("app.state", "workspace");
104
+ const second = value<{ ready: boolean }>("app.state", "workspace");
105
+ await storage.commit([setValue(first, { ready: true })], BACKGROUND_CONTEXT);
106
+ const stored = await storage.getValue(second, BACKGROUND_CONTEXT);
107
+ expect(stored).toEqual({ address: first, value: { ready: true }, seq: 1 });
108
+ expectTypeOf(stored).toEqualTypeOf<StoredValue<{ ready: boolean }> | undefined>();
109
+ await storage.close(BACKGROUND_CONTEXT);
110
+ });
111
+ });
112
+
113
+ describe("built-in durable addresses", () => {
114
+ it("uses the exact reserved namespaces, keys, kinds, and value types", () => {
115
+ const config = laneConfig("review");
116
+ const meta = operationMeta("operation");
117
+ const state = operationState("operation");
118
+ const frames = pendingAssistantFrames("operation", "response");
119
+ expectTypeOf(config).toEqualTypeOf<Value<LaneConfiguration>>();
120
+ expectTypeOf(branchTip("review")).toEqualTypeOf<Value<string | null>>();
121
+ expectTypeOf(laneState("review")).toEqualTypeOf<Value<LaneState>>();
122
+ expectTypeOf(operationResult("operation")).toEqualTypeOf<Value<OperationResultRecord>>();
123
+ expectTypeOf(meta).toEqualTypeOf<Value<OperationMeta>>();
124
+ expectTypeOf(state).toEqualTypeOf<Value<OperationState>>();
125
+ expectTypeOf(operationToolArgs("operation", "step", 2)).toEqualTypeOf<Value<Record<string, JsonValue>>>();
126
+ expectTypeOf(operationToolMemo("operation", "invocation", "name")).toEqualTypeOf<Value<JsonValue>>();
127
+ expectTypeOf(operationPreparation("operation", "task")).toEqualTypeOf<Value<DurableStructuralPreparation>>();
128
+ expectTypeOf(pendingEntry("entry")).toEqualTypeOf<Value<PendingEntry>>();
129
+ expectTypeOf(frames).toEqualTypeOf<ValueList<AssistantMessageFrame>>();
130
+
131
+ expect([
132
+ branchTip("review"),
133
+ laneConfig("review"),
134
+ laneState("review"),
135
+ operationResult("operation"),
136
+ meta,
137
+ state,
138
+ operationToolArgs("operation", "step", 2),
139
+ operationToolMemo("operation", "invocation", "name"),
140
+ operationPreparation("operation", "task"),
141
+ pendingEntry("entry"),
142
+ pendingToolOutput("operation", "invocation"),
143
+ frames,
144
+ sessionName,
145
+ entryLabel("entry"),
146
+ ]).toEqual([
147
+ { kind: "value", namespace: "pi.branch.tip", key: "review" },
148
+ { kind: "value", namespace: "pi.lane.config", key: "review" },
149
+ { kind: "value", namespace: "pi.lane.state", key: "review" },
150
+ { kind: "value", namespace: "pi.result", key: "operation" },
151
+ { kind: "value", namespace: "pi.op.meta", key: "operation" },
152
+ { kind: "value", namespace: "pi.op.state", key: "operation" },
153
+ { kind: "value", namespace: "pi.op.tool_args", key: "operation:step:2" },
154
+ { kind: "value", namespace: "pi.op.tool_memo", key: "operation:invocation:name" },
155
+ { kind: "value", namespace: "pi.op.preparation", key: "operation:task" },
156
+ { kind: "value", namespace: "pi.pending.entry", key: "entry" },
157
+ { kind: "value", namespace: "pi.pending.tool_output", key: "operation:invocation" },
158
+ { kind: "list", namespace: "pi.pending.assistant_frame", key: "operation:response" },
159
+ { kind: "value", namespace: "pi.session.name", key: "" },
160
+ { kind: "value", namespace: "pi.entry.label", key: "entry" },
161
+ ]);
162
+ });
163
+
164
+ it("exports exactly the five documented scan-prefix constructors", () => {
165
+ const prefixes = [
166
+ branchTipInventoryPrefix(),
167
+ operationToolArgsPrefix("operation"),
168
+ operationToolMemoPrefix("operation", "invocation"),
169
+ operationPreparationPrefix("operation"),
170
+ pendingToolOutputPrefix("operation"),
171
+ ];
172
+ expect(prefixes).toHaveLength(5);
173
+ expect(prefixes).toEqual([
174
+ { kind: "value", namespace: "pi.branch.tip", key: "" },
175
+ { kind: "value", namespace: "pi.op.tool_args", key: "operation:" },
176
+ { kind: "value", namespace: "pi.op.tool_memo", key: "operation:invocation:" },
177
+ { kind: "value", namespace: "pi.op.preparation", key: "operation:" },
178
+ { kind: "value", namespace: "pi.pending.tool_output", key: "operation:" },
179
+ ]);
180
+ expect(operationToolArgsPrefix("operation", "step").key).toBe("operation:step:");
181
+ expect(operationToolMemoPrefix("operation").key).toBe("operation:");
182
+ });
183
+ });
packages/agent/test/utils/calculate.ts ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import type { Usage } from "@earendil-works/pi-ai";
2
+ import { type Static, Type } from "typebox";
3
+ import type { AgentTool, AgentToolResult } from "../../src/types.ts";
4
+
5
+ export interface CalculateResult extends AgentToolResult<undefined> {
6
+ content: Array<{ type: "text"; text: string }>;
7
+ details: undefined;
8
+ }
9
+
10
+ export function calculate(expression: string): CalculateResult {
11
+ try {
12
+ const result = new Function(`return ${expression}`)();
13
+ return { content: [{ type: "text", text: `${expression} = ${result}` }], details: undefined };
14
+ } catch (e: any) {
15
+ throw new Error(e.message || String(e));
16
+ }
17
+ }
18
+
19
+ const calculateSchema = Type.Object({
20
+ expression: Type.String({ description: "The mathematical expression to evaluate" }),
21
+ });
22
+
23
+ type CalculateParams = Static<typeof calculateSchema>;
24
+
25
+ export const calculateTool: AgentTool<typeof calculateSchema, undefined> = {
26
+ label: "Calculator",
27
+ name: "calculate",
28
+ description: "Evaluate mathematical expressions",
29
+ parameters: calculateSchema,
30
+ execute: async (_toolCallId: string, args: CalculateParams) => {
31
+ return calculate(args.expression);
32
+ },
33
+ };
34
+
35
+ export function createCalculateToolWithUsage(usage: Usage): AgentTool<typeof calculateSchema, undefined> {
36
+ return {
37
+ ...calculateTool,
38
+ execute: async (_toolCallId: string, args: CalculateParams) => ({ ...calculate(args.expression), usage }),
39
+ };
40
+ }
packages/agent/test/utils/get-current-time.ts ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { type Static, Type } from "typebox";
2
+ import type { AgentTool, AgentToolResult } from "../../src/types.ts";
3
+
4
+ export interface GetCurrentTimeResult extends AgentToolResult<{ utcTimestamp: number }> {}
5
+
6
+ export async function getCurrentTime(timezone?: string): Promise<GetCurrentTimeResult> {
7
+ const date = new Date();
8
+ if (timezone) {
9
+ try {
10
+ const timeStr = date.toLocaleString("en-US", {
11
+ timeZone: timezone,
12
+ dateStyle: "full",
13
+ timeStyle: "long",
14
+ });
15
+ return {
16
+ content: [{ type: "text", text: timeStr }],
17
+ details: { utcTimestamp: date.getTime() },
18
+ };
19
+ } catch (_e) {
20
+ throw new Error(`Invalid timezone: ${timezone}. Current UTC time: ${date.toISOString()}`);
21
+ }
22
+ }
23
+ const timeStr = date.toLocaleString("en-US", { dateStyle: "full", timeStyle: "long" });
24
+ return {
25
+ content: [{ type: "text", text: timeStr }],
26
+ details: { utcTimestamp: date.getTime() },
27
+ };
28
+ }
29
+
30
+ const getCurrentTimeSchema = Type.Object({
31
+ timezone: Type.Optional(
32
+ Type.String({ description: "Optional timezone (e.g., 'America/New_York', 'Europe/London')" }),
33
+ ),
34
+ });
35
+
36
+ type GetCurrentTimeParams = Static<typeof getCurrentTimeSchema>;
37
+
38
+ export const getCurrentTimeTool: AgentTool<typeof getCurrentTimeSchema, { utcTimestamp: number }> = {
39
+ label: "Current Time",
40
+ name: "get_current_time",
41
+ description: "Get the current date and time",
42
+ parameters: getCurrentTimeSchema,
43
+ execute: async (_toolCallId: string, args: GetCurrentTimeParams) => {
44
+ return getCurrentTime(args.timezone);
45
+ },
46
+ };
packages/agent/test/utils/wait-for-tick.ts ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ export function waitForTick(): Promise<void> {
2
+ return new Promise((resolve) => setTimeout(resolve, 0));
3
+ }
packages/ai/src/api/openai-responses.ts ADDED
@@ -0,0 +1,389 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import OpenAI from "openai";
2
+ import type { ResponseCreateParamsStreaming } from "openai/resources/responses/responses.js";
3
+ import { clampThinkingLevel } from "../models.ts";
4
+ import type {
5
+ Api,
6
+ AssistantMessage,
7
+ CacheRetention,
8
+ Context,
9
+ Model,
10
+ OpenAIResponsesCompat,
11
+ ProviderEnv,
12
+ ProviderHeaders,
13
+ SimpleStreamOptions,
14
+ StreamFunction,
15
+ StreamOptions,
16
+ Usage,
17
+ } from "../types.ts";
18
+ import { splitDeferredTools } from "../utils/deferred-tools.ts";
19
+ import { formatProviderError, normalizeProviderError } from "../utils/error-body.ts";
20
+ import { AssistantMessageEventStream } from "../utils/event-stream.ts";
21
+ import { headersToRecord } from "../utils/headers.ts";
22
+ import { getPiUserAgent } from "../utils/pi-user-agent.ts";
23
+ import { getProviderEnvValue } from "../utils/provider-env.ts";
24
+ import { retryProviderRequest } from "../utils/provider-retry.ts";
25
+ import { createGrammarToolInputProperties } from "./constrained-sampling.ts";
26
+ import { buildCopilotDynamicHeaders, hasCopilotVisionInput } from "./github-copilot-headers.ts";
27
+ import { clampOpenAIPromptCacheKey } from "./openai-prompt-cache.ts";
28
+ import { convertResponsesMessages, convertResponsesTools, processResponsesStream } from "./openai-responses-shared.ts";
29
+ import { buildBaseOptions } from "./simple-options.ts";
30
+
31
+ const OPENAI_TOOL_CALL_PROVIDERS = new Set(["openai", "openai-codex", "opencode"]);
32
+ // OpenAI Responses rejects max_output_tokens below 16: https://github.com/earendil-works/pi/issues/6265
33
+ const OPENAI_RESPONSES_MIN_OUTPUT_TOKENS = 16;
34
+
35
+ function hasHeader(headers: ProviderHeaders | undefined, name: string): boolean {
36
+ if (!headers) return false;
37
+ const expected = name.toLowerCase();
38
+ for (const [key, value] of Object.entries(headers)) {
39
+ if (key.toLowerCase() === expected && value !== null && value.trim().length > 0) return true;
40
+ }
41
+ return false;
42
+ }
43
+
44
+ function getClientApiKey(provider: string, apiKey: string | undefined, headers: ProviderHeaders | undefined): string {
45
+ if (apiKey) return apiKey;
46
+ if (hasHeader(headers, "authorization") || hasHeader(headers, "cf-aig-authorization")) return "unused";
47
+ throw new Error(`No API key for provider: ${provider}`);
48
+ }
49
+
50
+ function detectSessionAffinityFormat(model: Pick<Model<"openai-responses">, "provider" | "baseUrl">) {
51
+ return model.provider === "openrouter" || model.baseUrl.includes("openrouter.ai") ? "openrouter" : "openai";
52
+ }
53
+
54
+ /**
55
+ * Resolve cache retention preference.
56
+ * Defaults to "short" and uses PI_CACHE_RETENTION for backward compatibility.
57
+ */
58
+ function resolveCacheRetention(cacheRetention?: CacheRetention, env?: ProviderEnv): CacheRetention {
59
+ if (cacheRetention) {
60
+ return cacheRetention;
61
+ }
62
+ if (getProviderEnvValue("PI_CACHE_RETENTION", env) === "long") {
63
+ return "long";
64
+ }
65
+ return "short";
66
+ }
67
+
68
+ function getCompat(model: Model<"openai-responses">): Required<OpenAIResponsesCompat> {
69
+ return {
70
+ supportsDeveloperRole: model.compat?.supportsDeveloperRole ?? true,
71
+ sessionAffinityFormat: model.compat?.sessionAffinityFormat ?? detectSessionAffinityFormat(model),
72
+ supportsLongCacheRetention: model.compat?.supportsLongCacheRetention ?? true,
73
+ supportsStrictMode: model.compat?.supportsStrictMode ?? false,
74
+ supportsOpenAIGrammarTools: model.compat?.supportsOpenAIGrammarTools ?? false,
75
+ supportsAdditionalTools: model.compat?.supportsAdditionalTools ?? false,
76
+ supportsToolSearch: model.compat?.supportsToolSearch ?? false,
77
+ supportsExplicitPromptCacheMode: model.compat?.supportsExplicitPromptCacheMode ?? false,
78
+ supportsMaxOutputTokens: model.compat?.supportsMaxOutputTokens ?? true,
79
+ };
80
+ }
81
+
82
+ function getPromptCacheRetention(
83
+ compat: Required<OpenAIResponsesCompat>,
84
+ cacheRetention: CacheRetention,
85
+ ): "24h" | undefined {
86
+ return cacheRetention === "long" && compat.supportsLongCacheRetention && !compat.supportsExplicitPromptCacheMode
87
+ ? "24h"
88
+ : undefined;
89
+ }
90
+
91
+ function getPromptCacheOptions(
92
+ compat: Required<OpenAIResponsesCompat>,
93
+ cacheRetention: CacheRetention,
94
+ ): { mode?: "explicit"; ttl?: "30m" } | undefined {
95
+ if (!compat.supportsExplicitPromptCacheMode) return undefined;
96
+ if (cacheRetention === "none") return { mode: "explicit" };
97
+ if (cacheRetention === "long" && compat.supportsLongCacheRetention) return { ttl: "30m" };
98
+ return undefined;
99
+ }
100
+
101
+ // OpenAI Responses-specific options
102
+ export interface OpenAIResponsesOptions extends StreamOptions {
103
+ reasoningEffort?: "minimal" | "low" | "medium" | "high" | "xhigh" | "max";
104
+ reasoningSummary?: "auto" | "detailed" | "concise" | null;
105
+ serviceTier?: ResponseCreateParamsStreaming["service_tier"];
106
+ toolChoice?: ResponseCreateParamsStreaming["tool_choice"];
107
+ }
108
+
109
+ /**
110
+ * Generate function for OpenAI Responses API
111
+ */
112
+ export const stream: StreamFunction<"openai-responses", OpenAIResponsesOptions> = (
113
+ model: Model<"openai-responses">,
114
+ context: Context,
115
+ options?: OpenAIResponsesOptions,
116
+ ): AssistantMessageEventStream => {
117
+ const stream = new AssistantMessageEventStream();
118
+
119
+ // Start async processing
120
+ (async () => {
121
+ const output: AssistantMessage = {
122
+ role: "assistant",
123
+ content: [],
124
+ api: model.api as Api,
125
+ provider: model.provider,
126
+ model: model.id,
127
+ usage: {
128
+ input: 0,
129
+ output: 0,
130
+ cacheRead: 0,
131
+ cacheWrite: 0,
132
+ totalTokens: 0,
133
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
134
+ },
135
+ stopReason: "pending",
136
+ timestamp: Date.now(),
137
+ };
138
+
139
+ try {
140
+ // Create OpenAI client
141
+ const apiKey = getClientApiKey(model.provider, options?.apiKey, options?.headers);
142
+ const cacheRetention = resolveCacheRetention(options?.cacheRetention, options?.env);
143
+ const cacheSessionId = cacheRetention === "none" ? undefined : options?.sessionId;
144
+ const compat = getCompat(model);
145
+ const grammarToolInputProperties = createGrammarToolInputProperties(
146
+ context.tools,
147
+ compat.supportsOpenAIGrammarTools,
148
+ );
149
+ const client = createClient(model, context, apiKey, options?.headers, options?.fetch, cacheSessionId);
150
+ let params = buildParams(model, context, options, compat, grammarToolInputProperties);
151
+ const nextParams = await options?.onPayload?.(params, model);
152
+ if (nextParams !== undefined) {
153
+ params = nextParams as ResponseCreateParamsStreaming;
154
+ }
155
+ const requestOptions = {
156
+ ...(options?.signal ? { signal: options.signal } : {}),
157
+ ...(options?.timeoutMs !== undefined ? { timeout: options.timeoutMs } : {}),
158
+ maxRetries: 0,
159
+ };
160
+ const { data: openaiStream, response } = await retryProviderRequest(
161
+ () => client.responses.create(params, requestOptions).withResponse(),
162
+ {
163
+ maxRetries: options?.maxRetries,
164
+ maxRetryDelayMs: options?.maxRetryDelayMs,
165
+ signal: options?.signal,
166
+ },
167
+ );
168
+ await options?.onResponse?.({ status: response.status, headers: headersToRecord(response.headers) }, model);
169
+ stream.push({ type: "start", partial: output });
170
+
171
+ await processResponsesStream(openaiStream, output, stream, model, {
172
+ serviceTier: options?.serviceTier,
173
+ grammarToolInputProperties,
174
+ applyServiceTierPricing: (usage, serviceTier) => applyServiceTierPricing(usage, serviceTier, model),
175
+ });
176
+
177
+ if (options?.signal?.aborted) {
178
+ throw new Error("Request was aborted");
179
+ }
180
+
181
+ if (output.stopReason === "pending") {
182
+ throw new Error("OpenAI Responses stream ended without a stop reason");
183
+ }
184
+ if (output.stopReason === "aborted" || output.stopReason === "error") {
185
+ throw new Error(output.errorMessage || "An unknown error occurred");
186
+ }
187
+
188
+ stream.push({ type: "done", reason: output.stopReason, message: output });
189
+ stream.end();
190
+ } catch (error) {
191
+ for (const block of output.content) {
192
+ delete (block as { index?: number }).index;
193
+ // Streaming scratch buffers are only used during parsing; never persist them.
194
+ delete (block as { partialJson?: string }).partialJson;
195
+ delete (block as { customInput?: unknown }).customInput;
196
+ }
197
+ output.stopReason = options?.signal?.aborted ? "aborted" : "error";
198
+ output.errorMessage = formatProviderError(
199
+ normalizeProviderError(error),
200
+ `${model.provider === "openai" ? "OpenAI" : model.provider} API error`,
201
+ );
202
+ stream.push({ type: "error", reason: output.stopReason, error: output });
203
+ stream.end();
204
+ }
205
+ })();
206
+
207
+ return stream;
208
+ };
209
+
210
+ export const streamSimple: StreamFunction<"openai-responses", SimpleStreamOptions> = (
211
+ model: Model<"openai-responses">,
212
+ context: Context,
213
+ options?: SimpleStreamOptions,
214
+ ): AssistantMessageEventStream => {
215
+ getClientApiKey(model.provider, options?.apiKey, options?.headers);
216
+
217
+ const base = {
218
+ ...buildBaseOptions(model, context, options, options?.apiKey),
219
+ toolChoice: options?.toolChoice,
220
+ } satisfies OpenAIResponsesOptions;
221
+ const clampedReasoning = options?.reasoning ? clampThinkingLevel(model, options.reasoning) : undefined;
222
+ const reasoningEffort = clampedReasoning === "off" ? undefined : clampedReasoning;
223
+
224
+ return stream(model, context, {
225
+ ...base,
226
+ reasoningEffort,
227
+ } satisfies OpenAIResponsesOptions);
228
+ };
229
+
230
+ function createClient(
231
+ model: Model<"openai-responses">,
232
+ context: Context,
233
+ apiKey: string,
234
+ optionsHeaders?: ProviderHeaders,
235
+ fetch?: typeof globalThis.fetch,
236
+ sessionId?: string,
237
+ ) {
238
+ const compat = getCompat(model);
239
+ const headers: ProviderHeaders = { "User-Agent": getPiUserAgent(), ...model.headers };
240
+ if (model.provider === "github-copilot") {
241
+ const hasImages = hasCopilotVisionInput(context.messages);
242
+ const copilotHeaders = buildCopilotDynamicHeaders({
243
+ messages: context.messages,
244
+ hasImages,
245
+ });
246
+ Object.assign(headers, copilotHeaders);
247
+ }
248
+
249
+ if (sessionId) {
250
+ if (compat.sessionAffinityFormat === "openrouter") {
251
+ headers["x-session-id"] = sessionId;
252
+ } else {
253
+ if (compat.sessionAffinityFormat === "openai") {
254
+ headers.session_id = sessionId;
255
+ }
256
+ headers["x-client-request-id"] = sessionId;
257
+ }
258
+ }
259
+
260
+ // Merge options headers last so they can override defaults
261
+ if (optionsHeaders) {
262
+ Object.assign(headers, optionsHeaders);
263
+ }
264
+
265
+ return new OpenAI({
266
+ apiKey,
267
+ baseURL: model.baseUrl,
268
+ dangerouslyAllowBrowser: true,
269
+ fetch,
270
+ defaultHeaders: headers,
271
+ });
272
+ }
273
+
274
+ function buildParams(
275
+ model: Model<"openai-responses">,
276
+ context: Context,
277
+ options: OpenAIResponsesOptions | undefined,
278
+ compat: Required<OpenAIResponsesCompat> = getCompat(model),
279
+ grammarToolInputProperties: ReadonlyMap<string, string> = createGrammarToolInputProperties(
280
+ context.tools,
281
+ compat.supportsOpenAIGrammarTools,
282
+ ),
283
+ ) {
284
+ const deferredToolsMode = compat.supportsAdditionalTools
285
+ ? "additional-tools"
286
+ : compat.supportsToolSearch
287
+ ? "tool-search"
288
+ : undefined;
289
+ const toolPlacement = splitDeferredTools(context, deferredToolsMode !== undefined);
290
+ const messages = convertResponsesMessages(model, context, OPENAI_TOOL_CALL_PROVIDERS, {
291
+ grammarToolInputProperties,
292
+ deferredTools: toolPlacement.deferred,
293
+ deferredToolsMode,
294
+ toolOptions: {
295
+ supportsStrictMode: compat.supportsStrictMode,
296
+ supportsOpenAIGrammarTools: compat.supportsOpenAIGrammarTools,
297
+ },
298
+ });
299
+
300
+ const cacheRetention = resolveCacheRetention(options?.cacheRetention, options?.env);
301
+ const params: ResponseCreateParamsStreaming & {
302
+ prompt_cache_options?: { mode?: "explicit"; ttl?: "30m" };
303
+ } = {
304
+ model: model.id,
305
+ input: messages,
306
+ stream: true,
307
+ prompt_cache_key: cacheRetention === "none" ? undefined : clampOpenAIPromptCacheKey(options?.sessionId),
308
+ prompt_cache_retention: getPromptCacheRetention(compat, cacheRetention),
309
+ prompt_cache_options: getPromptCacheOptions(compat, cacheRetention),
310
+ store: false,
311
+ };
312
+
313
+ if (options?.maxTokens && compat.supportsMaxOutputTokens) {
314
+ params.max_output_tokens = Math.max(options.maxTokens, OPENAI_RESPONSES_MIN_OUTPUT_TOKENS);
315
+ }
316
+
317
+ if (options?.temperature !== undefined) {
318
+ params.temperature = options?.temperature;
319
+ }
320
+
321
+ if (options?.serviceTier !== undefined) {
322
+ params.service_tier = options.serviceTier;
323
+ }
324
+
325
+ if (toolPlacement.immediate.length > 0) {
326
+ params.tools = convertResponsesTools(toolPlacement.immediate, {
327
+ supportsStrictMode: compat.supportsStrictMode,
328
+ supportsOpenAIGrammarTools: compat.supportsOpenAIGrammarTools,
329
+ });
330
+ }
331
+
332
+ if (options?.toolChoice !== undefined) {
333
+ params.tool_choice = options.toolChoice;
334
+ }
335
+
336
+ if (model.reasoning) {
337
+ if (options?.reasoningEffort || options?.reasoningSummary) {
338
+ const effort = options?.reasoningEffort
339
+ ? (model.thinkingLevelMap?.[options.reasoningEffort] ?? options.reasoningEffort)
340
+ : "medium";
341
+ params.reasoning = {
342
+ effort: effort as NonNullable<typeof params.reasoning>["effort"],
343
+ summary: options?.reasoningSummary || "auto",
344
+ };
345
+ params.include = ["reasoning.encrypted_content"];
346
+ } else if (model.provider !== "github-copilot" && model.thinkingLevelMap?.off !== null) {
347
+ params.reasoning = {
348
+ effort: (model.thinkingLevelMap?.off ?? "none") as NonNullable<typeof params.reasoning>["effort"],
349
+ };
350
+ }
351
+ if (model.provider === "xai") params.include = ["reasoning.encrypted_content"];
352
+ }
353
+
354
+ // Last so custom keys override the named request fields.
355
+ if (options?.samplingParams) {
356
+ Object.assign(params, options.samplingParams);
357
+ }
358
+
359
+ return params;
360
+ }
361
+
362
+ function getServiceTierCostMultiplier(
363
+ model: Pick<Model<"openai-responses">, "id">,
364
+ serviceTier: ResponseCreateParamsStreaming["service_tier"] | undefined,
365
+ ): number {
366
+ switch (serviceTier) {
367
+ case "flex":
368
+ return 0.5;
369
+ case "priority":
370
+ return model.id === "gpt-5.5" ? 2.5 : 2;
371
+ default:
372
+ return 1;
373
+ }
374
+ }
375
+
376
+ function applyServiceTierPricing(
377
+ usage: Usage,
378
+ serviceTier: ResponseCreateParamsStreaming["service_tier"] | undefined,
379
+ model: Pick<Model<"openai-responses">, "id">,
380
+ ) {
381
+ const multiplier = getServiceTierCostMultiplier(model, serviceTier);
382
+ if (multiplier === 1) return;
383
+
384
+ usage.cost.input *= multiplier;
385
+ usage.cost.output *= multiplier;
386
+ usage.cost.cacheRead *= multiplier;
387
+ usage.cost.cacheWrite *= multiplier;
388
+ usage.cost.total = usage.cost.input + usage.cost.output + usage.cost.cacheRead + usage.cost.cacheWrite;
389
+ }