notesoup 0.50.0 → 0.51.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (172) hide show
  1. package/README.md +12 -0
  2. package/dist/{src/claude → plugins/claude/src}/helper.js +7 -7
  3. package/dist/{src/claude → plugins/claude/src}/history.d.ts +1 -1
  4. package/dist/{src/claude → plugins/claude/src}/history.js +1 -1
  5. package/dist/plugins/claude/src/text.d.ts +6 -0
  6. package/dist/plugins/claude/src/text.js +7 -0
  7. package/dist/{src/claude → plugins/claude/src}/thresholds.js +3 -3
  8. package/dist/{src → plugins}/dsh/budget.js +1 -1
  9. package/dist/{src → plugins}/dsh/engine.d.ts +1 -1
  10. package/dist/{src → plugins}/dsh/engine.js +1 -1
  11. package/dist/{src → plugins}/dsh/history.d.ts +1 -1
  12. package/dist/{src → plugins}/dsh/history.js +1 -1
  13. package/dist/{src → plugins}/dsh/index.js +1 -1
  14. package/dist/{src → plugins}/dsh/tools.js +3 -3
  15. package/dist/{src → plugins}/dsh/window.d.ts +1 -1
  16. package/dist/{src → plugins}/dsh/window.js +5 -5
  17. package/dist/{src → plugins}/pi/boot.d.ts +1 -1
  18. package/dist/{src → plugins}/pi/boot.js +5 -4
  19. package/dist/{src → plugins}/pi/budget.js +4 -4
  20. package/dist/{src → plugins}/pi/dream/cli.d.ts +1 -1
  21. package/dist/{src → plugins}/pi/dream/cli.js +6 -6
  22. package/dist/{src → plugins}/pi/dream/runner.d.ts +1 -1
  23. package/dist/{src → plugins}/pi/dream/runner.js +3 -3
  24. package/dist/{src → plugins}/pi/dream/settings.d.ts +1 -1
  25. package/dist/{src → plugins}/pi/dream/settings.js +2 -2
  26. package/dist/{src → plugins}/pi/history-tools.js +1 -1
  27. package/dist/{src → plugins}/pi/history.d.ts +1 -1
  28. package/dist/{src → plugins}/pi/history.js +1 -1
  29. package/dist/plugins/pi/index.d.ts +1 -0
  30. package/dist/plugins/pi/index.js +1 -0
  31. package/dist/{src → plugins}/pi/notes/adapter.d.ts +1 -1
  32. package/dist/{src → plugins}/pi/notes/adapter.js +1 -1
  33. package/dist/{src → plugins}/pi/notes/tools.js +1 -1
  34. package/dist/{src → plugins}/pi/reset/artifacts.d.ts +1 -1
  35. package/dist/{src → plugins}/pi/reset/artifacts.js +1 -1
  36. package/dist/{src → plugins}/pi/reset/lifecycle.d.ts +1 -1
  37. package/dist/{src → plugins}/pi/reset/lifecycle.js +1 -1
  38. package/dist/{src → plugins}/pi/runtime.js +2 -2
  39. package/dist/plugins/pi/text.d.ts +23 -0
  40. package/dist/plugins/pi/text.js +30 -0
  41. package/dist/{src → plugins}/pi/thresholds.d.ts +1 -1
  42. package/dist/{src → plugins}/pi/thresholds.js +4 -4
  43. package/dist/{src → plugins}/pi/tool-result.d.ts +1 -1
  44. package/dist/{src → plugins}/pi/tool-result.js +1 -1
  45. package/dist/{src → plugins}/pi/window.d.ts +1 -1
  46. package/dist/src/boot/text.d.ts +4 -13
  47. package/dist/src/boot/text.js +1 -11
  48. package/dist/src/budget/policy.d.ts +2 -3
  49. package/dist/src/budget/policy.js +1 -1
  50. package/dist/src/budget/text.d.ts +1 -12
  51. package/dist/src/budget/text.js +2 -24
  52. package/dist/src/dream/settings.d.ts +1 -2
  53. package/dist/src/dream/settings.js +4 -2
  54. package/dist/src/index.d.ts +29 -1
  55. package/dist/src/index.js +26 -1
  56. package/dist/src/notes/address.d.ts +5 -4
  57. package/dist/src/notes/address.js +13 -7
  58. package/dist/src/notes/identity.js +3 -7
  59. package/dist/src/notes/paths.d.ts +4 -2
  60. package/dist/src/notes/paths.js +11 -6
  61. package/dist/src/notes/store.d.ts +4 -1
  62. package/dist/src/notes/store.js +66 -34
  63. package/dist/src/settings.d.ts +7 -16
  64. package/dist/src/settings.js +7 -10
  65. package/dist/src/tools/notes.d.ts +5 -5
  66. package/dist/src/tools/notes.js +5 -4
  67. package/dist/test/agent-loop.test.js +5 -4
  68. package/dist/test/boot.integration.test.js +5 -5
  69. package/dist/test/budget-settings.integration.test.js +1 -1
  70. package/dist/test/claude-history.test.js +2 -2
  71. package/dist/test/claude-mod.test.js +12 -11
  72. package/dist/test/claude-validation.test.js +3 -3
  73. package/dist/test/dependencies.test.js +52 -44
  74. package/dist/test/doctor.test.js +1 -1
  75. package/dist/test/dream-skill.test.js +4 -4
  76. package/dist/test/dream.test.js +2 -2
  77. package/dist/test/dsh-cli.test.js +2 -2
  78. package/dist/test/dsh-compaction-parity.test.js +1 -1
  79. package/dist/test/dsh.test.js +4 -4
  80. package/dist/test/helpers/dependency-graph.js +9 -7
  81. package/dist/test/helpers/dsh.d.ts +1 -1
  82. package/dist/test/helpers/dsh.js +2 -2
  83. package/dist/test/helpers/extension.js +6 -5
  84. package/dist/test/helpers/notes.js +1 -1
  85. package/dist/test/model-facing-text.test.js +4 -2
  86. package/dist/test/notes-query-homes.test.d.ts +1 -0
  87. package/dist/test/notes-query-homes.test.js +161 -0
  88. package/dist/test/notes.integration.test.js +3 -2
  89. package/dist/test/notes.test.js +1 -1
  90. package/dist/test/reset-lifecycle.test.js +8 -7
  91. package/docs/architecture.md +21 -18
  92. package/docs/claude-code-mod.md +3 -3
  93. package/docs/dsh.md +1 -1
  94. package/docs/dsh.profile.patch.yml +1 -1
  95. package/docs/notes-library.md +17 -10
  96. package/docs/reset-lifecycle.md +1 -1
  97. package/docs/sdk-integration.md +2 -2
  98. package/package.json +17 -13
  99. package/{mods/notesoup → plugins/claude}/.claude-plugin/plugin.json +1 -1
  100. package/{mods/notesoup → plugins/claude}/dist/claude/helper.js +565 -540
  101. package/{mods/notesoup → plugins/claude}/skills/memory/SKILL.md +3 -0
  102. package/{src/claude → plugins/claude/src}/helper.ts +10 -9
  103. package/{src/claude → plugins/claude/src}/history.ts +1 -1
  104. package/plugins/claude/src/text.ts +10 -0
  105. package/{src/claude → plugins/claude/src}/thresholds.ts +3 -3
  106. package/{src → plugins}/dsh/budget.ts +1 -1
  107. package/{src → plugins}/dsh/engine.ts +1 -1
  108. package/{src → plugins}/dsh/history.ts +1 -1
  109. package/{src → plugins}/dsh/index.ts +1 -1
  110. package/{src → plugins}/dsh/tools.ts +3 -3
  111. package/{src → plugins}/dsh/window.ts +5 -5
  112. package/{src → plugins}/pi/boot.ts +5 -4
  113. package/{src → plugins}/pi/budget.ts +4 -4
  114. package/{src → plugins}/pi/dream/cli.ts +8 -8
  115. package/{src → plugins}/pi/dream/runner.ts +4 -4
  116. package/{src → plugins}/pi/dream/settings.ts +2 -2
  117. package/{src → plugins}/pi/history-tools.ts +1 -1
  118. package/{src → plugins}/pi/history.ts +1 -1
  119. package/plugins/pi/index.ts +1 -0
  120. package/{src → plugins}/pi/notes/adapter.ts +1 -1
  121. package/{src → plugins}/pi/notes/tools.ts +2 -2
  122. package/{src → plugins}/pi/reset/artifacts.ts +1 -1
  123. package/{src → plugins}/pi/reset/lifecycle.ts +2 -2
  124. package/{src → plugins}/pi/runtime.ts +2 -2
  125. package/plugins/pi/text.ts +35 -0
  126. package/{src → plugins}/pi/thresholds.ts +4 -4
  127. package/{src → plugins}/pi/tool-result.ts +1 -1
  128. package/{src → plugins}/pi/window.ts +1 -1
  129. package/skills/memory/SKILL.md +3 -0
  130. package/src/boot/text.ts +5 -15
  131. package/src/budget/policy.ts +3 -3
  132. package/src/budget/text.ts +2 -30
  133. package/src/dream/settings.ts +6 -3
  134. package/src/index.ts +52 -1
  135. package/src/notes/address.ts +12 -8
  136. package/src/notes/identity.ts +2 -8
  137. package/src/notes/paths.ts +12 -6
  138. package/src/notes/store.ts +62 -29
  139. package/src/settings.ts +8 -24
  140. package/src/tools/notes.ts +5 -4
  141. /package/dist/{src/claude → plugins/claude/src}/helper.d.ts +0 -0
  142. /package/dist/{src/claude → plugins/claude/src}/thresholds.d.ts +0 -0
  143. /package/dist/{src → plugins}/dsh/budget.d.ts +0 -0
  144. /package/dist/{src → plugins}/dsh/index.d.ts +0 -0
  145. /package/dist/{src → plugins}/dsh/tools.d.ts +0 -0
  146. /package/dist/{src → plugins}/pi/anchored.d.ts +0 -0
  147. /package/dist/{src → plugins}/pi/anchored.js +0 -0
  148. /package/dist/{src → plugins}/pi/budget.d.ts +0 -0
  149. /package/dist/{src → plugins}/pi/entries.d.ts +0 -0
  150. /package/dist/{src → plugins}/pi/entries.js +0 -0
  151. /package/dist/{src → plugins}/pi/estimate.d.ts +0 -0
  152. /package/dist/{src → plugins}/pi/estimate.js +0 -0
  153. /package/dist/{src → plugins}/pi/extension.d.ts +0 -0
  154. /package/dist/{src → plugins}/pi/extension.js +0 -0
  155. /package/dist/{src → plugins}/pi/history-tools.d.ts +0 -0
  156. /package/dist/{src → plugins}/pi/notes/tools.d.ts +0 -0
  157. /package/dist/{src → plugins}/pi/reset/committed.d.ts +0 -0
  158. /package/dist/{src → plugins}/pi/reset/committed.js +0 -0
  159. /package/dist/{src → plugins}/pi/runtime.d.ts +0 -0
  160. /package/dist/{src → plugins}/pi/session-reader.d.ts +0 -0
  161. /package/dist/{src → plugins}/pi/session-reader.js +0 -0
  162. /package/dist/{src → plugins}/pi/window.js +0 -0
  163. /package/{mods/notesoup → plugins/claude}/hooks/hooks.json +0 -0
  164. /package/{mods/notesoup → plugins/claude}/hooks/register.ts +0 -0
  165. /package/{mods/notesoup → plugins/claude}/playbook.md +0 -0
  166. /package/{mods/notesoup → plugins/claude}/skills/dream/SKILL.md +0 -0
  167. /package/{src → plugins}/pi/anchored.ts +0 -0
  168. /package/{src → plugins}/pi/entries.ts +0 -0
  169. /package/{src → plugins}/pi/estimate.ts +0 -0
  170. /package/{src → plugins}/pi/extension.ts +0 -0
  171. /package/{src → plugins}/pi/reset/committed.ts +0 -0
  172. /package/{src → plugins}/pi/session-reader.ts +0 -0
