notesoup 0.44.0 → 0.45.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/README.md +1 -0
  2. package/cordis.patch.yml +14 -0
  3. package/dist/src/dsh/budget.d.ts +20 -0
  4. package/dist/src/dsh/budget.js +34 -0
  5. package/dist/src/dsh/engine.d.ts +22 -0
  6. package/dist/src/dsh/engine.js +193 -0
  7. package/dist/src/dsh/history.d.ts +6 -0
  8. package/dist/src/dsh/history.js +73 -0
  9. package/dist/src/dsh/index.d.ts +22 -0
  10. package/dist/src/dsh/index.js +63 -0
  11. package/dist/src/dsh/preflight.d.ts +8 -0
  12. package/dist/src/dsh/preflight.js +35 -0
  13. package/dist/src/dsh/tools.d.ts +3 -0
  14. package/dist/src/dsh/tools.js +111 -0
  15. package/dist/src/dsh/window.d.ts +46 -0
  16. package/dist/src/dsh/window.js +124 -0
  17. package/dist/test/dependencies.test.js +27 -1
  18. package/dist/test/dsh-cli.test.d.ts +1 -0
  19. package/dist/test/dsh-cli.test.js +44 -0
  20. package/dist/test/dsh-compaction-parity.test.d.ts +1 -0
  21. package/dist/test/dsh-compaction-parity.test.js +143 -0
  22. package/dist/test/dsh.test.d.ts +1 -0
  23. package/dist/test/dsh.test.js +323 -0
  24. package/dist/test/helpers/dependency-graph.js +3 -3
  25. package/dist/test/helpers/dsh-messages.d.ts +29 -0
  26. package/dist/test/helpers/dsh-messages.js +33 -0
  27. package/dist/test/helpers/dsh.d.ts +17 -0
  28. package/dist/test/helpers/dsh.js +50 -0
  29. package/docs/architecture.md +4 -1
  30. package/docs/dsh.md +61 -0
  31. package/docs/dsh.profile.patch.yml +34 -0
  32. package/mods/notesoup/.claude-plugin/plugin.json +1 -1
  33. package/package.json +63 -4
  34. package/src/dsh/budget.ts +35 -0
  35. package/src/dsh/engine.ts +160 -0
  36. package/src/dsh/history.ts +57 -0
  37. package/src/dsh/index.ts +69 -0
  38. package/src/dsh/preflight.ts +29 -0
  39. package/src/dsh/tools.ts +107 -0
  40. package/src/dsh/window.ts +126 -0
  41. package/mods/pi-context/dist/claude/helper.js +0 -9324
