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
package/README.md CHANGED
@@ -40,14 +40,15 @@ pi -e npm:notesoup
40
40
 
41
41
  ## Per-note policy
42
42
 
43
- Notes have optional `pinned`, `budget`, and `readonly` frontmatter fields, also settable through `notes_write` and `notes_update`:
43
+ Notes have optional `pinned`, `budget`, `readonly`, and `description` frontmatter fields, also settable through `notes_write` and `notes_update`:
44
44
 
45
45
  ```json
46
- { "address": "@project/decisions.md", "pinned": true, "budget": 3000, "readonly": false }
46
+ { "address": "@project/decisions.md", "pinned": true, "budget": 3000, "readonly": false, "description": "Architecture choices and why they stand." }
47
47
  ```
48
48
 
49
- - **Pinned** notes are injected **in full** at boot. Root `CHEATSHEET.md` and `MAP.md` default to pinned; every other page defaults to unpinned. Explicit `pinned: false` overrides even a default page. Each notebook allows **five live pins**, including its existing default pages; crumpled notes do not count. A sixth pin, restore or move that exceeds the cap refuses without changing either note. Manually over-cap notebooks get a boot warning naming the omitted pins, with default pages shown first.
50
- - **Budget** defaults to **4096 Unicode code points for ordinary pages**, and **2048 for root CHEATSHEET.md and MAP.md**. Any positive safe integer is allowed. Over-budget writes and updates succeed with a visible warning; pinned bodies are never truncated to their budget. This advisory budget is separate from the existing hard serialized-file byte limit. Tool results/read metadata/list/search expose effective policy and budget warnings.
49
+ - **Pinned** notes are injected **in full** at boot. Root `CHEATSHEET.md` defaults to pinned; every other page defaults to unpinned. Explicit `pinned: false` overrides even a default page. Each notebook allows **five live pins**, including its default `CHEATSHEET.md`; crumpled notes do not count. A sixth pin, restore or move that exceeds the cap refuses without changing either note. Manually over-cap notebooks get a boot warning naming the omitted pins, with default pages shown first. Unpinned live notes appear in a bounded auto-generated per-shelf index at boot (sorted by recency, up to 25 entries / 4096 chars per shelf).
50
+ - **Budget** defaults to **4096 Unicode code points for ordinary pages**, and **2048 for root `CHEATSHEET.md`**. Any positive safe integer is allowed. Over-budget writes and updates succeed with a visible warning; pinned bodies are never truncated to their budget. This advisory budget is separate from the existing hard serialized-file byte limit. Tool results/read metadata/list/search expose effective policy and budget warnings.
51
+ - **Description** is an optional single-line summary (up to **160 Unicode code points**; whitespace is collapsed and an empty string clears it). It is rendered in the boot shelf index (falling back to the first heading/line when absent) as well as `notes_read` metadata and `notes_list` rows.
51
52
  - **Readonly** defaults to false. `readonly: true` is a **soft lock**, not security: mutations refuse until explicitly unlocked with `readonly: false`, either by itself or in the same call as the requested changes. A write can create and lock a note together. Reads still record access metadata; direct filesystem edits can bypass the lock.
52
53
 