@@ -1,15 +1,16 @@
1
- import { notesIdentityFromPi } from "../../src/pi/notes/adapter.js";
2
- import { DEFAULT_BOOT_TOOL_NAMES, PI_PRE_RESET_HINTS, WINDOW_IDENTITY_CLOSE_TAG } from "../../src/boot/text.js";
1
+ import { notesIdentityFromPi } from "../../plugins/pi/notes/adapter.js";
2
+ import { DEFAULT_BOOT_TOOL_NAMES, WINDOW_IDENTITY_CLOSE_TAG } from "../../src/boot/text.js";
3
+ import { PI_PRE_RESET_HINTS } from "../../plugins/pi/text.js";
3
4
  import assert from "node:assert/strict";
4
5
  import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
5
6
  import { tmpdir } from "node:os";
6
7
  import { dirname, join } from "node:path";
7
8
  import { SessionManager, SettingsManager, } from "@earendil-works/pi-coding-agent";
8
- import notesoup, { createNotesoup } from "../../src/pi/extension.js";
9
+ import notesoup, { createNotesoup } from "../../plugins/pi/extension.js";
9
10
  import { loadNotesSnapshot } from "../../src/boot/snapshot.js";
10
11
  import { renderBootBlock } from "../../src/boot/render.js";
11
- import { agentSlug, modelSlug } from "../../src/pi/notes/adapter.js";
12
- import { rootWindowId } from "../../src/pi/window.js";
12
+ import { agentSlug, modelSlug } from "../../plugins/pi/notes/adapter.js";
13
+ import { rootWindowId } from "../../plugins/pi/window.js";
13
14
  import { TOOL_OUTPUT_MAX_BYTES } from "../../src/tools/output.js";
14
15
  import { structuredBytes } from "../../src/tools/result.js";
15
16
  let defaultCwd = "/private/tmp/notesoup-test-cwd";
@@ -1,5 +1,5 @@
1
1
  import { createNotesStore } from "../../src/notes/index.js";
2
- import { notesIdentityFromPi } from "../../src/pi/notes/adapter.js";
2
+ import { notesIdentityFromPi } from "../../plugins/pi/notes/adapter.js";
3
3
  import { physicalPath as corePhysicalPath, scopeDir as coreScopeDir } from "../../src/notes/paths.js";
4
4
  /** Test-only conveniences for fixtures that still model notes through a live Pi context. */
