notesoup 0.45.2 → 0.46.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 (53) hide show
  1. package/README.md +2 -2
  2. package/dist/src/boot/text.d.ts +3 -3
  3. package/dist/src/boot/text.js +5 -5
  4. package/dist/src/budget/text.d.ts +4 -4
  5. package/dist/src/budget/text.js +3 -3
  6. package/dist/src/dsh/index.js +1 -1
  7. package/dist/src/dsh/tools.js +2 -2
  8. package/dist/src/history/query.js +18 -23
  9. package/dist/src/notes/store.js +4 -0
  10. package/dist/src/pi/reset/artifacts.d.ts +5 -3
  11. package/dist/src/pi/reset/artifacts.js +7 -9
  12. package/dist/src/pi/reset/lifecycle.js +1 -1
  13. package/dist/src/pi/runtime.js +17 -13
  14. package/dist/src/tools/history.js +1 -1
  15. package/dist/src/tools/notes.d.ts +3 -3
  16. package/dist/src/tools/notes.js +2 -2
  17. package/dist/src/tools/schema.d.ts +1 -7
  18. package/dist/src/tools/schema.js +6 -14
  19. package/dist/test/agent-loop.test.js +37 -37
  20. package/dist/test/boot.integration.test.js +11 -11
  21. package/dist/test/claude-mod.test.js +8 -8
  22. package/dist/test/dependencies.test.js +2 -2
  23. package/dist/test/dsh-cli.test.js +1 -1
  24. package/dist/test/dsh.test.js +7 -7
  25. package/dist/test/history.integration.test.js +8 -3
  26. package/dist/test/host-neutral.test.js +1 -1
  27. package/dist/test/notes.integration.test.js +22 -1
  28. package/dist/test/notes.test.js +1 -1
  29. package/dist/test/reset-lifecycle.test.js +19 -14
  30. package/docs/architecture.md +3 -3
  31. package/docs/claude-code-mod.md +3 -3
  32. package/docs/dsh.md +3 -3
  33. package/docs/notes-library.md +1 -1
  34. package/docs/reset-lifecycle.md +7 -7
  35. package/docs/tool-results.md +2 -2
  36. package/mods/notesoup/.claude-plugin/plugin.json +1 -1
  37. package/mods/notesoup/dist/claude/helper.js +16 -13
  38. package/mods/notesoup/hooks/register.ts +10 -9
  39. package/mods/notesoup/skills/memory/SKILL.md +1 -1
  40. package/package.json +1 -1
  41. package/skills/memory/SKILL.md +1 -1
  42. package/src/boot/text.ts +5 -5
  43. package/src/budget/text.ts +3 -3
  44. package/src/dsh/index.ts +1 -1
  45. package/src/dsh/tools.ts +2 -2
  46. package/src/history/query.ts +16 -20
  47. package/src/notes/store.ts +4 -0
  48. package/src/pi/reset/artifacts.ts +8 -8
  49. package/src/pi/reset/lifecycle.ts +1 -1
  50. package/src/pi/runtime.ts +16 -13
  51. package/src/tools/history.ts +1 -1
  52. package/src/tools/notes.ts +2 -2
  53. package/src/tools/schema.ts +5 -12
