notesoup 0.47.1 → 0.48.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -2
- package/dist/src/boot/render.d.ts +14 -7
- package/dist/src/boot/render.js +29 -16
- package/dist/src/boot/text.d.ts +25 -4
- package/dist/src/boot/text.js +60 -13
- package/dist/src/budget/constants.d.ts +2 -4
- package/dist/src/budget/constants.js +2 -4
- package/dist/src/budget/policy.d.ts +2 -2
- package/dist/src/budget/policy.js +3 -3
- package/dist/src/budget/text.d.ts +29 -9
- package/dist/src/budget/text.js +51 -10
- package/dist/src/claude/helper.d.ts +2 -3
- package/dist/src/claude/helper.js +45 -11
- package/dist/src/claude/history.d.ts +9 -0
- package/dist/src/claude/history.js +271 -0
- package/dist/src/dsh/budget.js +1 -1
- package/dist/src/dsh/engine.d.ts +2 -1
- package/dist/src/dsh/engine.js +18 -9
- package/dist/src/dsh/index.js +9 -4
- package/dist/src/dsh/tools.js +1 -1
- package/dist/src/dsh/window.d.ts +2 -1
- package/dist/src/dsh/window.js +14 -8
- package/dist/src/history/query.js +59 -81
- package/dist/src/notes/address.d.ts +5 -0
- package/dist/src/notes/address.js +20 -21
- package/dist/src/notes/store.js +12 -19
- package/dist/src/pi/boot.d.ts +1 -1
- package/dist/src/pi/boot.js +28 -5
- package/dist/src/pi/budget.d.ts +1 -3
- package/dist/src/pi/budget.js +20 -61
- package/dist/src/pi/entries.d.ts +0 -1
- package/dist/src/pi/entries.js +0 -1
- package/dist/src/pi/history.d.ts +3 -0
- package/dist/src/pi/history.js +4 -0
- package/dist/src/pi/reset/artifacts.d.ts +7 -2
- package/dist/src/pi/reset/artifacts.js +16 -14
- package/dist/src/pi/reset/lifecycle.d.ts +21 -25
- package/dist/src/pi/reset/lifecycle.js +48 -72
- package/dist/src/pi/runtime.js +9 -8
- package/dist/src/pi/window.d.ts +12 -6
- package/dist/src/pi/window.js +7 -0
- package/dist/test/agent-loop.test.js +53 -30
- package/dist/test/boot.integration.test.js +123 -12
- package/dist/test/budget-settings.integration.test.js +10 -6
- package/dist/test/claude-history.test.d.ts +1 -0
- package/dist/test/claude-history.test.js +184 -0
- package/dist/test/claude-mod.test.js +236 -42
- package/dist/test/dsh.test.js +80 -3
- package/dist/test/helpers/extension.d.ts +3 -0
- package/dist/test/helpers/extension.js +33 -5
- package/dist/test/history.integration.test.js +66 -0
- package/dist/test/host-neutral.test.js +1 -1
- package/dist/test/model-facing-text.test.d.ts +1 -0
- package/dist/test/model-facing-text.test.js +181 -0
- package/dist/test/notes.integration.test.js +16 -18
- package/dist/test/reset-lifecycle.test.js +201 -46
- package/docs/architecture.md +3 -3
- package/docs/claude-code-mod.md +15 -3
- package/docs/dsh.md +2 -2
- package/docs/reset-lifecycle.md +32 -20
- package/docs/skills.md +1 -1
- package/mods/notesoup/.claude-plugin/plugin.json +1 -1
- package/mods/notesoup/dist/claude/helper.js +836 -92
- package/mods/notesoup/hooks/register.ts +140 -38
- package/package.json +1 -1
- package/src/boot/render.ts +41 -23
- package/src/boot/text.ts +69 -13
- package/src/budget/constants.ts +2 -4
- package/src/budget/policy.ts +3 -3
- package/src/budget/text.ts +61 -10
- package/src/claude/helper.ts +53 -22
- package/src/claude/history.ts +228 -0
- package/src/dsh/budget.ts +1 -1
- package/src/dsh/engine.ts +16 -9
- package/src/dsh/index.ts +8 -3
- package/src/dsh/tools.ts +1 -1
- package/src/dsh/window.ts +15 -9
- package/src/history/query.ts +57 -82
- package/src/notes/address.ts +19 -16
- package/src/notes/store.ts +9 -14
- package/src/pi/boot.ts +27 -5
- package/src/pi/budget.ts +20 -58
- package/src/pi/entries.ts +0 -1
- package/src/pi/history.ts +7 -2
- package/src/pi/reset/artifacts.ts +17 -14
- package/src/pi/reset/lifecycle.ts +56 -79
- package/src/pi/runtime.ts +9 -8
- package/src/pi/window.ts +11 -1
|
@@ -0,0 +1,184 @@
|
|
|
1
|
+
import assert from "node:assert/strict";
|
|
2
|
+
import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
|
|
3
|
+
import { tmpdir } from "node:os";
|
|
4
|
+
import { join } from "node:path";
|
|
5
|
+
import test from "node:test";
|
|
6
|
+
import { claudeHistoryFromJsonl, readClaudeHistory } from "../src/claude/history.js";
|
|
7
|
+
import { renderBootBlock } from "../src/boot/render.js";
|
|
8
|
+
import { unavailableNotesSnapshot } from "../src/boot/snapshot.js";
|
|
9
|
+
import { DEFAULT_BOOT_TOOL_NAMES } from "../src/boot/text.js";
|
|
10
|
+
import { allItems, eventDocument } from "../src/history/history.js";
|
|
11
|
+
import { historyList, historyRead, historyWindows } from "../src/tools/history.js";
|
|
12
|
+
import { dispatch } from "../src/claude/helper.js";
|
|
13
|
+
const sessionId = "synthetic-session";
|
|
14
|
+
function row(uuid, parentUuid, type, content, extra = {}) {
|
|
15
|
+
return { uuid, parentUuid, type, sessionId, timestamp: "2026-01-01T00:00:00Z", isSidechain: false,
|
|
16
|
+
...(type === "system" ? { content } : { message: { role: type, content } }), ...extra };
|
|
17
|
+
}
|
|
18
|
+
const user = (uuid, parent, text) => row(uuid, parent, "user", text);
|
|
19
|
+
const assistant = (uuid, parent, content) => row(uuid, parent, "assistant", content);
|
|
20
|
+
const call = (id, name = "bash") => ({ type: "tool_use", id, name, input: { command: `echo ${id}` } });
|
|
21
|
+
const result = (id, text, error = false) => ({ type: "tool_result", tool_use_id: id, content: text, is_error: error });
|
|
22
|
+
const jsonl = (rows) => `${rows.map((row) => JSON.stringify(row)).join("\n")}\n`;
|
|
23
|
+
const project = (rows, headUuid) => claudeHistoryFromJsonl(jsonl(rows), { sessionId, headUuid });
|
|
24
|
+
// Complete boot shape, not a real/private transcript fixture. `context_window` is the pre-rename
|
|
25
|
+
// spelling that transcripts already on disk carry; both spellings must yield the same ordinal.
|
|
26
|
+
const bootText = (ordinal, spelling = "legacy") => spelling === "legacy"
|
|
27
|
+
? `<context_window>\nAgent name: claude (brain: claude)\n\nclaude:${sessionId}\n</context_window>\n\n<context_window_protocol>\nSynthetic reset protocol\n</context_window_protocol>\nCurrent context window id: claude:${sessionId}:${ordinal}`
|
|
28
|
+
: `<notesoup:window_identity>\nAgent name: claude (brain: claude)\n\nclaude:${sessionId}\n</notesoup:window_identity>\n\n<notesoup:notes_protocol>\nSynthetic reset protocol\n</notesoup:notes_protocol>\nCurrent context window id: claude:${sessionId}:${ordinal}`;
|
|
29
|
+
function compact(uuid, logical, metadata = {}) {
|
|
30
|
+
return row(uuid, null, "system", "Conversation compacted", { subtype: "compact_boundary", logicalParentUuid: logical, compactMetadata: metadata });
|
|
31
|
+
}
|
|
32
|
+
test("Claude append and result arrival preserve call addresses and use the shared paired read", async () => {
|
|
33
|
+
const rows = [user("u", null, "run tools"), assistant("a", "u", [{ type: "thinking", thinking: "private thought" }, { type: "text", text: "working" }, call("one"), call("two")])];
|
|
34
|
+
const pending = project(rows, "a");
|
|
35
|
+
assert.equal(pending.highestSeq, 4);
|
|
36
|
+
assert.equal(allItems(pending).find((event) => event.seq === 3)?.execution?.status, "unfinished");
|
|
37
|
+
assert.doesNotMatch(allItems(pending).map(eventDocument).join("\n"), /private thought/);
|
|
38
|
+
rows.push(row("r", "a", "user", [result("two", "failure", true), result("one", [{ type: "text", text: "output one" }, { type: "thinking", thinking: "hidden result thinking" }])]));
|
|
39
|
+
const completed = project(rows, "r");
|
|
40
|
+
assert.equal(completed.highestSeq, 7);
|
|
41
|
+
const read = await historyRead.execute({ seq: 3 }, completed);
|
|
42
|
+
assert.ok(read.ok);
|
|
43
|
+
assert.equal(read.data.tool_status, "ok");
|
|
44
|
+
assert.match(read.data.text, /bash \{"command":"echo one"\}\n--- output ---\noutput one/);
|
|
45
|
+
assert.doesNotMatch(read.data.text, /hidden/);
|
|
46
|
+
assert.equal(allItems(completed).find((event) => event.seq === 4)?.execution?.status, "error");
|
|
47
|
+
const resultRead = await historyRead.execute({ seq: 7 }, completed);
|
|
48
|
+
assert.ok(!resultRead.ok);
|
|
49
|
+
assert.equal(resultRead.error.code, "not_an_event");
|
|
50
|
+
assert.match(resultRead.error.message, /read seq 3/);
|
|
51
|
+
const search = await historyList.execute({ query: "output one" }, completed);
|
|
52
|
+
assert.ok(search.ok);
|
|
53
|
+
assert.deepEqual(search.data.items.map((item) => "seq" in item ? item.seq : -1), [3]);
|
|
54
|
+
});
|
|
55
|
+
test("Claude duplicate UUID records do not allocate again or move addresses on reload", () => {
|
|
56
|
+
const u = user("u", null, "hello"), a = assistant("a", "u", [call("one")]);
|
|
57
|
+
const original = project([u, a], "a");
|
|
58
|
+
const repeated = [u, a, { ...u, cwd: "/new/provenance" }, { ...a, cwd: "/new/provenance" }];
|
|
59
|
+
const reloaded = project(repeated, "a");
|
|
60
|
+
assert.equal(reloaded.highestSeq, original.highestSeq);
|
|
61
|
+
assert.deepEqual(reloaded, original);
|
|
62
|
+
assert.deepEqual(project(repeated, "a"), reloaded);
|
|
63
|
+
});
|
|
64
|
+
test("Claude branch selection is bound to committed head, not append order or last-prompt", async () => {
|
|
65
|
+
const rows = [user("u", null, "root"), assistant("left", "u", [call("left-call")]), row("left-result", "left", "user", [result("left-call", "left output")]), assistant("right", "u", [{ type: "text", text: "right branch" }]), { type: "last-prompt", leafUuid: "right", sessionId }];
|
|
66
|
+
const left = project(rows, "left-result"), right = project(rows, "right");
|
|
67
|
+
assert.equal(left.highestSeq, right.highestSeq);
|
|
68
|
+
assert.ok(!allItems(left).some((event) => event.text === "right branch"));
|
|
69
|
+
assert.equal(left.pairedResults.get(5), 3);
|
|
70
|
+
assert.deepEqual(allItems(right).map((event) => event.seq), [1, 6]);
|
|
71
|
+
const offBranch = await historyRead.execute({ seq: 3 }, right);
|
|
72
|
+
assert.ok(!offBranch.ok);
|
|
73
|
+
assert.equal(offBranch.error.code, "not_on_branch");
|
|
74
|
+
assert.throws(() => claudeHistoryFromJsonl(jsonl(rows), { sessionId }), /no confirmed active head/);
|
|
75
|
+
assert.throws(() => project(rows, "not-written-yet"), /not persisted yet/);
|
|
76
|
+
});
|
|
77
|
+
test("a persisted boot yields its ordinal under both tag spellings", () => {
|
|
78
|
+
// Three boundaries but one boot: only a recognised boot explains the ordinal.
|
|
79
|
+
const rowsFor = (boot) => [user("u", null, "old request"), assistant("a", "u", [{ type: "text", text: "answered" }]), compact("boundary", "a"), row("boot", "boundary", "user", boot), user("after", "boot", "after reset")];
|
|
80
|
+
const legacy = project(rowsFor(bootText(3)), "after");
|
|
81
|
+
const current = project(rowsFor(bootText(3, "current")), "after");
|
|
82
|
+
assert.equal(allItems(legacy).find((event) => event.text === "after reset")?.windowId, `claude:${sessionId}:3`, "an old-spelling boot numbers the window it opens");
|
|
83
|
+
assert.deepEqual(current.windows.map((window) => window.windowId), legacy.windows.map((window) => window.windowId));
|
|
84
|
+
const rendered = renderBootBlock({
|
|
85
|
+
agentName: "claude",
|
|
86
|
+
modelName: "claude",
|
|
87
|
+
tree: { trunk: `claude:${sessionId}`, windows: [{ shortName: "3", isCurrent: true }] },
|
|
88
|
+
notes: unavailableNotesSnapshot(Date.now()),
|
|
89
|
+
tools: DEFAULT_BOOT_TOOL_NAMES,
|
|
90
|
+
});
|
|
91
|
+
const real = project(rowsFor(`${rendered}\nCurrent context window id: claude:${sessionId}:3`), "after");
|
|
92
|
+
assert.deepEqual(real.windows.map((window) => window.windowId), current.windows.map((window) => window.windowId));
|
|
93
|
+
const partial = `<notesoup:window_identity>\nAgent name: claude (brain: claude)\n\nclaude:${sessionId}\n</notesoup:window_identity>\nCurrent context window id: claude:${sessionId}:3`;
|
|
94
|
+
assert.equal(allItems(project(rowsFor(partial), "after")).find((event) => event.text === "after reset")?.windowId, `claude:${sessionId}:1`, "an identity line without the protocol block is not a trusted boot");
|
|
95
|
+
});
|
|
96
|
+
test("Claude native compaction and reset keep pre-reset history, preserved rewrites and matching boot windows", async () => {
|
|
97
|
+
const old = assistant("old", "u", [{ type: "text", text: "before first reset" }]);
|
|
98
|
+
const reset = row("boot", "boundary", "user", bootText(1));
|
|
99
|
+
const rows = [user("u", null, "old request"), old,
|
|
100
|
+
compact("boundary", "old", { preservedSegment: { headUuid: "old", tailUuid: "old", anchorUuid: "boot" }, preservedMessages: { allUuids: ["old", "virtual-unpersisted-attachment"] } }), reset,
|
|
101
|
+
{ ...old, parentUuid: "boot" }, assistant("new", "old", [{ type: "text", text: "after first reset" }]),
|
|
102
|
+
compact("second", "new"), row("boot2", "second", "user", bootText(2)), user("latest", "boot2", "after second reset")];
|
|
103
|
+
const projection = project(rows, "latest");
|
|
104
|
+
assert.deepEqual(projection.windows.map((window) => window.windowId), [0, 1, 2].map((ordinal) => `claude:${sessionId}:${ordinal}`));
|
|
105
|
+
assert.equal(allItems(projection).filter((event) => event.text === "before first reset").length, 1);
|
|
106
|
+
assert.equal(allItems(projection).find((event) => event.text === "before first reset")?.windowId, `claude:${sessionId}:0`);
|
|
107
|
+
assert.equal(allItems(projection).find((event) => event.text === "after first reset")?.windowId, `claude:${sessionId}:1`);
|
|
108
|
+
assert.equal(projection.highestSeq, 8);
|
|
109
|
+
const previous = await historyList.execute({ window_id: "@previous", roles: ["assistant"] }, projection);
|
|
110
|
+
assert.ok(previous.ok);
|
|
111
|
+
assert.deepEqual(previous.data.items.map((item) => "content" in item ? item.content : ""), ["after first reset"]);
|
|
112
|
+
const windows = await historyWindows.execute({}, projection, sessionId);
|
|
113
|
+
assert.ok(windows.ok);
|
|
114
|
+
assert.equal(windows.data.windows[0]?.first_seq, 1);
|
|
115
|
+
assert.deepEqual(project(rows, "latest"), projection, "reload does not need an in-memory seq cache");
|
|
116
|
+
});
|
|
117
|
+
test("Claude reset crosses native turn_duration graph metadata with no message content", async () => {
|
|
118
|
+
const duration = { type: "system", subtype: "turn_duration", uuid: "duration", parentUuid: "old", sessionId, durationMs: 123, messageCount: 2 };
|
|
119
|
+
const rows = [user("u", null, "marker before reset"), assistant("old", "u", [{ type: "text", text: "finished turn" }]), duration,
|
|
120
|
+
compact("boundary", "duration"), row("boot", "boundary", "user", bootText(1)), user("continuation", "boot", "continue")];
|
|
121
|
+
const projection = project(rows, "continuation");
|
|
122
|
+
assert.equal(projection.highestSeq, 5, "duration metadata does not allocate a message address");
|
|
123
|
+
assert.equal(projection.windows.length, 2);
|
|
124
|
+
assert.ok(allItems(projection).some((event) => event.text === "marker before reset"));
|
|
125
|
+
assert.ok((await historyList.execute({ window_id: "@previous" }, projection)).ok);
|
|
126
|
+
assert.ok((await historyRead.execute({ seq: 2 }, projection)).ok);
|
|
127
|
+
assert.ok((await historyWindows.execute({}, projection, sessionId)).ok);
|
|
128
|
+
});
|
|
129
|
+
test("Claude resolves forward persisted ancestry without renumbering or using later rewritten parent versions", () => {
|
|
130
|
+
const notice = row("notice", "attachment", "system", "hook notice");
|
|
131
|
+
const attachment = { type: "attachment", uuid: "attachment", parentUuid: "u", sessionId };
|
|
132
|
+
const rows = [user("u", null, "root"), notice, attachment, compact("boundary", "notice"),
|
|
133
|
+
row("boot", "boundary", "user", bootText(1), { isCompactSummary: true }), { ...attachment, parentUuid: "boot" }, user("new", "attachment", "after reset")];
|
|
134
|
+
const projection = project(rows, "new");
|
|
135
|
+
assert.equal(projection.highestSeq, 6);
|
|
136
|
+
assert.equal(allItems(projection).find((event) => event.text === "hook notice")?.seq, 2);
|
|
137
|
+
assert.equal(allItems(projection).find((event) => event.text === "hook notice")?.windowId, `claude:${sessionId}:0`);
|
|
138
|
+
assert.equal(allItems(projection).find((event) => event.text === "after reset")?.windowId, `claude:${sessionId}:1`);
|
|
139
|
+
assert.deepEqual(project(rows, "new"), projection);
|
|
140
|
+
assert.throws(() => project([notice], "notice"), /missing.*ancestor/);
|
|
141
|
+
assert.equal(project([user("u", null, bootText(9))], "u").windows.length, 1, "ordinary user text is not a trusted retained boot");
|
|
142
|
+
});
|
|
143
|
+
test("Claude attachments expose recorded renderings only and keep non-rendered nodes in ancestry", () => {
|
|
144
|
+
const rows = [user("u", null, "hi"), { type: "attachment", uuid: "raw", parentUuid: "u", sessionId, attachment: { type: "prompt_snapshot", content: "must not invent raw payload" } },
|
|
145
|
+
{ type: "attachment", uuid: "rendered", parentUuid: "raw", sessionId, renderedRole: "user", rendered: [{ content: [{ type: "text", text: "visible injection" }] }] }];
|
|
146
|
+
const projection = project(rows, "rendered");
|
|
147
|
+
assert.deepEqual(allItems(projection).map((event) => event.seq), [1, 2, 3]);
|
|
148
|
+
assert.equal(allItems(projection).at(-1)?.role, "context");
|
|
149
|
+
assert.match(allItems(projection).map(eventDocument).join("\n"), /visible injection/);
|
|
150
|
+
assert.doesNotMatch(allItems(projection).map(eventDocument).join("\n"), /must not invent/);
|
|
151
|
+
});
|
|
152
|
+
test("Claude tolerates only the uncommitted JSONL tail, not malformed committed lines or unknown message shapes", () => {
|
|
153
|
+
const text = jsonl([user("u", null, "first")]);
|
|
154
|
+
assert.deepEqual(claudeHistoryFromJsonl(`${text}{\"type\":\"user\"`, { sessionId, headUuid: "u" }), project([user("u", null, "first")], "u"));
|
|
155
|
+
assert.equal(claudeHistoryFromJsonl(text.trimEnd(), { sessionId, headUuid: "u" }).highestSeq, 1);
|
|
156
|
+
assert.throws(() => claudeHistoryFromJsonl(`${text}{broken}\n`, { sessionId, headUuid: "u" }), /malformed.*line 2/);
|
|
157
|
+
assert.throws(() => project([user("u", null, "first"), { type: "new-message-schema", uuid: "unknown" }], "u"), /unsupported.*record type/);
|
|
158
|
+
assert.throws(() => project([row("u", null, "user", [{ type: "new-block-schema" }])], "u"), /unsupported.*content block/);
|
|
159
|
+
assert.throws(() => project([row("u", null, "user", { type: "text", text: "not an array" })], "u"), /message content/);
|
|
160
|
+
assert.throws(() => project([user("u", null, "first"), user("u", null, "conflict")], "u"), /conflicting.*duplicate UUID/);
|
|
161
|
+
assert.throws(() => project([{ ...user("u", null, "first"), isSidechain: true }], "u"), /only the main/);
|
|
162
|
+
assert.throws(() => project([{ ...user("u", null, "first"), sessionId: "another-session" }], "u"), /different session/);
|
|
163
|
+
});
|
|
164
|
+
test("Claude helper history tools reuse shared schemas, outcomes and text rendering from a supplied path", async (t) => {
|
|
165
|
+
const root = mkdtempSync(join(tmpdir(), "claude-history-"));
|
|
166
|
+
t.after(() => rmSync(root, { recursive: true, force: true }));
|
|
167
|
+
const transcriptPath = join(root, "transcript.jsonl"), rows = [user("u", null, "remember this"), assistant("a", "u", [call("one")]), row("r", "a", "user", [result("one", "recorded output")])];
|
|
168
|
+
writeFileSync(transcriptPath, jsonl(rows));
|
|
169
|
+
const identity = { home: join(root, "notes"), sessionId, cwd: root, agent: "claude", model: "claude" };
|
|
170
|
+
const history = { sessionId, transcriptPath, headUuid: "r" };
|
|
171
|
+
const projection = await readClaudeHistory(history);
|
|
172
|
+
const operations = [historyList, historyRead, historyWindows];
|
|
173
|
+
for (const operation of operations) {
|
|
174
|
+
const params = operation.name === "history_read" ? { seq: 3 } : {};
|
|
175
|
+
const actual = await dispatch({ op: "tool", tool: operation.name, params, identity, history });
|
|
176
|
+
const expected = operation.name === "history_read" ? { text: historyRead.render(await historyRead.execute({ seq: 3 }, projection)), ok: true }
|
|
177
|
+
: operation.name === "history_list" ? { text: historyList.render(await historyList.execute({}, projection)), ok: true }
|
|
178
|
+
: { text: historyWindows.render(await historyWindows.execute({}, projection, sessionId)), ok: true };
|
|
179
|
+
assert.deepEqual(actual, expected);
|
|
180
|
+
}
|
|
181
|
+
assert.deepEqual(await dispatch({ op: "history_state", identity, history }), { window: 0 });
|
|
182
|
+
await assert.rejects(dispatch({ op: "tool", tool: "history_windows", params: {}, identity }), /transcript_path is unavailable/);
|
|
183
|
+
await assert.rejects(dispatch({ op: "tool", tool: "history_windows", params: {}, identity, history: { ...history, sessionId: "other" } }), /different session/);
|
|
184
|
+
});
|
|
@@ -10,7 +10,7 @@ import { dispatch, handleLine } from "../src/claude/helper.js";
|
|
|
10
10
|
import { DEFAULT_CLAUDE_RESET_MARGIN_TOKENS, resolveClaudeLimits } from "../src/claude/thresholds.js";
|
|
11
11
|
import { WARNING_RUNWAY_TOKENS } from "../src/budget/constants.js";
|
|
12
12
|
import { PROTOCOL_WIPE_SENTENCE, CLAUDE_WIPE_SENTENCE, renderProtocolBlock } from "../src/boot/text.js";
|
|
13
|
-
import { CLAUDE_WARNING_PROMPT,
|
|
13
|
+
import { CLAUDE_WARNING_PROMPT, COUNTDOWN_LINE, FORCED_CONTINUATIONS } from "../src/budget/text.js";
|
|
14
14
|
import { createNotesStore } from "../src/notes/index.js";
|
|
15
15
|
import { resolveProjectHome } from "../src/notes/project-home.js";
|
|
16
16
|
import { notesIdentityFromPi } from "../src/pi/notes/adapter.js";
|
|
@@ -60,33 +60,58 @@ function fakeEngine(home) {
|
|
|
60
60
|
},
|
|
61
61
|
};
|
|
62
62
|
}
|
|
63
|
-
test("Claude
|
|
63
|
+
test("Claude notes survive removal of the session's worktree cwd", async (t) => {
|
|
64
|
+
const root = mkdtempSync(join(tmpdir(), "claude-deleted-worktree-"));
|
|
65
|
+
t.after(() => rmSync(root, { recursive: true, force: true }));
|
|
66
|
+
const repo = join(root, "repo"), home = join(root, "notes"), worktree = join(repo, ".worktrees", "job");
|
|
67
|
+
mkdirSync(repo);
|
|
68
|
+
const git = (...args) => execFileSync("git", args, { cwd: repo, stdio: "pipe" });
|
|
69
|
+
git("init");
|
|
70
|
+
git("-c", "user.name=Test", "-c", "user.email=test@example.invalid", "commit", "--allow-empty", "-m", "fixture");
|
|
71
|
+
git("worktree", "add", "--detach", worktree);
|
|
72
|
+
const { host } = fakeEngine(home);
|
|
73
|
+
host.session.cwd = async () => worktree;
|
|
74
|
+
const handlers = new Map();
|
|
75
|
+
(await loadHookModule(t)).register((event, handler) => handlers.set(event, handler));
|
|
76
|
+
await handlers.get("session.start")(host, { cwd: worktree, isInteractive: true }, async () => ({}));
|
|
77
|
+
const call = (tool, params) => handlers.get("tool.call")(host, { tool: `mcp__notesoup__${tool}`, tool_use_id: "probe", ...params }, async () => ({}));
|
|
78
|
+
for (const address of ["task.md", "@project/task.md"]) {
|
|
79
|
+
assert.equal((await call("notes_write", { address, content: "pending" })).isError, undefined);
|
|
80
|
+
}
|
|
81
|
+
git("worktree", "remove", worktree);
|
|
82
|
+
for (const address of ["task.md", "@project/task.md"]) {
|
|
83
|
+
const updated = await call("notes_update", { address, edits: [{ oldText: "pending", newText: "done" }] });
|
|
84
|
+
assert.equal(updated.isError, undefined, updated.result);
|
|
85
|
+
assert.match((await call("notes_read", { address })).result, /done/);
|
|
86
|
+
}
|
|
87
|
+
});
|
|
88
|
+
test("Claude helper exposes the eight shared notes/history schemas", async () => {
|
|
64
89
|
const schemas = await dispatch({ op: "schemas" });
|
|
65
|
-
assert.deepEqual(schemas.map((schema) => schema.name), ["notes_write", "notes_update", "notes_read", "notes_list", "notes_search"]);
|
|
90
|
+
assert.deepEqual(schemas.map((schema) => schema.name), ["notes_write", "notes_update", "notes_read", "notes_list", "notes_search", "history_list", "history_read", "history_windows"]);
|
|
66
91
|
assert.ok(schemas.every((schema) => schema.description.length > 20 && schema.inputSchema.type === "object"));
|
|
67
92
|
});
|
|
68
|
-
test("Claude helper delivers
|
|
93
|
+
test("Claude helper delivers only shared rendered text and success", async () => {
|
|
69
94
|
const write = await callTool("notes_write", { address: "checkpoint.md", content: "hello" });
|
|
70
|
-
assert.equal(write.
|
|
95
|
+
assert.equal(write.ok, true);
|
|
71
96
|
assert.match(write.text, /checkpoint\.md/);
|
|
72
97
|
assert.equal(write.text.includes("READ WINDOW"), false, "Claude reads the same presentation as Pi");
|
|
73
98
|
const missing = await callTool("notes_read", { address: "absent.md" });
|
|
74
|
-
assert.equal(missing.
|
|
75
|
-
assert.
|
|
99
|
+
assert.equal(missing.ok, false);
|
|
100
|
+
assert.deepEqual(Object.keys(missing).sort(), ["ok", "text"]);
|
|
76
101
|
assert.match(missing.text, /^error: not_found: /, "the refusal renders as the shared error line");
|
|
77
102
|
});
|
|
78
103
|
test("Claude helper rejects malformed or unknown requests", async () => {
|
|
79
104
|
const malformed = JSON.parse(await handleLine("not json"));
|
|
80
105
|
assert.equal(malformed.ok, false);
|
|
81
106
|
assert.match(malformed.error, /Unexpected|malformed/);
|
|
82
|
-
const unknown = JSON.parse(await handleLine(JSON.stringify({ op: "tool", tool: "
|
|
107
|
+
const unknown = JSON.parse(await handleLine(JSON.stringify({ op: "tool", tool: "history_search", identity, params: {} })));
|
|
83
108
|
assert.equal(unknown.ok, false);
|
|
84
109
|
assert.equal(unknown.error, "unknown tool");
|
|
85
110
|
});
|
|
86
111
|
test("Claude helper refuses schema-invalid parameters before any operation runs", async () => {
|
|
87
112
|
const address = "boundary.md";
|
|
88
113
|
const written = await callTool("notes_write", { address, content: "boundary body" });
|
|
89
|
-
assert.equal(written.
|
|
114
|
+
assert.equal(written.ok, true, "the fixture note exists before anything is refused");
|
|
90
115
|
const cases = [
|
|
91
116
|
{ name: "a string offset", params: { address, offset_chars: "0" } },
|
|
92
117
|
{ name: "a fractional offset", params: { address, offset_chars: 0.5 } },
|
|
@@ -102,10 +127,10 @@ test("Claude helper refuses schema-invalid parameters before any operation runs"
|
|
|
102
127
|
// Refusal happens before execute: a rejected mutation leaves nothing on disk.
|
|
103
128
|
await assert.rejects(callTool("notes_write", { address: "rejected.md", content: 42 }), /invalid notes_write parameters/);
|
|
104
129
|
const absent = await callTool("notes_read", { address: "rejected.md" });
|
|
105
|
-
assert.equal(absent.
|
|
106
|
-
assert.
|
|
130
|
+
assert.equal(absent.ok, false);
|
|
131
|
+
assert.match(absent.text, /^error: not_found: /, "the refused write never reached the store");
|
|
107
132
|
const valid = await callTool("notes_read", { address, offset_chars: 0, max_chars: 8 });
|
|
108
|
-
assert.equal(valid.
|
|
133
|
+
assert.equal(valid.ok, true, "a schema-valid window still reads");
|
|
109
134
|
assert.match(valid.text, /^boundary\.md/);
|
|
110
135
|
});
|
|
111
136
|
test("Claude helper boot uses actual Claude note tool bindings and a fresh snapshot", async () => {
|
|
@@ -117,13 +142,24 @@ test("Claude helper boot uses actual Claude note tool bindings and a fresh snaps
|
|
|
117
142
|
assert.match(boot, /mcp__notesoup__notes_\*/);
|
|
118
143
|
assert.match(boot, /claude:session/);
|
|
119
144
|
assert.doesNotMatch(boot, /brain empty|continuation/);
|
|
145
|
+
assert.equal(boot.includes("chat view"), false, "a Claude boot never claims a reset clears the human's view");
|
|
120
146
|
});
|
|
121
147
|
test("Claude helper serves the shared reset prose and the host's wipe sentence", async () => {
|
|
122
148
|
const texts = await dispatch({ op: "texts" });
|
|
123
149
|
assert.equal(texts.warning, CLAUDE_WARNING_PROMPT, "the helper owns the one warning text the mod shows");
|
|
124
|
-
assert.equal(texts.continuation, CONTINUATION, "the reset message is Pi's, verbatim");
|
|
125
150
|
assert.equal(texts.wipeSentence, CLAUDE_WIPE_SENTENCE);
|
|
126
|
-
assert.match(texts.warning, /end your turn; the reset runs after it
|
|
151
|
+
assert.match(texts.warning, /end your turn; the reset runs after it\./);
|
|
152
|
+
assert.equal(texts.warning.endsWith(COUNTDOWN_LINE), true, "the Claude notice also ends with the countdown");
|
|
153
|
+
assert.equal(texts.continuation, undefined, "a plain text read never draws the reset handoff");
|
|
154
|
+
const random = Math.random;
|
|
155
|
+
Math.random = () => 0;
|
|
156
|
+
try {
|
|
157
|
+
assert.deepEqual(await dispatch({ op: "continuation", origin: "forced" }), { text: FORCED_CONTINUATIONS[0] }, "Claude's system-triggered reset draws the forced pool");
|
|
158
|
+
await assert.rejects(dispatch({ op: "continuation", origin: "user" }), /invalid reset origin/, "a third origin is refused, not invented");
|
|
159
|
+
}
|
|
160
|
+
finally {
|
|
161
|
+
Math.random = random;
|
|
162
|
+
}
|
|
127
163
|
});
|
|
128
164
|
/** The point values the resolver produced, without the margin bookkeeping. */
|
|
129
165
|
function limitPoints(facts) {
|
|
@@ -214,7 +250,7 @@ test("Claude Mod helper runs from a standalone copied plugin directory", () => {
|
|
|
214
250
|
}));
|
|
215
251
|
const schemas = run('{"op":"schemas"}');
|
|
216
252
|
assert.equal(schemas.ok, true);
|
|
217
|
-
assert.equal(schemas.result?.length,
|
|
253
|
+
assert.equal(schemas.result?.length, 8);
|
|
218
254
|
assert.equal(run("not json").ok, false);
|
|
219
255
|
}
|
|
220
256
|
finally {
|
|
@@ -254,6 +290,7 @@ test("Claude Mod appends boot once and reuses persisted blocks after re-registra
|
|
|
254
290
|
assert.match(boot.text, /mcp__notesoup__notes_\*/, "the boot text names the actual Claude note tool binding");
|
|
255
291
|
assert.ok(boot.text.includes(CLAUDE_WIPE_SENTENCE), "the boot speaks the Claude wipe path");
|
|
256
292
|
assert.equal(boot.text.includes("erase yourself with dignity"), false);
|
|
293
|
+
assert.equal(boot.text.includes("chat view"), false, "the Claude boot block carries no Pi-only pre-reset hints");
|
|
257
294
|
assert.equal(first.sentinel, "kept", "unrelated result fields survive");
|
|
258
295
|
assert.equal(bootRequests, 1, "the first prompt makes exactly one boot helper request");
|
|
259
296
|
assert.equal(nextCalls, 1, "the upstream chain runs exactly once per prompt");
|
|
@@ -322,7 +359,7 @@ test("Claude Mod hook delivers the helper's shared text, and marks only a refusa
|
|
|
322
359
|
const handlers = new Map();
|
|
323
360
|
hooks.register((event, handler) => handlers.set(event, handler));
|
|
324
361
|
await handlers.get("session.start")(host, { cwd: home, isInteractive: true }, async (event) => event);
|
|
325
|
-
assert.deepEqual(registered.map((spec) => spec.name), ["notes_write", "notes_update", "notes_read", "notes_list", "notes_search"]);
|
|
362
|
+
assert.deepEqual(registered.map((spec) => spec.name), ["notes_write", "notes_update", "notes_read", "notes_list", "notes_search", "history_list", "history_read", "history_windows"]);
|
|
326
363
|
for (const spec of registered) {
|
|
327
364
|
assert.equal(spec.isDeferred, false, `${spec.name} is available from the start without tool search`);
|
|
328
365
|
assert.ok(spec.description.length > 20);
|
|
@@ -338,6 +375,13 @@ test("Claude Mod hook delivers the helper's shared text, and marks only a refusa
|
|
|
338
375
|
// A tool this plugin never registered is somebody else's answer, not a notesoup refusal.
|
|
339
376
|
const foreign = await call("other_tool", {});
|
|
340
377
|
assert.equal("result" in foreign, false, "an unregistered tool falls through to the engine's own handling");
|
|
378
|
+
// A rejected host call is the only diagnosis there is, so its reason must reach the model.
|
|
379
|
+
const ran = host.process.run;
|
|
380
|
+
host.process.run = async () => { throw new Error("spawn timed out after 10000ms"); };
|
|
381
|
+
const crashed = await call("notes_write", { address: "hook.md", content: "again" });
|
|
382
|
+
host.process.run = ran;
|
|
383
|
+
assert.equal(crashed.isError, true);
|
|
384
|
+
assert.match(String(crashed.result), /^notesoup: helper execution failed: Error: spawn timed out after 10000ms$/, "the host's own reason survives the catch");
|
|
341
385
|
});
|
|
342
386
|
test("Claude Mod resets at Claude's resolved point after the turn, retains one fresh boot and deduplicates measure", async (t) => {
|
|
343
387
|
const home = mkdtempSync(join(tmpdir(), "claude-reset-home-"));
|
|
@@ -360,7 +404,7 @@ test("Claude Mod resets at Claude's resolved point after the turn, retains one f
|
|
|
360
404
|
return result;
|
|
361
405
|
};
|
|
362
406
|
await invoke("session.start", { cwd: home, isInteractive: true });
|
|
363
|
-
assert.equal(registered.length,
|
|
407
|
+
assert.equal(registered.length, 8);
|
|
364
408
|
const initial = await handlers.get("prompt.context")(host, {}, async () => ({ blocks: [] }));
|
|
365
409
|
assert.equal(initial.blocks.length, 1, "below the warn point no warning joins the boot");
|
|
366
410
|
assert.match(initial.blocks[0].text, /Current context window id: claude:hook-session:0/);
|
|
@@ -390,7 +434,7 @@ test("Claude Mod resets at Claude's resolved point after the turn, retains one f
|
|
|
390
434
|
assert.match(kept[0].text, /Previous context window id: claude:hook-session:0/);
|
|
391
435
|
assert.match(kept[0].text, /FRESH_NOTES_AT_RESET/);
|
|
392
436
|
assert.doesNotMatch(kept[0].text, /OLD_SECRET/);
|
|
393
|
-
assert.
|
|
437
|
+
assert.ok(FORCED_CONTINUATIONS.includes(kept[1].text), "the handoff comes from the shared forced pool");
|
|
394
438
|
await invoke("session.measure");
|
|
395
439
|
assert.equal(compactions, 1, "invalidated tokens cannot immediately reset twice");
|
|
396
440
|
const upstream = { blocks: [{ name: "unrelated", text: "leave this alone" }], sentinel: "kept" };
|
|
@@ -425,6 +469,25 @@ test("Claude Mod headless detection skips compaction and logs once", async (t) =
|
|
|
425
469
|
const boot = await handlers.get("prompt.context")(host, {}, async () => ({ blocks: [] }));
|
|
426
470
|
assert.match(boot.blocks[0].text, /Current context window id: claude:hook-session:0/);
|
|
427
471
|
});
|
|
472
|
+
test("Claude Mod keeps its window numbering from a boot written before the tag rename", async (t) => {
|
|
473
|
+
const home = mkdtempSync(join(tmpdir(), "claude-legacy-boot-"));
|
|
474
|
+
t.after(() => rmSync(home, { recursive: true, force: true }));
|
|
475
|
+
const { host } = fakeEngine(home);
|
|
476
|
+
const handlers = new Map();
|
|
477
|
+
(await loadHookModule(t)).register((event, handler) => handlers.set(event, handler));
|
|
478
|
+
const invoke = (name, event = {}, next = async () => ({ sentinel: name })) => handlers.get(name)(host, event, next);
|
|
479
|
+
const boot = (spelling) => `<${spelling}>\nAgent name: claude (brain: claude)\n\nhook-session\n</${spelling}>\n\nCurrent context window id: claude:hook-session:3`;
|
|
480
|
+
for (const spelling of ["context_window", "notesoup:window_identity"]) {
|
|
481
|
+
const text = boot(spelling);
|
|
482
|
+
host.session.messages = async () => [{ role: "user", text }];
|
|
483
|
+
await invoke("session.start", { cwd: home, isInteractive: true });
|
|
484
|
+
// A recognised retained boot is not injected a second time into prompt context.
|
|
485
|
+
const context = await invoke("prompt.context", {}, async () => ({ blocks: [] }));
|
|
486
|
+
assert.deepEqual(context.blocks, [], `${spelling} is recognised as this session's retained boot`);
|
|
487
|
+
const compacted = await invoke("session.compact", { trigger: "auto", instructions: "", messages: [] });
|
|
488
|
+
assert.match(compacted.messages[0].text, /Current context window id: claude:hook-session:4/, `${spelling} keeps its window ordinal`);
|
|
489
|
+
}
|
|
490
|
+
});
|
|
428
491
|
test("Claude Mod refuses to wipe on boot failure and can retry without advancing the window", async (t) => {
|
|
429
492
|
const home = mkdtempSync(join(tmpdir(), "claude-reset-failure-"));
|
|
430
493
|
t.after(() => rmSync(home, { recursive: true, force: true }));
|
|
@@ -453,7 +516,7 @@ test("Claude Mod refuses to wipe on boot failure and can retry without advancing
|
|
|
453
516
|
assert.equal(result.skip, undefined);
|
|
454
517
|
assert.equal(result.messages.length, 2);
|
|
455
518
|
assert.match(result.messages[0].text, /Current context window id: claude:hook-session:1/, "a failed reset never consumes a window ordinal");
|
|
456
|
-
assert.
|
|
519
|
+
assert.ok(FORCED_CONTINUATIONS.includes(result.messages[1].text));
|
|
457
520
|
});
|
|
458
521
|
test("Claude Mod manual reset uses one hidden close-out turn, then recovers its boot on reload", async (t) => {
|
|
459
522
|
const home = mkdtempSync(join(tmpdir(), "claude-manual-home-"));
|
|
@@ -490,7 +553,7 @@ test("Claude Mod manual reset uses one hidden close-out turn, then recovers its
|
|
|
490
553
|
assert.equal(compactions, 1);
|
|
491
554
|
assert.equal(kept.length, 2);
|
|
492
555
|
assert.match(kept[0].text, /Current context window id: claude:hook-session:1/);
|
|
493
|
-
assert.
|
|
556
|
+
assert.ok(FORCED_CONTINUATIONS.includes(kept[1].text));
|
|
494
557
|
host.session.messages = async () => [{ role: "user", text: "OLD_SECRET" }, ...kept];
|
|
495
558
|
handlers = new Map();
|
|
496
559
|
(await loadHookModule(t)).register((event, handler) => handlers.set(event, handler));
|
|
@@ -681,12 +744,49 @@ async function retainedFixture(t) {
|
|
|
681
744
|
host.session.messages = async () => [{ role: "user", text: `# notesoup:boot\n${boot}` }];
|
|
682
745
|
const handlers = new Map();
|
|
683
746
|
(await loadHookModule(t)).register((event, handler) => handlers.set(event, handler));
|
|
684
|
-
const invoke = (name, e = {}, result = {}) => handlers.get(name)(host, e, async () => result);
|
|
747
|
+
const invoke = (name, e = {}, result = {}, next) => handlers.get(name)(host, e, next ?? (async () => result));
|
|
685
748
|
const context = async () => await invoke("prompt.context", {}, { blocks: [] });
|
|
686
749
|
await invoke("session.start", { cwd: home, isInteractive: true });
|
|
687
750
|
assert.deepEqual((await context()).blocks, [], "the existing boot is retained, not injected twice");
|
|
688
751
|
return { home, host, invoke, context, boot };
|
|
689
752
|
}
|
|
753
|
+
test("Claude asks for one handoff per compaction and reuses it when the same window retries", async (t) => {
|
|
754
|
+
const { host, invoke } = await retainedFixture(t);
|
|
755
|
+
const run = host.process.run;
|
|
756
|
+
const draws = [];
|
|
757
|
+
host.process.run = async (argv, init) => {
|
|
758
|
+
const request = init?.stdin ? JSON.parse(init.stdin) : {};
|
|
759
|
+
if (request.op === "continuation")
|
|
760
|
+
draws.push(init?.stdin);
|
|
761
|
+
return run(argv, init);
|
|
762
|
+
};
|
|
763
|
+
// Every read path stays pure: no boot, warning, context, or measure draws a handoff.
|
|
764
|
+
await invoke("prompt.context", {}, { blocks: [] });
|
|
765
|
+
await invoke("session.measure");
|
|
766
|
+
await invoke("turn.start");
|
|
767
|
+
await invoke("turn.complete");
|
|
768
|
+
assert.equal(draws.length, 0, "only a reset draws, never a read");
|
|
769
|
+
const timers = [];
|
|
770
|
+
const lines = [];
|
|
771
|
+
host.clock.after = (_ms, callback) => { timers.push(callback); };
|
|
772
|
+
host.prompt.submit = async () => { await invoke("turn.start"); };
|
|
773
|
+
// The host retries one plugin compaction for the same window: one artifact, one draw.
|
|
774
|
+
host.session.compact = async ({ instructions }) => {
|
|
775
|
+
for (let attempt = 0; attempt < 2; attempt++) {
|
|
776
|
+
const result = await invoke("session.compact", { trigger: "plugin", instructions: instructions ?? "" });
|
|
777
|
+
lines.push(result.messages[1].text);
|
|
778
|
+
}
|
|
779
|
+
return { skip: "test default" };
|
|
780
|
+
};
|
|
781
|
+
assert.match((await invoke("command.run", { command: "fresh-window", args: "" })).text, /Brain being emptied/);
|
|
782
|
+
await Promise.resolve();
|
|
783
|
+
await timers.shift()();
|
|
784
|
+
await invoke("turn.complete");
|
|
785
|
+
assert.equal(draws.length, 1, "a retried compaction adds no second draw");
|
|
786
|
+
assert.equal(lines.length, 2, "both attempts returned a handoff");
|
|
787
|
+
assert.equal(lines[0], lines[1], "both attempts carry the same artifact's paragraph");
|
|
788
|
+
assert.ok(FORCED_CONTINUATIONS.includes(lines[0]), "Claude has no model reset tool, so its pool is always the forced one");
|
|
789
|
+
});
|
|
690
790
|
test("Claude session.end gives /clear, /resume and /branch a fresh boot and identity", async (t) => {
|
|
691
791
|
for (const action of ["clear", "resume", "branch"]) {
|
|
692
792
|
await t.test(action, async (t) => {
|
|
@@ -725,27 +825,64 @@ test("Claude lazy identity detects a switched session without session.start or s
|
|
|
725
825
|
assert.deepEqual(fresh.blocks.map((block) => block.name), ["notesoup:boot"]);
|
|
726
826
|
assert.match(fresh.blocks[0].text, /Current context window id: claude:lazy-session:0/);
|
|
727
827
|
});
|
|
728
|
-
test("Claude native compaction
|
|
729
|
-
|
|
730
|
-
|
|
731
|
-
const {
|
|
732
|
-
|
|
733
|
-
const
|
|
734
|
-
|
|
735
|
-
|
|
736
|
-
|
|
737
|
-
|
|
738
|
-
|
|
739
|
-
|
|
740
|
-
|
|
741
|
-
|
|
742
|
-
|
|
743
|
-
|
|
744
|
-
|
|
745
|
-
|
|
746
|
-
|
|
747
|
-
|
|
748
|
-
|
|
828
|
+
test("Claude native compaction becomes a notes-only reset, a veto, or a pass-through", async (t) => {
|
|
829
|
+
await t.test("manual and precompute are vetoed before upstream", async (t) => {
|
|
830
|
+
for (const [trigger, pattern] of [["manual", /No compacting brains here/], ["precompute", /No precomputing brains here/]]) {
|
|
831
|
+
const { invoke, context } = await retainedFixture(t);
|
|
832
|
+
let upstreamCalls = 0;
|
|
833
|
+
const result = await invoke("session.compact", { trigger, messages: [{ role: "user", text: "OLD" }] }, {}, async () => { upstreamCalls++; return { messages: [{ role: "user", text: "SUMMARY" }] }; });
|
|
834
|
+
assert.equal(upstreamCalls, 0, `${trigger} never runs the summarizer`);
|
|
835
|
+
assert.match(result.skip, pattern);
|
|
836
|
+
assert.equal(result.messages, undefined);
|
|
837
|
+
assert.deepEqual((await context()).blocks, [], "the retained boot is untouched");
|
|
838
|
+
}
|
|
839
|
+
});
|
|
840
|
+
await t.test("auto becomes the next window's notes boot", async (t) => {
|
|
841
|
+
const { invoke } = await retainedFixture(t);
|
|
842
|
+
let upstreamCalls = 0;
|
|
843
|
+
const result = await invoke("session.compact", { trigger: "auto", messages: [{ role: "user", text: "OLD" }] }, {}, async () => { upstreamCalls++; return { messages: [{ role: "user", text: "SUMMARY" }] }; });
|
|
844
|
+
assert.equal(upstreamCalls, 0, "an automatic compaction never runs the summarizer");
|
|
845
|
+
assert.equal(result.messages.length, 2);
|
|
846
|
+
assert.match(result.messages[0].text, /Current context window id: claude:hook-session:3/);
|
|
847
|
+
assert.doesNotMatch(result.messages[0].text, /OLD/);
|
|
848
|
+
assert.ok(FORCED_CONTINUATIONS.includes(result.messages[1].text));
|
|
849
|
+
const upstream = { blocks: [{ name: "claude:user-context", text: "upstream" }] };
|
|
850
|
+
const context = await invoke("prompt.context", {}, upstream);
|
|
851
|
+
assert.deepEqual(context.blocks, upstream.blocks, "the hijacked boot is retained, not injected again");
|
|
852
|
+
});
|
|
853
|
+
await t.test("a failed auto build falls back to native compaction", async (t) => {
|
|
854
|
+
const { host, invoke } = await retainedFixture(t);
|
|
855
|
+
const run = host.process.run;
|
|
856
|
+
host.process.run = async (argv, init) => JSON.parse(init.stdin).op === "boot" ? { exitCode: 1, stdout: "" } : run(argv, init);
|
|
857
|
+
const upstream = { messages: [{ role: "user", text: "SUMMARY" }], sentinel: "native" };
|
|
858
|
+
let upstreamCalls = 0;
|
|
859
|
+
const result = await invoke("session.compact", { trigger: "auto", messages: [{ role: "user", text: "OLD" }] }, upstream, async () => { upstreamCalls++; return upstream; });
|
|
860
|
+
assert.equal(upstreamCalls, 1, "an over-long prompt still compacts natively");
|
|
861
|
+
assert.equal(result, upstream);
|
|
862
|
+
});
|
|
863
|
+
await t.test("foreign plugin, veto, subagent and kept boot still pass through", async (t) => {
|
|
864
|
+
for (const mode of ["foreign plugin", "veto", "subagent", "kept boot"]) {
|
|
865
|
+
await t.test(mode, async (t) => {
|
|
866
|
+
const { host, invoke, context } = await retainedFixture(t);
|
|
867
|
+
const event = { trigger: mode === "subagent" ? "manual" : "plugin", messages: [{ role: "user", text: "OLD" }], ...(mode === "subagent" ? { agentId: "child" } : {}) };
|
|
868
|
+
const upstream = mode === "veto" ? { skip: "user veto" } : {
|
|
869
|
+
messages: mode === "kept boot" ? await host.session.messages() : [{ role: "user", text: "SUMMARY" }], sentinel: mode,
|
|
870
|
+
};
|
|
871
|
+
let upstreamCalls = 0;
|
|
872
|
+
const result = await invoke("session.compact", event, upstream, async () => { upstreamCalls++; return upstream; });
|
|
873
|
+
assert.equal(upstreamCalls, 1, "the engine's compaction is passed through");
|
|
874
|
+
assert.equal(result, upstream);
|
|
875
|
+
const after = await context();
|
|
876
|
+
if (mode === "foreign plugin") {
|
|
877
|
+
assert.deepEqual(after.blocks.map((block) => block.name), ["notesoup:boot"]);
|
|
878
|
+
assert.match(after.blocks[0].text, /Current context window id: claude:hook-session:2/);
|
|
879
|
+
}
|
|
880
|
+
else {
|
|
881
|
+
assert.deepEqual(after.blocks, [], "veto, subagent and kept boot leave the main boot alone");
|
|
882
|
+
}
|
|
883
|
+
});
|
|
884
|
+
}
|
|
885
|
+
});
|
|
749
886
|
});
|
|
750
887
|
test("Claude serves every registered notes tool to subagents without leaking event fields into params", async (t) => {
|
|
751
888
|
const { invoke } = await retainedFixture(t);
|
|
@@ -835,3 +972,60 @@ test("Claude session.end cannot be undone by an in-flight old reset", async (t)
|
|
|
835
972
|
assert.deepEqual(fresh.blocks.map((block) => block.name), ["notesoup:boot"]);
|
|
836
973
|
assert.match(fresh.blocks[0].text, /Current context window id: claude:after-flight:0/);
|
|
837
974
|
});
|
|
975
|
+
test("Claude history keeps classic transcript_path across startup, confirms append heads, and refuses subagent leakage", async (t) => {
|
|
976
|
+
const home = mkdtempSync(join(tmpdir(), "claude-history-hook-"));
|
|
977
|
+
t.after(() => rmSync(home, { recursive: true, force: true }));
|
|
978
|
+
const { host, registered } = fakeEngine(home);
|
|
979
|
+
const handlers = new Map();
|
|
980
|
+
(await loadHookModule(t)).register((event, handler) => handlers.set(event, handler));
|
|
981
|
+
const invoke = (name, event = {}, result = {}) => handlers.get(name)(host, event, async () => result);
|
|
982
|
+
const transcriptPath = join(home, "transcript.jsonl");
|
|
983
|
+
const root = { type: "user", uuid: "root", parentUuid: null, sessionId: "hook-session", message: { role: "user", content: "old request" } };
|
|
984
|
+
const attachment = { type: "attachment", uuid: "startup", parentUuid: "root", sessionId: "hook-session", rendered: [{ content: [{ type: "text", text: "startup injection" }] }] };
|
|
985
|
+
const sibling = { type: "assistant", uuid: "sibling", parentUuid: "root", sessionId: "hook-session", message: { role: "assistant", content: "another branch" } };
|
|
986
|
+
writeFileSync(transcriptPath, [root, attachment, sibling].map((row) => JSON.stringify(row)).join("\n") + "\n");
|
|
987
|
+
const call = (tool, params = {}, agentId) => invoke("tool.call", { tool: `mcp__notesoup__${tool}`, tool_use_id: "probe", ...params, ...(agentId ? { agentId } : {}) });
|
|
988
|
+
await invoke("classic.SessionStart", { session_id: "hook-session", transcript_path: transcriptPath, source: "startup" });
|
|
989
|
+
// Real order: classic -> startup attachment appends -> typed session.start.
|
|
990
|
+
await invoke("session.append", { uuid: "startup" }, { uuid: "startup", message: {} });
|
|
991
|
+
await invoke("session.start", { cwd: home, isInteractive: true });
|
|
992
|
+
assert.equal(registered.length, 8);
|
|
993
|
+
const listed = await call("history_list", { roles: ["user", "context"] });
|
|
994
|
+
assert.equal(listed.isError, undefined, listed.result);
|
|
995
|
+
assert.match(listed.result, /old request/);
|
|
996
|
+
assert.match(listed.result, /startup injection/);
|
|
997
|
+
assert.doesNotMatch(listed.result, /another branch/);
|
|
998
|
+
const boot = await invoke("prompt.context", {}, { blocks: [] });
|
|
999
|
+
assert.match(boot.blocks[0].text, /mcp__notesoup__history_\*/);
|
|
1000
|
+
const subagent = await call("history_list", {}, "worker");
|
|
1001
|
+
assert.equal(subagent.isError, true);
|
|
1002
|
+
assert.match(subagent.result, /unavailable for subagents/);
|
|
1003
|
+
// Subagent classic payloads/append results must not overwrite the main binding.
|
|
1004
|
+
await invoke("classic.SessionStart", { session_id: "hook-session", transcript_path: "/wrong/subagent.jsonl", source: "startup", agent_id: "worker" });
|
|
1005
|
+
await invoke("session.append", { uuid: "subagent", agentId: "worker" }, { uuid: "subagent" });
|
|
1006
|
+
assert.equal((await call("history_read", { seq: 1 })).isError, undefined);
|
|
1007
|
+
// A resumed head is not supplied by SessionStart or messages(); don't use the last file row.
|
|
1008
|
+
await invoke("classic.SessionStart", { session_id: "hook-session", transcript_path: transcriptPath, source: "resume" });
|
|
1009
|
+
const beforeAppend = await call("history_list");
|
|
1010
|
+
assert.equal(beforeAppend.isError, true);
|
|
1011
|
+
assert.match(beforeAppend.result, /no confirmed active head/);
|
|
1012
|
+
await invoke("session.append", { uuid: "sibling" }, { uuid: "sibling" });
|
|
1013
|
+
const switched = await call("history_list");
|
|
1014
|
+
assert.match(switched.result, /another branch/);
|
|
1015
|
+
assert.doesNotMatch(switched.result, /startup injection/);
|
|
1016
|
+
});
|
|
1017
|
+
test("Claude history without a documented path refuses honestly and keeps notes usable", async (t) => {
|
|
1018
|
+
const home = mkdtempSync(join(tmpdir(), "claude-no-history-path-"));
|
|
1019
|
+
t.after(() => rmSync(home, { recursive: true, force: true }));
|
|
1020
|
+
const { host } = fakeEngine(home);
|
|
1021
|
+
const handlers = new Map();
|
|
1022
|
+
(await loadHookModule(t)).register((event, handler) => handlers.set(event, handler));
|
|
1023
|
+
await handlers.get("session.start")(host, { cwd: home, isInteractive: true }, async () => ({}));
|
|
1024
|
+
const history = await handlers.get("tool.call")(host, { tool: "mcp__notesoup__history_windows", tool_use_id: "history" }, async () => ({}));
|
|
1025
|
+
assert.equal(history.isError, true);
|
|
1026
|
+
assert.match(history.result, /transcript_path is unavailable/);
|
|
1027
|
+
const notes = await handlers.get("tool.call")(host, { tool: "mcp__notesoup__notes_list", tool_use_id: "notes" }, async () => ({}));
|
|
1028
|
+
assert.equal(notes.isError, undefined);
|
|
1029
|
+
const boot = await handlers.get("prompt.context")(host, {}, async () => ({ blocks: [] }));
|
|
1030
|
+
assert.match(boot.blocks[0].text, /History isn't available.*no main transcript_path/);
|
|
1031
|
+
});
|