5
5
  export function physicalPath(scope, path, ctx, who) {
@@ -4,8 +4,10 @@ import { join } from "node:path";
4
4
  import { tmpdir } from "node:os";
5
5
  import { renderBootBlock } from "../src/boot/render.js";
6
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";
7
+ import { DEFAULT_BOOT_TOOL_NAMES, MAPS_BLOCK, NOTES_PROTOCOL_CLOSE_TAG, NOTES_PROTOCOL_OPEN_TAG, WINDOW_IDENTITY_CLOSE_TAG, WINDOW_IDENTITY_OPEN_TAG, renderProtocolBlock } from "../src/boot/text.js";
8
+ import { CLAUDE_WARNING_PROMPT, CLAUDE_WIPE_SENTENCE } from "../plugins/claude/src/text.js";
9
+ import { PI_PRE_RESET_HINTS, LAST_WORD_HINT, warningContent } from "../plugins/pi/text.js";
10
+ import { COUNTDOWN_LINE, FORCED_CONTINUATIONS, GUIDANCE_CLOSE_TAG, GUIDANCE_OPEN_TAG, NORMAL_CONTINUATIONS, WARNING_BODY, selectContinuation, tokenBudgetGuidance } from "../src/budget/text.js";
9
11
  /**
10
12
  * The reviewed Design text is what the model actually reads, so the golden copies below pin it
11
13
  * character for character: an edit that drifts the wording has to change them too.
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,161 @@
1
+ import assert from "node:assert/strict";
2
+ import { chmodSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
3
+ import { tmpdir } from "node:os";
4
+ import { join } from "node:path";
5
+ import test from "node:test";
6
+ import { createNotesStore, noteIdentity, NoteError } from "../src/notes/index.js";
7
+ import { scopeDir } from "../src/notes/paths.js";
8
+ function fixture(t) {
9
+ const home = mkdtempSync(join(tmpdir(), "notes-query-homes-"));
10
+ t.after(() => rmSync(home, { recursive: true, force: true }));
11
+ const identity = { home, sessionId: "DSH.Run_1+local", projectKey: "current-project", agent: "current-agent", model: "current-model" };
12
+ const foreignIdentity = { ...identity, sessionId: "DSH.Run_2+@remote", projectKey: "other-project", agent: "other-agent", model: "other-model" };
13
+ return { home, identity, foreignIdentity, notes: createNotesStore(identity), foreign: createNotesStore(foreignIdentity) };
14
+ }
15
+ function addresses(rows) {
16
+ return rows.map(row => row.address).sort();
17
+ }
18
+ async function populate(t) {
19
+ const fixtureData = fixture(t);
20
+ const { notes, foreign, foreignIdentity } = fixtureData;
21
+ const current = ["shared.md", "@project/shared.md", "@human/shared.md", "@self/shared.md", "@model/shared.md"].sort();
22
+ for (const address of current)
23
+ await notes.write(address, "needle in current home");
24
+ for (const address of ["shared.md", "@project/shared.md", "@self/shared.md", "@model/shared.md"])
25
+ await foreign.write(address, "needle in foreign home");
26
+ const all = [...current,
27
+ `@sessions/${foreignIdentity.sessionId}/shared.md`,
28
+ "@projects/other-project/shared.md", "@agents/other-agent/shared.md", "@models/other-model/shared.md",
29
+ ].sort();
30
+ return { ...fixtureData, current, all };
31
+ }
32
+ test("default spellings stay local while explicit ** lists and searches each home once", async (t) => {
33
+ const { notes, current, all, identity } = await populate(t);
34
+ assert.deepEqual(addresses(await notes.list()), current);
35
+ for (const glob of [null, "", "@default"]) {
36
+ assert.deepEqual(addresses(await notes.list({ glob })), current);
37
+ assert.deepEqual(addresses(await notes.search(["needle"], { glob })), current);
38
+ }
39
+ const rows = await notes.list({ glob: "**" });
40
+ assert.deepEqual(addresses(rows), all);
41
+ assert.deepEqual(addresses(await notes.search(["needle"], { glob: "**" })), all);
42
+ assert.equal(new Set(rows.map(row => row.address)).size, rows.length);
43
+ for (const row of rows)
44
+ assert.equal((await notes.read(row.address))?.body.startsWith("needle"), true, "every result is a real readable address");
45
+ assert.deepEqual(await notes.list({ glob: "@default/**" }), [], "@default is a bare selector, not an address prefix");
46
+ assert.deepEqual(addresses(await notes.list({ glob: "@project/**" })), ["@project/shared.md"]);
47
+ assert.deepEqual(addresses(await notes.list({ glob: "@self/**" })), ["@self/shared.md"]);
48
+ assert.deepEqual(addresses(await notes.list({ glob: "@model/**" })), ["@model/shared.md"]);
49
+ assert.deepEqual(addresses(await notes.list({ glob: `@projects/${identity.projectKey}/**` })), [`@projects/${identity.projectKey}/shared.md`], "explicit current project stays a named read-only address");
50
+ });
51
+ test("explicit patterns use canonical addresses, with bare-path matching only for the current session", async (t) => {
52
+ const { notes, identity, foreignIdentity, foreign, all } = await populate(t);
53
+ await notes.write("deep/nested.md", "needle nested");
54
+ await foreign.write("deep/nested.md", "needle elsewhere");
55
+ await foreign.write("only-foreign.md", "needle foreign only");
56
+ assert.deepEqual(addresses(await notes.list({ glob: "*.md" })), ["shared.md"]);
57
+ assert.deepEqual(addresses(await notes.list({ glob: "deep/**" })), ["deep/nested.md"]);
58
+ assert.deepEqual(await notes.search(["needle"], { glob: "only-foreign.md" }), [], "foreign sessions get no implicit basename alias");
59
+ assert.deepEqual(addresses(await notes.list({ glob: "**/shared.md" })), all);
60
+ assert.deepEqual(addresses(await notes.list({ glob: "@*/**/shared.md" })), all, "a wildcard head is not mistaken for an unknown reserved head");
61
+ assert.deepEqual(addresses(await notes.list({ glob: `@sessions/${identity.sessionId}/**` })), [
62
+ `@sessions/${identity.sessionId}/deep/nested.md`, `@sessions/${identity.sessionId}/shared.md`,
63
+ ].sort(), "explicit session patterns return canonical addresses even for the current session");
64
+ assert.deepEqual(addresses(await notes.list({ glob: "@sessions/*/shared.md" })), [
65
+ `@sessions/${identity.sessionId}/shared.md`, `@sessions/${foreignIdentity.sessionId}/shared.md`,
66
+ ].sort());
67
+ });
68
+ test("named session reads leave bytes untouched and explicit session mutations refuse both endpoints", async (t) => {
69
+ const { identity, foreignIdentity, notes, foreign } = fixture(t);
70
+ await notes.write("local.md", "local body");
71
+ await foreign.write("foreign.md", "foreign body", { origin: "user" });
72
+ const foreignAddress = `@sessions/${foreignIdentity.sessionId}/foreign.md`;
73
+ const currentAddress = `@sessions/${identity.sessionId}/local.md`;
74
+ const foreignFile = join(scopeDir("session", foreignIdentity), "foreign.md");
75
+ const currentFile = join(scopeDir("session", identity), "local.md");
76
+ const beforeForeign = readFileSync(foreignFile, "utf8");
77
+ const beforeCurrent = readFileSync(currentFile, "utf8");
78
+ const read = (await notes.read(foreignAddress));
79
+ assert.equal(read.body, "foreign body");
80
+ assert.equal(read.meta.accessCount, 0);
81
+ assert.equal(read.meta.project, foreignIdentity.projectKey);
82
+ assert.equal(read.resolvedScope, "session");
83
+ assert.equal((await notes.read(currentAddress))?.body, "local body");
84
+ assert.deepEqual(noteIdentity(identity, foreignAddress), { address: foreignAddress });
85
+ assert.equal(await notes.read(`@sessions/${foreignIdentity.sessionId}/missing.md`), undefined);
86
+ const readOnly = (error) => error instanceof NoteError && error.code === "invalid_scope";
87
+ await assert.rejects(() => notes.write(foreignAddress, "overwritten"), readOnly);
88
+ await assert.rejects(() => notes.write(currentAddress, "overwritten"), readOnly);
89
+ await assert.rejects(() => notes.update(foreignAddress, undefined, { crumpled: true }), readOnly);
90
+ await assert.rejects(() => notes.rename(foreignAddress, "stolen.md"), readOnly);
91
+ await assert.rejects(() => notes.rename("local.md", currentAddress), readOnly);
92
+ await assert.rejects(() => notes.update("local.md", [{ oldText: "local", newText: "changed" }], { renameTo: foreignAddress }), readOnly);
93
+ assert.equal(readFileSync(foreignFile, "utf8"), beforeForeign);
94
+ assert.equal(readFileSync(currentFile, "utf8"), beforeCurrent);
95
+ assert.equal((await notes.read("local.md"))?.meta.accessCount, 1, "the bare current-session alias retains ordinary access accounting");
96
+ await assert.rejects(() => notes.read("@sessions/../escape.md"), (error) => error instanceof NoteError && error.code === "invalid_address");
97
+ await assert.rejects(() => notes.list({ glob: "@sessions/bad:id/**" }), readOnly);
98
+ assert.equal(readFileSync(foreignFile, "utf8"), beforeForeign);
99
+ });
100
+ test("named project reads and relative identity rendering survive global enumeration of unmarked homes", async (t) => {
101
+ const { home, identity, notes } = fixture(t);
102
+ const project = join(home, "project", "another-project");
103
+ mkdirSync(project, { recursive: true });
104
+ writeFileSync(join(project, ".project"), JSON.stringify({ id: "remote/project", path: "/workspace/another" }));
105
+ writeFileSync(join(project, "decision.md"), "needle project");
106
+ const legacy = join(home, "project", "legacy-project");
107
+ mkdirSync(legacy, { recursive: true });
108
+ writeFileSync(join(legacy, "legacy.md"), "needle legacy");
109
+ await notes.write("@self/agent.md", "needle agent");
110
+ await notes.write("@model/model.md", "needle model");
111
+ assert.deepEqual(addresses(await notes.list({ glob: "**" })), [
112
+ "@projects/another-project/decision.md", "@projects/legacy-project/legacy.md", "@self/agent.md", "@model/model.md",
113
+ ].sort());
114
+ const address = "@projects/another-project/decision.md";
115
+ const before = readFileSync(join(project, "decision.md"), "utf8");
116
+ assert.equal((await notes.read(address))?.body, "needle project");
117
+ assert.equal(readFileSync(join(project, "decision.md"), "utf8"), before);
118
+ assert.deepEqual(noteIdentity(identity, address), { address, project_root: "/workspace/another" });
119
+ assert.equal(noteIdentity(identity, `@agents/${identity.agent}/agent.md`).address, "@self/agent.md");
120
+ assert.equal(noteIdentity(identity, `@models/${identity.model}/model.md`).address, "@model/model.md");
121
+ await assert.rejects(() => notes.write(address, "no"), (error) => error instanceof NoteError && error.code === "invalid_scope");
122
+ });
123
+ test("global status isolates every failed namespace and reserved heads do not scan unrelated homes", async (t) => {
124
+ const { home, notes } = fixture(t);
125
+ await notes.write("@human/available.md", "needle");
126
+ mkdirSync(join(home, "pi"), { recursive: true });
127
+ for (const root of ["pi/session", "project", "agents", "models"])
128
+ writeFileSync(join(home, root), "not a directory");
129
+ const expected = { homesUnavailable: ["@sessions", "@projects", "@agents", "@models"] };
130
+ const listed = await notes.listWithStatus({ glob: "**" });
131
+ assert.deepEqual(addresses(listed.rows), ["@human/available.md"]);
132
+ assert.deepEqual(listed.status, expected);
133
+ assert.deepEqual((await notes.searchWithStatus(["needle"], { glob: "**" })).status, expected);
134
+ assert.deepEqual((await notes.listWithStatus({ glob: "@human/**" })).status.homesUnavailable, []);
135
+ await assert.rejects(() => notes.list({ glob: "**" }), (error) => error.code === "ENOTDIR");
136
+ });
137
+ test("global status reports failed enumerated homes individually and keeps readable siblings", async (t) => {
138
+ if (process.getuid?.() === 0 || process.platform === "win32")
139
+ return t.skip("chmod 000 does not refuse this user's reads");
140
+ const { notes, foreignIdentity, current, home, all } = await populate(t);
141
+ const failed = [scopeDir("session", foreignIdentity), scopeDir("project", foreignIdentity)];
142
+ for (const dir of failed)
143
+ chmodSync(dir, 0o000);
144
+ try {
145
+ const result = await notes.listWithStatus({ glob: "**" });
146
+ const unavailable = [`@sessions/${foreignIdentity.sessionId}`, "@projects/other-project"];
147
+ assert.deepEqual(result.status.homesUnavailable, unavailable);
148
+ assert.deepEqual(addresses(result.rows), all.filter(address => !unavailable.some(prefix => address.startsWith(`${prefix}/`))));
149
+ assert.deepEqual((await notes.searchWithStatus(["needle"], { glob: "**" })).status.homesUnavailable, unavailable);
150
+ assert.deepEqual(addresses(await notes.list()), current, "local defaults do not enumerate unreadable foreign homes");
151
+ // A namespace scan must not read project marker files or let one bad marker abort its siblings.
152
+ chmodSync(failed[1], 0o755);
153
+ writeFileSync(join(home, "project/other-project/.project"), "{}");
154
+ chmodSync(join(home, "project/other-project/.project"), 0o000);
155
+ assert.deepEqual((await notes.listWithStatus({ glob: "@projects/*/**" })).status.homesUnavailable, []);
156
+ }
157
+ finally {
158
+ for (const dir of failed)
159
+ chmodSync(dir, 0o755);
160
+ }
161
+ });
@@ -1,4 +1,4 @@
1
- import { notesIdentityFromPi } from "../src/pi/notes/adapter.js";
1
+ import { notesIdentityFromPi } from "../plugins/pi/notes/adapter.js";
2
2
  import { DEFAULT_BOOT_TOOL_NAMES } from "../src/boot/text.js";
