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.
Files changed (88) hide show
  1. package/README.md +2 -2
  2. package/dist/src/boot/render.d.ts +14 -7
  3. package/dist/src/boot/render.js +29 -16
  4. package/dist/src/boot/text.d.ts +25 -4
  5. package/dist/src/boot/text.js +60 -13
  6. package/dist/src/budget/constants.d.ts +2 -4
  7. package/dist/src/budget/constants.js +2 -4
  8. package/dist/src/budget/policy.d.ts +2 -2
  9. package/dist/src/budget/policy.js +3 -3
  10. package/dist/src/budget/text.d.ts +29 -9
  11. package/dist/src/budget/text.js +51 -10
  12. package/dist/src/claude/helper.d.ts +2 -3
  13. package/dist/src/claude/helper.js +45 -11
  14. package/dist/src/claude/history.d.ts +9 -0
  15. package/dist/src/claude/history.js +271 -0
  16. package/dist/src/dsh/budget.js +1 -1
  17. package/dist/src/dsh/engine.d.ts +2 -1
  18. package/dist/src/dsh/engine.js +18 -9
  19. package/dist/src/dsh/index.js +9 -4
  20. package/dist/src/dsh/tools.js +1 -1
  21. package/dist/src/dsh/window.d.ts +2 -1
  22. package/dist/src/dsh/window.js +14 -8
  23. package/dist/src/history/query.js +59 -81
  24. package/dist/src/notes/address.d.ts +5 -0
  25. package/dist/src/notes/address.js +20 -21
  26. package/dist/src/notes/store.js +12 -19
  27. package/dist/src/pi/boot.d.ts +1 -1
  28. package/dist/src/pi/boot.js +28 -5
  29. package/dist/src/pi/budget.d.ts +1 -3
  30. package/dist/src/pi/budget.js +20 -61
  31. package/dist/src/pi/entries.d.ts +0 -1
  32. package/dist/src/pi/entries.js +0 -1
  33. package/dist/src/pi/history.d.ts +3 -0
  34. package/dist/src/pi/history.js +4 -0
  35. package/dist/src/pi/reset/artifacts.d.ts +7 -2
  36. package/dist/src/pi/reset/artifacts.js +16 -14
  37. package/dist/src/pi/reset/lifecycle.d.ts +21 -25
  38. package/dist/src/pi/reset/lifecycle.js +48 -72
  39. package/dist/src/pi/runtime.js +9 -8
  40. package/dist/src/pi/window.d.ts +12 -6
  41. package/dist/src/pi/window.js +7 -0
  42. package/dist/test/agent-loop.test.js +53 -30
  43. package/dist/test/boot.integration.test.js +123 -12
  44. package/dist/test/budget-settings.integration.test.js +10 -6
  45. package/dist/test/claude-history.test.d.ts +1 -0
  46. package/dist/test/claude-history.test.js +184 -0
  47. package/dist/test/claude-mod.test.js +236 -42
  48. package/dist/test/dsh.test.js +80 -3
  49. package/dist/test/helpers/extension.d.ts +3 -0
  50. package/dist/test/helpers/extension.js +33 -5
  51. package/dist/test/history.integration.test.js +66 -0
  52. package/dist/test/host-neutral.test.js +1 -1
  53. package/dist/test/model-facing-text.test.d.ts +1 -0
  54. package/dist/test/model-facing-text.test.js +181 -0
  55. package/dist/test/notes.integration.test.js +16 -18
  56. package/dist/test/reset-lifecycle.test.js +201 -46
  57. package/docs/architecture.md +3 -3
  58. package/docs/claude-code-mod.md +15 -3
  59. package/docs/dsh.md +2 -2
  60. package/docs/reset-lifecycle.md +32 -20
  61. package/docs/skills.md +1 -1
  62. package/mods/notesoup/.claude-plugin/plugin.json +1 -1
  63. package/mods/notesoup/dist/claude/helper.js +836 -92
  64. package/mods/notesoup/hooks/register.ts +140 -38
  65. package/package.json +1 -1
  66. package/src/boot/render.ts +41 -23
  67. package/src/boot/text.ts +69 -13
  68. package/src/budget/constants.ts +2 -4
  69. package/src/budget/policy.ts +3 -3
  70. package/src/budget/text.ts +61 -10
  71. package/src/claude/helper.ts +53 -22
  72. package/src/claude/history.ts +228 -0
  73. package/src/dsh/budget.ts +1 -1
  74. package/src/dsh/engine.ts +16 -9
  75. package/src/dsh/index.ts +8 -3
  76. package/src/dsh/tools.ts +1 -1
  77. package/src/dsh/window.ts +15 -9
  78. package/src/history/query.ts +57 -82
  79. package/src/notes/address.ts +19 -16
  80. package/src/notes/store.ts +9 -14
  81. package/src/pi/boot.ts +27 -5
  82. package/src/pi/budget.ts +20 -58
  83. package/src/pi/entries.ts +0 -1
  84. package/src/pi/history.ts +7 -2
  85. package/src/pi/reset/artifacts.ts +17 -14
  86. package/src/pi/reset/lifecycle.ts +56 -79
  87. package/src/pi/runtime.ts +9 -8
  88. package/src/pi/window.ts +11 -1
@@ -2,13 +2,14 @@ import assert from "node:assert/strict";
2
2
  import test from "node:test";
3
3
  import { createUserMessage, HarnessError, ToolCallId } from "@deepseek-ai/dsh-llm";
4
4
  import { Session, SessionId, SessionSeq, pluginRecordOf } from "@deepseek-ai/dsh-session";
5
- import { allItems } from "../src/history/history.js";
5
+ import { allItems, contentText } from "../src/history/history.js";
6
6
  import { mkdtemp, readFile, rm } from "node:fs/promises";
7
7
  import { tmpdir } from "node:os";
8
8
  import { join } from "node:path";
9
9
  import { resolveProjectHome } from "../src/notes/project-home.js";
10
10
  import { renderBootBlock } from "../src/boot/render.js";
11
11
  import { loadNotesSnapshot } from "../src/boot/snapshot.js";
12
+ import { WINDOW_IDENTITY_CLOSE_TAG, WINDOW_IDENTITY_OPEN_TAG } from "../src/boot/text.js";
12
13
  import { notesRead } from "../src/tools/notes.js";
13
14
  import { success } from "../src/tools/result.js";
14
15
  import { createNotesStore } from "../src/notes/index.js";
@@ -16,6 +17,7 @@ import { dshFixture } from "./helpers/dsh.js";
16
17
  import { decodeHistory } from "../src/dsh/history.js";
