notesoup 0.51.8 → 0.52.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 (78) hide show
  1. package/README.md +3 -10
  2. package/dist/plugins/claude/src/history.js +3 -7
  3. package/dist/plugins/pi/notes/tools.d.ts +1 -1
  4. package/dist/plugins/pi/notes/tools.js +27 -7
  5. package/dist/plugins/pi/render.d.ts +40 -0
  6. package/dist/plugins/pi/render.js +168 -0
  7. package/dist/plugins/pi/runtime.js +3 -0
  8. package/dist/plugins/pi/tool-result.d.ts +5 -2
  9. package/dist/plugins/pi/tool-result.js +4 -1
  10. package/dist/src/dream/git.d.ts +2 -3
  11. package/dist/src/dream/git.js +3 -8
  12. package/dist/src/dream/lock.d.ts +10 -27
  13. package/dist/src/dream/lock.js +16 -79
  14. package/dist/src/notes/errors.d.ts +1 -1
  15. package/dist/src/notes/identity.d.ts +2 -0
  16. package/dist/src/notes/identity.js +3 -1
  17. package/dist/src/notes/store.d.ts +2 -0
  18. package/dist/src/notes/store.js +40 -4
  19. package/dist/src/tools/dream.d.ts +113 -0
  20. package/dist/src/tools/dream.js +112 -0
  21. package/dist/src/tools/notes.d.ts +15 -1
  22. package/dist/src/tools/notes.js +4 -4
  23. package/dist/test/claude-history.test.js +18 -2
  24. package/dist/test/claude-mod.test.js +115 -30
  25. package/dist/test/dependencies.test.js +3 -6
  26. package/dist/test/dream-skill.test.js +2 -3
  27. package/dist/test/dream-tools.test.js +67 -0
  28. package/dist/test/pi-render.test.js +89 -0
  29. package/docs/claude-code-mod.md +1 -1
  30. package/docs/notes-library.md +1 -1
  31. package/docs/skills.md +12 -15
  32. package/package.json +151 -149
  33. package/plugins/claude/.claude-plugin/plugin.json +1 -1
  34. package/plugins/claude/dist/claude/helper.js +30 -22
  35. package/plugins/claude/hooks/register.ts +52 -33
  36. package/plugins/claude/src/history.ts +3 -6
  37. package/plugins/pi/notes/tools.ts +26 -8
  38. package/plugins/pi/render.ts +165 -0
  39. package/plugins/pi/runtime.ts +3 -0
  40. package/plugins/pi/tool-result.ts +9 -1
  41. package/src/dream/git.ts +3 -8
  42. package/src/dream/lock.ts +18 -66
  43. package/src/notes/errors.ts +1 -1
  44. package/src/notes/identity.ts +4 -1
  45. package/src/notes/store.ts +37 -4
  46. package/src/tools/dream.ts +112 -0
  47. package/src/tools/notes.ts +4 -4
  48. package/dist/plugins/pi/dream/cli.d.ts +0 -10
  49. package/dist/plugins/pi/dream/cli.js +0 -173
  50. package/dist/plugins/pi/dream/runner.d.ts +0 -27
  51. package/dist/plugins/pi/dream/runner.js +0 -91
  52. package/dist/plugins/pi/dream/settings.d.ts +0 -7
  53. package/dist/plugins/pi/dream/settings.js +0 -17
  54. package/dist/src/dream/doctor.d.ts +0 -2
  55. package/dist/src/dream/doctor.js +0 -161
  56. package/dist/src/dream/gates.d.ts +0 -10
  57. package/dist/src/dream/gates.js +0 -26
  58. package/dist/src/dream/jail.d.ts +0 -11
  59. package/dist/src/dream/jail.js +0 -71
  60. package/dist/src/dream/report.d.ts +0 -7
  61. package/dist/src/dream/report.js +0 -34
  62. package/dist/src/dream/result.d.ts +0 -9
  63. package/dist/src/dream/settings.d.ts +0 -9
  64. package/dist/src/dream/settings.js +0 -16
  65. package/dist/test/doctor.test.js +0 -37
  66. package/dist/test/dream.test.d.ts +0 -1
  67. package/dist/test/dream.test.js +0 -150
  68. package/plugins/pi/dream/cli.ts +0 -118
  69. package/plugins/pi/dream/runner.ts +0 -92
  70. package/plugins/pi/dream/settings.ts +0 -17
  71. package/src/dream/doctor.ts +0 -118
  72. package/src/dream/gates.ts +0 -26
  73. package/src/dream/jail.ts +0 -62
  74. package/src/dream/report.ts +0 -32
  75. package/src/dream/result.ts +0 -2
  76. package/src/dream/settings.ts +0 -19
  77. /package/dist/{src/dream/result.js → test/dream-tools.test.d.ts} +0 -0
  78. /package/dist/test/{doctor.test.d.ts → pi-render.test.d.ts} +0 -0
package/README.md CHANGED
@@ -62,17 +62,10 @@ The reminder threshold is Pi's compaction reserve plus a margin, configured unde
62
62
  }