3
3
  import assert from "node:assert/strict";
4
4
  import { mkdirSync, rmSync, writeFileSync } from "node:fs";
@@ -6,7 +6,8 @@ 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, MAPS_BLOCK, NOTES_PROTOCOL_CLOSE_TAG, NOTES_PROTOCOL_OPEN_TAG, PI_PRE_RESET_HINTS } from "../src/boot/text.js";
9
+ import { MAP_BOOT_MAX_CHARS, MAPS_BLOCK, NOTES_PROTOCOL_CLOSE_TAG, NOTES_PROTOCOL_OPEN_TAG } from "../src/boot/text.js";
10
+ import { PI_PRE_RESET_HINTS } from "../plugins/pi/text.js";
10
11
  import { localIso } from "../src/notes/frontmatter.js";
11
12
  import { listNotes, physicalPath, scopeDir } from "./helpers/notes.js";
12
13
  import { MAX_READ_WINDOW_CHARS, TOOL_OUTPUT_MAX_BYTES } from "../src/tools/output.js";
@@ -17,7 +17,7 @@ import { createNotesStore, projectKey } from "../src/notes/index.js";
17
17
  import { globToRegExp } from "../src/notes/address.js";
18
18
  import { listNotes, physicalPath, scopeDir } from "./helpers/notes.js";
19
19
  import { notesList, notesSearch } from "../src/tools/notes.js";
20
- import { notesIdentityFromPi } from "../src/pi/notes/adapter.js";
20
+ import { notesIdentityFromPi } from "../plugins/pi/notes/adapter.js";
21
21
  import { call, context, explicitBoot, makeExtension, manager, resultData, resultError, resultRead } from "./helpers/extension.js";
22
22
  import { installExtensionTestHooks } from "./helpers/extension-test-environment.js";
23
23
  const testEnvironment = installExtensionTestHooks("notesoup-notes");
@@ -5,14 +5,15 @@ import { join } from "node:path";
5
5
  import test from "node:test";
6
6
  import { Check } from "typebox/value";
7
7
  import { SessionManager as Manager } from "@earendil-works/pi-coding-agent";
8
- import notesoup from "../src/pi/extension.js";
9
- import { BOOT_TYPE, CONTINUATION_TYPE, GUIDANCE_TYPE, RESET_LAST_WORD_TYPE, RESET_MARKER_TYPE } from "../src/pi/entries.js";
10
- import { MANUAL_WIPE_TYPE } from "../src/pi/entries.js";
8
+ import notesoup from "../plugins/pi/extension.js";
9
+ import { BOOT_TYPE, CONTINUATION_TYPE, GUIDANCE_TYPE, RESET_LAST_WORD_TYPE, RESET_MARKER_TYPE } from "../plugins/pi/entries.js";
10
+ import { MANUAL_WIPE_TYPE } from "../plugins/pi/entries.js";
11
11
  import { assertBootHistory, toolContext } from "./helpers/extension.js";
12
- import { COUNTDOWN_LINE, FORCED_CONTINUATIONS, LAST_WORD_HINT, NORMAL_CONTINUATIONS, WARNING_CALL_PROMPTED, warningContent } from "../src/budget/text.js";
13
- import { historyFromSession, nextHistorySeq } from "../src/pi/history.js";
14
- import { buildResetDrafts, LAST_WORD_PREFIX, MAX_LAST_WORD_CHARS, sanitizeLastWord } from "../src/pi/reset/artifacts.js";
15
- import { initialResetControl, reduceResetControl, registerResetLifecycle, } from "../src/pi/reset/lifecycle.js";
12
+ import { COUNTDOWN_LINE, FORCED_CONTINUATIONS, NORMAL_CONTINUATIONS } from "../src/budget/text.js";
13
+ import { LAST_WORD_HINT, WARNING_CALL_PROMPTED, warningContent } from "../plugins/pi/text.js";
14
+ import { historyFromSession, nextHistorySeq } from "../plugins/pi/history.js";
15
+ import { buildResetDrafts, LAST_WORD_PREFIX, MAX_LAST_WORD_CHARS, sanitizeLastWord } from "../plugins/pi/reset/artifacts.js";
16
+ import { initialResetControl, reduceResetControl, registerResetLifecycle, } from "../plugins/pi/reset/lifecycle.js";
16
17
  const previousNotesHome = process.env.PI_NOTES_HOME;
17
18
  const testNotesHome = mkdtempSync(join(tmpdir(), "notesoup-lifecycle-notes-"));
18
19
  process.env.PI_NOTES_HOME = testNotesHome;
@@ -6,7 +6,9 @@ notesoup uses Pi's session branch as the durable source of truth. It does not ma
6
6
 
7
7
  | Module | Responsibility | Boundary |
8
8
  | --- | --- | --- |
