notesoup 0.51.9 → 0.52.2

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 (76) hide show
  1. package/README.md +3 -10
  2. package/dist/plugins/claude/src/history.js +9 -12
  3. package/dist/plugins/pi/notes/tools.d.ts +1 -1
  4. package/dist/plugins/pi/notes/tools.js +26 -7
  5. package/dist/plugins/pi/tool-result.d.ts +3 -2
  6. package/dist/plugins/pi/tool-result.js +3 -1
  7. package/dist/src/dream/git.d.ts +2 -3
  8. package/dist/src/dream/git.js +3 -8
  9. package/dist/src/dream/lock.d.ts +10 -27
  10. package/dist/src/dream/lock.js +16 -79
  11. package/dist/src/history/query.js +2 -1
  12. package/dist/src/notes/errors.d.ts +1 -1
  13. package/dist/src/notes/identity.d.ts +2 -0
  14. package/dist/src/notes/identity.js +3 -1
  15. package/dist/src/notes/store.d.ts +2 -0
  16. package/dist/src/notes/store.js +40 -4
  17. package/dist/src/tools/dream.d.ts +113 -0
  18. package/dist/src/tools/dream.js +112 -0
  19. package/dist/src/tools/history.js +1 -1
  20. package/dist/src/tools/notes.d.ts +15 -1
  21. package/dist/src/tools/notes.js +4 -4
  22. package/dist/test/claude-history.test.js +49 -2
  23. package/dist/test/claude-mod.test.js +136 -30
  24. package/dist/test/dependencies.test.js +3 -6
  25. package/dist/test/dream-skill.test.js +2 -3
  26. package/dist/test/dream-tools.test.js +67 -0
  27. package/docs/claude-code-mod.md +2 -2
  28. package/docs/notes-library.md +1 -1
  29. package/docs/skills.md +12 -15
  30. package/package.json +2 -5
  31. package/plugins/claude/.claude-plugin/plugin.json +1 -1
  32. package/plugins/claude/dist/claude/helper.js +36 -29
  33. package/plugins/claude/hooks/register.ts +71 -47
  34. package/plugins/claude/src/history.ts +9 -11
  35. package/plugins/pi/notes/tools.ts +25 -8
  36. package/plugins/pi/tool-result.ts +4 -1
  37. package/src/dream/git.ts +3 -8
  38. package/src/dream/lock.ts +18 -66
  39. package/src/history/query.ts +2 -1
  40. package/src/notes/errors.ts +1 -1
  41. package/src/notes/identity.ts +4 -1
  42. package/src/notes/store.ts +37 -4
  43. package/src/tools/dream.ts +112 -0
  44. package/src/tools/history.ts +1 -1
  45. package/src/tools/notes.ts +4 -4
  46. package/dist/plugins/pi/dream/cli.d.ts +0 -10
  47. package/dist/plugins/pi/dream/cli.js +0 -173
  48. package/dist/plugins/pi/dream/runner.d.ts +0 -27
  49. package/dist/plugins/pi/dream/runner.js +0 -91
  50. package/dist/plugins/pi/dream/settings.d.ts +0 -7
  51. package/dist/plugins/pi/dream/settings.js +0 -17
  52. package/dist/src/dream/doctor.d.ts +0 -2
  53. package/dist/src/dream/doctor.js +0 -161
  54. package/dist/src/dream/gates.d.ts +0 -10
  55. package/dist/src/dream/gates.js +0 -26
  56. package/dist/src/dream/jail.d.ts +0 -11
  57. package/dist/src/dream/jail.js +0 -71
  58. package/dist/src/dream/report.d.ts +0 -7
  59. package/dist/src/dream/report.js +0 -34
  60. package/dist/src/dream/result.d.ts +0 -9
  61. package/dist/src/dream/settings.d.ts +0 -9
  62. package/dist/src/dream/settings.js +0 -16
  63. package/dist/test/doctor.test.d.ts +0 -1
  64. package/dist/test/doctor.test.js +0 -37
  65. package/dist/test/dream.test.d.ts +0 -1
  66. package/dist/test/dream.test.js +0 -150
  67. package/plugins/pi/dream/cli.ts +0 -118
  68. package/plugins/pi/dream/runner.ts +0 -92
  69. package/plugins/pi/dream/settings.ts +0 -17
  70. package/src/dream/doctor.ts +0 -118
  71. package/src/dream/gates.ts +0 -26
  72. package/src/dream/jail.ts +0 -62
  73. package/src/dream/report.ts +0 -32
  74. package/src/dream/result.ts +0 -2
  75. package/src/dream/settings.ts +0 -19
  76. /package/dist/{src/dream/result.js → test/dream-tools.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); }