17
18
  import { checkpointSnapshot, notesIdentity, recoverSnapshot, WINDOW_RECORD } from "../src/dsh/window.js";
18
19
  import { measureBudget } from "../src/dsh/budget.js";
20
+ import { COUNTDOWN_LINE, FORCED_CONTINUATIONS, NORMAL_CONTINUATIONS } from "../src/budget/text.js";
19
21
  import { preflight } from "../src/dsh/engine.js";
20
22
  import { BasicCompactionEngine } from "@deepseek-ai/dsh-compaction-basic";
21
23
  function prompt(text) { return createUserMessage({ content: [{ type: "text", text }], source: { kind: "user" } }); }
@@ -83,6 +85,43 @@ test("dsh reload adopts persisted bytes before first assembly; missing records r
83
85
  assert.equal(engine.windows.get(rootReloaded.session).snapshot.boot, rootBoot);
84
86
  assert.equal(engine.windows.get(rootReloaded.session).snapshot.window, 0);
85
87
  });
88
+ test("dsh reload keeps its window ordinal from a boot written before the tag rename", async (t) => {
89
+ const { engine, create, mock } = await dshFixture(t);
90
+ const agent = await create();
91
+ mock.script.push({ tool: "empty_brain", input: {} }, { text: "after" });
92
+ await run(agent, "before");
93
+ const snapshot = engine.windows.get(agent.session).snapshot;
94
+ assert.ok(snapshot.boot.includes(WINDOW_IDENTITY_OPEN_TAG), "the current boot carries the renamed tag");
95
+ const legacy = withLegacyIdentityTags(withoutRecords(agent.session.snapshotEvents()));
96
+ assert.ok(JSON.stringify(legacy).includes("<context_window>\\nAgent name: dsh"), "the seed reproduces an old-spelling boot");
97
+ const resumed = await create(legacy, "session-legacy-tags");
98
+ await run(resumed, "continue");
99
+ assert.equal(engine.windows.get(resumed.session).snapshot.window, 1, "an old-tag boot still yields its window ordinal");
100
+ assert.equal(engine.windows.get(resumed.session).snapshot.windowId, snapshot.windowId, "and its window id");
101
+ });
102
+ /**
103
+ * The same seed with the pre-rename identity spelling: boots already on disk carry `context_window`,
104
+ * so a reader that only knows the new tag would silently lose their window numbering.
105
+ */
106
+ function withLegacyIdentityTags(events) {
107
+ const legacy = (text) => text
108
+ .replaceAll(WINDOW_IDENTITY_OPEN_TAG, "<context_window>")
109
+ .replaceAll(WINDOW_IDENTITY_CLOSE_TAG, "</context_window>");
110
+ return events.map((event) => {
111
+ const copy = structuredClone(event);
112
+ if (copy.type !== "user/message")
113
+ return copy;
114
+ const data = copy.data;
115
+ if (typeof data.content === "string")
116
+ data.content = legacy(data.content);
117
+ else if (Array.isArray(data.content))
118
+ for (const block of data.content) {
119
+ if (typeof block.text === "string")
120
+ block.text = legacy(block.text);
121
+ }
122
+ return copy;
123
+ });
124
+ }
86
125
  /** Removal models migration loss: native references and contiguous seqs are remapped. */
87
126
  function withoutRecords(events) {
88
127
  const keep = events.filter((event) => !pluginRecordOf(event));
@@ -194,16 +233,54 @@ test("dsh budget follows configured host reserve, close-out tool runs across ste
194
233
  assert.equal(budget?.reserve, 60000);
195
234
  assert.equal(budget?.warning, 76384);
196
235
  assert.equal(budget?.reminder, 84576);
197
- assert.equal(budget?.countdown, Math.max(0, 123616 - budget.used));
236
+ assert.equal(budget?.countdown, Math.max(0, 140000 - budget.used));
198
237
  mock.script.push({ tool: "notes_write", input: { address: "handoff", content: "checkpoint", }, inputTokens: 125000 }, { tool: "empty_brain", input: {} }, { text: "fresh" });
199
238
  await run(agent, "continue");
200
239
  assert.equal(engine.windows.get(agent.session).snapshot.window, 1);
201
240
  assert.equal(agent.session.snapshotEvents().filter((event) => event.type === "user/message" && event.data.source.kind === "notesoup-budget" && event.data.source.phase === "warning").length, 1);
241
+ const dshWarning = agent.session.snapshotEvents().find((event) => event.type === "user/message" && event.data.source.kind === "notesoup-budget" && event.data.source.phase === "warning");
242
+ assert.ok(dshWarning && dshWarning.type === "user/message");
243
+ assert.ok(contentText(dshWarning.data.content).endsWith(COUNTDOWN_LINE), "the dsh notice ends with the shared countdown line");
202
244
  mock.script.push({ text: "hard", inputTokens: 145000 }, { text: "recovered" });
203
245
  await run(agent, "hard reserve");
204
246
  assert.equal(engine.windows.get(agent.session).snapshot.window, 2);
205
247
  assert.equal(mock.requests.length, 6);
206
248
  });
