notesoup 0.53.2 → 0.54.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.
- package/README.md +2 -2
- package/dist/plugins/claude/src/helper.js +2 -1
- package/dist/plugins/codex/src/hooks.js +1 -1
- package/dist/plugins/codex/src/identity.d.ts +1 -1
- package/dist/plugins/codex/src/identity.js +3 -3
- package/dist/plugins/codex/src/mcp.js +2 -1
- package/dist/plugins/codex/src/text.d.ts +1 -1
- package/dist/plugins/codex/src/text.js +2 -2
- package/dist/plugins/dsh/engine.js +2 -2
- package/dist/plugins/dsh/tools.js +8 -7
- package/dist/plugins/dsh/window.d.ts +1 -0
- package/dist/plugins/dsh/window.js +7 -3
- package/dist/plugins/pi/history-tools.d.ts +1 -1
- package/dist/plugins/pi/history-tools.js +4 -4
- package/dist/plugins/pi/notes/tools.js +8 -6
- package/dist/plugins/pi/render.js +7 -4
- package/dist/plugins/pi/runtime.js +2 -2
- package/dist/plugins/pi/window.js +21 -7
- package/dist/src/boot/render.js +7 -7
- package/dist/src/boot/snapshot.d.ts +7 -7
- package/dist/src/boot/snapshot.js +17 -17
- package/dist/src/boot/text.d.ts +2 -2
- package/dist/src/boot/text.js +7 -5
- package/dist/src/dream/git.d.ts +2 -11
- package/dist/src/dream/git.js +6 -23
- package/dist/src/dream/lock.d.ts +2 -2
- package/dist/src/dream/lock.js +3 -3
- package/dist/src/index.d.ts +2 -1
- package/dist/src/index.js +3 -2
- package/dist/src/notes/address.d.ts +8 -8
- package/dist/src/notes/address.js +13 -13
- package/dist/src/notes/errors.d.ts +1 -1
- package/dist/src/notes/frontmatter.js +2 -2
- package/dist/src/notes/index.d.ts +1 -1
- package/dist/src/notes/index.js +1 -1
- package/dist/src/notes/paths.d.ts +6 -6
- package/dist/src/notes/paths.js +9 -9
- package/dist/src/notes/{project-home.d.ts → project-namespace.d.ts} +7 -7
- package/dist/src/notes/{project-home.js → project-namespace.js} +67 -25
- package/dist/src/notes/store.d.ts +4 -4
- package/dist/src/notes/store.js +55 -52
- package/dist/src/tools/dream.d.ts +21 -3
- package/dist/src/tools/dream.js +54 -16
- package/dist/src/tools/notes-context.d.ts +10 -0
- package/dist/src/tools/notes-context.js +27 -0
- package/dist/src/tools/notes.d.ts +69 -20
- package/dist/src/tools/notes.js +40 -31
- package/dist/test/boot.integration.test.js +1 -1
- package/dist/test/claude-mod.test.js +89 -43
- package/dist/test/codex-plugin.test.js +18 -1
- package/dist/test/context-edit-budget.test.js +121 -0
- package/dist/test/dependencies.test.js +71 -4
- package/dist/test/dream-tools.test.js +153 -8
- package/dist/test/dsh.test.js +62 -15
- package/dist/test/helpers/dsh.d.ts +4 -1
- package/dist/test/helpers/dsh.js +20 -4
- package/dist/test/helpers/extension.d.ts +5 -0
- package/dist/test/helpers/extension.js +33 -2
- package/dist/test/host-neutral.test.js +17 -15
- package/dist/test/model-facing-text.test.js +12 -8
- package/dist/test/notes-cwd.test.js +114 -0
- package/dist/test/notes-library.test.js +4 -4
- package/dist/test/notes-query-namespaces.test.d.ts +1 -0
- package/dist/test/{notes-query-homes.test.js → notes-query-namespaces.test.js} +13 -13
- package/dist/test/notes.integration.test.js +72 -23
- package/dist/test/notes.test.js +50 -20
- package/dist/test/pi-render.test.js +33 -1
- package/dist/test/project-namespace.test.d.ts +1 -0
- package/dist/test/project-namespace.test.js +324 -0
- package/docs/architecture.md +12 -7
- package/docs/codex.md +4 -4
- package/docs/dsh.md +8 -8
- package/docs/notes-library.md +9 -5
- package/docs/skills.md +3 -3
- package/docs/tool-results.md +6 -2
- package/package.json +4 -6
- package/playbook.md +6 -6
- package/plugins/claude/.claude-plugin/plugin.json +1 -1
- package/plugins/claude/dist/claude/helper.js +677 -615
- package/plugins/claude/hooks/register.ts +19 -11
- package/plugins/claude/playbook.md +6 -6
- package/plugins/claude/skills/memory/SKILL.md +4 -4
- package/plugins/claude/src/helper.ts +3 -2
- package/plugins/codex/README.md +1 -1
- package/plugins/codex/dist/codex/notesoup.js +877 -815
- package/plugins/codex/src/hooks.ts +1 -1
- package/plugins/codex/src/identity.ts +3 -3
- package/plugins/codex/src/mcp.ts +2 -1
- package/plugins/codex/src/text.ts +2 -2
- package/plugins/dsh/engine.ts +2 -2
- package/plugins/dsh/tools.ts +8 -7
- package/plugins/dsh/window.ts +8 -3
- package/plugins/paseo/OVERVIEW.md +4 -4
- package/plugins/paseo/README.md +1 -1
- package/plugins/paseo/client/brain-empty-card.tsx +3 -4
- package/plugins/paseo/client/markdown.tsx +179 -0
- package/plugins/paseo/client/notes-op-card.tsx +35 -34
- package/plugins/paseo/client/notes-op-transformer.ts +17 -68
- package/plugins/paseo/client/paper-card.tsx +8 -19
- package/plugins/paseo/client/paper-palette.ts +40 -0
- package/plugins/paseo/client/sticky-card.tsx +6 -4
- package/plugins/paseo/package.json +3 -0
- package/plugins/paseo/paseo-plugin.json +2 -2
- package/plugins/paseo/shared/notes-op.ts +13 -9
- package/plugins/paseo/test/notes-op.test.ts +52 -73
- package/plugins/paseo/test/paper-palette.test.ts +54 -0
- package/plugins/pi/history-tools.ts +4 -4
- package/plugins/pi/notes/tools.ts +8 -6
- package/plugins/pi/render.ts +6 -4
- package/plugins/pi/runtime.ts +2 -2
- package/plugins/pi/window.ts +22 -7
- package/skills/memory/SKILL.md +4 -4
- package/src/boot/render.ts +8 -8
- package/src/boot/snapshot.ts +20 -20
- package/src/boot/text.ts +7 -5
- package/src/dream/git.ts +7 -24
- package/src/dream/lock.ts +3 -3
- package/src/index.ts +4 -3
- package/src/notes/address.ts +13 -13
- package/src/notes/errors.ts +1 -1
- package/src/notes/frontmatter.ts +2 -2
- package/src/notes/index.ts +1 -1
- package/src/notes/paths.ts +9 -9
- package/src/notes/{project-home.ts → project-namespace.ts} +59 -28
- package/src/notes/store.ts +61 -58
- package/src/tools/dream.ts +63 -16
- package/src/tools/notes-context.ts +29 -0
- package/src/tools/notes.ts +39 -29
- package/dist/test/project-home.test.js +0 -134
- /package/dist/test/{notes-query-homes.test.d.ts → context-edit-budget.test.d.ts} +0 -0
- /package/dist/test/{project-home.test.d.ts → notes-cwd.test.d.ts} +0 -0
package/src/notes/store.ts
CHANGED
|
@@ -3,14 +3,14 @@ import type { Dirent } from "node:fs";
|
|
|
3
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
|
-
import { assertAddress, assertGlobPattern, addressFor, canonicalAddressFor, globToRegExp,
|
|
6
|
+
import { assertAddress, assertGlobPattern, addressFor, canonicalAddressFor, globToRegExp, NAMESPACE_HEADS } from "./address.js";
|
|
7
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
11
|
import { isOrigin, localIso, 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
|
-
import { projectReceipt, type ProjectReceipt } from "./project-
|
|
13
|
+
import { projectReceipt, type ProjectReceipt } from "./project-namespace.js";
|
|
14
14
|
|
|
15
15
|
export type { NoteMeta, Origin, Scope };
|
|
16
16
|
|
|
@@ -28,7 +28,7 @@ export type NoteSearchRow = { address: string; scope: Scope; path: string; meta:
|
|
|
28
28
|
export type EditOperation = { oldText: string; newText: string };
|
|
29
29
|
export type WriteOptions = { origin?: Origin };
|
|
30
30
|
export type EditOptions = { origin?: Origin; crumpled?: boolean; replaceAll?: boolean; renameTo?: string };
|
|
31
|
-
/** Omitted/null/empty glob or bare @default selects current
|
|
31
|
+
/** Omitted/null/empty glob or bare @default selects current notebooks; explicit globs match full addresses.
|
|
32
32
|
* Only the current session also matches its bare-path alias (e.g. *.md or deep/**).
|
|
33
33
|
*/
|
|
34
34
|
export type NotesQuery = { glob?: string | null; crumpled?: boolean };
|
|
@@ -41,8 +41,8 @@ export type NoteChange =
|
|
|
41
41
|
| { kind: "body" | "metadata"; before: string; after: string };
|
|
42
42
|
export type NoteEditResult = { meta: NoteMeta; applied: number; resolvedScope: Scope; change: NoteChange; moved: boolean; replacedCrumpledTarget: boolean };
|
|
43
43
|
export type NoteRenameResult = { meta: NoteMeta; replacedCrumpledTarget: boolean };
|
|
44
|
-
/** A
|
|
45
|
-
export type NoteQueryStatus = {
|
|
44
|
+
/** A notebook, or one unreadable note inside it, that a status-reporting query could not read. */
|
|
45
|
+
export type NoteQueryStatus = { namespacesUnavailable: string[] };
|
|
46
46
|
export type NoteQueryResult<T> = { rows: T[]; status: NoteQueryStatus };
|
|
47
47
|
|
|
48
48
|
/** Public note identity; named projects also carry their display root and sibling hints. */
|
|
@@ -104,8 +104,8 @@ async function walkMarkdown(dir: string, base = dir): Promise<string[]> {
|
|
|
104
104
|
try {
|
|
105
105
|
entries = await readdir(dir, { withFileTypes: true });
|
|
106
106
|
} catch (error) {
|
|
107
|
-
// A
|
|
108
|
-
// boot snapshot boundary instead of masquerading as an empty
|
|
107
|
+
// A notebook that has never been created is normal. Other failures must reach the
|
|
108
|
+
// boot snapshot boundary instead of masquerading as an empty notebook.
|
|
109
109
|
if (errno(error) === "ENOENT") return [];
|
|
110
110
|
throw error;
|
|
111
111
|
}
|
|
@@ -118,28 +118,28 @@ async function walkMarkdown(dir: string, base = dir): Promise<string[]> {
|
|
|
118
118
|
return paths;
|
|
119
119
|
}
|
|
120
120
|
|
|
121
|
-
/** Which
|
|
122
|
-
type
|
|
121
|
+
/** Which namespaces one call iterates; reserved heads narrow traversal before any file is read. */
|
|
122
|
+
type NamespaceRef = { scope: Scope; who?: string };
|
|
123
123
|
|
|
124
|
-
async function
|
|
124
|
+
async function namespacesForPattern(pattern: string | undefined, identity: NotesIdentity, status?: NoteQueryStatus): Promise<NamespaceRef[]> {
|
|
125
125
|
if (pattern === undefined) return SCOPE_ORDER.map((scope) => ({ scope }));
|
|
126
126
|
|
|
127
127
|
const families = [
|
|
128
|
-
{ scope: "session",
|
|
129
|
-
{ scope: "project",
|
|
130
|
-
{ scope: "agent",
|
|
131
|
-
{ scope: "model",
|
|
128
|
+
{ scope: "session", dir: "sessions", current: identity.sessionId },
|
|
129
|
+
{ scope: "project", dir: "project", current: identity.projectKey },
|
|
130
|
+
{ scope: "agent", dir: "agents", current: identity.agent },
|
|
131
|
+
{ scope: "model", dir: "models", current: identity.model },
|
|
132
132
|
] as const;
|
|
133
|
-
async function enumerate(family: typeof families[number], relative: boolean): Promise<
|
|
133
|
+
async function enumerate(family: typeof families[number], relative: boolean): Promise<NamespaceRef[]> {
|
|
134
134
|
let names: string[];
|
|
135
135
|
try {
|
|
136
|
-
names = await namespaceSlugs(family.
|
|
136
|
+
names = await namespaceSlugs(family.dir, identity.home);
|
|
137
137
|
} catch (error) {
|
|
138
138
|
if (!status || !isFilesystemError(error)) throw error;
|
|
139
|
-
status.
|
|
139
|
+
status.namespacesUnavailable.push(`@${family.dir === "project" ? "projects" : family.dir}`);
|
|
140
140
|
return [];
|
|
141
141
|
}
|
|
142
|
-
// Include the current
|
|
142
|
+
// Include the current namespace even when missing or a non-directory, and only once.
|
|
143
143
|
return [...new Set([family.current, ...names])].map((who) => ({
|
|
144
144
|
scope: family.scope,
|
|
145
145
|
who: relative && who === family.current ? undefined : who,
|
|
@@ -149,21 +149,21 @@ async function homesForPattern(pattern: string | undefined, identity: NotesIdent
|
|
|
149
149
|
if (pattern.startsWith("@")) {
|
|
150
150
|
const [rawHead, ...tail] = pattern.slice(1).split("/");
|
|
151
151
|
if (!/[*?]/.test(rawHead!)) {
|
|
152
|
-
const head =
|
|
152
|
+
const head = NAMESPACE_HEADS.get(rawHead!);
|
|
153
153
|
if (head === undefined || tail.length === 0) return [];
|
|
154
|
-
if (head.
|
|
154
|
+
if (head.dir === undefined) return [{ scope: head.scope }];
|
|
155
155
|
const name = tail[0];
|
|
156
156
|
if (name && !/[*?]/.test(name)) return [{ scope: head.scope, who: assertWho(name, head.scope) }];
|
|
157
|
-
return enumerate(families.find((family) => family.
|
|
157
|
+
return enumerate(families.find((family) => family.dir === head.dir)!, false);
|
|
158
158
|
}
|
|
159
159
|
}
|
|
160
160
|
// Unreserved patterns see the full universe, not just the current identities.
|
|
161
|
-
const
|
|
161
|
+
const namespaces: NamespaceRef[] = [];
|
|
162
162
|
for (const scope of SCOPE_ORDER) {
|
|
163
|
-
if (scope === "human")
|
|
164
|
-
else
|
|
163
|
+
if (scope === "human") namespaces.push({ scope });
|
|
164
|
+
else namespaces.push(...await enumerate(families.find((family) => family.scope === scope)!, true));
|
|
165
165
|
}
|
|
166
|
-
return
|
|
166
|
+
return namespaces;
|
|
167
167
|
}
|
|
168
168
|
|
|
169
169
|
/** Relative pattern heads resolve to canonical names, so they match canonical addresses. */
|
|
@@ -256,24 +256,27 @@ function frontmatterOf(meta: NoteMeta): string {
|
|
|
256
256
|
return serializeNote(meta, "").slice(0, -2);
|
|
257
257
|
}
|
|
258
258
|
|
|
259
|
-
/** Explicit session/project
|
|
260
|
-
function
|
|
259
|
+
/** Explicit session/project namespaces are read-only unless dreamed over; agent/model namespaces allow their owner. */
|
|
260
|
+
function assertWritableNamespace(scope: Scope, who: string | undefined, identity: NotesIdentity): void {
|
|
261
261
|
if (who === undefined) return;
|
|
262
|
-
// A dreamed project is writable whole;
|
|
262
|
+
// A dreamed project is writable whole; project and session ownership is checked per note by assertDreamNote.
|
|
263
263
|
if (identity.dreaming !== undefined && (scope === "session" || (scope === "project" && who === identity.dreaming))) return;
|
|
264
264
|
if (scope === "session") throw new NoteError("invalid_scope", `@sessions/${who}/ is read-only; use a bare path to write to this session.`);
|
|
265
265
|
if (scope === "project") throw new NoteError("invalid_scope", `@projects/${who}/ is read-only; use @project/ to write to your own project.`);
|
|
266
266
|
const current = scope === "agent" ? identity.agent : identity.model;
|
|
267
267
|
if (who === current) return;
|
|
268
|
-
const
|
|
269
|
-
throw new NoteError("invalid_scope", `${
|
|
268
|
+
const address = scope === "agent" ? `@agents/${who}/` : `@models/${who}/`;
|
|
269
|
+
throw new NoteError("invalid_scope", `${address} is someone else's notebook; you can write to this session, @project/, @human/, @self/, or @model/.`);
|
|
270
270
|
}
|
|
271
271
|
|
|
272
|
-
/**
|
|
273
|
-
function
|
|
274
|
-
if (scope !== "session"
|
|
275
|
-
|
|
276
|
-
|
|
272
|
+
/** Resolve aliases before checking that a dreamed note belongs to the open project. */
|
|
273
|
+
function assertDreamNote(scope: Scope, who: string | undefined, identity: NotesIdentity, raw: string | undefined, address: string): void {
|
|
274
|
+
if (identity.dreaming === undefined || (scope !== "session" && scope !== "project")) return;
|
|
275
|
+
const project = scope === "project" ? who ?? identity.projectKey
|
|
276
|
+
: raw !== undefined ? parseNote(raw).meta.project
|
|
277
|
+
: who === undefined ? identity.projectKey : undefined;
|
|
278
|
+
if (project === identity.dreaming) return;
|
|
279
|
+
throw new NoteError("invalid_scope", raw === undefined && scope === "session" && who !== undefined
|
|
277
280
|
? `${address}: a dream edits other sessions' existing notes, it doesn't create new ones there.`
|
|
278
281
|
: `${address} belongs to another project, not the one being dreamed over (${identity.dreaming}).`);
|
|
279
282
|
}
|
|
@@ -287,7 +290,7 @@ export function createNotesStore(input: NotesIdentity): NotesStore {
|
|
|
287
290
|
const destination = assertAddress(address);
|
|
288
291
|
assertWritablePath(destination.path);
|
|
289
292
|
const scope = destination.scope;
|
|
290
|
-
|
|
293
|
+
assertWritableNamespace(scope, destination.who, identity);
|
|
291
294
|
// Absent means "keep whatever the note already says": replacing a note must not silently
|
|
292
295
|
// re-attribute a user-written note to the agent that happened to rewrite it.
|
|
293
296
|
const origin = stableOptions.origin === undefined ? undefined : assertOrigin(stableOptions.origin);
|
|
@@ -296,7 +299,7 @@ export function createNotesStore(input: NotesIdentity): NotesStore {
|
|
|
296
299
|
const now = writeStamp();
|
|
297
300
|
const cleanBody = stripLeadingFrontmatter(content);
|
|
298
301
|
const existingRaw = await readFileIfExists(path);
|
|
299
|
-
|
|
302
|
+
assertDreamNote(scope, destination.who, identity, existingRaw, address);
|
|
300
303
|
const existing = existingRaw === undefined ? undefined : parseNote(existingRaw, now).meta;
|
|
301
304
|
const outcome = existing === undefined ? "created" : existing.crumpledAt === undefined ? "overwrote" : "uncrumpled";
|
|
302
305
|
const meta: NoteMeta = existing ?? {
|
|
@@ -328,7 +331,7 @@ export function createNotesStore(input: NotesIdentity): NotesStore {
|
|
|
328
331
|
if (raw === undefined) return undefined;
|
|
329
332
|
const now = Date.now();
|
|
330
333
|
const parsed = parseNote(raw, now);
|
|
331
|
-
// Named
|
|
334
|
+
// Named notebooks, and every read during a dream, leave no access stamp.
|
|
332
335
|
if (identity.dreaming !== undefined || ((scope === "project" || scope === "session") && destination.who !== undefined)) return { meta: { ...parsed.meta, scope }, body: parsed.body, resolvedScope: scope, accessedBefore: parsed.meta.lastAccessed };
|
|
333
336
|
// A read records its own access, exactly as a write records an edit.
|
|
334
337
|
const meta: NoteMeta = { ...parsed.meta, scope, lastAccessed: now, accessCount: (typeof parsed.meta.accessCount === "number" ? parsed.meta.accessCount : 0) + 1 };
|
|
@@ -344,8 +347,8 @@ export function createNotesStore(input: NotesIdentity): NotesStore {
|
|
|
344
347
|
const destination = stableOptions.renameTo === undefined ? from : assertAddress(stableOptions.renameTo);
|
|
345
348
|
assertWritablePath(destination.path);
|
|
346
349
|
const scope = destination.scope;
|
|
347
|
-
|
|
348
|
-
|
|
350
|
+
assertWritableNamespace(from.scope, from.who, identity);
|
|
351
|
+
assertWritableNamespace(scope, destination.who, identity);
|
|
349
352
|
if (operations.length === 0 && stableOptions.origin === undefined && stableOptions.crumpled === undefined && stableOptions.renameTo === undefined) {
|
|
350
353
|
throw new NoteError("nothing_to_do", "Nothing to change: provide edits, an origin, a crumpled state, or a new address.");
|
|
351
354
|
}
|
|
@@ -356,8 +359,8 @@ export function createNotesStore(input: NotesIdentity): NotesStore {
|
|
|
356
359
|
const raw = await readFileIfExists(fromPath);
|
|
357
360
|
if (raw === undefined) throw new NoteError("not_found", `No note at ${noteIdentity(identity, address).address}.`);
|
|
358
361
|
const targetRaw = differentPaths ? await readFileIfExists(path) : undefined;
|
|
359
|
-
|
|
360
|
-
if (differentPaths)
|
|
362
|
+
assertDreamNote(from.scope, from.who, identity, raw, address);
|
|
363
|
+
if (differentPaths) assertDreamNote(scope, destination.who, identity, targetRaw, stableOptions.renameTo!);
|
|
361
364
|
// Case and symlink aliases must not turn write-then-remove into deleting the result.
|
|
362
365
|
const sourceReal = targetRaw === undefined ? undefined : await realpath(fromPath);
|
|
363
366
|
const sameFile = sourceReal !== undefined && sourceReal === await realpath(path);
|
|
@@ -425,12 +428,12 @@ export function createNotesStore(input: NotesIdentity): NotesStore {
|
|
|
425
428
|
async function forget(address: string): Promise<NoteMeta> {
|
|
426
429
|
if (identity.dreaming === undefined) throw new NoteError("invalid_scope", "Only a dream can delete notes; begin one first.");
|
|
427
430
|
const target = assertAddress(address);
|
|
428
|
-
|
|
431
|
+
assertWritableNamespace(target.scope, target.who, identity);
|
|
429
432
|
const path = physicalPath(target.scope, target.path, identity, target.who);
|
|
430
433
|
return withPathQueue(path, async () => {
|
|
431
434
|
const raw = await readFileIfExists(path);
|
|
432
435
|
if (raw === undefined) throw new NoteError("not_found", `No note at ${noteIdentity(identity, address).address}.`);
|
|
433
|
-
|
|
436
|
+
assertDreamNote(target.scope, target.who, identity, raw, address);
|
|
434
437
|
const { meta } = parseNote(raw);
|
|
435
438
|
if (meta.crumpledAt === undefined) throw new NoteError("not_crumpled", `${noteIdentity(identity, address).address} isn't crumpled; crumple it before deleting.`);
|
|
436
439
|
await unlink(path);
|
|
@@ -443,30 +446,30 @@ export function createNotesStore(input: NotesIdentity): NotesStore {
|
|
|
443
446
|
const pattern = glob === "@default" ? undefined : glob;
|
|
444
447
|
const normalized = normalizePattern(pattern, identity);
|
|
445
448
|
const matcher = normalized === undefined ? undefined : globToRegExp(normalized);
|
|
446
|
-
const
|
|
447
|
-
for (const
|
|
448
|
-
const scope =
|
|
449
|
-
const root = scopeDir(scope, identity,
|
|
449
|
+
const namespaces = await namespacesForPattern(pattern, identity, status);
|
|
450
|
+
for (const namespace of namespaces) {
|
|
451
|
+
const scope = namespace.scope;
|
|
452
|
+
const root = scopeDir(scope, identity, namespace.who);
|
|
450
453
|
let paths: string[];
|
|
451
454
|
try {
|
|
452
455
|
paths = await walkMarkdown(root);
|
|
453
456
|
} catch (error) {
|
|
454
457
|
if (!status || !isFilesystemError(error)) throw error;
|
|
455
|
-
status.
|
|
458
|
+
status.namespacesUnavailable.push(addressFor(identity, scope, "", namespace.who).replace(/\/$/, "") || "session");
|
|
456
459
|
continue;
|
|
457
460
|
}
|
|
458
461
|
for (const path of paths) {
|
|
459
|
-
if (matcher && !matcher.test(canonicalAddressFor(identity, scope, path,
|
|
460
|
-
&& !(scope === "session" &&
|
|
461
|
-
const address = addressFor(identity, scope, path,
|
|
462
|
+
if (matcher && !matcher.test(canonicalAddressFor(identity, scope, path, namespace.who))
|
|
463
|
+
&& !(scope === "session" && namespace.who === undefined && !pattern!.startsWith("@") && matcher.test(path))) continue;
|
|
464
|
+
const address = addressFor(identity, scope, path, namespace.who);
|
|
462
465
|
const fullPath = join(root, path);
|
|
463
466
|
let raw: string;
|
|
464
467
|
try {
|
|
465
468
|
raw = await withPathQueue(fullPath, () => readFile(fullPath, "utf8"));
|
|
466
469
|
} catch (error) {
|
|
467
|
-
// One unreadable note is named on its own; its
|
|
470
|
+
// One unreadable note is named on its own; its notebook's readable notes still list.
|
|
468
471
|
if (!status || !isFilesystemError(error)) throw error;
|
|
469
|
-
status.
|
|
472
|
+
status.namespacesUnavailable.push(address);
|
|
470
473
|
continue;
|
|
471
474
|
}
|
|
472
475
|
const { meta, body } = parseNote(raw);
|
|
@@ -488,11 +491,11 @@ export function createNotesStore(input: NotesIdentity): NotesStore {
|
|
|
488
491
|
rows.push({ ...row, sizeBytes: Buffer.byteLength(row.body, "utf8") });
|
|
489
492
|
}
|
|
490
493
|
rows.sort((a, b) => b.meta.updatedAt - a.meta.updatedAt || a.address.localeCompare(b.address));
|
|
491
|
-
return { rows, status: status ?? {
|
|
494
|
+
return { rows, status: status ?? { namespacesUnavailable: [] } };
|
|
492
495
|
}
|
|
493
496
|
|
|
494
497
|
function listWithStatus(options: NotesQuery = {}): Promise<NoteQueryResult<NoteRow>> {
|
|
495
|
-
return listRows(options, {
|
|
498
|
+
return listRows(options, { namespacesUnavailable: [] });
|
|
496
499
|
}
|
|
497
500
|
|
|
498
501
|
async function search(queries: string[], options: NotesQuery = {}): Promise<NoteSearchRow[]> {
|
|
@@ -523,11 +526,11 @@ export function createNotesStore(input: NotesIdentity): NotesStore {
|
|
|
523
526
|
if (matches.length > 0) rows.push({ address, path, scope, meta, matches });
|
|
524
527
|
}
|
|
525
528
|
rows.sort((a, b) => a.address.localeCompare(b.address));
|
|
526
|
-
return { rows, status: status ?? {
|
|
529
|
+
return { rows, status: status ?? { namespacesUnavailable: [] } };
|
|
527
530
|
}
|
|
528
531
|
|
|
529
532
|
function searchWithStatus(queries: string[], options: NotesQuery = {}): Promise<NoteQueryResult<NoteSearchRow>> {
|
|
530
|
-
return searchRows(queries, options, {
|
|
533
|
+
return searchRows(queries, options, { namespacesUnavailable: [] });
|
|
531
534
|
}
|
|
532
535
|
|
|
533
536
|
return { write, read, update, rename, forget, list, search, listWithStatus, searchWithStatus };
|
package/src/tools/dream.ts
CHANGED
|
@@ -1,20 +1,46 @@
|
|
|
1
1
|
/** Dream operations: open one project's notes for consolidation, delete crumpled notes, close. */
|
|
2
2
|
import { Type, type Static } from "typebox";
|
|
3
3
|
import { createNotesStore, noteIdentity, type NoteRow, type NotesIdentity } from "../notes/index.js";
|
|
4
|
-
import {
|
|
4
|
+
import { projectNamespaces } from "../notes/project-namespace.js";
|
|
5
5
|
import { gitCommit } from "../dream/git.js";
|
|
6
6
|
import { acquireDreamLock, dreamLockPath, releaseDreamLock, type DreamLock } from "../dream/lock.js";
|
|
7
7
|
import { failure, renderOutcome, resultSchema, success, type Outcome } from "./result.js";
|
|
8
|
-
import { failureOf, listedFile, NotesListDataSchema, renderListData, snapshot } from "./notes.js";
|
|
8
|
+
import { failureOf, listedFile, NoteIdentitySchema, NotesListDataSchema, renderListData, snapshot } from "./notes.js";
|
|
9
9
|
|
|
10
10
|
/** The one open dream per session; the host owns where it lives. */
|
|
11
|
-
|
|
11
|
+
type DreamOpening = { project: string; lock: DreamLock; generation: number };
|
|
12
|
+
export type DreamState = { project?: string; lock?: DreamLock; pending?: DreamOpening; generation?: number };
|
|
13
|
+
|
|
14
|
+
function currentOpening(state: DreamState, opening: DreamOpening): boolean {
|
|
15
|
+
return state.pending === opening && state.generation === opening.generation;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
function nextGeneration(state: DreamState): number {
|
|
19
|
+
const generation = (state.generation ?? 0) + 1;
|
|
20
|
+
state.generation = generation;
|
|
21
|
+
return generation;
|
|
22
|
+
}
|
|
12
23
|
|
|
13
24
|
/** Drop an open dream without an end commit, e.g. when its session shuts down. */
|
|
14
25
|
export function abandonDream(state: DreamState): void {
|
|
15
|
-
|
|
26
|
+
const pending = state.pending;
|
|
27
|
+
if (pending) releaseDreamLock(pending.lock);
|
|
28
|
+
if (state.lock && state.lock !== pending?.lock) releaseDreamLock(state.lock);
|
|
29
|
+
nextGeneration(state);
|
|
16
30
|
delete state.project;
|
|
17
31
|
delete state.lock;
|
|
32
|
+
delete state.pending;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** Release an opening without disturbing a newer opening in the same state. */
|
|
36
|
+
function releaseOpening(state: DreamState, opening: DreamOpening): void {
|
|
37
|
+
releaseDreamLock(opening.lock);
|
|
38
|
+
if (currentOpening(state, opening)) delete state.pending;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function cancelledOpening(state: DreamState, opening: DreamOpening): Outcome<never> {
|
|
42
|
+
releaseOpening(state, opening);
|
|
43
|
+
return failure("cancelled", "The dream opening was cancelled before it completed.");
|
|
18
44
|
}
|
|
19
45
|
|
|
20
46
|
/** The identity a store uses while `state` holds an open dream. */
|
|
@@ -37,16 +63,22 @@ function renderBeginData(data: DreamBeginData): string {
|
|
|
37
63
|
|
|
38
64
|
export const dreamBegin = {
|
|
39
65
|
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.
|
|
66
|
+
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. Holds the notes home's dream lock through dream_end so Git audits cannot interleave, and commits a baseline of the notes home.",
|
|
41
67
|
parameters: dreamBeginParameters, outputSchema: resultSchema(DreamBeginDataSchema),
|
|
42
68
|
async execute(params: Static<typeof dreamBeginParameters>, identity: NotesIdentity, state: DreamState): Promise<Outcome<DreamBeginData>> {
|
|
43
|
-
if (state.project !== undefined
|
|
69
|
+
if (state.project !== undefined || state.pending !== undefined) {
|
|
70
|
+
const project = state.project ?? state.pending?.project;
|
|
71
|
+
return failure("already_dreaming", `Already dreaming over ${project}; call dream_end before opening another project.`);
|
|
72
|
+
}
|
|
44
73
|
const project = params.project ?? identity.projectKey;
|
|
45
|
-
if (project !== identity.projectKey && !
|
|
74
|
+
if (project !== identity.projectKey && !projectNamespaces(identity.home).some(namespace => namespace.name === project)) {
|
|
46
75
|
return failure("not_found", `No project named ${JSON.stringify(project)}; notes_list with glob @projects/*/** shows the names.`);
|
|
47
76
|
}
|
|
48
|
-
const lock = acquireDreamLock(dreamLockPath(identity.home
|
|
49
|
-
if (!lock) return failure("already_dreaming", `Another dream holds ${dreamLockPath(identity.home
|
|
77
|
+
const lock = acquireDreamLock(dreamLockPath(identity.home));
|
|
78
|
+
if (!lock) return failure("already_dreaming", `Another dream holds ${dreamLockPath(identity.home)}. If none is running, delete that file by hand.`);
|
|
79
|
+
// Publish ownership before the first await. Shutdown can therefore release this exact token.
|
|
80
|
+
const opening: DreamOpening = { project, lock, generation: nextGeneration(state) };
|
|
81
|
+
state.pending = opening;
|
|
50
82
|
try {
|
|
51
83
|
const store = createNotesStore({ ...identity, dreaming: project });
|
|
52
84
|
const rows: NoteRow[] = [];
|
|
@@ -54,24 +86,39 @@ export const dreamBegin = {
|
|
|
54
86
|
for (const crumpled of [false, true]) {
|
|
55
87
|
for (const glob of [`@projects/${project}/**`, "@sessions/*/**"]) {
|
|
56
88
|
const result = await store.listWithStatus({ glob, crumpled });
|
|
89
|
+
if (!currentOpening(state, opening)) return cancelledOpening(state, opening);
|
|
57
90
|
rows.push(...result.rows.filter(row => row.scope === "project" || row.meta.project === project));
|
|
58
|
-
unavailable.push(...result.status.
|
|
91
|
+
unavailable.push(...result.status.namespacesUnavailable);
|
|
59
92
|
}
|
|
60
93
|
}
|
|
61
94
|
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, {
|
|
63
|
-
if (!listed.ok) {
|
|
95
|
+
const listed = snapshot(rows.map(row => listedFile(row, identity)), undefined, { namespacesUnavailable: unavailable }, renderListData);
|
|
96
|
+
if (!listed.ok) {
|
|
97
|
+
releaseOpening(state, opening);
|
|
98
|
+
return listed;
|
|
99
|
+
}
|
|
100
|
+
if (!currentOpening(state, opening)) return cancelledOpening(state, opening);
|
|
64
101
|
const baseline = gitCommit(identity.home, `dream baseline ${project}`);
|
|
65
|
-
if (!baseline.ok) {
|
|
66
|
-
|
|
102
|
+
if (!baseline.ok) {
|
|
103
|
+
releaseOpening(state, opening);
|
|
104
|
+
return failure("audit_failed", `Couldn't commit the Git baseline, so nothing could be rolled back; no dream was opened: ${baseline.error}`);
|
|
105
|
+
}
|
|
106
|
+
if (!currentOpening(state, opening)) return cancelledOpening(state, opening);
|
|
107
|
+
state.project = opening.project;
|
|
108
|
+
state.lock = opening.lock;
|
|
109
|
+
delete state.pending;
|
|
67
110
|
return success({ project, baseline: baseline.commit, ...listed.data });
|
|
68
|
-
} catch (error) {
|
|
111
|
+
} catch (error) {
|
|
112
|
+
if (!currentOpening(state, opening)) return cancelledOpening(state, opening);
|
|
113
|
+
releaseOpening(state, opening);
|
|
114
|
+
return failureOf(error);
|
|
115
|
+
}
|
|
69
116
|
},
|
|
70
117
|
render: (result: Outcome<DreamBeginData>): string => renderOutcome(result, renderBeginData),
|
|
71
118
|
} as const;
|
|
72
119
|
|
|
73
120
|
export const dreamForgetParameters = Type.Object({ address: Type.String() }, { additionalProperties: false });
|
|
74
|
-
export const DreamForgetDataSchema = Type.Object({
|
|
121
|
+
export const DreamForgetDataSchema = Type.Object({ ...NoteIdentitySchema }, { additionalProperties: false });
|
|
75
122
|
export type DreamForgetData = Static<typeof DreamForgetDataSchema>;
|
|
76
123
|
|
|
77
124
|
export const dreamForget = {
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import { statSync } from "node:fs";
|
|
2
|
+
import { resolve } from "node:path";
|
|
3
|
+
import { NoteError } from "../notes/errors.js";
|
|
4
|
+
import { projectKey, snapshotNotesIdentity, type NotesIdentity } from "../notes/index.js";
|
|
5
|
+
|
|
6
|
+
/** Host-supplied facts for one notes tool registration; overrides never mutate this context. */
|
|
7
|
+
export type NotesToolContext = Readonly<{
|
|
8
|
+
identity: NotesIdentity;
|
|
9
|
+
cwd: string;
|
|
10
|
+
}>;
|
|
11
|
+
|
|
12
|
+
/** Capture the host's base cwd alongside its default identity. */
|
|
13
|
+
export function notesToolContext(identity: NotesIdentity, cwd: string): NotesToolContext {
|
|
14
|
+
if (typeof cwd !== "string" || cwd.length === 0) throw new TypeError("notes tool cwd must be a non-empty string");
|
|
15
|
+
return Object.freeze({ identity: snapshotNotesIdentity(identity), cwd: resolve(cwd) });
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/** Resolve the current-project override once, before any address, receipt, or ownership decision. */
|
|
19
|
+
export function notesIdentityForCall(context: NotesToolContext, cwd?: string): NotesIdentity {
|
|
20
|
+
if (cwd === undefined) return context.identity;
|
|
21
|
+
const resolved = resolve(context.cwd, cwd);
|
|
22
|
+
let directory = false;
|
|
23
|
+
try { directory = statSync(resolved).isDirectory(); } catch { /* Report one typed refusal below. */ }
|
|
24
|
+
if (!directory) throw new NoteError("invalid_cwd", `cwd is not an existing directory: ${JSON.stringify(cwd)} (resolved to ${resolved}).`);
|
|
25
|
+
return snapshotNotesIdentity({
|
|
26
|
+
...context.identity,
|
|
27
|
+
projectKey: projectKey(resolved, context.identity.home),
|
|
28
|
+
});
|
|
29
|
+
}
|