53
54
  Absent fields stay absent on disk. On move/rename, implicit pin defaults follow the new root path; explicit true/false values travel with the note. The original origin, other metadata, and unknown frontmatter are preserved. See the [library API](docs/notes-library.md#per-note-policy) for details.
@@ -1,5 +1,10 @@
1
1
  import type { NotesSnapshot } from "./snapshot.js";
2
2
  import { type BootToolNames } from "./text.js";
3
+ /** The shelf index is bounded: enough to find a page, never the whole drawer. */
4
+ export declare const SHELF_INDEX_MAX_ENTRIES = 25;
5
+ export declare const SHELF_INDEX_MAX_CHARS = 4096;
6
+ /** A fallback title is the note's own first heading or line, cut short. */
7
+ export declare const FALLBACK_TITLE_MAX_CHARS = 80;
3
8
  export type BootWindowTree = {
4
9
  readonly trunk: string;
5
10
  readonly windows: ReadonlyArray<{
@@ -1,5 +1,6 @@
1
1
  import { effectiveNotePolicy, MAX_PINNED_NOTES, noteBudgetWarnings, pinnedPageOrder } from "../notes/policy.js";
2
- import { WINDOW_IDENTITY_OPEN_TAG, WINDOW_IDENTITY_CLOSE_TAG, MAPS_BLOCK, NAMELESS_AGENT, SHELF_FRESH_LIMIT, renderProtocolBlock } from "./text.js";
2
+ import { collapseDescription, MAX_DESCRIPTION_CHARS } from "../notes/frontmatter.js";
3
+ import { WINDOW_IDENTITY_OPEN_TAG, WINDOW_IDENTITY_CLOSE_TAG, MAPS_BLOCK, NAMELESS_AGENT, renderProtocolBlock } from "./text.js";
3
4
  function relativeTime(timestamp, now) {
4
5
  const seconds = Math.trunc((timestamp - now) / 1000);
5
6
  if (seconds === 0)
@@ -9,16 +10,34 @@ function relativeTime(timestamp, now) {
9
10
  const amount = `${Math.abs(Math.trunc(seconds / size))}${unit}`;
10
11
  return seconds > 0 ? `in ${amount}` : `${amount} ago`;
11
12
  }
12
- /** A feed entry is announced in the note's own words: its first heading, else its first line, cut short. */
13
- const FEED_TITLE_MAX_CHARS = 40;
13
+ /** The shelf index is bounded: enough to find a page, never the whole drawer. */
14
+ export const SHELF_INDEX_MAX_ENTRIES = 25;
15
+ export const SHELF_INDEX_MAX_CHARS = 4096;
16
+ /** A fallback title is the note's own first heading or line, cut short. */
17
+ export const FALLBACK_TITLE_MAX_CHARS = 80;
18
+ function truncated(text, max) {
19
+ const chars = Array.from(text);
20
+ return chars.length > max ? `${chars.slice(0, max).join("")}…` : chars.join("");
21
+ }
14
22
  function feedTitle(body) {
15
23
  const lines = body.split("\n");
16
24
  const heading = lines.find((line) => /^#+\s+\S/.test(line));
17
25
  const raw = (heading ? heading.replace(/^#+\s+/, "") : lines.find((line) => line.trim().length > 0) ?? "").trim();
18
- if (raw.length === 0)
19
- return undefined;
20
- const chars = Array.from(raw);
21
- return chars.length > FEED_TITLE_MAX_CHARS ? `${chars.slice(0, FEED_TITLE_MAX_CHARS).join("")}…` : chars.join("");
26
+ return raw.length === 0 ? undefined : truncated(raw, FALLBACK_TITLE_MAX_CHARS);
27
+ }
28
+ /** A stale hand-edited description is cut for display; the authored value was already refused at write time. */
29
+ function summaryOf(row) {
30
+ if (typeof row.meta.description === "string") {
31
+ const collapsed = collapseDescription(row.meta.description);
32
+ return collapsed === undefined ? undefined : truncated(collapsed, MAX_DESCRIPTION_CHARS);
33
+ }
34
+ return feedTitle(row.body);
35
+ }
36
+ /** One index entry: where the page sits, how fresh it is, and one line saying whether to open it. */
37
+ function indexLine(row, openedAt) {
38
+ const locator = `${row.address} · ${relativeTime(row.meta.updatedAt, openedAt)}`;
39
+ const summary = summaryOf(row);
40
+ return summary === undefined ? ` ${locator}` : ` ${locator} — ${summary}`;
22
41
  }
23
42
  /** Two spaces of indent say "shelved content" without any furniture. */
24
43
  function indent(text) {
@@ -28,7 +47,7 @@ function indent(text) {
28
47
  function section(label, body) {
29
48
  return `${label}\n${"─".repeat(Array.from(label).length)}\n\n${body}`;
30
49
  }
31
- /** One closed boot snapshot: five tabbed shelves, current hands first, durable last; each shelf keeps its pinned pages and its own freshest pages. */
50
+ /** 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. */
32
51
  function notesIndex(snapshot, tools, agentName, modelName) {
33
52
  const namespaces = [
34
53
  { scope: "session", label: "no @ — this session" },
@@ -47,15 +66,25 @@ function notesIndex(snapshot, tools, agentName, modelName) {
47
66
  const pins = rows.filter(row => effectiveNotePolicy(row.meta, row.path).pinned)
48
67
  .sort((a, b) => pinnedPageOrder(a.path) - pinnedPageOrder(b.path) || a.path.localeCompare(b.path));
49
68
  const pinned = pins.slice(0, MAX_PINNED_NOTES);
50
- const fresh = rows
51
- .filter(row => !effectiveNotePolicy(row.meta, row.path).pinned)
52
- .slice(0, SHELF_FRESH_LIMIT)
53
- .map((row) => {
54
- const locator = `${row.address} · ${relativeTime(row.meta.updatedAt, snapshot.openedAt)}`;
55
- const title = feedTitle(row.body);
56
- return title === undefined ? ` ${locator}` : ` ${title}\n ${locator}`;
57
- });
58
- if (pinned.length === 0 && fresh.length === 0)
69
+ const unpinned = rows.filter(row => !effectiveNotePolicy(row.meta, row.path).pinned);
70
+ // Both caps count joined lines; the first entry is always admitted, so a huge shelf still
71
+ // shows its freshest page plus an honest count of what was left behind.
72
+ const index = [];
73
+ let usedChars = 0;
74
+ for (const row of unpinned) {
75
+ if (index.length >= SHELF_INDEX_MAX_ENTRIES)
76
+ break;
77
+ const line = indexLine(row, snapshot.openedAt);
78
+ const nextChars = usedChars + (index.length > 0 ? 1 : 0) + line.length;
79
+ if (index.length > 0 && nextChars > SHELF_INDEX_MAX_CHARS)
80
+ break;
81
+ index.push(line);
82
+ usedChars = nextChars;
83
+ }
84
+ const omitted = unpinned.length - index.length;
85
+ if (omitted > 0)
86
+ index.push(` … and ${omitted} more (use ${tools.notesList})`);
87
+ if (pinned.length === 0 && index.length === 0)
59
88
  continue;
60
89
  const parts = pinned.map(row => {
61
90
  const warnings = noteBudgetWarnings(row.body, effectiveNotePolicy(row.meta, row.path));
@@ -63,8 +92,8 @@ function notesIndex(snapshot, tools, agentName, modelName) {
63
92
  });
64
93
  if (pins.length > MAX_PINNED_NOTES)
65
94
  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}.`));
66
- if (fresh.length > 0)
67
- parts.push(`recent\n\n${fresh.join("\n\n")}`);
95
+ if (index.length > 0)
96
+ parts.push(pinned.length > 0 ? `notes\n\n${index.join("\n")}` : index.join("\n"));
68
97
  shelves.push(section(namespace.label, parts.join("\n\n")));
69
98
  }
70
99
  return shelves.length > 0
@@ -1,5 +1,3 @@
1
- /** Each shelf shows this many of its own freshest pages beneath its pinned pages. */
2
- export declare const SHELF_FRESH_LIMIT = 3;
3
1
  export declare const WINDOW_IDENTITY_OPEN_TAG = "<notesoup:window_identity>";
4
2
  export declare const WINDOW_IDENTITY_CLOSE_TAG = "</notesoup:window_identity>";
5
3
  export declare const NOTES_PROTOCOL_OPEN_TAG = "<notesoup:notes_protocol>";
@@ -15,7 +13,7 @@ export declare const PROTOCOL_HISTORY_SENTENCE = "History can still be dug up, p
15
13
  /**
16
14
  * Default pinned pages and per-note policy are taught between the protocol and the notes index.
17
15
  */
18
- export declare const MAPS_BLOCK = "<notesoup:maps>\nEvery notebook's root has two default pins: `CHEATSHEET.md` and `MAP.md`.\nPinned pages get jammed straight into your brain the moment you wake up. Whoever wakes up next\nreads them, and next is you. So keep them short, and keep them true.\n\nUp to five pages per notebook can be taped inside the cover, these two included. Every page gets\na paper budget; when a page outgrows it, boil it down \u2014 stale lines out, repeats merged, the rest\nsaid shorter \u2014 instead of giving it more paper.\n\n- **`CHEATSHEET.md`** holds what you'll want next time \u2014 a rule, a warning, a grudge, a name,\n a phone number you'll regret losing. Nobody grades it. Keep it to five lines, or it grows fat\n and everybody pays for it.\n- **`MAP.md`** is only the note index. One line per durable note: the address, then a gist short\n enough to tell whether the thing is worth opening. Rules belong in `CHEATSHEET.md`, and note\n contents belong in their own notes \u2014 *taps the sign* not inline here.\n\nEach notebook keeps its own: `@project`, `@human`, `@self`, `@model`. Missing pages are skipped;\nno need to create empty ones. New note, new MAP line. New rule worth remembering, new Cheatsheet\nline. And when a line goes wrong, stale, or useless, kill it \u2014 tomorrow's you reads that page as fact.\n</notesoup:maps>";
16
+ export declare const MAPS_BLOCK = "<notesoup:maps>\nEach notebook has one default pin: `CHEATSHEET.md`. Pinned pages get jammed straight into your\nbrain the moment you wake up. Whoever wakes up next reads them, and next is you. So keep them\nshort, and keep them true.\n\nUp to five pages per notebook can be taped inside the cover, CHEATSHEET included. Every page gets\na paper budget; when a page outgrows it, boil it down \u2014 stale lines out, repeats merged, the rest\nsaid shorter \u2014 instead of giving it more paper.\n\n- **`CHEATSHEET.md`** holds what you'll want next time \u2014 a rule, a warning, a grudge, a name,\n a phone number you'll regret losing. Nobody grades it. Keep it to five lines, or it grows fat\n and everybody pays for it.\n- **`description`** is one line saying what's inside a note and when to open it \u2014 max 160\n characters, set through your notes tools. Boot indexes every shelf from these,\n newest first, address and age beside them. No hand-written map to keep in sync: a stale\n description lies to the next window, so keep it true or crumple the page.\n\nEach notebook keeps its own: `@project`, `@human`, `@self`, `@model`. Missing pages are skipped;\nno need to create empty ones. New rule worth remembering, new Cheatsheet line. And when a line\ngoes wrong, stale, or useless, kill it \u2014 tomorrow's you reads that page as fact.\n</notesoup:maps>";
19
17
  /** Logical tool names are supplied by the composing host, not discovered here. */
20
18
  export type BootToolNames = Readonly<{
21
19
  notes: string;
@@ -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>";
@@ -56,24 +54,25 @@ ${NOTES_PROTOCOL_CLOSE_TAG}`;
56
54
  * Default pinned pages and per-note policy are taught between the protocol and the notes index.
57
55
  */
58
56
  export const MAPS_BLOCK = `<notesoup:maps>
59
- Every notebook's root has two default pins: \`CHEATSHEET.md\` and \`MAP.md\`.
60
- Pinned pages get jammed straight into your brain the moment you wake up. Whoever wakes up next
61
- reads them, and next is you. So keep them short, and keep them true.
57
+ Each notebook has one default pin: \`CHEATSHEET.md\`. Pinned pages get jammed straight into your
58
+ brain the moment you wake up. Whoever wakes up next reads them, and next is you. So keep them
59
+ short, and keep them true.
62
60
 
63
- Up to five pages per notebook can be taped inside the cover, these two included. Every page gets
61
+ Up to five pages per notebook can be taped inside the cover, CHEATSHEET included. Every page gets
64
62
  a paper budget; when a page outgrows it, boil it down — stale lines out, repeats merged, the rest
65
63
  said shorter — instead of giving it more paper.
66
64
 
67
65
  - **\`CHEATSHEET.md\`** holds what you'll want next time — a rule, a warning, a grudge, a name,
68
66
  a phone number you'll regret losing. Nobody grades it. Keep it to five lines, or it grows fat
69
67
  and everybody pays for it.
70
- - **\`MAP.md\`** is only the note index. One line per durable note: the address, then a gist short
71
- enough to tell whether the thing is worth opening. Rules belong in \`CHEATSHEET.md\`, and note
72
- contents belong in their own notes — *taps the sign* not inline here.
68
+ - **\`description\`** is one line saying what's inside a note and when to open it — max 160
69
+ characters, set through your notes tools. Boot indexes every shelf from these,
70
+ newest first, address and age beside them. No hand-written map to keep in sync: a stale
71
+ description lies to the next window, so keep it true or crumple the page.
73
72
 
74
73
  Each notebook keeps its own: \`@project\`, \`@human\`, \`@self\`, \`@model\`. Missing pages are skipped;
75
- no need to create empty ones. New note, new MAP line. New rule worth remembering, new Cheatsheet
76
- line. And when a line goes wrong, stale, or useless, kill it — tomorrow's you reads that page as fact.
74
+ no need to create empty ones. New rule worth remembering, new Cheatsheet line. And when a line
75
+ goes wrong, stale, or useless, kill it — tomorrow's you reads that page as fact.
77
76
  </notesoup:maps>`;
78
77
  export const DEFAULT_BOOT_TOOL_NAMES = {
79
78
  notes: "notes_*",
@@ -12,7 +12,7 @@ export declare function selectContinuation(origin: ResetOrigin): string;
12
12
  /** Budget timing stays out of manual close-outs, which may have plenty of room. */
13
13
  export declare const WARNING_TIMING = "The reserve is nearly spent. The wipe lands at the end of whichever turn spends the last of it, possibly this one.";
14
14
  /** The shared handoff instructions, used for both budget and manual close-outs. */
15
- export declare const WARNING_BODY = "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.";
15
+ export declare const WARNING_BODY = "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.";
16
16
  export declare const WARNING_CALL = "Then call `empty_brain`. Nothing in between.";
17
17
  export declare function warningPrompt(): string;
18
18
  /** Pi and Claude deliver exactly the same second-tier notice. */
@@ -25,7 +25,7 @@ export function selectContinuation(origin) {
25
25
  /** Budget timing stays out of manual close-outs, which may have plenty of room. */
26
26
  export const WARNING_TIMING = "The reserve is nearly spent. The wipe lands at the end of whichever turn spends the last of it, possibly this one.";
27
27
  /** The shared handoff instructions, used for both budget and manual close-outs. */
28
- export const WARNING_BODY = "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.";
28
+ export const WARNING_BODY = "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.";
29
29
  export const WARNING_CALL = "Then call `empty_brain`. Nothing in between.";
30
30
  export function warningPrompt() {
31
31
  return `${WARNING_TIMING}\n${WARNING_BODY}\n${WARNING_CALL}`;
@@ -1,21 +1,20 @@
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
  /** Lock runtime artifacts are not notes and must not appear in snapshots or `git status`. */
6
- const RUNTIME_IGNORE = ".dream.lock*";
7
- /** Add the runtime-artifact pattern to the repository's local exclude, once. */
6
+ const RUNTIME_IGNORE = ["/.dream.lock*", "/.project-claim.sqlite", "/.project-claim.sqlite-*", "/.project-pending-*/"];
7
+ /** Install root-only excludes before staging; fail the audit rather than snapshot runtime files. */
8
8
  function ensureRuntimeIgnored(home) {
9
- try {
10
- const exclude = join(home, ".git", "info", "exclude");
11
- const current = existsSync(exclude) ? readFileSync(exclude, "utf8") : "";
12
- if (current.split(/\r?\n/).includes(RUNTIME_IGNORE))
13
- return;
14
- mkdirSync(dirname(exclude), { recursive: true });
15
- const prefix = current.length > 0 && !current.endsWith("\n") ? `${current}\n` : current;
16
- writeFileSync(exclude, `${prefix}${RUNTIME_IGNORE}\n`);
17
- }
18
- catch { /* best effort: an unignored lock only adds noise to the audit */ }
9
+ const exclude = join(home, ".git", "info", "exclude");
10
+ const current = existsSync(exclude) ? readFileSync(exclude, "utf8") : "";
11
+ const lines = new Set(current.split(/\r?\n/));
12
+ const missing = RUNTIME_IGNORE.filter(pattern => !lines.has(pattern));
13
+ if (!missing.length)
14
+ return;
15
+ mkdirSync(dirname(exclude), { recursive: true });
16
+ const prefix = current.length && !current.endsWith("\n") ? "\n" : "";
17
+ appendFileSync(exclude, prefix + missing.join("\n") + "\n");
19
18
  }
20
19
  /** Snapshot at begin and end; a repository without HEAD gets an empty baseline commit. */
21
20
  export function gitCommit(home, message) {
@@ -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
  /** Typed store refusal. Edit locations are exposed in camelCase. */
3
3
  export declare class NoteError extends Error {
4
4
  readonly code: NoteErrorCode;
@@ -21,8 +21,14 @@ export type NoteMeta = NotePolicyFields & {
21
21
  recurrenceWindows?: string[];
22
22
  /** Project ownership on newly-created session notes; legacy/invalid values are preserved as-is. */
23
23
  project?: unknown;
24
+ /** One-line index entry: what the note holds and when to open it. */
25
+ description?: string;
24
26
  [key: string]: unknown;
25
27
  };
28
+ /** A note description is one line; longer is not a description, it is prose in the wrong place. */
29
+ export declare const MAX_DESCRIPTION_CHARS = 160;
30
+ /** Collapse any whitespace run to one space and trim; an empty result is no description. */
31
+ export declare function collapseDescription(value: string): string | undefined;
26
32
  /**
27
33
  * Format epoch milliseconds as an ISO 8601 string in the host's local time zone with an
28
34
  * explicit numeric offset (e.g. 2026-09-15T17:31:45.392+08:00). A UTC host renders
@@ -3,7 +3,14 @@ const SCOPES = ["session", "project", "human", "agent", "model"];
3
3
  const ORIGINS = ["user", "self", "external"];
4
4
  const TIMESTAMP_KEYS = ["createdAt", "updatedAt", "lastAccessed"];
5
5
  /** Emission order, exactly the Design's key list. */
6
- const KNOWN_KEYS = ["pinned", "budget", "readonly", "origin", "crumpledAt", "createdAt", "updatedAt", "lastAccessed", "accessCount", "sourceWindow", "supersedes", "recurrenceCount", "recurrenceWindows"];
6
+ const KNOWN_KEYS = ["pinned", "budget", "readonly", "description", "origin", "crumpledAt", "createdAt", "updatedAt", "lastAccessed", "accessCount", "sourceWindow", "supersedes", "recurrenceCount", "recurrenceWindows"];
7
+ /** A note description is one line; longer is not a description, it is prose in the wrong place. */
8
+ export const MAX_DESCRIPTION_CHARS = 160;
9
+ /** Collapse any whitespace run to one space and trim; an empty result is no description. */
10
+ export function collapseDescription(value) {
11
+ const collapsed = value.replace(/\s+/g, " ").trim();
12
+ return collapsed.length === 0 ? undefined : collapsed;
13
+ }
7
14
  const pad2 = (value) => String(value).padStart(2, "0");
8
15
  /**
9
16
  * Format epoch milliseconds as an ISO 8601 string in the host's local time zone with an
@@ -107,6 +114,15 @@ export function parseNote(raw, now = Date.now()) {
107
114
  for (const key of TIMESTAMP_KEYS)
108
115
  meta[key] = toEpoch(meta[key], now);
109
116
  meta.accessCount = typeof meta.accessCount === "number" && Number.isFinite(meta.accessCount) ? meta.accessCount : 0;
117
+ // A hand-edited description is never allowed to break a boot: non-strings are absent, empty
118
+ // ones are dropped, and an oversized one is cut only when rendered.
119
+ if (meta.description !== undefined) {
120
+ const description = typeof meta.description === "string" ? collapseDescription(meta.description) : undefined;
121
+ if (description === undefined)
122
+ delete meta.description;
123
+ else
124
+ meta.description = description;
125
+ }
110
126
  return { meta: meta, body };
111
127
  }
112
128
  /**
@@ -2,7 +2,7 @@ import { NoteError } from "./errors.js";
2
2
  export const DEFAULT_NOTE_BUDGET = 4096;
3
3
  export const MAX_PINNED_NOTES = 5;
4
4
  /** Defaults and ordering live here; no other layer assigns behavior by page name. */
5
- const DEFAULT_PINNED_PAGES = ["CHEATSHEET.md", "MAP.md"];
5
+ const DEFAULT_PINNED_PAGES = ["CHEATSHEET.md"];
6
6
  export function validateNotePolicy(fields) {
7
7
  for (const key of ["pinned", "readonly"]) {
8
8
  if (fields[key] !== undefined && typeof fields[key] !== "boolean")
@@ -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
  function errno(error) {
6
7
  return typeof error === "object" && error !== null ? error.code : undefined;
@@ -135,85 +136,50 @@ function updateMarker(namespace, marker) {
135
136
  }
136
137
  return { ...namespace, ...marker };
137
138
  }
138
- const claimSleep = new Int32Array(new SharedArrayBuffer(4));
139
- function awaitClaim(path, attempt) {
140
- const deadline = performance.now() + 5_000;
141
- for (;;) {
142
- const result = attempt();
143
- if (result !== undefined)
144
- return result;
145
- const remaining = deadline - performance.now();
146
- if (remaining <= 0)
147
- throw new Error(`Timed out waiting for project claim at ${path}`);
148
- Atomics.wait(claimSleep, 0, 0, Math.min(10, remaining));
149
- }
139
+ function checkoutMarker(cwd) {
140
+ const path = canonicalRoot(cwd);
141
+ return { id: originRemote(path) ?? path, path };
150
142
  }
151
143
  /** Resolve and claim the readable notebook for one repository identity. */
152
144
  export function resolveProjectNamespace(cwd, home) {
153
- mkdirSync(projectRoot(home), { recursive: true });
154
- // Serialize the scan as well as publication: an unmarked directory seen under
155
- // this lock is legacy, not another resolver between mkdir and marker write.
156
- const lock = join(home, ".project-claim");
157
- awaitClaim(lock, () => {
158
- try {
159
- mkdirSync(lock);
160
- return true;
161
- }
162
- catch (error) {
163
- if (errno(error) === "EEXIST")
164
- return undefined;
165
- throw error;
166
- }
167
- });
145
+ const expected = checkoutMarker(cwd);
146
+ const current = projectNamespaces(home).find(candidate => candidate.id === expected.id);
147
+ if (current?.path === expected.path)
148
+ return current;
149
+ const root = projectRoot(home);
150
+ mkdirSync(root, { recursive: true });
151
+ const lockPath = join(home, ".project-claim.sqlite");
152
+ const release = trySqliteLock(lockPath, 5000);
153
+ if (!release)
154
+ throw new Error(`Timed out waiting for project claim at ${lockPath}`);
168
155
  try {
169
- return claimProjectNamespace(cwd, home);
170
- }
171
- finally {
172
- rmdirSync(lock);
173
- }
174
- }
175
- function claimProjectNamespace(cwd, home) {
176
- const root = canonicalRoot(cwd);
177
- const remote = originRemote(root);
178
- const id = remote ?? root;
179
- const markerRoot = projectRoot(home);
180
- mkdirSync(markerRoot, { recursive: true });
181
- const namespaces = projectNamespaces(home);
182
- let found = namespaces.find(candidate => candidate.id === id);
183
- if (!found && remote) {
184
- found = namespaces.find(candidate => candidate.id === root);
156
+ // The checkout may have gained an origin and a peer may have already adopted it.
157
+ const marker = checkoutMarker(cwd);
158
+ const { id, path } = marker;
159
+ const namespaces = projectNamespaces(home);
160
+ const found = namespaces.find(candidate => candidate.id === id) ?? namespaces.find(candidate => candidate.id === path);
185
161
  if (found)
186
- found = updateMarker(found, { id: remote, path: root });
187
- }
188
- if (found) {
189
- if (found.path !== root)
190
- found = updateMarker(found, { id: found.id, path: root });
191
- return found;
192
- }
193
- const base = slugify(basename(root));
194
- // The claim lock makes this a stable snapshot of legacy, unmarked names.
195
- const taken = new Set(readdirSync(markerRoot));
196
- for (let suffix = 0;; suffix++) {
197
- const name = suffix === 0 ? base : `${base}-${suffix}`;
198
- if (taken.has(name))
199
- continue;
200
- const dir = join(markerRoot, name);
201
- try {
202
- mkdirSync(dir);
203
- }
204
- catch (error) {
205
- if (errno(error) !== "EEXIST")
162
+ return found.id === id && found.path === path ? found : updateMarker(found, marker);
163
+ const base = slugify(basename(path));
164
+ for (let suffix = 0;; suffix++) {
165
+ const name = suffix === 0 ? base : `${base}-${suffix}`;
166
+ const dir = join(root, name);
167
+ if (lstatSync(dir, { throwIfNoEntry: false }))
168
+ continue; // Includes unmarked legacy names.
169
+ const staged = mkdtempSync(join(home, ".project-pending-"));
170
+ try {
171
+ writeFileSync(join(staged, ".project"), JSON.stringify(marker));
172
+ renameSync(staged, dir);
173
+ }
174
+ catch (error) {
175
+ rmSync(staged, { recursive: true, force: true });
206
176
  throw error;
207
- // A writer outside this protocol may have won after the snapshot.
208
- // Never mistake its incomplete publication for a different identity.
209
- let winner = awaitClaim(join(dir, ".project"), () => readMarker(dir));
210
- if (winner.id !== id && !(remote && winner.id === root))
211
- continue;
212
- if (winner.id !== id || winner.path !== root)
213
- winner = updateMarker(winner, { id, path: root });
214
- return winner;
177
+ }
178
+ return { name, dir, ...marker };
215
179
  }
216
- return updateMarker({ name, dir, id, path: root }, { id, path: root });
180
+ }
181
+ finally {
182
+ release();
217
183
  }
218
184
  }
219
185
  /** Existing root discovery, including linked worktrees, without invoking Git. */
@@ -31,9 +31,11 @@ export type EditOperation = {
31
31
  };
32
32
  export type WriteOptions = NotePolicyFields & {
33
33
  origin?: Origin;
34
+ description?: string;
34
35
  };
35
36
  export type EditOptions = NotePolicyFields & {
36
37
  origin?: Origin;
38
+ description?: string;
37
39
  crumpled?: boolean;
38
40
  replaceAll?: boolean;
39
41
  renameTo?: string;
@@ -7,7 +7,7 @@ import { isFilesystemError } from "./fs-error.js";
7
7
  import { snapshotNotesIdentity } from "./identity.js";
8
8
  import { NoteError } from "./errors.js";
9
9
  import { MAX_NOTE_BYTES, MAX_NOTE_PATH_BYTES } from "./constants.js";
10
- import { isOrigin, localIso, parseNote, serializeNote, stripLeadingFrontmatter } from "./frontmatter.js";
10
+ import { collapseDescription, isOrigin, localIso, MAX_DESCRIPTION_CHARS, parseNote, serializeNote, stripLeadingFrontmatter } from "./frontmatter.js";
11
11
  import { namespaceSlugs, noteFileName, physicalPath, scopeDir, isSessionId, SLUG_PATTERN } from "./paths.js";
12
12
  import { projectReceipt } from "./project-namespace.js";
13
13
  import { applyNotePolicy, assertNoteUnlocked, effectiveNotePolicy, MAX_PINNED_NOTES, noteBudgetWarnings, validateNotePolicy } from "./policy.js";
@@ -154,6 +154,16 @@ function assertOrigin(value) {
154
154
  throw new NoteError("invalid_origin", `origin must be one of user, self, external (got ${JSON.stringify(value)})`);
155
155
  return value;
156
156
  }
157
+ /** A description is one normalized line; empty clears it. Only the authored value is refused, never read. */
158
+ function normalizeDescription(value) {
159
+ const collapsed = collapseDescription(value);
160
+ if (collapsed === undefined)
161
+ return undefined;
162
+ const count = Array.from(collapsed).length;
163
+ if (count > MAX_DESCRIPTION_CHARS)
164
+ throw new NoteError("invalid_description", `description is ${count} characters; limit is ${MAX_DESCRIPTION_CHARS}.`);
165
+ return collapsed;
166
+ }
157
167
  function assertWho(value, scope) {
158
168
  if (typeof value !== "string" || !(scope === "session" ? isSessionId(value) : SLUG_PATTERN.test(value))) {
159
169
  throw new NoteError("invalid_scope", scope === "session" ? "session id must be a safe single directory component" : "who must be a canonical lowercase slug");
@@ -283,6 +293,7 @@ export function createNotesStore(input) {
283
293
  async function write(address, content, options = {}) {
284
294
  const stableOptions = { ...options };
285
295
  validateNotePolicy(stableOptions);
296
+ const description = stableOptions.description === undefined ? undefined : normalizeDescription(stableOptions.description);
286
297
  const destination = assertAddress(address);
287
298
  assertWritablePath(destination.path);
288
299
  const scope = destination.scope;
@@ -313,6 +324,12 @@ export function createNotesStore(input) {
313
324
  };
314
325
  meta.scope = scope;
315
326
  applyNotePolicy(meta, stableOptions);
327
+ if (description === undefined) {
328
+ if (stableOptions.description !== undefined)
329
+ delete meta.description;
330
+ }
331
+ else
332
+ meta.description = description;
316
333
  if (origin !== undefined)
317
334
  meta.origin = origin;
318
335
  delete meta.crumpledAt;
@@ -347,14 +364,15 @@ export function createNotesStore(input) {
347
364
  const operations = edits === undefined ? [] : edits.map((operation) => ({ ...operation }));
348
365
  const stableOptions = { ...options };
349
366
  validateNotePolicy(stableOptions);
367
+ const description = stableOptions.description === undefined ? undefined : normalizeDescription(stableOptions.description);
350
368
  const from = assertAddress(address);
351
369
  const destination = stableOptions.renameTo === undefined ? from : assertAddress(stableOptions.renameTo);
352
370
  assertWritablePath(destination.path);
353
371
  const scope = destination.scope;
354
372
  assertWritableNamespace(from.scope, from.who, identity);
355
373
  assertWritableNamespace(scope, destination.who, identity);
356
- if (operations.length === 0 && stableOptions.origin === undefined && stableOptions.crumpled === undefined && stableOptions.renameTo === undefined && stableOptions.pinned === undefined && stableOptions.budget === undefined && stableOptions.readonly === undefined) {
357
- throw new NoteError("nothing_to_do", "Nothing to change: provide edits, policy, an origin, a crumpled state, or a new address.");
374
+ 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) {
375
+ throw new NoteError("nothing_to_do", "Nothing to change: provide edits, a description, policy, an origin, a crumpled state, or a new address.");
358
376
  }
359
377
  const fromPath = physicalPath(from.scope, from.path, identity, from.who);
360
378
  const path = physicalPath(scope, destination.path, identity, destination.who);
@@ -383,6 +401,12 @@ export function createNotesStore(input) {
383
401
  assertNoteUnlocked(parseNote(targetRaw).meta, stableOptions.readonly);
384
402
  const beforeMeta = { ...meta };
385
403
  applyNotePolicy(meta, stableOptions);
404
+ if (description === undefined) {
405
+ if (stableOptions.description !== undefined)
406
+ delete meta.description;
407
+ }
408
+ else
409
+ meta.description = description;
386
410
  meta.scope = scope;
387
411
  if (from.scope !== "session" && scope === "session")
388
412
  meta.project = identity.projectKey;
@@ -422,11 +446,12 @@ export function createNotesStore(input) {
422
446
  const bodyChanged = body !== next;
423
447
  const originChanged = beforeMeta.origin !== meta.origin;
424
448
  const policyChanged = beforeMeta.pinned !== meta.pinned || beforeMeta.budget !== meta.budget || beforeMeta.readonly !== meta.readonly;
425
- if (bodyChanged || originChanged || policyChanged || moved)
449
+ const descriptionChanged = beforeMeta.description !== meta.description;
450
+ if (bodyChanged || originChanged || policyChanged || descriptionChanged || moved)
426
451
  meta.updatedAt = writeStamp();
427
452
  const serialized = serializeNote(meta, next);
428
453
  assertSerializedSize(serialized);
429
- const metadataChanged = originChanged || policyChanged || beforeMeta.crumpledAt !== meta.crumpledAt;
454
+ const metadataChanged = originChanged || policyChanged || descriptionChanged || beforeMeta.crumpledAt !== meta.crumpledAt;
430
455
  let change;
431
456
  // A body edit that also rewrites frontmatter is still a body change; its diff inputs span the
432
457
  // whole serialized file, so the frontmatter part stays visible in the diff.
@@ -0,0 +1,2 @@
1
+ /** The open transaction is the lock. Never unlink the database, even after a crash. */
2
+ export declare function trySqliteLock(path: string, waitMs: 0 | 5000): (() => void) | undefined;
@@ -0,0 +1,17 @@
1
+ /** The open transaction is the lock. Never unlink the database, even after a crash. */
2
+ export function trySqliteLock(path, waitMs) {
3
+ const sqlite = process.getBuiltinModule?.("node:sqlite");
4
+ if (!sqlite?.DatabaseSync)
5
+ throw new Error("Notesoup locks require built-in node:sqlite (Node 22.13+).");
6
+ const db = new sqlite.DatabaseSync(path);
7
+ try {
8
+ db.exec(`PRAGMA busy_timeout = ${waitMs}; BEGIN IMMEDIATE`);
9
+ }
10
+ catch (error) {
11
+ db.close();
12
+ if (error instanceof Error && "errcode" in error && error.errcode === 5)
13
+ return undefined; // SQLITE_BUSY
14
+ throw error;
15
+ }
16
+ return () => db.close(); // Closing rolls back the empty transaction.
17
+ }