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
@@ -1,18 +1,36 @@
1
- import { generateDiffString, type ExtensionAPI } from "@earendil-works/pi-coding-agent";
1
+ import { generateDiffString, type ExtensionAPI, type ExtensionContext } 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, type DreamState } 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
  import type { NoteChange } from "../../../src/notes/index.js";
6
8
 
7
9
  function renderDiff(change: NoteChange): string {
8
10
  return change.kind === "none" ? "" : generateDiffString(change.before, change.after, 1).diff;
9
11
  }
10
12
 
11
- /** Register the five shared note operations; each one supplies Pi's session identity and nothing else. */
13
+ /** Register the five shared note operations and the three hidden dream tools; an open dream widens the note identity. */
12
14
  export function registerNotesTools(pi: ExtensionAPI) {
13
- registerOperation(pi, notesWrite, (params, ctx) => notesWrite.execute(params, notesIdentityFromPi(ctx)), NOTES_NAMESPACE);
14
- registerOperation(pi, notesUpdate, (params, ctx) => notesUpdate.execute(params, notesIdentityFromPi(ctx), renderDiff), NOTES_NAMESPACE);
15
- registerOperation(pi, notesRead, (params, ctx) => notesRead.execute(params, notesIdentityFromPi(ctx)), NOTES_NAMESPACE);
16
- registerOperation(pi, notesList, (params, ctx) => notesList.execute(params, notesIdentityFromPi(ctx)), NOTES_NAMESPACE);
17
- registerOperation(pi, notesSearch, (params, ctx) => notesSearch.execute(params, notesIdentityFromPi(ctx)), NOTES_NAMESPACE);
15
+ // One open dream per session, in memory: shutdown releases its lock without the end commit.
16
+ const dreams = new Map<string, DreamState>();
17
+ pi.on("session_shutdown", () => {
18
+ for (const state of dreams.values()) abandonDream(state);
19
+ dreams.clear();
20
+ });
21
+ const dreamOf = (ctx: ExtensionContext): DreamState => {
22
+ const id = ctx.sessionManager.getSessionId();
23
+ let state = dreams.get(id);
24
+ if (!state) dreams.set(id, state = {});
25
+ return state;
26
+ };
27
+ 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);
33
+ registerOperation(pi, dreamBegin, (params, ctx) => dreamBegin.execute(params, notesIdentityFromPi(ctx), dreamOf(ctx)), DREAM_NAMESPACE, undefined, "deferred");
34
+ registerOperation(pi, dreamForget, (params, ctx) => dreamForget.execute(params, notesIdentityFromPi(ctx), dreamOf(ctx)), DREAM_NAMESPACE, undefined, "deferred");
35
+ registerOperation(pi, dreamEnd, (params, ctx) => dreamEnd.execute(params, notesIdentityFromPi(ctx), dreamOf(ctx)), DREAM_NAMESPACE, undefined, "deferred");
18
36
  }
