notesoup 0.53.2 → 0.54.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 (186) hide show
  1. package/README.md +6 -4
  2. package/dist/plugins/claude/src/helper.d.ts +2 -1
  3. package/dist/plugins/claude/src/helper.js +21 -24
  4. package/dist/plugins/claude/src/history.d.ts +3 -14
  5. package/dist/plugins/claude/src/history.js +2 -298
  6. package/dist/plugins/claude/src/text.d.ts +0 -1
  7. package/dist/plugins/claude/src/text.js +0 -1
  8. package/dist/plugins/codex/src/history.d.ts +3 -8
  9. package/dist/plugins/codex/src/history.js +2 -238
  10. package/dist/plugins/codex/src/hooks.js +1 -1
  11. package/dist/plugins/codex/src/identity.d.ts +1 -1
  12. package/dist/plugins/codex/src/identity.js +3 -3
  13. package/dist/plugins/codex/src/mcp.js +9 -8
  14. package/dist/plugins/codex/src/text.d.ts +1 -1
  15. package/dist/plugins/codex/src/text.js +2 -2
  16. package/dist/plugins/codex/src/transcript.d.ts +3 -39
  17. package/dist/plugins/codex/src/transcript.js +2 -313
  18. package/dist/plugins/dsh/engine.js +2 -2
  19. package/dist/plugins/dsh/history.d.ts +3 -0
  20. package/dist/plugins/dsh/history.js +15 -0
  21. package/dist/plugins/dsh/tools.js +12 -12
  22. package/dist/plugins/dsh/window.d.ts +1 -0
  23. package/dist/plugins/dsh/window.js +7 -3
  24. package/dist/plugins/pi/history-tools.d.ts +1 -1
  25. package/dist/plugins/pi/history-tools.js +9 -5
  26. package/dist/plugins/pi/history.d.ts +2 -3
  27. package/dist/plugins/pi/history.js +4 -147
  28. package/dist/plugins/pi/notes/tools.js +8 -6
  29. package/dist/plugins/pi/render.js +7 -4
  30. package/dist/plugins/pi/runtime.js +2 -2
  31. package/dist/plugins/pi/window.js +21 -7
  32. package/dist/src/boot/render.js +9 -11
  33. package/dist/src/boot/snapshot.d.ts +7 -7
  34. package/dist/src/boot/snapshot.js +17 -17
  35. package/dist/src/boot/text.d.ts +5 -3
  36. package/dist/src/boot/text.js +18 -10
  37. package/dist/src/dream/git.d.ts +2 -11
  38. package/dist/src/dream/git.js +6 -23
  39. package/dist/src/dream/lock.d.ts +2 -2
  40. package/dist/src/dream/lock.js +3 -3
  41. package/dist/src/history/claude.d.ts +16 -0
  42. package/dist/src/history/claude.js +336 -0
  43. package/dist/src/history/codex-transcript.d.ts +39 -0
  44. package/dist/src/history/codex-transcript.js +315 -0
  45. package/dist/src/history/codex.d.ts +8 -0
  46. package/dist/src/history/codex.js +238 -0
  47. package/dist/src/history/corpus.d.ts +35 -0
  48. package/dist/src/history/corpus.js +54 -0
  49. package/dist/src/history/history.d.ts +4 -8
  50. package/dist/src/history/history.js +3 -11
  51. package/dist/src/history/local.d.ts +17 -0
  52. package/dist/src/history/local.js +101 -0
  53. package/dist/src/history/pi.d.ts +36 -0
  54. package/dist/src/history/pi.js +202 -0
  55. package/dist/src/history/query.d.ts +15 -5
  56. package/dist/src/history/query.js +42 -13
  57. package/dist/src/index.d.ts +6 -3
  58. package/dist/src/index.js +6 -4
  59. package/dist/src/notes/address.d.ts +8 -8
  60. package/dist/src/notes/address.js +13 -13
  61. package/dist/src/notes/errors.d.ts +1 -1
  62. package/dist/src/notes/frontmatter.js +2 -2
  63. package/dist/src/notes/index.d.ts +1 -1
  64. package/dist/src/notes/index.js +1 -1
  65. package/dist/src/notes/paths.d.ts +6 -6
  66. package/dist/src/notes/paths.js +9 -9
  67. package/dist/src/notes/{project-home.d.ts → project-namespace.d.ts} +7 -7
  68. package/dist/src/notes/{project-home.js → project-namespace.js} +67 -25
  69. package/dist/src/notes/store.d.ts +4 -4
  70. package/dist/src/notes/store.js +55 -52
  71. package/dist/src/tools/dream.d.ts +21 -3
  72. package/dist/src/tools/dream.js +54 -16
  73. package/dist/src/tools/history.d.ts +7 -19
  74. package/dist/src/tools/history.js +80 -93
  75. package/dist/src/tools/notes-context.d.ts +10 -0
  76. package/dist/src/tools/notes-context.js +27 -0
  77. package/dist/src/tools/notes.d.ts +69 -20
  78. package/dist/src/tools/notes.js +40 -31
  79. package/dist/test/boot.integration.test.js +2 -3
  80. package/dist/test/claude-history.test.js +47 -34
  81. package/dist/test/claude-mod.test.js +96 -50
  82. package/dist/test/codex-history.test.js +4 -10
  83. package/dist/test/codex-plugin.test.js +50 -12
  84. package/dist/test/context-edit-budget.test.js +121 -0
  85. package/dist/test/dependencies.test.js +73 -6
  86. package/dist/test/dream-tools.test.js +153 -8
  87. package/dist/test/dsh.test.js +88 -19
  88. package/dist/test/helpers/dsh.d.ts +4 -1
  89. package/dist/test/helpers/dsh.js +20 -4
  90. package/dist/test/helpers/extension.d.ts +5 -1
  91. package/dist/test/helpers/extension.js +33 -2
  92. package/dist/test/helpers/history-corpus.d.ts +7 -0
  93. package/dist/test/helpers/history-corpus.js +26 -0
  94. package/dist/test/history-corpus.test.js +307 -0
  95. package/dist/test/history.integration.test.js +40 -48
  96. package/dist/test/host-neutral.test.js +20 -33
  97. package/dist/test/model-facing-text.test.js +14 -8
  98. package/dist/test/notes-cwd.test.d.ts +1 -0
  99. package/dist/test/notes-cwd.test.js +114 -0
  100. package/dist/test/notes-library.test.js +4 -4
  101. package/dist/test/notes-query-namespaces.test.d.ts +1 -0
  102. package/dist/test/{notes-query-homes.test.js → notes-query-namespaces.test.js} +13 -13
  103. package/dist/test/notes.integration.test.js +73 -24
  104. package/dist/test/notes.test.js +51 -21
  105. package/dist/test/pi-render.test.js +33 -1
  106. package/dist/test/project-namespace.test.d.ts +1 -0
  107. package/dist/test/project-namespace.test.js +324 -0
  108. package/docs/architecture.md +19 -12
  109. package/docs/claude-code-mod.md +7 -5
  110. package/docs/codex.md +6 -6
  111. package/docs/dsh.md +9 -9
  112. package/docs/history-sessions.md +52 -0
  113. package/docs/notes-library.md +9 -5
  114. package/docs/skills.md +3 -3
  115. package/docs/tool-results.md +14 -8
  116. package/package.json +4 -6
  117. package/playbook.md +6 -6
  118. package/plugins/claude/.claude-plugin/plugin.json +1 -1
  119. package/plugins/claude/dist/claude/helper.js +2164 -1341
  120. package/plugins/claude/hooks/register.ts +19 -11
  121. package/plugins/claude/playbook.md +6 -6
  122. package/plugins/claude/skills/memory/SKILL.md +9 -7
  123. package/plugins/claude/src/helper.ts +22 -25
  124. package/plugins/claude/src/history.ts +3 -257
  125. package/plugins/claude/src/text.ts +0 -1
  126. package/plugins/codex/README.md +1 -1
  127. package/plugins/codex/dist/codex/notesoup.js +1582 -969
  128. package/plugins/codex/src/history.ts +3 -193
  129. package/plugins/codex/src/hooks.ts +1 -1
  130. package/plugins/codex/src/identity.ts +3 -3
  131. package/plugins/codex/src/mcp.ts +9 -8
  132. package/plugins/codex/src/text.ts +2 -2
  133. package/plugins/codex/src/transcript.ts +3 -275
  134. package/plugins/dsh/engine.ts +2 -2
  135. package/plugins/dsh/history.ts +17 -0
  136. package/plugins/dsh/tools.ts +12 -12
  137. package/plugins/dsh/window.ts +8 -3
  138. package/plugins/paseo/OVERVIEW.md +4 -4
  139. package/plugins/paseo/README.md +1 -1
  140. package/plugins/paseo/client/brain-empty-card.tsx +3 -4
  141. package/plugins/paseo/client/markdown.tsx +159 -0
  142. package/plugins/paseo/client/notes-op-card.tsx +35 -34
  143. package/plugins/paseo/client/notes-op-transformer.ts +17 -68
  144. package/plugins/paseo/client/paper-card.tsx +8 -19
  145. package/plugins/paseo/client/paper-palette.ts +40 -0
  146. package/plugins/paseo/client/sticky-card.tsx +6 -4
  147. package/plugins/paseo/package.json +3 -0
  148. package/plugins/paseo/paseo-plugin.json +2 -2
  149. package/plugins/paseo/shared/notes-op.ts +13 -9
  150. package/plugins/paseo/test/notes-op.test.ts +52 -73
  151. package/plugins/paseo/test/paper-palette.test.ts +54 -0
  152. package/plugins/pi/history-tools.ts +11 -5
  153. package/plugins/pi/history.ts +8 -157
  154. package/plugins/pi/notes/tools.ts +8 -6
  155. package/plugins/pi/render.ts +6 -4
  156. package/plugins/pi/runtime.ts +2 -2
  157. package/plugins/pi/window.ts +22 -7
  158. package/skills/memory/SKILL.md +9 -7
  159. package/src/boot/render.ts +10 -13
  160. package/src/boot/snapshot.ts +20 -20
  161. package/src/boot/text.ts +18 -10
  162. package/src/dream/git.ts +7 -24
  163. package/src/dream/lock.ts +3 -3
  164. package/src/history/claude.ts +286 -0
  165. package/src/history/codex-transcript.ts +276 -0
  166. package/src/history/codex.ts +193 -0
  167. package/src/history/corpus.ts +69 -0
  168. package/src/history/history.ts +5 -12
  169. package/src/history/local.ts +93 -0
  170. package/src/history/pi.ts +199 -0
  171. package/src/history/query.ts +45 -15
  172. package/src/index.ts +8 -5
  173. package/src/notes/address.ts +13 -13
  174. package/src/notes/errors.ts +1 -1
  175. package/src/notes/frontmatter.ts +2 -2
  176. package/src/notes/index.ts +1 -1
  177. package/src/notes/paths.ts +9 -9
  178. package/src/notes/{project-home.ts → project-namespace.ts} +59 -28
  179. package/src/notes/store.ts +61 -58
  180. package/src/tools/dream.ts +63 -16
  181. package/src/tools/history.ts +71 -101
  182. package/src/tools/notes-context.ts +29 -0
  183. package/src/tools/notes.ts +39 -29
  184. package/dist/test/project-home.test.js +0 -134
  185. /package/dist/test/{notes-query-homes.test.d.ts → context-edit-budget.test.d.ts} +0 -0
  186. /package/dist/test/{project-home.test.d.ts → history-corpus.test.d.ts} +0 -0