9
- | `index.ts` | Minimal re-export of the Pi extension and `createNotesoup` | Host entry only; shared domains cannot import it |
9
+ | `index.ts` | The curated host-neutral core surface: the notes library, the boot snapshot/renderer and bindings, the shared operations, and the budget prose | Host entry only; the core never imports a plugin |
10
+ | `plugins/pi/index.ts` | The Pi plugin entry: default extension and `createNotesoup` | Pi only; composed from the domains |
11
+ | `plugins/claude/src/` | Claude Code helper, persisted-transcript decoding and threshold derivation | Claude only; alongside the self-contained plugin in `plugins/claude/` |
10
12
  | `notes/identity.ts`, `notes/store.ts`, `notes/address.ts`, `notes/paths.ts` | Explicit `NotesIdentity`, filesystem homes, metadata, addressing and mutations | Node filesystem, no SDK or host environment identity |
11
13
  | `boot/snapshot.ts` | Load each of the closed five homes once; isolate filesystem errno failures | Explicit identity, captured time and optional scope loader |
12
14
  | `boot/render.ts`, `boot/text.ts` | Render identity, protocol, maps and recent-note metadata | Explicit snapshot and logical tool-name bindings; no I/O or clock |
@@ -14,38 +16,39 @@ notesoup uses Pi's session branch as the durable source of truth. It does not ma
14
16
  | `history/query.ts` | Bounded paging, `from` selection, literal matching, folding and preview rendering | Query projection only; no native session traversal |
15
17
  | `budget/constants.ts`, `budget/policy.ts`, `budget/text.ts` | Pure thresholds, unknown/clamped countdown and reminder text | Values supplied by the caller; no settings reads or scheduling |
16
18
  | `tools/notes.ts`, `tools/history.ts`, `tools/schema.ts`, `tools/result.ts`, `tools/output.ts` | Schema-derived outcomes, note/history operations, bounded result selection and pure text rendering | Explicit identity/projection; one bounded result feeds both text and structured output |
17
- | `settings.ts`, `dream/settings.ts` | Settings keys, per-key merge and dreamer validation | Parsed values only; no SDK or I/O |
19
+ | `settings.ts` | The `notesoup` settings key, the plain-object test and the per-key global/project merge | Raw records only; each host names and validates the fields it consumes |
20
+ | `dream/settings.ts` | Dreamer-pattern validation over the merged record | Parsed values only; no SDK or I/O |
18
21
  | `dream/` | Jail, crumpled-only physical deletion, locks, gates, Git audit, doctor, playbook and result/report logic | Independent filesystem/policy functions; no reverse import into Pi |
19
- | `dsh/` | Cordis registration, frozen prompt sections, plugin records/checkpoint recovery, token-meter budget, native reset transaction and session-query decoding | Host adapter; imports shared domains, never Pi or Claude |
20
- | `pi/extension.ts`, `pi/runtime.ts` | Compose registration, lifecycle hooks, commands, provider operations and UI | Public Pi SDK |
21
- | `pi/entries.ts` | Persisted native custom-entry/message tags | Pi persistence vocabulary, not an omnibus protocol barrel |
22
- | `pi/window.ts`, `pi/session-reader.ts` | Native `WindowMarker`, checkpoint validation, root/fork identity, branch scans, provider projection and usage | Pi entries/messages and read-only native session traversal |
23
- | `pi/history.ts` | Decode native messages, allocate seqs from append order and select active-branch visibility | Native SessionEntry/AgentMessage decoding; feeds shared query projection |
24
- | `pi/notes/`, `pi/history-tools.ts`, `pi/tool-result.ts` | Extract live execution data, register output schemas, package outcomes and render native note diffs | Native API -> shared operations; no second query or pagination path |
25
- | `pi/thresholds.ts`, `pi/budget.ts` | Read settings/usage, cache policy per instance, stage prompts, warn and schedule native reset decisions | Public SettingsManager and native lifecycle |
26
- | `pi/reset/lifecycle.ts` | Native turn/settle reducer facts, batching, recovery and continuation | Public Pi lifecycle hooks and boundary drafts |
27
- | `pi/reset/artifacts.ts`, `pi/reset/committed.ts` | Construct boundaries, repair only safe suffixes, independently confirm committed native boundaries | Active native branch; no shadow commit database |
28
- | `pi/dream/` | Pi dream sessions, native tool wrappers, settings reads and executable CLI composition | Pi backend over independent dream policy/filesystem functions |
22
+ | `plugins/dsh/` | Cordis registration, frozen prompt sections, plugin records/checkpoint recovery, token-meter budget, native reset transaction and session-query decoding | Host adapter; imports shared domains, never Pi or Claude |
23
+ | `plugins/pi/extension.ts`, `plugins/pi/runtime.ts` | Compose registration, lifecycle hooks, commands, provider operations and UI | Public Pi SDK |
24
+ | `plugins/pi/entries.ts` | Persisted native custom-entry/message tags | Pi persistence vocabulary, not an omnibus protocol barrel |
25
+ | `plugins/pi/window.ts`, `plugins/pi/session-reader.ts` | Native `WindowMarker`, checkpoint validation, root/fork identity, branch scans, provider projection and usage | Pi entries/messages and read-only native session traversal |
26
+ | `plugins/pi/history.ts` | Decode native messages, allocate seqs from append order and select active-branch visibility | Native SessionEntry/AgentMessage decoding; feeds shared query projection |
27
+ | `plugins/pi/notes/`, `plugins/pi/history-tools.ts`, `plugins/pi/tool-result.ts` | Extract live execution data, register output schemas, package outcomes and render native note diffs | Native API -> shared operations; no second query or pagination path |
28
+ | `plugins/pi/thresholds.ts`, `plugins/pi/budget.ts` | Read settings/usage, cache policy per instance, stage prompts, warn and schedule native reset decisions | Public SettingsManager and native lifecycle |
29
+ | `plugins/pi/reset/lifecycle.ts` | Native turn/settle reducer facts, batching, recovery and continuation | Public Pi lifecycle hooks and boundary drafts |
30
+ | `plugins/pi/reset/artifacts.ts`, `plugins/pi/reset/committed.ts` | Construct boundaries, repair only safe suffixes, independently confirm committed native boundaries | Active native branch; no shadow commit database |
31
+ | `plugins/pi/dream/` | Pi dream sessions, native tool wrappers, settings reads and executable CLI composition | Pi backend over independent dream policy/filesystem functions |
29
32
 
30
- Dependencies flow from host composition into the domains, never back. Shared code cannot import an SDK, `src/pi`, `src/claude`, `src/dsh`, or the root entry, even through erased types, re-exports, literal dynamic/import-type edges or intermediate modules. `test/dependencies.test.ts` uses TypeScript resolution and AST traversal, checks every shared source (including root settings/text matching; excludes the three host adapters), and tests rejecting indirect/aliased paths. Shared external packages must be declared in the package manifest. `typebox` is declared as a peer and development dependency rather than imported through Pi's SDK.
33
+ Dependencies flow from a plugin into the core, never back. Core code under `src/` cannot import an SDK or anything under `plugins/`, and a plugin cannot import another plugin's modules or a foreign host SDK; a plugin reaches note storage only through `src/notes/index.ts`. Each plugin owns its host's words: the Pi-only pre-reset hints, the `last_word` nudge and the `/empty <prompt>` close-out live in `plugins/pi/text.ts`, and the Claude wipe, missing-history and warning prose in `plugins/claude/src/text.ts`. `test/dependencies.test.ts` uses TypeScript resolution and AST traversal over every core source and each plugin tree, and tests rejecting indirect, aliased, dynamic and import-type edges. Shared external packages must be declared in the package manifest. `typebox` is declared as a peer and development dependency rather than imported through Pi's SDK.
31
34
 
32
- The configured extension is `src/index.ts`, loaded straight from TypeScript — no bundling step, so git installs work without a build. Its `pi-ai/utils/estimate` dependency is vendored in `src/pi/estimate.ts` because Pi's root-package aliases misresolve that public subpath on source loads; host-owned SDK APIs stay external. `/notes` is the intentional standalone library API. The CLI is `dist/src/pi/dream/cli.js`. Old internal bags, `NotesContext`, root history helpers and the deep-entry export alias are removed. This breaks source/import paths, not storage: note homes, metadata, session paths and raw history remain intact. There is no universal Harness, host-event emulator, registry, daemon or speculative second backend. No `src/window` exists because the current window responsibilities are genuinely native.
35
+ The configured extension is `plugins/pi/index.ts`, loaded straight from TypeScript — no bundling step, so git installs work without a build. Its `pi-ai/utils/estimate` dependency is vendored in `plugins/pi/estimate.ts` because Pi's root-package aliases misresolve that public subpath on source loads; host-owned SDK APIs stay external. The package root `.` exports the host-neutral core, `./pi` the Pi plugin, `/notes` the standalone library, and `./dsh` plus `./dsh/engine` the Cordis rows. The CLI is `dist/plugins/pi/dream/cli.js`, and the Claude Code plugin is the self-contained `plugins/claude/` directory. Old internal bags, `NotesContext`, root history helpers and the deep-entry export alias are removed. This breaks source/import paths, not storage: the on-disk notes layout is unchanged and host-independent — `pi/session/<sessionId>/` is a historical directory name every host still writes to, not a Pi adapter choice, and nothing migrates it. Note homes, metadata, session paths and raw history remain intact. There is no universal Harness, host-event emulator, registry, daemon or speculative second backend. No `src/window` exists because the current window responsibilities are genuinely native.
33
36
 