63
63
  ```
64
64
 
65
- The dreamer model is configured under the same key; `--dreamer <model pattern>` on the `dream` CLI wins, then a non-empty `notesoup.dreamer` string, then the automatic model:
66
-
67
- ```json
68
- {
69
- "notesoup": { "reminderMarginTokens": 24576, "dreamer": "anthropic/claude-sonnet-4-5" }
70
- }
71
- ```
72
-
73
65
  Environment variables:
74
66
 
75
67
  - `NOTESOUP_DISABLED` — presence-style kill switch: any value but an explicit no (`0`, `false`, `no`, `off`) turns notesoup off. On Pi the extension registers nothing at all; on Claude the mod passes every event through and native compaction behaves as if the mod were absent.
68
+ - `NOTESOUP_KEEP_MEMORY` — Claude only: keep Claude Code's auto-memory guidance, which notesoup omits by default (its summarization guidance is always omitted). Enabled by any non-empty value except `0`, `false`, `no`, or `off` (case-insensitive); read at session startup.
76
69
  - `NOTESOUP_HOME` — overrides the notes root (default `~/.agents/notes`).
77
70
  - `NOTESOUP_AGENT` — overrides the agent name on Pi (default `anonymous`).
78
71
 
@@ -83,7 +76,7 @@ Environment variables:
83
76
  - [Standalone notes library](docs/notes-library.md) — use the notes store from Node, no Pi required
84
77
  - [DeepSeek Harness](docs/dsh.md) — adapter and profile patch for dsh 0.2.1-alpha.2
85
78
  - [Claude Code Mod](docs/claude-code-mod.md) — early-access notes and persisted-session history tools for Claude Code
86
- - [Skills, dream, and the notes doctor](docs/skills.md) — `/skill:memory`, `/skill:dream`, `dream doctor`, the dream lock
79
+ - [Skills and dream](docs/skills.md) — `/skill:memory`, `/skill:dream`, the `dream_*` tools and the dream lock
87
80
 
88
81
  ## Development
89
82
 
@@ -100,7 +93,7 @@ The repository splits host-neutral code from host plugins:
100
93
  | Path | What it is |
101
94
  | --- | --- |
102
95
  | `src/` | The core: notes library, boot snapshot/renderer, history projection, budget policy and the shared tool operations. It never imports an SDK or a plugin. |
103
- | `plugins/pi/` | The Pi extension (`plugins/pi/index.ts` is what `pi.extensions` loads from source) and the `dream` CLI. |
96
+ | `plugins/pi/` | The Pi extension (`plugins/pi/index.ts` is what `pi.extensions` loads from source). |
104
97
  | `plugins/claude/` | The self-contained Claude Code plugin (`.claude-plugin/`, `hooks/`, bundled `dist/claude/helper.js`, skills and playbook), with its adapter sources in `plugins/claude/src/`. |
105
98
  | `plugins/dsh/` | The Cordis rows published as `notesoup/dsh` and `notesoup/dsh/engine`. |
106
99
 
@@ -2,10 +2,6 @@
2
2
  import { readFile } from "node:fs/promises";
3
3
  import { isDeepStrictEqual } from "node:util";
4
4
  import { contentText, projectHistory } from "../../../src/history/history.js";
5
- const METADATA = new Set([
6
- "queue-operation", "last-prompt", "atis-latch", "mode", "permission-mode", "file-history-snapshot", "cost-state",
7
- "summary", "custom-title", "agent-name", "agent-color", "tag", "session-title", "progress",
8
- ]);
9
5
  const MESSAGE_TYPES = new Set(["user", "assistant", "system", "attachment"]);
10
6
  const NON_TEXT_BLOCKS = new Set(["thinking", "redacted_thinking", "image", "document", "audio", "video", "server_tool_use", "web_search_tool_result", "tool_reference"]);
11
7
  function object(value) { return typeof value === "object" && value !== null && !Array.isArray(value); }
@@ -135,10 +131,10 @@ export function claudeHistoryFromJsonl(text, source) {
135
131
  const nodes = new Map();
136
132
  let nextSeq = 1;
137
133
  for (const row of rowsOf(text)) {
138
- if (METADATA.has(row.type))
139
- continue;
134
+ // Ignore non-message records, including future metadata. A skipped UUID that
135
+ // the selected branch actually requires still fails ancestry resolution below.
140
136
  if (!MESSAGE_TYPES.has(row.type))
141
- throw new Error(`unsupported Claude transcript record type: ${row.type}`);
137
+ continue;
142
138
  const uuid = requiredString(row.uuid, "uuid");
143
139
  parent(row);
144
140
  if (row.sessionId !== source.sessionId)
@@ -1,3 +1,3 @@
1
1
  import { type ExtensionAPI } from "@earendil-works/pi-coding-agent";
2
- /** Register the five shared note operations; each one supplies Pi's session identity and nothing else. */
2
+ /** Register the five shared note operations and the three hidden dream tools; an open dream widens the note identity. */
3
3
  export declare function registerNotesTools(pi: ExtensionAPI): void;
@@ -1,15 +1,35 @@
1
1
  import { generateDiffString } from "@earendil-works/pi-coding-agent";
2
2
  import { notesWrite, notesUpdate, notesRead, notesList, notesSearch } from "../../../src/tools/notes.js";
3
+ import { abandonDream, dreamBegin, dreamEnd, dreamForget, dreamingIdentity } from "../../../src/tools/dream.js";
3
4
  import { notesIdentityFromPi } from "./adapter.js";
4
- import { NOTES_NAMESPACE, registerOperation } from "../tool-result.js";
5
+ import { notesReadRenderers, notesUpdateRenderers, notesWriteRenderers } from "../render.js";
6
+ import { DREAM_NAMESPACE, NOTES_NAMESPACE, registerOperation } from "../tool-result.js";
5
7
  function renderDiff(change) {
6
8
  return change.kind === "none" ? "" : generateDiffString(change.before, change.after, 1).diff;
7
9
  }
8
- /** Register the five shared note operations; each one supplies Pi's session identity and nothing else. */
10
+ /** Register the five shared note operations and the three hidden dream tools; an open dream widens the note identity. */
9
11
  export function registerNotesTools(pi) {
10
- registerOperation(pi, notesWrite, (params, ctx) => notesWrite.execute(params, notesIdentityFromPi(ctx)), NOTES_NAMESPACE);
11
- registerOperation(pi, notesUpdate, (params, ctx) => notesUpdate.execute(params, notesIdentityFromPi(ctx), renderDiff), NOTES_NAMESPACE);
12
- registerOperation(pi, notesRead, (params, ctx) => notesRead.execute(params, notesIdentityFromPi(ctx)), NOTES_NAMESPACE);
13
- registerOperation(pi, notesList, (params, ctx) => notesList.execute(params, notesIdentityFromPi(ctx)), NOTES_NAMESPACE);
14
- registerOperation(pi, notesSearch, (params, ctx) => notesSearch.execute(params, notesIdentityFromPi(ctx)), NOTES_NAMESPACE);
12
+ // One open dream per session, in memory: shutdown releases its lock without the end commit.
13
+ const dreams = new Map();
14
+ pi.on("session_shutdown", () => {
15
+ for (const state of dreams.values())
16
+ abandonDream(state);
17
+ dreams.clear();
18
+ });
19
+ const dreamOf = (ctx) => {
20
+ const id = ctx.sessionManager.getSessionId();
21
+ let state = dreams.get(id);
22
+ if (!state)
23
+ dreams.set(id, state = {});
24
+ return state;
25
+ };
26
+ const identity = (ctx) => dreamingIdentity(notesIdentityFromPi(ctx), dreamOf(ctx));
27
+ registerOperation(pi, notesWrite, (params, ctx) => notesWrite.execute(params, identity(ctx)), NOTES_NAMESPACE, notesWriteRenderers);
28
+ registerOperation(pi, notesUpdate, (params, ctx) => notesUpdate.execute(params, identity(ctx), renderDiff), NOTES_NAMESPACE, notesUpdateRenderers);
29
+ registerOperation(pi, notesRead, (params, ctx) => notesRead.execute(params, identity(ctx)), NOTES_NAMESPACE, notesReadRenderers);
30
+ registerOperation(pi, notesList, (params, ctx) => notesList.execute(params, identity(ctx)), NOTES_NAMESPACE);
31
+ registerOperation(pi, notesSearch, (params, ctx) => notesSearch.execute(params, identity(ctx)), NOTES_NAMESPACE);
32
+ registerOperation(pi, dreamBegin, (params, ctx) => dreamBegin.execute(params, notesIdentityFromPi(ctx), dreamOf(ctx)), DREAM_NAMESPACE, undefined, "deferred");
33
+ registerOperation(pi, dreamForget, (params, ctx) => dreamForget.execute(params, notesIdentityFromPi(ctx), dreamOf(ctx)), DREAM_NAMESPACE, undefined, "deferred");
34
+ registerOperation(pi, dreamEnd, (params, ctx) => dreamEnd.execute(params, notesIdentityFromPi(ctx), dreamOf(ctx)), DREAM_NAMESPACE, undefined, "deferred");
15
35
  }
@@ -0,0 +1,40 @@
1
+ /** Pi TUI renderers for notesoup's own tools: collapsed one-line slips, expandable bodies. */
2
+ import { type AgentToolResult, type Theme } from "@earendil-works/pi-coding-agent";
3
+ import { type Component } from "@earendil-works/pi-tui";
4
+ import type { Static } from "typebox";
5
+ import { notesReadParameters, notesUpdateParameters, notesWriteParameters } from "../../src/tools/notes.js";
6
+ /** Only the render-context members these renderers read; the host's ToolRenderContext satisfies this. */
7
+ type CallContext<TArgs> = {
8
+ args: TArgs;
9
+ };
10
+ export type NotesWriteArgs = Static<typeof notesWriteParameters>;
11
+ export declare const notesWriteRenderers: {
12
+ renderCall: (args: NotesWriteArgs, theme: Theme) => Component;
13
+ renderResult(result: AgentToolResult<undefined>, options: {
14
+ expanded: boolean;
15
+ }, theme: Theme, context: CallContext<NotesWriteArgs>): Component;
16
+ };
17
+ export type NotesUpdateArgs = Static<typeof notesUpdateParameters>;
18
+ export declare const notesUpdateRenderers: {
19
+ renderCall(args: NotesUpdateArgs, theme: Theme): Component;
20
+ renderResult(result: AgentToolResult<undefined>, options: {
21
+ expanded: boolean;
22
+ }, theme: Theme, context: CallContext<NotesUpdateArgs>): Component;
23
+ };
24
+ export type NotesReadArgs = Static<typeof notesReadParameters>;
25
+ export declare const notesReadRenderers: {
26
+ renderCall: (args: NotesReadArgs, theme: Theme) => Component;
27
+ renderResult(result: AgentToolResult<undefined>, options: {
28
+ expanded: boolean;
29
+ }, theme: Theme): Component;
30
+ };
31
+ export type EmptyBrainArgs = {
32
+ last_word?: string;
33
+ };
34
+ export declare const emptyBrainRenderers: {
35
+ renderCall: (_args: EmptyBrainArgs, theme: Theme) => Component;
36
+ renderResult(result: AgentToolResult<unknown>, _options: {
37
+ expanded: boolean;
38
+ }, theme: Theme, context: CallContext<EmptyBrainArgs>): Component;
39
+ };
40
+ export {};
@@ -0,0 +1,168 @@
1
+ /** Pi TUI renderers for notesoup's own tools: collapsed one-line slips, expandable bodies. */
2
+ import { renderDiff } from "@earendil-works/pi-coding-agent";
3
+ import { Text, TruncatedText, visibleWidth } from "@earendil-works/pi-tui";
4
+ /** Expanded bodies show this many lines before a "more lines" marker; the full text is in the receipt. */
5
+ const EXPANDED_LINE_CAP = 80;
6
+ /** structuredContent is wireResult(outcome): the data itself, or {error, code}. Old sessions may lack it. */
7
+ function wireOf(result) {
8
+ const sc = result.structuredContent;
9
+ if (sc !== null && typeof sc === "object" && !Array.isArray(sc)) {
10
+ const obj = sc;
11
+ if (typeof obj.error === "string")
12
+ return { error: { error: obj.error, code: typeof obj.code === "string" ? obj.code : "error" } };
13
+ return { data: obj };
14
+ }
15
+ return {};
16
+ }
17
+ /** Results without a structured payload (resumed old sessions) fall back to the receipt's first line. */
18
+ function receiptFallback(result, theme) {
19
+ const text = result.content.find((c) => c.type === "text")?.text ?? "";
20
+ return new TruncatedText(theme.fg("dim", text.split("\n")[0] ?? ""), 0, 0);
21
+ }
22
+ function errorComponent(theme, error, expanded) {
23
+ if (!expanded)
24
+ return new TruncatedText(theme.fg("error", `${error.code}: ${error.error.split("\n")[0]}`), 0, 0);
25
+ return new Text(theme.fg("error", `${error.code}: ${error.error}`), 0, 0);
26
+ }
27
+ function addressText(theme, address) {
28
+ return theme.fg("accent", address);
29
+ }
30
+ function callLine(theme, tool, target, suffix = "") {
31
+ let line = theme.fg("toolTitle", theme.bold(tool));
32
+ if (target !== undefined && target !== "")
33
+ line += " " + addressText(theme, target);
34
+ if (suffix !== "")
35
+ line += theme.fg("dim", suffix);
36
+ return new TruncatedText(line, 0, 0);
37
+ }
38
+ /** First `+` line of a generateDiffString diff, without its line-number prefix: the sentence just written down. */
39
+ function firstAddedLine(diff) {
40
+ for (const line of diff.split("\n")) {
41
+ const match = /^\+(\s*\d*)?\s?(.*)$/.exec(line);
42
+ if (match)
43
+ return match[2];
44
+ }
45
+ return undefined;
46
+ }
47
+ function boundedLines(text, theme) {
48
+ const lines = text.split("\n");
49
+ if (lines.length <= EXPANDED_LINE_CAP)
50
+ return text;
51
+ return `${lines.slice(0, EXPANDED_LINE_CAP).join("\n")}\n${theme.fg("dim", `… ${lines.length - EXPANDED_LINE_CAP} more lines`)}`;
52
+ }
53
+ export const notesWriteRenderers = {
54
+ renderCall: (args, theme) => callLine(theme, "notes_write", args.address),
55
+ renderResult(result, options, theme, context) {
56
+ const { data, error } = wireOf(result);
57
+ if (error)
58
+ return errorComponent(theme, error, options.expanded);
59
+ if (!data)
60
+ return receiptFallback(result, theme);
61
+ const content = typeof context.args?.content === "string" ? context.args.content : "";
62
+ const qualifier = data.outcome === "created" ? "" : theme.fg("dim", ` · ${data.outcome}`);
63
+ const head = `wrote ${addressText(theme, data.address)}${qualifier}${theme.fg("dim", ` · ${Array.from(content).length} chars`)}`;
64
+ if (!options.expanded)
65
+ return new TruncatedText(head, 0, 0);
66
+ return new Text(`${head}\n\n${boundedLines(content, theme)}`, 0, 0);
67
+ },
68
+ };
69
+ export const notesUpdateRenderers = {
70
+ renderCall(args, theme) {
71
+ let suffix = "";
72
+ if (args.crumpled === true)
73
+ suffix = " · crumple";
74
+ else if (args.crumpled === false)
75
+ suffix = " · restore";
76
+ if (typeof args.rename_to === "string" && args.rename_to !== "")
77
+ suffix += ` → ${args.rename_to}`;
78
+ return callLine(theme, "notes_update", args.address, suffix);
79
+ },
80
+ renderResult(result, options, theme, context) {
81
+ const { data, error } = wireOf(result);
82
+ if (error)
83
+ return errorComponent(theme, error, options.expanded);
84
+ if (!data)
85
+ return receiptFallback(result, theme);
86
+ let head;
87
+ if (context.args?.crumpled === true) {
88
+ head = `✂ crumpled ${theme.strikethrough(theme.fg("dim", data.address))}`;
89
+ }
90
+ else if (context.args?.crumpled === false) {
91
+ head = `restored ${addressText(theme, data.address)}`;
92
+ }
93
+ else if (data.change_kind === "moved") {
94
+ head = `renamed ${theme.fg("dim", data.rename_from ?? "?")}${theme.fg("dim", " → ")}${addressText(theme, data.address)}`;
95
+ }
96
+ else if (data.change_kind === "none") {
97
+ head = theme.fg("dim", "unchanged ") + addressText(theme, data.address);
98
+ }
99
+ else {
100
+ head = `edited ${addressText(theme, data.address)}`;
101
+ const peek = firstAddedLine(data.diff);
102
+ if (peek !== undefined && peek !== "")
103
+ head += theme.fg("dim", " · ") + theme.fg("toolDiffAdded", `+ ${peek}`);
104
+ }
105
+ if (!options.expanded)
106
+ return new TruncatedText(head, 0, 0);
107
+ const parts = [head];
108
+ if (data.diff !== "")
109
+ parts.push("", renderDiff(data.diff));
110
+ if (data.change_kind !== "moved" && data.rename_from !== undefined)
111
+ parts.push(theme.fg("dim", `renamed from ${data.rename_from}`));
112
+ return new Text(parts.join("\n"), 0, 0);
113
+ },
114
+ };
115
+ export const notesReadRenderers = {
116
+ renderCall: (args, theme) => callLine(theme, "notes_read", args.address, args.offset_chars !== undefined && args.offset_chars !== 0 ? ` · offset ${args.offset_chars}` : ""),
117
+ renderResult(result, options, theme) {
118
+ const { data, error } = wireOf(result);
119
+ if (error)
120
+ return errorComponent(theme, error, options.expanded);
121
+ if (!data)
122
+ return receiptFallback(result, theme);
123
+ const truncated = data.next_offset_chars !== null;
124
+ let head = `read ${addressText(theme, data.address)}${theme.fg("dim", ` · ${data.total_chars} chars${truncated ? " · truncated" : ""}`)}`;
125
+ const peek = data.text.split("\n").find((line) => line.trim() !== "");
126
+ if (peek !== undefined)
127
+ head += theme.fg("dim", ` — ${peek.trim()}`);
128
+ if (!options.expanded)
129
+ return new TruncatedText(head, 0, 0);
130
+ const tail = truncated ? `\n${theme.fg("dim", `… continue at offset_chars=${data.next_offset_chars}`)}` : "";
131
+ return new Text(`${head}\n\n${boundedLines(data.text, theme)}${tail}`, 0, 0);
132
+ },
133
+ };
134
+ /** The empty_brain result is the JSON receipt text; there is no structured payload. */
135
+ function emptyBrainPayload(result) {
136
+ try {
137
+ const text = result.content.find((c) => c.type === "text")?.text ?? "";
138
+ const parsed = JSON.parse(text);
139
+ if (parsed !== null && typeof parsed === "object")
140
+ return parsed;
141
+ }
142
+ catch { /* a non-JSON receipt renders as a plain line */ }
143
+ return {};
144
+ }
145
+ export const emptyBrainRenderers = {
146
+ renderCall: (_args, theme) => callLine(theme, "empty_brain"),
147
+ renderResult(result, _options, theme, context) {
148
+ const payload = emptyBrainPayload(result);
149
+ if (result.isError || payload.error !== undefined) {
150
+ return new TruncatedText(theme.fg("error", `✂ brain refused to empty — ${payload.error ?? "unknown error"}`), 0, 0);
151
+ }
152
+ if (payload.status === "rollover_already_pending")
153
+ return new TruncatedText(theme.fg("dim", "✂ brain already being emptied"), 0, 0);
154
+ const lastWord = typeof context.args?.last_word === "string" && context.args.last_word !== "" ? context.args.last_word : undefined;
155
+ return {
156
+ invalidate() { },
157
+ render(width) {
158
+ const label = "✂ brain emptied";
159
+ const prefix = "── ";
160
+ const fill = Math.max(2, width - visibleWidth(prefix) - visibleWidth(label) - 1);
161
+ const lines = [theme.fg("dim", `${prefix}${label} ${"─".repeat(fill)}`)];
162
+ if (lastWord !== undefined)
163
+ lines.push(theme.fg("warning", theme.italic(`“${lastWord}”`)));
164
+ return lines;
165
+ },
166
+ };
167
+ },
168
+ };
@@ -4,6 +4,7 @@ import { getCurrentSystemMessage, Type } from "@earendil-works/pi-ai";
4
4
  import { VERSION, defineTool } from "@earendil-works/pi-coding-agent";
5
5
  import { registerBudget } from "./budget.js";
6
6
  import { output } from "./tool-result.js";
7
+ import { emptyBrainRenderers } from "./render.js";
7
8
  import { currentReset, currentWindowId, isCheckpointBackedReset, isWindowBoot, isWindowMarker, markerResetOrigin, projectRootWindow, projectWindow, rootWindowId } from "./window.js";
8
9
  import { registerResetLifecycle } from "./reset/lifecycle.js";
9
10
  import { buildResetDrafts, LAST_WORD_ADVERTISED_CHARS, MAX_LAST_WORD_CHARS, repairResetTail, sanitizeLastWord } from "./reset/artifacts.js";
@@ -209,6 +210,8 @@ export function registerContext(pi, settingsManager) {
209
210
  label: "Empty Brain",
210
211
  description: "Clear your in-context memory and start a fresh context window. Your session, notes, and history survive. Pass `last_word` to stick a tiny note on your forehead for after the wipe.",
211
212
  parameters: Type.Object({ last_word: Type.Optional(Type.String({ description: `A tiny sticky note, at most ${LAST_WORD_ADVERTISED_CHARS} characters. After the wipe it is slapped on your forehead; longer notes are refused.` })) }, { additionalProperties: false }),
213
+ renderCall: emptyBrainRenderers.renderCall,
214
+ renderResult: emptyBrainRenderers.renderResult,
212
215
  async execute(_id, params, _signal, _update, ctx) {
213
216
  if (!enabled)
214
217
  return output({ error: "notesoup is off, so memory can't be cleared; the user can turn it on with `/notesoup on`." });
@@ -1,5 +1,5 @@
1
1
  /** Pi transport for host-neutral operations. */
2
- import { type ExtensionAPI, type ExtensionToolContext } from "@earendil-works/pi-coding-agent";
2
+ import { type ExtensionAPI, type ExtensionToolContext, type ToolDefinition, type ToolExposure } from "@earendil-works/pi-coding-agent";
3
3
  import type { Static, TSchema } from "typebox";
4
4
  import { type Operation, type Outcome } from "../../src/tools/result.js";
5
5
  /** Pi's JSON envelope for reset and budget tools; details carry only log/UI metadata. */
@@ -17,6 +17,9 @@ export type ToolNamespace = {
17
17
  description: string;
18
18
  };
19
19
  export declare const NOTES_NAMESPACE: ToolNamespace;
20
+ export declare const DREAM_NAMESPACE: ToolNamespace;
20
21
  export declare const HISTORY_NAMESPACE: ToolNamespace;
22
+ /** Optional TUI renderers; without them the host draws its default call line and receipt text. */
23
+ export type OperationRenderers<TParams extends TSchema> = Pick<ToolDefinition<TParams, undefined>, "renderCall" | "renderResult">;
21
24
  /** Register `operation` as a Pi tool; `run` supplies only the host context it needs. */
22
- export declare function registerOperation<TParams extends TSchema, TData, TRest extends readonly unknown[]>(pi: ExtensionAPI, operation: Operation<TParams, TData, TRest>, run: (params: Static<TParams>, ctx: ExtensionToolContext) => Promise<Outcome<TData>>, namespace?: ToolNamespace): void;
25
+ export declare function registerOperation<TParams extends TSchema, TData, TRest extends readonly unknown[]>(pi: ExtensionAPI, operation: Operation<TParams, TData, TRest>, run: (params: Static<TParams>, ctx: ExtensionToolContext) => Promise<Outcome<TData>>, namespace?: ToolNamespace, renderers?: OperationRenderers<TParams>, exposure?: ToolExposure): void;
@@ -17,9 +17,10 @@ function piOperationResult(render, outcome) {
17
17
  };
18
18
  }
19
19
  export const NOTES_NAMESPACE = { name: "notes", description: "Notes you choose to keep across context windows. See the memory skill." };
20
+ export const DREAM_NAMESPACE = { name: "dream", description: "Consolidate one project's notes: begin, edit with notes_*, forget crumpled notes, end." };
20
21
  export const HISTORY_NAMESPACE = { name: "history", description: "What happened in this session, read-only. See the memory skill." };
21
22
  /** Register `operation` as a Pi tool; `run` supplies only the host context it needs. */
22
- export function registerOperation(pi, operation, run, namespace) {
23
+ export function registerOperation(pi, operation, run, namespace, renderers, exposure) {
23
24
  pi.registerTool(defineTool({
24
25
  name: operation.name,
25
26
  label: operation.label,
@@ -28,6 +29,8 @@ export function registerOperation(pi, operation, run, namespace) {
28
29
  outputSchema: operation.outputSchema,
29
30
  executionMode: operation.executionMode,
30
31
  ...(namespace ? { namespace } : {}),
32
+ ...(exposure ? { exposure } : {}),
33
+ ...renderers,
31
34
  async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
32
35
  return piOperationResult(operation.render, await run(params, ctx));
33
36
  },
@@ -12,9 +12,8 @@ export type AuditResult = {
12
12
  error: string;
13
13
  };
14
14
  /**
15
- * Git audit layer for a dream run: one commit before (baseline) and one after (dream),
16
- * so the human gate reviews `git show` instead of trusting a report, and rollback is
17
- * `git revert`. The caller decides how loud a failure is; this function only reports it.
15
+ * Git audit layer for a dream: one commit at dream_begin (baseline) and one at dream_end,
16
+ * so the human reviews `git show` instead of trusting a report, and rollback is `git revert`. The caller decides how loud a failure is; this function only reports it.
18
17
  * A clean tree on an established repository commits nothing; a repository with no HEAD
19
18
  * gets an empty baseline commit, because an audit run with no snapshot is not a success.
20
19
  */
@@ -18,9 +18,8 @@ function ensureRuntimeIgnored(home) {
18
18
  catch { /* best effort: an unignored lock only adds noise to the audit */ }
19
19
  }
20
20
  /**
21
- * Git audit layer for a dream run: one commit before (baseline) and one after (dream),
22
- * so the human gate reviews `git show` instead of trusting a report, and rollback is
23
- * `git revert`. The caller decides how loud a failure is; this function only reports it.
21
+ * Git audit layer for a dream: one commit at dream_begin (baseline) and one at dream_end,
22
+ * so the human reviews `git show` instead of trusting a report, and rollback is `git revert`. The caller decides how loud a failure is; this function only reports it.
24
23
  * A clean tree on an established repository commits nothing; a repository with no HEAD
25
24
  * gets an empty baseline commit, because an audit run with no snapshot is not a success.
26
25
  */
@@ -42,12 +41,10 @@ export function gitCommit(home, message) {
42
41
  const before = headCommit(home);
43
42
  if (!clean) {
44
43
  execFileSync("git", ["commit", "-q", "-m", message], { cwd: home, stdio: "ignore" });
45
- console.log(`git: committed "${message}"`);
46
44
  }
47
45
  else if (before === undefined) {
48
46
  // A newly initialized repository has no snapshot at all; give the audit one.
49
47
  execFileSync("git", ["commit", "-q", "--allow-empty", "-m", message], { cwd: home, stdio: "ignore" });
50
- console.log(`git: committed "${message}"`);
51
48
  }
52
49
  const commit = headCommit(home);
53
50
  if (commit === undefined)
@@ -55,9 +52,7 @@ export function gitCommit(home, message) {
55
52
  return { ok: true, commit, empty: clean };
56
53
  }
57
54
  catch (error) {
58
- const reason = errorMessage(error);
59
- console.log(`git audit layer failed: ${reason}`);
60
- return { ok: false, error: reason };
55
+ return { ok: false, error: errorMessage(error) };
61
56
  }
62
57
  }
63
58
  /** HEAD sha, or undefined when the repository has no commit yet. */
@@ -1,31 +1,14 @@
1
- export type LockState = {
1
+ /** One held dream lock; only the holder that wrote the token removes it. */
2
+ export type DreamLock = {
2
3
  path: string;
3
- held: boolean;
4
- reason?: string;
5
- startedAt: number;
6
- /** mtime of the last-run sidecar before this run took the lock; failLock restores it. */
7
- priorStampMtime?: number;
8
- /** Random identity written into the lock file; cleanup only removes the lock it wrote. */
9
- token?: string;
4
+ token: string;
10
5
  };
6
+ /** The per-project lock file in the notes home; `.dream.lock*` is excluded from the Git audit. */
7
+ export declare function dreamLockPath(home: string, project: string): string;
11
8
  /**
12
- * The scheduler's last-run timestamp lives in a sidecar beside the lock, never in the
13
- * lock file itself: acquiring, releasing or cleaning up the lock touches only the PID
14
- * marker, so lock lifecycle does not destroy the timestamp the time gate reads.
9
+ * Git-style exclusive existence lock: one O_CREAT|O_EXCL creation. An existing lock refuses,
10
+ * whatever its age; a crash-left lock is removed by hand after confirming no dream runs.
15
11
  */
16
- export declare function lastRunPath(lockPath: string): string;
17
- /**
18
- * Acquire the dream lock with Git-style exclusive existence locking: one O_CREAT|O_EXCL
19
- * creation. An existing path refuses acquisition regardless of its contents, PID, or age,
20
- * and is never read for permission, replaced, or removed. There is no automatic stale
21
- * recovery; a crash-left lock is human cleanup after confirming no dream is running.
22
- */
23
- export declare function acquireLock(path: string): LockState;
24
- /** Release only the lock this run acquired. Idempotent: repeated cleanup does nothing. */
25
- export declare function releaseLock(lock: LockState): void;
26
- /**
27
- * A failed run must not advance the scheduler: restore the previous timestamp, or remove
28
- * the one this run wrote when there was none. Only this run's own marker is removed, and
29
- * the state is marked released so a later cleanup attempt is harmless.
30
- */
31
- export declare function failLock(lock: LockState): void;
12
+ export declare function acquireDreamLock(path: string): DreamLock | undefined;
13
+ /** Release only a lock this holder wrote; repeated release is harmless. */
14
+ export declare function releaseDreamLock(lock: DreamLock): void;
@@ -1,92 +1,29 @@
1
1
  import { randomUUID } from "node:crypto";
2
- import { readFileSync, statSync, unlinkSync, utimesSync, writeFileSync } from "node:fs";
2
+ import { readFileSync, unlinkSync, writeFileSync } from "node:fs";
3
+ import { join } from "node:path";
4
+ /** The per-project lock file in the notes home; `.dream.lock*` is excluded from the Git audit. */
5
+ export function dreamLockPath(home, project) {
6
+ return join(home, `.dream.lock.${project}`);
7
+ }
3
8
  /**
4
- * The scheduler's last-run timestamp lives in a sidecar beside the lock, never in the
5
- * lock file itself: acquiring, releasing or cleaning up the lock touches only the PID
6
- * marker, so lock lifecycle does not destroy the timestamp the time gate reads.
9
+ * Git-style exclusive existence lock: one O_CREAT|O_EXCL creation. An existing lock refuses,
10
+ * whatever its age; a crash-left lock is removed by hand after confirming no dream runs.
7
11
  */
8
- export function lastRunPath(lockPath) {
9
- return `${lockPath}.last-run`;
10
- }
11
- function readText(path) {
12
+ export function acquireDreamLock(path) {
13
+ const token = `${process.pid} ${randomUUID()}`;
12
14
  try {
13
- return readFileSync(path, "utf8");
15
+ writeFileSync(path, token, { flag: "wx" });
14
16
  }
15
17
  catch {
16
18
  return undefined;
17
19
  }
20
+ return { path, token };
18
21
  }
19
- function ownsLock(lock) {
20
- if (!lock.held || !lock.token)
21
- return false;
22
- return readText(lock.path)?.trim() === `${process.pid} ${lock.token}`;
23
- }
24
- /**
25
- * Acquire the dream lock with Git-style exclusive existence locking: one O_CREAT|O_EXCL
26
- * creation. An existing path refuses acquisition regardless of its contents, PID, or age,
27
- * and is never read for permission, replaced, or removed. There is no automatic stale
28
- * recovery; a crash-left lock is human cleanup after confirming no dream is running.
29
- */
30
- export function acquireLock(path) {
31
- const now = Date.now();
32
- // The sidecar's mtime is the scheduler's timestamp; a missing one means no prior dream.
33
- let priorStampMtime;
34
- try {
35
- priorStampMtime = statSync(lastRunPath(path)).mtimeMs;
36
- }
37
- catch { /* no sidecar yet */ }
38
- const token = randomUUID();
39
- try {
40
- writeFileSync(path, `${process.pid} ${token}`, { flag: "wx" });
41
- }
42
- catch {
43
- return { path, held: false, reason: "lock gate: lock already exists", startedAt: now };
44
- }
45
- // Only a held lock advances the scheduler timestamp.
22
+ /** Release only a lock this holder wrote; repeated release is harmless. */
23
+ export function releaseDreamLock(lock) {
46
24
  try {
47
- writeFileSync(lastRunPath(path), new Date(now).toISOString());
48
- }
49
- catch { /* advisory */ }
50
- return { path, held: true, startedAt: now, priorStampMtime, token };
51
- }
52
- /** Release only the lock this run acquired. Idempotent: repeated cleanup does nothing. */
53
- export function releaseLock(lock) {
54
- if (!lock.held)
55
- return;
56
- if (ownsLock(lock)) {
57
- try {
58
- unlinkSync(lock.path);
59
- }
60
- catch { /* best effort */ }
61
- }
62
- lock.held = false;
63
- }
64
- /**
65
- * A failed run must not advance the scheduler: restore the previous timestamp, or remove
66
- * the one this run wrote when there was none. Only this run's own marker is removed, and
67
- * the state is marked released so a later cleanup attempt is harmless.
68
- */
69
- export function failLock(lock) {
70
- if (!lock.held)
71
- return;
72
- if (ownsLock(lock)) {
73
- const stampPath = lastRunPath(lock.path);
74
- if (lock.priorStampMtime === undefined) {
75
- try {
76
- unlinkSync(stampPath);
77
- }
78
- catch { /* best effort */ }
79
- }
80
- else {
81
- try {
82
- utimesSync(stampPath, new Date(), new Date(lock.priorStampMtime));
83
- }
84
- catch { /* best effort */ }
85
- }
86
- try {
25
+ if (readFileSync(lock.path, "utf8") === lock.token)
87
26
  unlinkSync(lock.path);
88
- }
89
- catch { /* best effort */ }
90
27
  }
91
- lock.held = false;
28
+ catch { /* already gone */ }
92
29
  }
@@ -1,4 +1,4 @@
1
- export type NoteErrorCode = "not_found" | "already_exists" | "ambiguous_edit" | "no_match" | "invalid_edit" | "nothing_to_do" | "too_large" | "invalid_scope" | "invalid_origin" | "invalid_address" | "invalid_pattern" | "invalid_query" | "invalid_offset" | "io_error" | "internal_error";
1
+ export type NoteErrorCode = "not_found" | "already_exists" | "ambiguous_edit" | "no_match" | "invalid_edit" | "nothing_to_do" | "not_crumpled" | "too_large" | "invalid_scope" | "invalid_origin" | "invalid_address" | "invalid_pattern" | "invalid_query" | "invalid_offset" | "io_error" | "internal_error";
2
2
  /** Typed store refusal. Edit locations are exposed in camelCase. */
3
3
  export declare class NoteError extends Error {
4
4
  readonly code: NoteErrorCode;
@@ -5,6 +5,8 @@ export type NotesIdentity = Readonly<{
5
5
  projectKey: string;
6
6
  agent: string;
7
7
  model: string;
8
+ /** Project slug being dreamed over: its named project and session notes become writable, and reads leave no access stamp. */
9
+ dreaming?: string;
8
10
  }>;
9
11
  /** Validate and snapshot caller identity; no global or environment defaults are consulted. */
10
12
  export declare function snapshotNotesIdentity(value: NotesIdentity): NotesIdentity;
@@ -22,6 +22,8 @@ export function snapshotNotesIdentity(value) {
22
22
  throw new TypeError("notes context agent must be a canonical lowercase slug");
23
23
  if (!SLUG_PATTERN.test(model))
24
24
  throw new TypeError("notes context model must be a canonical lowercase slug");
25
+ if (value.dreaming !== undefined && !SLUG_PATTERN.test(value.dreaming))
26
+ throw new TypeError("notes context dreaming must be a canonical lowercase slug");
25
27
  const home = resolve(homeValue);
26
- return Object.freeze({ home, sessionId, projectKey, agent, model });
28
+ return Object.freeze({ home, sessionId, projectKey, agent, model, ...(value.dreaming === undefined ? {} : { dreaming: value.dreaming }) });
27
29
  }
@@ -93,6 +93,8 @@ export interface NotesStore {
93
93
  read(address: string): Promise<NoteReadResult | undefined>;
94
94
  update(address: string, edits?: EditOperation[], options?: EditOptions): Promise<NoteEditResult>;
95
95
  rename(fromAddress: string, toAddress: string): Promise<NoteRenameResult>;
96
+ /** Physically delete one crumpled note; only a dreaming identity may call it. */
97
+ forget(address: string): Promise<NoteMeta>;
96
98
  list(options?: NotesQuery): Promise<NoteRow[]>;
97
99
  search(queries: string[], options?: NotesQuery): Promise<NoteSearchRow[]>;
98
100
  listWithStatus(options?: NotesQuery): Promise<NoteQueryResult<NoteRow>>;