@@ -1,4 +1,4 @@
1
1
  {
2
- "id": "notesoup-last-word",
3
- "requirements": { "paseo": ">=0.11.2 <0.12.0" }
2
+ "id": "notesoup",
3
+ "requirements": { "paseo": ">=0.11.2" }
4
4
  }
@@ -1,14 +1,22 @@
1
1
  import { z } from "zod";
2
2
 
3
+ /** Client display budget, including the omission line; source history stays unchanged. */
4
+ export const OUTPUT_DISPLAY_MAX_CHARS = 32_000;
5
+ export const COLLAPSED_PREVIEW_MAX_CHARS = 1_000;
6
+ export function outputPreview(text: string, maxChars = OUTPUT_DISPLAY_MAX_CHARS): string {
7
+ if (text.length <= maxChars) return text;
8
+ const middle = "\n\n… Showing the beginning and end; the middle is hidden in this preview. …\n\n";
9
+ const headChars = Math.floor((maxChars - middle.length) / 2);
10
+ // Budget in UTF-16 units, but never split a surrogate pair.
11
+ const head = text.slice(0, headChars).replace(/[\uD800-\uDBFF]$/, "");
12
+ const tail = text.slice(-(maxChars - middle.length - headChars)).replace(/^[\uDC00-\uDFFF]/, "");
13
+ return head + middle + tail;
14
+ }
15
+
3
16
  export const NOTES_OP_KIND = "notes-op";