34
37
  For the native dsh reset transaction, prompt ordering, capability checks and limits, see [DeepSeek Harness](dsh.md). Its adapter keeps the shared domains unchanged and uses only dsh public services.
35
38
 
36
39
  ## State and persistence
37
40
 
38
- `pi/reset/lifecycle.ts` is the sole `turn_end` composer: it accepts incoming drafts, drains budget-owned guidance/warning drafts, and appends a reset boundary for an explicit tool request or the hard-reserve safety path. Manual and budget close-outs stay armed across note/tool turns and commit from `agent_before_settle` after a successful stop with queued work drained; a manual close-out stops the run while a budget close-out continues in the fresh window. Repeated requests for the same window deduplicate. See [reset lifecycle](reset-lifecycle.md).
41
+ `plugins/pi/reset/lifecycle.ts` is the sole `turn_end` composer: it accepts incoming drafts, drains budget-owned guidance/warning drafts, and appends a reset boundary for an explicit tool request or the hard-reserve safety path. Manual and budget close-outs stay armed across note/tool turns and commit from `agent_before_settle` after a successful stop with queued work drained; a manual close-out stops the run while a budget close-out continues in the fresh window. Repeated requests for the same window deduplicate. See [reset lifecycle](reset-lifecycle.md).
39
42
 
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, origin: "normal" | "forced" }`, 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.
43
+ 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, origin: "normal" | "forced" }`, 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. `plugins/pi/window.ts` owns marker/checkpoint validation, active-branch scan, root/current IDs, and per-window message lookup; `plugins/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
44
 
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.
45
+ The runtime in `plugins/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
46
 
44
47
  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
48
 
46
49
  Manual `/fresh-window` stores command settlement policy and sends a hidden warning: idle commands start a model turn, running commands steer it. Tool requests are recorded independently and retained under that policy. A bare command settles and stops; a command with text settles and continues, with its text supplied only to the closing window. Budget warnings create no reset state: only an explicit tool request, hard reserve or bounded overflow recovery triggers a reset. Abort and ordinary errors do not count as successful settlement. Hard reserve preserves a bare command's stop in a run-scoped latch; `context_with_system` cancels only an empty tool-batch follow-up after confirming the committed boundary. Queued user input is answered before stopping. See [reset lifecycle](reset-lifecycle.md) for the state and recovery rules.
47
50
 
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 a brain-cleared notice 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`.
51
+ 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 a brain-cleared notice 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. `plugins/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
52
 
50
53
  The Pi history adapter decodes the selected raw session branch on demand without a cache. It allocates stable seq values from the session's append-order entry list, then selects current-branch-only visibility, so navigation cannot expose a sibling's history. Shared history pairs and queries those decoded events; it neither traverses SessionReader nor reconstructs inference messages. The public stream combines each tool call with its result at the call seq; paired result slots are not public event addresses, and unpaired results retain their own seq. Summaries and injected messages project as `context`. List pages chronologically with seq anchors and an explicit `from`. Tool executions retain structured call/result facts and any native nested-call metadata. A deterministic event document supplies both query-match positions and read windows. Nested calls have no independent seq and never imply that unrecorded child outputs are available.
51
54
 
@@ -1,8 +1,8 @@
1
1
  # Claude Code Mod
2
2
 
3
- The package also ships `mods/notesoup`, an early-access Claude Code Mod that registers five notes tools as `mcp__notesoup__notes_*` and three history tools as `mcp__notesoup__history_*` and attaches one host-scoped notes boot block through Claude's conversation-scoped `prompt.context` event; Claude persists it across resume and reload. The sandboxed hooks module delegates filesystem and shared-domain work to the plugin-local `mods/notesoup/dist/claude/helper.js` through Claude's bounded `$.process.run` capability.
3
+ The package also ships `plugins/claude/`, an early-access Claude Code Mod that registers five notes tools as `mcp__notesoup__notes_*` and three history tools as `mcp__notesoup__history_*` and attaches one host-scoped notes boot block through Claude's conversation-scoped `prompt.context` event; Claude persists it across resume and reload. The sandboxed hooks module delegates filesystem and shared-domain work to the plugin-local `plugins/claude/dist/claude/helper.js` through Claude's bounded `$.process.run` capability.
4
4
 
5
- In interactive sessions it resets automatically when the measured context reaches notesoup's reset point, checking after `session.measure` and `turn.complete` and waiting for a running turn to complete. That point is derived from Claude's own auto-compact threshold instead of a fixed percent, in `src/claude/thresholds.ts`, and reaches the sandboxed hooks module through the helper's `limits` operation:
5
+ In interactive sessions it resets automatically when the measured context reaches notesoup's reset point, checking after `session.measure` and `turn.complete` and waiting for a running turn to complete. That point is derived from Claude's own auto-compact threshold instead of a fixed percent, in `plugins/claude/src/thresholds.ts`, and reaches the sandboxed hooks module through the helper's `limits` operation:
6
6
 
7
7
  1. `$.session.usage({breakdown:"summary"}).context.autoCompactThreshold` when it is a positive number, with `CLAUDE_AUTOCOMPACT_PCT_OVERRIDE` applied the way Claude applies it (it can only lower the point);
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;
@@ -28,4 +28,4 @@ The selected tree follows the latest native `parentUuid` links. Compact boundari
28
28
 
29
29
  ## Validation
30
30
 
31
- `npm run typecheck` includes the mod against the vendored Claude Code 2.1.295 contract. `npm test` also typechecks it and runs `claude plugin validate mods/notesoup --strict`, skipping validation with a clear message only if `claude` is not installed. Scanner regression tests deliberately reintroduce each of the three forbidden call shapes and require the gate to fail. From a built checkout, check the real load with `claude --plugin-dir mods/notesoup -p "ok"`; a model/API failure after load is separate from a hooks-module refusal. The package build and `npm pack --dry-run` include the manifests, hooks module, helper, skills, and playbook.
31
+ `npm run typecheck` includes the mod against the vendored Claude Code 2.1.295 contract. `npm test` also typechecks it and runs `claude plugin validate plugins/claude --strict`, skipping validation with a clear message only if `claude` is not installed. Scanner regression tests deliberately reintroduce each of the three forbidden call shapes and require the gate to fail. From a built checkout, check the real load with `claude --plugin-dir plugins/claude -p "ok"`; a model/API failure after load is separate from a hooks-module refusal. The package build and `npm pack --dry-run` include the manifests, hooks module, helper, skills, and playbook.
package/docs/dsh.md CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
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 `empty_brain`. 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
- 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.
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/plugins/dsh/engine.js` and `file:///.../dist/plugins/dsh/index.js` module names. The example shows all rows for a profile assembled without the package bundle.
6
6
 
7
7
  Declare explicit `models` for `llm-deepseek`, with `contextWindow` and `maxTokens` appropriate to your provider. The shipped `deepseek-flash` declaration uses `systemPromptUpdate: in-history`; changing the boot under that route can leave an earlier system prompt in the leading slot. The example uses **200000 context tokens and 8192 output tokens**. Those numbers are test inputs, not a promise about your provider's capacity.
8
8
 
@@ -1,6 +1,6 @@
1
1
  # Add to $DSH_HOME/profiles/<profile>/cordis.patch.yml after installing notesoup.
2
2
  # For a source checkout, run npm ci --ignore-scripts && npm run build, then replace
3
- # notesoup/dsh[/engine] below with absolute file:///.../dist/src/dsh/...js paths.
3
+ # notesoup/dsh[/engine] below with absolute file:///.../dist/plugins/dsh/...js paths.
4
4
  - id: compaction-basic
5
5
  disabled: true
6
6
 
@@ -26,32 +26,32 @@ const files = await notes.list({ glob: "@project/**" });
26
26
  const matches = await notes.search(["library"]);