@@ -0,0 +1,46 @@
1
+ import type { Agent } from "@deepseek-ai/dsh-agent";
2
+ import { type Session, type SessionEvent } from "@deepseek-ai/dsh-session";
3
+ import { type NotesIdentity } from "../notes/identity.js";
4
+ export declare const WINDOW_RECORD = "plugin:notesoup/window";
5
+ export declare const BOOT_SECTION = "notesoup:boot";
6
+ export type WindowSnapshot = Readonly<{
7
+ version: 1;
8
+ window: number;
9
+ windowId: string;
10
+ openedAt: number;
11
+ boot: string;
12
+ notesDigest: string;
13
+ }>;
14
+ export type WindowState = {
15
+ snapshot: WindowSnapshot;
16
+ pendingReset: boolean;
17
+ warned: boolean;
18
+ reminded: boolean;
19
+ };
20
+ export type NotesConfig = {
21
+ notesHome?: string;
22
+ agentName?: string;
23
+ };
24
+ export declare function restoreWarnings(state: WindowState, events: readonly SessionEvent[]): void;
25
+ declare module "@deepseek-ai/dsh-session/types" {
26
+ interface PluginRecordMap {
27
+ "plugin:notesoup/window": WindowSnapshot;
28
+ }
29
+ }
30
+ export declare function windowId(sessionId: string, window: number): string;
31
+ export declare function checkpointText(snapshot: WindowSnapshot): string;
32
+ export declare function recordSnapshot(event: SessionEvent): WindowSnapshot | undefined;
33
+ /** The checkpoint is authoritative when an ignorable record was lost or the transaction's close failed. */
34
+ export declare function checkpointSnapshot(event: SessionEvent): WindowSnapshot | undefined;
35
+ export declare function recoverSnapshot(events: readonly SessionEvent[]): WindowSnapshot | undefined;
36
+ /** Identity is extracted here, never in the filesystem domain. */
37
+ export declare function notesIdentity(agent: Pick<Agent, "session" | "options">, config: NotesConfig): NotesIdentity;
38
+ /** Engine-owned, per-session state; prompt reads are synchronous and never read notes again. */
39
+ export declare class Windows {
40
+ readonly config: NotesConfig;
41
+ private states;
42
+ constructor(config: NotesConfig);
43
+ get(session: Session): WindowState;
44
+ adopt(agent: Agent, signal?: AbortSignal): Promise<WindowState>;
45
+ mint(agent: Pick<Agent, "session" | "options">, window: number, openedAt: number): Promise<WindowSnapshot>;
46
+ }
@@ -0,0 +1,124 @@
1
+ import { appendPluginRecord, pluginRecordOf } from "@deepseek-ai/dsh-session";
2
+ import { isCompactCheckpointSource } from "@deepseek-ai/dsh-compaction";
3
+ import { homedir } from "node:os";
4
+ import { join } from "node:path";
5
+ import { createHash } from "node:crypto";
6
+ import { loadNotesSnapshot } from "../boot/snapshot.js";
7
+ import { renderBootBlock } from "../boot/render.js";
8
+ import { CONTINUATION } from "../budget/text.js";
9
+ import { contentText } from "../history/history.js";
10
+ import { slugify } from "../notes/paths.js";
11
+ import { resolveProjectHome } from "../notes/project-home.js";
12
+ import { snapshotNotesIdentity } from "../notes/identity.js";
13
+ export const WINDOW_RECORD = "plugin:notesoup/window";
14
+ export const BOOT_SECTION = "notesoup:boot";
15
+ const BOOT_OPEN = "<notesoup-boot>\n";
16
+ const BOOT_CLOSE = "\n</notesoup-boot>";
17
+ const CHECKPOINT_END = "\n\n<notesoup-continuation>\n";
18
+ const TOOLS = { notes: "notes_*", notesList: "notes_list", history: "history_*", remaining: "get_context_remaining", wipe: "clear_memory" };
19
+ export function restoreWarnings(state, events) {
20
+ state.warned = false;
21
+ state.reminded = false;
22
+ for (const event of events) {
23
+ if (event.type === "user/message" && event.data.source.kind === "notesoup-budget" && event.data.source.windowId === state.snapshot.windowId) {
24
+ if (event.data.source.phase === "warning")
25
+ state.warned = true;
26
+ else
27
+ state.reminded = true;
28
+ }
29
+ }
30
+ }
31
+ export function windowId(sessionId, window) { return `dsh:${sessionId}:${window}`; }
32
+ function digest(boot) { return createHash("sha256").update(boot).digest("hex"); }
33
+ export function checkpointText(snapshot) { return snapshot.boot + CHECKPOINT_END + CONTINUATION + "\n</notesoup-continuation>"; }
34
+ export function recordSnapshot(event) {
35
+ const record = pluginRecordOf(event);
36
+ if (record?.type !== WINDOW_RECORD || typeof record.data !== "object" || record.data === null)
37
+ return undefined;
38
+ const value = record.data;
39
+ if (value.version !== 1 || !Number.isSafeInteger(value.window) || value.window < 0 || typeof value.windowId !== "string" || typeof value.openedAt !== "number" || typeof value.boot !== "string" || value.notesDigest !== digest(value.boot))
40
+ return undefined;
41
+ return Object.freeze(value);
42
+ }
43
+ /** The checkpoint is authoritative when an ignorable record was lost or the transaction's close failed. */
44
+ export function checkpointSnapshot(event) {
45
+ if (event.type !== "user/message" || !isCompactCheckpointSource(event.data.source))
46
+ return undefined;
47
+ const text = contentText(event.data.content);
48
+ const end = text.lastIndexOf(CHECKPOINT_END);
49
+ if (end < 0 || !text.startsWith(BOOT_OPEN))
50
+ return undefined;
51
+ return snapshotFromBoot(text.slice(0, end), event.time);
52
+ }
53
+ function systemSnapshot(event) {
54
+ if (event.type !== "system/message")
55
+ return undefined;
56
+ const text = contentText(event.data.message.content);
57
+ const start = text.indexOf(BOOT_OPEN);
58
+ const end = text.lastIndexOf(BOOT_CLOSE);
59
+ if (start < 0 || end < 0)
60
+ return undefined;
61
+ return snapshotFromBoot(text.slice(start, end + BOOT_CLOSE.length), event.time);
62
+ }
63
+ function snapshotFromBoot(boot, openedAt) {
64
+ const id = /^Current context window id: (dsh:.*:(\d+))$/m.exec(boot);
65
+ if (!id || !Number.isSafeInteger(Number(id[2])))
66
+ return undefined;
67
+ return Object.freeze({ version: 1, window: Number(id[2]), windowId: id[1], openedAt, boot, notesDigest: digest(boot) });
68
+ }
69
+ export function recoverSnapshot(events) {
70
+ let latest;
71
+ for (const event of events) {
72
+ const candidate = checkpointSnapshot(event) ?? recordSnapshot(event) ?? systemSnapshot(event);
73
+ if (candidate && (!latest || candidate.window >= latest.window))
74
+ latest = candidate;
75
+ }
76
+ return latest;
77
+ }
78
+ /** Identity is extracted here, never in the filesystem domain. */
79
+ export function notesIdentity(agent, config) {
80
+ const home = config.notesHome ?? join(homedir(), ".agents", "notes");
81
+ return snapshotNotesIdentity({
82
+ home,
83
+ sessionId: agent.session.id,
84
+ projectKey: resolveProjectHome(agent.session.header.cwd ?? process.cwd(), home).name,
85
+ agent: slugify(config.agentName ?? "dsh"),
86
+ model: slugify(agent.session.requestHeader()?.config.model ?? agent.options.model ?? "unknown"),
87
+ });
88
+ }
89
+ /** Engine-owned, per-session state; prompt reads are synchronous and never read notes again. */
90
+ export class Windows {
91
+ config;
92
+ states = new WeakMap();
93
+ constructor(config) {
94
+ this.config = config;
95
+ }
96
+ get(session) {
97
+ const state = this.states.get(session);
98
+ if (!state)
99
+ throw Object.assign(new Error("notesoup: window missing; initialize at agent/created before sending a request."), { code: "WINDOW_MISSING" });
100
+ return state;
101
+ }
102
+ async adopt(agent, signal) {
103
+ const existing = this.states.get(agent.session);
104
+ if (existing)
105
+ return existing;
106
+ const restored = recoverSnapshot(agent.session.snapshotEvents());
107
+ const snapshot = restored ?? await this.mint(agent, 0, agent.session.header.createdAt);
108
+ signal?.throwIfAborted();
109
+ if (!restored)
110
+ appendPluginRecord(agent.session, WINDOW_RECORD, snapshot);
111
+ const state = { snapshot, pendingReset: false, warned: false, reminded: false };
112
+ restoreWarnings(state, agent.session.snapshotEvents());
113
+ this.states.set(agent.session, state);
114
+ return state;
115
+ }
116
+ async mint(agent, window, openedAt) {
117
+ const identity = notesIdentity(agent, this.config);
118
+ const notes = await loadNotesSnapshot(identity, openedAt);
119
+ const previous = this.states.get(agent.session)?.snapshot;
120
+ const firstWindowId = previous?.boot.match(/^First context window id: (.+)$/m)?.[1] ?? windowId(agent.session.id, 0);
121
+ const boot = BOOT_OPEN + renderBootBlock({ agentName: identity.agent, modelName: identity.model, firstWindowId, currentWindowId: windowId(agent.session.id, window), ...(window ? { previousWindowId: previous?.windowId ?? windowId(agent.session.id, window - 1) } : {}), notes, tools: TOOLS }) + BOOT_CLOSE;
122
+ return Object.freeze({ version: 1, window, windowId: windowId(agent.session.id, window), openedAt, boot, notesDigest: digest(boot) });
123
+ }
124
+ }
@@ -26,7 +26,7 @@ test("all shared domains resolve without any direct or transitive SDK, Pi adapte
26
26
  const parsed = ts.parseJsonConfigFileContent(config.config, ts.sys, root);
27
27
  assert.deepEqual(parsed.errors, []);
28
28
  const manifest = JSON.parse(readFileSync(join(root, "package.json"), "utf8"));
29
- const shared = sources(join(root, "src")).filter((file) => !file.startsWith(join(root, "src/pi/")) && file !== join(root, "src/index.ts"));
29
+ const shared = sources(join(root, "src")).filter((file) => !["pi", "claude", "dsh"].some((adapter) => file.startsWith(join(root, "src", adapter) + "/")) && file !== join(root, "src/index.ts"));
30
30
  for (const domain of ["notes", "boot", "history", "budget", "tools", "dream"])
31
31
  assert.ok(shared.some((file) => file.startsWith(join(root, "src", domain) + "/")), `${domain} is included`);
32
32
  assert.deepEqual(dependencyViolations(root, shared, parsed.options, new Set(["typebox"])), []);
@@ -35,6 +35,25 @@ test("all shared domains resolve without any direct or transitive SDK, Pi adapte
35
35
  assert.equal(manifest.peerDependencies[name], "*", `${name} follows Pi's host dependency contract`);
36
36
  }
37
37
  });
