notesoup 0.60.0 → 0.61.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. package/README.md +5 -4
  2. package/dist/src/boot/render.d.ts +5 -0
  3. package/dist/src/boot/render.js +48 -19
  4. package/dist/src/boot/text.d.ts +1 -3
  5. package/dist/src/boot/text.js +10 -11
  6. package/dist/src/budget/text.d.ts +1 -1
  7. package/dist/src/budget/text.js +1 -1
  8. package/dist/src/dream/git.js +12 -13
  9. package/dist/src/notes/errors.d.ts +1 -1
  10. package/dist/src/notes/frontmatter.d.ts +6 -0
  11. package/dist/src/notes/frontmatter.js +17 -1
  12. package/dist/src/notes/policy.js +1 -1
  13. package/dist/src/notes/project-namespace.js +39 -73
  14. package/dist/src/notes/store.d.ts +2 -0
  15. package/dist/src/notes/store.js +30 -5
  16. package/dist/src/sqlite-lock.d.ts +2 -0
  17. package/dist/src/sqlite-lock.js +17 -0
  18. package/dist/src/tools/dream.d.ts +4 -4
  19. package/dist/src/tools/dream.js +15 -16
  20. package/dist/src/tools/notes.d.ts +10 -0
  21. package/dist/src/tools/notes.js +14 -8
  22. package/dist/test/dream-tools.test.js +42 -14
  23. package/dist/test/host-neutral.test.js +1 -1
  24. package/dist/test/note-policy.test.js +122 -8
  25. package/dist/test/notes.integration.test.js +3 -7
  26. package/dist/test/project-namespace.test.js +33 -88
  27. package/docs/dsh.md +2 -2
  28. package/docs/notes-library.md +10 -4
  29. package/docs/reset-lifecycle.md +1 -1
  30. package/docs/skills.md +2 -6
  31. package/docs/tool-results.md +1 -1
  32. package/package.json +1 -1
  33. package/playbook.md +3 -3
  34. package/plugins/claude/.claude-plugin/plugin.json +1 -1
  35. package/plugins/claude/dist/claude/helper.js +150 -103
  36. package/plugins/claude/playbook.md +3 -3
  37. package/plugins/claude/skills/dream/SKILL.md +2 -2
  38. package/plugins/claude/skills/memory/SKILL.md +1 -1
  39. package/plugins/codex/dist/codex/notesoup.js +149 -102
  40. package/skills/dream/SKILL.md +2 -2
  41. package/skills/memory/SKILL.md +1 -1
  42. package/src/boot/render.ts +48 -17
  43. package/src/boot/text.ts +10 -11
  44. package/src/budget/text.ts +1 -1
  45. package/src/dream/git.ts +11 -11
  46. package/src/notes/errors.ts +1 -1
  47. package/src/notes/frontmatter.ts +19 -1
  48. package/src/notes/policy.ts +1 -1
  49. package/src/notes/project-namespace.ts +37 -59
  50. package/src/notes/store.ts +25 -7
  51. package/src/sqlite-lock.ts +14 -0
  52. package/src/tools/dream.ts +15 -14
  53. package/src/tools/notes.ts +14 -8
  54. package/dist/src/dream/lock.d.ts +0 -14
  55. package/dist/src/dream/lock.js +0 -29
  56. package/src/dream/lock.ts +0 -28
@@ -1,6 +1,8 @@
1
1
  import type { NotesNamespace, NotesSnapshot } from "./snapshot.js";
2
2
  import { effectiveNotePolicy, MAX_PINNED_NOTES, noteBudgetWarnings, pinnedPageOrder } from "../notes/policy.js";
3
- import { WINDOW_IDENTITY_OPEN_TAG, WINDOW_IDENTITY_CLOSE_TAG, MAPS_BLOCK, NAMELESS_AGENT, SHELF_FRESH_LIMIT, renderProtocolBlock, type BootToolNames } from "./text.js";
3
+ import { collapseDescription, MAX_DESCRIPTION_CHARS } from "../notes/frontmatter.js";
4
+ import type { NoteRow } from "../notes/index.js";
5
+ import { WINDOW_IDENTITY_OPEN_TAG, WINDOW_IDENTITY_CLOSE_TAG, MAPS_BLOCK, NAMELESS_AGENT, renderProtocolBlock, type BootToolNames } from "./text.js";
4
6
 
