notesoup 0.41.0 → 0.43.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/dist/src/boot/render.js +11 -20
- package/dist/src/boot/snapshot.js +1 -6
- package/dist/src/boot/text.d.ts +12 -0
- package/dist/src/boot/text.js +15 -3
- package/dist/src/budget/parse.d.ts +14 -0
- package/dist/src/budget/parse.js +36 -0
- package/dist/src/budget/policy.js +2 -7
- package/dist/src/budget/text.d.ts +14 -0
- package/dist/src/budget/text.js +14 -0
- package/dist/src/claude/helper.js +24 -4
- package/dist/src/claude/thresholds.d.ts +39 -0
- package/dist/src/claude/thresholds.js +128 -0
- package/dist/src/dream/doctor.js +1 -1
- package/dist/src/dream/jail.js +10 -10
- package/dist/src/dream/lock.js +6 -13
- package/dist/src/dream/report.js +5 -15
- package/dist/src/history/history.js +5 -3
- package/dist/src/history/query.js +14 -26
- package/dist/src/notes/address.d.ts +1 -2
- package/dist/src/notes/address.js +14 -26
- package/dist/src/notes/errors.d.ts +2 -0
- package/dist/src/notes/errors.js +5 -0
- package/dist/src/notes/frontmatter.js +16 -2
- package/dist/src/notes/identity.js +0 -3
- package/dist/src/notes/paths.d.ts +11 -1
- package/dist/src/notes/paths.js +28 -7
- package/dist/src/notes/store.d.ts +1 -0
- package/dist/src/notes/store.js +54 -49
- package/dist/src/pi/boot.js +1 -5
- package/dist/src/pi/budget.d.ts +3 -3
- package/dist/src/pi/budget.js +11 -11
- package/dist/src/pi/dream/cli.js +43 -11
- package/dist/src/pi/estimate.d.ts +1 -5
- package/dist/src/pi/estimate.js +4 -4
- package/dist/src/pi/history.js +1 -4
- package/dist/src/pi/notes/adapter.d.ts +1 -1
- package/dist/src/pi/notes/adapter.js +2 -2
- package/dist/src/pi/reset/artifacts.d.ts +0 -2
- package/dist/src/pi/reset/artifacts.js +4 -4
- package/dist/src/pi/reset/committed.js +2 -2
- package/dist/src/pi/runtime.js +9 -6
- package/dist/src/pi/thresholds.js +5 -9
- package/dist/src/pi/tool-result.d.ts +1 -4
- package/dist/src/pi/tool-result.js +3 -3
- package/dist/src/pi/window.d.ts +5 -0
- package/dist/src/pi/window.js +7 -0
- package/dist/src/settings.d.ts +10 -0
- package/dist/src/settings.js +10 -4
- package/dist/src/tools/history.js +15 -18
- package/dist/src/tools/notes.d.ts +3 -7
- package/dist/src/tools/notes.js +18 -27
- package/dist/src/tools/output.d.ts +2 -3
- package/dist/src/tools/output.js +3 -9
- package/dist/src/tools/result.d.ts +1 -0
- package/dist/src/tools/result.js +15 -21
- package/dist/src/tools/schema.d.ts +0 -1
- package/dist/src/tools/schema.js +3 -4
- package/dist/test/agent-loop.test.js +1 -2
- package/dist/test/boot.integration.test.js +1 -1
- package/dist/test/claude-mod.test.js +425 -23
- package/dist/test/claude-validation.test.d.ts +1 -0
- package/dist/test/claude-validation.test.js +73 -0
- package/dist/test/dream-skill.test.js +2 -4
- package/dist/test/dream.test.js +17 -3
- package/dist/test/helpers/extension.js +1 -1
- package/dist/test/history.integration.test.js +9 -9
- package/dist/test/host-neutral.test.js +16 -1
- package/dist/test/notes-library.test.js +31 -2
- package/dist/test/notes.integration.test.js +11 -11
- package/dist/test/notes.test.js +40 -21
- package/dist/test/reset-lifecycle.test.js +1 -1
- package/docs/claude-code-mod.md +13 -3
- package/mods/notesoup/.claude-plugin/plugin.json +1 -1
- package/mods/notesoup/dist/claude/helper.js +285 -152
- package/mods/notesoup/hooks/register.ts +308 -51
- package/mods/notesoup/playbook.md +1 -1
- package/mods/notesoup/skills/dream/SKILL.md +1 -1
- package/mods/notesoup/skills/memory/SKILL.md +61 -0
- package/mods/pi-context/dist/claude/helper.js +9324 -0
- package/package.json +5 -3
- package/playbook.md +1 -1
- package/skills/dream/SKILL.md +1 -1
- package/skills/memory/SKILL.md +1 -1
- package/src/boot/render.ts +11 -21
- package/src/boot/snapshot.ts +2 -7
- package/src/boot/text.ts +21 -3
- package/src/budget/parse.ts +39 -0
- package/src/budget/policy.ts +2 -6
- package/src/budget/text.ts +20 -0
- package/src/claude/helper.ts +22 -5
- package/src/claude/thresholds.ts +153 -0
- package/src/dream/doctor.ts +1 -1
- package/src/dream/jail.ts +10 -10
- package/src/dream/lock.ts +3 -9
- package/src/dream/report.ts +5 -10
- package/src/history/history.ts +5 -3
- package/src/history/query.ts +14 -27
- package/src/notes/address.ts +13 -25
- package/src/notes/errors.ts +6 -0
- package/src/notes/frontmatter.ts +12 -2
- package/src/notes/identity.ts +0 -2
- package/src/notes/paths.ts +23 -5
- package/src/notes/store.ts +50 -48
- package/src/pi/boot.ts +1 -13
- package/src/pi/budget.ts +10 -11
- package/src/pi/dream/cli.ts +35 -10
- package/src/pi/estimate.ts +4 -4
- package/src/pi/history.ts +1 -5
- package/src/pi/notes/adapter.ts +2 -2
- package/src/pi/reset/artifacts.ts +4 -4
- package/src/pi/reset/committed.ts +2 -2
- package/src/pi/runtime.ts +8 -7
- package/src/pi/thresholds.ts +5 -11
- package/src/pi/tool-result.ts +3 -3
- package/src/pi/window.ts +8 -0
- package/src/settings.ts +22 -5
- package/src/tools/history.ts +15 -19
- package/src/tools/notes.ts +21 -32
- package/src/tools/output.ts +3 -12
- package/src/tools/result.ts +14 -19
- package/src/tools/schema.ts +3 -4
- package/dist/src/dream/playbook.d.ts +0 -1
- package/dist/src/dream/playbook.js +0 -2
- package/dist/src/pi/reset/text.d.ts +0 -5
- package/dist/src/pi/reset/text.js +0 -6
- package/src/dream/playbook.ts +0 -3
- package/src/pi/reset/text.ts +0 -10
package/dist/src/dream/report.js
CHANGED
|
@@ -5,20 +5,10 @@ import { errorMessage } from "../error-message.js";
|
|
|
5
5
|
function writeList(writes) {
|
|
6
6
|
return writes.length ? writes.map((w) => `- ${w.tool}: ${w.path}`).join("\n") : "- no changes";
|
|
7
7
|
}
|
|
8
|
-
/** Best-effort
|
|
9
|
-
function
|
|
8
|
+
/** Best-effort filesystem step; returns the failure message instead of throwing. */
|
|
9
|
+
function attempt(action) {
|
|
10
10
|
try {
|
|
11
|
-
|
|
12
|
-
writeFileSync(path, content);
|
|
13
|
-
return undefined;
|
|
14
|
-
}
|
|
15
|
-
catch (error) {
|
|
16
|
-
return errorMessage(error);
|
|
17
|
-
}
|
|
18
|
-
}
|
|
19
|
-
function appendText(path, content) {
|
|
20
|
-
try {
|
|
21
|
-
appendFileSync(path, content);
|
|
11
|
+
action();
|
|
22
12
|
return undefined;
|
|
23
13
|
}
|
|
24
14
|
catch (error) {
|
|
@@ -32,11 +22,11 @@ function appendText(path, content) {
|
|
|
32
22
|
*/
|
|
33
23
|
export function finishDream(home, stamp, reportPath, failed, body, writes) {
|
|
34
24
|
const header = failed ? `# Dream ${stamp} (failed)` : `# Dream ${stamp}`;
|
|
35
|
-
let reportError =
|
|
25
|
+
let reportError = attempt(() => { mkdirSync(dirname(reportPath), { recursive: true }); writeFileSync(reportPath, `${header}\n\n${body}\n\n${writeList(writes)}\n`); });
|
|
36
26
|
const audit = gitCommit(home, `dream ${stamp}${failed ? " (failed)" : ""}`);
|
|
37
27
|
if (!audit.ok) {
|
|
38
28
|
console.error(`dream: final audit failed: ${audit.error}`);
|
|
39
|
-
reportError ??=
|
|
29
|
+
reportError ??= attempt(() => appendFileSync(reportPath, `\n## Final audit failed\n\n${audit.error}\n`));
|
|
40
30
|
}
|
|
41
31
|
if (reportError)
|
|
42
32
|
console.error(`dream: could not write report at ${reportPath}: ${reportError}`);
|
|
@@ -161,14 +161,16 @@ export function visibleItem(event, maxChars, matchOffset) {
|
|
|
161
161
|
const document = eventDocument(event);
|
|
162
162
|
const chars = Array.from(document);
|
|
163
163
|
const start = matchOffset ?? 0;
|
|
164
|
-
|
|
164
|
+
// A negative budget would cut the tail and still call the result a prefix.
|
|
165
|
+
const limit = Math.max(0, maxChars);
|
|
166
|
+
const truncated = start > 0 || start + limit < chars.length;
|
|
165
167
|
return {
|
|
166
168
|
seq: event.seq,
|
|
167
169
|
window_id: event.windowId,
|
|
168
170
|
role: event.role,
|
|
169
171
|
created_at: event.createdAt ?? null,
|
|
170
172
|
...toolSummary(event),
|
|
171
|
-
content: truncated ? chars.slice(start, start +
|
|
173
|
+
content: truncated ? chars.slice(start, start + limit).join("") : document,
|
|
172
174
|
truncated,
|
|
173
175
|
...(matchOffset === undefined ? {} : { offset_chars: matchOffset }),
|
|
174
176
|
};
|
|
@@ -180,7 +182,7 @@ export function unknownWindowId(projection, params) {
|
|
|
180
182
|
if (typeof params.window_id !== "string")
|
|
181
183
|
return undefined;
|
|
182
184
|
const known = projection.windows.map((current) => current.windowId);
|
|
183
|
-
return known.includes(params.window_id) ? undefined : { message: `
|
|
185
|
+
return known.includes(params.window_id) ? undefined : { message: `No window "${params.window_id}" in this session`, known };
|
|
184
186
|
}
|
|
185
187
|
/**
|
|
186
188
|
* Whether one event is inside the selection: its window, its seq bounds, and a half-open
|
|
@@ -1,25 +1,19 @@
|
|
|
1
1
|
/** Stable-anchor paging, folding and literal matching. The operation supplies the full-response budget check. */
|
|
2
2
|
import { Type } from "typebox";
|
|
3
3
|
import { failure, success } from "../tools/result.js";
|
|
4
|
-
import {
|
|
4
|
+
import { prefixFit, TOOL_OUTPUT_LIMIT } from "../tools/output.js";
|
|
5
|
+
import { earliestMatchOffsetChars } from "../text-match.js";
|
|
5
6
|
import { InvalidQueryError, searchQueries } from "../tools/schema.js";
|
|
6
7
|
import { allItems, eventDocument, filteredItems, inSelection, visibleItem, HistoryFoldedRowSchema, HistoryPageItemSchema, MAX_FOLD_TOOL_NAMES, MAX_FOLD_TOOL_NAME_CHARS } from "./history.js";
|
|
7
8
|
/** ISO 8601 date or date-time; the offset is optional (group 1) and a missing one is read as UTC. */
|
|
8
9
|
const ISO_8601 = /^\d{4}-\d{2}-\d{2}(?:T\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?)?(Z|[+-]\d{2}:?\d{2})?$/;
|
|
9
|
-
/** Epoch ms for one ISO 8601 value, with a missing offset read as UTC. */
|
|
10
|
-
function isoUtcMs(value) {
|
|
11
|
-
const match = ISO_8601.exec(value);
|
|
12
|
-
if (match === null)
|
|
13
|
-
return undefined;
|
|
14
|
-
const at = Date.parse(match[1] === undefined ? `${value}Z` : value);
|
|
15
|
-
return Number.isNaN(at) ? undefined : at;
|
|
16
|
-
}
|
|
17
10
|
/** Epoch ms for one optional time param, or a refusal naming it. */
|
|
18
11
|
function timeBound(name, value) {
|
|
19
12
|
if (value === undefined)
|
|
20
13
|
return success(undefined);
|
|
21
|
-
const
|
|
22
|
-
|
|
14
|
+
const match = ISO_8601.exec(value);
|
|
15
|
+
const at = match === null ? undefined : Date.parse(match[1] === undefined ? `${value}Z` : value);
|
|
16
|
+
return at === undefined || Number.isNaN(at) ? failure("invalid_time", `\`${name}\` isn't an ISO 8601 time: "${value}".`) : success(at);
|
|
23
17
|
}
|
|
24
18
|
/** Parse `since`/`until`; a malformed or inverted pair refuses here. */
|
|
25
19
|
function resolveTimeBounds(params) {
|
|
@@ -30,7 +24,7 @@ function resolveTimeBounds(params) {
|
|
|
30
24
|
if (!until.ok)
|
|
31
25
|
return until;
|
|
32
26
|
if (since.data !== undefined && until.data !== undefined && since.data >= until.data) {
|
|
33
|
-
return failure("invalid_time", "since must be earlier than until");
|
|
27
|
+
return failure("invalid_time", "`since` must be earlier than `until`.");
|
|
34
28
|
}
|
|
35
29
|
return success({ ...(since.data === undefined ? {} : { sinceMs: since.data }), ...(until.data === undefined ? {} : { untilMs: until.data }) });
|
|
36
30
|
}
|
|
@@ -45,8 +39,8 @@ export const HistoryNewerSchema = Type.Object({
|
|
|
45
39
|
}, { additionalProperties: false });
|
|
46
40
|
export const HistoryPageSchema = Type.Object({
|
|
47
41
|
items: Type.Array(Type.Union([HistoryPageItemSchema, HistoryFoldedRowSchema])),
|
|
48
|
-
page_older: Type.Union([HistoryOlderSchema, Type.Null()]
|
|
49
|
-
page_newer: Type.Union([HistoryNewerSchema, Type.Null()]
|
|
42
|
+
page_older: Type.Union([HistoryOlderSchema, Type.Null()]),
|
|
43
|
+
page_newer: Type.Union([HistoryNewerSchema, Type.Null()]),
|
|
50
44
|
}, { additionalProperties: false });
|
|
51
45
|
/** Shorten preview text first; omit an oversized tool name rather than invent a partial name. */
|
|
52
46
|
function truncateHistoryItem(item, fits) {
|
|
@@ -157,15 +151,6 @@ function selectionCandidates(projection, params) {
|
|
|
157
151
|
.map((event) => ({ event, matchOffset: earliestMatchOffsetChars(eventDocument(event), needles) }))
|
|
158
152
|
.filter((candidate) => candidate.matchOffset >= 0));
|
|
159
153
|
}
|
|
160
|
-
/**
|
|
161
|
-
* Take the limit from the end `from` names, starting there so a budget for one row keeps the most
|
|
162
|
-
* important row. The selection is already filtered to its range; `from` never states a direction.
|
|
163
|
-
*/
|
|
164
|
-
function orderedCandidates(vis, params, limit) {
|
|
165
|
-
const ascending = [...vis].sort((a, b) => a.event.seq - b.event.seq);
|
|
166
|
-
const selected = params.from === "oldest" ? ascending.slice(0, limit) : ascending.slice(-limit);
|
|
167
|
-
return params.from === "oldest" ? selected : selected.reverse();
|
|
168
|
-
}
|
|
169
154
|
/**
|
|
170
155
|
* Resolve the time bounds once, then filter and fold against the same [sinceMs, untilMs) window.
|
|
171
156
|
* Grow the page in selection order; shorten the first preview only when no full row fits.
|
|
@@ -179,9 +164,12 @@ export function selectPage(projection, params, fits, maxChars) {
|
|
|
179
164
|
if (!candidates.ok)
|
|
180
165
|
return candidates;
|
|
181
166
|
const vis = candidates.data;
|
|
182
|
-
|
|
167
|
+
// Take the limit from the end `from` names, so a budget for one row keeps the most important one.
|
|
168
|
+
// At least one: `slice(-0)` would otherwise return the whole selection.
|
|
169
|
+
const limit = Math.max(1, scoped.limit ?? 20);
|
|
183
170
|
const folds = foldsRuns(scoped);
|
|
184
|
-
const
|
|
171
|
+
const ascending = [...vis].sort((a, b) => a.event.seq - b.event.seq);
|
|
172
|
+
const ordered = scoped.from === "oldest" ? ascending.slice(0, limit) : ascending.slice(-limit).reverse();
|
|
185
173
|
const allVisible = vis.map((candidate) => candidate.event).sort((a, b) => a.seq - b.seq);
|
|
186
174
|
const kept = [];
|
|
187
175
|
for (const candidate of ordered) {
|
|
@@ -195,7 +183,7 @@ export function selectPage(projection, params, fits, maxChars) {
|
|
|
195
183
|
}
|
|
196
184
|
const page = pageData(projection, scoped, allVisible, kept, maxChars, folds);
|
|
197
185
|
if (!fits(page)) {
|
|
198
|
-
return failure("page_too_large",
|
|
186
|
+
return failure("page_too_large", `Even trimmed to their shortest, these ${page.items.length} rows and their folded runs fill the ${TOOL_OUTPUT_LIMIT} a call can carry; narrow with \`before_seq\`/\`after_seq\` or \`since\`/\`until\`, pass \`roles\` to skip folding, or \`history_read\` one seq.`);
|
|
199
187
|
}
|
|
200
188
|
return success(page);
|
|
201
189
|
}
|
|
@@ -5,8 +5,7 @@ export type NoteAddress = {
|
|
|
5
5
|
path: string;
|
|
6
6
|
who?: string;
|
|
7
7
|
};
|
|
8
|
-
export declare const ADDRESS_FORMS = "
|
|
9
|
-
export declare function assertVirtualPath(value: unknown): string;
|
|
8
|
+
export declare const ADDRESS_FORMS = "Use <path> for this session, or @project/, @human/, @self/, or @model/ followed by a path.";
|
|
10
9
|
/**
|
|
11
10
|
* Minimal glob over virtual note paths: `*` matches any run within a segment (never
|
|
12
11
|
* `/`), `**` matches any run across segments (a leading double-star followed by a
|
|
@@ -1,21 +1,6 @@
|
|
|
1
|
-
import { NoteError } from "./errors.js";
|
|
2
|
-
import { SLUG_PATTERN } from "./paths.js";
|
|
3
|
-
export const ADDRESS_FORMS = "
|
|
4
|
-
/** A refusal names the offending input; JSON quoting keeps control chars visible, and stringify misses get String(). */
|
|
5
|
-
function shown(value) {
|
|
6
|
-
const json = JSON.stringify(value);
|
|
7
|
-
return json === undefined ? String(value) : json;
|
|
8
|
-
}
|
|
9
|
-
export function assertVirtualPath(value) {
|
|
10
|
-
if (typeof value !== "string" || value.length === 0)
|
|
11
|
-
throw new NoteError("invalid_address", `invalid address ${shown(value)}: path must be a non-empty string`);
|
|
12
|
-
if (value.includes("\0") || value.includes("\\") || value.startsWith("/"))
|
|
13
|
-
throw new NoteError("invalid_address", `invalid address ${shown(value)}: paths reject backslashes, leading "/", and NUL`);
|
|
14
|
-
const parts = value.split("/");
|
|
15
|
-
if (parts.some((part) => part.length === 0 || part === "." || part === ".."))
|
|
16
|
-
throw new NoteError("invalid_address", `invalid address ${shown(value)}: paths reject "..", ".", and empty segments`);
|
|
17
|
-
return value;
|
|
18
|
-
}
|
|
1
|
+
import { NoteError, shown } from "./errors.js";
|
|
2
|
+
import { assertVirtualPath, SLUG_PATTERN } from "./paths.js";
|
|
3
|
+
export const ADDRESS_FORMS = "Use <path> for this session, or @project/, @human/, @self/, or @model/ followed by a path.";
|
|
19
4
|
/**
|
|
20
5
|
* Minimal glob over virtual note paths: `*` matches any run within a segment (never
|
|
21
6
|
* `/`), `**` matches any run across segments (a leading double-star followed by a
|
|
@@ -37,6 +22,9 @@ export function globToRegExp(pattern) {
|
|
|
37
22
|
source += "[^/]*";
|
|
38
23
|
}
|
|
39
24
|
}
|
|
25
|
+
else if (char === "?") {
|
|
26
|
+
source += "[^/]";
|
|
27
|
+
}
|
|
40
28
|
else {
|
|
41
29
|
source += char.replace(/[\\^$.*+?()[\]{}|]/g, "\\$&");
|
|
42
30
|
}
|
|
@@ -48,9 +36,9 @@ export function assertGlobPattern(value) {
|
|
|
48
36
|
if (value === undefined || value === null || value === "")
|
|
49
37
|
return undefined;
|
|
50
38
|
if (typeof value !== "string")
|
|
51
|
-
throw new NoteError("invalid_pattern", `
|
|
39
|
+
throw new NoteError("invalid_pattern", `glob ${shown(value)} must be a string.`);
|
|
52
40
|
if (value.includes("\0") || value.includes("\\"))
|
|
53
|
-
throw new NoteError("invalid_pattern", `
|
|
41
|
+
throw new NoteError("invalid_pattern", `glob ${shown(value)} can't contain "\\" or NUL.`);
|
|
54
42
|
return value;
|
|
55
43
|
}
|
|
56
44
|
/**
|
|
@@ -59,7 +47,7 @@ export function assertGlobPattern(value) {
|
|
|
59
47
|
*/
|
|
60
48
|
export function assertAddress(value) {
|
|
61
49
|
if (typeof value !== "string")
|
|
62
|
-
throw new NoteError("invalid_address",
|
|
50
|
+
throw new NoteError("invalid_address", `${shown(value)} isn't a note address. ${ADDRESS_FORMS}`);
|
|
63
51
|
let scope = "session";
|
|
64
52
|
let path = value;
|
|
65
53
|
let who;
|
|
@@ -81,20 +69,20 @@ export function assertAddress(value) {
|
|
|
81
69
|
const nameEnd = tail.indexOf("/");
|
|
82
70
|
who = nameEnd === -1 ? tail : tail.slice(0, nameEnd);
|
|
83
71
|
if (!SLUG_PATTERN.test(who))
|
|
84
|
-
throw new NoteError("invalid_address",
|
|
72
|
+
throw new NoteError("invalid_address", `${shown(value)} isn't a note address. ${ADDRESS_FORMS}`);
|
|
85
73
|
scope = head === "agents" ? "agent" : "model";
|
|
86
74
|
path = nameEnd === -1 ? "" : tail.slice(nameEnd + 1);
|
|
87
75
|
}
|
|
88
76
|
else {
|
|
89
|
-
throw new NoteError("invalid_address",
|
|
77
|
+
throw new NoteError("invalid_address", `${shown(value)} isn't a note address. ${ADDRESS_FORMS}`);
|
|
90
78
|
}
|
|
91
79
|
if (path === "" && scope !== "agent" && scope !== "model")
|
|
92
|
-
throw new NoteError("invalid_address",
|
|
80
|
+
throw new NoteError("invalid_address", `${shown(value)} isn't a note address. ${ADDRESS_FORMS}`);
|
|
93
81
|
if (path === "" && who === undefined)
|
|
94
|
-
throw new NoteError("invalid_address",
|
|
82
|
+
throw new NoteError("invalid_address", `${shown(value)} isn't a note address. ${ADDRESS_FORMS}`);
|
|
95
83
|
}
|
|
96
84
|
if (path.includes("@"))
|
|
97
|
-
throw new NoteError("invalid_address",
|
|
85
|
+
throw new NoteError("invalid_address", `${shown(value)} isn't a note address. ${ADDRESS_FORMS}`);
|
|
98
86
|
assertVirtualPath(path);
|
|
99
87
|
return { scope, path, who };
|
|
100
88
|
}
|
package/dist/src/notes/errors.js
CHANGED
|
@@ -11,3 +11,8 @@ export class NoteError extends Error {
|
|
|
11
11
|
this.editIndex = extra.editIndex;
|
|
12
12
|
}
|
|
13
13
|
}
|
|
14
|
+
/** A refusal names the offending input; JSON quoting keeps control chars visible, and stringify misses get String(). */
|
|
15
|
+
export function shown(value) {
|
|
16
|
+
const json = JSON.stringify(value);
|
|
17
|
+
return json === undefined ? String(value) : json;
|
|
18
|
+
}
|
|
@@ -107,15 +107,29 @@ export function parseNote(raw, now = Date.now()) {
|
|
|
107
107
|
meta.accessCount = typeof meta.accessCount === "number" && Number.isFinite(meta.accessCount) ? meta.accessCount : 0;
|
|
108
108
|
return { meta: meta, body };
|
|
109
109
|
}
|
|
110
|
-
/**
|
|
110
|
+
/**
|
|
111
|
+
* Emit a YAML scalar: bare for safe strings and JSON literals, JSON-quoted otherwise.
|
|
112
|
+
* A quoted string must not come back as another type: a value that `JSON.parse` reads as a
|
|
113
|
+
* non-string (`"1"`, `"1e5"`) is always emitted quoted, so an unknown key survives a rewrite
|
|
114
|
+
* with its type intact.
|
|
115
|
+
*/
|
|
111
116
|
function yamlScalar(value) {
|
|
112
117
|
if (typeof value === "string") {
|
|
113
118
|
const reserved = new Set(["true", "false", "null", "yes", "no", "on", "off", "~"]);
|
|
114
|
-
if (/^[A-Za-z0-9_.+\-:/]+$/.test(value) && !reserved.has(value.toLowerCase()))
|
|
119
|
+
if (/^[A-Za-z0-9_.+\-:/]+$/.test(value) && !reserved.has(value.toLowerCase()) && !parsesAsNonString(value))
|
|
115
120
|
return value;
|
|
116
121
|
}
|
|
117
122
|
return JSON.stringify(value);
|
|
118
123
|
}
|
|
124
|
+
/** True when a bare scalar would be read back as a number, boolean or null instead of text. */
|
|
125
|
+
function parsesAsNonString(text) {
|
|
126
|
+
try {
|
|
127
|
+
return typeof JSON.parse(text) !== "string";
|
|
128
|
+
}
|
|
129
|
+
catch {
|
|
130
|
+
return false;
|
|
131
|
+
}
|
|
132
|
+
}
|
|
119
133
|
/** Serialize frontmatter + blank line + body. Known keys emit in Design order, extras after. */
|
|
120
134
|
export function serializeNote(meta, body) {
|
|
121
135
|
const lines = [];
|
|
@@ -14,9 +14,6 @@ function assertDirectoryComponent(field, value) {
|
|
|
14
14
|
export function snapshotNotesIdentity(value) {
|
|
15
15
|
if (typeof value !== "object" || value === null || Array.isArray(value))
|
|
16
16
|
throw new TypeError("notes context must be a plain object");
|
|
17
|
-
const prototype = Object.getPrototypeOf(value);
|
|
18
|
-
if (prototype !== Object.prototype && prototype !== null)
|
|
19
|
-
throw new TypeError("notes context must be a plain object");
|
|
20
17
|
const homeValue = requireString("home", value.home);
|
|
21
18
|
const sessionId = requireString("sessionId", value.sessionId);
|
|
22
19
|
const projectKey = requireString("projectKey", value.projectKey);
|
|
@@ -4,7 +4,17 @@ export type Scope = "session" | "project" | "human" | "agent" | "model";
|
|
|
4
4
|
export declare const SLUG_PATTERN: RegExp;
|
|
5
5
|
/** Slugify a caller-declared identity; identity is never inferred from note content. */
|
|
6
6
|
export declare function slugify(value: string): string;
|
|
7
|
-
/**
|
|
7
|
+
/**
|
|
8
|
+
* The one virtual-path grammar: a relative, `/`-separated path with no empty, `.` or `..`
|
|
9
|
+
* segment. Both the address decoder and the physical-path builder enforce it here, so a
|
|
10
|
+
* caller that reaches a path without going through an address still cannot escape a home.
|
|
11
|
+
*/
|
|
12
|
+
export declare function assertVirtualPath(value: unknown): string;
|
|
13
|
+
/**
|
|
14
|
+
* `<basename(canonical git root)-sha1(canonical git root)[:8]>`, or the same formula over cwd
|
|
15
|
+
* with no git root. Git writes the canonical spelling into a linked worktree's `.git` pointer,
|
|
16
|
+
* so canonicalizing here is what keeps one repository — and its worktrees — on one home.
|
|
17
|
+
*/
|
|
8
18
|
export declare function projectKey(cwd: string): string;
|
|
9
19
|
/** Absolute directory holding the per-session note homes. */
|
|
10
20
|
export declare function sessionHomesRoot(home: string): string;
|
package/dist/src/notes/paths.js
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
import { createHash } from "node:crypto";
|
|
2
|
-
import { existsSync, readFileSync, statSync } from "node:fs";
|
|
2
|
+
import { existsSync, readFileSync, realpathSync, statSync } from "node:fs";
|
|
3
3
|
import { readdir } from "node:fs/promises";
|
|
4
4
|
import { basename, dirname, join, resolve, sep } from "node:path";
|
|
5
|
+
import { NoteError, shown } from "./errors.js";
|
|
5
6
|
/** The one legal home-name shape: lowercase [a-z0-9-] runs separated by single dashes. */
|
|
6
7
|
export const SLUG_PATTERN = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
|
|
7
8
|
/** Slugify a caller-declared identity; identity is never inferred from note content. */
|
|
@@ -9,10 +10,34 @@ export function slugify(value) {
|
|
|
9
10
|
const slug = value.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
|
|
10
11
|
return slug.length > 0 ? slug : "root";
|
|
11
12
|
}
|
|
12
|
-
/**
|
|
13
|
+
/**
|
|
14
|
+
* The one virtual-path grammar: a relative, `/`-separated path with no empty, `.` or `..`
|
|
15
|
+
* segment. Both the address decoder and the physical-path builder enforce it here, so a
|
|
16
|
+
* caller that reaches a path without going through an address still cannot escape a home.
|
|
17
|
+
*/
|
|
18
|
+
export function assertVirtualPath(value) {
|
|
19
|
+
if (typeof value !== "string" || value.length === 0)
|
|
20
|
+
throw new NoteError("invalid_address", "The address is empty; give the note a path.");
|
|
21
|
+
if (value.includes("\0") || value.includes("\\") || value.startsWith("/"))
|
|
22
|
+
throw new NoteError("invalid_address", `${shown(value)}: a note path can't start with "/" or contain "\\" or NUL.`);
|
|
23
|
+
const parts = value.split("/");
|
|
24
|
+
if (parts.some((part) => part.length === 0 || part === "." || part === ".."))
|
|
25
|
+
throw new NoteError("invalid_address", `${shown(value)}: a note path can't have empty, ".", or ".." folder names.`);
|
|
26
|
+
return value;
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* `<basename(canonical git root)-sha1(canonical git root)[:8]>`, or the same formula over cwd
|
|
30
|
+
* with no git root. Git writes the canonical spelling into a linked worktree's `.git` pointer,
|
|
31
|
+
* so canonicalizing here is what keeps one repository — and its worktrees — on one home.
|
|
32
|
+
*/
|
|
13
33
|
export function projectKey(cwd) {
|
|
14
34
|
const absolute = resolve(cwd);
|
|
15
|
-
const
|
|
35
|
+
const spelled = gitRoot(absolute) ?? absolute;
|
|
36
|
+
let root = spelled;
|
|
37
|
+
try {
|
|
38
|
+
root = realpathSync(spelled);
|
|
39
|
+
}
|
|
40
|
+
catch { /* An unresolvable path keeps its spelling. */ }
|
|
16
41
|
const digest = createHash("sha1").update(root).digest("hex").slice(0, 8);
|
|
17
42
|
return `${basename(root)}-${digest}`;
|
|
18
43
|
}
|
|
@@ -105,9 +130,5 @@ export function noteFileName(vpath) {
|
|
|
105
130
|
}
|
|
106
131
|
/** Absolute file path for a virtual path in a scope. Callers validate the vpath first. */
|
|
107
132
|
export function physicalPath(scope, vpath, identity, who) {
|
|
108
|
-
if (typeof vpath !== "string" || vpath.length === 0 || vpath.includes("\0") || vpath.includes("\\") || vpath.startsWith("/"))
|
|
109
|
-
throw new TypeError("path must be a safe virtual relative path");
|
|
110
|
-
if (vpath.split("/").some((part) => part.length === 0 || part === "." || part === ".."))
|
|
111
|
-
throw new TypeError("path contains an unsupported component");
|
|
112
133
|
return join(scopeDir(scope, identity, who), ...noteFileName(vpath).split("/"));
|
|
113
134
|
}
|
|
@@ -76,6 +76,7 @@ export type NoteRenameResult = {
|
|
|
76
76
|
meta: NoteMeta;
|
|
77
77
|
replacedCrumpledTarget: boolean;
|
|
78
78
|
};
|
|
79
|
+
/** A home, or one unreadable note inside it, that a status-reporting query could not read. */
|
|
79
80
|
export type NoteQueryStatus = {
|
|
80
81
|
homesUnavailable: string[];
|
|
81
82
|
};
|
package/dist/src/notes/store.js
CHANGED
|
@@ -75,10 +75,6 @@ async function walkMarkdown(dir, base = dir) {
|
|
|
75
75
|
}
|
|
76
76
|
return paths;
|
|
77
77
|
}
|
|
78
|
-
function matcherFor(pattern) {
|
|
79
|
-
const normalized = assertGlobPattern(pattern);
|
|
80
|
-
return normalized === undefined ? undefined : globToRegExp(normalized);
|
|
81
|
-
}
|
|
82
78
|
async function homesForPattern(pattern, identity) {
|
|
83
79
|
if (!pattern || !pattern.startsWith("@"))
|
|
84
80
|
return undefined;
|
|
@@ -110,11 +106,6 @@ function normalizePattern(pattern, identity) {
|
|
|
110
106
|
return `@models/${identity.model}/${pattern.slice("@model/".length)}`;
|
|
111
107
|
return pattern;
|
|
112
108
|
}
|
|
113
|
-
function assertScope(value) {
|
|
114
|
-
if (!isScope(value))
|
|
115
|
-
throw new NoteError("invalid_scope", `scope must be one of session, project, human, agent, model (got ${JSON.stringify(value)})`);
|
|
116
|
-
return value;
|
|
117
|
-
}
|
|
118
109
|
function assertOrigin(value) {
|
|
119
110
|
if (!isOrigin(value))
|
|
120
111
|
throw new NoteError("invalid_origin", `origin must be one of user, self, external (got ${JSON.stringify(value)})`);
|
|
@@ -128,7 +119,9 @@ function assertWho(value) {
|
|
|
128
119
|
}
|
|
129
120
|
async function homesFor(identity, opts) {
|
|
130
121
|
if (opts.scope !== undefined) {
|
|
131
|
-
|
|
122
|
+
if (!isScope(opts.scope))
|
|
123
|
+
throw new NoteError("invalid_scope", `scope must be one of session, project, human, agent, model (got ${JSON.stringify(opts.scope)})`);
|
|
124
|
+
const scope = opts.scope;
|
|
132
125
|
if (opts.who !== undefined) {
|
|
133
126
|
const who = assertWho(opts.who);
|
|
134
127
|
if (scope !== "agent" && scope !== "model")
|
|
@@ -195,12 +188,16 @@ async function atomicWrite(path, content) {
|
|
|
195
188
|
function assertWritablePath(vpath) {
|
|
196
189
|
const bytes = Buffer.byteLength(vpath, "utf8");
|
|
197
190
|
if (bytes > MAX_NOTE_PATH_BYTES)
|
|
198
|
-
throw new NoteError("too_large", `
|
|
191
|
+
throw new NoteError("too_large", `Path too long: ${bytes} bytes; the limit is ${MAX_NOTE_PATH_BYTES}.`);
|
|
192
|
+
}
|
|
193
|
+
/** Rounded up, so a note just over the limit never reads as exactly at it. */
|
|
194
|
+
function megabytes(bytes) {
|
|
195
|
+
return `${Math.ceil(bytes / 10_000) / 100} MB`;
|
|
199
196
|
}
|
|
200
197
|
function assertSerializedSize(content) {
|
|
201
198
|
const bytes = Buffer.byteLength(content, "utf8");
|
|
202
199
|
if (bytes > MAX_NOTE_BYTES)
|
|
203
|
-
throw new NoteError("too_large", `note
|
|
200
|
+
throw new NoteError("too_large", `This note would be ${megabytes(bytes)}, over the ${megabytes(MAX_NOTE_BYTES)} limit per note; split it into several notes.`);
|
|
204
201
|
}
|
|
205
202
|
/** Frontmatter block only (the body separator stripped), for metadata-only change inputs. */
|
|
206
203
|
function frontmatterOf(meta) {
|
|
@@ -214,14 +211,7 @@ function assertWritableHome(scope, who, identity) {
|
|
|
214
211
|
if (who === current)
|
|
215
212
|
return;
|
|
216
213
|
const home = scope === "agent" ? `@agents/${who}/` : `@models/${who}/`;
|
|
217
|
-
throw new NoteError("invalid_scope", `${home} is
|
|
218
|
-
}
|
|
219
|
-
/** Normalize parsed metadata exactly as a read does, including its access mutation. */
|
|
220
|
-
function accessedMeta(meta, scope, now) {
|
|
221
|
-
const next = { ...meta, scope };
|
|
222
|
-
next.lastAccessed = now;
|
|
223
|
-
next.accessCount = (typeof next.accessCount === "number" ? next.accessCount : 0) + 1;
|
|
224
|
-
return next;
|
|
214
|
+
throw new NoteError("invalid_scope", `${home} is someone else's home; you can write to this session, @project/, @human/, @self/, or @model/.`);
|
|
225
215
|
}
|
|
226
216
|
/** Create a store over one validated, immutable snapshot of the supplied explicit identity. */
|
|
227
217
|
export function createNotesStore(input) {
|
|
@@ -232,7 +222,9 @@ export function createNotesStore(input) {
|
|
|
232
222
|
assertWritablePath(destination.path);
|
|
233
223
|
const scope = destination.scope;
|
|
234
224
|
assertWritableHome(scope, destination.who, identity);
|
|
235
|
-
|
|
225
|
+
// Absent means "keep whatever the note already says": replacing a note must not silently
|
|
226
|
+
// re-attribute a user-written note to the agent that happened to rewrite it.
|
|
227
|
+
const origin = stableOptions.origin === undefined ? undefined : assertOrigin(stableOptions.origin);
|
|
236
228
|
const path = physicalPath(scope, destination.path, identity, destination.who);
|
|
237
229
|
return withPathQueue(path, async () => {
|
|
238
230
|
const now = writeStamp();
|
|
@@ -242,7 +234,7 @@ export function createNotesStore(input) {
|
|
|
242
234
|
const outcome = existing === undefined ? "created" : existing.crumpledAt === undefined ? "overwrote" : "uncrumpled";
|
|
243
235
|
const meta = existing ?? {
|
|
244
236
|
scope,
|
|
245
|
-
origin,
|
|
237
|
+
origin: origin ?? "self",
|
|
246
238
|
createdAt: now,
|
|
247
239
|
updatedAt: now,
|
|
248
240
|
lastAccessed: now,
|
|
@@ -250,7 +242,8 @@ export function createNotesStore(input) {
|
|
|
250
242
|
...(scope === "session" ? { project: identity.projectKey } : {}),
|
|
251
243
|
};
|
|
252
244
|
meta.scope = scope;
|
|
253
|
-
|
|
245
|
+
if (origin !== undefined)
|
|
246
|
+
meta.origin = origin;
|
|
254
247
|
delete meta.crumpledAt;
|
|
255
248
|
meta.updatedAt = now;
|
|
256
249
|
const serialized = serializeNote(meta, cleanBody);
|
|
@@ -269,7 +262,8 @@ export function createNotesStore(input) {
|
|
|
269
262
|
return undefined;
|
|
270
263
|
const now = Date.now();
|
|
271
264
|
const parsed = parseNote(raw, now);
|
|
272
|
-
|
|
265
|
+
// A read records its own access, exactly as a write records an edit.
|
|
266
|
+
const meta = { ...parsed.meta, scope, lastAccessed: now, accessCount: (typeof parsed.meta.accessCount === "number" ? parsed.meta.accessCount : 0) + 1 };
|
|
273
267
|
await atomicWrite(path, serializeNote(meta, parsed.body));
|
|
274
268
|
return { meta, body: parsed.body, resolvedScope: scope };
|
|
275
269
|
});
|
|
@@ -282,13 +276,13 @@ export function createNotesStore(input) {
|
|
|
282
276
|
const scope = destination.scope;
|
|
283
277
|
assertWritableHome(scope, destination.who, identity);
|
|
284
278
|
if (operations.length === 0 && stableOptions.origin === undefined && stableOptions.crumpled === undefined) {
|
|
285
|
-
throw new NoteError("nothing_to_do", "
|
|
279
|
+
throw new NoteError("nothing_to_do", "Nothing to change: pass edits, origin, crumpled, or rename_to.");
|
|
286
280
|
}
|
|
287
281
|
const path = physicalPath(scope, destination.path, identity, destination.who);
|
|
288
282
|
return withPathQueue(path, async () => {
|
|
289
283
|
const raw = await readFileIfExists(path);
|
|
290
284
|
if (raw === undefined)
|
|
291
|
-
throw new NoteError("not_found",
|
|
285
|
+
throw new NoteError("not_found", `No note at ${noteIdentity(identity, address).address}.`);
|
|
292
286
|
const { meta, body } = parseNote(raw);
|
|
293
287
|
meta.scope = scope;
|
|
294
288
|
const beforeMeta = { ...meta };
|
|
@@ -298,14 +292,14 @@ export function createNotesStore(input) {
|
|
|
298
292
|
const oldText = operation?.oldText;
|
|
299
293
|
const newText = operation?.newText;
|
|
300
294
|
if (typeof oldText !== "string" || oldText.length === 0)
|
|
301
|
-
throw new NoteError("no_match", `
|
|
295
|
+
throw new NoteError("no_match", `edits[${index}].oldText is empty.`, { editIndex: index });
|
|
302
296
|
if (typeof newText !== "string")
|
|
303
|
-
throw new NoteError("no_match", `
|
|
297
|
+
throw new NoteError("no_match", `edits[${index}].newText must be a string.`, { editIndex: index });
|
|
304
298
|
const lines = matchLineNumbers(next, oldText);
|
|
305
299
|
if (lines.length === 0)
|
|
306
|
-
throw new NoteError("no_match", `
|
|
300
|
+
throw new NoteError("no_match", `edits[${index}].oldText isn't in the note${index > 0 ? " (after the earlier edits)" : ""}. Nothing was saved.`, { editIndex: index });
|
|
307
301
|
if (lines.length > 1 && !stableOptions.replaceAll) {
|
|
308
|
-
throw new NoteError("ambiguous_edit", `
|
|
302
|
+
throw new NoteError("ambiguous_edit", `edits[${index}].oldText appears ${lines.length} times (${anchorLines(lines)}); add surrounding text to pick one, or set replace_all. Nothing was saved.`, { lineNumbers: lines, editIndex: index });
|
|
309
303
|
}
|
|
310
304
|
if (oldText !== newText)
|
|
311
305
|
applied++;
|
|
@@ -361,15 +355,15 @@ export function createNotesStore(input) {
|
|
|
361
355
|
const fromPath = physicalPath(fromScope, from.path, identity, from.who);
|
|
362
356
|
const toPath = physicalPath(toScope, to.path, identity, to.who);
|
|
363
357
|
if (resolve(fromPath) === resolve(toPath))
|
|
364
|
-
throw new NoteError("nothing_to_do", "rename_to
|
|
358
|
+
throw new NoteError("nothing_to_do", "rename_to points at the note itself.");
|
|
365
359
|
const [first, second] = [fromPath, toPath].sort();
|
|
366
360
|
return withPathQueue(first, () => withPathQueue(second, async () => {
|
|
367
361
|
const raw = await readFileIfExists(fromPath);
|
|
368
362
|
if (raw === undefined)
|
|
369
|
-
throw new NoteError("not_found",
|
|
363
|
+
throw new NoteError("not_found", `No note at ${noteIdentity(identity, fromAddress).address}.`);
|
|
370
364
|
const targetRaw = await readFileIfExists(toPath);
|
|
371
365
|
if (targetRaw !== undefined && parseNote(targetRaw).meta.crumpledAt === undefined) {
|
|
372
|
-
throw new NoteError("already_exists",
|
|
366
|
+
throw new NoteError("already_exists", `${noteIdentity(identity, toAddress).address} already holds a note; crumple it first or pick another address.`);
|
|
373
367
|
}
|
|
374
368
|
const { meta, body } = parseNote(raw);
|
|
375
369
|
meta.scope = toScope;
|
|
@@ -387,7 +381,9 @@ export function createNotesStore(input) {
|
|
|
387
381
|
}));
|
|
388
382
|
}
|
|
389
383
|
async function* scan(options, status) {
|
|
390
|
-
const
|
|
384
|
+
const pattern = normalizePattern(options.glob, identity);
|
|
385
|
+
const normalized = assertGlobPattern(pattern);
|
|
386
|
+
const matcher = normalized === undefined ? undefined : globToRegExp(normalized);
|
|
391
387
|
let homes;
|
|
392
388
|
try {
|
|
393
389
|
homes = await homesFor(identity, options);
|
|
@@ -401,20 +397,9 @@ export function createNotesStore(input) {
|
|
|
401
397
|
for (const home of homes) {
|
|
402
398
|
const scope = home.scope;
|
|
403
399
|
const root = scopeDir(scope, identity, home.who);
|
|
404
|
-
|
|
400
|
+
let paths;
|
|
405
401
|
try {
|
|
406
|
-
|
|
407
|
-
if (matcher && !matcher.test(canonicalAddressFor(identity, scope, path, home.who)))
|
|
408
|
-
continue;
|
|
409
|
-
const address = addressFor(identity, scope, path, home.who);
|
|
410
|
-
const fullPath = join(root, path);
|
|
411
|
-
const raw = await withPathQueue(fullPath, () => readFile(fullPath, "utf8"));
|
|
412
|
-
const { meta, body } = parseNote(raw);
|
|
413
|
-
meta.scope = scope;
|
|
414
|
-
if ((meta.crumpledAt !== undefined) !== (options.crumpled === true))
|
|
415
|
-
continue;
|
|
416
|
-
homeRows.push({ address, scope, path, meta, body });
|
|
417
|
-
}
|
|
402
|
+
paths = await walkMarkdown(root);
|
|
418
403
|
}
|
|
419
404
|
catch (error) {
|
|
420
405
|
if (!status || !isFilesystemError(error))
|
|
@@ -422,8 +407,28 @@ export function createNotesStore(input) {
|
|
|
422
407
|
status.homesUnavailable.push(addressFor(identity, scope, "", home.who).replace(/\/$/, "") || "session");
|
|
423
408
|
continue;
|
|
424
409
|
}
|
|
425
|
-
for (const
|
|
426
|
-
|
|
410
|
+
for (const path of paths) {
|
|
411
|
+
if (matcher && !matcher.test(canonicalAddressFor(identity, scope, path, home.who)))
|
|
412
|
+
continue;
|
|
413
|
+
const address = addressFor(identity, scope, path, home.who);
|
|
414
|
+
const fullPath = join(root, path);
|
|
415
|
+
let raw;
|
|
416
|
+
try {
|
|
417
|
+
raw = await withPathQueue(fullPath, () => readFile(fullPath, "utf8"));
|
|
418
|
+
}
|
|
419
|
+
catch (error) {
|
|
420
|
+
// One unreadable note is named on its own; its home's readable notes still list.
|
|
421
|
+
if (!status || !isFilesystemError(error))
|
|
422
|
+
throw error;
|
|
423
|
+
status.homesUnavailable.push(address);
|
|
424
|
+
continue;
|
|
425
|
+
}
|
|
426
|
+
const { meta, body } = parseNote(raw);
|
|
427
|
+
meta.scope = scope;
|
|
428
|
+
if ((meta.crumpledAt !== undefined) !== (options.crumpled === true))
|
|
429
|
+
continue;
|
|
430
|
+
yield { address, scope, path, meta, body };
|
|
431
|
+
}
|
|
427
432
|
}
|
|
428
433
|
}
|
|
429
434
|
async function list(options = {}) {
|