4
17
  export const NOTES_OP_TOOLS = ["notes_read", "notes_write", "notes_update"] as const;
5
18
  export type NotesOpTool = (typeof NOTES_OP_TOOLS)[number];
6
19
 
7
- /** Card data stays small: the plugin timeline refuses payloads over 64 KB. */
8
- export const READ_TEXT_MAX_CHARS = 4000;
9
- export const DIFF_MAX_CHARS = 8000;
10
- export const PREVIEW_MAX_CHARS = 4000;
11
-
12
20
  export const notesOpSchema = z.object({
13
21
  op: z.enum(["read", "write", "update"]),
14
22
  address: z.string(),
@@ -16,15 +24,11 @@ export const notesOpSchema = z.object({
16
24
  error: z.string().optional(),
17
25
  // read
18
26
  text: z.string().optional(),
19
- totalChars: z.number().optional(),
20
27
  // write
21
- outcome: z.string().optional(),
22
28
  preview: z.string().optional(),
23
29
  // update
24
- changeKind: z.string().optional(),
25
30
  diff: z.string().optional(),
26
31
  renamedFrom: z.string().optional(),
27
32
  crumpled: z.boolean().optional(),
28
- truncated: z.boolean().optional(),
29
33
  });
30
34
  export type NotesOp = z.infer<typeof notesOpSchema>;
@@ -1,7 +1,7 @@
1
1
  import assert from "node:assert/strict";
2
2
  import test from "node:test";
3
3
  import { notesOpTransformer } from "../client/notes-op-transformer.ts";
4
- import { DIFF_MAX_CHARS, PREVIEW_MAX_CHARS, READ_TEXT_MAX_CHARS, notesOpSchema } from "../shared/notes-op.ts";
4
+ import { OUTPUT_DISPLAY_MAX_CHARS, notesOpSchema } from "../shared/notes-op.ts";
5
5
  import { claudeReadCompleted, claudeReadFailed, claudeUpdateCompleted, claudeWriteCompleted } from "./fixtures/claude-tool-calls.ts";
6
6
 
7
7
  function toolCall(overrides: Record<string, unknown>) {
@@ -18,75 +18,60 @@ function toolCall(overrides: Record<string, unknown>) {
18
18
 
19
19
  const transform = (overrides: Record<string, unknown>) => notesOpTransformer.transform({ item: toolCall(overrides) as never });
20
20
 
21
- test("notes_read renders the structured window, marks continuation as truncated", () => {
22
- const result = transform({
23
- detail: {
24
- type: "unknown",
25
- input: { address: "@self/foo.md" },
26
- output: { structuredContent: { address: "@self/foo.md", text: "hello note", total_chars: 9999, next_offset_chars: 4000 } },
27
- },
28
- });
29
- const data = notesOpSchema.parse(result!.items[0]!.data);
30
- assert.deepEqual(data, { op: "read", address: "@self/foo.md", status: "completed", text: "hello note", totalChars: 9999, truncated: true });
21
+ test("live and replay project the same complete delivered read, including continuation", () => {
22
+ const body = "笔记🦈\n".repeat(3000) + "\n[truncated; continue at offset_chars=15000]";
23
+ const content = [{ type: "text", text: `big.md\norigin self | created today | updated today\n\n${body}` }];
24
+ const replay = transform({ detail: { type: "unknown", input: { address: "big.md" }, output: { content } } });
25
+ const live = transform({ detail: { type: "unknown", input: { address: "big.md" }, output: {
26
+ content, structuredContent: { text: body, next_offset_chars: 15000 },
27
+ } } });
28
+ assert.equal(notesOpSchema.parse(replay!.items[0]!.data).text, body);
29
+ assert.deepEqual(live, replay);
31
30
  });
32
31
 
33
- test("notes_write carries outcome and a clipped content preview", () => {
34
- const result = transform({
35
- name: "notes_write",
36
- detail: {
37
- type: "unknown",
38
- input: { address: "session.md", content: "x".repeat(PREVIEW_MAX_CHARS + 10) },
39
- output: { structuredContent: { address: "session.md", outcome: "created" } },
40
- },
32
+ test("write and moved update project the entire input and delivered diff", () => {
33
+ const body = "long note\n".repeat(2000);
34
+ const write = transform({ name: "notes_write", detail: { type: "unknown",
35
+ input: { address: "a.md", content: body }, output: { content: [{ type: "text", text: "created a.md" }] },
36
+ } });
37
+ assert.equal(notesOpSchema.parse(write!.items[0]!.data).preview, body);
38
+ const diff = "+ 1 + new\n".repeat(2000) + "[diff truncated; update applied]";
39
+ const update = transform({ name: "notes_update", detail: { type: "unknown",
40
+ input: { address: "a.md", rename_to: "b.md" },
41
+ output: { content: [{ type: "text", text: `moved a.md -> b.md\ndiff:\n${diff}` }] },
42
+ } });
43
+ assert.deepEqual(notesOpSchema.parse(update!.items[0]!.data), {
44
+ op: "update", address: "b.md", renamedFrom: "a.md", status: "completed", diff,
41
45
  });
42
- const data = notesOpSchema.parse(result!.items[0]!.data);
43
- assert.equal(data.op, "write");
44
- assert.equal(data.outcome, "created");
45
- assert.equal(data.preview!.length, PREVIEW_MAX_CHARS);
46
- assert.equal(data.truncated, true);
47
46
  });
48
47
 
49
- test("notes_update carries change kind, rename, and clipped diff", () => {
50
- const result = transform({
51
- name: "notes_update",
52
- detail: {
53
- type: "unknown",
54
- input: { address: "@project/a.md" },
55
- output: { structuredContent: { address: "@project/b.md", change_kind: "moved", rename_from: "@project/a.md", diff: "y".repeat(DIFF_MAX_CHARS + 10) } },
56
- },
57
- });
58
- const data = notesOpSchema.parse(result!.items[0]!.data);
59
- assert.equal(data.changeKind, "moved");
60
- assert.equal(data.renamedFrom, "@project/a.md");
61
- assert.equal(data.diff!.length, DIFF_MAX_CHARS);
62
- assert.equal(data.truncated, true);
48
+ test("oversized read, write and diff displays retain head and tail without changing history", () => {
49
+ const body = "START\n" + "🦈".repeat(500_000) + "\nEND";
50
+ for (const [name, field, receipt] of [
51
+ ["notes_read", "text", `a.md\nmetadata\n\n${body}`],
52
+ ["notes_write", "preview", "created a.md"],
53
+ ["notes_update", "diff", `updated a.md\ndiff:\n${body}`],
54
+ ] as const) {
55
+ const source = { name, detail: { type: "unknown", input: { address: "a.md", content: body },
56
+ output: { content: [{ type: "text", text: receipt }] } } };
57
+ const before = JSON.stringify(source);
58
+ const data = notesOpSchema.parse(transform(source)!.items[0]!.data);
59
+ const preview = data[field]!;
60
+ assert.ok(preview.length <= OUTPUT_DISPLAY_MAX_CHARS);
61
+ assert.ok(preview.startsWith("START\n") && preview.endsWith("\nEND"));
62
+ assert.match(preview, /middle is hidden/);
63
+ assert.equal(Buffer.from(preview).toString("utf8"), preview);
64
+ assert.equal(JSON.stringify(source), before);
65
+ }
63
66
  });
64
67
 
65
- test("wire errors and failed calls surface the refusal text", () => {
66
- const refused = transform({
67
- detail: { type: "unknown", input: { address: "@self/foo.md" }, output: { structuredContent: { error: "No note at @self/foo.md.", code: "not_found" } } },
68
- });
69
- assert.equal(notesOpSchema.parse(refused!.items[0]!.data).error, "No note at @self/foo.md.");
70
-
71
- const failed = transform({
72
- status: "failed",
73
- error: { message: "boom" },
74
- detail: { type: "unknown", input: { address: "@self/foo.md" }, output: { content: [{ type: "text", text: "io failed" }] } },
68
+ test("failed calls surface the refusal text; running calls need only input", () => {
69
+ const failed = transform({ status: "failed", error: { message: "boom" },
70
+ detail: { type: "unknown", input: { address: "a.md" }, output: { content: [{ type: "text", text: "io failed" }] } },
75
71
  });
76
72
  assert.equal(notesOpSchema.parse(failed!.items[0]!.data).error, "io failed");
77
- });
78
-
79
- test("running calls render from input alone; long reads clip to the card budget", () => {
80
- const running = transform({ status: "running", detail: { type: "unknown", input: { address: "@human/map.md" }, output: null } });
81
- assert.deepEqual(notesOpSchema.parse(running!.items[0]!.data), { op: "read", address: "@human/map.md", status: "running" });
82
-
83
- const long = transform({
84
- detail: { type: "unknown", input: { address: "big.md" }, output: { structuredContent: { address: "big.md", text: "z".repeat(READ_TEXT_MAX_CHARS + 500), total_chars: 50000, next_offset_chars: null } } },
85
- });
86
- const data = notesOpSchema.parse(long!.items[0]!.data);
87
- assert.equal(data.text!.length, READ_TEXT_MAX_CHARS);
88
- assert.equal(data.truncated, true);
89
- assert.ok(JSON.stringify(result_items(long)).length < 64 * 1024, "plugin payload stays under the timeline limit");
73
+ const running = transform({ status: "running", detail: { type: "unknown", input: { address: "a.md" }, output: null } });
74
+ assert.deepEqual(notesOpSchema.parse(running!.items[0]!.data), { op: "read", address: "a.md", status: "running" });
90
75
  });
91
76
 
92
77
  test("history replay has no structured payload: the rendered text is parsed instead", () => {
@@ -100,7 +85,6 @@ test("history replay has no structured payload: the rendered text is parsed inst
100
85
  detail: { type: "unknown", input: { address: "a.md", content: "the new body" }, output: { content: [{ type: "text", text: "overwrote a.md (project pi-context)" }] } },
101
86
  });
102
87
  const writeData = notesOpSchema.parse(write!.items[0]!.data);
103
- assert.equal(writeData.outcome, "overwrote");
104
88
  assert.equal(writeData.preview, "the new body", "replay carries the call arguments, so the content preview comes from input on every path");
105
89
 
106
90
  const update = transform({
@@ -108,14 +92,13 @@ test("history replay has no structured payload: the rendered text is parsed inst
108
92
  detail: { type: "unknown", input: { address: "a.md" }, output: { content: [{ type: "text", text: "updated a.md\ndiff:\n- 1 - old\n+ 1 + new" }] } },
109
93
  });
110
94
  const updateData = notesOpSchema.parse(update!.items[0]!.data);
111
- assert.equal(updateData.changeKind, "body");
112
95
  assert.equal(updateData.diff, "- 1 - old\n+ 1 + new");
113
96
 
114
97
  const moved = transform({
115
98
  name: "notes_update",
116
- detail: { type: "unknown", input: { address: "a.md" }, output: { content: [{ type: "text", text: "moved a.md -> b.md" }] } },
99
+ detail: { type: "unknown", input: { address: "a.md", rename_to: "b.md" }, output: { content: [{ type: "text", text: "moved a.md -> b.md" }] } },
117
100
  });
118
- assert.equal(notesOpSchema.parse(moved!.items[0]!.data).changeKind, "moved");
101
+ assert.equal(notesOpSchema.parse(moved!.items[0]!.data).address, "b.md");
119
102
  });
120
103
 
121
104
  test("non-notes tools, unknown shapes and missing addresses stay untouched", () => {
@@ -131,10 +114,10 @@ test("Claude completed calls use the adapter's output text for read, write previ
131
114
  const read = notesOpSchema.parse(transform(claudeReadCompleted)!.items[0]!.data);
132
115
  assert.deepEqual(read, { op: "read", address: "@self/foo.md", status: "completed", text: "body line one\nbody line two" });
133
116
  assert.deepEqual(notesOpSchema.parse(transform(claudeWriteCompleted)!.items[0]!.data), {
134
- op: "write", address: "a.md", status: "completed", outcome: "overwrote", preview: "the new body",
117
+ op: "write", address: "a.md", status: "completed", preview: "the new body",
135
118
  });
136
119
  assert.deepEqual(notesOpSchema.parse(transform(claudeUpdateCompleted)!.items[0]!.data), {
137
- op: "update", address: "a.md", status: "completed", changeKind: "body", diff: "- 1 - old\n+ 1 + new",
120
+ op: "update", address: "a.md", status: "completed", diff: "- 1 - old\n+ 1 + new",
138
121
  });
139
122
  });
140
123
 
@@ -162,21 +145,17 @@ test("Claude failures keep raw error content and transport messages instead of p
162
145
  assert.deepEqual(notesOpSchema.parse(update!.items[0]!.data), { op: "update", address: "a.md", status: "failed", error: "MCP connection closed" });
163
146
  });
164
147
 
165
- function result_items(result: { items: Array<{ data: unknown }> } | undefined) {
166
- return result!.items.map((item) => item.data);
167
- }
168
-
169
148
  test("a crumple call is marked from the input alone", () => {
170
149
  const result = transform({
171
150
  name: "notes_update",
172
151
  detail: {
173
152
  type: "unknown",
174
153
  input: { address: "@self/stale.md", crumpled: true },
175
- output: { structuredContent: { address: "@self/stale.md", change_kind: "metadata" } },
154
+ output: { content: [{ type: "text", text: "updated @self/stale.md" }] },
176
155
  },
177
156
  });
178
157
  const data = notesOpSchema.parse(result!.items[0]!.data);
179
158
  assert.equal(data.crumpled, true);
180
- assert.equal(transform({ name: "notes_update", detail: { type: "unknown", input: { address: "@self/a.md", crumpled: false }, output: { structuredContent: { address: "@self/a.md", change_kind: "metadata" } } } })!
159
+ assert.equal(transform({ name: "notes_update", detail: { type: "unknown", input: { address: "@self/a.md", crumpled: false }, output: { content: [{ type: "text", text: "updated @self/a.md" }] } } })!
181
160
  .items[0]!.data.crumpled, undefined);
182
161
  });
@@ -0,0 +1,54 @@
1
+ import assert from "node:assert/strict";
2
+ import test from "node:test";
3
+ import type { PluginTheme } from "@getpaseo/plugin";
4
+ import { paperPalette } from "../client/paper-palette.ts";
5
+
6
+ function theme(surface0: string, foreground: string): PluginTheme {
7
+ return { colors: {
8
+ surface0, foreground,
9
+ surface1: surface0, surface2: surface0, border: foreground,
10
+ foregroundMuted: foreground, accent: foreground, accentForeground: surface0,
11
+ statusSuccess: foreground, statusWarning: foreground, statusDanger: foreground,
12
+ } };
13
+ }
14
+
15
+ function luminance(hex: string): number {
16
+ const [r, g, b] = [1, 3, 5].map(index => {
17
+ const channel = parseInt(hex.slice(index, index + 2), 16) / 255;
18
+ return channel <= 0.04045 ? channel / 12.92 : ((channel + 0.055) / 1.055) ** 2.4;
19
+ });
20
+ return 0.2126 * r + 0.7152 * g + 0.0722 * b;
21
+ }
22
+
23
+ function contrast(a: string, b: string): number {
24
+ const lighter = Math.max(luminance(a), luminance(b));
25
+ const darker = Math.min(luminance(a), luminance(b));
26
+ return (lighter + 0.05) / (darker + 0.05);
27
+ }
28
+
29
+ test("paper follows the host theme and preserves the light palette when switching back", () => {
30
+ const light = theme("#ffffff", "#18181b");
31
+ const dark = theme("#18181b", "#fafafa");
32
+ const paper = paperPalette(light);
33
+ assert.equal(paper.background, "#f8f3e1");
34
+ assert.equal(paper.ink, "#33301f");
35
+ assert.ok(luminance(paperPalette(dark).background) < 0.05);
36
+ assert.notDeepEqual(paperPalette(dark), paper);
37
+ assert.deepEqual(paperPalette(light), paper);
38
+ });
39
+
40
+ test("host hex shorthand and alpha colors select the same dark paper", () => {
41
+ const paper = paperPalette(theme("#000000", "#ffffff"));
42
+ assert.deepEqual(paperPalette(theme("#000", "#fff")), paper);
43
+ assert.deepEqual(paperPalette(theme("#000000ff", "#ffffffff")), paper);
44
+ assert.equal(paperPalette(theme("#fff", "#000")).background, "#f8f3e1");
45
+ });
46
+
47
+ test("dark text, muted labels, additions and errors remain readable on normal and crumpled paper", () => {
48
+ const paper = paperPalette(theme("#18181b", "#fafafa"));
49
+ for (const background of [paper.background, paper.crumpled]) {
50
+ for (const ink of [paper.ink, paper.inkMuted, paper.added, paper.removed]) {
51
+ assert.ok(contrast(ink, background) >= 4.5, `${ink} on ${background} must meet WCAG AA text contrast`);
52
+ }
53
+ }
54
+ });
@@ -1,11 +1,17 @@
1
1
  import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
2
- import { historyWindows, historyList, historyRead } from "../../src/tools/history.js";
2
+ import { historyList, historyRead } from "../../src/tools/history.js";
3
3
  import { historyFromSession } from "./history.js";
4
+ import { localHistoryCorpus } from "../../src/history/local.js";
5
+ import type { SessionReader } from "./session-reader.js";
4
6
  import { HISTORY_NAMESPACE, registerOperation } from "./tool-result.js";
5
7
 
6
- /** Register the three shared history operations; the adapter allocates addresses and supplies them. */
8
+ function historyContext(ctx: SessionReader) {
9
+ const current = () => historyFromSession(ctx);
10
+ return { current, corpus: localHistoryCorpus({ current: { harness: "pi", id: ctx.sessionManager.getSessionId(), load: async () => ({ projection: current() }) } }) };
11
+ }
12
+
13
+ /** Register the two deferred history operations; the adapter allocates addresses and supplies them. */
7
14
  export function registerHistoryTools(pi: ExtensionAPI) {
8
- registerOperation(pi, historyWindows, (params, ctx) => historyWindows.execute(params, historyFromSession(ctx), ctx.sessionManager.getSessionId()), HISTORY_NAMESPACE);
9
- registerOperation(pi, historyList, (params, ctx) => historyList.execute(params, historyFromSession(ctx)), HISTORY_NAMESPACE);
10
- registerOperation(pi, historyRead, (params, ctx) => historyRead.execute(params, historyFromSession(ctx)), HISTORY_NAMESPACE);
15
+ registerOperation(pi, historyList, (params, ctx) => historyList.execute(params, historyContext(ctx)), HISTORY_NAMESPACE, undefined, "deferred");
16
+ registerOperation(pi, historyRead, (params, ctx) => historyRead.execute(params, historyContext(ctx)), HISTORY_NAMESPACE, undefined, "deferred");
11
17
  }
@@ -1,163 +1,14 @@
1
- /**
2
- * Native history decoder. This lane owns nothing but the host boundary: it allocates the stable
3
- * file-order seq, selects the active branch, and decodes session entries into typed facts. Pairing,
4
- * bounding, and the readable projection belong to the shared domain in ../history/history.ts.
5
- *
6
- * The address contract is deliberate and unchanged in spirit: a seq is allocated from entry kind and
7
- * role alone, never from visible content, so appending or branching never renumbers an existing
8
- * address. What changed is that a result folded into a pairing no longer doubles as a second
9
- * readable address for its call.
10
- */
11
- import type { ToolCall } from "@earendil-works/pi-ai";
12
- import type { AgentMessage } from "@earendil-works/pi-agent-core";
13
- import type { SessionBoundaryDraft, SessionEntry } from "@earendil-works/pi-coding-agent";
1
+ /** Pi's native reader and pending-boundary addressing use the shared Pi wire decoder. */
2
+ import type { SessionBoundaryDraft } from "@earendil-works/pi-coding-agent";
14
3
  import type { SessionReader } from "./session-reader.js";
15
- import { isWindowMarker, rootWindowId } from "./window.js";
16
- import { contentText, projectHistory, type DecodedHistoryItem, type DecodedHistoryWindow, type HistoryProjection, type NestedCallRecord, type ToolCallStatus } from "../../src/history/history.js";
4
+ import { piHistoryFromEntries, piSequenceCount } from "../../src/history/pi.js";
5
+ import type { HistoryProjection } from "../../src/history/history.js";
17
6
 
18
- function mapRole(role: AgentMessage["role"]): DecodedHistoryItem["role"] | undefined {
19
- if (role === "user" || role === "assistant") return role;
20
- if (role === "toolResult" || role === "bashExecution") return "tool";
21
- if (role === "custom") return "developer";
22
- if (role === "compactionSummary" || role === "branchSummary") return "system";
23
- return undefined;
24
- }
25
-
26
- function isToolCall(part: unknown): part is ToolCall {
27
- return typeof part === "object" && part !== null && (part as { type?: unknown }).type === "toolCall";
28
- }
29
-
30
- /** Seq allocation depends on entry kind and role, never on visible content. */
31
- function sequenceCount(entry: SessionEntry | SessionBoundaryDraft): number {
32
- if (entry.type === "compaction" || entry.type === "branch_summary" || entry.type === "custom_message") return 1;
33
- if (entry.type !== "message" || mapRole(entry.message.role) === undefined) return 0;
34
- if (entry.message.role !== "assistant" || !Array.isArray(entry.message.content)) return 1;
35
- return 1 + entry.message.content.filter(isToolCall).length;
36
- }
37
-
38
- /** Pending boundary drafts use the same slots as persisted entries. */
39
7
  export function nextHistorySeq(ctx: SessionReader, pending: readonly SessionBoundaryDraft[] = []): number {
40
- return 1 + [...ctx.sessionManager.getEntries(), ...pending].reduce((sum, entry) => sum + sequenceCount(entry), 0);
41
- }
42
-
43
- function messageContent(message: AgentMessage): string {
44
- switch (message.role) {
45
- case "bashExecution":
46
- return message.output;
47
- case "branchSummary":
48
- case "compactionSummary":
49
- return message.summary;
50
- default:
51
- return contentText(message.content);
52
- }
53
- }
54
-
55
- /**
56
- * Pass the host's nested-call record through as recorded. It is evidence about calls this run made,
57
- * not a second transcript: the host stores no nested results, and this lane invents none.
58
- */
59
- function nestedCallsOf(message: AgentMessage): { calls: NestedCallRecord[]; complete: boolean } | undefined {
60
- if (message.role !== "toolResult" || message.nestedCalls === undefined) return undefined;
61
- return { calls: message.nestedCalls.calls, complete: message.nestedCalls.complete };
8
+ return 1 + [...ctx.sessionManager.getEntries(), ...pending].reduce((sum, entry) => sum + piSequenceCount(entry), 0);
62
9
  }
63
10
 
64
- function toolInfo(message: AgentMessage): Pick<DecodedHistoryItem, "toolName" | "arguments" | "outputTruncated" | "fullOutputPath" | "toolError" | "toolCallId" | "nestedCalls" | "recordedStatus"> {
65
- if (message.role === "bashExecution") {
66
- // A standalone bash run records its own outcome, so its status is read here rather than
67
- // inferred from a result message that will never arrive: a cancelled or nonzero run is an
68
- // error, and a run with no recorded exit code stays unknown instead of being called ok.
69
- const status: ToolCallStatus = message.cancelled === true ? "error" : typeof message.exitCode === "number" ? (message.exitCode === 0 ? "ok" : "error") : "unfinished";
70
- // A truncated run is only half the record without the on-disk path: surface both.
71
- return { toolName: "bash", arguments: { command: message.command }, recordedStatus: status, outputTruncated: message.truncated || undefined, fullOutputPath: message.truncated ? message.fullOutputPath : undefined };
72
- }
73
- if (message.role !== "toolResult") return {};
74
- const nestedCalls = nestedCallsOf(message);
75
- return {
76
- toolName: message.toolName,
77
- toolCallId: message.toolCallId,
78
- toolError: message.isError === true ? true : undefined,
79
- ...(nestedCalls ? { nestedCalls } : {}),
80
- };
81
- }
82
-
83
- function toolCallItems(windowId: string, entry: { id: string; timestamp?: string }, message: AgentMessage, entrySeq: number): DecodedHistoryItem[] {
84
- if (message.role !== "assistant" || !Array.isArray(message.content)) return [];
85
- const items: DecodedHistoryItem[] = [];
86
- let callIndex = 0;
87
- for (const part of message.content) {
88
- if (!isToolCall(part)) continue;
89
- items.push({
90
- seq: entrySeq + callIndex + 1,
91
- windowId,
92
- role: "tool_call",
93
- text: "",
94
- createdAt: entry.timestamp,
95
- toolName: part.name,
96
- toolCallId: part.id,
97
- arguments: part.arguments,
98
- });
99
- callIndex += 1;
100
- }
101
- return items;
102
- }
103
-
104
- /** Build stable internal addresses, then project the active branch into public events. */
105
11
  export function historyFromSession(ctx: SessionReader): HistoryProjection {
106
- const seqByEntryId = new Map<string, number>();
107
- let nextSeq = 1;
108
- for (const entry of ctx.sessionManager.getEntries()) {
109
- const count = sequenceCount(entry);
110
- if (count === 0) continue;
111
- seqByEntryId.set(entry.id, nextSeq);
112
- nextSeq += count;
113
- }
114
- const highestSeq = nextSeq - 1;
115
-
116
- const sessionId = ctx.sessionManager.getSessionId();
117
- let window: DecodedHistoryWindow = { windowId: rootWindowId(sessionId), items: [] };
118
- const rawWindows = [window];
119
- const branchSeqs = new Set<number>();
120
-
121
- for (const entry of ctx.sessionManager.getBranch()) {
122
- if (isWindowMarker(entry)) {
123
- window = { windowId: entry.data.windowId, createdAt: entry.timestamp, items: [] };
124
- rawWindows.push(window);
125
- continue;
126
- }
127
- const entrySeq = seqByEntryId.get(entry.id);
128
- if (entrySeq === undefined) continue;
129
- branchSeqs.add(entrySeq);
130
-
131
- if (entry.type === "compaction" || entry.type === "branch_summary") {
132
- window.items.push({ seq: entrySeq, windowId: window.windowId, role: "system", text: entry.summary, createdAt: entry.timestamp });
133
- continue;
134
- }
135
- if (entry.type === "message") {
136
- const role = mapRole(entry.message.role);
137
- if (!role) continue;
138
- window.items.push({
139
- seq: entrySeq,
140
- windowId: window.windowId,
141
- role,
142
- text: messageContent(entry.message),
143
- createdAt: entry.timestamp,
144
- ...toolInfo(entry.message),
145
- });
146
- const calls = toolCallItems(window.windowId, entry, entry.message, entrySeq);
147
- for (const call of calls) branchSeqs.add(call.seq);
148
- window.items.push(...calls);
149
- continue;
150
- }
151
- if (entry.type === "custom_message") {
152
- window.items.push({
153
- seq: entrySeq,
154
- windowId: window.windowId,
155
- role: "developer",
156
- text: contentText(entry.content),
157
- createdAt: entry.timestamp,
158
- });
159
- }
160
- }
161
-
162
- return projectHistory(rawWindows, highestSeq, branchSeqs);
163
- }
12
+ const manager = ctx.sessionManager;
13
+ return piHistoryFromEntries(manager.getSessionId(), manager.getEntries(), manager.getBranch());
14
+ }
@@ -5,6 +5,7 @@ import { notesIdentityFromPi } from "./adapter.js";
5
5
  import { notesReadRenderers, notesUpdateRenderers, notesWriteRenderers } from "../render.js";
6
6
  import { DREAM_NAMESPACE, NOTES_NAMESPACE, registerOperation } from "../tool-result.js";
7
7
  import type { NoteChange } from "../../../src/notes/index.js";
8
+ import { notesToolContext } from "../../../src/tools/notes-context.js";
8
9
 
9
10
  function renderDiff(change: NoteChange): string {
10
11
  return change.kind === "none" ? "" : generateDiffString(change.before, change.after, 1).diff;
@@ -12,7 +13,7 @@ function renderDiff(change: NoteChange): string {
12
13
 
13
14
  /** Register the five shared note operations and the three hidden dream tools; an open dream widens the note identity. */
14
15
  export function registerNotesTools(pi: ExtensionAPI) {
15
- // One open dream per session, in memory: shutdown releases its lock without the end commit.
16
+ // One pending or open dream per session: shutdown releases ownership without the end commit.
16
17
  const dreams = new Map<string, DreamState>();
17
18
  pi.on("session_shutdown", () => {
18
19
  for (const state of dreams.values()) abandonDream(state);
@@ -25,11 +26,12 @@ export function registerNotesTools(pi: ExtensionAPI) {
25
26
  return state;
26
27
  };
27
28
  const identity = (ctx: ExtensionContext) => dreamingIdentity(notesIdentityFromPi(ctx), dreamOf(ctx));
28
- registerOperation(pi, notesWrite, (params, ctx) => notesWrite.execute(params, identity(ctx)), NOTES_NAMESPACE, notesWriteRenderers);
29
- registerOperation(pi, notesUpdate, (params, ctx) => notesUpdate.execute(params, identity(ctx), renderDiff), NOTES_NAMESPACE, notesUpdateRenderers);
30
- registerOperation(pi, notesRead, (params, ctx) => notesRead.execute(params, identity(ctx)), NOTES_NAMESPACE, notesReadRenderers);
31
- registerOperation(pi, notesList, (params, ctx) => notesList.execute(params, identity(ctx)), NOTES_NAMESPACE);
32
- registerOperation(pi, notesSearch, (params, ctx) => notesSearch.execute(params, identity(ctx)), NOTES_NAMESPACE);
29
+ const toolContext = (ctx: ExtensionContext) => notesToolContext(identity(ctx), ctx.cwd);
30
+ registerOperation(pi, notesWrite, (params, ctx) => notesWrite.execute(params, toolContext(ctx)), NOTES_NAMESPACE, notesWriteRenderers);
31
+ registerOperation(pi, notesUpdate, (params, ctx) => notesUpdate.execute(params, toolContext(ctx), renderDiff), NOTES_NAMESPACE, notesUpdateRenderers);
32
+ registerOperation(pi, notesRead, (params, ctx) => notesRead.execute(params, toolContext(ctx)), NOTES_NAMESPACE, notesReadRenderers);
33
+ registerOperation(pi, notesList, (params, ctx) => notesList.execute(params, toolContext(ctx)), NOTES_NAMESPACE);
34
+ registerOperation(pi, notesSearch, (params, ctx) => notesSearch.execute(params, toolContext(ctx)), NOTES_NAMESPACE);
33
35
  registerOperation(pi, dreamBegin, (params, ctx) => dreamBegin.execute(params, notesIdentityFromPi(ctx), dreamOf(ctx)), DREAM_NAMESPACE, undefined, "deferred");
34
36
  registerOperation(pi, dreamForget, (params, ctx) => dreamForget.execute(params, notesIdentityFromPi(ctx), dreamOf(ctx)), DREAM_NAMESPACE, undefined, "deferred");
35
37
  registerOperation(pi, dreamEnd, (params, ctx) => dreamEnd.execute(params, notesIdentityFromPi(ctx), dreamOf(ctx)), DREAM_NAMESPACE, undefined, "deferred");
@@ -1,6 +1,6 @@
1
1
  /** Pi TUI renderers for notesoup's own tools: collapsed one-line slips, expandable bodies. */
2
2
  import { renderDiff, type AgentToolResult, type Theme } from "@earendil-works/pi-coding-agent";
3
- import { Text, TruncatedText, visibleWidth, type Component } from "@earendil-works/pi-tui";
3
+ import { Text, TruncatedText, truncateToWidth, visibleWidth, type Component } from "@earendil-works/pi-tui";
4
4
  import type { Static } from "typebox";
5
5
  import type { NotesReadData, NotesUpdateData, NotesWriteData } from "../../src/tools/notes.js";
6
6
  import { notesReadParameters, notesUpdateParameters, notesWriteParameters } from "../../src/tools/notes.js";
@@ -153,12 +153,14 @@ export const emptyBrainRenderers = {
153
153
  return {
154
154
  invalidate() {},
155
155
  render(width: number): string[] {
156
+ if (width <= 0) return [];
156
157
  const label = "✂ brain emptied";
157
158
  const prefix = "── ";
158
- const fill = Math.max(2, width - visibleWidth(prefix) - visibleWidth(label) - 1);
159
+ const fill = Math.max(0, width - visibleWidth(prefix) - visibleWidth(label) - 1);
159
160
  const lines = [theme.fg("dim", `${prefix}${label} ${"─".repeat(fill)}`)];
160
- if (lastWord !== undefined) lines.push(theme.fg("warning", theme.italic(`“${lastWord}”`)));
161
- return lines;
161
+ if (lastWord !== undefined) lines.push(...new Text(theme.fg("warning", theme.italic(`“${lastWord}”`)), 0, 0).render(width));
162
+ // The divider, or a wide glyph in a one-column viewport, may still need clipping.
163
+ return lines.map((line) => truncateToWidth(line, width, ""));
162
164
  },
163
165
  };
164
166
  },
@@ -88,8 +88,8 @@ export function registerContext(pi: ExtensionAPI, settingsManager?: SettingsMana
88
88
  const notifyIncompleteNotes: IncompleteNotesNotifier = (ctx, windowId, snapshot) => {
89
89
  if (snapshot.unavailable.length === 0 || incompleteNotesNotified.has(windowId)) return;
90
90
  incompleteNotesNotified.add(windowId);
91
- const homes = snapshot.unavailable.map((home) => home.label).join(", ");
92
- ctx.ui.notify(`🥣 Some notes went missing: ${homes}`, "warning");
91
+ const namespaces = snapshot.unavailable.map((namespace) => namespace.label).join(", ");
92
+ ctx.ui.notify(`🥣 Some notes went missing: ${namespaces}`, "warning");
93
93
  };
94
94
  const budget = registerBudget(pi, () => enabled, settingsManager);
95
95
 
@@ -129,17 +129,32 @@ export function projectRootWindow(messages: AgentMessage[], windowId: string): A
129
129
  /** Usage for the selected window, excluding provider usage recorded before its marker. */
130
130
  export function windowUsage(ctx: Pick<ExtensionContext, "sessionManager" | "getContextUsage" | "model">) {
131
131
  const reset = currentReset(ctx);
132
- if (!reset) return ctx.getContextUsage();
132
+ // Native checkpoints already cut the active projection and Pi invalidates usage
133
+ // after context edits. Preserve that authority, including unknown/unavailable usage.
134
+ if (!reset || isCheckpointBackedReset(ctx, reset)) return ctx.getContextUsage();
133
135
  const contextWindow = ctx.model?.contextWindow ?? ctx.getContextUsage()?.contextWindow;
134
136
  if (!contextWindow) return undefined;
135
137
  const windowId = reset.data.windowId;
136
138
  try {
137
- const canonicalMessages = ctx.sessionManager.buildSessionProjection().messages;
138
- // New resets already cut the durable Pi projection. Marker slicing is retained only
139
- // for sessions written before native reset checkpoints existed.
140
- const messages: AgentMessage[] = isCheckpointBackedReset(ctx, reset)
141
- ? canonicalMessages
142
- : projectWindow(canonicalMessages, windowId);
139
+ const projection = ctx.sessionManager.buildSessionProjection();
140
+ const branch = ctx.sessionManager.getBranch();
141
+ let invalidatedThrough = -1;
142
+ for (let i = branch.length - 1; i >= 0; i--) {
143
+ if (branch[i].type === "context_edit" || branch[i].type === "compaction") {
144
+ invalidatedThrough = i;
145
+ break;
146
+ }
147
+ }
148
+ const staleIds = new Set(branch.slice(0, invalidatedThrough + 1).map((entry) => entry.id));
149
+ const staleMessages = new Set(projection.entries
150
+ .filter((entry) => staleIds.has(entry.sourceEntry.id))
151
+ .flatMap((entry) => entry.messages));
152
+ // Legacy marker-only windows still need slicing. Edits preserve assistant metadata,
153
+ // so clear stale usage only in this estimate, never in the persisted projection.
154
+ const messages = projectWindow(projection.messages, windowId).map((message) =>
155
+ message.role === "assistant" && staleMessages.has(message)
156
+ ? { ...message, usage: { ...message.usage, input: 0, output: 0, cacheRead: 0, cacheWrite: 0, totalTokens: 0 } }
157
+ : message);
143
158
  const { tokens } = estimateContextTokens(convertToLlm(messages));
144
159
  return { tokens, contextWindow, percent: tokens / contextWindow * 100 };
145
160
  } catch {