5
7
  function relativeTime(timestamp: number, now: number): string {
6
8
  const seconds = Math.trunc((timestamp - now) / 1000);
@@ -11,16 +13,38 @@ function relativeTime(timestamp: number, now: number): string {
11
13
  return seconds > 0 ? `in ${amount}` : `${amount} ago`;
12
14
  }
13
15
 
14
- /** A feed entry is announced in the note's own words: its first heading, else its first line, cut short. */
15
- const FEED_TITLE_MAX_CHARS = 40;
16
+ /** The shelf index is bounded: enough to find a page, never the whole drawer. */
17
+ export const SHELF_INDEX_MAX_ENTRIES = 25;
18
+ export const SHELF_INDEX_MAX_CHARS = 4096;
19
+ /** A fallback title is the note's own first heading or line, cut short. */
20
+ export const FALLBACK_TITLE_MAX_CHARS = 80;
21
+
22
+ function truncated(text: string, max: number): string {
23
+ const chars = Array.from(text);
24
+ return chars.length > max ? `${chars.slice(0, max).join("")}…` : chars.join("");
25
+ }
16
26
 
17
27
  function feedTitle(body: string): string | undefined {
18
28
  const lines = body.split("\n");
19
29
  const heading = lines.find((line) => /^#+\s+\S/.test(line));
20
30
  const raw = (heading ? heading.replace(/^#+\s+/, "") : lines.find((line) => line.trim().length > 0) ?? "").trim();
21
- if (raw.length === 0) return undefined;
22
- const chars = Array.from(raw);
23
- return chars.length > FEED_TITLE_MAX_CHARS ? `${chars.slice(0, FEED_TITLE_MAX_CHARS).join("")}…` : chars.join("");
31
+ return raw.length === 0 ? undefined : truncated(raw, FALLBACK_TITLE_MAX_CHARS);
32
+ }
33
+
34
+ /** A stale hand-edited description is cut for display; the authored value was already refused at write time. */
35
+ function summaryOf(row: NoteRow): string | undefined {
36
+ if (typeof row.meta.description === "string") {
37
+ const collapsed = collapseDescription(row.meta.description);
38
+ return collapsed === undefined ? undefined : truncated(collapsed, MAX_DESCRIPTION_CHARS);
39
+ }
40
+ return feedTitle(row.body);
41
+ }
42
+
43
+ /** One index entry: where the page sits, how fresh it is, and one line saying whether to open it. */
44
+ function indexLine(row: NoteRow, openedAt: number): string {
45
+ const locator = `${row.address} · ${relativeTime(row.meta.updatedAt, openedAt)}`;
46
+ const summary = summaryOf(row);
47
+ return summary === undefined ? ` ${locator}` : ` ${locator} — ${summary}`;
24
48
  }
25
49
 
26
50
  /** Two spaces of indent say "shelved content" without any furniture. */
@@ -33,7 +57,7 @@ function section(label: string, body: string): string {
33
57
  return `${label}\n${"─".repeat(Array.from(label).length)}\n\n${body}`;
34
58
  }
35
59
 
36
- /** One closed boot snapshot: five tabbed shelves, current hands first, durable last; each shelf keeps its pinned pages and its own freshest pages. */
60
+ /** One closed boot snapshot: five tabbed shelves, current hands first, durable last; each shelf keeps its pinned pages and an auto-indexed glimpse of the rest. */
37
61
  function notesIndex(snapshot: NotesSnapshot, tools: BootToolNames, agentName: string, modelName: string): string {
38
62
  const namespaces: ReadonlyArray<{ scope: NotesNamespace["scope"]; label: string }> = [
39
63
  { scope: "session", label: "no @ — this session" },
@@ -53,21 +77,28 @@ function notesIndex(snapshot: NotesSnapshot, tools: BootToolNames, agentName: st
53
77
  const pins = rows.filter(row => effectiveNotePolicy(row.meta, row.path).pinned)
54
78
  .sort((a, b) => pinnedPageOrder(a.path) - pinnedPageOrder(b.path) || a.path.localeCompare(b.path));
55
79
  const pinned = pins.slice(0, MAX_PINNED_NOTES);
56
- const fresh = rows
57
- .filter(row => !effectiveNotePolicy(row.meta, row.path).pinned)
58
- .slice(0, SHELF_FRESH_LIMIT)
59
- .map((row) => {
60
- const locator = `${row.address} · ${relativeTime(row.meta.updatedAt, snapshot.openedAt)}`;
61
- const title = feedTitle(row.body);
62
- return title === undefined ? ` ${locator}` : ` ${title}\n ${locator}`;
63
- });
64
- if (pinned.length === 0 && fresh.length === 0) continue;
80
+ const unpinned = rows.filter(row => !effectiveNotePolicy(row.meta, row.path).pinned);
81
+ // Both caps count joined lines; the first entry is always admitted, so a huge shelf still
82
+ // shows its freshest page plus an honest count of what was left behind.
83
+ const index: string[] = [];
84
+ let usedChars = 0;
85
+ for (const row of unpinned) {
86
+ if (index.length >= SHELF_INDEX_MAX_ENTRIES) break;
87
+ const line = indexLine(row, snapshot.openedAt);
88
+ const nextChars = usedChars + (index.length > 0 ? 1 : 0) + line.length;
89
+ if (index.length > 0 && nextChars > SHELF_INDEX_MAX_CHARS) break;
90
+ index.push(line);
91
+ usedChars = nextChars;
92
+ }
93
+ const omitted = unpinned.length - index.length;
94
+ if (omitted > 0) index.push(` … and ${omitted} more (use ${tools.notesList})`);
95
+ if (pinned.length === 0 && index.length === 0) continue;
65
96
  const parts = pinned.map(row => {
66
97
  const warnings = noteBudgetWarnings(row.body, effectiveNotePolicy(row.meta, row.path));
67
98
  return `${row.address}\n\n${indent([...warnings, row.body].join("\n"))}`;
68
99
  });
69
100
  if (pins.length > MAX_PINNED_NOTES) parts.push(indent(`Warning: only ${MAX_PINNED_NOTES} pinned notes per notebook are injected; omitted pins: ${pins.slice(MAX_PINNED_NOTES).map(row => row.address).join(", ")}. Unpin some notes or read the omitted pages with ${tools.notes}.`));
70
- if (fresh.length > 0) parts.push(`recent\n\n${fresh.join("\n\n")}`);
101
+ if (index.length > 0) parts.push(pinned.length > 0 ? `notes\n\n${index.join("\n")}` : index.join("\n"));
71
102
  shelves.push(section(namespace.label, parts.join("\n\n")));
72
103
  }
73
104
 
package/src/boot/text.ts CHANGED
@@ -1,5 +1,3 @@
1
- /** Each shelf shows this many of its own freshest pages beneath its pinned pages. */
2
- export const SHELF_FRESH_LIMIT = 3;
3
1
  export const WINDOW_IDENTITY_OPEN_TAG = "<notesoup:window_identity>";
4
2
  export const WINDOW_IDENTITY_CLOSE_TAG = "</notesoup:window_identity>";
5
3
  export const NOTES_PROTOCOL_OPEN_TAG = "<notesoup:notes_protocol>";
@@ -58,24 +56,25 @@ ${NOTES_PROTOCOL_CLOSE_TAG}`;
58
56
  * Default pinned pages and per-note policy are taught between the protocol and the notes index.
59
57
  */
60
58
  export const MAPS_BLOCK = `<notesoup:maps>
61
- Every notebook's root has two default pins: \`CHEATSHEET.md\` and \`MAP.md\`.
62
- Pinned pages get jammed straight into your brain the moment you wake up. Whoever wakes up next
63
- reads them, and next is you. So keep them short, and keep them true.
59
+ Each notebook has one default pin: \`CHEATSHEET.md\`. Pinned pages get jammed straight into your
60
+ brain the moment you wake up. Whoever wakes up next reads them, and next is you. So keep them
61
+ short, and keep them true.
64
62
 
65
- Up to five pages per notebook can be taped inside the cover, these two included. Every page gets
63
+ Up to five pages per notebook can be taped inside the cover, CHEATSHEET included. Every page gets
66
64
  a paper budget; when a page outgrows it, boil it down — stale lines out, repeats merged, the rest
67
65
  said shorter — instead of giving it more paper.
68
66
 
69
67
  - **\`CHEATSHEET.md\`** holds what you'll want next time — a rule, a warning, a grudge, a name,
70
68
  a phone number you'll regret losing. Nobody grades it. Keep it to five lines, or it grows fat
71
69
  and everybody pays for it.
72
- - **\`MAP.md\`** is only the note index. One line per durable note: the address, then a gist short
73
- enough to tell whether the thing is worth opening. Rules belong in \`CHEATSHEET.md\`, and note
74
- contents belong in their own notes — *taps the sign* not inline here.
70
+ - **\`description\`** is one line saying what's inside a note and when to open it — max 160
71
+ characters, set through your notes tools. Boot indexes every shelf from these,
72
+ newest first, address and age beside them. No hand-written map to keep in sync: a stale
73
+ description lies to the next window, so keep it true or crumple the page.
75
74
 
76
75
  Each notebook keeps its own: \`@project\`, \`@human\`, \`@self\`, \`@model\`. Missing pages are skipped;
77
- no need to create empty ones. New note, new MAP line. New rule worth remembering, new Cheatsheet
78
- line. And when a line goes wrong, stale, or useless, kill it — tomorrow's you reads that page as fact.
76
+ no need to create empty ones. New rule worth remembering, new Cheatsheet line. And when a line
77
+ goes wrong, stale, or useless, kill it — tomorrow's you reads that page as fact.
79
78
  </notesoup:maps>`;
80
79
 
81
80
  /** Logical tool names are supplied by the composing host, not discovered here. */
@@ -33,7 +33,7 @@ export const WARNING_TIMING = "The reserve is nearly spent. The wipe lands at th
33
33
 
34
34
  /** The shared handoff instructions, used for both budget and manual close-outs. */
35
35
  export const WARNING_BODY =
36
- "Stop the task. Write down what git and history can't give back:\n- where you are, and how far you got\n- what the human decided, in their words\n- what's blocked or waiting\n- the next move\n- where the half-done work sits\n- what failed, and why\n- which skills, seqs, notes, or files to reopen\n- anything else worth noting\nThen leave the shelf current: replace what's stale, a whole note or a section inside one, and crumple the dead ones. Update and trim pinned pages (CHEATSHEET.md and MAP.md by default); every new window loads the pins. The next window gets whatever you leave, dead notes and dead sections alike.\nDon't call anything that might return a large output. One big read can spend the rest of the reserve before your notes are saved.";
36
+ "Stop the task. Write down what git and history can't give back:\n- where you are, and how far you got\n- what the human decided, in their words\n- what's blocked or waiting\n- the next move\n- where the half-done work sits\n- what failed, and why\n- which skills, seqs, notes, or files to reopen\n- anything else worth noting\nThen leave the shelf current: replace what's stale, a whole note or a section inside one, and crumple the dead ones. Update and trim pinned pages (CHEATSHEET.md by default) and keep each page's one-line `description` true; every new window loads the pins and renders the index. The next window gets whatever you leave, dead notes and dead sections alike.\nDon't call anything that might return a large output. One big read can spend the rest of the reserve before your notes are saved.";
37
37
 
38
38
  export const WARNING_CALL = "Then call `empty_brain`. Nothing in between.";
39
39
 
package/src/dream/git.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { execFileSync, spawnSync } from "node:child_process";
2
- import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
2
+ import { appendFileSync, existsSync, mkdirSync, readFileSync } from "node:fs";
3
3
  import { dirname, join } from "node:path";
4
4
  import { errorMessage } from "../error-message.js";
5
5
 
@@ -9,18 +9,18 @@ export type AuditResult =
9
9
  | { ok: false; error: string };
10
10
 
11
11
  /** Lock runtime artifacts are not notes and must not appear in snapshots or `git status`. */
12
- const RUNTIME_IGNORE = ".dream.lock*";
12
+ const RUNTIME_IGNORE = ["/.dream.lock*", "/.project-claim.sqlite", "/.project-claim.sqlite-*", "/.project-pending-*/"];
13
13
 
14
- /** Add the runtime-artifact pattern to the repository's local exclude, once. */
14
+ /** Install root-only excludes before staging; fail the audit rather than snapshot runtime files. */
15
15
  function ensureRuntimeIgnored(home: string): void {
16
- try {
17
- const exclude = join(home, ".git", "info", "exclude");
18
- const current = existsSync(exclude) ? readFileSync(exclude, "utf8") : "";
19
- if (current.split(/\r?\n/).includes(RUNTIME_IGNORE)) return;
20
- mkdirSync(dirname(exclude), { recursive: true });
21
- const prefix = current.length > 0 && !current.endsWith("\n") ? `${current}\n` : current;
22
- writeFileSync(exclude, `${prefix}${RUNTIME_IGNORE}\n`);
23
- } catch { /* best effort: an unignored lock only adds noise to the audit */ }
16
+ const exclude = join(home, ".git", "info", "exclude");
17
+ const current = existsSync(exclude) ? readFileSync(exclude, "utf8") : "";
18
+ const lines = new Set(current.split(/\r?\n/));
19
+ const missing = RUNTIME_IGNORE.filter(pattern => !lines.has(pattern));
20
+ if (!missing.length) return;
21
+ mkdirSync(dirname(exclude), { recursive: true });
22
+ const prefix = current.length && !current.endsWith("\n") ? "\n" : "";
23
+ appendFileSync(exclude, prefix + missing.join("\n") + "\n");
24
24
  }
25
25
 
26
26
  /** Snapshot at begin and end; a repository without HEAD gets an empty baseline commit. */
@@ -1,4 +1,4 @@
1
- export type NoteErrorCode = "invalid_policy" | "pin_limit" | "readonly" | "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" | "invalid_cwd" | "io_error" | "internal_error";
1
+ export type NoteErrorCode = "invalid_policy" | "invalid_description" | "pin_limit" | "readonly" | "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" | "invalid_cwd" | "io_error" | "internal_error";
2
2
 
3
3
  /** Typed store refusal. Edit locations are exposed in camelCase. */
4
4
  export class NoteError extends Error {
@@ -23,6 +23,8 @@ export type NoteMeta = NotePolicyFields & {
23
23
  recurrenceWindows?: string[];
24
24
  /** Project ownership on newly-created session notes; legacy/invalid values are preserved as-is. */
25
25
  project?: unknown;
26
+ /** One-line index entry: what the note holds and when to open it. */
27
+ description?: string;
26
28
  [key: string]: unknown;
27
29
  };
28
30
 
@@ -30,7 +32,16 @@ const SCOPES: readonly Scope[] = ["session", "project", "human", "agent", "model
30
32
  const ORIGINS: readonly Origin[] = ["user", "self", "external"];
31
33
  const TIMESTAMP_KEYS = ["createdAt", "updatedAt", "lastAccessed"] as const;
32
34
  /** Emission order, exactly the Design's key list. */
33
- const KNOWN_KEYS = ["pinned", "budget", "readonly", "origin", "crumpledAt", "createdAt", "updatedAt", "lastAccessed", "accessCount", "sourceWindow", "supersedes", "recurrenceCount", "recurrenceWindows"] as const;
35
+ const KNOWN_KEYS = ["pinned", "budget", "readonly", "description", "origin", "crumpledAt", "createdAt", "updatedAt", "lastAccessed", "accessCount", "sourceWindow", "supersedes", "recurrenceCount", "recurrenceWindows"] as const;
36
+
37
+ /** A note description is one line; longer is not a description, it is prose in the wrong place. */
38
+ export const MAX_DESCRIPTION_CHARS = 160;
39
+
40
+ /** Collapse any whitespace run to one space and trim; an empty result is no description. */
41
+ export function collapseDescription(value: string): string | undefined {
42
+ const collapsed = value.replace(/\s+/g, " ").trim();
43
+ return collapsed.length === 0 ? undefined : collapsed;
44
+ }
34
45
 
35
46
  const pad2 = (value: number) => String(value).padStart(2, "0");
36
47
 
@@ -131,6 +142,13 @@ export function parseNote(raw: string, now = Date.now()): { meta: NoteMeta; body
131
142
  meta.origin = isOrigin(meta.origin) ? meta.origin : "self";
132
143
  for (const key of TIMESTAMP_KEYS) meta[key] = toEpoch(meta[key], now);
133
144
  meta.accessCount = typeof meta.accessCount === "number" && Number.isFinite(meta.accessCount) ? meta.accessCount : 0;
145
+ // A hand-edited description is never allowed to break a boot: non-strings are absent, empty
146
+ // ones are dropped, and an oversized one is cut only when rendered.
147
+ if (meta.description !== undefined) {
148
+ const description = typeof meta.description === "string" ? collapseDescription(meta.description) : undefined;
149
+ if (description === undefined) delete meta.description;
150
+ else meta.description = description;
151
+ }
134
152
  return { meta: meta as NoteMeta, body };
135
153
  }
136
154
 
@@ -5,7 +5,7 @@ export type NotePolicy = Required<NotePolicyFields>;
5
5
  export const DEFAULT_NOTE_BUDGET = 4096;
6
6
  export const MAX_PINNED_NOTES = 5;
7
7
  /** Defaults and ordering live here; no other layer assigns behavior by page name. */
8
- const DEFAULT_PINNED_PAGES = ["CHEATSHEET.md", "MAP.md"] as const;
8
+ const DEFAULT_PINNED_PAGES = ["CHEATSHEET.md"] as const;
9
9
 
10
10
  export function validateNotePolicy(fields: NotePolicyFields): void {
11
11
  for (const key of ["pinned", "readonly"] as const) {
@@ -1,6 +1,7 @@
1
1
  import { randomUUID } from "node:crypto";
2
- import { existsSync, mkdirSync, readFileSync, readdirSync, realpathSync, renameSync, rmdirSync, rmSync, statSync, writeFileSync } from "node:fs";
2
+ import { existsSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
3
3
  import { basename, dirname, join, resolve, sep } from "node:path";
4
+ import { trySqliteLock } from "../sqlite-lock.js";
4
5
  import { slugify } from "./paths.js";
5
6
 
6
7
  export type ProjectMarker = { id: string; path: string };
@@ -115,70 +116,47 @@ function updateMarker(namespace: ProjectNamespace, marker: ProjectMarker): Proje
115
116
  return { ...namespace, ...marker };
116
117
  }
117
118
 
118
- const claimSleep = new Int32Array(new SharedArrayBuffer(4));
119
-
120
- function awaitClaim<T>(path: string, attempt: () => T | undefined): T {
121
- const deadline = performance.now() + 5_000;
122
- for (;;) {
123
- const result = attempt();
124
- if (result !== undefined) return result;
125
- const remaining = deadline - performance.now();
126
- if (remaining <= 0) throw new Error(`Timed out waiting for project claim at ${path}`);
127
- Atomics.wait(claimSleep, 0, 0, Math.min(10, remaining));
128
- }
119
+ function checkoutMarker(cwd: string): ProjectMarker {
120
+ const path = canonicalRoot(cwd);
121
+ return { id: originRemote(path) ?? path, path };
129
122
  }
130
123
 
131
124
  /** Resolve and claim the readable notebook for one repository identity. */
132
125
  export function resolveProjectNamespace(cwd: string, home: string): ProjectNamespace {
133
- mkdirSync(projectRoot(home), { recursive: true });
134
- // Serialize the scan as well as publication: an unmarked directory seen under
135
- // this lock is legacy, not another resolver between mkdir and marker write.
136
- const lock = join(home, ".project-claim");
137
- awaitClaim(lock, () => {
138
- try { mkdirSync(lock); return true; } catch (error) {
139
- if (errno(error) === "EEXIST") return undefined;
140
- throw error;
141
- }
142
- });
143
- try { return claimProjectNamespace(cwd, home); } finally { rmdirSync(lock); }
144
- }
126
+ const expected = checkoutMarker(cwd);
127
+ const current = projectNamespaces(home).find(candidate => candidate.id === expected.id);
128
+ if (current?.path === expected.path) return current;
145
129
 
146
- function claimProjectNamespace(cwd: string, home: string): ProjectNamespace {
147
- const root = canonicalRoot(cwd);
148
- const remote = originRemote(root);
149
- const id = remote ?? root;
150
- const markerRoot = projectRoot(home);
151
- mkdirSync(markerRoot, { recursive: true });
152
- const namespaces = projectNamespaces(home);
153
- let found = namespaces.find(candidate => candidate.id === id);
154
- if (!found && remote) {
155
- found = namespaces.find(candidate => candidate.id === root);
156
- if (found) found = updateMarker(found, { id: remote, path: root });
157
- }
158
- if (found) {
159
- if (found.path !== root) found = updateMarker(found, { id: found.id, path: root });
160
- return found;
161
- }
162
-
163
- const base = slugify(basename(root));
164
- // The claim lock makes this a stable snapshot of legacy, unmarked names.
165
- const taken = new Set(readdirSync(markerRoot));
166
- for (let suffix = 0; ; suffix++) {
167
- const name = suffix === 0 ? base : `${base}-${suffix}`;
168
- if (taken.has(name)) continue;
169
- const dir = join(markerRoot, name);
170
- try {
171
- mkdirSync(dir);
172
- } catch (error) {
173
- if (errno(error) !== "EEXIST") throw error;
174
- // A writer outside this protocol may have won after the snapshot.
175
- // Never mistake its incomplete publication for a different identity.
176
- let winner = awaitClaim(join(dir, ".project"), () => readMarker(dir));
177
- if (winner.id !== id && !(remote && winner.id === root)) continue;
178
- if (winner.id !== id || winner.path !== root) winner = updateMarker(winner, { id, path: root });
179
- return winner;
130
+ const root = projectRoot(home);
131
+ mkdirSync(root, { recursive: true });
132
+ const lockPath = join(home, ".project-claim.sqlite");
133
+ const release = trySqliteLock(lockPath, 5000);
134
+ if (!release) throw new Error(`Timed out waiting for project claim at ${lockPath}`);
135
+ try {
136
+ // The checkout may have gained an origin and a peer may have already adopted it.
137
+ const marker = checkoutMarker(cwd);
138
+ const { id, path } = marker;
139
+ const namespaces = projectNamespaces(home);
140
+ const found = namespaces.find(candidate => candidate.id === id) ?? namespaces.find(candidate => candidate.id === path);
141
+ if (found) return found.id === id && found.path === path ? found : updateMarker(found, marker);
142
+
143
+ const base = slugify(basename(path));
144
+ for (let suffix = 0; ; suffix++) {
145
+ const name = suffix === 0 ? base : `${base}-${suffix}`;
146
+ const dir = join(root, name);
147
+ if (lstatSync(dir, { throwIfNoEntry: false })) continue; // Includes unmarked legacy names.
148
+ const staged = mkdtempSync(join(home, ".project-pending-"));
149
+ try {
150
+ writeFileSync(join(staged, ".project"), JSON.stringify(marker));
151
+ renameSync(staged, dir);
152
+ } catch (error) {
153
+ rmSync(staged, { recursive: true, force: true });
154
+ throw error;
155
+ }
156
+ return { name, dir, ...marker };
180
157
  }
181
- return updateMarker({ name, dir, id, path: root }, { id, path: root });
158
+ } finally {
159
+ release();
182
160
  }
183
161
  }
184
162
 
@@ -8,7 +8,7 @@ import { isFilesystemError } from "./fs-error.js";
8
8
  import { snapshotNotesIdentity, type NotesIdentity } from "./identity.js";
9
9
  import { NoteError } from "./errors.js";
10
10
  import { MAX_NOTE_BYTES, MAX_NOTE_PATH_BYTES } from "./constants.js";
11
- import { isOrigin, localIso, parseNote, serializeNote, stripLeadingFrontmatter, type NoteMeta, type Origin } from "./frontmatter.js";
11
+ import { collapseDescription, isOrigin, localIso, MAX_DESCRIPTION_CHARS, parseNote, serializeNote, stripLeadingFrontmatter, type NoteMeta, type Origin } from "./frontmatter.js";
12
12
  import { namespaceSlugs, noteFileName, physicalPath, scopeDir, isSessionId, SLUG_PATTERN, type Scope } from "./paths.js";
13
13
  import { projectReceipt, type ProjectReceipt } from "./project-namespace.js";
14
14
  import { applyNotePolicy, assertNoteUnlocked, effectiveNotePolicy, MAX_PINNED_NOTES, noteBudgetWarnings, validateNotePolicy, type NotePolicyFields } from "./policy.js";
@@ -27,8 +27,8 @@ function writeStamp(): number {
27
27
  export type NoteMatch = { line: number; text: string; /** Code-point offset into the note body, not into the serialized file. */ offsetChars: number };
28
28
  export type NoteSearchRow = { address: string; scope: Scope; path: string; meta: NoteMeta; warnings: string[]; matches: NoteMatch[] };
29
29
  export type EditOperation = { oldText: string; newText: string };
30
- export type WriteOptions = NotePolicyFields & { origin?: Origin };
31
- export type EditOptions = NotePolicyFields & { origin?: Origin; crumpled?: boolean; replaceAll?: boolean; renameTo?: string };
30
+ export type WriteOptions = NotePolicyFields & { origin?: Origin; description?: string };
31
+ export type EditOptions = NotePolicyFields & { origin?: Origin; description?: string; crumpled?: boolean; replaceAll?: boolean; renameTo?: string };
32
32
  /** Omit glob for current notebooks. A pattern without `@` or `/` matches filenames at any depth. */
33
33
  export type NotesQuery = { glob?: string; crumpled?: boolean };
34
34
  /** A read exposes metadata and the pure body; the serialized frontmatter is never part of the body. */
@@ -188,6 +188,15 @@ function assertOrigin(value: unknown): Origin {
188
188
  return value;
189
189
  }
190
190
 
191
+ /** A description is one normalized line; empty clears it. Only the authored value is refused, never read. */
192
+ function normalizeDescription(value: string): string | undefined {
193
+ const collapsed = collapseDescription(value);
194
+ if (collapsed === undefined) return undefined;
195
+ const count = Array.from(collapsed).length;
196
+ if (count > MAX_DESCRIPTION_CHARS) throw new NoteError("invalid_description", `description is ${count} characters; limit is ${MAX_DESCRIPTION_CHARS}.`);
197
+ return collapsed;
198
+ }
199
+
191
200
  function assertWho(value: unknown, scope: Scope): string {
192
201
  if (typeof value !== "string" || !(scope === "session" ? isSessionId(value) : SLUG_PATTERN.test(value))) {
193
202
  throw new NoteError("invalid_scope", scope === "session" ? "session id must be a safe single directory component" : "who must be a canonical lowercase slug");
@@ -310,6 +319,7 @@ export function createNotesStore(input: NotesIdentity): NotesStore {
310
319
  async function write(address: string, content: string, options: WriteOptions = {}): Promise<NoteWriteResult> {
311
320
  const stableOptions = { ...options };
312
321
  validateNotePolicy(stableOptions);
322
+ const description = stableOptions.description === undefined ? undefined : normalizeDescription(stableOptions.description);
313
323
  const destination = assertAddress(address);
314
324
  assertWritablePath(destination.path);
315
325
  const scope = destination.scope;
@@ -339,6 +349,9 @@ export function createNotesStore(input: NotesIdentity): NotesStore {
339
349
  };
340
350
  meta.scope = scope;
341
351
  applyNotePolicy(meta, stableOptions);
352
+ if (description === undefined) {
353
+ if (stableOptions.description !== undefined) delete meta.description;
354
+ } else meta.description = description;
342
355
  if (origin !== undefined) meta.origin = origin;
343
356
  delete meta.crumpledAt;
344
357
  meta.updatedAt = now;
@@ -372,14 +385,15 @@ export function createNotesStore(input: NotesIdentity): NotesStore {
372
385
  const operations = edits === undefined ? [] : edits.map((operation) => ({ ...operation }));
373
386
  const stableOptions = { ...options };
374
387
  validateNotePolicy(stableOptions);
388
+ const description = stableOptions.description === undefined ? undefined : normalizeDescription(stableOptions.description);
375
389
  const from = assertAddress(address);
376
390
  const destination = stableOptions.renameTo === undefined ? from : assertAddress(stableOptions.renameTo);
377
391
  assertWritablePath(destination.path);
378
392
  const scope = destination.scope;
379
393
  assertWritableNamespace(from.scope, from.who, identity);
380
394
  assertWritableNamespace(scope, destination.who, identity);
381
- if (operations.length === 0 && stableOptions.origin === undefined && stableOptions.crumpled === undefined && stableOptions.renameTo === undefined && stableOptions.pinned === undefined && stableOptions.budget === undefined && stableOptions.readonly === undefined) {
382
- throw new NoteError("nothing_to_do", "Nothing to change: provide edits, policy, an origin, a crumpled state, or a new address.");
395
+ if (operations.length === 0 && stableOptions.origin === undefined && stableOptions.description === undefined && stableOptions.crumpled === undefined && stableOptions.renameTo === undefined && stableOptions.pinned === undefined && stableOptions.budget === undefined && stableOptions.readonly === undefined) {
396
+ throw new NoteError("nothing_to_do", "Nothing to change: provide edits, a description, policy, an origin, a crumpled state, or a new address.");
383
397
  }
384
398
  const fromPath = physicalPath(from.scope, from.path, identity, from.who);
385
399
  const path = physicalPath(scope, destination.path, identity, destination.who);
@@ -405,6 +419,9 @@ export function createNotesStore(input: NotesIdentity): NotesStore {
405
419
  if (moved && targetRaw !== undefined) assertNoteUnlocked(parseNote(targetRaw).meta, stableOptions.readonly);
406
420
  const beforeMeta: NoteMeta = { ...meta };
407
421
  applyNotePolicy(meta, stableOptions);
422
+ if (description === undefined) {
423
+ if (stableOptions.description !== undefined) delete meta.description;
424
+ } else meta.description = description;
408
425
  meta.scope = scope;
409
426
  if (from.scope !== "session" && scope === "session") meta.project = identity.projectKey;
410
427
  if (from.scope === "session" && scope !== "session") delete meta.project;
@@ -434,10 +451,11 @@ export function createNotesStore(input: NotesIdentity): NotesStore {
434
451
  const bodyChanged = body !== next;
435
452
  const originChanged = beforeMeta.origin !== meta.origin;
436
453
  const policyChanged = beforeMeta.pinned !== meta.pinned || beforeMeta.budget !== meta.budget || beforeMeta.readonly !== meta.readonly;
437
- if (bodyChanged || originChanged || policyChanged || moved) meta.updatedAt = writeStamp();
454
+ const descriptionChanged = beforeMeta.description !== meta.description;
455
+ if (bodyChanged || originChanged || policyChanged || descriptionChanged || moved) meta.updatedAt = writeStamp();
438
456
  const serialized = serializeNote(meta, next);
439
457
  assertSerializedSize(serialized);
440
- const metadataChanged = originChanged || policyChanged || beforeMeta.crumpledAt !== meta.crumpledAt;
458
+ const metadataChanged = originChanged || policyChanged || descriptionChanged || beforeMeta.crumpledAt !== meta.crumpledAt;
441
459
  let change: NoteChange;
442
460
  // A body edit that also rewrites frontmatter is still a body change; its diff inputs span the
443
461
  // whole serialized file, so the frontmatter part stays visible in the diff.
@@ -0,0 +1,14 @@
1
+ /** The open transaction is the lock. Never unlink the database, even after a crash. */
2
+ export function trySqliteLock(path: string, waitMs: 0 | 5000): (() => void) | undefined {
3
+ const sqlite = process.getBuiltinModule?.("node:sqlite") as typeof import("node:sqlite") | undefined;
4
+ if (!sqlite?.DatabaseSync) throw new Error("Notesoup locks require built-in node:sqlite (Node 22.13+).");
5
+ const db = new sqlite.DatabaseSync(path);
6
+ try {
7
+ db.exec(`PRAGMA busy_timeout = ${waitMs}; BEGIN IMMEDIATE`);
8
+ } catch (error) {
9
+ db.close();
10
+ if (error instanceof Error && "errcode" in error && error.errcode === 5) return undefined; // SQLITE_BUSY
11
+ throw error;
12
+ }
13
+ return () => db.close(); // Closing rolls back the empty transaction.
14
+ }
@@ -1,17 +1,18 @@
1
1
  /** Dream operations: open one project's notes for consolidation, delete crumpled notes, close. */
2
+ import { join } from "node:path";
2
3
  import { Type, type Static } from "typebox";
3
4
  import { localIso } from "../notes/frontmatter.js";
4
5
  import { createNotesStore, noteIdentity, type NoteRow, type NotesIdentity } from "../notes/index.js";
5
6
  import { projectNamespaces } from "../notes/project-namespace.js";
6
7
  import { gitCommit } from "../dream/git.js";
7
- import { acquireDreamLock, dreamLockPath, releaseDreamLock, type DreamLock } from "../dream/lock.js";
8
+ import { trySqliteLock } from "../sqlite-lock.js";
8
9
  import { failure, success, type Outcome } from "../result.js";
9
10
  import { renderOutcome, resultSchema } from "./result.js";
10
11
  import { failureOf, listedFile, ListedFileSchema, NoteIdentitySchema, renderListData, snapshot, SnapshotSchema } from "./notes.js";
11
12
 
12
13
  /** The one open dream per session; the host owns where it lives. */
13
- type DreamOpening = { project: string; lock: DreamLock; generation: number };
14
- export type DreamState = { project?: string; lock?: DreamLock; pending?: DreamOpening; generation?: number };
14
+ type DreamOpening = { project: string; release: () => void; generation: number };
15
+ export type DreamState = { project?: string; release?: () => void; pending?: DreamOpening; generation?: number };
15
16
 
16
17
  function currentOpening(state: DreamState, opening: DreamOpening): boolean {
17
18
  return state.pending === opening && state.generation === opening.generation;
@@ -25,19 +26,19 @@ function nextGeneration(state: DreamState): number {
25
26
 
26
27
  /** Drop an open dream without an end commit, e.g. when its session shuts down. */
27
28
  export function abandonDream(state: DreamState): void {
28
- const pending = state.pending;
29
- if (pending) releaseDreamLock(pending.lock);
30
- if (state.lock && state.lock !== pending?.lock) releaseDreamLock(state.lock);
29
+ state.pending?.release();
30
+ state.release?.();
31
31
  nextGeneration(state);
32
32
  delete state.project;
33
- delete state.lock;
33
+ delete state.release;
34
34
  delete state.pending;
35
35
  }
36
36
 
37
37
  /** Release an opening without disturbing a newer opening in the same state. */
38
38
  function releaseOpening(state: DreamState, opening: DreamOpening): void {
39
- releaseDreamLock(opening.lock);
40
- if (currentOpening(state, opening)) delete state.pending;
39
+ if (!currentOpening(state, opening)) return;
40
+ opening.release();
41
+ delete state.pending;
41
42
  }
42
43
 
43
44
  function cancelledOpening(state: DreamState, opening: DreamOpening): Outcome<never> {
@@ -80,10 +81,10 @@ export const dreamBegin = {
80
81
  if (project !== identity.projectKey && !projectNamespaces(identity.home).some(namespace => namespace.name === project)) {
81
82
  return failure("not_found", `No project named ${JSON.stringify(project)}; notes_list with glob @projects/*/** shows the names.`);
82
83
  }
83
- const lock = acquireDreamLock(dreamLockPath(identity.home));
84
- if (!lock) return failure("already_dreaming", `Another dream holds ${dreamLockPath(identity.home)}. If none is running, delete that file by hand.`);
85
- // Publish ownership before the first await. Shutdown can therefore release this exact token.
86
- const opening: DreamOpening = { project, lock, generation: nextGeneration(state) };
84
+ const release = trySqliteLock(join(identity.home, ".dream.lock.sqlite"), 0);
85
+ if (!release) return failure("already_dreaming", "Another dream is open in this notes home.");
86
+ // Publish ownership before the first await so shutdown can release this transaction.
87
+ const opening: DreamOpening = { project, release, generation: nextGeneration(state) };
87
88
  state.pending = opening;
88
89
  try {
89
90
  const store = createNotesStore({ ...identity, dreaming: project });
@@ -111,7 +112,7 @@ export const dreamBegin = {
111
112
  }
112
113
  if (!currentOpening(state, opening)) return cancelledOpening(state, opening);
113
114
  state.project = opening.project;
114
- state.lock = opening.lock;
115
+ state.release = opening.release;
115
116
  delete state.pending;
116
117
  return success({ project, baseline: baseline.commit, ...listed.data });
117
118
  } catch (error) {