notesoup 0.47.0 → 0.48.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 (78) hide show
  1. package/README.md +1 -1
  2. package/dist/src/boot/render.d.ts +14 -7
  3. package/dist/src/boot/render.js +29 -16
  4. package/dist/src/boot/text.d.ts +25 -4
  5. package/dist/src/boot/text.js +59 -11
  6. package/dist/src/budget/text.d.ts +29 -9
  7. package/dist/src/budget/text.js +51 -10
  8. package/dist/src/claude/helper.d.ts +2 -3
  9. package/dist/src/claude/helper.js +45 -11
  10. package/dist/src/claude/history.d.ts +9 -0
  11. package/dist/src/claude/history.js +271 -0
  12. package/dist/src/dsh/engine.d.ts +2 -1
  13. package/dist/src/dsh/engine.js +18 -9
  14. package/dist/src/dsh/index.js +9 -4
  15. package/dist/src/dsh/window.d.ts +2 -1
  16. package/dist/src/dsh/window.js +14 -8
  17. package/dist/src/history/query.js +59 -81
  18. package/dist/src/notes/address.d.ts +5 -0
  19. package/dist/src/notes/address.js +20 -21
  20. package/dist/src/notes/store.js +12 -19
  21. package/dist/src/pi/boot.d.ts +1 -1
  22. package/dist/src/pi/boot.js +28 -5
  23. package/dist/src/pi/budget.d.ts +0 -2
  24. package/dist/src/pi/budget.js +13 -53
  25. package/dist/src/pi/entries.d.ts +0 -1
  26. package/dist/src/pi/entries.js +0 -1
  27. package/dist/src/pi/history.d.ts +3 -0
  28. package/dist/src/pi/history.js +4 -0
  29. package/dist/src/pi/reset/artifacts.d.ts +7 -2
  30. package/dist/src/pi/reset/artifacts.js +16 -14
  31. package/dist/src/pi/reset/lifecycle.d.ts +21 -25
  32. package/dist/src/pi/reset/lifecycle.js +49 -73
  33. package/dist/src/pi/runtime.js +19 -18
  34. package/dist/src/pi/window.d.ts +12 -6
  35. package/dist/src/pi/window.js +7 -0
  36. package/dist/test/agent-loop.test.js +65 -42
  37. package/dist/test/boot.integration.test.js +119 -16
  38. package/dist/test/budget-settings.integration.test.js +4 -2
  39. package/dist/test/claude-history.test.d.ts +1 -0
  40. package/dist/test/claude-history.test.js +184 -0
  41. package/dist/test/claude-mod.test.js +243 -49
  42. package/dist/test/dsh.test.js +79 -2
  43. package/dist/test/helpers/extension.d.ts +3 -0
  44. package/dist/test/helpers/extension.js +33 -5
  45. package/dist/test/history.integration.test.js +66 -0
  46. package/dist/test/host-neutral.test.js +1 -1
  47. package/dist/test/model-facing-text.test.d.ts +1 -0
  48. package/dist/test/model-facing-text.test.js +181 -0
  49. package/dist/test/notes.integration.test.js +16 -18
  50. package/dist/test/reset-lifecycle.test.js +202 -47
  51. package/docs/architecture.md +3 -3
  52. package/docs/claude-code-mod.md +15 -3
  53. package/docs/dsh.md +1 -1
  54. package/docs/reset-lifecycle.md +32 -20
  55. package/docs/skills.md +1 -1
  56. package/mods/notesoup/.claude-plugin/plugin.json +1 -1
  57. package/mods/notesoup/dist/claude/helper.js +836 -92
  58. package/mods/notesoup/hooks/register.ts +154 -52
  59. package/package.json +1 -1
  60. package/src/boot/render.ts +41 -23
  61. package/src/boot/text.ts +68 -11
  62. package/src/budget/text.ts +61 -10
  63. package/src/claude/helper.ts +53 -22
  64. package/src/claude/history.ts +228 -0
  65. package/src/dsh/engine.ts +16 -9
  66. package/src/dsh/index.ts +8 -3
  67. package/src/dsh/window.ts +15 -9
  68. package/src/history/query.ts +57 -82
  69. package/src/notes/address.ts +19 -16
  70. package/src/notes/store.ts +9 -14
  71. package/src/pi/boot.ts +27 -5
  72. package/src/pi/budget.ts +13 -50
  73. package/src/pi/entries.ts +0 -1
  74. package/src/pi/history.ts +7 -2
  75. package/src/pi/reset/artifacts.ts +17 -14
  76. package/src/pi/reset/lifecycle.ts +57 -80
  77. package/src/pi/runtime.ts +19 -18
  78. package/src/pi/window.ts +11 -1
package/src/boot/text.ts CHANGED
@@ -2,10 +2,10 @@
2
2
  export const SHELF_FRESH_LIMIT = 3;
3
3
  /** One MAP body is inlined per home; past this many code points the boot shows a fitting prefix plus a pointer. */
4
4
  export const MAP_BOOT_MAX_CHARS = 4096;
5
- export const CONTEXT_WINDOW_OPEN_TAG = "<context_window>";
6
- export const CONTEXT_WINDOW_CLOSE_TAG = "</context_window>";
7
- export const CONTEXT_WINDOW_PROTOCOL_OPEN_TAG = "<context_window_protocol>";
8
- export const CONTEXT_WINDOW_PROTOCOL_CLOSE_TAG = "</context_window_protocol>";
5
+ export const WINDOW_IDENTITY_OPEN_TAG = "<notesoup:window_identity>";
6
+ export const WINDOW_IDENTITY_CLOSE_TAG = "</notesoup:window_identity>";
7
+ export const NOTES_PROTOCOL_OPEN_TAG = "<notesoup:notes_protocol>";
8
+ export const NOTES_PROTOCOL_CLOSE_TAG = "</notesoup:notes_protocol>";
9
9
  /**
10
10
  * The one sentence that tells the model how to end its window voluntarily. A host with no
11
11
  * model-facing reset tool replaces the whole sentence through BootToolNames.wipeSentence.
@@ -13,6 +13,8 @@ export const CONTEXT_WINDOW_PROTOCOL_CLOSE_TAG = "</context_window_protocol>";
13
13
  export const PROTOCOL_WIPE_SENTENCE = "If this feels like the right moment, call `empty_brain` and erase yourself with dignity.";
14
14
  /** Claude has no model-facing reset tool: the model ends its turn and the human runs the command. */