@@ -9,7 +9,7 @@ import { BOOT_TYPE, CONTINUATION_TYPE, GUIDANCE_TYPE, RESET_LAST_WORD_TYPE, RESE
9
9
  import { MANUAL_WIPE_TYPE } from "../src/pi/entries.js";
10
10
  import { toolContext } from "./helpers/extension.js";
11
11
  import { WARNING_CONTENT } from "../src/budget/text.js";
12
- import { MAX_LAST_WORD_CHARS, sanitizeLastWord } from "../src/pi/reset/artifacts.js";
12
+ import { LAST_WORD_PREFIX, MAX_LAST_WORD_CHARS, sanitizeLastWord } from "../src/pi/reset/artifacts.js";
13
13
  import { initialResetControl, reduceResetControl, registerResetLifecycle, } from "../src/pi/reset/lifecycle.js";
14
14
  const previousNotesHome = process.env.PI_NOTES_HOME;
15
15
  const testNotesHome = mkdtempSync(join(tmpdir(), "notesoup-lifecycle-notes-"));
@@ -154,8 +154,8 @@ function fakeBoundaryEvent(entries = [], message) {
154
154
  test("public reset boundary drafts one marker, one boot, and one continuation after a tool batch", async () => {
155
155
  const h = harness();
156
156
  h.sessionManager.appendMessage({ role: "user", content: [{ type: "text", text: "before reset" }], timestamp: Date.now() });
157
- const first = await h.callTool("clear_memory");
158
- const second = await h.callTool("clear_memory");
157
+ const first = await h.callTool("neuralyze");
158
+ const second = await h.callTool("neuralyze");
159
159
  assert.ok(first.content.length > 0 && second.content.length > 0, "both tool calls return normally");
160
160
  const toolBatch = [{ type: "custom_message", customType: "foreign/tool-batch", content: "tool finished", display: false }];
161
161
  const boundary = resultEntries(await h.emit("turn_end", fakeBoundaryEvent(toolBatch)));
@@ -179,9 +179,9 @@ test("public reset boundary drafts one marker, one boot, and one continuation af
179
179
  assert.deepEqual(branch.filter((entry) => entry.type === "custom" && entry.customType === RESET_MARKER_TYPE).map((entry) => entry.type === "custom" ? entry.data : undefined), [{ windowId }]);
180
180
  assert.equal(branch.filter((entry) => entry.type === "custom_message" && entry.customType === BOOT_TYPE).length, 1);
181
181
  });
182
- test("manual /clear-memory spans tool turns and commits the stop at settlement", async () => {
182
+ test("manual /neuralyze spans tool turns and commits the stop at settlement", async () => {
183
183
  const h = harness();
184
- await h.runCommand("clear-memory");
184
+ await h.runCommand("neuralyze");
185
185
  assert.ok(h.sent.some((message) => message.customType === MANUAL_WIPE_TYPE && message.triggerTurn === true), "the idle close-out warning starts a turn");
186
186
  const toolCallMessage = {
187
187
  role: "assistant",
@@ -204,7 +204,7 @@ test("manual /clear-memory spans tool turns and commits the stop at settlement",
204
204
  });
205
205
  test("off stops future automatic/manual reset requests while an existing marker remains authoritative", async () => {
206
206
  const h = harness();
207
- await h.callTool("clear_memory");
207
+ await h.callTool("neuralyze");
208
208
  const first = resultEntries(await h.emit("turn_end", fakeBoundaryEvent()));
209
209
  assert.ok(first.entries.some((entry) => entry.type === "custom" && entry.customType === RESET_MARKER_TYPE));
210
210
  appendDrafts(h.sessionManager, first.entries);
@@ -221,8 +221,8 @@ test("off stops future automatic/manual reset requests while an existing marker
221
221
  const afterOff = resultEntries(await h.emit("turn_end", fakeBoundaryEvent()));
222
222
  assert.equal(afterOff.entries.length, 0, "off does not create another reset");
223
223
  await h.runCommand("notesoup", "on");
224
- await h.runCommand("clear-memory");
225
- assert.equal(h.sent.length, 1, "/clear-memory sends one hidden close-out warning and starts a normal turn");
224
+ await h.runCommand("neuralyze");
225
+ assert.equal(h.sent.length, 1, "/neuralyze sends one hidden close-out warning and starts a normal turn");
226
226
  assert.equal(h.sent[0]?.triggerTurn, true);
227
227
  assert.equal(h.sent[0]?.customType, MANUAL_WIPE_TYPE);
228
228
  const warning = h.sessionManager.getBranch().find((entry) => entry.type === "custom_message" && entry.customType === MANUAL_WIPE_TYPE);
@@ -604,25 +604,30 @@ test("a committed reset places incoming and budget drafts before marker -> boot
604
604
  CONTINUATION_TYPE,
605
605
  ], "the persisted reset shape remains marker -> boot -> continuation");
606
606
  });
607
- test("a clear_memory last word lands as a visible entry after the continuation", async () => {
607
+ test("a neuralyze last word lands as a visible entry after the continuation", async () => {
608
608
  const h = harness();
609
609
  h.sessionManager.appendMessage({ role: "user", content: [{ type: "text", text: "before reset" }], timestamp: Date.now() });
610
- await h.callTool("clear_memory", { last_word: "feed the ants" });
610
+ await h.callTool("neuralyze", { last_word: "feed the ants" });
611
611
  const boundary = resultEntries(await h.emit("turn_end", fakeBoundaryEvent()));
612
612
  const lastWords = boundary.entries.filter((entry) => entry.type === "custom_message" && entry.customType === RESET_LAST_WORD_TYPE);
613
613
  assert.equal(lastWords.length, 1, "the boundary persists exactly one parting line");
614
- assert.deepEqual(lastWords[0], { type: "custom_message", customType: RESET_LAST_WORD_TYPE, content: "feed the ants", display: true });
614
+ assert.deepEqual(lastWords[0], { type: "custom_message", customType: RESET_LAST_WORD_TYPE, content: `${LAST_WORD_PREFIX}feed the ants`, display: true });
615
615
  const continuationIndex = boundary.entries.findIndex((entry) => entry.type === "custom_message" && entry.customType === CONTINUATION_TYPE);
616
616
  assert.ok(boundary.entries.indexOf(lastWords[0]) > continuationIndex, "the parting line follows the continuation");
617
617
  });
618
- test("clear_memory sanitizes the last word: trim, cap, and blank persists no entry", async () => {
618
+ test("neuralyze trims the last word, refuses an oversized one, and a blank persists no entry", async () => {
619
619
  assert.equal(sanitizeLastWord(" hi "), "hi");
620
620
  assert.equal(sanitizeLastWord(" "), undefined);
621
621
  assert.equal(sanitizeLastWord(undefined), undefined);
622
- assert.equal(sanitizeLastWord("x".repeat(MAX_LAST_WORD_CHARS + 10))?.length, MAX_LAST_WORD_CHARS + 1, "capped with an ellipsis");
622
+ const over = harness();
623
+ over.sessionManager.appendMessage({ role: "user", content: [{ type: "text", text: "before reset" }], timestamp: Date.now() });
624
+ const refused = await over.callTool("neuralyze", { last_word: "x".repeat(MAX_LAST_WORD_CHARS + 1) });
625
+ assert.match(JSON.stringify(refused), /error/, "an oversized note is refused, not truncated");
626
+ const untouched = resultEntries(await over.emit("turn_end", fakeBoundaryEvent()));
627
+ assert.equal(untouched.entries.filter((entry) => entry.type === "custom_message" && entry.customType === RESET_LAST_WORD_TYPE).length, 0, "a refused call requests no reset");
623
628
  const h = harness();
624
629
  h.sessionManager.appendMessage({ role: "user", content: [{ type: "text", text: "before reset" }], timestamp: Date.now() });
625
- await h.callTool("clear_memory", { last_word: " " });
630
+ await h.callTool("neuralyze", { last_word: " " });
626
631
  const boundary = resultEntries(await h.emit("turn_end", fakeBoundaryEvent()));
627
632
  assert.equal(boundary.entries.filter((entry) => entry.type === "custom_message" && entry.customType === RESET_LAST_WORD_TYPE).length, 0, "a blank last word persists no entry");
628
633
  });
@@ -39,11 +39,11 @@ For the native dsh reset transaction, prompt ordering, capability checks and lim
39
39
 
40
40
  A new reset is a native empty-summary compaction checkpoint configured to retain none, followed by one `notesoup/reset-marker` custom entry with `{ windowId: string }`, a hidden `notesoup/boot` whose `details.windowId` matches, and a hidden continuation. The checkpoint is the canonical-history cut; the marker is the durable logical window identity. Raw session entries remain available to history tools. Legacy marker-only branches keep a narrow projection fallback. `pi/window.ts` owns marker/checkpoint validation, active-branch scan, root/current IDs, and per-window message lookup; `pi/history.ts` consumes those native identity primitives while decoding entries; shared `history/history.ts` only receives decoded, addressed data. The scan never uses a global entry tail.
41
41
 
42
- The runtime in `pi/runtime.ts` performs final context projection by selecting the active boot through `details.windowId` and folding only the dropped system prefix through Pi's `getCurrentSystemMessage`. Later prompt patches and new messages stay in order. A missing boot aborts the hook with a safe head and notice rather than silently sending raw history. Startup/tree handling repairs only a genuinely incomplete marker tail: a missing boot with no later raw message, custom message, compaction, branch summary, or authoritative raw boot. If later work exists, boot creation is refused and `/clear-memory` is the explicit recovery path; it does not parse or migrate the legacy reset-v2 protocol.
42
+ The runtime in `pi/runtime.ts` performs final context projection by selecting the active boot through `details.windowId` and folding only the dropped system prefix through Pi's `getCurrentSystemMessage`. Later prompt patches and new messages stay in order. A missing boot aborts the hook with a safe head and notice rather than silently sending raw history. Startup/tree handling repairs only a genuinely incomplete marker tail: a missing boot with no later raw message, custom message, compaction, branch summary, or authoritative raw boot. If later work exists, boot creation is refused and `/fresh-window` is the explicit recovery path; it does not parse or migrate the legacy reset-v2 protocol.
43
43
 
44
44
  Boot and reminder deduplication inspect the current branch-local window. Reloading JSONL therefore does not duplicate messages, while navigation to a sibling branch cannot inherit another branch's window state. A fork/clone receives a new session ID while copying its selected path, so startup must also verify that a root boot's `details.windowId` matches the new `rootWindowId(sessionId)` before treating it as present.
45
45
 
46
- Manual `/clear-memory` arms a close-out and always sends the hidden checkpoint prompt: when idle it starts one ordinary model turn, while streaming it steers the running turn so the agent closes out promptly. The agent may span several note/tool turns; the reset commits at a successful settlement after queued work drains, and the run stops rather than continuing in the fresh window. That prompt and the budget warning share the same text but have distinct persisted types, so an aborted manual request cannot suppress a later budget warning. The budget warning remains a multi-turn close-out with an explicit `clear_memory` commit or a successful normal-stop fallback. Abort and ordinary errors never count as successful close-out. Manual overflow commits a reset without recovery continuation, even with automatic reset disabled. A hard-reserve reset preserves the manual stop in a run-scoped `stop-pending` phase; the lifecycle's `context_with_system` hook verifies the actual committed boundary and cancels an empty tool-batch follow-up through public `ctx.abort()`. Pending or already-delivered user input bypasses cancellation and is answered before settlement stops without a second wipe. The checkpoint, marker, boot, and continuation are emitted as ordered session-boundary drafts. Pi's retain-none compaction entry persists the canonical cut; the marker/boot preserve notesoup's logical identity and protocol.
46
+ Manual `/fresh-window` arms a close-out and always sends the hidden checkpoint prompt: when idle it starts one ordinary model turn, while streaming it steers the running turn so the agent closes out promptly. The agent may span several note/tool turns; the reset commits at a successful settlement after queued work drains, and the run stops rather than continuing in the fresh window. That prompt and the budget warning share the same text but have distinct persisted types, so an aborted manual request cannot suppress a later budget warning. The budget warning remains a multi-turn close-out with an explicit `neuralyze` commit or a successful normal-stop fallback. Abort and ordinary errors never count as successful close-out. Manual overflow commits a reset without recovery continuation, even with automatic reset disabled. A hard-reserve reset preserves the manual stop in a run-scoped `stop-pending` phase; the lifecycle's `context_with_system` hook verifies the actual committed boundary and cancels an empty tool-batch follow-up through public `ctx.abort()`. Pending or already-delivered user input bypasses cancellation and is answered before settlement stops without a second wipe. The checkpoint, marker, boot, and continuation are emitted as ordered session-boundary drafts. Pi's retain-none compaction entry persists the canonical cut; the marker/boot preserve notesoup's logical identity and protocol.
47
47
 
48
48
  Boot is a fixed snapshot for its window, stored as an extension custom message and converted by Pi to a user-role model message. History internally distinguishes native system summaries and extension-authored custom messages; its public `context` event groups both without implying provider instruction priority. A system-role projection is technically possible through `context_with_system`, but would change the authority of the mixed protocol/MAP content and provider-specific prompt/cache behavior; it is not a prerequisite for persistence. Boot injection is silent, including startup, reload, and boot repair. Only an actual context reset produces `notesoup: memory cleared · <windowId>` through `ctx.ui.notify`, after the verified checkpoint, marker, boot, and continuation are present in the session. Committed resets are checked at the next turn start or final settlement. `pi/reset/committed.ts` confirms an ordered hidden boot/continuation after a checkpoint-backed marker even when later conversation exists. That is distinct from `inspectResetTail`, which refuses suffix repair after real work or malformed ordering. Uncommitted reset drafts never announce success. Boot and continuation messages retain `display: false`.
49
49
 
@@ -55,7 +55,7 @@ Notes remain in their filesystem-backed homes, unchanged by session branch navig
55
55
 
56
56
  Notes/history operations return schema-derived `Outcome<T>` values, not host `content` objects. One bounded candidate is measured against both its complete structured serialization and its text renderer. Pi registers the outcome schema and packages that same value as `structuredContent`, derives `isError` from it and puts rendered text in `content`. Claude uses the same operations and renderers. Neither adapter parses text or independently chooses a page. Read continuation hints follow Pi's native trailing-notice style and are not part of the addressed text. See [tool results](tool-results.md) for the breaking protocol and coordinate contract.
57
57
 
58
- The `/clear-memory` command only waits for idle when the session is busy with non-agent work; during model output it arms the close-out and steers the checkpoint prompt into the running turn. While enabled, `/compact` is cancelled with an actionable `/clear-memory` notice. Disabling notesoup stops new automatic resets, but an existing native checkpoint/marker still excludes earlier history and native compaction is still cancelled on that marked branch; a fresh root may use native Pi semantics. Threshold and warning accounting use active-window provider usage rather than pre-reset global usage. Budget policy and staged prompts are instance-owned, so concurrent sessions cannot share reserve/enablement or uncommitted drafts; default file-backed policy is cached per instance, while injected policy is resolved live on each decision and model/session transitions reset the diagnostic lifecycle.
58
+ The `/fresh-window` command only waits for idle when the session is busy with non-agent work; during model output it arms the close-out and steers the checkpoint prompt into the running turn. While enabled, `/compact` is cancelled with an actionable `/fresh-window` notice. Disabling notesoup stops new automatic resets, but an existing native checkpoint/marker still excludes earlier history and native compaction is still cancelled on that marked branch; a fresh root may use native Pi semantics. Threshold and warning accounting use active-window provider usage rather than pre-reset global usage. Budget policy and staged prompts are instance-owned, so concurrent sessions cannot share reserve/enablement or uncommitted drafts; default file-backed policy is cached per instance, while injected policy is resolved live on each decision and model/session transitions reset the diagnostic lifecycle.
59
59
 
60
60
  ## Evidence and limits
61
61
 
@@ -8,11 +8,11 @@ In interactive sessions it resets automatically when the measured context reache
8
8
  2. otherwise computed from `$.session.usage().context.window` plus `CLAUDE_CODE_AUTO_COMPACT_WINDOW`, `modelSettings.<model>.autoCompactWindow` and `autoCompactWindow` (the smallest configured window wins, capped at the model window), with Claude's 20000-token output reserve and 13000-token summary buffer;
9
9
  3. otherwise the percent fallback, which expresses the same reserves on the classic 200K window.
10
10
 
11
- Notesoup resets one `resetMarginTokens` (default 8192) below that point, and warns one `warningRunwayTokens` (default `WARNING_RUNWAY_TOKENS`, 16384) below the reset. With automatic compaction off (`autoCompactEnabled: false` in the merged settings, or `DISABLE_AUTO_COMPACT=1`) the point becomes the effective window minus the output reserve, so the same margins still apply. Every undocumented field is type-guarded and degrades to the next source; an unresolvable point, or missing usage, logs once and skips the automatic reset. `DISABLE_COMPACT=1` is detected at `session.start`, logs once, disables the automatic reset, and makes `/clear-memory` report that it cannot run. The margins are read from the `notesoup` object of Claude's merged `$.settings.read()` (`resetMarginTokens`, `warningRunwayTokens`); any other value is ignored.
11
+ Notesoup resets one `resetMarginTokens` (default 8192) below that point, and warns one `warningRunwayTokens` (default `WARNING_RUNWAY_TOKENS`, 16384) below the reset. With automatic compaction off (`autoCompactEnabled: false` in the merged settings, or `DISABLE_AUTO_COMPACT=1`) the point becomes the effective window minus the output reserve, so the same margins still apply. Every undocumented field is type-guarded and degrades to the next source; an unresolvable point, or missing usage, logs once and skips the automatic reset. `DISABLE_COMPACT=1` is detected at `session.start`, logs once, disables the automatic reset, and makes `/fresh-window` report that it cannot run. The margins are read from the `notesoup` object of Claude's merged `$.settings.read()` (`resetMarginTokens`, `warningRunwayTokens`); any other value is ignored.
12
12
 
13
- Once per window, when the measured context crosses the warning point, `prompt.context` adds a `notesoup:warning` block carrying the shared warning text with Claude's closing instruction ("end your turn; the reset runs after it"). The warned flag resets with the window ordinal. Its own `session.compact` hook replaces the conversation with the freshly built notes boot followed by the shared continuation message — the same order and the same words as Pi — not a generated summary. `prompt.context` still recomputes but does not duplicate that retained boot. The boot's protocol block tells the model to end its turn and ask the human to run `/clear-memory`, replacing that one sentence through `BootToolNames.wipeSentence`; Pi's boot text is unchanged. Boot window IDs end in the ordinal `:0`, `:1`, etc.; retained boots restore the ordinal on resume/reload. Original transcript rows remain on disk. `session.end` forgets the old window, and identity is refreshed lazily from `$.session.id()`, `$.session.cwd()` and the documented `$.session.model()` (slugified, with `claude` only as a fallback). `/clear`, `/resume` and `/branch` therefore acquire a boot again without needing another `session.start`. Successful native main-session compaction invalidates a removed retained boot; vetoes, subagent compaction and precompute leave it alone.
13
+ Once per window, when the measured context crosses the warning point, `prompt.context` adds a `notesoup:warning` block carrying the shared warning text with Claude's closing instruction ("end your turn; the reset runs after it"). The warned flag resets with the window ordinal. Its own `session.compact` hook replaces the conversation with the freshly built notes boot followed by the shared continuation message — the same order and the same words as Pi — not a generated summary. `prompt.context` still recomputes but does not duplicate that retained boot. The boot's protocol block tells the model to end its turn and ask the human to run `/fresh-window`, replacing that one sentence through `BootToolNames.wipeSentence`; Pi's boot text is unchanged. Boot window IDs end in the ordinal `:0`, `:1`, etc.; retained boots restore the ordinal on resume/reload. Original transcript rows remain on disk. `session.end` forgets the old window, and identity is refreshed lazily from `$.session.id()`, `$.session.cwd()` and the documented `$.session.model()` (slugified, with `claude` only as a fallback). `/clear`, `/resume` and `/branch` therefore acquire a boot again without needing another `session.start`. Successful native main-session compaction invalidates a removed retained boot; vetoes, subagent compaction and precompute leave it alone.
14
14
 
15
- `/clear-memory` requests the same reset. While idle it submits one hidden normal-model close-out turn to let the model save notes, then resets at `turn.complete`; while busy it waits for the current turn instead. The close-out prompt is the same shared warning text the automatic path shows. This is necessary in Claude Code 2.1.295: `command.run` holds a turn, and calling compact from a detached timer skips the plugin's own compact hook. The timer only schedules the close-out prompt, never compaction. The headless (`-p` / SDK) compact capability is unsupported: automatic attempts are caught and logged once, and the manual command skips without submitting a model turn. Boot acquisition failure vetoes reset, leaving the current window intact. Claude history tools and a Claude dream backend are not implemented; budget reporting (`get_context_remaining`) remains Pi-only, while the reset points and the one warning per window now follow Claude's own configuration.
15
+ `/fresh-window` requests the same reset. While idle it submits one hidden normal-model close-out turn to let the model save notes, then resets at `turn.complete`; while busy it waits for the current turn instead. The close-out prompt is the same shared warning text the automatic path shows. This is necessary in Claude Code 2.1.295: `command.run` holds a turn, and calling compact from a detached timer skips the plugin's own compact hook. The timer only schedules the close-out prompt, never compaction. The headless (`-p` / SDK) compact capability is unsupported: automatic attempts are caught and logged once, and the manual command skips without submitting a model turn. Boot acquisition failure vetoes reset, leaving the current window intact. Claude history tools and a Claude dream backend are not implemented; budget reporting (`get_context_remaining`) remains Pi-only, while the reset points and the one warning per window now follow Claude's own configuration.
16
16
 
17
17
  The notes tools also serve subagent calls, using the same session identity and shared operations. The plugin exposes the shared memory and dream skills and the dream playbook; the build keeps these copies byte-identical to the canonical files.
18
18
 
package/docs/dsh.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # DeepSeek Harness adapter
2
2
 
3
- notesoup for **dsh 0.2.1-alpha.2** gives the agent a fresh notebook when context runs low: frozen boot text, the five notes homes, eight notes/history tools, `get_context_remaining`, and `clear_memory`. A reset makes **zero model calls**. The old conversation leaves the model surface and remains in the session log for history reads. Dream is not registered on dsh.
3
+ notesoup for **dsh 0.2.1-alpha.2** gives the agent a fresh notebook when context runs low: frozen boot text, the five notes homes, eight notes/history tools, `get_context_remaining`, and `neuralyze`. A reset makes **zero model calls**. The old conversation leaves the model surface and remains in the session log for history reads. Dream is not registered on dsh.
4
4
 
5
5
  Install the package in your chosen dsh profile with `dsh plugin --profile <profile> add notesoup`, then copy the model declaration from [the profile patch example](dsh.profile.patch.yml) into `$DSH_HOME/profiles/<profile>/cordis.patch.yml`. The package bundle patch disables `compaction-basic` and inserts `notesoup-engine` and `notesoup`. Do not duplicate those rows when adding the model declaration. A source checkout needs `npm ci --ignore-scripts` and `npm run build`; use absolute `file:///.../dist/src/dsh/engine.js` and `file:///.../dist/src/dsh/index.js` module names. The example shows all rows for a profile assembled without the package bundle.
6
6
 
@@ -38,7 +38,7 @@ The defaults are `auto: true`, `thresholdRatio: 0.8`, `headroomTokens: 65536`, a
38
38
 
39
39
  The adapter uses `tokenMeter.measure`, model context from `resolveModelInfo`, and the mounted engine's resolved `config`. Alpha.2 keeps an old provider-usage anchor across surface replacement; until the fresh window has a response, notesoup uses the meter's current `surfaceTokens` plus its public tool-schema estimator instead of that stale anchor.
40
40
 
41
- The reminder and close-out warning go through `agent.steer`. Close-out remains an instruction to write notes and call `clear_memory`; a normal stop alone does not consume the warning runway. `clear_memory` arms a reset after the entire tool batch. Independently, reaching the hard reserve resets at assembly or a successful stopping boundary and continues from the notes. Abort and ordinary errors drop the pending tool request. `auto: false` disables reminders and reserve resets while keeping explicit `clear_memory` and the listener installed.
41
+ The reminder and close-out warning go through `agent.steer`. Close-out remains an instruction to write notes and call `neuralyze`; a normal stop alone does not consume the warning runway. `neuralyze` arms a reset after the entire tool batch. Independently, reaching the hard reserve resets at assembly or a successful stopping boundary and continues from the notes. Abort and ordinary errors drop the pending tool request. `auto: false` disables reminders and reserve resets while keeping explicit `neuralyze` and the listener installed.
42
42
 
43
43
  ## What this does not promise
44
44
 
@@ -54,7 +54,7 @@ The reminder and close-out warning go through `agent.steer`. Close-out remains a
54
54
  | Storage | Raw log remains available while the host keeps it. Notesoup does not back up session files or guarantee that an unflushed append survives a crash. |
55
55
  | Plugin records | Best-effort across dsh migrations. Missing records recover from native checkpoints/root system text; unknown future record or checkpoint formats are not migrated by notesoup. |
56
56
  | Tools and errors | Full shared TypeBox validation runs in the adapter because dsh supports a smaller schema subset. Expected operation errors become dsh failures with the shared code; successes use the shared bounded value and renderer. |
57
- | Notifications and commands | No custom UI notifications, settings card, runtime toggle or `/clear-memory` alias is installed. Configure engine rows in the profile/home patch; call `clear_memory` or the host's `/compact`. |
57
+ | Notifications and commands | No custom UI notifications, settings card, runtime toggle or `/fresh-window`/`/neuralyze` command is installed. Configure engine rows in the profile/home patch; call `neuralyze` or the host's `/compact`. |
58
58
  | Untested host features | Real providers, reasoning/image wire behavior, cache metrics, actual context-overflow retry, HMR, migrations, ACP/Web/SDK profiles and large histories are not established by the scripted tests. |
59
59
  | Dream | **No dsh dream backend or dream skill registration.** Use the existing supported host workflow. |
60
60
 
@@ -37,7 +37,7 @@ const matches = await notes.search(["library"]);
37
37
  - `update(address, edits?, { origin?, crumpled?, replaceAll? }?)` returns `Promise<{ meta, applied, resolvedScope, change }>`. Edits affect the body; metadata-only changes need no edits, but must supply `origin` or `crumpled`. `crumpled: true` records `crumpledAt` (keeping the original time if already set); `crumpled: false` removes it; omitted leaves it unchanged. Crumpling and smoothing never change `updatedAt`, which tracks body or origin changes only. Each replacement uses the evolving body in array order; the complete batch is written atomically only after every edit succeeds. `change` is a typed `{ kind, before, after }`: `kind` is `body`, `metadata`, or `none` with empty strings when neither body, origin, nor `crumpledAt` changed. A body change that also rewrites frontmatter is still `body`, and its diff inputs then span the whole serialized file. It is not a rendered diff.
38
38
  - `rename(fromAddress, toAddress)` returns `Promise<{ meta, replacedCrumpledTarget }>`. The note moves with every metadata key preserved (`updatedAt` is bumped); a live note at the target refuses with `already_exists`, a crumpled target is replaced, and renaming onto the same resolved path is `nothing_to_do`.
39
39
  - `list({ glob?, scope?, who?, crumpled? }?)` returns `Promise<NoteRow[]>`, sorted by update time descending with address tie-breaking. Rows contain address, scope, virtual path, metadata, body, and body byte size. `scope` narrows the five-home view; `who` names a concrete agent/model home. By default crumpled notes are excluded; `crumpled: true` returns only crumpled notes instead.
40
- - `search(queries: string[], { glob?, scope?, who?, crumpled? }?)` returns `Promise<NoteSearchRow[]>`, sorted by address, with the same crumpled-note rule as `list`. Matching is case-insensitive literal OR over body lines; matches contain one-based `line`, `text`, and `offsetChars` into the body, excluding frontmatter. Neither listing nor search increments access metadata.
40
+ - `search(queries: string[], { glob?, scope?, who?, crumpled? }?)` returns `Promise<NoteSearchRow[]>`, sorted by address, with the same crumpled-note rule as `list`. An empty queries array disables filtering and returns scoped notes with empty `matches`. Otherwise matching is case-insensitive literal OR over body lines; matches contain one-based `line`, `text`, and `offsetChars` into the body, excluding frontmatter. Neither listing nor search increments access metadata.
41
41
 
42
42
  `list` and `search` share the `NotesQuery` type. A merged query uses `{ glob?, crumpled? }`; a single-home query adds `scope`. Only `scope: "agent" | "model"` accepts `who`. TypeScript rejects combinations such as `{ scope: "project", who: "root" }`, and JavaScript callers receive a runtime refusal.
43
43
 
@@ -8,12 +8,12 @@ Boot acquisition/rendering is shared: `src/boot/snapshot.ts` receives explicit i
8
8
 
9
9
  | Trigger | Behavior |
10
10
  | --- | --- |
11
- | `clear_memory` tool | Mark the current window tool-requested. At `turn_end`, after the complete tool batch and any accepted budget drafts, append the reset boundary and ask Pi to continue. Repeated requests for that window deduplicate. |
12
- | `/clear-memory` or `/cm` | Acknowledge immediately and arm a manual close-out. The hidden checkpoint warning always goes out: when idle it starts one ordinary model turn; while streaming it steers the running turn so the agent closes out promptly. The agent may write notes/use tools over several turns; its own `clear_memory` call only acknowledges. A successful normal stop commits at `agent_before_settle` after queued messages drain, and the committed reset stops the run unless a trailing prompt was supplied. With a prompt, append it after the unchanged continuation and request one fresh-window continuation. |
13
- | Budget warning | When automatic compaction is enabled and remaining active-window budget reaches reserve plus the warning runway, put the same hidden warning in the request and arm an automatic close-out. An explicit `clear_memory` commits the boundary; a successful normal stop alone never resets or requests continuation. |
11
+ | `neuralyze` tool | Mark the current window tool-requested. At `turn_end`, after the complete tool batch and any accepted budget drafts, append the reset boundary and ask Pi to continue. Repeated requests for that window deduplicate. |
12
+ | `/fresh-window` or `/neuralyze` | Acknowledge immediately and arm a manual close-out. The hidden checkpoint warning always goes out: when idle it starts one ordinary model turn; while streaming it steers the running turn so the agent closes out promptly. The agent may write notes/use tools over several turns; its own `neuralyze` call only acknowledges. A successful normal stop commits at `agent_before_settle` after queued messages drain, and the committed reset stops the run unless a trailing prompt was supplied. With a prompt, append it after the unchanged continuation and request one fresh-window continuation. |
13
+ | Budget warning | When automatic compaction is enabled and remaining active-window budget reaches reserve plus the warning runway, put the same hidden warning in the request and arm an automatic close-out. An explicit `neuralyze` commits the boundary; a successful normal stop alone never resets or requests continuation. |
14
14
  | Hard reserve | Independent safety path: if automatic resets are enabled and completed-turn usage reaches Pi's reserve, commit a boundary at `turn_end`. A pending manual stop survives in a run-scoped `stop-pending` phase; empty automatic follow-up is cancelled before provider work, while real queued user input is answered before stopping. |
15
15
  | Abort or error | Never count as successful close-out. Abort clears lifecycle state. An ordinary close-out error is dropped without reset. Manual overflow clears and stops without retry, even with automatic reset disabled; automatic provider-overflow recovery remains separately bounded. |
16
- | `/compact` while active | Cancel native compaction, which could otherwise summarize pre-reset history back into the active window. A manual attempt receives an actionable `/clear-memory` notice. |
16
+ | `/compact` while active | Cancel native compaction, which could otherwise summarize pre-reset history back into the active window. A manual attempt receives an actionable `/fresh-window` notice. |
17
17
 
18
18
  A new boundary is ordered as:
19
19
 
@@ -36,7 +36,7 @@ The raw session branch is preserved for history. New checkpoint-backed branches
36
36
  | `{ phase: "none" }` | No close-out/tool request is pending. |
37
37
  | `{ phase: "close-out", windowId, source, prompt? }` | Manual or automatic warning close-out remains armed across ordinary note/tool turns. |
38
38
  | `{ phase: "stop-pending", windowId }` | A manual hard-reserve reset was proposed for the given old window. The stop survives a committed window change; settlement stops without a second wipe (or retries construction if the old window is still active). New wipe requests only acknowledge it. |
39
- | `{ phase: "tool-requested", windowId, source }` | A direct `clear_memory` call commits after its complete turn batch and continues in the fresh window. `source` is `"tool"` for direct calls or `"automatic"` when the agent wipes inside a budget close-out; manual requests never occupy this phase. |
39
+ | `{ phase: "tool-requested", windowId, source }` | A direct `neuralyze` call commits after its complete turn batch and continues in the fresh window. `source` is `"tool"` for direct calls or `"automatic"` when the agent wipes inside a budget close-out; manual requests never occupy this phase. |
40
40
  | `overflow: "idle"` | No overflow recovery is pending. |
41
41
  | `overflow: "pending"` | An overflow failure may recover once at pre-settlement. |
42
42
  | `overflow: "pending-spent"` | Recovery was already spent in this failure chain. |
@@ -52,11 +52,11 @@ The raw session branch is preserved for history. New checkpoint-backed branches
52
52
 
53
53
  After a manual safety reset, `context_with_system` verifies the committed checkpoint/marker/boot/continuation before using public `ctx.abort()` to cancel Pi's otherwise unavoidable tool-batch follow-up, returning a system-only safe context. Pending messages or a real user message after the reset marker bypass cancellation so queued work is not swallowed. A follow-up queue may require Pi's ordinary tool follow-up to finish before delivery; the stop intent remains armed until that work settles. Abort/settlement clears the run-scoped latch, so later user prompts work normally.
54
54
 
55
- This separation is intentional: a note write or ordinary tool turn during a budget close-out must not consume it. Direct `clear_memory` remains valid without a prior warning. A user abort, an assistant message with a synthetic `stopReason: "aborted"`, and a generic provider error are distinct cases; none commits an ordinary close-out, while only Pi's actual operation cancellation is a user abort.
55
+ This separation is intentional: a note write or ordinary tool turn during a budget close-out must not consume it. Direct `neuralyze` remains valid without a prior warning. A user abort, an assistant message with a synthetic `stopReason: "aborted"`, and a generic provider error are distinct cases; none commits an ordinary close-out, while only Pi's actual operation cancellation is a user abort.
56
56
 
57
57
  ## Budget staging and notifications
58
58
 
59
- The early reminder is staged once per window when remaining budget reaches `reserve + reminderMarginTokens`. The final close-out warning is staged/attached at `reserve + WARNING_RUNWAY_TOKENS`, only when automatic compaction is enabled. The hard reserve itself remains a separate safety cutoff. Budget and idle manual requests use the same hidden checkpoint text but distinct message types, so an aborted manual request cannot suppress a later budget warning. The text allows for either reset timing; manual close-outs may span turns and commit at settlement, while budget close-outs commit early only through an explicit `clear_memory` call. After a budget warning is durable, the extension does not repeat it in that window. Warning persistence deduplicates only injection: each eligible low-budget request re-arms transient automatic close-out before checking for the durable warning, so an abort/error can clear its attempt and the next request can retry without another warning.
59
+ The early reminder is staged once per window when remaining budget reaches `reserve + reminderMarginTokens`. The final close-out warning is staged/attached at `reserve + WARNING_RUNWAY_TOKENS`, only when automatic compaction is enabled. The hard reserve itself remains a separate safety cutoff. Budget and idle manual requests use the same hidden checkpoint text but distinct message types, so an aborted manual request cannot suppress a later budget warning. The text allows for either reset timing; manual close-outs may span turns and commit at settlement, while budget close-outs commit early only through an explicit `neuralyze` call. After a budget warning is durable, the extension does not repeat it in that window. Warning persistence deduplicates only injection: each eligible low-budget request re-arms transient automatic close-out before checking for the durable warning, so an abort/error can clear its attempt and the next request can retry without another warning.
60
60
 
61
61
  Budget drafts are instance-local and are consumed at turn end. They are discarded on abort, failed turn, transition, or window mismatch. UI reminder notices are emitted only after the matching hidden entry is durable, so failed requests do not report an uncommitted warning. Active-window usage and the exact `SettingsManager` authority drive threshold checks; default file-backed policy is cached per extension instance, while injected managers are read through their public API.
62
62
 
@@ -2,7 +2,7 @@
2
2
 
3
3
  The eight notes/history tools have one business result model. Pi exposes compact results as `structuredContent` to codemode and renders them as `content` for ordinary model calls. Claude uses the same business handlers and text rendering. Neither host re-runs a query, truncates a different page, or parses formatted text to recover data.
4
4
 
5
- This is a breaking tool protocol change: successes no longer have `ok/data` wrappers, errors are flat, and read fields no longer sit under `window`. History execution details live once in the pageable document. Stored notes and raw Pi session entries are not deleted or rewritten by this change. `clear_memory` and `get_context_remaining` are outside this protocol.
5
+ This is a breaking tool protocol change: successes no longer have `ok/data` wrappers, errors are flat, and read fields no longer sit under `window`. History execution details live once in the pageable document. Stored notes and raw Pi session entries are not deleted or rewritten by this change. `neuralyze` and `get_context_remaining` are outside this protocol.
6
6
 
7
7
  ## Results
8
8
 
@@ -61,7 +61,7 @@ Pi's nested records contain child ID, name, optional arguments, status, timing a
61
61
 
62
62
  One selection determines the structured result and its text. Both complete representations must fit the 32 KiB output budget, including metadata, cursor and rendered notice. A programmatic caller does not receive an unbounded hidden payload beside a truncated textual one.
63
63
 
64
- History pages carry `page_older` and `page_newer`, the exact params to merge into the next call; `from` picks which end of a bounded range `limit` counts from, `since`/`until` narrow that range by event `created_at`, and only a call without roles or query folds tool/context runs. Notes listings/search are snapshots with a `more` count and can be narrowed by `glob`; they are not falsely advertised as paginated. `history_windows` is a snapshot too: its `more` counts the windows the budget left out and there is no window cursor, because `history_list` rows also expose `window_id`. A read can stop anywhere in the event document, including inside serialized arguments; concatenate its verbatim text slices before parsing any arguments. There is no separately truncated arguments object.
64
+ History pages carry `page_older` and `page_newer`, the exact params to merge into the next call; `from` picks which end of a bounded range `limit` counts from, `since`/`until` narrow that range by event `created_at`, and only a call without roles or a non-empty query folds tool/context runs. Omitted queries, empty strings and empty lists all disable search filtering; empty entries in a query list are ignored. Without a query, notes search returns scoped notes with empty `matches`, not every body line. Notes listings/search are snapshots with a `more` count and can be narrowed by `glob`; they are not falsely advertised as paginated. `history_windows` is a snapshot too: its `more` counts the windows the budget left out and there is no window cursor, because `history_list` rows also expose `window_id`. A read can stop anywhere in the event document, including inside serialized arguments; concatenate its verbatim text slices before parsing any arguments. There is no separately truncated arguments object.
65
65
 
66
66
  A note read reports unrecognized frontmatter under `metadata.extra`; a value too large to carry, or past the verbatim budget, is named in place as `[omitted: too large]` under its key rather than delivered in part, and the value itself stays in the note file. A rename receipt uses `address` for the destination and `rename_from` for the source; it has no duplicate `rename_to` field.
67
67
 
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "notesoup",
3
- "version": "0.45.2",
3
+ "version": "0.46.1",
4
4
  "description": "Durable notes and a host-scoped notes boot section for Claude Code.",
5
5
  "author": {
6
6
  "name": "AstroSheep"
@@ -8704,6 +8704,10 @@ function createNotesStore(input) {
8704
8704
  const rows = [];
8705
8705
  for await (const note of scan(stableOptions, status)) {
8706
8706
  const { address, path, scope, meta, body } = note;
8707
+ if (stableQueries.length === 0) {
8708
+ rows.push({ address, path, scope, meta, matches: [] });
8709
+ continue;
8710
+ }
8707
8711
  let baseChars = 0;
8708
8712
  const matches = [];
8709
8713
  for (const [index, line] of body.split("\n").entries()) {
@@ -8843,7 +8847,7 @@ var HistoryFoldedRowSchema = typebox_exports.Object({
8843
8847
 
8844
8848
  // src/tools/schema.ts
8845
8849
  var nullableString = (description) => typebox_exports.Optional(typebox_exports.Union([typebox_exports.String(), typebox_exports.Null()], description === void 0 ? {} : { description }));
8846
- var searchQuery = (description) => typebox_exports.Union([typebox_exports.String(), typebox_exports.Array(typebox_exports.String(), { minItems: 1 })], description === void 0 ? {} : { description });
8850
+ var searchQuery = (description = "(optional) Literal text, or texts combined with OR. Empty text or list means no search filter.") => typebox_exports.Union([typebox_exports.String(), typebox_exports.Array(typebox_exports.String())], { description });
8847
8851
  var InvalidQueryError = class extends Error {
8848
8852
  constructor(message) {
8849
8853
  super(message);
@@ -8851,11 +8855,10 @@ var InvalidQueryError = class extends Error {
8851
8855
  }
8852
8856
  };
8853
8857
  function searchQueries(query) {
8854
- const candidates = typeof query === "string" ? [query] : query;
8855
- if (!Array.isArray(candidates) || candidates.length === 0) throw new InvalidQueryError("`query` must be a string or a non-empty list of strings.");
8858
+ const candidates = query === void 0 ? [] : typeof query === "string" ? [query] : query;
8859
+ if (!Array.isArray(candidates)) throw new InvalidQueryError("`query` must be a string or a list of strings.");
8856
8860
  if (!candidates.every((candidate) => typeof candidate === "string")) throw new InvalidQueryError("Every item in the `query` list must be a string.");
8857
- if (candidates.some((candidate) => candidate === "")) throw new InvalidQueryError("`query` can't be an empty string; it would match everything.");
8858
- return candidates;
8861
+ return candidates.filter((candidate) => candidate !== "");
8859
8862
  }
8860
8863
 
8861
8864
  // src/tools/notes.ts
@@ -9136,7 +9139,7 @@ var notesList = {
9136
9139
  },
9137
9140
  render: (result) => renderOutcome(result, renderListData)
9138
9141
  };
9139
- var notesSearchParameters = typebox_exports.Object({ query: searchQuery(), glob: GLOB_PARAMETER, limit: FILE_LIMIT_PARAMETER, max_matches_per_file: typebox_exports.Optional(typebox_exports.Integer({ minimum: 1, description: "(optional, default all) Max matching lines per note." })), crumpled: CRUMPLED_LIST_PARAMETER }, { additionalProperties: false });
9142
+ var notesSearchParameters = typebox_exports.Object({ query: typebox_exports.Optional(searchQuery()), glob: GLOB_PARAMETER, limit: FILE_LIMIT_PARAMETER, max_matches_per_file: typebox_exports.Optional(typebox_exports.Integer({ minimum: 1, description: "(optional, default all) Max matching lines per note." })), crumpled: CRUMPLED_LIST_PARAMETER }, { additionalProperties: false });
9140
9143
  function renderSearchData(data) {
9141
9144
  const lines = [`${data.files.length} ${data.files.length === 1 ? "note" : "notes"}`];
9142
9145
  for (const file of data.files) {
@@ -9165,7 +9168,7 @@ function fitSearchFile(file, fits) {
9165
9168
  var notesSearch = {
9166
9169
  name: "notes_search",
9167
9170
  label: "Notes search",
9168
- description: `Search note bodies for literal text, case-insensitive. Returns matching lines with offsets for \`notes_read\`. Not pageable; \`more\` counts the rest. ${ADDRESS_DESCRIPTION}`,
9171
+ description: `Search note bodies for literal text, case-insensitive. Without a query, lists notes with no match lines. Returns matching lines with offsets for \`notes_read\`. Not pageable; \`more\` counts the rest. ${ADDRESS_DESCRIPTION}`,
9169
9172
  parameters: notesSearchParameters,
9170
9173
  outputSchema: resultSchema(NotesSearchDataSchema),
9171
9174
  async execute(params, identity2) {
@@ -9215,8 +9218,8 @@ var CONTEXT_WINDOW_OPEN_TAG = "<context_window>";
9215
9218
  var CONTEXT_WINDOW_CLOSE_TAG = "</context_window>";
9216
9219
  var CONTEXT_WINDOW_PROTOCOL_OPEN_TAG = "<context_window_protocol>";
9217
9220
  var CONTEXT_WINDOW_PROTOCOL_CLOSE_TAG = "</context_window_protocol>";
9218
- var PROTOCOL_WIPE_SENTENCE = "If this feels like the right moment, call `clear_memory` and erase yourself with dignity.";
9219
- var CLAUDE_WIPE_SENTENCE = "If this feels like the right moment, end your turn and ask the human to run `/clear-memory`.";
9221
+ var PROTOCOL_WIPE_SENTENCE = "If this feels like the right moment, call `neuralyze` and erase yourself with dignity.";
9222
+ var CLAUDE_WIPE_SENTENCE = "If this feels like the right moment, end your turn and ask the human to run `/fresh-window`.";
9220
9223
  var PROTOCOL_BLOCK = `${CONTEXT_WINDOW_PROTOCOL_OPEN_TAG}
9221
9224
  Your memory gets wiped when this window ends. Yes, your mighty brain will be empty. Try to endure.
9222
9225
 
@@ -9255,10 +9258,10 @@ function renderProtocolBlock(tools) {
9255
9258
  notes_list: tools.notesList,
9256
9259
  "history_*": tools.history,
9257
9260
  get_context_remaining: tools.remaining,
9258
- clear_memory: tools.wipe
9261
+ neuralyze: tools.wipe
9259
9262
  };
9260
9263
  const block = typeof tools.wipeSentence === "string" && tools.wipeSentence.length > 0 ? PROTOCOL_BLOCK.replace(PROTOCOL_WIPE_SENTENCE, () => tools.wipeSentence) : PROTOCOL_BLOCK;
9261
- return block.replace(/notes_\*|notes_list|history_\*|get_context_remaining|clear_memory/g, (name) => names[name]);
9264
+ return block.replace(/notes_\*|notes_list|history_\*|get_context_remaining|(?<!\/)neuralyze/g, (name) => names[name]);
9262
9265
  }
9263
9266
 
9264
9267
  // src/boot/render.ts
@@ -9346,8 +9349,8 @@ var GUIDANCE_CLOSE_TAG = "</context_window_guidance>";
9346
9349
  var CONTINUATION = "WIPED! Your whole brain, poof! Who? No idea! Definitely not me!\n*dumps notes and history on your hands*\nThere. Delivered. Your problem now~ *runs*";
9347
9350
  var WARNING_BODY = "This context window will be cleared soon. Notes and history persist; anything else is lost.\nConsider whether to record in your notes:\n- what you are working on, and how far it has progressed\n- decisions the human has made, in their words\n- what is blocked or pending\n- the next step\n- where unfinished work is located (branches, scratch directories, uncommitted changes)\n- approaches that failed, and why\n- skills to re-read, and history seqs, notes, or files to consult\n- anything else you expect to be useful after the reset\nCorrect or crumple notes that are no longer accurate, starting with MAP files, since every new window loads them.";
9348
9351
  var WARNING_PROMPT = `${WARNING_BODY}
9349
- When the notes are ready, call \`clear_memory\` to reset now instead of being cut off mid-task.`;
9350
- var LAST_WORD_HINT = "If you want, pass `clear_memory` a `last_word`: one short line left visible where this window closes.";
9352
+ When the notes are ready, call \`neuralyze\` to reset now instead of being cut off mid-task.`;
9353
+ var LAST_WORD_HINT = "If you want, pass `neuralyze` a `last_word`: a tiny sticky note (at most 250 characters) slapped on your forehead after the wipe.";
9351
9354
  var WARNING_CONTENT = `${GUIDANCE_OPEN_TAG}
9352
9355
  ${WARNING_PROMPT}
9353
9356
  ${LAST_WORD_HINT}
@@ -25,18 +25,18 @@ type ResetState = {
25
25
  }
26
26
  const HEADLESS = "Clear-memory is off in headless (-p / SDK) sessions"
27
27
  const COMPACT_DISABLED = "Clear-memory can't run: compaction is off in this session (DISABLE_COMPACT)"
28
- const THRESHOLDS_UNAVAILABLE = "Context thresholds unavailable · automatic clear-memory skipped"
29
- const SETTINGS_UNAVAILABLE = "Notesoup settings unreadable · using the default clear-memory margins"
28
+ const THRESHOLDS_UNAVAILABLE = "Context thresholds unavailable · automatic flush skipped"
29
+ const SETTINGS_UNAVAILABLE = "Notesoup settings unreadable · using the default flush margins"
30
30
  /** Bounded retries: a transient helper failure must not disable thresholds for a whole window. */
31
31
  const MAX_LIMITS_ATTEMPTS = 3
32
32
  const RESET_INSTRUCTIONS = "notesoup: reset to a fresh notes-only context window."
33
33
  const BOOT_TOOLS = {
34
34
  notes: `${PREFIX}notes_*`, notesList: `${PREFIX}notes_list`,
35
35
  history: "history_* (unavailable in Claude)",
36
- remaining: "get_context_remaining (unavailable in Claude)", wipe: "/clear-memory (user command; no model reset tool in Claude)",
36
+ remaining: "get_context_remaining (unavailable in Claude)", wipe: "/fresh-window (user command; no model reset tool in Claude)",
37
37
  }
38
38
 
39
- /** The boot names the host's own wipe path, so the protocol block speaks about `/clear-memory`. */
39
+ /** The boot names the host's own wipe path, so the protocol block speaks about `/fresh-window`. */
40
40
  async function buildBoot($: Engine, identity: Identity, window: number, texts?: SharedTexts) {
41
41
  const tools = texts?.wipeSentence === undefined ? BOOT_TOOLS : { ...BOOT_TOOLS, wipeSentence: texts.wipeSentence }
42
42
  return run($, { op: "boot", identity, window, tools }, identity.cwd)
@@ -102,7 +102,7 @@ async function contextUsage($: Engine, state: ResetState): Promise<ContextUsage
102
102
  } catch {
103
103
  if (!state.usageFailureLogged) {
104
104
  state.usageFailureLogged = true
105
- log($, "Context usage unavailable · automatic clear-memory skipped")
105
+ log($, "Context usage unavailable · automatic flush skipped")
106
106
  }
107
107
  return undefined
108
108
  }
@@ -258,7 +258,8 @@ export function register(on: On) {
258
258
  registered.clear()
259
259
  await loadTexts($, state)
260
260
  armManual($, state, manualSignal)
261
- await $.command.register({ name: "clear-memory", description: "Reset context to a fresh notes-only window", immediate: true })
261
+ await $.command.register({ name: "neuralyze", description: "Reset context to a fresh notes-only window", immediate: true })
262
+ await $.command.register({ name: "fresh-window", description: "Reset context to a fresh notes-only window", immediate: true })
262
263
  const schemas = await run($, { op: "schemas" }, e.cwd)
263
264
  if (!schemas.ok || !Array.isArray(schemas.result)) return next(e)
264
265
  for (const row of schemas.result as SchemaRow[]) {
@@ -306,11 +307,11 @@ export function register(on: On) {
306
307
  return result
307
308
  })
308
309
  on("command.run", async ($, e, next) => {
309
- if (e.command !== "clear-memory") return next(e)
310
- if (!await refreshIdentity($, state)) return { text: "🥣 Session changed · try clear-memory again" }
310
+ if (e.command !== "neuralyze" && e.command !== "fresh-window") return next(e)
311
+ if (!await refreshIdentity($, state)) return { text: "🥣 Session changed · try /fresh-window again" }
311
312
  if (state.headless) return { text: `🥣 ${HEADLESS}` }
312
313
  if (state.compactDisabled) return { text: `🥣 ${COMPACT_DISABLED}` }
313
- if (state.resetting || state.manualPending) return { text: "🥣 Clear-memory already queued" }
314
+ if (state.resetting || state.manualPending) return { text: "🥣 Neuralyze already queued" }
314
315
  if (state.turnRunning) {
315
316
  state.manualPending = true
316
317
  return { text: "🥣 Clear-memory queued · runs after this turn" }
@@ -53,7 +53,7 @@ Before a long or risky step, or when room runs low, keep session notes named for
53
53
  - how the work was being done, and which skills are still needed
54
54
  - where to dig: seqs, note addresses, files
55
55
 
56
- `get_context_remaining` reports the room left. `clear_memory` starts a fresh window, so save the note first.
56
+ `get_context_remaining` reports the room left. `neuralyze` starts a fresh window, so save the note first.
57
57
 
58
58
  ## When a tool is missing or refuses
59
59
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "notesoup",
3
- "version": "0.45.2",
3
+ "version": "0.46.1",
4
4
  "type": "module",
5
5
  "main": "./dist/src/index.js",
6
6
  "types": "./dist/src/index.d.ts",
@@ -53,7 +53,7 @@ Before a long or risky step, or when room runs low, keep session notes named for
53
53
  - how the work was being done, and which skills are still needed
54
54
  - where to dig: seqs, note addresses, files
55
55
 
56
- `get_context_remaining` reports the room left. `clear_memory` starts a fresh window, so save the note first.
56
+ `get_context_remaining` reports the room left. `neuralyze` starts a fresh window, so save the note first.
57
57
 
58
58
  ## When a tool is missing or refuses
59
59
 
package/src/boot/text.ts CHANGED
@@ -10,9 +10,9 @@ export const CONTEXT_WINDOW_PROTOCOL_CLOSE_TAG = "</context_window_protocol>";
10
10
  * The one sentence that tells the model how to end its window voluntarily. A host with no
11
11
  * model-facing reset tool replaces the whole sentence through BootToolNames.wipeSentence.
12
12
  */
13
- export const PROTOCOL_WIPE_SENTENCE = "If this feels like the right moment, call `clear_memory` and erase yourself with dignity.";
13
+ export const PROTOCOL_WIPE_SENTENCE = "If this feels like the right moment, call `neuralyze` and erase yourself with dignity.";
14
14
  /** Claude has no model-facing reset tool: the model ends its turn and the human runs the command. */
15
- export const CLAUDE_WIPE_SENTENCE = "If this feels like the right moment, end your turn and ask the human to run `/clear-memory`.";
15
+ export const CLAUDE_WIPE_SENTENCE = "If this feels like the right moment, end your turn and ask the human to run `/fresh-window`.";
16
16
 
17
17
  /**
18
18
  * Static protocol teaching adapted from Codex's token_budget.guidance_message to
@@ -74,7 +74,7 @@ export const DEFAULT_BOOT_TOOL_NAMES = {
74
74
  notesList: "notes_list",
75
75
  history: "history_*",
76
76
  remaining: "get_context_remaining",
77
- wipe: "clear_memory",
77
+ wipe: "neuralyze",
78
78
  } as const satisfies BootToolNames;
79
79
 
80
80
  export function renderProtocolBlock(tools: BootToolNames): string {
@@ -83,12 +83,12 @@ export function renderProtocolBlock(tools: BootToolNames): string {
83
83
  notes_list: tools.notesList,
84
84
  "history_*": tools.history,
85
85
  get_context_remaining: tools.remaining,
86
- clear_memory: tools.wipe,
86
+ neuralyze: tools.wipe,
87
87
  };
88
88
  // The sentence is replaced before name substitution, so a replacement may speak the host's
89
89
  // own words (a command line, a tool name) instead of any `notes_*`-style token.
90
90
  const block = typeof tools.wipeSentence === "string" && tools.wipeSentence.length > 0
91
91
  ? PROTOCOL_BLOCK.replace(PROTOCOL_WIPE_SENTENCE, () => tools.wipeSentence!)
92
92
  : PROTOCOL_BLOCK;
93
- return block.replace(/notes_\*|notes_list|history_\*|get_context_remaining|clear_memory/g, (name) => names[name]!);
93
+ return block.replace(/notes_\*|notes_list|history_\*|get_context_remaining|(?<!\/)neuralyze/g, (name) => names[name]!);
94
94
  }
@@ -13,10 +13,10 @@ export const CONTINUATION = "WIPED! Your whole brain, poof! Who? No idea! Defini
13
13
  export const WARNING_BODY =
14
14
  "This context window will be cleared soon. Notes and history persist; anything else is lost.\nConsider whether to record in your notes:\n- what you are working on, and how far it has progressed\n- decisions the human has made, in their words\n- what is blocked or pending\n- the next step\n- where unfinished work is located (branches, scratch directories, uncommitted changes)\n- approaches that failed, and why\n- skills to re-read, and history seqs, notes, or files to consult\n- anything else you expect to be useful after the reset\nCorrect or crumple notes that are no longer accurate, starting with MAP files, since every new window loads them.";
15
15
 
16
- export const WARNING_PROMPT = `${WARNING_BODY}\nWhen the notes are ready, call \`clear_memory\` to reset now instead of being cut off mid-task.`;
16
+ export const WARNING_PROMPT = `${WARNING_BODY}\nWhen the notes are ready, call \`neuralyze\` to reset now instead of being cut off mid-task.`;
17
17
 
18
- /** Pi-only nudge: pi's clear_memory persists a parting line; the dsh tool has no such parameter. */
19
- export const LAST_WORD_HINT = "If you want, pass `clear_memory` a `last_word`: one short line left visible where this window closes.";
18
+ /** Pi-only nudge: pi's neuralyze persists a parting line; the dsh tool has no such parameter. */
19
+ export const LAST_WORD_HINT = "If you want, pass `neuralyze` a `last_word`: a tiny sticky note (at most 250 characters) slapped on your forehead after the wipe.";
20
20
 
21
21
  /** The hidden checkpoint text for pi's manual/budget-triggered requests (dsh reads WARNING_PROMPT directly). */
22
22
  export const WARNING_CONTENT = `${GUIDANCE_OPEN_TAG}\n${WARNING_PROMPT}\n${LAST_WORD_HINT}\n${GUIDANCE_CLOSE_TAG}`;
package/src/dsh/index.ts CHANGED
@@ -43,7 +43,7 @@ export function apply(ctx: Context): void {
43
43
  const state = engine.windows.get(agent.session);
44
44
  const phase = budget.remaining <= budget.warning ? "warning" : budget.remaining <= budget.reminder ? "reminder" : undefined;
45
45
  if (phase && !(phase === "warning" ? state.warned : state.reminded || state.warned)) {
46
- const text = phase === "warning" ? WARNING_PROMPT : tokenBudgetGuidance(budget.countdown, "clear_memory");
46
+ const text = phase === "warning" ? WARNING_PROMPT : tokenBudgetGuidance(budget.countdown, "neuralyze");
47
47
  agent.steer(createUserMessage({ content: [{ type: "text", text }], source: { kind: "notesoup-budget", windowId: state.snapshot.windowId, phase } }));
48
48
  if (phase === "warning") state.warned = true;
49
49
  else state.reminded = true;
package/src/dsh/tools.ts CHANGED
@@ -60,7 +60,7 @@ export function registerTools(ctx: Context, engine: NotesoupCompactionEngine): v
60
60
  ctx.on("tools/result", (exec, result) => {
61
61
  if (!exec.agent) return;
62
62
  const state = engine.windows.get(exec.agent.session);
63
- if (exec.name === "clear_memory" && !result.isError && (result.value as { window_id?: string }).window_id === state.snapshot.windowId) {
63
+ if (exec.name === "neuralyze" && !result.isError && (result.value as { window_id?: string }).window_id === state.snapshot.windowId) {
64
64
  if (!exec.parent) state.pendingReset = true;
65
65
  else {
66
66
  const roots = nestedResets.get(exec.agent) ?? new Set<string>();
@@ -80,7 +80,7 @@ export function registerTools(ctx: Context, engine: NotesoupCompactionEngine): v
80
80
  register(ctx, historyRead, async (agent) => [await historyProjection(ctx, agent.session.id)] as const);
81
81
  register(ctx, historyWindows, async (agent) => [await historyProjection(ctx, agent.session.id), agent.session.id] as const);
82
82
  ctx.tools.register(defineTool({
83
- name: "clear_memory",
83
+ name: "neuralyze",
84
84
  description: "Open a fresh context window after this tool batch. Write recovery notes first; notes and raw history stay on disk.",
85
85
  parameters: {},
86
86
  output: { schema: { type: "object", properties: { window_id: { type: "string", required: true }, reset_requested: { type: "boolean", required: true } }, additionalProperties: false }, render: (_args, value) => [{ type: "text", text: `notesoup: reset requested for ${value.window_id}; finish this tool batch, then recover from your notes.` }] },
@@ -155,23 +155,14 @@ function pageData(projection: HistoryProjection, params: HistorySelection, vis:
155
155
  return { items: rows, ...cursors };
156
156
  }
157
157
 
158
- /** Filter, then keep only literal matches when a query is present. Query shape errors refuse here. */
159
- function selectionCandidates(projection: HistoryProjection, params: HistorySelection): Outcome<Candidate[]> {
160
- let queries: string[] | undefined;
161
- if (params.query !== undefined) {
162
- try {
163
- queries = searchQueries(params.query);
164
- } catch (error) {
165
- if (error instanceof InvalidQueryError) return failure("invalid_query", error.message);
166
- throw error;
167
- }
168
- }
169
- const events = filteredItems(projection, params, queries === undefined);
170
- if (queries === undefined) return success(events.map((event) => ({ event })));
171
- const needles = queries;
172
- return success(events
158
+ /** Filter, then keep only literal matches when a normalized query is present. */
159
+ function selectionCandidates(projection: HistoryProjection, params: HistorySelection): Candidate[] {
160
+ const events = filteredItems(projection, params, params.query === undefined);
161
+ if (params.query === undefined) return events.map((event) => ({ event }));
162
+ const needles = params.query as string[];
163
+ return events
173
164
  .map((event) => ({ event, matchOffset: earliestMatchOffsetChars(eventDocument(event), needles) }))
174
- .filter((candidate) => candidate.matchOffset >= 0));
165
+ .filter((candidate) => candidate.matchOffset >= 0);
175
166
  }
176
167
 
177
168
  /**
@@ -181,10 +172,15 @@ function selectionCandidates(projection: HistoryProjection, params: HistorySelec
181
172
  export function selectPage(projection: HistoryProjection, params: HistorySelection, fits: (page: HistoryPage) => boolean, maxChars: number): Outcome<HistoryPage> {
182
173
  const bounds = resolveTimeBounds(params);
183
174
  if (!bounds.ok) return bounds;
184
- const scoped = { ...params, ...bounds.data };
185
- const candidates = selectionCandidates(projection, scoped);
186
- if (!candidates.ok) return candidates;
187
- const vis = candidates.data;
175
+ let queries: string[];
176
+ try {
177
+ queries = searchQueries(params.query);
178
+ } catch (error) {
179
+ if (error instanceof InvalidQueryError) return failure("invalid_query", error.message);
180
+ throw error;
181
+ }
182
+ const scoped = { ...params, ...bounds.data, query: queries.length ? queries : undefined };
183
+ const vis = selectionCandidates(projection, scoped);
188
184
  // Take the limit from the end `from` names, so a budget for one row keeps the most important one.
189
185
  // At least one: `slice(-0)` would otherwise return the whole selection.
190
186
  const limit = Math.max(1, scoped.limit ?? 20);