@@ -117,15 +113,16 @@ const BOOT_IDENTITY = /^<(?:notesoup:window_identity|context_window)>\nAgent nam
117
113
  const BOOT_PROTOCOL_OPEN = /\n<(?:notesoup:notes_protocol|context_window_protocol)>\n/;
118
114
  const BOOT_PROTOCOL_CLOSE = /\n<\/(?:notesoup:notes_protocol|context_window_protocol)>/;
119
115
  /** Match the complete retained notesoup boot, not a casually quoted window-id line. */
120
- function bootOrdinal(row, sessionId, retained) {
116
+ function bootOrdinal(row, retained) {
121
117
  if (!retained || row.type !== "user" || !object(row.message))
122
118
  return undefined;
123
119
  const text = contentText(row.message.content);
124
120
  if (!BOOT_IDENTITY.test(text) || !BOOT_PROTOCOL_OPEN.test(text) || !BOOT_PROTOCOL_CLOSE.test(text))
125
121
  return undefined;
126
- const prefix = `Current context window id: claude:${sessionId}:`;
127
- const suffix = text.split("\n").find((line) => line.startsWith(prefix))?.slice(prefix.length);
128
- if (suffix === undefined || !/^\d+$/.test(suffix))
122
+ // A fork copies the retained boot verbatim. Its ordinal survives, while
123
+ // public window ids below always belong to the current transcript session.
124
+ const suffix = /^Current context window id: claude:[^\n]+:(\d+)$/m.exec(text)?.[1];
125
+ if (suffix === undefined)
129
126
  return undefined;
130
127
  const ordinal = Number(suffix);
131
128
  return Number.isSafeInteger(ordinal) ? ordinal : undefined;
@@ -135,10 +132,10 @@ export function claudeHistoryFromJsonl(text, source) {
135
132
  const nodes = new Map();
136
133
  let nextSeq = 1;
137
134
  for (const row of rowsOf(text)) {
138
- if (METADATA.has(row.type))
139
- continue;
135
+ // Ignore non-message records, including future metadata. A skipped UUID that
136
+ // the selected branch actually requires still fails ancestry resolution below.
140
137
  if (!MESSAGE_TYPES.has(row.type))
141
- throw new Error(`unsupported Claude transcript record type: ${row.type}`);
138
+ continue;
142
139
  const uuid = requiredString(row.uuid, "uuid");
143
140
  parent(row);
144
141
  if (row.sessionId !== source.sessionId)
@@ -184,7 +181,7 @@ export function claudeHistoryFromJsonl(text, source) {
184
181
  let before = cursor.ordinal ?? 0;
185
182
  for (const current of chain.reverse()) {
186
183
  const retained = current.row.isCompactSummary === true || (current.ancestor !== undefined && boundary(current.ancestor.row));
187
- const marked = bootOrdinal(current.row, source.sessionId, retained);
184
+ const marked = bootOrdinal(current.row, retained);
188
185
  current.ordinal = marked === undefined ? before + (boundary(current.row) ? 1 : 0) : Math.max(before, marked);
189
186
  before = current.ordinal;
190
187
  }
@@ -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,16 +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
5
  import { notesReadRenderers, notesUpdateRenderers, notesWriteRenderers } from "../render.js";
5
- import { NOTES_NAMESPACE, registerOperation } from "../tool-result.js";
6
+ import { DREAM_NAMESPACE, NOTES_NAMESPACE, registerOperation } from "../tool-result.js";
6
7
  function renderDiff(change) {
7
8
  return change.kind === "none" ? "" : generateDiffString(change.before, change.after, 1).diff;
8
9
  }
9
- /** 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. */
10
11
  export function registerNotesTools(pi) {
11
- registerOperation(pi, notesWrite, (params, ctx) => notesWrite.execute(params, notesIdentityFromPi(ctx)), NOTES_NAMESPACE, notesWriteRenderers);
12
- registerOperation(pi, notesUpdate, (params, ctx) => notesUpdate.execute(params, notesIdentityFromPi(ctx), renderDiff), NOTES_NAMESPACE, notesUpdateRenderers);
13
- registerOperation(pi, notesRead, (params, ctx) => notesRead.execute(params, notesIdentityFromPi(ctx)), NOTES_NAMESPACE, notesReadRenderers);
14
- registerOperation(pi, notesList, (params, ctx) => notesList.execute(params, notesIdentityFromPi(ctx)), NOTES_NAMESPACE);
15
- 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");
16
35
  }
@@ -1,5 +1,5 @@
1
1
  /** Pi transport for host-neutral operations. */
2
- import { type ExtensionAPI, type ExtensionToolContext, type ToolDefinition } 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,8 +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;
21
22
  /** Optional TUI renderers; without them the host draws its default call line and receipt text. */
22
23
  export type OperationRenderers<TParams extends TSchema> = Pick<ToolDefinition<TParams, undefined>, "renderCall" | "renderResult">;
23
24
  /** Register `operation` as a Pi tool; `run` supplies only the host context it needs. */
24
- 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>): 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, renderers) {
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,7 @@ export function registerOperation(pi, operation, run, namespace, renderers) {
28
29
  outputSchema: operation.outputSchema,
29
30
  executionMode: operation.executionMode,
30
31
  ...(namespace ? { namespace } : {}),
32
+ ...(exposure ? { exposure } : {}),
31
33
  ...renderers,
32
34
  async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
33
35
  return piOperationResult(operation.render, await run(params, ctx));
@@ -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
  }
@@ -85,7 +85,8 @@ function prepareSelection(projection, params) {
85
85
  run.push(event);
86
86
  continue;
87
87
  }
88
- if (folds && eventDocument(event) === "")
88
+ // Tool/thinking-only envelopes are not dialogue, even with explicit roles.
89
+ if ((event.role === "user" || event.role === "assistant") && eventDocument(event) === "")
89
90
  continue;
90
91
  const matchOffset = params.query === undefined ? undefined : earliestMatchOffsetChars(eventDocument(event), params.query);
91
92
  if (matchOffset !== undefined && matchOffset < 0)
@@ -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>>;
@@ -1,5 +1,5 @@
1
1
  import { randomUUID } from "node:crypto";
2
- import { mkdir, readdir, readFile, realpath, rename, rm, writeFile } from "node:fs/promises";
2
+ import { mkdir, readdir, readFile, realpath, rename, rm, unlink, writeFile } from "node:fs/promises";
3
3
  import { dirname, join, resolve } from "node:path";
4
4
  import { earliestMatchOffsetChars } from "../text-match.js";
5
5
  import { assertAddress, assertGlobPattern, addressFor, canonicalAddressFor, globToRegExp, HOME_HEADS } from "./address.js";
@@ -218,10 +218,13 @@ function assertSerializedSize(content) {
218
218
  function frontmatterOf(meta) {
219
219
  return serializeNote(meta, "").slice(0, -2);
220
220
  }
221
- /** Explicit session/project homes are always read-only; agent/model homes allow their owner. */
221
+ /** Explicit session/project homes are read-only unless dreamed over; agent/model homes allow their owner. */
222
222
  function assertWritableHome(scope, who, identity) {
223
223
  if (who === undefined)
224
224
  return;
225
+ // A dreamed project is writable whole; its other sessions are checked per note by assertDreamSessionNote.
226
+ if (identity.dreaming !== undefined && (scope === "session" || (scope === "project" && who === identity.dreaming)))
227
+ return;
225
228
  if (scope === "session")
226
229
  throw new NoteError("invalid_scope", `@sessions/${who}/ is read-only; use a bare path to write to this session.`);
227
230
  if (scope === "project")
@@ -232,6 +235,16 @@ function assertWritableHome(scope, who, identity) {
232
235
  const home = scope === "agent" ? `@agents/${who}/` : `@models/${who}/`;
233
236
  throw new NoteError("invalid_scope", `${home} is someone else's home; you can write to this session, @project/, @human/, @self/, or @model/.`);
234
237
  }
238
+ /** A dream reaches another session's note only when that note was born in the dreamed project. */
239
+ function assertDreamSessionNote(scope, who, identity, raw, address) {
240
+ if (scope !== "session" || who === undefined || identity.dreaming === undefined)
241
+ return;
242
+ if (raw !== undefined && parseNote(raw).meta.project === identity.dreaming)
243
+ return;
244
+ throw new NoteError("invalid_scope", raw === undefined
245
+ ? `${address}: a dream edits other sessions' existing notes, it doesn't create new ones there.`
246
+ : `${address} belongs to another project, not the one being dreamed over (${identity.dreaming}).`);
247
+ }
235
248
  /** Create a store over one validated, immutable snapshot of the supplied explicit identity. */
236
249
  export function createNotesStore(input) {
237
250
  const identity = snapshotNotesIdentity(input);
@@ -249,6 +262,7 @@ export function createNotesStore(input) {
249
262
  const now = writeStamp();
250
263
  const cleanBody = stripLeadingFrontmatter(content);
251
264
  const existingRaw = await readFileIfExists(path);
265
+ assertDreamSessionNote(scope, destination.who, identity, existingRaw, address);
252
266
  const existing = existingRaw === undefined ? undefined : parseNote(existingRaw, now).meta;
253
267
  const outcome = existing === undefined ? "created" : existing.crumpledAt === undefined ? "overwrote" : "uncrumpled";
254
268
  const meta = existing ?? {
@@ -281,7 +295,8 @@ export function createNotesStore(input) {
281
295
  return undefined;
282
296
  const now = Date.now();
283
297
  const parsed = parseNote(raw, now);
284
- if ((scope === "project" || scope === "session") && destination.who !== undefined)
298
+ // Named homes, and every read during a dream, leave no access stamp.
299
+ if (identity.dreaming !== undefined || ((scope === "project" || scope === "session") && destination.who !== undefined))
285
300
  return { meta: { ...parsed.meta, scope }, body: parsed.body, resolvedScope: scope };
286
301
  // A read records its own access, exactly as a write records an edit.
287
302
  const meta = { ...parsed.meta, scope, lastAccessed: now, accessCount: (typeof parsed.meta.accessCount === "number" ? parsed.meta.accessCount : 0) + 1 };
@@ -309,6 +324,9 @@ export function createNotesStore(input) {
309
324
  if (raw === undefined)
310
325
  throw new NoteError("not_found", `No note at ${noteIdentity(identity, address).address}.`);
311
326
  const targetRaw = differentPaths ? await readFileIfExists(path) : undefined;
327
+ assertDreamSessionNote(from.scope, from.who, identity, raw, address);
328
+ if (differentPaths)
329
+ assertDreamSessionNote(scope, destination.who, identity, targetRaw, stableOptions.renameTo);
312
330
  // Case and symlink aliases must not turn write-then-remove into deleting the result.
313
331
  const sourceReal = targetRaw === undefined ? undefined : await realpath(fromPath);
314
332
  const sameFile = sourceReal !== undefined && sourceReal === await realpath(path);
@@ -388,6 +406,24 @@ export function createNotesStore(input) {
388
406
  const { meta, replacedCrumpledTarget } = await update(fromAddress, undefined, { renameTo: toAddress });
389
407
  return { meta, replacedCrumpledTarget };
390
408
  }
409
+ async function forget(address) {
410
+ if (identity.dreaming === undefined)
411
+ throw new NoteError("invalid_scope", "Only a dream can delete notes; begin one first.");
412
+ const target = assertAddress(address);
413
+ assertWritableHome(target.scope, target.who, identity);
414
+ const path = physicalPath(target.scope, target.path, identity, target.who);
415
+ return withPathQueue(path, async () => {
416
+ const raw = await readFileIfExists(path);
417
+ if (raw === undefined)
418
+ throw new NoteError("not_found", `No note at ${noteIdentity(identity, address).address}.`);
419
+ assertDreamSessionNote(target.scope, target.who, identity, raw, address);
420
+ const { meta } = parseNote(raw);
421
+ if (meta.crumpledAt === undefined)
422
+ throw new NoteError("not_crumpled", `${noteIdentity(identity, address).address} isn't crumpled; crumple it before deleting.`);
423
+ await unlink(path);
424
+ return { ...meta, scope: target.scope };
425
+ });
426
+ }
391
427
  async function* scan(options, status) {
392
428
  const glob = assertGlobPattern(options.glob);
393
429
  const pattern = glob === "@default" ? undefined : glob;
@@ -480,5 +516,5 @@ export function createNotesStore(input) {
480
516
  function searchWithStatus(queries, options = {}) {
481
517
  return searchRows(queries, options, { homesUnavailable: [] });
482
518
  }
483
- return { write, read, update, rename, list, search, listWithStatus, searchWithStatus };
519
+ return { write, read, update, rename, forget, list, search, listWithStatus, searchWithStatus };
484
520
  }