notesoup 0.57.3 → 0.58.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 +15 -1
- package/dist/plugins/claude/src/helper.js +2 -11
- package/dist/plugins/claude/src/thresholds.js +5 -18
- package/dist/plugins/codex/src/mcp.js +3 -11
- package/dist/plugins/codex/src/state.d.ts +1 -1
- package/dist/plugins/codex/src/state.js +1 -1
- package/dist/plugins/dsh/tools.js +1 -1
- package/dist/plugins/pi/boot.d.ts +1 -1
- package/dist/plugins/pi/boot.js +2 -3
- package/dist/plugins/pi/budget.d.ts +1 -1
- package/dist/plugins/pi/budget.js +1 -1
- package/dist/plugins/pi/render.d.ts +1 -1
- package/dist/plugins/pi/render.js +20 -11
- package/dist/plugins/pi/runtime.js +6 -2
- package/dist/plugins/pi/tool-result.d.ts +2 -1
- package/dist/plugins/pi/window.js +24 -1
- package/dist/src/boot/render.d.ts +3 -4
- package/dist/src/boot/render.js +23 -21
- package/dist/src/boot/text.d.ts +2 -5
- package/dist/src/boot/text.js +12 -9
- package/dist/src/budget/text.d.ts +1 -1
- package/dist/src/budget/text.js +1 -1
- package/dist/src/history/corpus.d.ts +1 -1
- package/dist/src/history/corpus.js +1 -1
- package/dist/src/history/history.d.ts +2 -2
- package/dist/src/history/history.js +5 -8
- package/dist/src/history/query.d.ts +11 -3
- package/dist/src/history/query.js +7 -11
- package/dist/src/index.d.ts +4 -3
- package/dist/src/index.js +1 -1
- package/dist/src/notes/constants.d.ts +1 -1
- package/dist/src/notes/constants.js +1 -1
- package/dist/src/notes/errors.d.ts +1 -1
- package/dist/src/notes/frontmatter.d.ts +2 -1
- package/dist/src/notes/frontmatter.js +3 -1
- package/dist/src/notes/index.d.ts +1 -0
- package/dist/src/notes/index.js +1 -0
- package/dist/src/notes/policy.d.ts +16 -0
- package/dist/src/notes/policy.js +43 -0
- package/dist/src/notes/store.d.ts +8 -3
- package/dist/src/notes/store.js +64 -20
- package/dist/src/result.d.ts +21 -0
- package/dist/src/result.js +18 -0
- package/dist/src/text-match.d.ts +8 -0
- package/dist/src/text-match.js +34 -0
- package/dist/src/tools/dream.d.ts +9 -1
- package/dist/src/tools/dream.js +2 -1
- package/dist/src/tools/history.js +14 -5
- package/dist/src/tools/notes.d.ts +75 -13
- package/dist/src/tools/notes.js +58 -19
- package/dist/src/tools/output.d.ts +1 -3
- package/dist/src/tools/output.js +1 -19
- package/dist/src/tools/result.d.ts +2 -20
- package/dist/src/tools/result.js +4 -18
- package/dist/src/tools/schema.d.ts +3 -7
- package/dist/src/tools/schema.js +10 -16
- package/dist/test/agent-loop.test.js +78 -6
- package/dist/test/boot.integration.test.js +30 -3
- package/dist/test/claude-mod.test.js +7 -6
- package/dist/test/codex-history.test.js +2 -2
- package/dist/test/codex-plugin.test.js +2 -0
- package/dist/test/dependencies.test.js +38 -3
- package/dist/test/dsh.test.js +1 -1
- package/dist/test/helpers/dependency-graph.js +12 -6
- package/dist/test/helpers/extension.d.ts +2 -1
- package/dist/test/history.integration.test.js +47 -1
- package/dist/test/host-neutral.test.js +4 -3
- package/dist/test/model-facing-text.test.js +20 -16
- package/dist/test/note-policy.test.d.ts +1 -0
- package/dist/test/note-policy.test.js +227 -0
- package/dist/test/notes-query-namespaces.test.js +7 -3
- package/dist/test/notes.integration.test.js +10 -10
- package/dist/test/notes.test.js +4 -4
- package/dist/test/pi-render.test.js +28 -1
- package/dist/test/project-namespace.test.js +1 -1
- package/docs/architecture.md +10 -7
- package/docs/dsh.md +1 -1
- package/docs/notes-library.md +20 -7
- package/docs/reset-lifecycle.md +2 -2
- package/docs/tool-results.md +3 -1
- package/package.json +12 -12
- package/playbook.md +1 -1
- package/plugins/claude/.claude-plugin/plugin.json +1 -1
- package/plugins/claude/dist/claude/helper.js +528 -422
- package/plugins/claude/hooks/register.ts +1 -10
- package/plugins/claude/playbook.md +1 -1
- package/plugins/claude/skills/dream/SKILL.md +1 -1
- package/plugins/claude/skills/memory/SKILL.md +1 -1
- package/plugins/claude/src/helper.ts +2 -11
- package/plugins/claude/src/thresholds.ts +5 -15
- package/plugins/codex/dist/codex/notesoup.js +520 -403
- package/plugins/codex/src/mcp.ts +5 -12
- package/plugins/codex/src/state.ts +1 -1
- package/plugins/dsh/tools.ts +2 -1
- package/plugins/pi/boot.ts +3 -4
- package/plugins/pi/budget.ts +1 -1
- package/plugins/pi/render.ts +20 -8
- package/plugins/pi/runtime.ts +6 -2
- package/plugins/pi/tool-result.ts +2 -1
- package/plugins/pi/window.ts +20 -1
- package/skills/dream/SKILL.md +1 -1
- package/skills/memory/SKILL.md +1 -1
- package/src/boot/render.ts +24 -21
- package/src/boot/text.ts +12 -9
- package/src/budget/text.ts +1 -1
- package/src/history/corpus.ts +1 -1
- package/src/history/history.ts +5 -6
- package/src/history/query.ts +11 -14
- package/src/index.ts +5 -2
- package/src/notes/constants.ts +1 -1
- package/src/notes/errors.ts +1 -1
- package/src/notes/frontmatter.ts +4 -2
- package/src/notes/index.ts +1 -0
- package/src/notes/policy.ts +49 -0
- package/src/notes/store.ts +66 -26
- package/src/result.ts +26 -0
- package/src/text-match.ts +32 -0
- package/src/tools/dream.ts +2 -1
- package/src/tools/history.ts +15 -6
- package/src/tools/notes.ts +60 -20
- package/src/tools/output.ts +1 -17
- package/src/tools/result.ts +4 -26
- package/src/tools/schema.ts +11 -17
- package/dist/plugins/codex/src/history.d.ts +0 -3
- package/dist/plugins/codex/src/history.js +0 -2
- package/dist/plugins/codex/src/transcript.d.ts +0 -3
- package/dist/plugins/codex/src/transcript.js +0 -2
- package/plugins/codex/src/history.ts +0 -3
- package/plugins/codex/src/transcript.ts +0 -3
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import { NoteError } from "./errors.js";
|
|
2
|
+
|
|
3
|
+
export type NotePolicyFields = { pinned?: boolean; budget?: number; readonly?: boolean };
|
|
4
|
+
export type NotePolicy = Required<NotePolicyFields>;
|
|
5
|
+
export const DEFAULT_NOTE_BUDGET = 2048;
|
|
6
|
+
export const MAX_PINNED_NOTES = 5;
|
|
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;
|
|
9
|
+
|
|
10
|
+
export function validateNotePolicy(fields: NotePolicyFields): void {
|
|
11
|
+
for (const key of ["pinned", "readonly"] as const) {
|
|
12
|
+
if (fields[key] !== undefined && typeof fields[key] !== "boolean") throw new NoteError("invalid_policy", `${key} must be a boolean.`);
|
|
13
|
+
}
|
|
14
|
+
if (fields.budget !== undefined && (!Number.isSafeInteger(fields.budget) || fields.budget <= 0)) {
|
|
15
|
+
throw new NoteError("invalid_policy", "budget must be a positive safe integer of Unicode code points.");
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/** Only root default pages are pinned implicitly; an explicit false always wins. */
|
|
20
|
+
export function effectiveNotePolicy(fields: NotePolicyFields, path: string): NotePolicy {
|
|
21
|
+
validateNotePolicy(fields);
|
|
22
|
+
return {
|
|
23
|
+
pinned: fields.pinned ?? DEFAULT_PINNED_PAGES.some(page => page === path),
|
|
24
|
+
budget: fields.budget ?? DEFAULT_NOTE_BUDGET,
|
|
25
|
+
readonly: fields.readonly ?? false,
|
|
26
|
+
};
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export function pinnedPageOrder(path: string): number {
|
|
30
|
+
const index = DEFAULT_PINNED_PAGES.findIndex(page => page === path);
|
|
31
|
+
return index === -1 ? DEFAULT_PINNED_PAGES.length : index;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export function noteBudgetWarnings(body: string, policy: NotePolicy): string[] {
|
|
35
|
+
const count = Array.from(body).length;
|
|
36
|
+
return count > policy.budget ? [`Warning: note body is ${count} Unicode code points, over budget ${policy.budget}; the full body is kept.`] : [];
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export function assertNoteUnlocked(fields: NotePolicyFields, unlock?: boolean): void {
|
|
40
|
+
if (fields.readonly === true && unlock !== false) throw new NoteError("readonly", "This note has a soft readonly lock; explicitly set readonly:false to unlock before changing it (or in the same call).");
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** Apply only explicit values, leaving absent on-disk defaults absent across moves. */
|
|
44
|
+
export function applyNotePolicy(target: NotePolicyFields, fields: NotePolicyFields): void {
|
|
45
|
+
validateNotePolicy(fields);
|
|
46
|
+
for (const key of ["pinned", "budget", "readonly"] as const) {
|
|
47
|
+
if (fields[key] !== undefined) Object.assign(target, { [key]: fields[key] });
|
|
48
|
+
}
|
|
49
|
+
}
|
package/src/notes/store.ts
CHANGED
|
@@ -11,6 +11,7 @@ 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
13
|
import { projectReceipt, type ProjectReceipt } from "./project-namespace.js";
|
|
14
|
+
import { applyNotePolicy, assertNoteUnlocked, effectiveNotePolicy, MAX_PINNED_NOTES, noteBudgetWarnings, validateNotePolicy, type NotePolicyFields } from "./policy.js";
|
|
14
15
|
|
|
15
16
|
export type { NoteMeta, Origin, Scope };
|
|
16
17
|
|
|
@@ -24,22 +25,22 @@ function writeStamp(): number {
|
|
|
24
25
|
return lastWriteStamp;
|
|
25
26
|
}
|
|
26
27
|
export type NoteMatch = { line: number; text: string; /** Code-point offset into the note body, not into the serialized file. */ offsetChars: number };
|
|
27
|
-
export type NoteSearchRow = { address: string; scope: Scope; path: string; meta: NoteMeta; matches: NoteMatch[] };
|
|
28
|
+
export type NoteSearchRow = { address: string; scope: Scope; path: string; meta: NoteMeta; warnings: string[]; matches: NoteMatch[] };
|
|
28
29
|
export type EditOperation = { oldText: string; newText: string };
|
|
29
|
-
export type WriteOptions = { origin?: Origin };
|
|
30
|
-
export type EditOptions = { origin?: Origin; crumpled?: boolean; replaceAll?: boolean; renameTo?: string };
|
|
30
|
+
export type WriteOptions = NotePolicyFields & { origin?: Origin };
|
|
31
|
+
export type EditOptions = NotePolicyFields & { origin?: Origin; crumpled?: boolean; replaceAll?: boolean; renameTo?: string };
|
|
31
32
|
/** Omitted/null/empty glob or bare @default selects current notebooks; explicit globs match full addresses.
|
|
32
|
-
*
|
|
33
|
+
* A pattern without `@` or `/` matches filenames at any depth; relative paths with `/` match the current session.
|
|
33
34
|
*/
|
|
34
35
|
export type NotesQuery = { glob?: string | null; crumpled?: boolean };
|
|
35
36
|
/** A read exposes metadata and the pure body; the serialized frontmatter is never part of the body. */
|
|
36
37
|
export type NoteReadResult = { meta: NoteMeta; body: string; resolvedScope: Scope };
|
|
37
|
-
export type NoteWriteResult = { meta: NoteMeta; outcome: "created" | "overwrote" | "uncrumpled" };
|
|
38
|
+
export type NoteWriteResult = { meta: NoteMeta; warnings: string[]; outcome: "created" | "overwrote" | "uncrumpled" };
|
|
38
39
|
export type NoteChange =
|
|
39
40
|
| { kind: "none"; before: ""; after: "" }
|
|
40
41
|
| { kind: "body" | "metadata"; before: string; after: string };
|
|
41
|
-
export type NoteEditResult = { meta: NoteMeta; applied: number; resolvedScope: Scope; change: NoteChange; moved: boolean; replacedCrumpledTarget: boolean };
|
|
42
|
-
export type NoteRenameResult = { meta: NoteMeta; replacedCrumpledTarget: boolean };
|
|
42
|
+
export type NoteEditResult = { meta: NoteMeta; warnings: string[]; applied: number; resolvedScope: Scope; change: NoteChange; moved: boolean; replacedCrumpledTarget: boolean };
|
|
43
|
+
export type NoteRenameResult = { meta: NoteMeta; warnings: string[]; replacedCrumpledTarget: boolean };
|
|
43
44
|
/** A notebook, or one unreadable note inside it, that a status-reporting query could not read. */
|
|
44
45
|
export type NoteQueryStatus = { namespacesUnavailable: string[] };
|
|
45
46
|
export type NoteQueryResult<T> = { rows: T[]; status: NoteQueryStatus };
|
|
@@ -84,6 +85,15 @@ function withPathQueue<T>(path: string, operation: () => Promise<T>): Promise<T>
|
|
|
84
85
|
return result;
|
|
85
86
|
}
|
|
86
87
|
|
|
88
|
+
/** Lock each path once in stable order. Mutations acquire notebook keys before file keys;
|
|
89
|
+
* readers take only file keys; admission scans read atomic files without waiting on readers.
|
|
90
|
+
*/
|
|
91
|
+
function withPathQueues<T>(paths: string[], operation: () => Promise<T>): Promise<T> {
|
|
92
|
+
const keys = [...new Set(paths.map(path => resolve(path)))].sort();
|
|
93
|
+
const lock = (index: number): Promise<T> => index === keys.length ? operation() : withPathQueue(keys[index]!, () => lock(index + 1));
|
|
94
|
+
return lock(0);
|
|
95
|
+
}
|
|
96
|
+
|
|
87
97
|
function errno(error: unknown): string | undefined {
|
|
88
98
|
return typeof error === "object" && error !== null ? (error as NodeJS.ErrnoException).code : undefined;
|
|
89
99
|
}
|
|
@@ -165,9 +175,10 @@ async function namespacesForPattern(pattern: string | undefined, identity: Notes
|
|
|
165
175
|
return namespaces;
|
|
166
176
|
}
|
|
167
177
|
|
|
168
|
-
/** Relative pattern heads resolve to canonical names
|
|
178
|
+
/** Relative pattern heads resolve to canonical names; slashless bare patterns match filenames at any depth. */
|
|
169
179
|
function normalizePattern(pattern: string | undefined, identity: NotesIdentity): string | undefined {
|
|
170
180
|
if (!pattern) return pattern;
|
|
181
|
+
if (!pattern.startsWith("@") && !pattern.includes("/")) return `**/${pattern}`;
|
|
171
182
|
if (pattern.startsWith("@project/")) return `@projects/${identity.projectKey}/${pattern.slice("@project/".length)}`;
|
|
172
183
|
if (pattern.startsWith("@self/")) return `@agents/${identity.agent}/${pattern.slice("@self/".length)}`;
|
|
173
184
|
if (pattern.startsWith("@model/")) return `@models/${identity.model}/${pattern.slice("@model/".length)}`;
|
|
@@ -242,6 +253,7 @@ function assertWritablePath(vpath: string): void {
|
|
|
242
253
|
|
|
243
254
|
/** Rounded up, so a note just over the limit never reads as exactly at it. */
|
|
244
255
|
function megabytes(bytes: number): string {
|
|
256
|
+
if (bytes < 1_000_000) return `${Math.ceil(bytes / 1_000)} KB`;
|
|
245
257
|
return `${Math.ceil(bytes / 10_000) / 100} MB`;
|
|
246
258
|
}
|
|
247
259
|
|
|
@@ -284,8 +296,22 @@ function assertDreamNote(scope: Scope, who: string | undefined, identity: NotesI
|
|
|
284
296
|
export function createNotesStore(input: NotesIdentity): NotesStore {
|
|
285
297
|
const identity = snapshotNotesIdentity(input);
|
|
286
298
|
|
|
299
|
+
/** Only admission of a new live pin needs a count; existing over-cap notebooks can still be repaired. */
|
|
300
|
+
async function assertPinAdmission(root: string, path: string, meta: NoteMeta, previous?: NoteMeta, source?: { root: string; path: string; meta: NoteMeta }): Promise<void> {
|
|
301
|
+
const livePin = (value: NoteMeta | undefined, name: string) => value !== undefined && value.crumpledAt === undefined && effectiveNotePolicy(value, name).pinned;
|
|
302
|
+
if (!livePin(meta, path) || livePin(previous, path)) return;
|
|
303
|
+
if (source?.root === root && livePin(source.meta, source.path)) return;
|
|
304
|
+
let count = 0;
|
|
305
|
+
for (const name of await walkMarkdown(root)) {
|
|
306
|
+
const raw = await readFileIfExists(join(root, name));
|
|
307
|
+
if (raw !== undefined && livePin(parseNote(raw).meta, name)) count++;
|
|
308
|
+
}
|
|
309
|
+
if (count >= MAX_PINNED_NOTES) throw new NoteError("pin_limit", `This notebook already has ${count} live pinned notes; the limit is ${MAX_PINNED_NOTES}. Unpin or crumple one first. Nothing was saved.`);
|
|
310
|
+
}
|
|
311
|
+
|
|
287
312
|
async function write(address: string, content: string, options: WriteOptions = {}): Promise<NoteWriteResult> {
|
|
288
313
|
const stableOptions = { ...options };
|
|
314
|
+
validateNotePolicy(stableOptions);
|
|
289
315
|
const destination = assertAddress(address);
|
|
290
316
|
assertWritablePath(destination.path);
|
|
291
317
|
const scope = destination.scope;
|
|
@@ -294,12 +320,15 @@ export function createNotesStore(input: NotesIdentity): NotesStore {
|
|
|
294
320
|
// re-attribute a user-written note to the agent that happened to rewrite it.
|
|
295
321
|
const origin = stableOptions.origin === undefined ? undefined : assertOrigin(stableOptions.origin);
|
|
296
322
|
const path = physicalPath(scope, destination.path, identity, destination.who);
|
|
297
|
-
|
|
323
|
+
const root = scopeDir(scope, identity, destination.who);
|
|
324
|
+
return withPathQueues([root], () => withPathQueue(path, async () => {
|
|
298
325
|
const now = writeStamp();
|
|
299
326
|
const cleanBody = stripLeadingFrontmatter(content);
|
|
300
327
|
const existingRaw = await readFileIfExists(path);
|
|
301
328
|
assertDreamNote(scope, destination.who, identity, existingRaw, address);
|
|
302
329
|
const existing = existingRaw === undefined ? undefined : parseNote(existingRaw, now).meta;
|
|
330
|
+
if (existing) assertNoteUnlocked(existing, stableOptions.readonly);
|
|
331
|
+
const previous = existing === undefined ? undefined : { ...existing };
|
|
303
332
|
const outcome = existing === undefined ? "created" : existing.crumpledAt === undefined ? "overwrote" : "uncrumpled";
|
|
304
333
|
const meta: NoteMeta = existing ?? {
|
|
305
334
|
scope,
|
|
@@ -311,14 +340,16 @@ export function createNotesStore(input: NotesIdentity): NotesStore {
|
|
|
311
340
|
...(scope === "session" ? { project: identity.projectKey } : {}),
|
|
312
341
|
};
|
|
313
342
|
meta.scope = scope;
|
|
343
|
+
applyNotePolicy(meta, stableOptions);
|
|
314
344
|
if (origin !== undefined) meta.origin = origin;
|
|
315
345
|
delete meta.crumpledAt;
|
|
316
346
|
meta.updatedAt = now;
|
|
317
347
|
const serialized = serializeNote(meta, cleanBody);
|
|
318
348
|
assertSerializedSize(serialized);
|
|
349
|
+
await assertPinAdmission(root, noteFileName(destination.path), meta, previous);
|
|
319
350
|
await atomicWrite(path, serialized);
|
|
320
|
-
return { meta, outcome };
|
|
321
|
-
});
|
|
351
|
+
return { meta, outcome, warnings: noteBudgetWarnings(cleanBody, effectiveNotePolicy(meta, noteFileName(destination.path))) };
|
|
352
|
+
}));
|
|
322
353
|
}
|
|
323
354
|
|
|
324
355
|
async function read(address: string): Promise<NoteReadResult | undefined> {
|
|
@@ -342,18 +373,21 @@ export function createNotesStore(input: NotesIdentity): NotesStore {
|
|
|
342
373
|
async function update(address: string, edits?: EditOperation[], options: EditOptions = {}): Promise<NoteEditResult> {
|
|
343
374
|
const operations = edits === undefined ? [] : edits.map((operation) => ({ ...operation }));
|
|
344
375
|
const stableOptions = { ...options };
|
|
376
|
+
validateNotePolicy(stableOptions);
|
|
345
377
|
const from = assertAddress(address);
|
|
346
378
|
const destination = stableOptions.renameTo === undefined ? from : assertAddress(stableOptions.renameTo);
|
|
347
379
|
assertWritablePath(destination.path);
|
|
348
380
|
const scope = destination.scope;
|
|
349
381
|
assertWritableNamespace(from.scope, from.who, identity);
|
|
350
382
|
assertWritableNamespace(scope, destination.who, identity);
|
|
351
|
-
if (operations.length === 0 && stableOptions.origin === undefined && stableOptions.crumpled === undefined && stableOptions.renameTo === undefined) {
|
|
352
|
-
throw new NoteError("nothing_to_do", "Nothing to change: provide edits, an origin, a crumpled state, or a new address.");
|
|
383
|
+
if (operations.length === 0 && stableOptions.origin === undefined && stableOptions.crumpled === undefined && stableOptions.renameTo === undefined && stableOptions.pinned === undefined && stableOptions.budget === undefined && stableOptions.readonly === undefined) {
|
|
384
|
+
throw new NoteError("nothing_to_do", "Nothing to change: provide edits, policy, an origin, a crumpled state, or a new address.");
|
|
353
385
|
}
|
|
354
386
|
const fromPath = physicalPath(from.scope, from.path, identity, from.who);
|
|
355
387
|
const path = physicalPath(scope, destination.path, identity, destination.who);
|
|
356
388
|
const differentPaths = resolve(fromPath) !== resolve(path);
|
|
389
|
+
const fromRoot = scopeDir(from.scope, identity, from.who);
|
|
390
|
+
const root = scopeDir(scope, identity, destination.who);
|
|
357
391
|
const mutate = async (): Promise<NoteEditResult> => {
|
|
358
392
|
const raw = await readFileIfExists(fromPath);
|
|
359
393
|
if (raw === undefined) throw new NoteError("not_found", `No note at ${noteIdentity(identity, address).address}.`);
|
|
@@ -368,7 +402,11 @@ export function createNotesStore(input: NotesIdentity): NotesStore {
|
|
|
368
402
|
throw new NoteError("already_exists", `${noteIdentity(identity, stableOptions.renameTo!).address} already holds a note; crumple it first or pick another address.`);
|
|
369
403
|
}
|
|
370
404
|
const { meta, body } = parseNote(raw);
|
|
405
|
+
assertNoteUnlocked(meta, stableOptions.readonly);
|
|
406
|
+
// Replacing a locked crumpled target also needs an explicit unlock.
|
|
407
|
+
if (moved && targetRaw !== undefined) assertNoteUnlocked(parseNote(targetRaw).meta, stableOptions.readonly);
|
|
371
408
|
const beforeMeta: NoteMeta = { ...meta };
|
|
409
|
+
applyNotePolicy(meta, stableOptions);
|
|
372
410
|
meta.scope = scope;
|
|
373
411
|
if (from.scope !== "session" && scope === "session") meta.project = identity.projectKey;
|
|
374
412
|
if (from.scope === "session" && scope !== "session") delete meta.project;
|
|
@@ -397,10 +435,11 @@ export function createNotesStore(input: NotesIdentity): NotesStore {
|
|
|
397
435
|
if (stableOptions.crumpled === false) delete meta.crumpledAt;
|
|
398
436
|
const bodyChanged = body !== next;
|
|
399
437
|
const originChanged = beforeMeta.origin !== meta.origin;
|
|
400
|
-
|
|
438
|
+
const policyChanged = beforeMeta.pinned !== meta.pinned || beforeMeta.budget !== meta.budget || beforeMeta.readonly !== meta.readonly;
|
|
439
|
+
if (bodyChanged || originChanged || policyChanged || moved) meta.updatedAt = writeStamp();
|
|
401
440
|
const serialized = serializeNote(meta, next);
|
|
402
441
|
assertSerializedSize(serialized);
|
|
403
|
-
const metadataChanged = originChanged || beforeMeta.crumpledAt !== meta.crumpledAt;
|
|
442
|
+
const metadataChanged = originChanged || policyChanged || beforeMeta.crumpledAt !== meta.crumpledAt;
|
|
404
443
|
let change: NoteChange;
|
|
405
444
|
// A body edit that also rewrites frontmatter is still a body change; its diff inputs span the
|
|
406
445
|
// whole serialized file, so the frontmatter part stays visible in the diff.
|
|
@@ -408,20 +447,19 @@ export function createNotesStore(input: NotesIdentity): NotesStore {
|
|
|
408
447
|
else if (bodyChanged) change = { kind: "body", before: body, after: next };
|
|
409
448
|
else if (metadataChanged) change = { kind: "metadata", before: frontmatterOf(beforeMeta), after: frontmatterOf(meta) };
|
|
410
449
|
else change = { kind: "none", before: "", after: "" };
|
|
450
|
+
await assertPinAdmission(root, noteFileName(destination.path), meta, moved ? targetRaw === undefined ? undefined : parseNote(targetRaw).meta : beforeMeta,
|
|
451
|
+
moved ? { root: fromRoot, path: noteFileName(from.path), meta: beforeMeta } : undefined);
|
|
411
452
|
await atomicWrite(sameFile ? sourceReal! : path, serialized);
|
|
412
453
|
if (moved) await rm(fromPath, { force: true });
|
|
413
|
-
return { meta, applied, resolvedScope: scope, change, moved, replacedCrumpledTarget: moved && targetRaw !== undefined };
|
|
454
|
+
return { meta, warnings: noteBudgetWarnings(next, effectiveNotePolicy(meta, noteFileName(destination.path))), applied, resolvedScope: scope, change, moved, replacedCrumpledTarget: moved && targetRaw !== undefined };
|
|
414
455
|
};
|
|
415
|
-
|
|
416
|
-
if (!differentPaths) return withPathQueue(path, mutate);
|
|
417
|
-
const [first, second] = [fromPath, path].sort();
|
|
418
|
-
return withPathQueue(first!, () => withPathQueue(second!, mutate));
|
|
456
|
+
return withPathQueues([fromRoot, root], () => withPathQueues([fromPath, path], mutate));
|
|
419
457
|
}
|
|
420
458
|
|
|
421
459
|
/** Moving alone shares validation and persistence with a combined edit-and-move. */
|
|
422
460
|
async function rename(fromAddress: string, toAddress: string): Promise<NoteRenameResult> {
|
|
423
|
-
const { meta, replacedCrumpledTarget } = await update(fromAddress, undefined, { renameTo: toAddress });
|
|
424
|
-
return { meta, replacedCrumpledTarget };
|
|
461
|
+
const { meta, warnings, replacedCrumpledTarget } = await update(fromAddress, undefined, { renameTo: toAddress });
|
|
462
|
+
return { meta, warnings, replacedCrumpledTarget };
|
|
425
463
|
}
|
|
426
464
|
|
|
427
465
|
async function forget(address: string): Promise<NoteMeta> {
|
|
@@ -429,15 +467,16 @@ export function createNotesStore(input: NotesIdentity): NotesStore {
|
|
|
429
467
|
const target = assertAddress(address);
|
|
430
468
|
assertWritableNamespace(target.scope, target.who, identity);
|
|
431
469
|
const path = physicalPath(target.scope, target.path, identity, target.who);
|
|
432
|
-
return withPathQueue(path, async () => {
|
|
470
|
+
return withPathQueues([scopeDir(target.scope, identity, target.who)], () => withPathQueue(path, async () => {
|
|
433
471
|
const raw = await readFileIfExists(path);
|
|
434
472
|
if (raw === undefined) throw new NoteError("not_found", `No note at ${noteIdentity(identity, address).address}.`);
|
|
435
473
|
assertDreamNote(target.scope, target.who, identity, raw, address);
|
|
436
474
|
const { meta } = parseNote(raw);
|
|
475
|
+
assertNoteUnlocked(meta);
|
|
437
476
|
if (meta.crumpledAt === undefined) throw new NoteError("not_crumpled", `${noteIdentity(identity, address).address} isn't crumpled; crumple it before deleting.`);
|
|
438
477
|
await unlink(path);
|
|
439
478
|
return { ...meta, scope: target.scope };
|
|
440
|
-
});
|
|
479
|
+
}));
|
|
441
480
|
}
|
|
442
481
|
|
|
443
482
|
async function* scan(options: NotesQuery, status?: NoteQueryStatus): AsyncGenerator<Omit<NoteRow, "sizeBytes">> {
|
|
@@ -507,8 +546,9 @@ export function createNotesStore(input: NotesIdentity): NotesStore {
|
|
|
507
546
|
const rows: NoteSearchRow[] = [];
|
|
508
547
|
for await (const note of scan(stableOptions, status)) {
|
|
509
548
|
const { address, path, scope, meta, body } = note;
|
|
549
|
+
const warnings = noteBudgetWarnings(body, effectiveNotePolicy(meta, path));
|
|
510
550
|
if (stableQueries.length === 0) {
|
|
511
|
-
rows.push({ address, path, scope, meta, matches: [] });
|
|
551
|
+
rows.push({ address, path, scope, meta, warnings, matches: [] });
|
|
512
552
|
continue;
|
|
513
553
|
}
|
|
514
554
|
// Offsets address the note body alone: no frontmatter length is predicted, so an
|
|
@@ -522,7 +562,7 @@ export function createNotesStore(input: NotesIdentity): NotesStore {
|
|
|
522
562
|
}
|
|
523
563
|
baseChars += Array.from(line).length + 1;
|
|
524
564
|
}
|
|
525
|
-
if (matches.length > 0) rows.push({ address, path, scope, meta, matches });
|
|
565
|
+
if (matches.length > 0) rows.push({ address, path, scope, meta, warnings, matches });
|
|
526
566
|
}
|
|
527
567
|
rows.sort((a, b) => a.address.localeCompare(b.address));
|
|
528
568
|
return { rows, status: status ?? { namespacesUnavailable: [] } };
|
package/src/result.ts
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
/** Shared outcomes and bounded refusals, independent of tool transport and output budgets. */
|
|
2
|
+
import { Type, type Static } from "typebox";
|
|
3
|
+
|
|
4
|
+
/** The one refusal shape: `code` is a stable internal identifier, `message` the bounded reading. */
|
|
5
|
+
export const OperationErrorSchema = Type.Object({
|
|
6
|
+
code: Type.String(),
|
|
7
|
+
message: Type.String(),
|
|
8
|
+
}, { additionalProperties: false });
|
|
9
|
+
export type OperationError = Static<typeof OperationErrorSchema>;
|
|
10
|
+
|
|
11
|
+
/** `data` exists without `error`, never both, never neither. */
|
|
12
|
+
export type Outcome<T> = { ok: true; data: T } | { ok: false; error: OperationError };
|
|
13
|
+
|
|
14
|
+
export function success<T>(data: T): Outcome<T> {
|
|
15
|
+
return { ok: true, data };
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/** A code is an internal stable identifier and is never clipped; the dynamic message is the bounded surface. */
|
|
19
|
+
export const ERROR_MESSAGE_MAX_CHARS = 2000;
|
|
20
|
+
|
|
21
|
+
/** Bounded refusal: a runaway message is clipped with a marker instead of filling the wire. */
|
|
22
|
+
export function failure(code: string, message: string): Outcome<never> {
|
|
23
|
+
const chars = Array.from(message);
|
|
24
|
+
const bounded = chars.length <= ERROR_MESSAGE_MAX_CHARS ? message : `${chars.slice(0, ERROR_MESSAGE_MAX_CHARS).join("")}…[truncated ${chars.length - ERROR_MESSAGE_MAX_CHARS} chars]`;
|
|
25
|
+
return { ok: false, error: { code, message: bounded } };
|
|
26
|
+
}
|
package/src/text-match.ts
CHANGED
|
@@ -1,3 +1,35 @@
|
|
|
1
|
+
/** Expected search-query refusal, distinct from any other Error an operation may raise. */
|
|
2
|
+
export class InvalidQueryError extends Error {
|
|
3
|
+
constructor(message: string) {
|
|
4
|
+
super(message);
|
|
5
|
+
this.name = "InvalidQueryError";
|
|
6
|
+
}
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
/** Missing/empty queries disable filtering; empty list entries are ignored, not OR wildcards. */
|
|
10
|
+
export function searchQueries(query: unknown): string[] {
|
|
11
|
+
const candidates = query === undefined ? [] : typeof query === "string" ? [query] : query;
|
|
12
|
+
if (!Array.isArray(candidates)) throw new InvalidQueryError("`query` must be a string or a list of strings.");
|
|
13
|
+
if (!candidates.every((candidate) => typeof candidate === "string")) throw new InvalidQueryError("Every item in the `query` list must be a string.");
|
|
14
|
+
return candidates.filter((candidate) => candidate !== "") as string[];
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/** Longest fitting code-point prefix, without inserted markers. Callers report omissions. */
|
|
18
|
+
export function prefixFit(text: string, fits: (content: string) => boolean): string {
|
|
19
|
+
if (fits(text)) return text;
|
|
20
|
+
const chars = Array.from(text);
|
|
21
|
+
// Serialized size is non-decreasing in the kept count, so the largest fitting prefix is
|
|
22
|
+
// found by a monotone binary search instead of a quadratic shrink loop.
|
|
23
|
+
let low = 0;
|
|
24
|
+
let high = chars.length;
|
|
25
|
+
while (low < high) {
|
|
26
|
+
const mid = Math.ceil((low + high) / 2);
|
|
27
|
+
if (fits(chars.slice(0, mid).join(""))) low = mid;
|
|
28
|
+
else high = mid - 1;
|
|
29
|
+
}
|
|
30
|
+
return chars.slice(0, low).join("");
|
|
31
|
+
}
|
|
32
|
+
|
|
1
33
|
/**
|
|
2
34
|
* Code-point offset of the earliest case-insensitive literal match, or -1 when
|
|
3
35
|
* none occurs. Match against the original text so Unicode casing cannot shift offsets.
|
package/src/tools/dream.ts
CHANGED
|
@@ -5,7 +5,8 @@ import { createNotesStore, noteIdentity, type NoteRow, type NotesIdentity } from
|
|
|
5
5
|
import { projectNamespaces } from "../notes/project-namespace.js";
|
|
6
6
|
import { gitCommit } from "../dream/git.js";
|
|
7
7
|
import { acquireDreamLock, dreamLockPath, releaseDreamLock, type DreamLock } from "../dream/lock.js";
|
|
8
|
-
import { failure,
|
|
8
|
+
import { failure, success, type Outcome } from "../result.js";
|
|
9
|
+
import { renderOutcome, resultSchema } from "./result.js";
|
|
9
10
|
import { failureOf, listedFile, ListedFileSchema, NoteIdentitySchema, renderListData, snapshot, SnapshotSchema } from "./notes.js";
|
|
10
11
|
|
|
11
12
|
/** The one open dream per session; the host owns where it lives. */
|
package/src/tools/history.ts
CHANGED
|
@@ -1,9 +1,10 @@
|
|
|
1
1
|
/** Host-neutral history operations: one bounded payload for text and structured results. */
|
|
2
2
|
import { Type, type Static } from "typebox";
|
|
3
|
-
import { HISTORY_PREVIEW_CHARS, MAX_READ_WINDOW_CHARS } from "./output.js";
|
|
4
|
-
import { failure,
|
|
3
|
+
import { HISTORY_PREVIEW_CHARS, MAX_READ_WINDOW_CHARS, TOOL_OUTPUT_LIMIT } from "./output.js";
|
|
4
|
+
import { failure, success, type Outcome } from "../result.js";
|
|
5
|
+
import { fitsResult, resultSchema, readTextWindow, renderOutcome, renderTextWindow, TextWindowRequestSchema, TextWindowSchema, type Operation } from "./result.js";
|
|
5
6
|
import { historyRoles, searchQuery } from "./schema.js";
|
|
6
|
-
import { HistoryPageSchema, CorpusCollector, corpusSelection, isMultiPage, markMultiPage, selectPage, type HistoryPage } from "../history/query.js";
|
|
7
|
+
import { HistoryPageSchema, CorpusCollector, corpusSelection, isMultiPage, markMultiPage, selectPage, type HistoryPage, type HistoryPageResult } from "../history/query.js";
|
|
7
8
|
import { currentHistory, loadHistoryRepresentative, loadHistorySession, matchesSession, parseSessionSelector, resolveSession, sessionIdentity, type HistoryContext } from "../history/corpus.js";
|
|
8
9
|
import { allItems, eventDocument, nestedCallSummary, toolSummary, HistoryRoleSchema, NestedCallSummarySchema, ToolSummarySchema, type HistoryFoldedRow, type HistoryPageItem } from "../history/history.js";
|
|
9
10
|
|
|
@@ -81,6 +82,14 @@ function renderRead(data: HistoryReadData): string {
|
|
|
81
82
|
export type HistoryTextWrapper = (text: string) => string;
|
|
82
83
|
const plainText: HistoryTextWrapper = (text) => text;
|
|
83
84
|
|
|
85
|
+
/** Translate query budget facts into this tool's bounded refusal; successful pages are unchanged. */
|
|
86
|
+
function pageOutcome(result: HistoryPageResult): Outcome<HistoryPage> {
|
|
87
|
+
if (!("pageTooLarge" in result)) return result;
|
|
88
|
+
const { count, multi } = result.pageTooLarge;
|
|
89
|
+
const narrow = multi ? "narrow the session pattern, query, roles or `since`/`until`, or read one session/seq with `history_read`" : "narrow with `before_seq`/`after_seq` or `since`/`until`, pass `roles` to skip folding, or `history_read` one seq";
|
|
90
|
+
return failure("page_too_large", `Even trimmed to their shortest, these ${count} rows${multi ? "" : " and their folded runs"} fill the ${TOOL_OUTPUT_LIMIT} a call can carry; ${narrow}.`);
|
|
91
|
+
}
|
|
92
|
+
|
|
84
93
|
/* ------------------------------------------------------------------ history_list */
|
|
85
94
|
|
|
86
95
|
const sessionParameter = Type.Optional(Type.String({ minLength: 1, description: "(optional) Session ID or unique prefix, optionally pi:, claude:, codex:, or dsh:. Omit for this session. In history_list, * searches sessions with query or lists recent sessions without it; history_read needs one session." }));
|
|
@@ -108,7 +117,7 @@ export const historyList: Operation<typeof historyListParameters, HistoryPage, [
|
|
|
108
117
|
// Charge wrapped rendering, identities, notices and recipes, not only event previews.
|
|
109
118
|
const fits = (page: HistoryPage) => fitsResult(success(page), (result) => wrapText(renderOutcome(result, renderPage)));
|
|
110
119
|
const maxChars = params.max_chars_per_item ?? HISTORY_PREVIEW_CHARS;
|
|
111
|
-
if (params.session === undefined) return selectPage(await currentHistory(context), params, fits, maxChars);
|
|
120
|
+
if (params.session === undefined) return pageOutcome(selectPage(await currentHistory(context), params, fits, maxChars));
|
|
112
121
|
const selector = parseSessionSelector(params.session);
|
|
113
122
|
if (!selector.ok) return selector;
|
|
114
123
|
const corpus = "corpus" in context ? context.corpus : undefined;
|
|
@@ -137,7 +146,7 @@ export const historyList: Operation<typeof historyListParameters, HistoryPage, [
|
|
|
137
146
|
}
|
|
138
147
|
}
|
|
139
148
|
const notice = notices.length ? { notice: notices.join("") } : {};
|
|
140
|
-
const result = collector.page((page) => fits(markMultiPage({ ...page, ...notice })), maxChars, unvisited);
|
|
149
|
+
const result = pageOutcome(collector.page((page) => fits(markMultiPage({ ...page, ...notice })), maxChars, unvisited));
|
|
141
150
|
return result.ok ? success(markMultiPage({ ...result.data, ...notice })) : result;
|
|
142
151
|
}
|
|
143
152
|
const target = await resolveSession(corpus, selector.data);
|
|
@@ -145,7 +154,7 @@ export const historyList: Operation<typeof historyListParameters, HistoryPage, [
|
|
|
145
154
|
const loaded = await loadHistorySession(target.data);
|
|
146
155
|
if (!loaded.ok) return loaded;
|
|
147
156
|
const notice = loaded.data.notice === undefined ? {} : { notice: loaded.data.notice };
|
|
148
|
-
const result = selectPage(loaded.data.projection, { ...params, session: sessionIdentity(target.data) }, (page) => fits({ ...page, ...notice }), maxChars);
|
|
157
|
+
const result = pageOutcome(selectPage(loaded.data.projection, { ...params, session: sessionIdentity(target.data) }, (page) => fits({ ...page, ...notice }), maxChars));
|
|
149
158
|
return result.ok ? success({ ...result.data, ...notice }) : result;
|
|
150
159
|
},
|
|
151
160
|
render: (result) => renderOutcome(result, renderPage),
|