@@ -0,0 +1,165 @@
1
+ /** Pi TUI renderers for notesoup's own tools: collapsed one-line slips, expandable bodies. */
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";
4
+ import type { Static } from "typebox";
5
+ import type { NotesReadData, NotesUpdateData, NotesWriteData } from "../../src/tools/notes.js";
6
+ import { notesReadParameters, notesUpdateParameters, notesWriteParameters } from "../../src/tools/notes.js";
7
+
8
+ /** Only the render-context members these renderers read; the host's ToolRenderContext satisfies this. */
9
+ type CallContext<TArgs> = { args: TArgs };
10
+
11
+ /** Expanded bodies show this many lines before a "more lines" marker; the full text is in the receipt. */
12
+ const EXPANDED_LINE_CAP = 80;
13
+
14
+ type WireError = { error: string; code: string };
15
+
16
+ /** structuredContent is wireResult(outcome): the data itself, or {error, code}. Old sessions may lack it. */
17
+ function wireOf<T>(result: AgentToolResult<undefined>): { data?: T; error?: WireError } {
18
+ const sc = result.structuredContent;
19
+ if (sc !== null && typeof sc === "object" && !Array.isArray(sc)) {
20
+ const obj = sc as Record<string, unknown>;
21
+ if (typeof obj.error === "string") return { error: { error: obj.error, code: typeof obj.code === "string" ? obj.code : "error" } };
22
+ return { data: obj as T };
23
+ }
24
+ return {};
25
+ }
26
+
27
+ /** Results without a structured payload (resumed old sessions) fall back to the receipt's first line. */
28
+ function receiptFallback(result: AgentToolResult<undefined>, theme: Theme): Component {
29
+ const text = result.content.find((c) => c.type === "text")?.text ?? "";
30
+ return new TruncatedText(theme.fg("dim", text.split("\n")[0] ?? ""), 0, 0);
31
+ }
32
+
33
+ function errorComponent(theme: Theme, error: WireError, expanded: boolean): Component {
34
+ if (!expanded) return new TruncatedText(theme.fg("error", `${error.code}: ${error.error.split("\n")[0]}`), 0, 0);
35
+ return new Text(theme.fg("error", `${error.code}: ${error.error}`), 0, 0);
36
+ }
37
+
38
+ function addressText(theme: Theme, address: string): string {
39
+ return theme.fg("accent", address);
40
+ }
41
+
42
+ function callLine(theme: Theme, tool: string, target?: string, suffix = ""): Component {
43
+ let line = theme.fg("toolTitle", theme.bold(tool));
44
+ if (target !== undefined && target !== "") line += " " + addressText(theme, target);
45
+ if (suffix !== "") line += theme.fg("dim", suffix);
46
+ return new TruncatedText(line, 0, 0);
47
+ }
48
+
49
+ /** First `+` line of a generateDiffString diff, without its line-number prefix: the sentence just written down. */
50
+ function firstAddedLine(diff: string): string | undefined {
51
+ for (const line of diff.split("\n")) {
52
+ const match = /^\+(\s*\d*)?\s?(.*)$/.exec(line);
53
+ if (match) return match[2];
54
+ }
55
+ return undefined;
56
+ }
57
+
58
+ function boundedLines(text: string, theme: Theme): string {
59
+ const lines = text.split("\n");
60
+ if (lines.length <= EXPANDED_LINE_CAP) return text;
61
+ return `${lines.slice(0, EXPANDED_LINE_CAP).join("\n")}\n${theme.fg("dim", `… ${lines.length - EXPANDED_LINE_CAP} more lines`)}`;
62
+ }
63
+
64
+ export type NotesWriteArgs = Static<typeof notesWriteParameters>;
65
+ export const notesWriteRenderers = {
66
+ renderCall: (args: NotesWriteArgs, theme: Theme): Component => callLine(theme, "notes_write", args.address),
67
+ renderResult(result: AgentToolResult<undefined>, options: { expanded: boolean }, theme: Theme, context: CallContext<NotesWriteArgs>): Component {
68
+ const { data, error } = wireOf<NotesWriteData>(result);
69
+ if (error) return errorComponent(theme, error, options.expanded);
70
+ if (!data) return receiptFallback(result, theme);
71
+ const content = typeof context.args?.content === "string" ? context.args.content : "";
72
+ const qualifier = data.outcome === "created" ? "" : theme.fg("dim", ` · ${data.outcome}`);
73
+ const head = `wrote ${addressText(theme, data.address)}${qualifier}${theme.fg("dim", ` · ${Array.from(content).length} chars`)}`;
74
+ if (!options.expanded) return new TruncatedText(head, 0, 0);
75
+ return new Text(`${head}\n\n${boundedLines(content, theme)}`, 0, 0);
76
+ },
77
+ };
78
+
79
+ export type NotesUpdateArgs = Static<typeof notesUpdateParameters>;
80
+ export const notesUpdateRenderers = {
81
+ renderCall(args: NotesUpdateArgs, theme: Theme): Component {
82
+ let suffix = "";
83
+ if (args.crumpled === true) suffix = " · crumple";
84
+ else if (args.crumpled === false) suffix = " · restore";
85
+ if (typeof args.rename_to === "string" && args.rename_to !== "") suffix += ` → ${args.rename_to}`;
86
+ return callLine(theme, "notes_update", args.address, suffix);
87
+ },
88
+ renderResult(result: AgentToolResult<undefined>, options: { expanded: boolean }, theme: Theme, context: CallContext<NotesUpdateArgs>): Component {
89
+ const { data, error } = wireOf<NotesUpdateData>(result);
90
+ if (error) return errorComponent(theme, error, options.expanded);
91
+ if (!data) return receiptFallback(result, theme);
92
+ let head: string;
93
+ if (context.args?.crumpled === true) {
94
+ head = `✂ crumpled ${theme.strikethrough(theme.fg("dim", data.address))}`;
95
+ } else if (context.args?.crumpled === false) {
96
+ head = `restored ${addressText(theme, data.address)}`;
97
+ } else if (data.change_kind === "moved") {
98
+ head = `renamed ${theme.fg("dim", data.rename_from ?? "?")}${theme.fg("dim", " → ")}${addressText(theme, data.address)}`;
99
+ } else if (data.change_kind === "none") {
100
+ head = theme.fg("dim", "unchanged ") + addressText(theme, data.address);
101
+ } else {
102
+ head = `edited ${addressText(theme, data.address)}`;
103
+ const peek = firstAddedLine(data.diff);
104
+ if (peek !== undefined && peek !== "") head += theme.fg("dim", " · ") + theme.fg("toolDiffAdded", `+ ${peek}`);
105
+ }
106
+ if (!options.expanded) return new TruncatedText(head, 0, 0);
107
+ const parts = [head];
108
+ if (data.diff !== "") parts.push("", renderDiff(data.diff));
109
+ if (data.change_kind !== "moved" && data.rename_from !== undefined) parts.push(theme.fg("dim", `renamed from ${data.rename_from}`));
110
+ return new Text(parts.join("\n"), 0, 0);
111
+ },
112
+ };
113
+
114
+ export type NotesReadArgs = Static<typeof notesReadParameters>;
115
+ export const notesReadRenderers = {
116
+ renderCall: (args: NotesReadArgs, theme: Theme): Component =>
117
+ callLine(theme, "notes_read", args.address, args.offset_chars !== undefined && args.offset_chars !== 0 ? ` · offset ${args.offset_chars}` : ""),
118
+ renderResult(result: AgentToolResult<undefined>, options: { expanded: boolean }, theme: Theme): Component {
119
+ const { data, error } = wireOf<NotesReadData>(result);
120
+ if (error) return errorComponent(theme, error, options.expanded);
121
+ if (!data) return receiptFallback(result, theme);
122
+ const truncated = data.next_offset_chars !== null;
123
+ let head = `read ${addressText(theme, data.address)}${theme.fg("dim", ` · ${data.total_chars} chars${truncated ? " · truncated" : ""}`)}`;
124
+ const peek = data.text.split("\n").find((line) => line.trim() !== "");
125
+ if (peek !== undefined) head += theme.fg("dim", ` — ${peek.trim()}`);
126
+ if (!options.expanded) return new TruncatedText(head, 0, 0);
127
+ const tail = truncated ? `\n${theme.fg("dim", `… continue at offset_chars=${data.next_offset_chars}`)}` : "";
128
+ return new Text(`${head}\n\n${boundedLines(data.text, theme)}${tail}`, 0, 0);
129
+ },
130
+ };
131
+
132
+ export type EmptyBrainArgs = { last_word?: string };
133
+
134
+ /** The empty_brain result is the JSON receipt text; there is no structured payload. */
135
+ function emptyBrainPayload(result: AgentToolResult<unknown>): { status?: string; error?: string } {
136
+ try {
137
+ const text = result.content.find((c) => c.type === "text")?.text ?? "";
138
+ const parsed: unknown = JSON.parse(text);
139
+ if (parsed !== null && typeof parsed === "object") return parsed as { status?: string; error?: string };
140
+ } catch { /* a non-JSON receipt renders as a plain line */ }
141
+ return {};
142
+ }
143
+
144
+ export const emptyBrainRenderers = {
145
+ renderCall: (_args: EmptyBrainArgs, theme: Theme): Component => callLine(theme, "empty_brain"),
146
+ renderResult(result: AgentToolResult<unknown>, _options: { expanded: boolean }, theme: Theme, context: CallContext<EmptyBrainArgs>): Component {
147
+ const payload = emptyBrainPayload(result);
148
+ if (result.isError || payload.error !== undefined) {
149
+ return new TruncatedText(theme.fg("error", `✂ brain refused to empty — ${payload.error ?? "unknown error"}`), 0, 0);
150
+ }
151
+ if (payload.status === "rollover_already_pending") return new TruncatedText(theme.fg("dim", "✂ brain already being emptied"), 0, 0);
152
+ const lastWord = typeof context.args?.last_word === "string" && context.args.last_word !== "" ? context.args.last_word : undefined;
153
+ return {
154
+ invalidate() {},
155
+ render(width: number): string[] {
156
+ const label = "✂ brain emptied";
157
+ const prefix = "── ";
158
+ const fill = Math.max(2, width - visibleWidth(prefix) - visibleWidth(label) - 1);
159
+ const lines = [theme.fg("dim", `${prefix}${label} ${"─".repeat(fill)}`)];
160
+ if (lastWord !== undefined) lines.push(theme.fg("warning", theme.italic(`“${lastWord}”`)));
161
+ return lines;
162
+ },
163
+ };
164
+ },
165
+ };
@@ -4,6 +4,7 @@ import { getCurrentSystemMessage, Type } from "@earendil-works/pi-ai";
4
4
  import { VERSION, defineTool, type ExtensionAPI, type ExtensionCommandContext, type ExtensionContext, type SettingsManager } 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, type WindowMarker } 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";