27
27
  ```
28
28
 
29
- `/notes` ships JavaScript and TypeScript declarations. It does not import Pi or read `PI_*` environment variables. Pi packages are optional peers: a notes-only installation does not install them. Using the plugin, root SDK entry, or `dream` CLI still requires Pi. This is a filesystem library for Node, not a browser storage API.
29
+ `/notes` ships JavaScript and TypeScript declarations. It does not import Pi or read `PI_*` environment variables. Pi packages are optional peers: a notes-only installation does not install them. Using the Pi plugin (`notesoup/pi`), the dsh rows (`notesoup/dsh`), or the `dream` CLI still requires its host. This is a filesystem library for Node, not a browser storage API.
30
30
 
31
31
  ## API and identity
32
32
 
33
33
  `createNotesStore(identity)` snapshots the five required identity fields; changing the supplied object afterward does not retarget the store. It resolves `home` once, validates identity components, and creates no files until an operation needs to write. Create a new store to change identity. Multiple stores can use independent roots and identities without changing process environment.
34
34
 
35
35
  - `write(address, content, { origin? }?)` returns `Promise<{ meta, outcome }>` (`created`, `overwritten` or `uncrumpled`). New notes default to origin `self`; overwriting preserves the existing origin unless explicitly supplied, creation time, project ownership, and unknown metadata, and always produces an uncrumpled note (it clears any `crumpledAt`).
36
- - `read(address)` returns `Promise<{ meta, body, resolvedScope } | undefined>`. **Reads update** `lastAccessed` and `accessCount` on disk. The body is separate from metadata; the serialized frontmatter is not part of the read API.
37
- - `update(address, edits?, { origin?, crumpled?, replaceAll?, renameTo? }?)` returns `Promise<{ meta, applied, resolvedScope, change, moved, replacedCrumpledTarget }>`. Body edits, origin, crumpled state and a move can be combined. Every edit, destination and size check passes before saving; a live target refuses with `already_exists`, while a crumpled target can be replaced. Cross-session moves update project ownership. Each replacement uses the evolving body in array order. `crumpled: true` keeps an existing `crumpledAt` or adds it; false removes it; omitted preserves it. `updatedAt` advances for body/origin changes and actual moves, not crumpling alone. `change` contains `{ kind, before, after }`, with kind `body`, `metadata` or `none`; a body edit that also changes metadata or moves includes the whole serialized file in its diff inputs. Moves lock both paths in stable order, atomically write the destination, then remove the source; this is not a crash-atomic two-file transaction.
36
+ - `read(address)` returns `Promise<{ meta, body, resolvedScope } | undefined>`. Reads update `lastAccessed` and `accessCount` on disk, except explicit named project/session reads, which leave the file untouched. The body is separate from metadata; the serialized frontmatter is not part of the read API.
37
+ - `update(address, edits?, { origin?, crumpled?, replaceAll?, renameTo? }?)` returns `Promise<{ meta, applied, resolvedScope, change, moved, replacedCrumpledTarget }>`. Body edits, origin, crumpled state and a move can be combined. Every edit, destination and size check passes before saving; a live target refuses with `already_exists`, while a crumpled target can be replaced. Moves into or out of the current session home update project ownership; explicit named session addresses are read-only. Each replacement uses the evolving body in array order. `crumpled: true` keeps an existing `crumpledAt` or adds it; false removes it; omitted preserves it. `updatedAt` advances for body/origin changes and actual moves, not crumpling alone. `change` contains `{ kind, before, after }`, with kind `body`, `metadata` or `none`; a body edit that also changes metadata or moves includes the whole serialized file in its diff inputs. Moves lock both paths in stable order, atomically write the destination, then remove the source; this is not a crash-atomic two-file transaction.
38
38
  - `rename(fromAddress, toAddress)` returns `Promise<{ meta, replacedCrumpledTarget }>`. It delegates to the same update path with `renameTo`, preserving metadata. A same-file destination, including a case or symlink alias resolved by the filesystem, applies accompanying edits without removing the source. An exact path alias needs only one lock.
39
39
  - `list({ glob?, 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. Crumpled notes are excluded by default; `crumpled: true` returns only crumpled notes.
40
40
  - `search(queries: string[], { glob?, crumpled? }?)` returns `Promise<NoteSearchRow[]>`, sorted by address, with the same selection and crumpled-note rules. An empty queries array returns matching notes with empty `matches`. Otherwise search is case-insensitive literal OR over body lines; matches contain one-based `line`, `text`, and code-point `offsetChars` into the body. Neither listing nor search increments access metadata.
41
41
 
42
- `list` and `search` share `NotesQuery`: **glob is the only home/path selector**. Omit it for the five current homes; use `@project/**`, `@self/**`, or `@projects/<name>/**` to select a home. The former `scope`/`who` query parameters are removed, without compatibility aliases. Row metadata still includes scope.
42
+ `list` and `search` share `NotesQuery`: **glob is the only home/path selector**. Omit it or use the bare collection alias `@default` for the five current homes. Explicit `**` searches all homes, including other sessions, projects, agents and models; `@sessions/*/**` selects all session homes. Use `@project/**`, `@self/**`, or `@projects/<name>/**` to select a home. `@default` is query-only, not a directory or a read/write address; `@default/**` is not its spelling. The former `scope`/`who` query parameters are removed, without compatibility aliases. Row metadata still includes scope.
43
43
 
44
- The library returns full data, not tool envelopes or paginated/truncated output. `NoteError` exposes the existing named store refusals through `code`, with `lineNumbers` for ambiguous edits and `editIndex` for a failed edit. Runtime API fields and known persisted note metadata use camelCase; Pi tool wire fields such as `updated_at`, `offset_chars`, and `replace_all` retain their established names. Unrecognized frontmatter keys, including old snake_case metadata, are preserved as ordinary extras; they are not interpreted as current camelCase fields or migrated automatically. Invalid addresses/identities and filesystem failures reject; only a missing `read` returns `undefined`. Notes remain markdown files with the existing size limits and same-directory atomic rename. Same-file read/modify/write work is serialized by absolute physical filename across all store instances in this process (including `.md` address aliases); symlink/case aliases and cross-process locking are not guaranteed. `list` and `search` asynchronously traverse homes and serialize each discovered file read against pending mutations, but are not global snapshots and may not discover a file created after traversal. Foreign named homes can be read (including the access-metadata update), but their bodies cannot be written or edited through the store. These are cooperative address rules, not an OS security sandbox.
44
+ The library returns full data, not tool envelopes or paginated/truncated output. `NoteError` exposes the existing named store refusals through `code`, with `lineNumbers` for ambiguous edits and `editIndex` for a failed edit. Runtime API fields and known persisted note metadata use camelCase; Pi tool wire fields such as `updated_at`, `offset_chars`, and `replace_all` retain their established names. Unrecognized frontmatter keys, including old snake_case metadata, are preserved as ordinary extras; they are not interpreted as current camelCase fields or migrated automatically. Invalid addresses/identities and filesystem failures reject; only a missing `read` returns `undefined`. Notes remain markdown files with the existing size limits and same-directory atomic rename. Same-file read/modify/write work is serialized by absolute physical filename across all store instances in this process (including `.md` address aliases); symlink/case aliases and cross-process locking are not guaranteed. `list` and `search` asynchronously traverse homes and serialize each discovered file read against pending mutations, but are not global snapshots and may not discover a file created after traversal. Foreign named homes can be read, but their bodies cannot be written or edited through the store. Named project and session reads do not update access metadata. These are cooperative address rules, not an OS security sandbox.
45
45
 
46
- Addresses are a relative path (a session note), `@project/`, `@human/`, `@self/`, `@model/`, or explicit `@agents/<slug>/` and `@models/<slug>/`. Only the first character of an address is sigil-position: an unknown leading `@head` refuses, while `@` inside the path (`release@v1.md`, `@project/mail/alice@example.com.md`) is an ordinary character. Relative self/model addresses resolve to the supplied identity. Results show the current agent's and model's notes as `@self/` and `@model/`; only other agents' or models' notes carry an explicit `@agents/<slug>/` or `@models/<slug>/`. Globs accept either form. The disk layout remains `pi/session/<sessionId>/`, `project/<projectKey>/`, `human/`, `agents/<agent>/`, and `models/<model>/`. No data migration happens on library import or construction. Notes already using camelCase metadata retain their metadata; old snake_case keys are preserved as unrecognized extras, not interpreted or migrated. New session notes record the supplied project key.
46
+ Addresses are a relative path (a current-session note), `@project/`, `@human/`, `@self/`, `@model/`, or explicit `@projects/<slug>/`, `@sessions/<id>/`, `@agents/<slug>/` and `@models/<slug>/`. Named project and session addresses are read-only, including for rename sources and destinations. Session IDs use the same safe single-directory-component grammar as `NotesIdentity.sessionId`, not the agent/model slug grammar. Only the first character of an address is sigil-position: an unknown leading `@head` refuses, while `@` inside the path (`release@v1.md`, `@project/mail/alice@example.com.md`) is an ordinary character. Relative self/model addresses resolve to the supplied identity. Results show the current agent's and model's notes as `@self/` and `@model/`; only other agents' or models' notes carry an explicit `@agents/<slug>/` or `@models/<slug>/`. Globs accept either form. The disk layout remains `pi/session/<sessionId>/`, `project/<projectKey>/`, `human/`, `agents/<agent>/`, and `models/<model>/`. No data migration happens on library import or construction. Notes already using camelCase metadata retain their metadata; old snake_case keys are preserved as unrecognized extras, not interpreted or migrated. New session notes record the supplied project key.
47
47
 
48
48
  ## Library and plugin boundary
49
49
 
50
50
  Ownership is explicit in the file tree:
51
51
 
52
52
  ```text
53
- src/
54
- index.ts # only the Pi extension and createNotesoup factory
53
+ src/ # host-neutral core; never imports a plugin or an SDK
54
+ index.ts # curated core surface: notes, boot, operations, budget prose
55
55
  notes/ # filesystem semantics and explicit NotesIdentity
56
56
  boot/ # five-home snapshot and pure rendering with tool bindings
57
57
  history/ # decoded query projection, pairing, paging and folding
@@ -59,7 +59,8 @@ src/
59
59
  tools/ # operation schemas, typed outcomes and bounded presentation
60
60
  dream/ # jail, deletion policy, locks, gates, audit, reports, doctor
61
61
  settings.ts # SDK-independent settings keys and per-key parsing
62
- pi/ # native integration, not part of /notes
62
+ plugins/ # one directory per host; each owns its SDK and its words
63
+ pi/ # Pi plugin; index.ts is the extension entry
63
64
  extension.ts # registration composition
64
65
  runtime.ts # native lifecycle, commands, provider projection and UI
65
66
  window.ts # native markers, checkpoints, branches and usage
@@ -67,8 +68,14 @@ src/
67
68
  notes/ # live identity extraction, registration and native diffs
68
69
  reset/ # reducer, boundary drafts, commit confirmation and repair
69
70
  dream/ # Pi session backend, settings reads and CLI
71
+ text.ts # Pi-only pre-reset hints, last-word nudge, prompted close-out
72
+ claude/ # the self-contained Claude Code plugin (hooks, dist, skills)
73
+ src/ # helper, transcript decoding, threshold derivation, text
74
+ dsh/ # Cordis plugin rows (notesoup, notesoup-engine)
70
75
  ```
71
76
 
77
+ The disk layout is older than this split and is shared by every host: `pi/session/<sessionId>/` is a historical directory name, not the Pi adapter's private layout, and nothing here migrates or renames it.
78
+
72
79
  The public runtime exports are `createNotesStore`, `NoteError`, `projectKey(cwd)`, and `slugify(value)`, alongside the API's TypeScript types. The factory and `projectKey` remain synchronous; `projectKey` provides the existing repository/worktree identity algorithm, while `slugify` normalizes an agent/model name. The six primary store methods return promises and use asynchronous filesystem operations. Path/glob helpers, serialization, validation internals and constants are implementation details, not exported through `/notes`.
73
80
 
74
- The Pi adapter supplies the root and live session/project/agent/model identity on each call. Tools and boot use the same storage implementation. Shared tool schemas use `typebox`, declared as a peer supplied by Pi and as a dev dependency for standalone development; their handlers accept explicit identities or decoded history projections. Pi owns registration, execution-context extraction and native edit diff rendering. Boot snapshot acquisition receives identity, a captured timestamp and an optional home loader; rendering receives explicit logical tool names. Native session traversal, stable seq allocation, branch selection and inference projection stay in Pi. Shared history is a query view, never a way to reconstruct inference messages. There are no compatibility shims or generic host runtime. Internal source paths are not the supported library API.
81
+ The Pi plugin supplies the root and live session/project/agent/model identity on each call. Tools and boot use the same storage implementation. Shared tool schemas use `typebox`, declared as a peer supplied by Pi and as a dev dependency for standalone development; their handlers accept explicit identities or decoded history projections. Pi owns registration, execution-context extraction and native edit diff rendering. Boot snapshot acquisition receives identity, a captured timestamp and an optional home loader; rendering receives explicit logical tool names. Native session traversal, stable seq allocation, branch selection and inference projection stay in Pi. Shared history is a query view, never a way to reconstruct inference messages. There are no compatibility shims or generic host runtime. Internal source paths are not the supported library API.
@@ -1,6 +1,6 @@
1
1
  # Reset lifecycle
2
2
 
3
- All lifecycle control flow is native Pi integration. `src/pi/reset/lifecycle.ts` owns actual tool requests, command settlement policy, bounded overflow recovery and scheduling. `src/pi/budget.ts` reads usage/settings and stages reminders; `src/budget/policy.ts` derives thresholds. `src/pi/reset/artifacts.ts` constructs ordered drafts and repairs incomplete suffixes; `src/pi/reset/committed.ts` confirms durable boundaries. `src/pi/window.ts` owns markers and provider projection. `src/pi/runtime.ts` wires commands, tools and public Pi hooks.
3
+ All lifecycle control flow is native Pi integration. `plugins/pi/reset/lifecycle.ts` owns actual tool requests, command settlement policy, bounded overflow recovery and scheduling. `plugins/pi/budget.ts` reads usage/settings and stages reminders; `src/budget/policy.ts` derives thresholds. `plugins/pi/reset/artifacts.ts` constructs ordered drafts and repairs incomplete suffixes; `plugins/pi/reset/committed.ts` confirms durable boundaries. `plugins/pi/window.ts` owns markers and provider projection. `plugins/pi/runtime.ts` wires commands, tools and public Pi hooks.
4
4
 
5
5
  Boot acquisition/rendering is shared: `src/boot/snapshot.ts` receives explicit identity, a captured time and an optional scope loader; `src/boot/render.ts` receives the snapshot and logical tool bindings. Pi supplies its existing names. Shared history is an addressed query projection, never an inference transcript or reset scheduler. There is no generic HostEvent or Harness reducer, and no second commit database.
6
6
 
@@ -8,7 +8,7 @@ import {
8
8
  DefaultResourceLoader,
9
9
  SettingsManager,
10
10
  } from "@earendil-works/pi-coding-agent";
11
- import { createNotesoup } from "notesoup";
11
+ import { createNotesoup } from "notesoup/pi";
12
12
 
13
13
  const cwd = process.cwd();
14
14
  const agentDir = "/tmp/my-pi-agent";
@@ -32,7 +32,7 @@ const { session } = await createAgentSession({
32
32
  });
33
33
  ```
34
34
 
35
- The root entry exports only the default Pi extension and `createNotesoup`. This is a breaking source/API refactor: `NotesContext` is replaced by `NotesIdentity`; old internal export bags, root history helpers and the `./dist/src/index.js` export alias are removed. Import the root for Pi integration and `/notes` for the standalone library. The configured dream executable is now `dist/src/pi/dream/cli.js`. Stored notes, session paths, metadata and raw histories are unchanged; no migration runs.
35
+ The package root exports the host-neutral core (the notes library, the boot snapshot/renderer and bindings, the shared operations, and the budget prose); the Pi plugin entry is `notesoup/pi`, which exports the default Pi extension and `createNotesoup`. This is a breaking source/API refactor: `NotesContext` is replaced by `NotesIdentity`; old internal export bags, root history helpers and the `./dist/src/index.js` export alias are removed. Import `notesoup/pi` for Pi integration and `/notes` for the standalone library. The configured dream executable is now `dist/plugins/pi/dream/cli.js`. Stored notes, session paths, metadata and raw histories are unchanged; no migration runs.
36
36
 
37
37
  The manager must be shared by the resource loader's factory and `createAgentSession`. If the host replaces its settings authority, it must create and bind a new `createNotesoup({ settingsManager })` factory together with the replacement manager; an existing factory remains bound to the manager it was created with.
38
38