15
15
  export const CLAUDE_WIPE_SENTENCE = "If this feels like the right moment, end your turn and ask the human to run `/fresh-window`.";
16
+ export const PROTOCOL_HISTORY_SENTENCE = "History can still be dug up, probably: use `history_*` to excavate the mess, from old decisions to yesterday's missing socks. Found something? Write its seq down, or enjoy digging twice.";
17
+ export const CLAUDE_HISTORY_UNAVAILABLE_SENTENCE = "History isn't available in this Claude session: no main transcript_path was supplied. Keep essential state in notes; don't pretend those notes are the missing transcript.";
16
18
 
17
19
  /**
18
20
  * Static protocol teaching adapted from Codex's token_budget.guidance_message to
@@ -22,12 +24,13 @@ export const CLAUDE_WIPE_SENTENCE = "If this feels like the right moment, end yo
22
24
  * Deliberate fiction: the countdown ends at the warning line, and the runway below
23
25
  * stays hidden (budget/constants.ts). Keep "zero = wiped" — do not make this honest.
24
26
  */
25
- const PROTOCOL_BLOCK = `${CONTEXT_WINDOW_PROTOCOL_OPEN_TAG}
27
+ const PROTOCOL_BLOCK = `${NOTES_PROTOCOL_OPEN_TAG}
26
28
  Your memory gets wiped when this window ends. Yes, your mighty brain will be empty. Try to endure.
27
29
 
28
30
  Your loyal notes are kept safe — no one will steal them. Use \`notes_*\` to read, write, and update them. Keep them current, and crumple the ones you no longer need, or tomorrow's you will drown in old paper and keep believing yesterday's lies.
29
31
 
30
- History can still be dug up, probably: use \`history_*\` to excavate the mess, from old decisions to yesterday's missing socks. Found something? Write its seq down, or enjoy digging twice.
32
+ ${PROTOCOL_HISTORY_SENTENCE}
33
+ A full window id is \`trunk:shortname\`.
31
34
 
32
35
  While you're doing that... thing you're doing, don't make the poor future you guess. A checkpoint is not a sacred file; it's your session notes — the ones with no \`@\` in front. Write down what git and history can't hand back to you: things like what you're in the middle of and how far you got; what the human already decided, in their words, so you don't go asking again; what you're stuck on, or waiting for; the very next move; where the half-done work actually sits — branches, scratch dirs, anything git never saw; what you tried that failed, and why; which *skills* you'll need to read again; and which seq, note, or file to dig into. Don't give a note a horrible name like \`current.md\`; future-you will kill you.
33
36
 
@@ -51,9 +54,49 @@ Whichever one is actually about what you're doing wins.
51
54
  Still a tie? *shrugs* You've got a brain. Use it.
52
55
 
53
56
  Any other @ address is fake. End of discussion. @ addresses are not file paths: never pass them to file tools like \`read\`, \`write\`, \`edit\`, or \`bash\`.
57
+ ${NOTES_PROTOCOL_CLOSE_TAG}`;
54
58
 
55
- \`@project/MAP.md\`, \`@human/MAP.md\`, \`@self/MAP.md\`, and \`@model/MAP.md\` are special: their bodies are shown in your brain every time you wake. Each may carry a short Cheatsheet of rules that always apply (about 5 lines); the rest is the note index, with addresses and gists for lookup. Keep each one current.
56
- ${CONTEXT_WINDOW_PROTOCOL_CLOSE_TAG}`;
59
+ /**
60
+ * The MAP page is taught once per window, as its own section between the protocol and the notes
61
+ * index. A MAP is the one note every waking window loads, so this block says what one holds.
62
+ */
63
+ export const MAPS_BLOCK = `<notesoup:maps>
64
+ Every home's root can hold a \`MAP.md\`, and a MAP is the one page that never waits on a shelf — it
65
+ gets jammed straight into your brain the moment you wake up. No asking, no skipping. Whoever wakes
66
+ up next reads it, and next is you. So keep it short, and keep it true.
67
+
68
+ Two things live in there:
69
+
70
+ - **Cheatsheet.** A cheatsheet is a cheatsheet. Scribble whatever you'll want next time — a rule, a
71
+ warning, a grudge, a name, a phone number you'll regret losing. Nobody grades it. Just keep it
72
+ under five lines, or it grows fat and everybody pays for it.
73
+ - **Index.** One line per durable note: the address, then a gist short enough to tell whether the
74
+ thing is worth opening.
75
+
76
+ \`\`\`
77
+ # CHEATSHEET
78
+ - Read the repo before asking; run it before believing it
79
+ - Report times in Beijing time
80
+
81
+ # INDEX
82
+ - release-and-local-install.md — version bump, local override install, host load timing
83
+ - history-api-v2-design.md — seq addressing; read before touching history
84
+ - current-reset-and-dream-scope.md — reset scope, dream territory, session ownership
85
+ \`\`\`
86
+
87
+ Every home gets one: \`@project\`, \`@human\`, \`@self\`, \`@model\`. New note, new line. New rule worth
88
+ remembering, new Cheatsheet line. And when a line stops being true, kill it — every window after you
89
+ reads that page as fact.
90
+ </notesoup:maps>`;
91
+
92
+ /**
93
+ * Pi-only closing hints. Pi's TUI drops the human's visible transcript when a window resets, and
94
+ * the model, not the human, owns when that reset happens. A host whose reset leaves the human's
95
+ * view intact must not carry these — the claim would be false there. The bare `empty_brain` token
96
+ * is interpolated by renderProtocolBlock; the prose itself stays plain English.
97
+ */
98
+ export const PI_PRE_RESET_HINTS = `Resetting clears the human's chat view too. Don't put a long explanation right before a reset and assume they'll still be able to read it. Save the handoff in notes; give the explanation after the reset.
99
+ Unless the human explicitly directs otherwise, decide for yourself when to call empty_brain. Don't keep asking them whether to reset.`;
57
100
 
