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
@@ -7,10 +7,6 @@ type Row = Record<string, unknown>;
7
7
  type Version = { row: Row; ancestorUuid?: string; ancestor?: Version; ordinal?: number };
8
8
  type Node = { first: Version; latest: Version; items: DecodedHistoryItem[] };
9
9
  export type ClaudeHistorySource = { sessionId: string; transcriptPath: string; headUuid?: string };
10
- const METADATA = new Set([
11
- "queue-operation", "last-prompt", "atis-latch", "mode", "permission-mode", "file-history-snapshot", "cost-state",
12
- "summary", "custom-title", "agent-name", "agent-color", "tag", "session-title", "progress",
13
- ]);
14
10
  const MESSAGE_TYPES = new Set(["user", "assistant", "system", "attachment"]);
15
11
  const NON_TEXT_BLOCKS = new Set(["thinking", "redacted_thinking", "image", "document", "audio", "video", "server_tool_use", "web_search_tool_result", "tool_reference"]);
16
12
  function object(value: unknown): value is Row { return typeof value === "object" && value !== null && !Array.isArray(value); }
@@ -103,13 +99,14 @@ const BOOT_PROTOCOL_OPEN = /\n<(?:notesoup:notes_protocol|context_window_protoco
103
99
  const BOOT_PROTOCOL_CLOSE = /\n<\/(?:notesoup:notes_protocol|context_window_protocol)>/;
104
100
 
105
101
  /** Match the complete retained notesoup boot, not a casually quoted window-id line. */
106
- function bootOrdinal(row: Row, sessionId: string, retained: boolean): number | undefined {
102
+ function bootOrdinal(row: Row, retained: boolean): number | undefined {
107
103
  if (!retained || row.type !== "user" || !object(row.message)) return undefined;
108
104
  const text = contentText(row.message.content);
109
105
  if (!BOOT_IDENTITY.test(text) || !BOOT_PROTOCOL_OPEN.test(text) || !BOOT_PROTOCOL_CLOSE.test(text)) return undefined;
110
- const prefix = `Current context window id: claude:${sessionId}:`;
111
- const suffix = text.split("\n").find((line) => line.startsWith(prefix))?.slice(prefix.length);
112
- if (suffix === undefined || !/^\d+$/.test(suffix)) return undefined;
106
+ // A fork copies the retained boot verbatim. Its ordinal survives, while
107
+ // public window ids below always belong to the current transcript session.
108
+ const suffix = /^Current context window id: claude:[^\n]+:(\d+)$/m.exec(text)?.[1];
109
+ if (suffix === undefined) return undefined;
113
110
  const ordinal = Number(suffix);
114
111
  return Number.isSafeInteger(ordinal) ? ordinal : undefined;
115
112
  }
@@ -119,8 +116,9 @@ export function claudeHistoryFromJsonl(text: string, source: Omit<ClaudeHistoryS
119
116
  const nodes = new Map<string, Node>();
120
117
  let nextSeq = 1;
121
118
  for (const row of rowsOf(text)) {
122
- if (METADATA.has(row.type as string)) continue;
123
- if (!MESSAGE_TYPES.has(row.type as string)) throw new Error(`unsupported Claude transcript record type: ${row.type}`);
119
+ // Ignore non-message records, including future metadata. A skipped UUID that
120
+ // the selected branch actually requires still fails ancestry resolution below.
121
+ if (!MESSAGE_TYPES.has(row.type as string)) continue;
124
122
  const uuid = requiredString(row.uuid, "uuid");
125
123
  parent(row);
126
124
  if (row.sessionId !== source.sessionId) throw new Error("Claude transcript belongs to a different session");
@@ -161,7 +159,7 @@ export function claudeHistoryFromJsonl(text: string, source: Omit<ClaudeHistoryS
161
159
  let before = cursor.ordinal ?? 0;
162
160
  for (const current of chain.reverse()) {
163
161
  const retained = current.row.isCompactSummary === true || (current.ancestor !== undefined && boundary(current.ancestor.row));
164
- const marked = bootOrdinal(current.row, source.sessionId, retained);
162
+ const marked = bootOrdinal(current.row, retained);
165
163
  current.ordinal = marked === undefined ? before + (boundary(current.row) ? 1 : 0) : Math.max(before, marked);
166
164
  before = current.ordinal;
167
165
  }
@@ -1,19 +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
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
  import type { NoteChange } from "../../../src/notes/index.js";
7
8
 
8
9
  function renderDiff(change: NoteChange): string {
9
10
  return change.kind === "none" ? "" : generateDiffString(change.before, change.after, 1).diff;
10
11
  }
11
12
 
12
- /** 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. */
13
14
  export function registerNotesTools(pi: ExtensionAPI) {
14
- registerOperation(pi, notesWrite, (params, ctx) => notesWrite.execute(params, notesIdentityFromPi(ctx)), NOTES_NAMESPACE, notesWriteRenderers);
15
- registerOperation(pi, notesUpdate, (params, ctx) => notesUpdate.execute(params, notesIdentityFromPi(ctx), renderDiff), NOTES_NAMESPACE, notesUpdateRenderers);
16
- registerOperation(pi, notesRead, (params, ctx) => notesRead.execute(params, notesIdentityFromPi(ctx)), NOTES_NAMESPACE, notesReadRenderers);
17
- registerOperation(pi, notesList, (params, ctx) => notesList.execute(params, notesIdentityFromPi(ctx)), NOTES_NAMESPACE);
18
- 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");
19
36
  }
@@ -1,5 +1,5 @@
1
1
  /** Pi transport for host-neutral operations. */
2
- import { defineTool, type ExtensionAPI, type ExtensionToolContext, type ToolDefinition } 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,6 +24,7 @@ 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
 
29
30
  /** Optional TUI renderers; without them the host draws its default call line and receipt text. */
@@ -36,6 +37,7 @@ export function registerOperation<TParams extends TSchema, TData, TRest extends
36
37
  run: (params: Static<TParams>, ctx: ExtensionToolContext) => Promise<Outcome<TData>>,
37
38
  namespace?: ToolNamespace,
38
39
  renderers?: OperationRenderers<TParams>,
40
+ exposure?: ToolExposure,
39
41
  ): void {
40
42
  pi.registerTool(defineTool<TParams, undefined>({
41
43
  name: operation.name,
@@ -45,6 +47,7 @@ export function registerOperation<TParams extends TSchema, TData, TRest extends
45
47
  outputSchema: operation.outputSchema,
46
48
  executionMode: operation.executionMode,
47
49
  ...(namespace ? { namespace } : {}),
50
+ ...(exposure ? { exposure } : {}),
48
51
  ...renderers,
49
52
  async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
50
53
  return piOperationResult(operation.render, await run(params, ctx));
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
  }
@@ -108,7 +108,8 @@ function prepareSelection(projection: HistoryProjection, params: HistorySelectio
108
108
  run.push(event);
109
109
  continue;
110
110
  }
111
- if (folds && eventDocument(event) === "") continue;
111
+ // Tool/thinking-only envelopes are not dialogue, even with explicit roles.
112
+ if ((event.role === "user" || event.role === "assistant") && eventDocument(event) === "") continue;
112
113
  const matchOffset = params.query === undefined ? undefined : earliestMatchOffsetChars(eventDocument(event), params.query as string[]);
113
114
  if (matchOffset !== undefined && matchOffset < 0) continue;
114
115
  candidates.push({ event, matchOffset, before: foldedRun(run) });
@@ -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
+
@@ -75,7 +75,7 @@ function renderRead(data: HistoryReadData): string {
75
75
  const tool = toolHeader(data);
76
76
  const afterSeq = data.seq - 10;
77
77
  const neighborhood = `neighborhood → \`history_list\`(${JSON.stringify({ ...(afterSeq >= 1 ? { after_seq: afterSeq } : {}), before_seq: data.seq + 10 })})`;
78
- return [header(data), ...(tool ? [tool] : []), neighborhood, "", renderTextWindow(data)].join("\n");
78
+ return [header(data), ...(tool ? [tool] : []), neighborhood, "", data.total_chars === 0 ? "No visible text recorded for this event." : renderTextWindow(data)].join("\n");
79
79
  }
80
80
 
81
81
  /* ------------------------------------------------------------------ shared bounding */
@@ -22,7 +22,7 @@ const ADDRESS_DESCRIPTION = "Addresses: a bare path is this session's note; `@pr
22
22
  * Typed refusal. Every fact a caller needs is already in the message; there is no separate context.
23
23
  * Convert expected refusals; unexpected errors propagate unchanged.
24
24
  */
25
- function failureOf(error: unknown): Outcome<never> {
25
+ export function failureOf(error: unknown): Outcome<never> {
26
26
  if (error instanceof NoteError) return failure(error.code, error.message);
27
27
  // Address, glob, and query guards raise declared types; nothing else is converted.
28
28
  if (error instanceof InvalidQueryError) return failure("invalid_query", error.message);
@@ -169,7 +169,7 @@ export type NotesSearchData = Static<typeof NotesSearchDataSchema>;
169
169
  type Snapshot<T> = Omit<NotesListData, "files"> & { files: T[] };
170
170
 
171
171
  /** Keep identities intact. Only search previews may shrink to make the first row fit. */
172
- function snapshot<T extends { address: string }>(
172
+ export function snapshot<T extends { address: string }>(
173
173
  rows: T[],
174
174
  limit: number | undefined,
175
175
  status: NoteQueryStatus,
@@ -196,7 +196,7 @@ function snapshot<T extends { address: string }>(
196
196
  return fitsResult(outcome, render) ? outcome : failure("output_too_large", `The list of unreachable homes is itself over ${TOOL_OUTPUT_LIMIT}; narrow \`glob\` to fewer homes.`);
197
197
  }
198
198
 
199
- function listedFile(row: Pick<NoteRow, "address" | "meta">, identity: NotesIdentity): NotesListData["files"][number] {
199
+ export function listedFile(row: Pick<NoteRow, "address" | "meta">, identity: NotesIdentity): NotesListData["files"][number] {
200
200
  return { ...noteIdentity(identity, row.address), updated_at: localIso(row.meta.updatedAt), ...(row.meta.crumpledAt === undefined ? {} : { crumpled_at: row.meta.crumpledAt }) };
201
201
  }
202
202
 
@@ -300,7 +300,7 @@ export const notesRead = {
300
300
 
301
301
  export const notesListParameters = Type.Object({ glob: GLOB_PARAMETER, limit: FILE_LIMIT_PARAMETER, crumpled: CRUMPLED_LIST_PARAMETER }, { additionalProperties: false });
302
302
 
303
- function renderListData(data: NotesListData): string {
303
+ export function renderListData(data: NotesListData): string {
304
304
  const lines = [`${data.files.length} ${data.files.length === 1 ? "note" : "notes"}`];
305
305
  for (const file of data.files) {
306
306
  lines.push(`- ${renderIdentity(file)} | updated ${file.updated_at}${file.crumpled_at === undefined ? "" : ` | crumpled ${file.crumpled_at}`}`);
@@ -1,10 +0,0 @@
1
- #!/usr/bin/env node
2
- import type { DreamerSetting } from "../../../src/dream/settings.js";
3
- import { runDreamer, type DreamerSessionFactory } from "./runner.js";
4
- /** Injection seams used by tests; production uses the defaults. */
5
- export type DreamDependencies = {
6
- sessionFactory?: DreamerSessionFactory;
7
- dreamerSettings?: (cwd?: string) => DreamerSetting;
8
- runDreamer?: typeof runDreamer;
9
- };
10
- export declare function main(argv?: string[], deps?: DreamDependencies): Promise<number>;