38
+ test("dsh resolves into shared domains without Pi, Claude, dream or the root entry", () => {
39
+ const root = repository();
40
+ const seen = new Set();
41
+ const inspect = (file) => {
42
+ if (seen.has(file))
43
+ return;
44
+ seen.add(file);
45
+ assert.ok(!["pi", "claude", "dream"].some((adapter) => file.startsWith(join(root, "src", adapter) + "/")) && file !== join(root, "src/index.ts"), file);
46
+ const source = ts.createSourceFile(file, readFileSync(file, "utf8"), ts.ScriptTarget.Latest, true);
47
+ for (const reference of moduleReferences(source)) {
48
+ assert.ok(!/^@(?:earendil-works|mariozechner)\/pi-/.test(reference), reference);
49
+ const resolved = ts.resolveModuleName(reference, file, options, ts.sys).resolvedModule;
50
+ if (resolved && resolved.resolvedFileName.startsWith(join(root, "src") + "/"))
51
+ inspect(resolved.resolvedFileName);
52
+ }
53
+ };
54
+ for (const file of sources(join(root, "src/dsh")))
55
+ inspect(file);
56
+ });
38
57
  test("dependency guard follows indirect types, re-exports, dynamic imports and import-type edges through resolved aliases", (t) => {
39
58
  const root = mkdtempSync(join(tmpdir(), "context-dependencies-"));
40
59
  t.after(() => rmSync(root, { recursive: true, force: true }));
@@ -56,6 +75,13 @@ test("dependency guard follows indirect types, re-exports, dynamic imports and i
56
75
  "src/boot/snapshot.ts -> src/pi/native.ts",
57
76
  "src/history/query.ts -> src/history/decoder.ts -> @earendil-works/pi-coding-agent",
58
77
  ]);
78
+ put("src/boot/snapshot.ts", 'export type Snapshot = import("../dsh/native.js").Native;');
79
+ put("src/dsh/native.ts", "export type Native = string;");
80
+ put("src/history/query.ts", 'export type { Session } from "@deepseek-ai/dsh-session";');
81
+ assert.deepEqual(dependencyViolations(root, ["src/boot/snapshot.ts", "src/history/query.ts"], fixtureOptions, new Set()), [
82
+ "src/boot/snapshot.ts -> src/dsh/native.ts",
83
+ "src/history/query.ts -> @deepseek-ai/dsh-session",
84
+ ]);
59
85
  put("src/notes/bridge.ts", 'export type { Value as Native } from "./safe.js";');
60
86
  put("src/notes/safe.ts", "export type Value = string;");
61
87
  assert.deepEqual(dependencyViolations(root, ["src/notes/identity.ts"], fixtureOptions, new Set()), [], "a host-neutral type/re-export chain is allowed");
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,44 @@
1
+ import assert from "node:assert/strict";
2
+ import test from "node:test";
3
+ import { execFile } from "node:child_process";
4
+ import { promisify } from "node:util";
5
+ import { mkdtemp, mkdir, readFile, writeFile, rm, readdir } from "node:fs/promises";
6
+ import { tmpdir } from "node:os";
7
+ import { join, resolve } from "node:path";
8
+ import { fileURLToPath, pathToFileURL } from "node:url";
9
+ import { messagesServer } from "./helpers/dsh-messages.js";
10
+ const exec = promisify(execFile);
11
+ const repository = fileURLToPath(new URL("../../", import.meta.url));
12
+ const system = (request) => typeof request.system === "string" ? request.system : request.system?.map((block) => block.text).join("\n") ?? "";
13
+ test("dsh profile loads our rows and a second process restores the on-disk window", { timeout: 45000 }, async (t) => {
14
+ const directory = await mkdtemp(join(tmpdir(), "notesoup-dsh-cli-"));
15
+ const mock = await messagesServer();
16
+ t.after(async () => { await mock.close(); await rm(directory, { recursive: true, force: true }); });
17
+ const home = join(directory, "home");
18
+ const profile = join(home, "profiles", "notesoup-test");
19
+ await mkdir(profile, { recursive: true });
20
+ await writeFile(join(home, "cordis.patch.yml"), "[]\n");
21
+ await writeFile(join(profile, "cordis.yml"), "[]\n");
22
+ await writeFile(join(profile, "package.json"), JSON.stringify({ name: "notesoup-test", private: true, version: "0.0.0", dsh: { profile: { bundles: ["@deepseek-ai/dsh-base", "@deepseek-ai/dsh-headless"] } } }));
23
+ const example = await readFile(join(repository, "docs/dsh.profile.patch.yml"), "utf8");
24
+ const patch = example
25
+ .replace("'notesoup/dsh/engine'", `'${pathToFileURL(join(repository, "dist/src/dsh/engine.js")).href}'`)
26
+ .replace("'notesoup/dsh'", `'${pathToFileURL(join(repository, "dist/src/dsh/index.js")).href}'`)
27
+ .replace("# notesHome: /absolute/path/to/notes", `notesHome: ${join(directory, "notes")}`);
28
+ await writeFile(join(profile, "cordis.patch.yml"), patch + "\n- id: session-title-llm\n disabled: true\n");
29
+ const env = { ...process.env, DSH_HOME: home, DEEPSEEK_API_KEY: "mock-key", DEEPSEEK_BASE_URL: mock.url, DSH_TOOLS_MODE: "native" };
30
+ const cli = resolve(repository, "node_modules/@deepseek-ai/dsh/lib/bin.js");
31
+ mock.script.push({ tool: "clear_memory", input: {} }, { text: "after reset" });
32
+ const first = await exec(process.execPath, [cli, "--profile", "notesoup-test", "old conversation"], { cwd: directory, env, timeout: 20000 });
33
+ assert.equal(mock.requests.length, 2, first.stderr);
34
+ assert.equal(mock.requests[1].messages.length, 1);
35
+ assert.notEqual(system(mock.requests[0]), system(mock.requests[1]));
36
+ const sessionPaths = await readdir(join(home, "sessions"), { recursive: true });
37
+ const sessionId = sessionPaths.map((entry) => entry.split("/").at(-1)).find((entry) => entry.startsWith("session-"));
38
+ assert.ok(sessionId, JSON.stringify(sessionPaths));
39
+ mock.script.push({ text: "reloaded" });
40
+ const second = await exec(process.execPath, [cli, "--profile", "notesoup-test", "--session-id", sessionId, "resume"], { cwd: directory, env, timeout: 20000 });
41
+ assert.equal(mock.requests.length, 3, second.stderr);
42
+ assert.equal(system(mock.requests[2]), system(mock.requests[1]));
43
+ assert.equal(JSON.stringify(mock.requests[2].messages).includes("old conversation"), false);
44
+ });
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,143 @@
1
+ import assert from "node:assert/strict";
2
+ import test from "node:test";
3
+ import { BasicCompactionEngine } from "@deepseek-ai/dsh-compaction-basic";
4
+ import { createUserMessage } from "@deepseek-ai/dsh-llm";
5
+ import { pluginRecordOf } from "@deepseek-ai/dsh-session";
6
+ import { dshFixture } from "./helpers/dsh.js";
7
+ import { WINDOW_RECORD } from "../src/dsh/window.js";
8
+ /** Pin the shared host contract while naming our intentional template-vs-LLM differences. */
9
+ function transactionShape(session, from, head, result) {
10
+ const events = session.snapshotEvents().slice(from);
11
+ const records = events.filter((event) => event.type.startsWith("compaction/") || event.type === "user/message");
12
+ for (const event of records)
13
+ assert.deepEqual(Object.keys(event).sort(), event.type === "user/message" ? ["data", "seq", "sourceEventSeqs", "surfaceOp", "time", "type"] : ["data", "seq", "time", "type"]);
14
+ const start = records[0];
15
+ const summary = records[1];
16
+ const end = records.at(-1);
17
+ assert.equal(start.type, "compaction/start");
18
+ assert.equal(summary.type, "compaction/summary");
19
+ assert.equal(end.type, "compaction/end");
20
+ if (start.type !== "compaction/start" || summary.type !== "compaction/summary" || end.type !== "compaction/end")
21
+ assert.fail("compaction protocol changed");
22
+ assert.deepEqual(Object.keys(start.data).sort(), ["compactionId", "turn"]);
23
+ assert.deepEqual(Object.keys(end.data).sort(), result ? ["compactionId", "turn"] : ["compactionId", "error", "turn"]);
24
+ assert.equal(summary.data.compactionId, start.data.compactionId);
25
+ assert.equal(end.data.compactionId, start.data.compactionId);
26
+ assert.equal(end.data.turn, start.data.turn);
27
+ assert.equal(typeof start.data.compactionId, "string");
28
+ assert.equal(typeof summary.data.shadowedTokenCount, "number");
29
+ const fields = Object.keys(summary.data).sort();
30
+ const common = ["compactionId", "model", "provider", "shadowedRange", "shadowedSeqs", "shadowedTokenCount", "summary"].sort();
31
+ if (summary.data.provider === "notesoup") {
32
+ assert.deepEqual(fields, common);
33
+ const window = events.map(pluginRecordOf).find((record) => record?.type === WINDOW_RECORD);
34
+ if (result) {
35
+ assert.ok(window);
36
+ assert.deepEqual(Object.keys(window.data).sort(), ["boot", "notesDigest", "openedAt", "version", "window", "windowId"]);
37
+ assert.equal(events.find((event) => event.seq === window.seq)?.ignorable, true);
38
+ assert.ok(window.seq > end.seq);
39
+ }
40
+ else
41
+ assert.equal(window, undefined);
42
+ }
43
+ else {
44
+ assert.deepEqual(fields, [...common, "llmStreamCall", "maxTokens", "rawOutput", "usage"].sort());
45
+ assert.equal(summary.data.llmStreamCall, true);
46
+ }
47
+ assert.equal(session.surface.nodes[0], head);
48
+ assert.deepEqual(summary.data.shadowedRange, { start: summary.data.shadowedSeqs[0], end: summary.data.shadowedSeqs.at(-1) });
49
+ if (result) {
50
+ assert.deepEqual(Object.keys(result).sort(), ["compactionId", "endSeq", "shadowedRange", "shadowedSeqs", "shadowedTokenCount", "startSeq", "summary", "summarySeq"]);
51
+ assert.equal(result.startSeq, start.seq);
52
+ assert.equal(result.summarySeq, summary.seq);
53
+ assert.equal(result.endSeq, end.seq);
54
+ assert.deepEqual(result.summary, summary.data.summary);
55
+ const replacement = records[2];
56
+ assert.equal(replacement.type, "user/message");
57
+ if (replacement.type !== "user/message")
58
+ assert.fail("checkpoint message changed");
59
+ assert.deepEqual(Object.keys(replacement.data).sort(), ["content", "id", "role", "source"]);
60
+ assert.deepEqual(replacement.data.source, { kind: "compact-checkpoint", compactionId: start.data.compactionId });
61
+ assert.deepEqual(replacement.surfaceOp, { op: "replace", startSeq: result.shadowedRange.start, endSeq: result.shadowedRange.end });
62
+ assert.deepEqual(replacement.sourceEventSeqs, [start.seq, summary.seq, ...result.shadowedSeqs]);
63
+ assert.equal(replacement.seq, summary.seq + 1, "shadow price must be adjacent to replacement");
64
+ assert.ok(session.surface.nodes.includes(replacement.seq));
65
+ }
66
+ return { types: records.map((event) => event.type), owner: start.data.turn, summaryFields: common, error: typeof end.data.error };
67
+ }
68
+ async function seedAgents(fixture) {
69
+ const ours = await fixture.create();
70
+ const native = await fixture.create();
71
+ for (const agent of [ours, native]) {
72
+ agent.followup(createUserMessage({ source: { kind: "user" }, content: [{ type: "text", text: "long enough for Basic's shrink check. ".repeat(500) }] }));
73
+ await agent.whenIdle();
74
+ }
75
+ return { ours, native };
76
+ }
77
+ test("dsh compaction parity: open-turn and idle transactions match Basic's event and replacement contract", async (t) => {
78
+ const fixture = await dshFixture(t);
79
+ const { ours, native } = await seedAgents(fixture);
80
+ const child = fixture.ctx.isolate("compaction");
81
+ const fiber = await child.plugin(BasicCompactionEngine, { auto: false });
82
+ t.after(() => fiber.dispose());
83
+ const basic = child.compaction;
84
+ const oursHead = ours.session.surface.nodes[0];
85
+ const nativeHead = native.session.surface.nodes[0];
86
+ ours.session.append("turn/start", { turn: 2 });
87
+ native.session.append("turn/start", { turn: 2 });
88
+ const oursFrom = ours.session.seq;
89
+ const nativeFrom = native.session.seq;
90
+ fixture.mock.script.push({ text: "checkpoint ".repeat(1000) });
91
+ const oursResult = await fixture.engine.compactRegion(ours.session.surface.nodes[1], ours.session.surface.nodes.at(-1), ours);
92
+ const nativeResult = await basic.compactRegion(native.session.surface.nodes[1], native.session.surface.nodes.at(-1), native);
93
+ assert.equal(oursResult.shadowedSeqs.length, 2);
94
+ assert.equal(nativeResult.shadowedSeqs.length, 2);
95
+ assert.equal(ours.session.surface.nodes.length, 2);
96
+ assert.equal(native.session.surface.nodes.length, 2);
97
+ assert.equal(transactionShape(ours.session, oursFrom, oursHead, oursResult).owner, 2);
98
+ assert.deepEqual(transactionShape(ours.session, oursFrom, oursHead, oursResult), transactionShape(native.session, nativeFrom, nativeHead, nativeResult));
99
+ ours.session.append("turn/end", { turn: 2, reason: { kind: "completed" } });
100
+ native.session.append("turn/end", { turn: 2, reason: { kind: "completed" } });
101
+ // Add enough fresh text for Basic's idle shrink requirement, without another model turn.
102
+ for (const agent of [ours, native])
103
+ agent.session.append("user/message", createUserMessage({ source: { kind: "user" }, content: [{ type: "text", text: "idle input ".repeat(500) }] }), { surfaceOp: "append" });
104
+ const oursIdle = ours.session.seq;
105
+ const nativeIdle = native.session.seq;
106
+ fixture.mock.script.push({ text: "checkpoint" });
107
+ const oursManual = await fixture.engine.compactNow(ours, new AbortController().signal);
108
+ const nativeManual = await basic.compactNow(native, new AbortController().signal);
109
+ assert.ok(oursManual && nativeManual);
110
+ assert.equal(oursManual.shadowedSeqs.length, 2);
111
+ assert.equal(nativeManual.shadowedSeqs.length, 1, "Basic retains the last node; notesoup intentionally retains none");
112
+ assert.equal(ours.session.surface.nodes.length, 2);
113
+ assert.equal(native.session.surface.nodes.length, 3);
114
+ assert.equal(transactionShape(ours.session, oursIdle, oursHead, oursManual).owner, null);
115
+ assert.deepEqual(transactionShape(ours.session, oursIdle, oursHead, oursManual), transactionShape(native.session, nativeIdle, nativeHead, nativeManual));
116
+ assert.equal(fixture.mock.requests.length, 4, "only Basic calls the model during these two transactions");
117
+ });
118
+ test("dsh compaction parity: rejected checkpoint closes the bracket and leaves node zero and surface intact", async (t) => {
119
+ const fixture = await dshFixture(t);
120
+ const { ours, native } = await seedAgents(fixture);
121
+ const child = fixture.ctx.isolate("compaction");
122
+ const fiber = await child.plugin(BasicCompactionEngine, { auto: false });
123
+ t.after(() => fiber.dispose());
124
+ const fail = new Error("injected checkpoint rejection");
125
+ const shapes = [];
126
+ for (const [agent, engine] of [[ours, fixture.engine], [native, child.compaction]]) {
127
+ agent.session.append("turn/start", { turn: 2 });
128
+ const surface = [...agent.session.surface.nodes];
129
+ const from = agent.session.seq;
130
+ const append = agent.session.append.bind(agent.session);
131
+ t.mock.method(agent.session, "append", (...args) => { if (args[0] === "user/message")
132
+ throw fail; return append(...args); });
133
+ if (agent === native)
134
+ fixture.mock.script.push({ text: "checkpoint" });
135
+ await assert.rejects(engine.compactRegion(surface[1], surface.at(-1), agent), (error) => error === fail);
136
+ assert.deepEqual(agent.session.surface.nodes, surface);
137
+ shapes.push(transactionShape(agent.session, from, surface[0]));
138
+ t.mock.restoreAll();
139
+ agent.session.append("turn/end", { turn: 2, reason: { kind: "completed" } });
140
+ }
141
+ assert.deepEqual(shapes[0], shapes[1]);
142
+ assert.equal(fixture.engine.windows.get(ours.session).snapshot.window, 0);
143
+ });
@@ -0,0 +1 @@
1
+ export {};