@@ -205,6 +206,8 @@ export function registerContext(pi: ExtensionAPI, settingsManager?: SettingsMana
205
206
  label: "Empty Brain",
206
207
  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.",
207
208
  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 }),
209
+ renderCall: emptyBrainRenderers.renderCall,
210
+ renderResult: emptyBrainRenderers.renderResult,
208
211
  async execute(_id, params, _signal, _update, ctx) {
209
212
  if (!enabled) return output({ error: "notesoup is off, so memory can't be cleared; the user can turn it on with `/notesoup on`." });
210
213
  const lastWord = sanitizeLastWord(params.last_word);
@@ -1,5 +1,5 @@
1
1
  /** Pi transport for host-neutral operations. */
2
- import { defineTool, type ExtensionAPI, type ExtensionToolContext } from "@earendil-works/pi-coding-agent";
2
+ import { defineTool, type ExtensionAPI, type ExtensionToolContext, type ToolDefinition, type ToolExposure } from "@earendil-works/pi-coding-agent";
3
3
  import type { AgentToolResult } from "@earendil-works/pi-agent-core";
4
4
  import type { JsonValue } from "@earendil-works/pi-ai";
5
5
  import type { Static, TSchema } from "typebox";
@@ -24,14 +24,20 @@ function piOperationResult<TData>(render: Renderer<TData>, outcome: Outcome<TDat
24
24
 
25
25
  export type ToolNamespace = { name: string; description: string };
26
26
  export const NOTES_NAMESPACE: ToolNamespace = { name: "notes", description: "Notes you choose to keep across context windows. See the memory skill." };
27
+ export const DREAM_NAMESPACE: ToolNamespace = { name: "dream", description: "Consolidate one project's notes: begin, edit with notes_*, forget crumpled notes, end." };
27
28
  export const HISTORY_NAMESPACE: ToolNamespace = { name: "history", description: "What happened in this session, read-only. See the memory skill." };
28
29
 
30
+ /** Optional TUI renderers; without them the host draws its default call line and receipt text. */
31
+ export type OperationRenderers<TParams extends TSchema> = Pick<ToolDefinition<TParams, undefined>, "renderCall" | "renderResult">;
32
+
29
33
  /** Register `operation` as a Pi tool; `run` supplies only the host context it needs. */
30
34
  export function registerOperation<TParams extends TSchema, TData, TRest extends readonly unknown[]>(
31
35
  pi: ExtensionAPI,
32
36
  operation: Operation<TParams, TData, TRest>,
33
37
  run: (params: Static<TParams>, ctx: ExtensionToolContext) => Promise<Outcome<TData>>,
34
38
  namespace?: ToolNamespace,
39
+ renderers?: OperationRenderers<TParams>,
40
+ exposure?: ToolExposure,
35
41
  ): void {
36
42
  pi.registerTool(defineTool<TParams, undefined>({
37
43
  name: operation.name,
@@ -41,6 +47,8 @@ export function registerOperation<TParams extends TSchema, TData, TRest extends
41
47
  outputSchema: operation.outputSchema,
42
48
  executionMode: operation.executionMode,
43
49
  ...(namespace ? { namespace } : {}),
50
+ ...(exposure ? { exposure } : {}),
51
+ ...renderers,
44
52
  async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
45
53
  return piOperationResult(operation.render, await run(params, ctx));
46
54
  },
package/src/dream/git.ts CHANGED
@@ -28,9 +28,8 @@ function ensureRuntimeIgnored(home: string): void {
28
28
  }
29
29
 
30
30
  /**
31
- * Git audit layer for a dream run: one commit before (baseline) and one after (dream),
32
- * so the human gate reviews `git show` instead of trusting a report, and rollback is
33
- * `git revert`. The caller decides how loud a failure is; this function only reports it.
31
+ * Git audit layer for a dream: one commit at dream_begin (baseline) and one at dream_end,
32
+ * 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.
34
33
  * A clean tree on an established repository commits nothing; a repository with no HEAD
35
34
  * gets an empty baseline commit, because an audit run with no snapshot is not a success.
36
35
  */
@@ -49,19 +48,15 @@ export function gitCommit(home: string, message: string): AuditResult {
49
48
  const before = headCommit(home);
50
49
  if (!clean) {
51
50
  execFileSync("git", ["commit", "-q", "-m", message], { cwd: home, stdio: "ignore" });
52
- console.log(`git: committed "${message}"`);
53
51
  } else if (before === undefined) {
54
52
  // A newly initialized repository has no snapshot at all; give the audit one.
55
53
  execFileSync("git", ["commit", "-q", "--allow-empty", "-m", message], { cwd: home, stdio: "ignore" });
56
- console.log(`git: committed "${message}"`);
57
54
  }
58
55
  const commit = headCommit(home);
59
56
  if (commit === undefined) return { ok: false, error: "audit commit produced no snapshot (no HEAD)" };
60
57
  return { ok: true, commit, empty: clean };
61
58
  } catch (error) {
62
- const reason = errorMessage(error);
63
- console.log(`git audit layer failed: ${reason}`);
64
- return { ok: false, error: reason };
59
+ return { ok: false, error: errorMessage(error) };
65
60
  }
66
61
  }
67
62
 
package/src/dream/lock.ts CHANGED
@@ -1,76 +1,28 @@
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";
3
4
 
4
- export type LockState = {
5
- path: string;
6
- held: boolean;
7
- reason?: string;
8
- startedAt: number;
9
- /** mtime of the last-run sidecar before this run took the lock; failLock restores it. */
10
- priorStampMtime?: number;
11
- /** Random identity written into the lock file; cleanup only removes the lock it wrote. */
12
- token?: string;
13
- };
5
+ /** One held dream lock; only the holder that wrote the token removes it. */
6
+ export type DreamLock = { path: string; token: string };
14
7
 
15
- /**
16
- * The scheduler's last-run timestamp lives in a sidecar beside the lock, never in the
17
- * lock file itself: acquiring, releasing or cleaning up the lock touches only the PID
18
- * marker, so lock lifecycle does not destroy the timestamp the time gate reads.
19
- */
20
- export function lastRunPath(lockPath: string): string {
21
- return `${lockPath}.last-run`;
22
- }
23
-
24
- function readText(path: string): string | undefined {
25
- try { return readFileSync(path, "utf8"); } catch { return undefined; }
26
- }
27
-
28
- function ownsLock(lock: LockState): boolean {
29
- if (!lock.held || !lock.token) return false;
30
- return readText(lock.path)?.trim() === `${process.pid} ${lock.token}`;
8
+ /** The per-project lock file in the notes home; `.dream.lock*` is excluded from the Git audit. */
9
+ export function dreamLockPath(home: string, project: string): string {
10
+ return join(home, `.dream.lock.${project}`);
31
11
  }
32
12
 
33
13
  /**
34
- * Acquire the dream lock with Git-style exclusive existence locking: one O_CREAT|O_EXCL
35
- * creation. An existing path refuses acquisition regardless of its contents, PID, or age,
36
- * and is never read for permission, replaced, or removed. There is no automatic stale
37
- * recovery; a crash-left lock is human cleanup after confirming no dream is running.
14
+ * Git-style exclusive existence lock: one O_CREAT|O_EXCL creation. An existing lock refuses,
15
+ * whatever its age; a crash-left lock is removed by hand after confirming no dream runs.
38
16
  */
39
- export function acquireLock(path: string): LockState {
40
- const now = Date.now();
41
- // The sidecar's mtime is the scheduler's timestamp; a missing one means no prior dream.
42
- let priorStampMtime: number | undefined;
43
- try { priorStampMtime = statSync(lastRunPath(path)).mtimeMs; } catch { /* no sidecar yet */ }
44
- const token = randomUUID();
45
- try {
46
- writeFileSync(path, `${process.pid} ${token}`, { flag: "wx" });
47
- } catch {
48
- return { path, held: false, reason: "lock gate: lock already exists", startedAt: now };
49
- }
50
- // Only a held lock advances the scheduler timestamp.
51
- try { writeFileSync(lastRunPath(path), new Date(now).toISOString()); } catch { /* advisory */ }
52
- return { path, held: true, startedAt: now, priorStampMtime, token };
53
- }
54
-
55
- /** Release only the lock this run acquired. Idempotent: repeated cleanup does nothing. */
56
- export function releaseLock(lock: LockState): void {
57
- if (!lock.held) return;
58
- if (ownsLock(lock)) { try { unlinkSync(lock.path); } catch { /* best effort */ } }
59
- lock.held = false;
17
+ export function acquireDreamLock(path: string): DreamLock | undefined {
18
+ const token = `${process.pid} ${randomUUID()}`;
19
+ try { writeFileSync(path, token, { flag: "wx" }); } catch { return undefined; }
20
+ return { path, token };
60
21
  }
61
22
 
62
- /**
63
- * A failed run must not advance the scheduler: restore the previous timestamp, or remove
64
- * the one this run wrote when there was none. Only this run's own marker is removed, and
65
- * the state is marked released so a later cleanup attempt is harmless.
66
- */
67
- export function failLock(lock: LockState): void {
68
- if (!lock.held) return;
69
- if (ownsLock(lock)) {
70
- const stampPath = lastRunPath(lock.path);
71
- if (lock.priorStampMtime === undefined) { try { unlinkSync(stampPath); } catch { /* best effort */ } }
72
- else { try { utimesSync(stampPath, new Date(), new Date(lock.priorStampMtime)); } catch { /* best effort */ } }
73
- try { unlinkSync(lock.path); } catch { /* best effort */ }
74
- }
75
- lock.held = false;
23
+ /** Release only a lock this holder wrote; repeated release is harmless. */
24
+ export function releaseDreamLock(lock: DreamLock): void {
25
+ try {
26
+ if (readFileSync(lock.path, "utf8") === lock.token) unlinkSync(lock.path);
27
+ } catch { /* already gone */ }
76
28
  }
@@ -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
 
3
3
  /** Typed store refusal. Edit locations are exposed in camelCase. */
4
4
  export class NoteError extends Error {
@@ -8,6 +8,8 @@ export type NotesIdentity = Readonly<{
8
8
  projectKey: string;
9
9
  agent: string;
10
10
  model: string;
11
+ /** Project slug being dreamed over: its named project and session notes become writable, and reads leave no access stamp. */
12
+ dreaming?: string;
11
13
  }>;
12
14
 
13
15
  function requireString(field: string, value: unknown): string {
@@ -27,6 +29,7 @@ export function snapshotNotesIdentity(value: NotesIdentity): NotesIdentity {
27
29
  if (!SLUG_PATTERN.test(projectKey)) throw new TypeError("notes context projectKey must be a canonical lowercase slug");
28
30
  if (!SLUG_PATTERN.test(agent)) throw new TypeError("notes context agent must be a canonical lowercase slug");
29
31
  if (!SLUG_PATTERN.test(model)) throw new TypeError("notes context model must be a canonical lowercase slug");
32
+ if (value.dreaming !== undefined && !SLUG_PATTERN.test(value.dreaming)) throw new TypeError("notes context dreaming must be a canonical lowercase slug");
30
33
  const home = resolve(homeValue);
31
- return Object.freeze({ home, sessionId, projectKey, agent, model });
34
+ return Object.freeze({ home, sessionId, projectKey, agent, model, ...(value.dreaming === undefined ? {} : { dreaming: value.dreaming }) });
32
35
  }
@@ -1,6 +1,6 @@
1
1
  import { randomUUID } from "node:crypto";
2
2
  import type { Dirent } from "node:fs";
3
- import { mkdir, readdir, readFile, realpath, rename, rm, writeFile } from "node:fs/promises";
3
+ import { mkdir, readdir, readFile, realpath, rename, rm, unlink, writeFile } from "node:fs/promises";
4
4
  import { dirname, join, resolve } from "node:path";
5
5
  import { earliestMatchOffsetChars } from "../text-match.js";
6
6
  import { assertAddress, assertGlobPattern, addressFor, canonicalAddressFor, globToRegExp, HOME_HEADS } from "./address.js";
@@ -59,6 +59,8 @@ export interface NotesStore {
59
59
  read(address: string): Promise<NoteReadResult | undefined>;
60
60
  update(address: string, edits?: EditOperation[], options?: EditOptions): Promise<NoteEditResult>;
61
61
  rename(fromAddress: string, toAddress: string): Promise<NoteRenameResult>;
62
+ /** Physically delete one crumpled note; only a dreaming identity may call it. */
63
+ forget(address: string): Promise<NoteMeta>;
62
64
  list(options?: NotesQuery): Promise<NoteRow[]>;
63
65
  search(queries: string[], options?: NotesQuery): Promise<NoteSearchRow[]>;
64
66
  listWithStatus(options?: NotesQuery): Promise<NoteQueryResult<NoteRow>>;
@@ -253,9 +255,11 @@ function frontmatterOf(meta: NoteMeta): string {
253
255
  return serializeNote(meta, "").slice(0, -2);
254
256
  }
255
257
 
256
- /** Explicit session/project homes are always read-only; agent/model homes allow their owner. */
258
+ /** Explicit session/project homes are read-only unless dreamed over; agent/model homes allow their owner. */
257
259
  function assertWritableHome(scope: Scope, who: string | undefined, identity: NotesIdentity): void {
258
260
  if (who === undefined) return;
261
+ // A dreamed project is writable whole; its other sessions are checked per note by assertDreamSessionNote.
262
+ if (identity.dreaming !== undefined && (scope === "session" || (scope === "project" && who === identity.dreaming))) return;
259
263
  if (scope === "session") throw new NoteError("invalid_scope", `@sessions/${who}/ is read-only; use a bare path to write to this session.`);
260
264
  if (scope === "project") throw new NoteError("invalid_scope", `@projects/${who}/ is read-only; use @project/ to write to your own project.`);
261
265
  const current = scope === "agent" ? identity.agent : identity.model;
@@ -264,6 +268,15 @@ function assertWritableHome(scope: Scope, who: string | undefined, identity: Not
264
268
  throw new NoteError("invalid_scope", `${home} is someone else's home; you can write to this session, @project/, @human/, @self/, or @model/.`);
265
269
  }
266
270
 
271
+ /** A dream reaches another session's note only when that note was born in the dreamed project. */
272
+ function assertDreamSessionNote(scope: Scope, who: string | undefined, identity: NotesIdentity, raw: string | undefined, address: string): void {
273
+ if (scope !== "session" || who === undefined || identity.dreaming === undefined) return;
274
+ if (raw !== undefined && parseNote(raw).meta.project === identity.dreaming) return;
275
+ throw new NoteError("invalid_scope", raw === undefined
276
+ ? `${address}: a dream edits other sessions' existing notes, it doesn't create new ones there.`
277
+ : `${address} belongs to another project, not the one being dreamed over (${identity.dreaming}).`);
278
+ }
279
+
267
280
  /** Create a store over one validated, immutable snapshot of the supplied explicit identity. */
268
281
  export function createNotesStore(input: NotesIdentity): NotesStore {
269
282
  const identity = snapshotNotesIdentity(input);
@@ -282,6 +295,7 @@ export function createNotesStore(input: NotesIdentity): NotesStore {
282
295
  const now = writeStamp();
283
296
  const cleanBody = stripLeadingFrontmatter(content);
284
297
  const existingRaw = await readFileIfExists(path);
298
+ assertDreamSessionNote(scope, destination.who, identity, existingRaw, address);
285
299
  const existing = existingRaw === undefined ? undefined : parseNote(existingRaw, now).meta;
286
300
  const outcome = existing === undefined ? "created" : existing.crumpledAt === undefined ? "overwrote" : "uncrumpled";
287
301
  const meta: NoteMeta = existing ?? {
@@ -313,7 +327,8 @@ export function createNotesStore(input: NotesIdentity): NotesStore {
313
327
  if (raw === undefined) return undefined;
314
328
  const now = Date.now();
315
329
  const parsed = parseNote(raw, now);
316
- if ((scope === "project" || scope === "session") && destination.who !== undefined) return { meta: { ...parsed.meta, scope }, body: parsed.body, resolvedScope: scope };
330
+ // Named homes, and every read during a dream, leave no access stamp.
331
+ if (identity.dreaming !== undefined || ((scope === "project" || scope === "session") && destination.who !== undefined)) return { meta: { ...parsed.meta, scope }, body: parsed.body, resolvedScope: scope };
317
332
  // A read records its own access, exactly as a write records an edit.
318
333
  const meta: NoteMeta = { ...parsed.meta, scope, lastAccessed: now, accessCount: (typeof parsed.meta.accessCount === "number" ? parsed.meta.accessCount : 0) + 1 };
319
334
  await atomicWrite(path, serializeNote(meta, parsed.body));
@@ -340,6 +355,8 @@ export function createNotesStore(input: NotesIdentity): NotesStore {
340
355
  const raw = await readFileIfExists(fromPath);
341
356
  if (raw === undefined) throw new NoteError("not_found", `No note at ${noteIdentity(identity, address).address}.`);
342
357
  const targetRaw = differentPaths ? await readFileIfExists(path) : undefined;
358
+ assertDreamSessionNote(from.scope, from.who, identity, raw, address);
359
+ if (differentPaths) assertDreamSessionNote(scope, destination.who, identity, targetRaw, stableOptions.renameTo!);
343
360
  // Case and symlink aliases must not turn write-then-remove into deleting the result.
344
361
  const sourceReal = targetRaw === undefined ? undefined : await realpath(fromPath);
345
362
  const sameFile = sourceReal !== undefined && sourceReal === await realpath(path);
@@ -404,6 +421,22 @@ export function createNotesStore(input: NotesIdentity): NotesStore {
404
421
  return { meta, replacedCrumpledTarget };
405
422
  }
406
423
 
424
+ async function forget(address: string): Promise<NoteMeta> {
425
+ if (identity.dreaming === undefined) throw new NoteError("invalid_scope", "Only a dream can delete notes; begin one first.");
426
+ const target = assertAddress(address);
427
+ assertWritableHome(target.scope, target.who, identity);
428
+ const path = physicalPath(target.scope, target.path, identity, target.who);
429
+ return withPathQueue(path, async () => {
430
+ const raw = await readFileIfExists(path);
431
+ if (raw === undefined) throw new NoteError("not_found", `No note at ${noteIdentity(identity, address).address}.`);
432
+ assertDreamSessionNote(target.scope, target.who, identity, raw, address);
433
+ const { meta } = parseNote(raw);
434
+ if (meta.crumpledAt === undefined) throw new NoteError("not_crumpled", `${noteIdentity(identity, address).address} isn't crumpled; crumple it before deleting.`);
435
+ await unlink(path);
436
+ return { ...meta, scope: target.scope };
437
+ });
438
+ }
439
+
407
440
  async function* scan(options: NotesQuery, status?: NoteQueryStatus): AsyncGenerator<Omit<NoteRow, "sizeBytes">> {
408
441
  const glob = assertGlobPattern(options.glob);
409
442
  const pattern = glob === "@default" ? undefined : glob;
@@ -496,5 +529,5 @@ export function createNotesStore(input: NotesIdentity): NotesStore {
496
529
  return searchRows(queries, options, { homesUnavailable: [] });
497
530
  }
498
531
 
499
- return { write, read, update, rename, list, search, listWithStatus, searchWithStatus };
532
+ return { write, read, update, rename, forget, list, search, listWithStatus, searchWithStatus };
500
533
  }
@@ -0,0 +1,112 @@
1
+ /** Dream operations: open one project's notes for consolidation, delete crumpled notes, close. */
2
+ import { Type, type Static } from "typebox";
3
+ import { createNotesStore, noteIdentity, type NoteRow, type NotesIdentity } from "../notes/index.js";
4
+ import { projectHomes } from "../notes/project-home.js";
5
+ import { gitCommit } from "../dream/git.js";
6
+ import { acquireDreamLock, dreamLockPath, releaseDreamLock, type DreamLock } from "../dream/lock.js";
7
+ import { failure, renderOutcome, resultSchema, success, type Outcome } from "./result.js";
8
+ import { failureOf, listedFile, NotesListDataSchema, renderListData, snapshot } from "./notes.js";
9
+
10
+ /** The one open dream per session; the host owns where it lives. */
11
+ export type DreamState = { project?: string; lock?: DreamLock };
12
+
13
+ /** Drop an open dream without an end commit, e.g. when its session shuts down. */
14
+ export function abandonDream(state: DreamState): void {
15
+ if (state.lock) releaseDreamLock(state.lock);
16
+ delete state.project;
17
+ delete state.lock;
18
+ }
19
+
20
+ /** The identity a store uses while `state` holds an open dream. */
21
+ export function dreamingIdentity(identity: NotesIdentity, state: DreamState): NotesIdentity {
22
+ return state.project === undefined ? identity : { ...identity, dreaming: state.project };
23
+ }
24
+
25
+ const NOT_DREAMING = "No dream is open; call dream_begin first.";
26
+
27
+ export const dreamBeginParameters = Type.Object({
28
+ project: Type.Optional(Type.String({ description: "(optional, default this project) Project name, as in @projects/<name>/." })),
29
+ }, { additionalProperties: false });
30
+
31
+ export const DreamBeginDataSchema = Type.Object({ project: Type.String(), baseline: Type.String(), ...NotesListDataSchema.properties }, { additionalProperties: false });
32
+ export type DreamBeginData = Static<typeof DreamBeginDataSchema>;
33
+
34
+ function renderBeginData(data: DreamBeginData): string {
35
+ return `dreaming over ${data.project} (baseline ${data.baseline})\n${renderListData(data)}`;
36
+ }
37
+
38
+ export const dreamBegin = {
39
+ name: "dream_begin", label: "Dream begin",
40
+ description: "Dream: open one project's notes for consolidation, one project at a time. Lists its @projects/<name>/ notes and every session note born in it, crumpled ones included. Until dream_end, notes_write/notes_update can edit those addresses and reads leave no access stamp. Takes the project's dream lock and commits a Git baseline of the notes home.",
41
+ parameters: dreamBeginParameters, outputSchema: resultSchema(DreamBeginDataSchema),
42
+ async execute(params: Static<typeof dreamBeginParameters>, identity: NotesIdentity, state: DreamState): Promise<Outcome<DreamBeginData>> {
43
+ if (state.project !== undefined) return failure("already_dreaming", `Already dreaming over ${state.project}; call dream_end before opening another project.`);
44
+ const project = params.project ?? identity.projectKey;
45
+ if (project !== identity.projectKey && !projectHomes(identity.home).some(home => home.name === project)) {
46
+ return failure("not_found", `No project named ${JSON.stringify(project)}; notes_list with glob @projects/*/** shows the names.`);
47
+ }
48
+ const lock = acquireDreamLock(dreamLockPath(identity.home, project));
49
+ if (!lock) return failure("already_dreaming", `Another dream holds ${dreamLockPath(identity.home, project)}. If none is running, delete that file by hand.`);
50
+ try {
51
+ const store = createNotesStore({ ...identity, dreaming: project });
52
+ const rows: NoteRow[] = [];
53
+ const unavailable: string[] = [];
54
+ for (const crumpled of [false, true]) {
55
+ for (const glob of [`@projects/${project}/**`, "@sessions/*/**"]) {
56
+ const result = await store.listWithStatus({ glob, crumpled });
57
+ rows.push(...result.rows.filter(row => row.scope === "project" || row.meta.project === project));
58
+ unavailable.push(...result.status.homesUnavailable);
59
+ }
60
+ }
61
+ rows.sort((a, b) => b.meta.updatedAt - a.meta.updatedAt || a.address.localeCompare(b.address));
62
+ const listed = snapshot(rows.map(row => listedFile(row, identity)), undefined, { homesUnavailable: unavailable }, renderListData);
63
+ if (!listed.ok) { releaseDreamLock(lock); return listed; }
64
+ const baseline = gitCommit(identity.home, `dream baseline ${project}`);
65
+ if (!baseline.ok) { releaseDreamLock(lock); return failure("audit_failed", `Couldn't commit the Git baseline, so nothing could be rolled back; no dream was opened: ${baseline.error}`); }
66
+ Object.assign(state, { project, lock });
67
+ return success({ project, baseline: baseline.commit, ...listed.data });
68
+ } catch (error) { releaseDreamLock(lock); return failureOf(error); }
69
+ },
70
+ render: (result: Outcome<DreamBeginData>): string => renderOutcome(result, renderBeginData),
71
+ } as const;
72
+
73
+ export const dreamForgetParameters = Type.Object({ address: Type.String() }, { additionalProperties: false });
74
+ export const DreamForgetDataSchema = Type.Object({ address: Type.String(), project_key: Type.Optional(Type.String()) }, { additionalProperties: false });
75
+ export type DreamForgetData = Static<typeof DreamForgetDataSchema>;
76
+
77
+ export const dreamForget = {
78
+ name: "dream_forget", label: "Dream forget",
79
+ description: "Dream: permanently delete one crumpled note in the project being dreamed over, or in @human/, @self/, @model/. Crumple it first; live notes refuse.",
80
+ parameters: dreamForgetParameters, outputSchema: resultSchema(DreamForgetDataSchema),
81
+ async execute(params: Static<typeof dreamForgetParameters>, identity: NotesIdentity, state: DreamState): Promise<Outcome<DreamForgetData>> {
82
+ if (state.project === undefined) return failure("not_dreaming", NOT_DREAMING);
83
+ try {
84
+ const dreaming = dreamingIdentity(identity, state);
85
+ await createNotesStore(dreaming).forget(params.address);
86
+ return success(noteIdentity(dreaming, params.address));
87
+ } catch (error) { return failureOf(error); }
88
+ },
89
+ render: (result: Outcome<DreamForgetData>): string => renderOutcome(result, data => `forgot ${data.address}`),
90
+ } as const;
91
+
92
+ export const dreamEndParameters = Type.Object({}, { additionalProperties: false });
93
+ export const DreamEndDataSchema = Type.Object({ project: Type.String(), commit: Type.Optional(Type.String()), audit_error: Type.Optional(Type.String()) }, { additionalProperties: false });
94
+ export type DreamEndData = Static<typeof DreamEndDataSchema>;
95
+
96
+ export const dreamEnd = {
97
+ name: "dream_end", label: "Dream end",
98
+ description: "Dream: close the open dream. Commits the dream's changes to the notes home's Git and releases the lock; the project's notes are read-only again and reads stamp access again.",
99
+ parameters: dreamEndParameters, outputSchema: resultSchema(DreamEndDataSchema),
100
+ async execute(_params: Static<typeof dreamEndParameters>, identity: NotesIdentity, state: DreamState): Promise<Outcome<DreamEndData>> {
101
+ const project = state.project;
102
+ if (project === undefined) return failure("not_dreaming", NOT_DREAMING);
103
+ // The dream closes even when the audit commit fails; the uncommitted changes stay in the work tree.
104
+ const audit = gitCommit(identity.home, `dream ${project}`);
105
+ abandonDream(state);
106
+ return success(audit.ok ? { project, commit: audit.commit } : { project, audit_error: audit.error });
107
+ },
108
+ render: (result: Outcome<DreamEndData>): string => renderOutcome(result, data => data.commit !== undefined
109
+ ? `woke from ${data.project} (commit ${data.commit})`
110
+ : `woke from ${data.project}; the Git commit failed, changes are uncommitted: ${data.audit_error}`),
111
+ } as const;
112
+