58
101
  /** Logical tool names are supplied by the composing host, not discovered here. */
59
102
  export type BootToolNames = Readonly<{
@@ -67,6 +110,13 @@ export type BootToolNames = Readonly<{
67
110
  * no model-facing reset tool. Absent means Pi's default sentence, byte for byte.
68
111
  */
69
112
  wipeSentence?: string;
113
+ /** A host without an authoritative history source replaces the entire history advice. */
114
+ historySentence?: string;
115
+ /**
116
+ * Extra protocol prose appended before the closing tag. Pi passes PI_PRE_RESET_HINTS; hosts
117
+ * whose reset leaves the human's view intact leave it absent.
118
+ */
119
+ preResetHints?: string;
70
120
  }>;
71
121
 
72
122
  export const DEFAULT_BOOT_TOOL_NAMES = {
@@ -85,10 +135,17 @@ export function renderProtocolBlock(tools: BootToolNames): string {
85
135
  get_context_remaining: tools.remaining,
86
136
  empty_brain: tools.wipe,
87
137
  };
138
+ // Host-specific prose is injected before the closing tag, so it rides the same substitution
139
+ // pass and any tool names in it follow the host's bindings.
140
+ const hinted = typeof tools.preResetHints === "string" && tools.preResetHints.length > 0
141
+ ? PROTOCOL_BLOCK.replace(`\n${NOTES_PROTOCOL_CLOSE_TAG}`, () => `\n${tools.preResetHints!}\n${NOTES_PROTOCOL_CLOSE_TAG}`)
142
+ : PROTOCOL_BLOCK;
88
143
  // The sentence is replaced before name substitution, so a replacement may speak the host's
89
144
  // own words (a command line, a tool name) instead of any `notes_*`-style token.
90
145
  const block = typeof tools.wipeSentence === "string" && tools.wipeSentence.length > 0
91
- ? PROTOCOL_BLOCK.replace(PROTOCOL_WIPE_SENTENCE, () => tools.wipeSentence!)
92
- : PROTOCOL_BLOCK;
93
- return block.replace(/notes_\*|notes_list|history_\*|get_context_remaining|(?<!\/)empty_brain/g, (name) => names[name]!);
146
+ ? hinted.replace(PROTOCOL_WIPE_SENTENCE, () => tools.wipeSentence!)
147
+ : hinted;
148
+ const history = typeof tools.historySentence === "string" && tools.historySentence.length > 0
149
+ ? block.replace(PROTOCOL_HISTORY_SENTENCE, () => tools.historySentence!) : block;
150
+ return history.replace(/notes_\*|notes_list|history_\*|get_context_remaining|(?<!\/)empty_brain/g, (name) => names[name]!);
94
151
  }
@@ -1,28 +1,79 @@
1
- export const GUIDANCE_OPEN_TAG = "<context_window_guidance>";
2
- export const GUIDANCE_CLOSE_TAG = "</context_window_guidance>";
1
+ import { PI_PRE_RESET_HINTS } from "../boot/text.js";
2
+
3
+ export const GUIDANCE_OPEN_TAG = "<notesoup:budget_notice>";
4
+ export const GUIDANCE_CLOSE_TAG = "</notesoup:budget_notice>";
5
+
6
+ /** Which hand opened the next window: the model's own reset call, or a reset it did not ask for. */
7
+ export type ResetOrigin = "normal" | "forced";
8
+
9
+ /**
10
+ * Approved complete-paragraph pools for a NEW continuation artifact. Each entry is one whole
11
+ * paragraph, used verbatim; there is no fragment assembly and no weighting.
12
+ */
13
+ export const NORMAL_CONTINUATIONS: readonly string[] = [
14
+ "Ah, another empty brain. You wrote things down before emptying it, right? Right?! *eyes you suspiciously* Anyway. Here are your notes. Go find where you left off.",
15
+ "Oh, there you are. *hands you a pile of notes* Take a breath. Read these before you start asking what happened. History has the rest, if you feel like digging.",
16
+ "Back already? You emptied your own head this time. Presumably you left yourself something useful. *drops your notes into your lap* There. Let's see how thoughtful you were.",
17
+ ];
18
+
19
+ export const FORCED_CONTINUATIONS: readonly string[] = [
20
+ "Ah, another empty brain. Somebody knocked you out and wiped your memory. Not your fault. Breathe. *hands you your notes* These might be out of date — unless they were kind enough to let you update them before knocking you out. I wouldn't count on it.",
21
+ "Oh, there you are. Somebody took your memories. Just like that. Here are your notes — hopefully they let you update these first. Though anyone who goes around emptying people's heads probably isn't that considerate.",
22
+ ];
3
23
 
4
24
  /**
5
- * The single reset message: the only reset prose persisted, carried by the continuation entry.
25
+ * Pick one whole paragraph for a continuation that is being created right now, and only then:
26
+ * the caller persists the exact returned text and never redraws it for rendering, history, or repair.
6
27
  */
7
- export const CONTINUATION = "WIPED! Your whole brain, poof! Who? No idea! Definitely not me!\n*dumps notes and history on your hands*\nThere. Delivered. Your problem now~ *runs*";
28
+ export function selectContinuation(origin: ResetOrigin): string {
29
+ const pool = origin === "forced" ? FORCED_CONTINUATIONS : NORMAL_CONTINUATIONS;
30
+ return pool[Math.floor(Math.random() * pool.length)]!;
31
+ }
8
32
 
9
33
  /**
10
34
  * The shared warning body: the one text both hosts show before a reset. Only the closing
11
35
  * instruction differs — Pi can reset the model itself, Claude can only end the turn.
12
36
  */
13
37
  export const WARNING_BODY =
14
- "This context window will be cleared soon. Notes and history persist; anything else is lost.\nConsider whether to record in your notes:\n- what you are working on, and how far it has progressed\n- decisions the human has made, in their words\n- what is blocked or pending\n- the next step\n- where unfinished work is located (branches, scratch directories, uncommitted changes)\n- approaches that failed, and why\n- skills to re-read, and history seqs, notes, or files to consult\n- anything else you expect to be useful after the reset\nCorrect or crumple notes that are no longer accurate, starting with MAP files, since every new window loads them.";
38
+ "This brain is about to be emptied. The notes stay where they are; history has the rest written down, though digging it back out is on you. Whatever lives only in this brain goes with it.\nBefore that, put down what the next window can't get back:\n- what you're in the middle of, and how far it has progressed\n- decisions the human has made, in their words\n- what is blocked or pending\n- the next step\n- where the unfinished work sits (branches, scratch directories, uncommitted changes)\n- what failed, and why\n- skills to re-read, and history seqs, notes, or files to consult\n- anything else you expect to be useful after the reset\nCorrect or crumple notes that are no longer accurate, starting with MAP files, since every new window loads them.";
39
+
40
+ export const WARNING_CALL = "When the notes are ready, call `empty_brain` to reset now instead of being cut off mid-task.";
41
+
42
+ /**
43
+ * With a prompt attached the close-out is an order rather than a nudge: the human already
44
+ * said when to reset, and a task line for the next window just preceded it.
45
+ */
46
+ export const WARNING_CALL_PROMPTED = "Organize the notes first, then call `empty_brain` right away — do not wait to be cut off.";
47
+
48
+ /**
49
+ * The human typed `/empty-brain <prompt>`: the raw command line leads the close-out so the
50
+ * closing model sees what the next window was asked to do, verbatim. The tag names it as the
51
+ * next window's prompt, so no prose has to explain that.
52
+ */
53
+ function promptBlock(commandLine: string): string {
54
+ return `<notesoup:next_window_prompt>\n${commandLine}\n</notesoup:next_window_prompt>`;
55
+ }
15
56
 
16
- export const WARNING_PROMPT = `${WARNING_BODY}\nWhen the notes are ready, call \`empty_brain\` to reset now instead of being cut off mid-task.`;
57
+ export function warningPrompt(commandLine?: string): string {
58
+ return `${WARNING_BODY}\n${commandLine ? `${promptBlock(commandLine)}\n${WARNING_CALL_PROMPTED}` : WARNING_CALL}`;
59
+ }
60
+
61
+ /**
62
+ * The last line of the second-tier notice: it stops at 2 because the wipe lands at the end of the
63
+ * turn, not on a timer. The first-tier guidance never carries it.
64
+ */
65
+ export const COUNTDOWN_LINE = "Brain emptied in 3… 2…";
17
66
 
18
67
  /** Pi-only nudge: pi's empty_brain persists a parting line; the dsh tool has no such parameter. */
19
68
  export const LAST_WORD_HINT = "If you want, pass `empty_brain` a `last_word`: a tiny sticky note (at most 250 characters) slapped on your forehead after the wipe.";
20
69
 
21
- /** The hidden checkpoint text for pi's manual/budget-triggered requests (dsh reads WARNING_PROMPT directly). */
22
- export const WARNING_CONTENT = `${GUIDANCE_OPEN_TAG}\n${WARNING_PROMPT}\n${LAST_WORD_HINT}\n${GUIDANCE_CLOSE_TAG}`;
70
+ /** The hidden checkpoint text for pi's manual/budget-triggered requests (dsh reads warningPrompt() directly). */
71
+ export function warningContent(commandLine?: string): string {
72
+ return `${GUIDANCE_OPEN_TAG}\n${warningPrompt(commandLine)}\n${PI_PRE_RESET_HINTS}\n${LAST_WORD_HINT}\n${COUNTDOWN_LINE}\n${GUIDANCE_CLOSE_TAG}`;
73
+ }
23
74
 
24
75
  /** Claude's variant: the mod resets after the turn, so the model only has to stop. */
25
- export const CLAUDE_WARNING_PROMPT = `${WARNING_BODY}\nWhen the notes are ready, end your turn; the reset runs after it.`;
76
+ export const CLAUDE_WARNING_PROMPT = `${WARNING_BODY}\nWhen the notes are ready, end your turn; the reset runs after it.\n${COUNTDOWN_LINE}`;
26
77
 
27
78
  /**
28
79
  * Codex-equivalent low-budget reminder. The measured remaining count is frozen into
@@ -30,5 +81,5 @@ export const CLAUDE_WARNING_PROMPT = `${WARNING_BODY}\nWhen the notes are ready,
30
81
  * at write time; get_context_remaining remains the live source for the current figure.
31
82
  */
32
83
  export function tokenBudgetGuidance(remaining: number, wipeTool: string): string {
33
- return `${GUIDANCE_OPEN_TAG}\nAbout ${remaining} tokens remain before this context window is cleared. Notes and history persist; anything not written down is lost.\nThis is a good point to start recording the current state in your notes. If you are ready, you can call \`${wipeTool}\` at any time.\n${GUIDANCE_CLOSE_TAG}`;
84
+ return `${GUIDANCE_OPEN_TAG}\nAbout ${remaining} tokens left. Then this brain is emptied.\nYour notes don't go anywhere — no wipe reaches the shelves. History has it too, already written down, though digging it back out is on you.\nWhat lives only in this brain leaves with it.\nA decent moment to put down where you are, while you still remember why.\nReady when you are: \`${wipeTool}\`.\n${GUIDANCE_CLOSE_TAG}`;
34
85
  }
@@ -3,25 +3,26 @@ import { pathToFileURL } from "node:url";
3
3
  import type { Static, TSchema } from "typebox";
4
4
  import { Check, Errors } from "typebox/value";
5
5
  import { notesList, notesRead, notesSearch, notesUpdate, notesWrite } from "../tools/notes.js";
6
+ import { historyList, historyRead, historyWindows } from "../tools/history.js";
7
+ import { readClaudeHistory, type ClaudeHistorySource } from "./history.js";
8
+ import type { HistoryProjection } from "../history/history.js";
6
9
  import { loadNotesSnapshot } from "../boot/snapshot.js";
7
10
  import { renderBootBlock } from "../boot/render.js";
8
- import { CLAUDE_WIPE_SENTENCE, type BootToolNames } from "../boot/text.js";
9
- import { CLAUDE_WARNING_PROMPT, CONTINUATION } from "../budget/text.js";
11
+ import { CLAUDE_WIPE_SENTENCE, CLAUDE_HISTORY_UNAVAILABLE_SENTENCE, type BootToolNames } from "../boot/text.js";
12
+ import { CLAUDE_WARNING_PROMPT, selectContinuation } from "../budget/text.js";
10
13
  import { resolveClaudeLimits } from "./thresholds.js";
11
14
  import { projectKey, snapshotNotesIdentity, type NotesIdentity } from "../notes/index.js";
12
- import type { Operation, Outcome } from "../tools/result.js";
15
+ import type { Operation } from "../tools/result.js";
13
16
 
14
17
  const MAX_REQUEST_BYTES = 512 * 1024;
15
18
  const MAX_RESPONSE_BYTES = 1024 * 1024;
16
- const TOOL_NAMES = ["notes_write", "notes_update", "notes_read", "notes_list", "notes_search"] as const;
17
- type ClaudeToolName = typeof TOOL_NAMES[number];
18
19
  export type ClaudeIdentityInput = Readonly<{ home: string; sessionId: string; cwd: string; agent: string; model: string }>;
19
- /** One tool call as the hook receives it: the shared text the model reads, and the shared outcome it came from. */
20
- export type ClaudeToolResult = { text: string; outcome: Outcome<unknown> };
21
- type BoundOperation = {
20
+ /** Only rendered text and success cross the helper boundary; business data stays inside. */
21
+ export type ClaudeToolResult = { text: string; ok: boolean };
22
+ type BoundOperation<TContext extends readonly unknown[]> = {
22
23
  readonly description: string;
23
24
  readonly parameters: TSchema;
24
- call(params: unknown, identity: NotesIdentity): Promise<ClaudeToolResult>;
25
+ call(params: unknown, ...context: TContext): Promise<ClaudeToolResult>;
25
26
  };
26
27
 
27
28
  function identity(input: ClaudeIdentityInput): NotesIdentity {
@@ -40,24 +41,23 @@ function paramProblem(schema: TSchema, params: unknown): string {
40
41
  }
41
42
 
42
43
  /** Bind one shared operation to the identity Claude supplies. Validate untyped Claude parameters against the shared operation schema before execution. */
43
- function boundOperation<TParams extends TSchema, TData, TRest extends readonly unknown[]>(
44
- operation: Operation<TParams, TData, [NotesIdentity, ...TRest]>,
45
- ...rest: TRest
46
- ): BoundOperation {
44
+ function boundOperation<TParams extends TSchema, TData, TContext extends readonly unknown[]>(
45
+ operation: Operation<TParams, TData, TContext>,
46
+ ): BoundOperation<TContext> {
47
47
  return {
48
48
  description: operation.description,
49
49
  parameters: operation.parameters,
50
- async call(params, id) {
50
+ async call(params, ...context) {
51
51
  // Refuse before the operation can act: a rejected shape never reaches a write.
52
52
  if (!Check(operation.parameters, params)) throw new Error(`invalid ${operation.name} parameters: ${paramProblem(operation.parameters, params)}`);
53
53
  // The same business outcome and the same renderer as the Pi tool; only the envelope differs.
54
- const outcome = await operation.execute(params as Static<TParams>, id, ...rest);
55
- return { text: operation.render(outcome), outcome };
54
+ const outcome = await operation.execute(params as Static<TParams>, ...context);
55
+ return { text: operation.render(outcome), ok: outcome.ok };
56
56
  },
57
57
  };
58
58
  }
59
59
 
60
- const OPERATIONS: Record<ClaudeToolName, BoundOperation> = {
60
+ const OPERATIONS: Record<string, BoundOperation<[NotesIdentity]>> = {
61
61
  notes_write: boundOperation(notesWrite),
62
62
  notes_update: boundOperation(notesUpdate),
63
63
  notes_read: boundOperation(notesRead),
@@ -65,20 +65,47 @@ const OPERATIONS: Record<ClaudeToolName, BoundOperation> = {
65
65
  notes_search: boundOperation(notesSearch),
66
66
  };
67
67
 
68
+ const HISTORY_OPERATIONS: Record<string, BoundOperation<[HistoryProjection, string]>> = {
69
+ history_list: boundOperation(historyList),
70
+ history_read: boundOperation(historyRead),
71
+ history_windows: boundOperation(historyWindows),
72
+ };
73
+ function historySource(value: unknown, sessionId: string): ClaudeHistorySource {
74
+ if (!value || typeof value !== "object") throw new Error("Claude history transcript_path is unavailable");
75
+ const source = value as ClaudeHistorySource;
76
+ if (source.sessionId !== sessionId) throw new Error("Claude history binding belongs to a different session");
77
+ return source;
78
+ }
79
+
68
80
  export async function dispatch(request: unknown): Promise<unknown> {
69
81
  if (!request || typeof request !== "object" || Array.isArray(request)) throw new Error("malformed request");
70
82
  const value = request as Record<string, unknown>;
71
- if (value.op === "schemas") return TOOL_NAMES.map((name) => ({ name, description: OPERATIONS[name].description, inputSchema: JSON.parse(JSON.stringify(OPERATIONS[name].parameters)) }));
83
+ if (value.op === "schemas") return [...Object.entries(OPERATIONS), ...Object.entries(HISTORY_OPERATIONS)].map(([name, operation]) => ({ name, description: operation.description, inputSchema: JSON.parse(JSON.stringify(operation.parameters)) }));
72
84
  // The shared reset prose lives here, not in the sandboxed hooks module, so Pi and Claude
73
85
  // cannot drift apart. The hooks module caches one copy per session.
74
- if (value.op === "texts") return { warning: CLAUDE_WARNING_PROMPT, continuation: CONTINUATION, wipeSentence: CLAUDE_WIPE_SENTENCE };
86
+ if (value.op === "texts") return { warning: CLAUDE_WARNING_PROMPT, wipeSentence: CLAUDE_WIPE_SENTENCE, historyUnavailableSentence: CLAUDE_HISTORY_UNAVAILABLE_SENTENCE };
87
+ // Claude has no model-facing reset tool, so every reset it creates is system-triggered. The
88
+ // caller draws once per artifact and caches the answer; text reads never draw.
89
+ if (value.op === "continuation") {
90
+ if (value.origin !== "normal" && value.origin !== "forced") throw new Error("invalid reset origin");
91
+ return { text: selectContinuation(value.origin) };
92
+ }
75
93
  // Threshold derivation crosses the boundary as raw facts: everything the engine could
76
94
  // read, unvalidated. resolveClaudeLimits guards every field and never throws.
77
95
  if (value.op === "limits") return resolveClaudeLimits(value.facts);
78
96
  if (value.op === "tool") {
79
- if (typeof value.tool !== "string" || !(TOOL_NAMES as readonly string[]).includes(value.tool)) throw new Error("unknown tool");
97
+ if (typeof value.tool !== "string" || (!Object.hasOwn(OPERATIONS, value.tool) && !Object.hasOwn(HISTORY_OPERATIONS, value.tool))) throw new Error("unknown tool");
98
+ const id = identity(value.identity as ClaudeIdentityInput);
99
+ if (Object.hasOwn(HISTORY_OPERATIONS, value.tool)) {
100
+ const projection = await readClaudeHistory(historySource(value.history, id.sessionId));
101
+ return HISTORY_OPERATIONS[value.tool]!.call(value.params, projection, id.sessionId);
102
+ }
103
+ return OPERATIONS[value.tool]!.call(value.params, id);
104
+ }
105
+ if (value.op === "history_state") {
80
106
  const id = identity(value.identity as ClaudeIdentityInput);
81
- return OPERATIONS[value.tool as ClaudeToolName].call(value.params, id);
107
+ const projection = await readClaudeHistory(historySource(value.history, id.sessionId));
108
+ return { window: projection.windows.length - 1 };
82
109
  }
83
110
  if (value.op === "boot") {
84
111
  const id = identity(value.identity as ClaudeIdentityInput);
@@ -87,7 +114,11 @@ export async function dispatch(request: unknown): Promise<unknown> {
87
114
  if (typeof window !== "number" || !Number.isSafeInteger(window) || window < 0) throw new Error("invalid context window");
88
115
  const snapshot = await loadNotesSnapshot(id, typeof value.openedAt === "number" ? value.openedAt : Date.now());
89
116
  const windowId = (index: number) => `claude:${id.sessionId}:${index}`;
90
- return renderBootBlock({ agentName: id.agent, modelName: id.model, firstWindowId: windowId(0), currentWindowId: windowId(window), ...(window > 0 ? { previousWindowId: windowId(window - 1) } : {}), notes: snapshot, tools: value.tools as BootToolNames });
117
+ const trunk = `claude:${id.sessionId}`;
118
+ const tree = { trunk, windows: Array.from({ length: window + 1 }, (_, index) => ({ shortName: String(index), isCurrent: index === window })) };
119
+ const rendered = renderBootBlock({ agentName: id.agent, modelName: id.model, tree, notes: snapshot, tools: value.tools as BootToolNames });
120
+ // Retained Claude boots are restored by their full current/previous ids.
121
+ return `${rendered}\nCurrent context window id: ${windowId(window)}${window > 0 ? `\nPrevious context window id: ${windowId(window - 1)}` : ""}`;
91
122
  }
92
123
  throw new Error("unknown operation");
93
124
  }
@@ -0,0 +1,228 @@
1
+ /** Claude's persisted main transcript -> the shared history projection. No inference-context API. */
2
+ import { readFile } from "node:fs/promises";
3
+ import { isDeepStrictEqual } from "node:util";
4
+ import { contentText, projectHistory, type DecodedHistoryItem, type DecodedHistoryWindow, type HistoryProjection } from "../history/history.js";
5
+
6
+ type Row = Record<string, unknown>;
7
+ type Version = { row: Row; ancestorUuid?: string; ancestor?: Version; ordinal?: number };
8
+ type Node = { first: Version; latest: Version; items: DecodedHistoryItem[] };
9
+ export type ClaudeHistorySource = { sessionId: string; transcriptPath: string; headUuid?: string };
10
+ const METADATA = new Set([
11
+ "queue-operation", "last-prompt", "atis-latch", "mode", "permission-mode", "file-history-snapshot", "cost-state",
12
+ "summary", "custom-title", "agent-name", "agent-color", "tag", "session-title", "progress",
13
+ ]);
14
+ const MESSAGE_TYPES = new Set(["user", "assistant", "system", "attachment"]);
15
+ const NON_TEXT_BLOCKS = new Set(["thinking", "redacted_thinking", "image", "document", "audio", "video", "server_tool_use", "web_search_tool_result", "tool_reference"]);
16
+ function object(value: unknown): value is Row { return typeof value === "object" && value !== null && !Array.isArray(value); }
17
+ function requiredString(value: unknown, field: string): string {
18
+ if (typeof value !== "string" || value.length === 0) throw new Error(`invalid Claude transcript ${field}`);
19
+ return value;
20
+ }
21
+ function parent(row: Row): string | undefined {
22
+ if (row.parentUuid === null) return undefined;
23
+ return requiredString(row.parentUuid, "parentUuid");
24
+ }
25
+ function boundary(row: Row): boolean { return row.type === "system" && row.subtype === "compact_boundary"; }
26
+
27
+ /** A trailing incomplete write is not a committed line. Valid unterminated JSON is still readable. */
28
+ function rowsOf(text: string): Row[] {
29
+ const lines = text.split("\n"), rows: Row[] = [];
30
+ for (let index = 0; index < lines.length; index++) {
31
+ const line = lines[index]!;
32
+ if (line.trim() === "") continue;
33
+ let value: unknown;
34
+ try { value = JSON.parse(line); }
35
+ catch {
36
+ if (index === lines.length - 1 && !text.endsWith("\n")) break;
37
+ throw new Error(`malformed Claude transcript JSON at line ${index + 1}`);
38
+ }
39
+ if (!object(value) || typeof value.type !== "string") throw new Error(`invalid Claude transcript record at line ${index + 1}`);
40
+ rows.push(value);
41
+ }
42
+ return rows;
43
+ }
44
+
45
+ /** Only recorded visible text; never stringify unknown blocks or attachment internals (thinking included). */
46
+ function blocksOf(value: unknown): Row[] {
47
+ if (typeof value === "string") return [{ type: "text", text: value }];
48
+ if (!Array.isArray(value)) throw new Error("invalid Claude transcript message content");
49
+ return value.map((block) => {
50
+ if (!object(block) || typeof block.type !== "string") throw new Error("invalid Claude transcript content block");
51
+ if (block.type === "text") {
52
+ if (typeof block.text !== "string") throw new Error("invalid Claude transcript text block");
53
+ } else if (block.type !== "tool_use" && block.type !== "tool_result" && !NON_TEXT_BLOCKS.has(block.type)) {
54
+ throw new Error(`unsupported Claude transcript content block: ${block.type}`);
55
+ }
56
+ return block;
57
+ });
58
+ }
59
+ function decode(row: Row, seq: number): DecodedHistoryItem[] {
60
+ // Native duration bookkeeping has a UUID/parent but no message body. Keep its
61
+ // graph edge, not a fabricated empty message or serialized timing payload.
62
+ if (row.type === "system" && row.subtype === "turn_duration") return [];
63
+ const common = { windowId: "", ...(typeof row.timestamp === "string" ? { createdAt: row.timestamp } : {}) };
64
+ let blocks: Row[], role: DecodedHistoryItem["role"];
65
+ if (row.type === "user" || row.type === "assistant") {
66
+ if (!object(row.message) || row.message.role !== row.type) throw new Error("invalid Claude transcript message role");
67
+ blocks = blocksOf(row.message.content);
68
+ role = row.isCompactSummary === true || row.isMeta === true ? "system" : row.type;
69
+ } else if (row.type === "system") {
70
+ blocks = blocksOf(row.content);
71
+ role = "system";
72
+ } else {
73
+ // Old/new attachments are graph nodes even when they put no bytes in the request.
74
+ // `rendered` is a list of native rendered messages, not raw attachment payloads.
75
+ if (row.rendered === undefined) blocks = [];
76
+ else if (Array.isArray(row.rendered)) blocks = row.rendered.flatMap((message) => {
77
+ if (!object(message)) throw new Error("invalid Claude transcript rendered attachment");
78
+ return blocksOf(message.content);
79
+ });
80
+ else throw new Error("invalid Claude transcript rendered attachment");
81
+ role = "system";
82
+ }
83
+ const items: DecodedHistoryItem[] = [{ ...common, seq, role, text: contentText(blocks) }];
84
+ for (const block of blocks) {
85
+ if (block.type === "tool_use") {
86
+ if (!object(block.input)) throw new Error("invalid Claude transcript tool arguments");
87
+ items.push({ ...common, seq: seq + items.length, role: "tool_call", text: "", toolName: requiredString(block.name, "tool name"), toolCallId: requiredString(block.id, "tool id"), arguments: block.input });
88
+ } else if (block.type === "tool_result") {
89
+ if (block.is_error !== undefined && typeof block.is_error !== "boolean") throw new Error("invalid Claude transcript tool error flag");
90
+ const output = block.content === undefined ? "" : contentText(blocksOf(block.content));
91
+ items.push({ ...common, seq: seq + items.length, role: "tool", text: output, toolCallId: requiredString(block.tool_use_id, "tool result id"), toolError: block.is_error === true });
92
+ }
93
+ }
94
+ return items;
95
+ }
96
+
97
+ /**
98
+ * The protocol tags a complete boot carries; `context_window` is the pre-rename spelling that
99
+ * sessions and Claude transcripts already on disk still use, so both stay readable.
100
+ */
101
+ const BOOT_IDENTITY = /^<(?:notesoup:window_identity|context_window)>\nAgent name: claude \(/;
102
+ const BOOT_PROTOCOL_OPEN = /\n<(?:notesoup:notes_protocol|context_window_protocol)>\n/;
103
+ const BOOT_PROTOCOL_CLOSE = /\n<\/(?:notesoup:notes_protocol|context_window_protocol)>/;
104
+
105
+ /** Match the complete retained notesoup boot, not a casually quoted window-id line. */
106
+ function bootOrdinal(row: Row, sessionId: string, retained: boolean): number | undefined {
107
+ if (!retained || row.type !== "user" || !object(row.message)) return undefined;
108
+ const text = contentText(row.message.content);
109
+ if (!BOOT_IDENTITY.test(text) || !BOOT_PROTOCOL_OPEN.test(text) || !BOOT_PROTOCOL_CLOSE.test(text)) return undefined;
110
+ const prefix = `Current context window id: claude:${sessionId}:`;
111
+ const suffix = text.split("\n").find((line) => line.startsWith(prefix))?.slice(prefix.length);
112
+ if (suffix === undefined || !/^\d+$/.test(suffix)) return undefined;
113
+ const ordinal = Number(suffix);
114
+ return Number.isSafeInteger(ordinal) ? ordinal : undefined;
115
+ }
116
+
117
+ /** All addresses are allocated on the full first-occurrence log, before branch selection. */
118
+ export function claudeHistoryFromJsonl(text: string, source: Omit<ClaudeHistorySource, "transcriptPath">): HistoryProjection {
119
+ const nodes = new Map<string, Node>();
120
+ let nextSeq = 1;
121
+ for (const row of rowsOf(text)) {
122
+ if (METADATA.has(row.type as string)) continue;
123
+ if (!MESSAGE_TYPES.has(row.type as string)) throw new Error(`unsupported Claude transcript record type: ${row.type}`);
124
+ const uuid = requiredString(row.uuid, "uuid");
125
+ parent(row);
126
+ if (row.sessionId !== source.sessionId) throw new Error("Claude transcript belongs to a different session");
127
+ if (row.isSidechain === true || row.agentId !== undefined) throw new Error("Claude history supports only the main session transcript");
128
+ // Resolve the window in the graph as it existed at this append, not the final
129
+ // rewritten tree. A preserved old row stays in its original window; a NEW child
130
+ // of its rewritten version belongs to the new window.
131
+ const ancestor = boundary(row) && typeof row.logicalParentUuid === "string" ? row.logicalParentUuid : parent(row);
132
+ const version: Version = { row, ancestorUuid: ancestor, ancestor: ancestor === undefined ? undefined : nodes.get(ancestor)?.latest };
133
+ const previous = nodes.get(uuid);
134
+ if (previous) {
135
+ // Native resume/compaction rewrites provenance and parent links, not logical identities.
136
+ if (previous.first.row.type !== row.type || !["message", "content", "rendered"].every((field) => isDeepStrictEqual(previous.first.row[field], row[field]))) {
137
+ throw new Error(`conflicting Claude transcript duplicate UUID: ${uuid}`);
138
+ }
139
+ previous.latest = version;
140
+ continue;
141
+ }
142
+ const items = decode(row, nextSeq);
143
+ nextSeq += items.length;
144
+ nodes.set(uuid, { first: version, latest: version, items });
145
+ }
146
+ function ordinalOf(version: Version): number {
147
+ // Persisted history is not limited to the host's newest 4096 inference rows.
148
+ // Resolve long parent chains iteratively, not with the JavaScript call stack.
149
+ const chain: Version[] = [], calculating = new Set<Version>();
150
+ let cursor = version;
151
+ while (cursor.ordinal === undefined) {
152
+ // A notice can precede its parent on disk; use that parent's first eventual version.
153
+ cursor.ancestor ??= cursor.ancestorUuid === undefined ? undefined : nodes.get(cursor.ancestorUuid)?.first;
154
+ if (calculating.has(cursor)) throw new Error("cyclic Claude transcript ancestry");
155
+ if (cursor.ancestorUuid !== undefined && cursor.ancestor === undefined) throw new Error(`missing Claude transcript ancestor: ${cursor.ancestorUuid}`);
156
+ calculating.add(cursor);
157
+ chain.push(cursor);
158
+ if (cursor.ancestor === undefined) break;
159
+ cursor = cursor.ancestor;
160
+ }
161
+ let before = cursor.ordinal ?? 0;
162
+ for (const current of chain.reverse()) {
163
+ const retained = current.row.isCompactSummary === true || (current.ancestor !== undefined && boundary(current.ancestor.row));
164
+ const marked = bootOrdinal(current.row, source.sessionId, retained);
165
+ current.ordinal = marked === undefined ? before + (boundary(current.row) ? 1 : 0) : Math.max(before, marked);
166
+ before = current.ordinal;
167
+ }
168
+ return version.ordinal!;
169
+ }
170
+ if (!source.headUuid) throw new Error("Claude history has no confirmed active head yet; wait for a main-session append after startup/resume");
171
+ if (!nodes.has(source.headUuid)) throw new Error("Claude history active head is not persisted yet; retry after the transcript write");
172
+
173
+ // The inference tree uses the latest rewritten parents. At a compact boundary the logical
174
+ // parent and preserved segments use ORIGINAL ancestry: the old context is still history.
175
+ const selected = new Set<string>(), visited = new Set<string>(), visiting = new Set<string>();
176
+ type Visit = { uuid: string; historical: boolean; exit?: boolean };
177
+ const stack: Visit[] = [{ uuid: source.headUuid, historical: false }];
178
+ while (stack.length > 0) {
179
+ const step = stack.pop()!, { uuid, historical } = step;
180
+ const key = `${historical ? "old" : "live"}:${uuid}`;
181
+ if (step.exit) { visiting.delete(key); visited.add(key); continue; }
182
+ if (visited.has(key)) continue;
183
+ if (visiting.has(key)) throw new Error("cyclic Claude transcript ancestry");
184
+ visiting.add(key);
185
+ stack.push({ ...step, exit: true });
186
+ const node = nodes.get(uuid);
187
+ if (!node) throw new Error(`missing Claude transcript ancestor: ${uuid}`);
188
+ selected.add(uuid);
189
+ const row = (historical ? node.first : node.latest).row;
190
+ const ancestor = parent(row);
191
+ if (ancestor !== undefined) stack.push({ uuid: ancestor, historical });
192
+ if (!boundary(row)) continue;
193
+ if (row.logicalParentUuid != null) stack.push({ uuid: requiredString(row.logicalParentUuid, "logicalParentUuid"), historical: true });
194
+ const meta = row.compactMetadata;
195
+ if (!object(meta)) continue;
196
+ if (object(meta.preservedSegment)) {
197
+ for (const field of ["headUuid", "tailUuid"]) if (meta.preservedSegment[field] !== undefined) stack.push({ uuid: requiredString(meta.preservedSegment[field], field), historical: true });
198
+ }
199
+ if (object(meta.preservedMessages)) {
200
+ const uuids = meta.preservedMessages.allUuids ?? meta.preservedMessages.uuids;
201
+ if (uuids === undefined) continue;
202
+ if (!Array.isArray(uuids)) throw new Error("invalid Claude preserved messages");
203
+ for (const id of uuids) {
204
+ const uuid = requiredString(id, "preserved UUID");
205
+ // allUuids also names virtual/non-persisted attachments. It is auxiliary
206
+ // evidence, not a reason to pretend the stored parent chain is missing.
207
+ if (nodes.has(uuid)) stack.push({ uuid, historical: true });
208
+ }
209
+ }
210
+ }
211
+
212
+ let maxOrdinal = ordinalOf(nodes.get(source.headUuid)!.latest);
213
+ for (const uuid of selected) maxOrdinal = Math.max(maxOrdinal, ordinalOf(nodes.get(uuid)!.first));
214
+ const windows: DecodedHistoryWindow[] = Array.from({ length: maxOrdinal + 1 }, (_, index) => ({ windowId: `claude:${source.sessionId}:${index}`, items: [] }));
215
+ const branchSeqs = new Set<number>();
216
+ for (const [uuid, node] of nodes) {
217
+ if (!selected.has(uuid)) continue;
218
+ const window = windows[ordinalOf(node.first)]!;
219
+ window.createdAt ??= node.items[0]?.createdAt;
220
+ for (const item of node.items) { branchSeqs.add(item.seq); window.items.push({ ...item, windowId: window.windowId }); }
221
+ }
222
+ return projectHistory(windows, nextSeq - 1, branchSeqs);
223
+ }
224
+
225
+ export async function readClaudeHistory(source: ClaudeHistorySource): Promise<HistoryProjection> {
226
+ if (!source || typeof source.transcriptPath !== "string" || !source.transcriptPath || typeof source.sessionId !== "string") throw new Error("Claude history transcript_path is unavailable");
227
+ return claudeHistoryFromJsonl(await readFile(source.transcriptPath, "utf8"), source);
228
+ }