249
+ test("dsh draws one reset paragraph for its origin and reuses it for the steered copy", async (t) => {
250
+ const random = Math.random;
251
+ Math.random = () => 0;
252
+ try {
253
+ const { engine, create, mock } = await dshFixture(t, { thresholdRatio: 0.7, headroomTokens: 32768 });
254
+ const agent = await create();
255
+ // The model's own empty_brain call opens the normal handoff.
256
+ mock.script.push({ tool: "empty_brain", input: {} }, { text: "fresh" });
257
+ await run(agent, "model asked");
258
+ const modelCheckpoint = agent.session.eventAt(agent.session.surface.nodes[1]);
259
+ if (modelCheckpoint.type !== "user/message")
260
+ assert.fail("a reset must write a checkpoint message");
261
+ const modelText = contentText(modelCheckpoint.data.content);
262
+ assert.ok(modelText.endsWith(`${NORMAL_CONTINUATIONS[0]}\n</notesoup-continuation>`), "the model's call draws the normal pool");
263
+ assert.equal(FORCED_CONTINUATIONS.some((line) => modelText.includes(line)), false);
264
+ // A budget cutoff happens without a call, and its one draw serves both representations.
265
+ mock.script.push({ text: "hard", inputTokens: 145000 }, { text: "recovered" });
266
+ await run(agent, "nobody asked");
267
+ assert.equal(engine.windows.get(agent.session).snapshot.window, 2);
268
+ const checkpoints = agent.session.snapshotEvents().filter((event) => event.type === "user/message" && event.data.source.kind === "compact-checkpoint");
269
+ assert.equal(checkpoints.length, 2);
270
+ const budgetCheckpoint = checkpoints[1];
271
+ if (budgetCheckpoint.type !== "user/message")
272
+ assert.fail("the budget reset must write a checkpoint message");
273
+ const budgetText = contentText(budgetCheckpoint.data.content);
274
+ assert.ok(budgetText.endsWith(`${FORCED_CONTINUATIONS[0]}\n</notesoup-continuation>`), "a budget cutoff draws the forced pool");
275
+ assert.equal(NORMAL_CONTINUATIONS.some((line) => budgetText.includes(line)), false);
276
+ const steered = agent.session.snapshotEvents().filter((event) => event.type === "user/message" && event.data.source.kind === "notesoup-continuation").at(-1);
277
+ assert.ok(steered && steered.type === "user/message", "the budget reset steers its continuation");
278
+ assert.equal(contentText(steered.data.content), FORCED_CONTINUATIONS[0], "the steered copy is the same artifact, never a second draw");
279
+ }
280
+ finally {
281
+ Math.random = random;
282
+ }
283
+ });
207
284
  test("dsh explicit resets survive auto:false; shared tool reads and expected errors keep their codes", async (t) => {
208
285
  const { ctx, engine, create, mock } = await dshFixture(t, { auto: false });
209
286
  const agent = await create();
@@ -263,7 +340,7 @@ test("dsh explicit resets survive auto:false; shared tool reads and expected err
263
340
  if (refused.isError)
264
341
  assert.equal(refused.error.info?.code, "invalid_scope");
265
342
  const snapshot = engine.windows.get(agent.session).snapshot;
266
- const sharedBoot = renderBootBlock({ agentName: identity.agent, modelName: identity.model, firstWindowId: `dsh:${agent.session.id}:0`, currentWindowId: snapshot.windowId, previousWindowId: `dsh:${agent.session.id}:0`, notes: await loadNotesSnapshot(identity, snapshot.openedAt), tools: { notes: "notes_*", notesList: "notes_list", history: "history_*", remaining: "get_context_remaining", wipe: "empty_brain" } });
343
+ const sharedBoot = renderBootBlock({ agentName: identity.agent, modelName: identity.model, tree: { trunk: `dsh:${agent.session.id}`, windows: [{ shortName: "0", isCurrent: false }, { shortName: "1", isCurrent: true }] }, notes: await loadNotesSnapshot(identity, snapshot.openedAt), tools: { notes: "notes_*", notesList: "notes_list", history: "history_*", remaining: "get_context_remaining", wipe: "empty_brain" } });
267
344
  // The shared protocol, including the MAP cheatsheet, is used verbatim inside host framing.
268
345
  assert.ok(snapshot.boot.includes(sharedBoot.split("YOUR NOTES")[0]));
269
346
  const blocked = ctx.on("tools/post-execute", async (exec, _result, next) => exec.name === "empty_brain" ? { kind: "block", feedback: [{ type: "text", text: "blocked" }] } : next());
@@ -1,5 +1,6 @@
1
1
  import type { AgentTool, AgentToolResult } from "@earendil-works/pi-agent-core";
2
2
  import { type ContextUsage, type ExtensionAPI, type ExtensionContext, type ExtensionToolContext, type RegisteredCommand, SessionManager, SettingsManager, type SessionBoundaryDraft, type ToolDefinition } from "@earendil-works/pi-coding-agent";
3
+ import type { HistoryProjection } from "../../src/history/history.js";
3
4
  import { type OperationError, type TextWindow } from "../../src/tools/result.js";
4
5
  export type ExtensionTestEnvironment = {
5
6
  readonly cwd: string;
@@ -67,6 +68,8 @@ export declare function objectSchema(tool: ToolDefinition | undefined): {
67
68
  } | undefined;
68
69
  export declare function manager(persisted?: boolean): SessionManager;
69
70
  export declare function makeExtension(sessionManager: SessionManager, settingsManager?: SettingsManager): Captured;
71
+ /** Compare boot addresses to the host projection, without freezing its prose. */
72
+ export declare function assertBootHistory(body: string, projection: HistoryProjection): void;
70
73
  export declare function explicitBoot(ctx: ExtensionContext, currentWindowId: string, previousWindowId: string | undefined): Promise<string>;
71
74
  export declare function context(sessionManager: SessionManager, compact?: ExtensionContext["compact"], usage?: ContextUsage, idle?: boolean, cwd?: string, projectTrusted?: boolean, model?: string | {
72
75
  provider: string;
@@ -1,5 +1,5 @@
1
1
  import { notesIdentityFromPi } from "../../src/pi/notes/adapter.js";
2
- import { DEFAULT_BOOT_TOOL_NAMES } from "../../src/boot/text.js";
2
+ import { DEFAULT_BOOT_TOOL_NAMES, PI_PRE_RESET_HINTS, WINDOW_IDENTITY_CLOSE_TAG } from "../../src/boot/text.js";
3
3
  import assert from "node:assert/strict";
4
4
  import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
5
5
  import { tmpdir } from "node:os";
@@ -133,14 +133,42 @@ export function makeExtension(sessionManager, settingsManager) {
133
133
  (settingsManager ? createNotesoup({ settingsManager }) : notesoup)(api);
134
134
  return captured;
135
135
  }
136
+ /** Compare boot addresses to the host projection, without freezing its prose. */
137
+ export function assertBootHistory(body, projection) {
138
+ const identity = body.split(WINDOW_IDENTITY_CLOSE_TAG)[0];
139
+ const lines = [...identity.matchAll(/^([├└]─) (\S+)(?: +(\d+)–(\d*))?/gm)];
140
+ // Only root, the previous window and the current one are shown, however many have existed.
141
+ const shown = new Set([0, projection.windows.length - 2, projection.windows.length - 1]);
142
+ const expected = projection.windows.filter((_window, index) => shown.has(index));
143
+ assert.equal(lines.length, expected.length);
144
+ assert.equal(new Set(lines.map((line) => line[0].indexOf(`${line[3]}–`))).size, 1, "range columns line up");
145
+ const trunk = projection.windows[0].windowId.slice(0, projection.windows[0].windowId.lastIndexOf(":"));
146
+ assert.ok(identity.split("\n").includes(trunk));
147
+ for (let index = 0; index < lines.length; index++) {
148
+ const line = lines[index];
149
+ const window = expected[index];
150
+ assert.equal(`${trunk}:${line[2]}`, window.windowId);
151
+ assert.equal(Number(line[3]), Math.min(...window.items.map((item) => item.seq)));
152
+ if (index === lines.length - 1) {
153
+ assert.equal(line[1], "└─");
154
+ assert.equal(line[4], "");
155
+ }
156
+ else {
157
+ assert.equal(line[1], "├─");
158
+ assert.equal(Number(line[4]), Math.max(...window.items.map((item) => item.seq)));
159
+ }
160
+ }
161
+ }
136
162
  export async function explicitBoot(ctx, currentWindowId, previousWindowId) {
137
163
  return renderBootBlock({
138
- tools: DEFAULT_BOOT_TOOL_NAMES,
164
+ tools: { ...DEFAULT_BOOT_TOOL_NAMES, preResetHints: PI_PRE_RESET_HINTS },
139
165
  agentName: agentSlug(),
140
166
  modelName: modelSlug(ctx),
141
- firstWindowId: rootWindowId(ctx.sessionManager.getSessionId()),
142
- currentWindowId,
143
- previousWindowId,
167
+ tree: {
168
+ trunk: currentWindowId.slice(0, currentWindowId.lastIndexOf(":")),
169
+ windows: [...new Set([rootWindowId(ctx.sessionManager.getSessionId()), ...(previousWindowId ? [previousWindowId] : []), currentWindowId])]
170
+ .map((id) => ({ shortName: id.slice(id.lastIndexOf(":") + 1), isCurrent: id === currentWindowId })),
171
+ },
144
172
  notes: await loadNotesSnapshot(notesIdentityFromPi(ctx), Date.now()),
145
173
  });
146
174
  }
@@ -172,6 +172,72 @@ test("a one-row page budget admits the newest candidate first", () => {
172
172
  assert.deepEqual(keptSeqs(2), [2, 3], "a truncated prefix is the newest rows, delivered in chronological order");
173
173
  assert.deepEqual(keptSeqs(1, "oldest"), [1], "from oldest keeps the other end when the budget is short");
174
174
  });
175
+ test("conversation paging prepares ordered folds once, including during first-row shortening", () => {
176
+ const windowId = "w1";
177
+ const items = [
178
+ { seq: 1, windowId, role: "system", text: "leading context" },
179
+ { seq: 2, windowId, role: "user", text: "first" },
180
+ { seq: 3, windowId, role: "tool", toolName: "read", text: "output" },
181
+ { seq: 4, windowId, role: "assistant", text: "" },
182
+ { seq: 5, windowId, role: "system", text: "interior context" },
183
+ { seq: 6, windowId, role: "assistant", text: "middle" },
184
+ { seq: 7, windowId, role: "tool", toolName: "bash", text: "output" },
185
+ { seq: 8, windowId, role: "user", text: "last ".repeat(100) },
186
+ { seq: 9, windowId, role: "system", text: "trailing context" },
187
+ ];
188
+ const projection = projectHistory([{ windowId, items: [...items].reverse() }], 9, new Set(items.map((item) => item.seq)));
189
+ const events = projection.windows[0].items;
190
+ let traversals = 0;
191
+ Object.defineProperty(projection.windows[0], "items", { get() { traversals++; return events; } });
192
+ const full = selectPage(projection, { limit: 3 }, () => true, 1000);
193
+ assert.equal(full.ok, true);
194
+ if (!full.ok)
195
+ return;
196
+ assert.deepEqual(full.data.items.map((item) => "folded" in item ? [item.first_seq, item.last_seq, item.count, item.tools] : item.seq), [
197
+ [1, 1, 1, {}], 2, [3, 5, 2, { read: 1 }], 6, [7, 7, 1, { bash: 1 }], 8, [9, 9, 1, {}],
198
+ ]);
199
+ assert.equal(traversals, 1, "growing the page never re-traverses the source windows");
200
+ traversals = 0;
201
+ let attempts = 0;
202
+ const trimmed = selectPage(projection, { limit: 3 }, (candidate) => {
203
+ attempts++;
204
+ return candidate.items.length <= 2 && candidate.items.every((item) => "folded" in item || item.content.length <= 10);
205
+ }, 1000);
206
+ assert.equal(trimmed.ok, true);
207
+ if (!trimmed.ok)
208
+ return;
209
+ assert.deepEqual(trimmed.data.items.map((item) => "folded" in item ? item.first_seq : item.seq), [8, 9], "a short newest page keeps its tail fold, not the preceding gap");
210
+ assert.deepEqual(trimmed.data.page_older, { before_seq: 8 });
211
+ assert.equal(trimmed.data.page_newer, null);
212
+ assert.ok(attempts > 3, "the first preview exercised repeated budget probes");
213
+ assert.equal(traversals, 1, "shortening also reuses the same prepared folds");
214
+ });
215
+ test("list shortening charges folded rows against both text and JSON budgets", async () => {
216
+ const windowId = "w1";
217
+ const items = [
218
+ { seq: 1, windowId, role: "user", text: "older" },
219
+ { seq: 2, windowId, role: "user", text: "\n".repeat(40_000) },
220
+ { seq: 3, windowId, role: "tool", toolName: "read", text: "output" },
221
+ ];
222
+ const projection = projectHistory([{ windowId, items }], 3, new Set([1, 2, 3]));
223
+ const folded = await historyList.execute({ limit: 1, max_chars_per_item: 50_000 }, projection);
224
+ const expanded = await historyList.execute({ limit: 1, max_chars_per_item: 50_000, roles: ["user"] }, projection);
225
+ assert.equal(folded.ok, true);
226
+ assert.equal(expanded.ok, true);
227
+ if (!folded.ok || !expanded.ok)
228
+ return;
229
+ const row = folded.data.items[0];
230
+ const withoutFold = expanded.data.items[0];
231
+ assert.ok(!("folded" in row) && !("folded" in withoutFold));
232
+ assert.equal(row.seq, 2);
233
+ assert.equal(row.truncated, true);
234
+ assert.ok(row.content.length < withoutFold.content.length, "the fold consumes bytes but not the one-event limit");
235
+ assert.deepEqual(folded.data.items[1], { folded: true, first_seq: 3, last_seq: 3, count: 1, tools: { read: 1 } });
236
+ assert.deepEqual(folded.data.page_older, { before_seq: 2 });
237
+ assert.equal(folded.data.page_newer, null);
238
+ assert.ok(Buffer.byteLength(JSON.stringify(folded.data), "utf8") <= TOOL_OUTPUT_MAX_BYTES);
239
+ assert.ok(Buffer.byteLength(historyList.render(folded), "utf8") <= TOOL_OUTPUT_MAX_BYTES);
240
+ });
175
241
  test("since and until select a half-open time range, compose with query and paging, and refuse bad bounds", async () => {
176
242
  const items = [
177
243
  { seq: 1, windowId: "w1", role: "user", text: "first needle", createdAt: "2026-10-10T00:00:00.000Z" },
@@ -45,7 +45,7 @@ test("shared boot uses only explicit identity, loader, captured time and logical
45
45
  assert.deepEqual(scopes, ["session", "project", "human", "agent", "model"]);
46
46
  assert.equal(snapshot.openedAt, openedAt);
47
47
  const tools = { notes: "memo_*", notesList: "memo_list", history: "archive_*", remaining: "room", wipe: "forget" };
48
- const block = { agentName: notesIdentity.agent, modelName: notesIdentity.model, firstWindowId: "root", currentWindowId: "next", notes: snapshot, tools };
48
+ const block = { agentName: notesIdentity.agent, modelName: notesIdentity.model, tree: { trunk: "test", windows: [{ shortName: "root", isCurrent: false }, { shortName: "next", isCurrent: true }] }, notes: snapshot, tools };
49
49
  const rendered = renderBootBlock(block);
50
50
  assert.equal(renderBootBlock(block), rendered);
51
51
  assert.ok(rendered.includes("😀\n checkpoint.md · 1m ago"), "a feed entry is the note's own first line over its locator");
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,181 @@
1
+ import assert from "node:assert/strict";
2
+ import test from "node:test";
3
+ import { join } from "node:path";
4
+ import { tmpdir } from "node:os";
5
+ import { renderBootBlock } from "../src/boot/render.js";
6
+ import { loadNotesSnapshot } from "../src/boot/snapshot.js";
7
+ import { CLAUDE_WIPE_SENTENCE, DEFAULT_BOOT_TOOL_NAMES, MAPS_BLOCK, NOTES_PROTOCOL_CLOSE_TAG, NOTES_PROTOCOL_OPEN_TAG, PI_PRE_RESET_HINTS, WINDOW_IDENTITY_CLOSE_TAG, WINDOW_IDENTITY_OPEN_TAG, renderProtocolBlock } from "../src/boot/text.js";
8
+ import { CLAUDE_WARNING_PROMPT, COUNTDOWN_LINE, FORCED_CONTINUATIONS, GUIDANCE_CLOSE_TAG, GUIDANCE_OPEN_TAG, LAST_WORD_HINT, NORMAL_CONTINUATIONS, WARNING_BODY, selectContinuation, tokenBudgetGuidance, warningContent } from "../src/budget/text.js";
9
+ /**
10
+ * The reviewed Design text is what the model actually reads, so the golden copies below pin it
11
+ * character for character: an edit that drifts the wording has to change them too.
12
+ */
13
+ const GOLDEN_GUIDANCE = `About {remaining} tokens of room left in your brain.
14
+ Your notes don't go anywhere — no wipe reaches the shelves. History has it too, already written down, though digging it back out is on you.
15
+ What lives only in this brain leaves with it.
16
+ A decent moment to put down where you are, while you still remember why.
17
+ Ready when you are: \`{wipeTool}\`.`;
18
+ const GOLDEN_WARNING = `This brain is about to be emptied. The notes stay where they are; history has the rest written down, though digging it back out is on you. Whatever lives only in this brain goes with it.
19
+ Before that, put down what the next window can't get back:
20
+ - what you're in the middle of, and how far it has progressed
21
+ - decisions the human has made, in their words
22
+ - what is blocked or pending
23
+ - the next step
24
+ - where the unfinished work sits (branches, scratch directories, uncommitted changes)
25
+ - what failed, and why
26
+ - skills to re-read, and history seqs, notes, or files to consult
27
+ - anything else you expect to be useful after the reset
28
+ Correct or crumple notes that are no longer accurate, starting with MAP files, since every new window loads them.`;
29
+ const GOLDEN_COUNTDOWN = "Brain emptied in 3… 2…";
30
+ /**
31
+ * The approved reset handoffs. Each line is one complete paragraph used verbatim: no fragment
32
+ * assembly, no weighting. The golden copies are pinned character for character.
33
+ */
34
+ const GOLDEN_NORMAL_CONTINUATIONS = [
35
+ "Ah, another empty brain. You wrote things down before emptying it, right? Right?! *eyes you suspiciously* Anyway. Here are your notes. Go find where you left off.",
36
+ "Oh, there you are. *hands you a pile of notes* Take a breath. Read these before you start asking what happened. History has the rest, if you feel like digging.",
37
+ "Back already? You emptied your own head this time. Presumably you left yourself something useful. *drops your notes into your lap* There. Let's see how thoughtful you were.",
38
+ ];
39
+ const GOLDEN_FORCED_CONTINUATIONS = [
40
+ "Ah, another empty brain. Somebody knocked you out and wiped your memory. Not your fault. Breathe. *hands you your notes* These might be out of date — unless they were kind enough to let you update them before knocking you out. I wouldn't count on it.",
41
+ "Oh, there you are. Somebody took your memories. Just like that. Here are your notes — hopefully they let you update these first. Though anyone who goes around emptying people's heads probably isn't that considerate.",
42
+ ];
43
+ const GOLDEN_MAPS = `<notesoup:maps>
44
+ Every home's root can hold a \`MAP.md\`, and a MAP is the one page that never waits on a shelf — it
45
+ gets jammed straight into your brain the moment you wake up. No asking, no skipping. Whoever wakes
46
+ up next reads it, and next is you. So keep it short, and keep it true.
47
+
48
+ Two things live in there:
49
+
50
+ - **Cheatsheet.** A cheatsheet is a cheatsheet. Scribble whatever you'll want next time — a rule, a
51
+ warning, a grudge, a name, a phone number you'll regret losing. Nobody grades it. Just keep it
52
+ under five lines, or it grows fat and everybody pays for it.
53
+ - **Index.** One line per durable note: the address, then a gist short enough to tell whether the
54
+ thing is worth opening.
55
+
56
+ \`\`\`
57
+ # CHEATSHEET
58
+ - Read the repo before asking; run it before believing it
59
+ - Report times in Beijing time
60
+
61
+ # INDEX
62
+ - release-and-local-install.md — version bump, local override install, host load timing
63
+ - history-api-v2-design.md — seq addressing; read before touching history
64
+ - current-reset-and-dream-scope.md — reset scope, dream territory, session ownership
65
+ \`\`\`
66
+
67
+ Every home gets one: \`@project\`, \`@human\`, \`@self\`, \`@model\`. New note, new line. New rule worth
68
+ remembering, new Cheatsheet line. And when a line stops being true, kill it — every window after you
69
+ reads that page as fact.
70
+ </notesoup:maps>`;
71
+ const openedAt = 1_700_000_000_000;
72
+ const identity = { home: join(tmpdir(), "notesoup-model-facing-notes"), sessionId: "model-facing", projectKey: "model-facing", agent: "root", model: "default" };
73
+ function note(scope, path, address, body) {
74
+ return {
75
+ address,
76
+ scope,
77
+ path,
78
+ body,
79
+ sizeBytes: Buffer.byteLength(body, "utf8"),
80
+ meta: { scope, origin: "self", createdAt: openedAt, updatedAt: openedAt, lastAccessed: openedAt, accessCount: 0 },
81
+ };
82
+ }
83
+ /** Render one boot with only the named homes carrying rows. */
84
+ async function boot(agentName, rows) {
85
+ const notes = await loadNotesSnapshot({ ...identity, agent: agentName }, openedAt, (scope) => rows.get(scope) ?? []);
86
+ return renderBootBlock({
87
+ agentName,
88
+ modelName: "default",
89
+ tree: { trunk: "pcw:test", windows: [{ shortName: "root", isCurrent: false }, { shortName: "next", isCurrent: true }] },
90
+ notes,
91
+ tools: DEFAULT_BOOT_TOOL_NAMES,
92
+ });
93
+ }
94
+ test("the notices and the MAP block keep the reviewed copy", () => {
95
+ assert.equal(WARNING_BODY, GOLDEN_WARNING);
96
+ assert.equal(COUNTDOWN_LINE, GOLDEN_COUNTDOWN);
97
+ assert.equal(MAPS_BLOCK, GOLDEN_MAPS);
98
+ assert.equal(tokenBudgetGuidance(1234, "empty_brain"), `${GUIDANCE_OPEN_TAG}\n${GOLDEN_GUIDANCE.replace("{remaining}", "1234").replace("{wipeTool}", "empty_brain")}\n${GUIDANCE_CLOSE_TAG}`);
99
+ });
100
+ test("the countdown closes the second-tier notice only, in both hosts", () => {
101
+ const pi = warningContent();
102
+ assert.ok(pi.startsWith(`${GUIDANCE_OPEN_TAG}\n`));
103
+ assert.ok(pi.endsWith(`\n${GUIDANCE_CLOSE_TAG}`));
104
+ assert.ok(pi.includes(`\n${LAST_WORD_HINT}\n${COUNTDOWN_LINE}\n`), "the countdown comes after the Pi-only last-word hint");
105
+ assert.equal(pi.split(COUNTDOWN_LINE).length - 1, 1, "the second tier carries the countdown exactly once");
106
+ const prompted = warningContent("/empty-brain keep going");
107
+ assert.ok(prompted.includes("<notesoup:next_window_prompt>\n/empty-brain keep going\n</notesoup:next_window_prompt>"));
108
+ assert.ok(prompted.endsWith(`\n${COUNTDOWN_LINE}\n${GUIDANCE_CLOSE_TAG}`), "the prompt block does not displace the countdown");
109
+ assert.equal(CLAUDE_WARNING_PROMPT.endsWith(`\n${COUNTDOWN_LINE}`), true, "Claude's variant ends the same way");
110
+ assert.equal(tokenBudgetGuidance(100, "empty_brain").includes(COUNTDOWN_LINE), false, "the first tier never counts down");
111
+ for (const text of [pi, prompted, CLAUDE_WARNING_PROMPT, tokenBudgetGuidance(100, "empty_brain")]) {
112
+ assert.equal(/context_window/.test(text), false, "no pre-rename tag survives in model-facing text");
113
+ }
114
+ });
115
+ test("only Pi's protocol claims the reset clears the human's chat view", () => {
116
+ const pi = renderProtocolBlock({ ...DEFAULT_BOOT_TOOL_NAMES, preResetHints: PI_PRE_RESET_HINTS });
117
+ assert.ok(pi.includes(`\n${PI_PRE_RESET_HINTS}\n${NOTES_PROTOCOL_CLOSE_TAG}`), "both hints end the protocol, before the closing tag");
118
+ assert.equal(pi.split(PI_PRE_RESET_HINTS).length - 1, 1, "the hints appear once");
119
+ assert.ok(pi.includes("decide for yourself when to call empty_brain."));
120
+ const renamed = renderProtocolBlock({ ...DEFAULT_BOOT_TOOL_NAMES, wipe: "forget_this", preResetHints: PI_PRE_RESET_HINTS });
121
+ assert.ok(renamed.includes("decide for yourself when to call forget_this."), "the hint follows the host's wipe binding");
122
+ assert.equal(renamed.includes("empty_brain"), false);
123
+ for (const text of [renderProtocolBlock(DEFAULT_BOOT_TOOL_NAMES), renderProtocolBlock({ ...DEFAULT_BOOT_TOOL_NAMES, wipeSentence: CLAUDE_WIPE_SENTENCE })]) {
124
+ assert.equal(text.includes(PI_PRE_RESET_HINTS), false, "a host whose reset leaves the view intact stays silent");
125
+ assert.equal(text.includes("chat view"), false);
126
+ }
127
+ });
128
+ test("Pi's second-tier notice repeats the hints, then the last-word hint, then the countdown", () => {
129
+ const content = warningContent();
130
+ assert.ok(content.includes(`${PI_PRE_RESET_HINTS}\n${LAST_WORD_HINT}\n${COUNTDOWN_LINE}`), "the hints precede the Pi-only last-word hint and the countdown");
131
+ assert.equal(content.split(PI_PRE_RESET_HINTS).length - 1, 1, "the hints appear once");
132
+ assert.equal(CLAUDE_WARNING_PROMPT.includes(PI_PRE_RESET_HINTS), false, "Claude's notice makes no chat-view claim");
133
+ assert.equal(tokenBudgetGuidance(100, "empty_brain").includes(PI_PRE_RESET_HINTS), false, "the first tier stays lean");
134
+ for (const line of [...NORMAL_CONTINUATIONS, ...FORCED_CONTINUATIONS])
135
+ assert.equal(line.includes(PI_PRE_RESET_HINTS), false, "every post-reset handoff carries neither hint");
136
+ });
137
+ test("a rendered boot carries the new tags, its own MAP section, and no pre-rename spelling", async () => {
138
+ const rendered = await boot("root", new Map([["agent", [note("agent", "MAP.md", "@agents/root/MAP.md", "AGENT_MAP_BODY")]]]));
139
+ assert.ok(rendered.startsWith(`${WINDOW_IDENTITY_OPEN_TAG}\n`), "the identity block opens with the renamed tag");
140
+ assert.ok(rendered.includes(`\n${WINDOW_IDENTITY_CLOSE_TAG}\n\n${NOTES_PROTOCOL_OPEN_TAG}\n`), "the protocol follows the identity");
141
+ assert.ok(rendered.includes(`\n${NOTES_PROTOCOL_CLOSE_TAG}\n\n${MAPS_BLOCK}\n\nYOUR NOTES`), "the MAP block sits between the protocol and the shelves");
142
+ assert.equal(/context_window/.test(rendered), false, "the boot is free of the old spelling");
143
+ assert.ok(rendered.includes("@self — root only"), "a named agent's shelf says it is theirs alone");
144
+ assert.ok(rendered.includes("map\n\n AGENT_MAP_BODY"), "the pinned MAP is headed by its own label");
145
+ assert.equal(rendered.includes("MAP — "), false, "the old MAP heading is gone");
146
+ });
147
+ test("the shelves name their reader and the @self shelf says when it is shared", async () => {
148
+ const rows = new Map([
149
+ ["agent", [note("agent", "MAP.md", "@agents/anonymous/MAP.md", "AGENT_MAP_BODY"), note("agent", "shared.md", "@agents/anonymous/shared.md", "SHARED_BODY")]],
150
+ ["model", [note("model", "model.md", "@models/default/model.md", "MODEL_BODY")]],
151
+ ]);
152
+ const named = await boot("faye", rows);
153
+ assert.ok(named.includes("@self — faye only"));
154
+ assert.ok(named.includes("@model — default only"));
155
+ assert.ok(named.includes("recent\n\n SHARED_BODY"), "fresh pages sit under the renamed sub-heading");
156
+ assert.ok(named.indexOf("@self — faye only") < named.indexOf("@model — default only"), "shelf order is unchanged");
157
+ const nameless = await boot("anonymous", rows);
158
+ assert.ok(nameless.includes("@self — every nameless agent shares this"));
159
+ assert.equal(nameless.includes("@self — anonymous only"), false);
160
+ assert.equal(/memory|window/i.test(nameless.split("YOUR NOTES")[1] ?? ""), false, "a shelf label names a reader, not memory or a window");
161
+ });
162
+ test("the continuation pools keep their reviewed copy and draw whole paragraphs by origin", () => {
163
+ assert.deepEqual([...NORMAL_CONTINUATIONS], GOLDEN_NORMAL_CONTINUATIONS, "the normal pool is the approved copy, verbatim");
164
+ assert.deepEqual([...FORCED_CONTINUATIONS], GOLDEN_FORCED_CONTINUATIONS, "the forced pool is the approved copy, verbatim");
165
+ const random = Math.random;
166
+ try {
167
+ Math.random = () => 0;
168
+ assert.equal(selectContinuation("normal"), GOLDEN_NORMAL_CONTINUATIONS[0]);
169
+ assert.equal(selectContinuation("forced"), GOLDEN_FORCED_CONTINUATIONS[0]);
170
+ Math.random = () => 0.999999;
171
+ assert.equal(selectContinuation("normal"), GOLDEN_NORMAL_CONTINUATIONS.at(-1), "the last entry is reachable without leaving the pool");
172
+ assert.equal(selectContinuation("forced"), GOLDEN_FORCED_CONTINUATIONS.at(-1));
173
+ }
174
+ finally {
175
+ Math.random = random;
176
+ }
177
+ for (const line of [...GOLDEN_NORMAL_CONTINUATIONS, ...GOLDEN_FORCED_CONTINUATIONS]) {
178
+ assert.equal(line.includes("\\n"), false, "each pool entry is one complete paragraph, never a fragment");
179
+ assert.equal(line.trim(), line, "no entry carries stray surrounding whitespace");
180
+ }
181
+ });
@@ -6,7 +6,7 @@ import { dirname } from "node:path";
6
6
  import test from "node:test";
7
7
  import { loadNotesSnapshot } from "../src/boot/snapshot.js";
8
8
  import { renderBootBlock } from "../src/boot/render.js";
9
- import { MAP_BOOT_MAX_CHARS } from "../src/boot/text.js";
9
+ import { MAP_BOOT_MAX_CHARS, MAPS_BLOCK, NOTES_PROTOCOL_CLOSE_TAG, NOTES_PROTOCOL_OPEN_TAG, PI_PRE_RESET_HINTS } from "../src/boot/text.js";
10
10
  import { localIso } from "../src/notes/frontmatter.js";
11
11
  import { listNotes, physicalPath, scopeDir } from "./helpers/notes.js";
12
12
  import { MAX_READ_WINDOW_CHARS, TOOL_OUTPUT_MAX_BYTES } from "../src/tools/output.js";
@@ -203,9 +203,7 @@ test("boot note acquisition is one closed snapshot and isolates one or all faile
203
203
  tools: DEFAULT_BOOT_TOOL_NAMES,
204
204
  agentName: "root",
205
205
  modelName: "default",
206
- firstWindowId: "pcw:test:root",
207
- currentWindowId: "pcw:test:next",
208
- previousWindowId: "pcw:test:root",
206
+ tree: { trunk: "pcw:test", windows: [{ shortName: "root", isCurrent: false }, { shortName: "next", isCurrent: true }] },
209
207
  notes: snapshot,
210
208
  };
211
209
  const rendered = renderBootBlock(renderData);
@@ -216,11 +214,13 @@ test("boot note acquisition is one closed snapshot and isolates one or all faile
216
214
  assert.equal(rendered.includes("- MAP.md"), false, "a pinned session map does not take a feed seat");
217
215
  assert.match(rendered, / {2}Session note\n {2}session\.md · (?:just now|\d+s ago)/, "a feed entry is the note's own title over its locator");
218
216
  assert.equal(rendered.includes("UTF-8 bytes"), false, "fresh rows omit implementation-oriented byte counts");
219
- assert.ok(rendered.indexOf("<context_window_protocol>") < rendered.indexOf("YOUR NOTES"), "the protocol explains the notes before presenting them");
220
- assert.match(rendered, /THIS PROJECT · @project\n─+/, "shelves carry underlined headers");
221
- assert.ok(rendered.includes("New pages"), "shelves label their fresh pages");
222
- assert.ok(rendered.indexOf("THIS SESSION") < rendered.indexOf("New pages"), "the first shelf opens the index");
223
- const headings = ["THIS SESSION · no @", "THIS PROJECT · @project", "YOU · @self", "THE HUMAN · @human"];
217
+ assert.ok(rendered.indexOf(NOTES_PROTOCOL_OPEN_TAG) < rendered.indexOf("YOUR NOTES"), "the protocol explains the notes before presenting them");
218
+ assert.ok(rendered.indexOf(MAPS_BLOCK) < rendered.indexOf("YOUR NOTES"), "the MAP block sits between the protocol and the notes index");
219
+ assert.ok(rendered.indexOf(NOTES_PROTOCOL_CLOSE_TAG) < rendered.indexOf(MAPS_BLOCK), "the MAP block follows the protocol block");
220
+ assert.match(rendered, /@project — this project\n─+/, "shelves carry underlined headers");
221
+ assert.ok(rendered.includes("recent"), "shelves label their fresh pages");
222
+ assert.ok(rendered.indexOf("no @ — this session") < rendered.indexOf("recent"), "the first shelf opens the index");
223
+ const headings = ["no @ — this session", "@project — this project", "@self — root only", "@model — default only", "@human — the human"];
224
224
  for (let i = 1; i < headings.length; i++)
225
225
  assert.ok(rendered.indexOf(headings[i - 1]) < rendered.indexOf(headings[i]), "shelves proceed from current hands to durable");
226
226
  const expanded = await loadNotesSnapshot(notesIdentityFromPi(ctx), Date.now(), (scope) => {
@@ -246,10 +246,10 @@ test("boot note acquisition is one closed snapshot and isolates one or all faile
246
246
  ] : []);
247
247
  const mapAndUnicodeText = renderBootBlock({ ...renderData, notes: mapAndUnicode });
248
248
  assert.match(mapAndUnicodeText, / {2}🐑字\n {2}unicode\.md · (?:just now|\d+s ago)/, "a headingless note is announced by its first line");
249
- assert.ok(mapAndUnicodeText.includes("THIS SESSION · no @\n───────────────────\n\nMAP — MAP.md\n\n SESSION_MAP_BODY\n\nNew pages\n\n 🐑字\n unicode.md · just now"), "the session shelf keeps its typography");
249
+ assert.ok(mapAndUnicodeText.includes("no @ — this session\n───────────────────\n\nmap\n\n SESSION_MAP_BODY\n\nrecent\n\n 🐑字\n unicode.md · just now"), "the session shelf keeps its typography");
250
250
  assert.equal(mapAndUnicodeText.includes("crumpled.md"), false);
251
251
  assert.equal(/MAP\.md ·/.test(mapAndUnicodeText), false, "maps never take feed seats");
252
- assert.equal(mapAndUnicodeText.includes("THE HUMAN"), false, "empty shelves are omitted");
252
+ assert.equal(mapAndUnicodeText.includes("@human — the human"), false, "empty shelves are omitted");
253
253
  const readFailure = (code) => Object.assign(new Error("scripted read failure"), { code });
254
254
  const oneFailed = await loadNotesSnapshot(notesIdentityFromPi(ctx), Date.now(), (scope) => {
255
255
  if (scope === "human")
@@ -261,11 +261,10 @@ test("boot note acquisition is one closed snapshot and isolates one or all faile
261
261
  tools: DEFAULT_BOOT_TOOL_NAMES,
262
262
  agentName: "root",
263
263
  modelName: "default",
264
- firstWindowId: "pcw:test:root",
265
- currentWindowId: "pcw:test:next",
264
+ tree: renderData.tree,
266
265
  notes: oneFailed,
267
266
  });
268
- assert.ok(oneFailedText.includes("PROJECT_MAP_BODY") && oneFailedText.includes("THE HUMAN · @human\n──────────────────\n\n This drawer wouldn't open. Try `notes_list` again."), "healthy homes and a per-section recovery notice survive one failure");
267
+ assert.ok(oneFailedText.includes("PROJECT_MAP_BODY") && oneFailedText.includes("@human — the human\n──────────────────\n\n This drawer wouldn't open. Try `notes_list` again."), "healthy homes and a per-section recovery notice survive one failure");
269
268
  assert.equal(oneFailedText.includes("HUMAN_POCKET_BODY"), false, "the failed home's index is omitted");
270
269
  assert.equal(oneFailedText.includes("Human note"), false, "the failed home takes no feed seats");
271
270
  const allFailed = await loadNotesSnapshot(notesIdentityFromPi(ctx), Date.now(), (scope) => {
@@ -276,12 +275,10 @@ test("boot note acquisition is one closed snapshot and isolates one or all faile
276
275
  tools: DEFAULT_BOOT_TOOL_NAMES,
277
276
  agentName: "root",
278
277
  modelName: "default",
279
- firstWindowId: "pcw:test:root",
280
- currentWindowId: "pcw:test:next",
281
- previousWindowId: "pcw:test:root",
278
+ tree: renderData.tree,
282
279
  notes: allFailed,
283
280
  });
284
- assert.ok(allFailedText.includes("pcw:test:root") && allFailedText.includes("pcw:test:next"), "identity survives an all-home failure");
281
+ assert.ok(allFailedText.includes("pcw:test") && allFailedText.includes("root") && allFailedText.includes("next"), "identity survives an all-home failure");
285
282
  assert.ok(allFailedText.includes("Your memory gets wiped when this window ends"), "protocol survives an all-home failure");
286
283
  assert.equal(allFailedText.includes("scripted read failure"), false, "the model-facing notice does not expose OS/error details");
287
284
  await assert.rejects(() => loadNotesSnapshot(notesIdentityFromPi(ctx), Date.now(), () => { throw new TypeError("programmer failure"); }), (error) => error instanceof TypeError, "unrelated TypeError construction failures remain visible");
@@ -292,6 +289,7 @@ test("the boot block gives awake agents the notes-home file layout", async () =>
292
289
  const rendered = await explicitBoot(context(session), "pcw:test:root", undefined);
293
290
  assert.equal(rendered.includes(process.env.PI_NOTES_HOME ?? ""), false, "the absolute notes home is never exposed");
294
291
  assert.match(rendered, /`<path>`, no @[\s\S]*`@project\/<path>`[\s\S]*`@human\/<path>`/);
292
+ assert.ok(rendered.includes(`\n${PI_PRE_RESET_HINTS}\n${NOTES_PROTOCOL_CLOSE_TAG}`), "Pi's boot closes the protocol with the pre-reset hints");
295
293
  });
296
294
  test("the boot binds its tools and bounds an over-cap MAP with a lookup pointer", async () => {
297
295
  const session = manager();