notesoup 0.0.0-stage → 0.40.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/LICENSE +21 -0
- package/README.md +94 -2
- package/dist/src/boot/render.d.ts +16 -0
- package/dist/src/boot/render.js +95 -0
- package/dist/src/boot/snapshot.d.ts +32 -0
- package/dist/src/boot/snapshot.js +36 -0
- package/dist/src/boot/text.d.ts +17 -0
- package/dist/src/boot/text.js +48 -0
- package/dist/src/budget/constants.d.ts +9 -0
- package/dist/src/budget/constants.js +9 -0
- package/dist/src/budget/policy.d.ts +19 -0
- package/dist/src/budget/policy.js +36 -0
- package/dist/src/budget/text.d.ts +8 -0
- package/dist/src/budget/text.js +10 -0
- package/dist/src/claude/helper.d.ts +15 -0
- package/dist/src/claude/helper.js +87 -0
- package/dist/src/dream/doctor.d.ts +2 -0
- package/dist/src/dream/doctor.js +160 -0
- package/dist/src/dream/gates.d.ts +10 -0
- package/dist/src/dream/gates.js +26 -0
- package/dist/src/dream/git.d.ts +21 -0
- package/dist/src/dream/git.js +71 -0
- package/dist/src/dream/jail.d.ts +11 -0
- package/dist/src/dream/jail.js +71 -0
- package/dist/src/dream/lock.d.ts +31 -0
- package/dist/src/dream/lock.js +99 -0
- package/dist/src/dream/playbook.d.ts +1 -0
- package/dist/src/dream/playbook.js +2 -0
- package/dist/src/dream/report.d.ts +7 -0
- package/dist/src/dream/report.js +43 -0
- package/dist/src/dream/result.d.ts +9 -0
- package/dist/src/dream/result.js +1 -0
- package/dist/src/dream/settings.d.ts +10 -0
- package/dist/src/dream/settings.js +14 -0
- package/dist/src/history/history.d.ts +156 -0
- package/dist/src/history/history.js +212 -0
- package/dist/src/history/query.d.ts +63 -0
- package/dist/src/history/query.js +201 -0
- package/dist/src/index.d.ts +1 -0
- package/dist/src/index.js +1 -0
- package/dist/src/notes/address.d.ts +31 -0
- package/dist/src/notes/address.js +123 -0
- package/dist/src/notes/constants.d.ts +3 -0
- package/dist/src/notes/constants.js +3 -0
- package/dist/src/notes/errors.d.ts +11 -0
- package/dist/src/notes/errors.js +13 -0
- package/dist/src/notes/frontmatter.d.ts +44 -0
- package/dist/src/notes/frontmatter.js +145 -0
- package/dist/src/notes/fs-error.d.ts +2 -0
- package/dist/src/notes/fs-error.js +5 -0
- package/dist/src/notes/identity.d.ts +10 -0
- package/dist/src/notes/identity.js +33 -0
- package/dist/src/notes/index.d.ts +5 -0
- package/dist/src/notes/index.js +3 -0
- package/dist/src/notes/paths.d.ts +21 -0
- package/dist/src/notes/paths.js +113 -0
- package/dist/src/notes/store.d.ts +103 -0
- package/dist/src/notes/store.js +474 -0
- package/dist/src/pi/boot.d.ts +24 -0
- package/dist/src/pi/boot.js +56 -0
- package/dist/src/pi/budget.d.ts +13 -0
- package/dist/src/pi/budget.js +178 -0
- package/dist/src/pi/dream/cli.d.ts +10 -0
- package/dist/src/pi/dream/cli.js +140 -0
- package/dist/src/pi/dream/runner.d.ts +27 -0
- package/dist/src/pi/dream/runner.js +90 -0
- package/dist/src/pi/dream/settings.d.ts +7 -0
- package/dist/src/pi/dream/settings.js +17 -0
- package/dist/src/pi/entries.d.ts +7 -0
- package/dist/src/pi/entries.js +7 -0
- package/dist/src/pi/estimate.d.ts +16 -0
- package/dist/src/pi/estimate.js +99 -0
- package/dist/src/pi/extension.d.ts +10 -0
- package/dist/src/pi/extension.js +24 -0
- package/dist/src/pi/history-tools.d.ts +3 -0
- package/dist/src/pi/history-tools.js +9 -0
- package/dist/src/pi/history.d.ts +4 -0
- package/dist/src/pi/history.js +150 -0
- package/dist/src/pi/notes/adapter.d.ts +10 -0
- package/dist/src/pi/notes/adapter.js +27 -0
- package/dist/src/pi/notes/tools.d.ts +3 -0
- package/dist/src/pi/notes/tools.js +15 -0
- package/dist/src/pi/reset/artifacts.d.ts +24 -0
- package/dist/src/pi/reset/artifacts.js +84 -0
- package/dist/src/pi/reset/committed.d.ts +7 -0
- package/dist/src/pi/reset/committed.js +28 -0
- package/dist/src/pi/reset/lifecycle.d.ts +101 -0
- package/dist/src/pi/reset/lifecycle.js +277 -0
- package/dist/src/pi/reset/text.d.ts +5 -0
- package/dist/src/pi/reset/text.js +6 -0
- package/dist/src/pi/runtime.d.ts +3 -0
- package/dist/src/pi/runtime.js +206 -0
- package/dist/src/pi/session-reader.d.ts +5 -0
- package/dist/src/pi/session-reader.js +1 -0
- package/dist/src/pi/thresholds.d.ts +17 -0
- package/dist/src/pi/thresholds.js +33 -0
- package/dist/src/pi/tool-names.d.ts +7 -0
- package/dist/src/pi/tool-names.js +7 -0
- package/dist/src/pi/tool-result.d.ts +15 -0
- package/dist/src/pi/tool-result.js +29 -0
- package/dist/src/pi/window.d.ts +41 -0
- package/dist/src/pi/window.js +127 -0
- package/dist/src/settings.d.ts +9 -0
- package/dist/src/settings.js +18 -0
- package/dist/src/text-match.d.ts +5 -0
- package/dist/src/text-match.js +16 -0
- package/dist/src/tools/history.d.ts +58 -0
- package/dist/src/tools/history.js +210 -0
- package/dist/src/tools/notes.d.ts +250 -0
- package/dist/src/tools/notes.js +360 -0
- package/dist/src/tools/output.d.ts +23 -0
- package/dist/src/tools/output.js +39 -0
- package/dist/src/tools/result.d.ts +82 -0
- package/dist/src/tools/result.js +104 -0
- package/dist/src/tools/schema.d.ts +18 -0
- package/dist/src/tools/schema.js +31 -0
- package/dist/test/agent-loop.test.d.ts +1 -0
- package/dist/test/agent-loop.test.js +1497 -0
- package/dist/test/boot.integration.test.d.ts +1 -0
- package/dist/test/boot.integration.test.js +294 -0
- package/dist/test/budget-settings.integration.test.d.ts +1 -0
- package/dist/test/budget-settings.integration.test.js +144 -0
- package/dist/test/claude-mod.test.d.ts +1 -0
- package/dist/test/claude-mod.test.js +404 -0
- package/dist/test/dependencies.test.d.ts +1 -0
- package/dist/test/dependencies.test.js +101 -0
- package/dist/test/doctor.test.d.ts +1 -0
- package/dist/test/doctor.test.js +37 -0
- package/dist/test/dream-skill.test.d.ts +1 -0
- package/dist/test/dream-skill.test.js +72 -0
- package/dist/test/dream.test.d.ts +1 -0
- package/dist/test/dream.test.js +136 -0
- package/dist/test/helpers/dependency-graph.d.ts +5 -0
- package/dist/test/helpers/dependency-graph.js +73 -0
- package/dist/test/helpers/extension-test-environment.d.ts +1 -0
- package/dist/test/helpers/extension-test-environment.js +9 -0
- package/dist/test/helpers/extension.d.ts +119 -0
- package/dist/test/helpers/extension.js +367 -0
- package/dist/test/helpers/notes.d.ts +6 -0
- package/dist/test/helpers/notes.js +13 -0
- package/dist/test/history.integration.test.d.ts +1 -0
- package/dist/test/history.integration.test.js +633 -0
- package/dist/test/host-neutral.test.d.ts +1 -0
- package/dist/test/host-neutral.test.js +274 -0
- package/dist/test/notes-library.test.d.ts +1 -0
- package/dist/test/notes-library.test.js +214 -0
- package/dist/test/notes.integration.test.d.ts +1 -0
- package/dist/test/notes.integration.test.js +515 -0
- package/dist/test/notes.test.d.ts +1 -0
- package/dist/test/notes.test.js +530 -0
- package/dist/test/reset-lifecycle.test.d.ts +1 -0
- package/dist/test/reset-lifecycle.test.js +605 -0
- package/docs/architecture.md +63 -0
- package/docs/claude-code-mod.md +9 -0
- package/docs/notes-library.md +74 -0
- package/docs/reset-lifecycle.md +75 -0
- package/docs/sdk-integration.md +39 -0
- package/docs/skills.md +30 -0
- package/docs/tool-results.md +78 -0
- package/mods/notesoup/.claude-plugin/plugin.json +8 -0
- package/mods/notesoup/dist/claude/helper.js +9265 -0
- package/mods/notesoup/hooks/hooks.json +4 -0
- package/mods/notesoup/hooks/register.ts +240 -0
- package/mods/notesoup/playbook.md +34 -0
- package/mods/notesoup/skills/dream/SKILL.md +12 -0
- package/mods/pi-context/dist/claude/helper.js +9324 -0
- package/package.json +89 -5
- package/playbook.md +34 -0
- package/skills/dream/SKILL.md +12 -0
- package/skills/memory/SKILL.md +59 -0
- package/src/boot/render.ts +115 -0
- package/src/boot/snapshot.ts +46 -0
- package/src/boot/text.ts +58 -0
- package/src/budget/constants.ts +9 -0
- package/src/budget/policy.ts +36 -0
- package/src/budget/text.ts +11 -0
- package/src/claude/helper.ts +94 -0
- package/src/dream/doctor.ts +117 -0
- package/src/dream/gates.ts +26 -0
- package/src/dream/git.ts +73 -0
- package/src/dream/jail.ts +62 -0
- package/src/dream/lock.ts +82 -0
- package/src/dream/playbook.ts +3 -0
- package/src/dream/report.ts +36 -0
- package/src/dream/result.ts +2 -0
- package/src/dream/settings.ts +16 -0
- package/src/history/history.ts +286 -0
- package/src/history/query.ts +222 -0
- package/src/index.ts +1 -0
- package/src/notes/address.ts +110 -0
- package/src/notes/constants.ts +3 -0
- package/src/notes/errors.ts +15 -0
- package/src/notes/frontmatter.ts +166 -0
- package/src/notes/fs-error.ts +5 -0
- package/src/notes/identity.ts +40 -0
- package/src/notes/index.ts +24 -0
- package/src/notes/paths.ts +109 -0
- package/src/notes/store.ts +494 -0
- package/src/pi/boot.ts +88 -0
- package/src/pi/budget.ts +178 -0
- package/src/pi/dream/cli.ts +92 -0
- package/src/pi/dream/runner.ts +91 -0
- package/src/pi/dream/settings.ts +17 -0
- package/src/pi/entries.ts +7 -0
- package/src/pi/estimate.ts +116 -0
- package/src/pi/extension.ts +27 -0
- package/src/pi/history-tools.ts +11 -0
- package/src/pi/history.ts +162 -0
- package/src/pi/notes/adapter.ts +33 -0
- package/src/pi/notes/tools.ts +18 -0
- package/src/pi/reset/artifacts.ts +100 -0
- package/src/pi/reset/committed.ts +26 -0
- package/src/pi/reset/lifecycle.ts +342 -0
- package/src/pi/reset/text.ts +10 -0
- package/src/pi/runtime.ts +200 -0
- package/src/pi/session-reader.ts +6 -0
- package/src/pi/thresholds.ts +50 -0
- package/src/pi/tool-names.ts +9 -0
- package/src/pi/tool-result.ts +41 -0
- package/src/pi/window.ts +133 -0
- package/src/settings.ts +22 -0
- package/src/text-match.ts +14 -0
- package/src/tools/history.ts +234 -0
- package/src/tools/notes.ts +381 -0
- package/src/tools/output.ts +41 -0
- package/src/tools/result.ts +144 -0
- package/src/tools/schema.ts +31 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,274 @@
|
|
|
1
|
+
import assert from "node:assert/strict";
|
|
2
|
+
import { mkdtempSync, rmSync } from "node:fs";
|
|
3
|
+
import { tmpdir } from "node:os";
|
|
4
|
+
import { join } from "node:path";
|
|
5
|
+
import test from "node:test";
|
|
6
|
+
import { Type } from "typebox";
|
|
7
|
+
import { Check } from "typebox/value";
|
|
8
|
+
import { loadNotesSnapshot } from "../src/boot/snapshot.js";
|
|
9
|
+
import { renderBootBlock } from "../src/boot/render.js";
|
|
10
|
+
import { HistoryPageItemSchema, HistoryRoleSchema, projectHistory } from "../src/history/history.js";
|
|
11
|
+
import { createNotesStore } from "../src/notes/store.js";
|
|
12
|
+
import { notesWrite, notesUpdate, notesRead } from "../src/tools/notes.js";
|
|
13
|
+
import { historyWindows, historyList, historyRead } from "../src/tools/history.js";
|
|
14
|
+
import { historyRoles } from "../src/tools/schema.js";
|
|
15
|
+
import { MAX_READ_WINDOW_CHARS, TOOL_OUTPUT_MAX_BYTES } from "../src/tools/output.js";
|
|
16
|
+
import { ERROR_MESSAGE_MAX_CHARS, failure, fitsResult, resultSchema, wireResult, readTextWindow, renderOutcome, renderTextWindow, success, structuredBytes, } from "../src/tools/result.js";
|
|
17
|
+
function identity(t) {
|
|
18
|
+
const home = mkdtempSync(join(tmpdir(), "host-neutral-notes-"));
|
|
19
|
+
t.after(() => rmSync(home, { recursive: true, force: true }));
|
|
20
|
+
return { home, sessionId: "explicit-session", projectKey: "explicit-12345678", agent: "explicit-agent", model: "explicit-model" };
|
|
21
|
+
}
|
|
22
|
+
/** The data of a successful outcome, or a failed assertion naming the refusal. */
|
|
23
|
+
function data(result) {
|
|
24
|
+
assert.ok(result.ok, `expected success, got ${result.ok ? "" : JSON.stringify(result.error)}`);
|
|
25
|
+
return result.data;
|
|
26
|
+
}
|
|
27
|
+
/** The refusal of a failed outcome, or a failed assertion naming the data. */
|
|
28
|
+
function refusal(result) {
|
|
29
|
+
assert.ok(!result.ok, `expected a refusal, got success ${JSON.stringify(result.ok ? result.data : null)}`);
|
|
30
|
+
return result.error;
|
|
31
|
+
}
|
|
32
|
+
const makeData = (window) => ({ header: "identity, metadata, cursors, and a footer".repeat(4), window });
|
|
33
|
+
const renderData = (result) => result.ok ? `${result.data.header}\n${renderTextWindow(result.data.window)}` : renderOutcome(result, () => "");
|
|
34
|
+
const read = (text, offset, limit) => readTextWindow(text, offset, limit, makeData, renderData);
|
|
35
|
+
test("shared boot uses only explicit identity, loader, captured time and logical tool bindings", async (t) => {
|
|
36
|
+
const notesIdentity = identity(t);
|
|
37
|
+
const openedAt = 1_700_000_000_000;
|
|
38
|
+
const scopes = [];
|
|
39
|
+
const snapshot = await loadNotesSnapshot(notesIdentity, openedAt, (scope) => {
|
|
40
|
+
scopes.push(scope);
|
|
41
|
+
if (scope === "human")
|
|
42
|
+
throw Object.assign(new Error("unavailable"), { code: "EIO" });
|
|
43
|
+
return scope === "session" ? [{ address: "checkpoint.md", path: "checkpoint.md", scope, body: "😀", sizeBytes: 4, meta: { scope, origin: "self", createdAt: openedAt, updatedAt: openedAt - 60_000, lastAccessed: openedAt, accessCount: 0 } }] : [];
|
|
44
|
+
});
|
|
45
|
+
assert.deepEqual(scopes, ["session", "project", "human", "agent", "model"]);
|
|
46
|
+
assert.equal(snapshot.openedAt, openedAt);
|
|
47
|
+
const tools = { notes: "memo_*", notesList: "memo_list", history: "archive_*", remaining: "room", wipe: "forget" };
|
|
48
|
+
const block = { agentName: notesIdentity.agent, modelName: notesIdentity.model, firstWindowId: "root", currentWindowId: "next", notes: snapshot, tools };
|
|
49
|
+
const rendered = renderBootBlock(block);
|
|
50
|
+
assert.equal(renderBootBlock(block), rendered);
|
|
51
|
+
assert.ok(rendered.includes("😀\n checkpoint.md · 1m ago"), "a feed entry is the note's own first line over its locator");
|
|
52
|
+
assert.ok(rendered.includes("ask `memo_list` to try again"));
|
|
53
|
+
assert.equal(/notes_\*|notes_list|history_\*|history_list|history_read|get_context_remaining|clear_memory/.test(rendered), false);
|
|
54
|
+
});
|
|
55
|
+
test("the shared result module bounds both surfaces and resumes by offset", () => {
|
|
56
|
+
const text = `${"a".repeat(120)}😀${"b".repeat(30)}`;
|
|
57
|
+
const chars = Array.from(text);
|
|
58
|
+
// The requested count stops the read, and the footer says only where to continue.
|
|
59
|
+
const first = data(read(text, 0, 10));
|
|
60
|
+
assert.equal(first.window.text, chars.slice(0, 10).join(""));
|
|
61
|
+
assert.equal(first.window.next_offset_chars, 10);
|
|
62
|
+
assert.equal(first.window.total_chars, chars.length);
|
|
63
|
+
assert.match(renderData(success(first)), /\[truncated; continue at offset_chars=10\]$/);
|
|
64
|
+
// Concatenating windows by their cursors reproduces the source, marker-free.
|
|
65
|
+
const second = data(read(text, first.window.next_offset_chars ?? 0, 10));
|
|
66
|
+
assert.equal(`${first.window.text}${second.window.text}`, chars.slice(0, 20).join(""));
|
|
67
|
+
// A negative offset counts back from the end and reaches a complete window: no footer at all.
|
|
68
|
+
const tail = data(read(text, -4));
|
|
69
|
+
assert.equal(tail.window.text, "bbbb");
|
|
70
|
+
assert.equal(tail.window.next_offset_chars, null);
|
|
71
|
+
assert.equal(renderTextWindow(tail.window), "bbbb");
|
|
72
|
+
// The byte cap, not the requested count, is what stops an oversized read, and the rendered
|
|
73
|
+
// header is counted against the same budget as the payload.
|
|
74
|
+
const huge = "b".repeat(4 * MAX_READ_WINDOW_CHARS);
|
|
75
|
+
const capped = data(read(huge, 0, MAX_READ_WINDOW_CHARS));
|
|
76
|
+
const cappedEnd = capped.window.next_offset_chars ?? 0;
|
|
77
|
+
assert.ok(cappedEnd < MAX_READ_WINDOW_CHARS, "the byte cap cut the requested window short");
|
|
78
|
+
assert.equal(fitsResult(success(capped), renderData), true);
|
|
79
|
+
assert.ok(Buffer.byteLength(renderData(success(capped)), "utf8") <= TOOL_OUTPUT_MAX_BYTES, "the model text fits");
|
|
80
|
+
assert.ok(Buffer.byteLength(JSON.stringify(wireResult(success(capped))), "utf8") <= TOOL_OUTPUT_MAX_BYTES, "the structured outcome fits");
|
|
81
|
+
assert.equal(capped.window.text, huge.slice(0, cappedEnd), "the delivered slice is a verbatim prefix");
|
|
82
|
+
assert.match(renderData(success(capped)), new RegExp(`\\[truncated; continue at offset_chars=${cappedEnd}\\]$`));
|
|
83
|
+
// Code points, not UTF-16 units.
|
|
84
|
+
const emoji = data(read("😀😀😀", 1, 1));
|
|
85
|
+
assert.equal(emoji.window.text, "😀");
|
|
86
|
+
assert.equal(emoji.window.total_chars, 3);
|
|
87
|
+
assert.equal(emoji.window.next_offset_chars, 2);
|
|
88
|
+
// An empty source is a complete, footer-free window rather than a refusal.
|
|
89
|
+
const empty = data(read("", 0, 10));
|
|
90
|
+
assert.equal(empty.window.text, "");
|
|
91
|
+
assert.equal(empty.window.total_chars, 0);
|
|
92
|
+
assert.equal(empty.window.next_offset_chars, null);
|
|
93
|
+
assert.equal(renderOutcome(success(first), () => "model text"), "model text");
|
|
94
|
+
assert.equal(renderOutcome(failure("not_found", "note not found"), () => "never"), "error: not_found: note not found");
|
|
95
|
+
assert.equal(renderOutcome(failure("ambiguous_edit", "edit 0: occurs 2 times"), () => "never"), "error: ambiguous_edit: edit 0: occurs 2 times");
|
|
96
|
+
const schema = resultSchema(Type.Object({ name: Type.String() }));
|
|
97
|
+
assert.equal(Check(schema, wireResult(success({ name: "test" }))), true);
|
|
98
|
+
assert.equal(Check(schema, wireResult(failure("not_found", "missing"))), true);
|
|
99
|
+
assert.equal(Check(schema, { name: 123 }), false);
|
|
100
|
+
assert.equal(Check(schema, success({ name: "test" })), false, "the old success envelope is not the wire contract");
|
|
101
|
+
assert.equal(Check(schema, failure("not_found", "missing")), false, "the old error envelope is not the wire contract");
|
|
102
|
+
});
|
|
103
|
+
test("an envelope that cannot fit is refused rather than resumed forever", () => {
|
|
104
|
+
const text = "c".repeat(1000);
|
|
105
|
+
// An operation whose rendered text is over budget whatever window it delivers.
|
|
106
|
+
const envelope = (header) => ({
|
|
107
|
+
makeData: (window) => ({ header, window }),
|
|
108
|
+
render: (result) => result.ok ? `${result.data.header}\n${renderTextWindow(result.data.window)}` : renderOutcome(result, () => ""),
|
|
109
|
+
});
|
|
110
|
+
const oversized = envelope("h".repeat(2 * TOOL_OUTPUT_MAX_BYTES));
|
|
111
|
+
const refusing = readTextWindow(text, 0, undefined, oversized.makeData, oversized.render);
|
|
112
|
+
const error = refusal(refusing);
|
|
113
|
+
assert.equal(error.code, "output_too_large");
|
|
114
|
+
assert.ok(structuredBytes(wireResult(refusing)) <= TOOL_OUTPUT_MAX_BYTES, "the refusal that replaces an unresumable window is itself bounded");
|
|
115
|
+
assert.equal(fitsResult(refusing, oversized.render), true);
|
|
116
|
+
// Empty text fitting is insufficient when not even one source character can fit.
|
|
117
|
+
const noProgressRender = (result) => result.ok ? "x".repeat(TOOL_OUTPUT_MAX_BYTES) + result.data.window.text : renderOutcome(result, () => "");
|
|
118
|
+
assert.equal(refusal(readTextWindow("😀", 0, 1, makeData, noProgressRender)).code, "output_too_large");
|
|
119
|
+
// At the document end, removing the footer can make the full window fit even though prefixes do not.
|
|
120
|
+
const endFitsRender = (result) => result.ok ? (result.data.window.next_offset_chars === null ? result.data.window.text : "x".repeat(TOOL_OUTPUT_MAX_BYTES + 1)) : renderOutcome(result, () => "");
|
|
121
|
+
assert.equal(data(readTextWindow("abc", 0, 3, makeData, endFitsRender)).window.text, "abc");
|
|
122
|
+
// The same text is delivered normally as soon as the envelope fits.
|
|
123
|
+
const fitting = envelope("ok");
|
|
124
|
+
const delivered = data(readTextWindow(text, 0, undefined, fitting.makeData, fitting.render));
|
|
125
|
+
assert.equal(delivered.window.text, text);
|
|
126
|
+
assert.equal(delivered.window.next_offset_chars, null);
|
|
127
|
+
});
|
|
128
|
+
test("every resumed window advances the cursor and reconstructs the source exactly", () => {
|
|
129
|
+
const text = `${"é".repeat(50)}👨👩👧${"x".repeat(200_000)}\r\n😀${"漢".repeat(1000)}`;
|
|
130
|
+
const chars = Array.from(text);
|
|
131
|
+
assert.notEqual(text.length, chars.length, "the fixture would not catch UTF-16 counting");
|
|
132
|
+
const windows = [];
|
|
133
|
+
for (let offset = 0; offset < chars.length;) {
|
|
134
|
+
const window = data(read(text, offset, MAX_READ_WINDOW_CHARS)).window;
|
|
135
|
+
assert.equal(window.total_chars, chars.length, "one source, one length");
|
|
136
|
+
if (window.next_offset_chars === null) {
|
|
137
|
+
assert.equal(offset + Array.from(window.text).length, window.total_chars, "the last window reaches the true end");
|
|
138
|
+
windows.push(window);
|
|
139
|
+
break;
|
|
140
|
+
}
|
|
141
|
+
assert.ok(window.next_offset_chars > offset, "a window with text left always advances the cursor");
|
|
142
|
+
windows.push(window);
|
|
143
|
+
offset = window.next_offset_chars;
|
|
144
|
+
}
|
|
145
|
+
assert.ok(windows.length > 1, "the fixture needed more than one window");
|
|
146
|
+
assert.equal(windows.map((window) => window.text).join(""), text, "concatenating the windows reproduces the source code point for code point");
|
|
147
|
+
for (const window of windows) {
|
|
148
|
+
assert.ok(structuredBytes(wireResult(success({ window }))) <= TOOL_OUTPUT_MAX_BYTES, "each window fits the structured surface");
|
|
149
|
+
}
|
|
150
|
+
});
|
|
151
|
+
test("window offsets count code points, not UTF-16 units or graphemes", () => {
|
|
152
|
+
const cases = [
|
|
153
|
+
{ name: "astral", text: "😀😀😀", cursor: 1 },
|
|
154
|
+
{ name: "zwj sequence", text: "👨👩👧", cursor: 2 },
|
|
155
|
+
{ name: "combining mark", text: "é", cursor: 1 },
|
|
156
|
+
{ name: "cjk", text: "漢字", cursor: 1 },
|
|
157
|
+
{ name: "crlf", text: "a\r\nb", cursor: 3 },
|
|
158
|
+
{ name: "mixed", text: "a😀b👨👩👧c", cursor: 1 },
|
|
159
|
+
];
|
|
160
|
+
for (const { name, text, cursor } of cases) {
|
|
161
|
+
const chars = Array.from(text);
|
|
162
|
+
const window = data(read(text, cursor, undefined)).window;
|
|
163
|
+
assert.equal(window.total_chars, chars.length, `${name}: totals count code points`);
|
|
164
|
+
assert.equal(window.text, chars.slice(cursor).join(""), `${name}: the slice starts on a code-point boundary`);
|
|
165
|
+
assert.equal(window.text.includes("�"), false, `${name}: no surrogate is split`);
|
|
166
|
+
}
|
|
167
|
+
// Negative offsets resolve from the code-point end, not the byte or unit end.
|
|
168
|
+
const emoji = "😀".repeat(3);
|
|
169
|
+
const tail = data(read(emoji, -1)).window;
|
|
170
|
+
assert.equal(tail.text, "😀");
|
|
171
|
+
assert.equal(tail.next_offset_chars, null);
|
|
172
|
+
});
|
|
173
|
+
test("a runaway refusal message is clipped with its lost length", () => {
|
|
174
|
+
const long = refusal(failure("internal_error", "m".repeat(50_000)));
|
|
175
|
+
assert.ok(Array.from(long.message).length < ERROR_MESSAGE_MAX_CHARS + 40, "a runaway message is clipped with a marker");
|
|
176
|
+
assert.match(long.message, /…\[truncated \d+ chars\]$/, "the clip says how much was dropped");
|
|
177
|
+
assert.ok(structuredBytes(wireResult(failure("internal_error", "m".repeat(50_000)))) <= TOOL_OUTPUT_MAX_BYTES, "even a pathological refusal fits the budget");
|
|
178
|
+
});
|
|
179
|
+
test("structuredBytes has no size for a value with no JSON representation", () => {
|
|
180
|
+
assert.throws(() => structuredBytes(undefined), TypeError, "undefined has no structured size");
|
|
181
|
+
});
|
|
182
|
+
test("shared note operations return canonical outcomes with a body-only read window", async (t) => {
|
|
183
|
+
const notesIdentity = identity(t);
|
|
184
|
+
const written = data(await notesWrite.execute({ address: "@project/test.md", content: "alpha\nbeta" }, notesIdentity));
|
|
185
|
+
assert.equal(written.address, "@project/test.md");
|
|
186
|
+
assert.equal(written.project_key, notesIdentity.projectKey);
|
|
187
|
+
assert.equal(written.outcome, "created");
|
|
188
|
+
const updated = data(await notesUpdate.execute({ address: "@project/test.md", edits: [{ oldText: "alpha", newText: "gamma" }] }, notesIdentity, (change) => {
|
|
189
|
+
assert.equal(change.kind, "body");
|
|
190
|
+
return "caller-rendered-diff";
|
|
191
|
+
}));
|
|
192
|
+
assert.equal(updated.change_kind, "body");
|
|
193
|
+
assert.equal(updated.diff, "caller-rendered-diff");
|
|
194
|
+
// Frontmatter is metadata, not body: the window addresses the body and counts only the body.
|
|
195
|
+
const stored = await createNotesStore(notesIdentity).read("@project/test.md");
|
|
196
|
+
assert.ok(stored, "the note is on disk");
|
|
197
|
+
const body = Array.from(stored.body);
|
|
198
|
+
const read = data(await notesRead.execute({ address: "@project/test.md" }, notesIdentity));
|
|
199
|
+
assert.equal(read.text, stored.body, "a complete read is the whole body and nothing else");
|
|
200
|
+
assert.equal(read.total_chars, body.length);
|
|
201
|
+
assert.equal(read.next_offset_chars, null);
|
|
202
|
+
assert.equal(read.metadata.origin, "self");
|
|
203
|
+
assert.equal(notesRead.render(success(read)).includes("READ WINDOW"), false, "a read presents no metadata block");
|
|
204
|
+
// A negative offset resolves against the body, never against the serialized file.
|
|
205
|
+
const tail = data(await notesRead.execute({ address: "@project/test.md", offset_chars: -4 }, notesIdentity));
|
|
206
|
+
assert.equal(tail.text, body.slice(-4).join(""));
|
|
207
|
+
assert.equal(tail.total_chars, body.length, "metadata length never enters the body cursor");
|
|
208
|
+
assert.equal(tail.next_offset_chars, null);
|
|
209
|
+
assert.equal(refusal(await notesRead.execute({ address: "@project/missing.md" }, notesIdentity)).code, "not_found");
|
|
210
|
+
assert.equal(refusal(await notesWrite.execute({ address: "../escape", content: "x" }, notesIdentity)).code, "invalid_address");
|
|
211
|
+
assert.equal(refusal(await notesRead.execute({ address: "@project/test.md", offset_chars: 99_999 }, notesIdentity)).code, "invalid_offset");
|
|
212
|
+
});
|
|
213
|
+
test("shared history operations read typed events through the addresses the adapter allocated", async () => {
|
|
214
|
+
const projection = projectHistory([{ windowId: "root", items: [
|
|
215
|
+
{ seq: 1, windowId: "root", role: "user", text: "hello there" },
|
|
216
|
+
{ seq: 2, windowId: "root", role: "tool_call", text: "", toolName: "read", toolCallId: "call", arguments: { path: "one.md" } },
|
|
217
|
+
{ seq: 3, windowId: "root", role: "tool", text: "😀 needle output", toolName: "read", toolCallId: "call" },
|
|
218
|
+
] }], 3, new Set([1, 2, 3]));
|
|
219
|
+
const windows = data(await historyWindows.execute({}, projection, "explicit-session"));
|
|
220
|
+
assert.equal(windows.session_id, "explicit-session");
|
|
221
|
+
assert.equal(windows.windows.length, 1);
|
|
222
|
+
assert.deepEqual(windows.windows[0], { window_id: "root", created_at: null, first_seq: 1, last_seq: 2 }, "a call and its result are one event, not two");
|
|
223
|
+
const listed = data(await historyList.execute({ roles: ["tool"] }, projection));
|
|
224
|
+
assert.equal(listed.items.length, 1);
|
|
225
|
+
const item = listed.items[0];
|
|
226
|
+
assert.ok(item && !('folded' in item), "the tool event carries an address");
|
|
227
|
+
const seq = item.seq;
|
|
228
|
+
assert.notEqual(seq, 3, "a paired result address is not an event of its own");
|
|
229
|
+
// A tool event is one typed event whose document carries the call, its arguments, and its result.
|
|
230
|
+
const full = data(await historyRead.execute({ seq }, projection));
|
|
231
|
+
assert.equal(full.seq, seq);
|
|
232
|
+
assert.equal(full.role, "tool");
|
|
233
|
+
assert.match(full.text, /one\.md/, "the document carries the arguments");
|
|
234
|
+
assert.match(full.text, /needle output/, "the document carries the result");
|
|
235
|
+
assert.equal(full.next_offset_chars, null);
|
|
236
|
+
// A query offset addresses that same document, so reading from it resumes inside the result.
|
|
237
|
+
const searched = data(await historyList.execute({ query: "NEEDLE", roles: ["tool"] }, projection));
|
|
238
|
+
assert.equal(searched.items.length, 1);
|
|
239
|
+
const hit = searched.items[0];
|
|
240
|
+
if ("folded" in hit)
|
|
241
|
+
assert.fail("a query returns event rows only");
|
|
242
|
+
assert.equal(hit.seq, seq);
|
|
243
|
+
assert.ok((hit.offset_chars ?? 0) > 0);
|
|
244
|
+
const fromMatch = data(await historyRead.execute({ seq: hit.seq, offset_chars: hit.offset_chars }, projection));
|
|
245
|
+
assert.match(fromMatch.text, /^needle output/, "the match offset lands on the matched text");
|
|
246
|
+
assert.equal(fromMatch.total_chars, full.total_chars, "one document, one length");
|
|
247
|
+
assert.match(refusal(await historyRead.execute({ seq: 9_999 }, projection)).message, /9,?999/, "an unknown address is refused by name");
|
|
248
|
+
assert.equal(refusal(await historyRead.execute({ seq: 3 }, projection)).code, "not_an_event", "a paired result address is refused");
|
|
249
|
+
});
|
|
250
|
+
test("an unknown window_id names at most five known windows in its message", async () => {
|
|
251
|
+
const windows = Array.from({ length: 7 }, (_, index) => ({ windowId: `pcw:w${index}`, items: [{ seq: index + 1, windowId: `pcw:w${index}`, role: "user", text: `message-${index}` }] }));
|
|
252
|
+
const projection = projectHistory(windows, 7, new Set([1, 2, 3, 4, 5, 6, 7]));
|
|
253
|
+
const outcome = await historyList.execute({ window_id: "pcw:absent" }, projection);
|
|
254
|
+
assert.equal(outcome.ok, false);
|
|
255
|
+
if (!outcome.ok) {
|
|
256
|
+
assert.equal(outcome.error.code, "unknown_window_id");
|
|
257
|
+
assert.match(outcome.error.message, /unknown window_id "pcw:absent"; known: pcw:w0, pcw:w1, pcw:w2, pcw:w3, pcw:w4/, "the message names the known windows itself");
|
|
258
|
+
assert.equal(outcome.error.message.includes("pcw:w5"), false, "at most five known windows are named");
|
|
259
|
+
}
|
|
260
|
+
});
|
|
261
|
+
test("one role schema declares the four public roles for the page item, the read payload, and the role filter", () => {
|
|
262
|
+
const read = (role) => ({
|
|
263
|
+
seq: 1, window_id: "root", role, created_at: null,
|
|
264
|
+
text: "", total_chars: 0, next_offset_chars: null,
|
|
265
|
+
});
|
|
266
|
+
assert.equal(HistoryPageItemSchema.properties.role, HistoryRoleSchema, "the page item reuses the authoritative role schema");
|
|
267
|
+
assert.deepEqual(historyRoles().items, HistoryRoleSchema, "the role filter carries the authoritative role schema");
|
|
268
|
+
for (const role of ["user", "assistant", "tool", "context"]) {
|
|
269
|
+
assert.equal(Check(HistoryRoleSchema, role), true, `${role} is a public role`);
|
|
270
|
+
assert.equal(Check(historyRead.outputSchema, read(role)), true, `history_read accepts ${role}`);
|
|
271
|
+
}
|
|
272
|
+
assert.equal(Check(HistoryRoleSchema, "developer"), false, "a role outside the four is refused");
|
|
273
|
+
assert.equal(Check(historyRead.outputSchema, read("developer")), false, "history_read refuses a role outside the four");
|
|
274
|
+
});
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,214 @@
|
|
|
1
|
+
import assert from "node:assert/strict";
|
|
2
|
+
import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
|
3
|
+
import { tmpdir } from "node:os";
|
|
4
|
+
import { join } from "node:path";
|
|
5
|
+
import test from "node:test";
|
|
6
|
+
import { createNotesStore, NoteError } from "../src/notes/index.js";
|
|
7
|
+
function fixture(t) {
|
|
8
|
+
const home = mkdtempSync(join(tmpdir(), "notes-library-"));
|
|
9
|
+
t.after(() => rmSync(home, { recursive: true, force: true }));
|
|
10
|
+
const context = { home, sessionId: "session-a", projectKey: "project-12345678", agent: "root", model: "test-model" };
|
|
11
|
+
return { home, context, notes: createNotesStore(context) };
|
|
12
|
+
}
|
|
13
|
+
test("standalone notes API persists camelCase metadata, edits, lists and searches full results", async (t) => {
|
|
14
|
+
const { home, notes } = fixture(t);
|
|
15
|
+
const first = await notes.write("checkpoint", "alpha\nneedle 😀", { origin: "user" });
|
|
16
|
+
assert.equal(first.meta.project, "project-12345678");
|
|
17
|
+
const read = (await notes.read("checkpoint.md"));
|
|
18
|
+
assert.equal(read.body, "alpha\nneedle 😀");
|
|
19
|
+
assert.equal(read.meta.origin, "user");
|
|
20
|
+
assert.equal(read.meta.accessCount, 1);
|
|
21
|
+
assert.equal(await notes.read("missing.md"), undefined);
|
|
22
|
+
const edited = await notes.update("checkpoint", [{ oldText: "alpha", newText: "beta" }]);
|
|
23
|
+
assert.deepEqual(edited.change, { kind: "body", before: "alpha\nneedle 😀", after: "beta\nneedle 😀" });
|
|
24
|
+
assert.equal(edited.resolvedScope, read.resolvedScope);
|
|
25
|
+
assert.equal(edited.applied, 1);
|
|
26
|
+
const updatedBefore = (await notes.read("checkpoint")).meta.updatedAt;
|
|
27
|
+
const metadataEdit = await notes.update("checkpoint", undefined, { crumpled: true });
|
|
28
|
+
assert.equal(metadataEdit.change.kind, "metadata");
|
|
29
|
+
assert.equal(metadataEdit.change.before.includes("crumpledAt"), false);
|
|
30
|
+
assert.match(metadataEdit.change.after, /\ncrumpledAt: \d{4}-\d{2}-\d{2}T/);
|
|
31
|
+
assert.equal(metadataEdit.change.after.includes("needle"), false, "metadata-only diff excludes body");
|
|
32
|
+
assert.equal((await notes.list()).some((row) => row.address === "checkpoint.md"), false, "a crumpled note leaves the live list");
|
|
33
|
+
assert.equal((await notes.search(["needle"])).length, 0, "search also skips crumpled notes");
|
|
34
|
+
const basket = (await notes.list({ crumpled: true }))[0];
|
|
35
|
+
assert.equal(basket.address, "checkpoint.md");
|
|
36
|
+
assert.ok(basket.meta.crumpledAt);
|
|
37
|
+
assert.equal(basket.meta.updatedAt, updatedBefore, "crumpling does not bump updatedAt");
|
|
38
|
+
const crumpledAt = basket.meta.crumpledAt;
|
|
39
|
+
await notes.update("checkpoint", undefined, { crumpled: true });
|
|
40
|
+
assert.equal((await notes.list({ crumpled: true }))[0]?.meta.crumpledAt, crumpledAt, "re-crumpling keeps the original time");
|
|
41
|
+
await notes.update("checkpoint", undefined, { crumpled: false });
|
|
42
|
+
assert.equal((await notes.list()).some((row) => row.address === "checkpoint.md"), true, "smoothing returns the note to the live list");
|
|
43
|
+
assert.equal((await notes.list({ crumpled: true })).length, 0);
|
|
44
|
+
const matches = await notes.search(["needle"]);
|
|
45
|
+
assert.equal(matches[0]?.matches[0]?.line, 2);
|
|
46
|
+
const body = (await notes.read("checkpoint")).body;
|
|
47
|
+
assert.equal(Array.from(body).slice(matches[0].matches[0].offsetChars).join(""), "needle 😀", "offsets address the body, so they survive the access-counter rewrite a read performs");
|
|
48
|
+
// An existing hand-written extra field and original ownership survive a new caller.
|
|
49
|
+
const path = join(home, "pi/session/session-a/checkpoint.md");
|
|
50
|
+
writeFileSync(path, readFileSync(path, "utf8").replace("\n---\n\n", "\nsourceWindow: pcw:test\nrecurrenceCount: 2\nrecurrenceWindows:\n - pcw:one\n - pcw:two\n__proto__: {\"sentinel\":true}\ncustom: preserved\n---\n\n"));
|
|
51
|
+
const moved = createNotesStore({ home, sessionId: "session-a", projectKey: "other-12345678", agent: "root", model: "test-model" });
|
|
52
|
+
const rewritten = await moved.write("checkpoint", "new body");
|
|
53
|
+
assert.equal(rewritten.meta.createdAt, first.meta.createdAt);
|
|
54
|
+
assert.equal(rewritten.meta.project, "project-12345678");
|
|
55
|
+
assert.equal(rewritten.meta.custom, "preserved");
|
|
56
|
+
assert.deepEqual(rewritten.meta["__proto__"], { sentinel: true });
|
|
57
|
+
assert.deepEqual((await moved.read("checkpoint"))?.meta["__proto__"], { sentinel: true }, "unknown __proto__ metadata survives persistence and reread");
|
|
58
|
+
assert.equal(rewritten.meta.sourceWindow, "pcw:test");
|
|
59
|
+
assert.equal(rewritten.meta.recurrenceCount, 2);
|
|
60
|
+
assert.deepEqual(rewritten.meta.recurrenceWindows, ["pcw:one", "pcw:two"]);
|
|
61
|
+
assert.equal(rewritten.meta.crumpledAt, undefined, "writing always produces an uncrumpled note");
|
|
62
|
+
const combined = await moved.update("checkpoint", [{ oldText: "new", newText: "final" }], { crumpled: true });
|
|
63
|
+
assert.equal(combined.change.kind, "body");
|
|
64
|
+
assert.match(combined.change.after, /\ncrumpledAt: \d{4}-\d{2}-\d{2}T/);
|
|
65
|
+
assert.match(combined.change.after, /final body$/);
|
|
66
|
+
assert.deepEqual((await moved.update("checkpoint", undefined, { crumpled: true })).change, { kind: "none", before: "", after: "" });
|
|
67
|
+
assert.equal((await moved.write("checkpoint", "revived body")).meta.crumpledAt, undefined, "writing a crumpled address smooths it");
|
|
68
|
+
});
|
|
69
|
+
test("same-file read/modify/write operations serialize across stores and markdown aliases", async (t) => {
|
|
70
|
+
const { home, context, notes } = fixture(t);
|
|
71
|
+
const other = createNotesStore(context);
|
|
72
|
+
await notes.write("shared", "alpha\nbeta");
|
|
73
|
+
const firstEdit = notes.update("shared", [{ oldText: "alpha", newText: "A" }]);
|
|
74
|
+
const secondEdit = other.update("shared.md", [{ oldText: "beta", newText: "B" }]);
|
|
75
|
+
await Promise.all([firstEdit, secondEdit]);
|
|
76
|
+
assert.equal((await notes.read("shared"))?.body, "A\nB", "edits through address aliases retain both changes");
|
|
77
|
+
const before = (await notes.read("shared")).meta.accessCount;
|
|
78
|
+
const [readA, readB] = await Promise.all([notes.read("shared.md"), other.read("shared")]);
|
|
79
|
+
assert.ok(readA && readB);
|
|
80
|
+
assert.equal((await notes.list({ scope: "session" }))[0]?.meta.accessCount, before + 2, "parallel reads do not lose access-counter updates");
|
|
81
|
+
const file = join(home, "pi/session/session-a/shared.md");
|
|
82
|
+
const stableEdits = [{ oldText: "A", newText: "first" }];
|
|
83
|
+
const operation = notes.update("shared", stableEdits);
|
|
84
|
+
stableEdits[0].newText = "mutated after call";
|
|
85
|
+
await operation;
|
|
86
|
+
assert.equal((await notes.read("shared"))?.body, "first\nB", "edit arguments are snapshotted at method entry");
|
|
87
|
+
assert.equal(readFileSync(file, "utf8").includes("mutated after call"), false);
|
|
88
|
+
});
|
|
89
|
+
test("stores snapshot explicit identity and do not leak homes across instances", async (t) => {
|
|
90
|
+
const { home, context } = fixture(t);
|
|
91
|
+
const mutable = { ...context };
|
|
92
|
+
const notes = createNotesStore(mutable);
|
|
93
|
+
const other = createNotesStore({ ...context, home: join(home, "other"), agent: "other-agent", model: "other-model" });
|
|
94
|
+
assert.equal(existsSync(join(home, "other")), false, "construction does not create the supplied home");
|
|
95
|
+
mutable.agent = "changed-after-construction";
|
|
96
|
+
await notes.write("@self/private", "first");
|
|
97
|
+
await other.write("@self/private", "second");
|
|
98
|
+
assert.equal((await notes.read("@self/private"))?.body, "first");
|
|
99
|
+
assert.equal((await other.read("@self/private"))?.body, "second");
|
|
100
|
+
assert.equal((await notes.list())[0]?.address, "@self/private.md");
|
|
101
|
+
assert.equal((await other.list())[0]?.address, "@self/private.md");
|
|
102
|
+
mkdirSync(join(home, "agents/visitor"), { recursive: true });
|
|
103
|
+
writeFileSync(join(home, "agents/visitor/hello.md"), "visiting");
|
|
104
|
+
assert.equal((await notes.read("@agents/visitor/hello"))?.body, "visiting");
|
|
105
|
+
await assert.rejects(() => notes.write("@agents/visitor/hello", "overwrite"), (error) => error instanceof NoteError && error.code === "invalid_scope");
|
|
106
|
+
});
|
|
107
|
+
test("list and search share scoped glob scans and search offsets count Unicode code points", async (t) => {
|
|
108
|
+
const { notes } = fixture(t);
|
|
109
|
+
await notes.write("shared.md", "😀 needle in session");
|
|
110
|
+
await notes.write("@project/shared.md", "needle in project");
|
|
111
|
+
await notes.write("@human/shared.md", "needle in human");
|
|
112
|
+
await notes.write("@project/elsewhere.md", "unrelated");
|
|
113
|
+
const glob = "**/shared.md";
|
|
114
|
+
const listed = await notes.list({ glob });
|
|
115
|
+
const searched = await notes.search(["needle"], { glob });
|
|
116
|
+
const listedAddresses = listed.map((row) => row.address).sort();
|
|
117
|
+
const searchedAddresses = searched.map((row) => row.address).sort();
|
|
118
|
+
assert.deepEqual(searchedAddresses, ["@human/shared.md", "@project/shared.md", "shared.md"]);
|
|
119
|
+
assert.deepEqual(searchedAddresses, listedAddresses, "list and search traverse the same filtered homes and files");
|
|
120
|
+
const sessionMatch = searched.find((row) => row.address === "shared.md").matches[0];
|
|
121
|
+
const body = (await notes.read("shared.md")).body;
|
|
122
|
+
assert.equal(body, "😀 needle in session");
|
|
123
|
+
assert.equal(Array.from(body).slice(sessionMatch.offsetChars).join(""), "needle in session", "the body offset counts the emoji as one code point and lands on the match");
|
|
124
|
+
});
|
|
125
|
+
test("search offsets address the body and never move when access metadata grows", async (t) => {
|
|
126
|
+
const { notes } = fixture(t);
|
|
127
|
+
await notes.write("counted.md", "needle here");
|
|
128
|
+
const offsetOf = async () => (await notes.search(["needle"])).find((row) => row.address === "counted.md").matches[0].offsetChars;
|
|
129
|
+
assert.equal(await offsetOf(), 0, "a match at the first body character has body offset 0");
|
|
130
|
+
// Walk the access counter across a digit boundary; an offset into the serialized file
|
|
131
|
+
// would shift by one character here, because the rewrite adds a digit to the frontmatter.
|
|
132
|
+
for (let read = 0; read < 12; read++)
|
|
133
|
+
await notes.read("counted.md");
|
|
134
|
+
assert.equal((await notes.list({ scope: "session" })).find((row) => row.address === "counted.md").meta.accessCount, 12);
|
|
135
|
+
assert.equal(await offsetOf(), 0, "reads that rewrite access metadata do not move the match");
|
|
136
|
+
await notes.write("front.md", `---\nbig: ${"x".repeat(200)}\n---\n\nneedle later`);
|
|
137
|
+
const frontMatch = (await notes.search(["needle"])).find((row) => row.address === "front.md").matches[0];
|
|
138
|
+
const frontBody = (await notes.read("front.md")).body;
|
|
139
|
+
assert.equal(frontBody, "needle later");
|
|
140
|
+
assert.equal(frontMatch.offsetChars, 0, "frontmatter length is not part of the body offset");
|
|
141
|
+
assert.equal(Array.from(frontBody).slice(frontMatch.offsetChars).join(""), "needle later");
|
|
142
|
+
assert.deepEqual(Object.keys((await notes.read("counted.md"))).sort(), ["body", "meta", "resolvedScope"], "a read exposes metadata and the body, never a serialized rendering");
|
|
143
|
+
});
|
|
144
|
+
test("invalid addressing and failed edits leave stored bytes untouched without poisoning the queue", async (t) => {
|
|
145
|
+
const { home, context, notes } = fixture(t);
|
|
146
|
+
assert.throws(() => createNotesStore({ ...context, sessionId: "../escape" }));
|
|
147
|
+
await assert.rejects(() => notes.write("@project/../escape", "bad"), (error) => error instanceof NoteError && error.code === "invalid_address");
|
|
148
|
+
await assert.rejects(() => notes.list({ scope: "agent", who: "../escape" }));
|
|
149
|
+
// The typed API disallows this; JavaScript callers must still receive a refusal.
|
|
150
|
+
// @ts-expect-error who cannot accompany project scope
|
|
151
|
+
await assert.rejects(() => notes.list({ scope: "project", who: "root" }), (error) => error instanceof NoteError && error.code === "invalid_scope");
|
|
152
|
+
await notes.write("edit", "alpha\nbeta\nbeta");
|
|
153
|
+
const path = join(home, "pi/session/session-a/edit.md");
|
|
154
|
+
const before = readFileSync(path, "utf8");
|
|
155
|
+
await assert.rejects(() => notes.update("edit", [{ oldText: "beta", newText: "B" }]), (error) => error instanceof NoteError && error.code === "ambiguous_edit" && error.lineNumbers?.join(",") === "2,3");
|
|
156
|
+
await assert.rejects(() => notes.update("edit", [{ oldText: "alpha", newText: "A" }, { oldText: "absent", newText: "X" }]), (error) => error instanceof NoteError && error.code === "no_match" && error.editIndex === 1);
|
|
157
|
+
assert.equal(readFileSync(path, "utf8"), before);
|
|
158
|
+
await assert.rejects(() => notes.update("absent", undefined, { crumpled: true }), (error) => error instanceof NoteError && error.code === "not_found");
|
|
159
|
+
await notes.update("edit", [{ oldText: "alpha", newText: "A" }]);
|
|
160
|
+
assert.equal((await notes.read("edit"))?.body, "A\nbeta\nbeta", "failed operations do not poison later queue work");
|
|
161
|
+
});
|
|
162
|
+
test("rename moves a note with metadata intact across scopes and refuses live targets", async (t) => {
|
|
163
|
+
const { context, notes } = fixture(t);
|
|
164
|
+
const written = await notes.write("old-name", "body text", { origin: "user" });
|
|
165
|
+
await notes.read("old-name.md");
|
|
166
|
+
const moved = await notes.rename("old-name.md", "@project/new-name.md");
|
|
167
|
+
assert.equal(moved.meta.createdAt, written.meta.createdAt, "createdAt survives the move");
|
|
168
|
+
assert.equal(moved.meta.origin, "user");
|
|
169
|
+
assert.equal(moved.meta.accessCount, 1, "accessCount survives the move");
|
|
170
|
+
assert.ok(moved.meta.updatedAt >= written.meta.updatedAt, "updatedAt is bumped");
|
|
171
|
+
assert.equal(moved.meta.project, undefined, "leaving the session scope drops project ownership");
|
|
172
|
+
assert.equal(moved.replacedCrumpledTarget, false);
|
|
173
|
+
assert.equal(await notes.read("old-name.md"), undefined, "the old address is gone");
|
|
174
|
+
assert.equal((await notes.read("@project/new-name.md"))?.body, "body text");
|
|
175
|
+
const back = await notes.rename("@project/new-name.md", "back.md");
|
|
176
|
+
assert.equal(back.meta.project, context.projectKey, "entering the session scope stamps current project ownership");
|
|
177
|
+
assert.equal((await notes.read("back.md"))?.meta.createdAt, written.meta.createdAt);
|
|
178
|
+
const within = await notes.rename("back.md", "still-back.md");
|
|
179
|
+
assert.equal(within.meta.project, context.projectKey, "a same-scope rename keeps project ownership untouched");
|
|
180
|
+
await notes.write("occupied", "live target");
|
|
181
|
+
await assert.rejects(() => notes.rename("still-back.md", "occupied.md"), (error) => error instanceof NoteError && error.code === "already_exists");
|
|
182
|
+
await notes.update("occupied", undefined, { crumpled: true });
|
|
183
|
+
const replaced = await notes.rename("still-back.md", "occupied.md");
|
|
184
|
+
assert.equal(replaced.replacedCrumpledTarget, true, "a crumpled target is replaced");
|
|
185
|
+
assert.equal((await notes.read("occupied.md"))?.meta.createdAt, written.meta.createdAt, "the moved note keeps its identity, not the target's");
|
|
186
|
+
await assert.rejects(() => notes.rename("occupied", "occupied.md"), (error) => error instanceof NoteError && error.code === "nothing_to_do");
|
|
187
|
+
await assert.rejects(() => notes.rename("occupied.md", "@models/other-model/stolen.md"), (error) => error instanceof NoteError && error.code === "invalid_scope");
|
|
188
|
+
await assert.rejects(() => notes.rename("@agents/someone-else/private.md", "mine.md"), (error) => error instanceof NoteError && error.code === "invalid_scope");
|
|
189
|
+
await assert.rejects(() => notes.rename("absent.md", "anywhere.md"), (error) => error instanceof NoteError && error.code === "not_found");
|
|
190
|
+
});
|
|
191
|
+
test("ambiguous multiline anchors report each starting line", async (t) => {
|
|
192
|
+
const { notes } = fixture(t);
|
|
193
|
+
await notes.write("multiline", "a\nb\na\nb\na\nb");
|
|
194
|
+
await assert.rejects(() => notes.update("multiline", [{ oldText: "a\nb", newText: "x" }]), (error) => {
|
|
195
|
+
assert.ok(error instanceof NoteError);
|
|
196
|
+
assert.deepEqual(error.lineNumbers, [1, 3, 5]);
|
|
197
|
+
return true;
|
|
198
|
+
});
|
|
199
|
+
});
|
|
200
|
+
test("a massively ambiguous edit still reports every match line to a library caller", async (t) => {
|
|
201
|
+
const { notes } = fixture(t);
|
|
202
|
+
await notes.write("many", `${"beta\n".repeat(2000)}end`);
|
|
203
|
+
await assert.rejects(() => notes.update("many", [{ oldText: "beta", newText: "B" }]), (error) => {
|
|
204
|
+
assert.ok(error instanceof NoteError);
|
|
205
|
+
assert.equal(error.code, "ambiguous_edit");
|
|
206
|
+
assert.equal(error.lineNumbers?.length, 2000, "the domain keeps every match line rather than a sample");
|
|
207
|
+
assert.deepEqual(error.lineNumbers?.slice(0, 3), [1, 2, 3]);
|
|
208
|
+
assert.equal(error.lineNumbers?.[1999], 2000);
|
|
209
|
+
assert.match(error.message, /occurs 2000 times \(lines 1, 2, 3, 4, 5, 6, 7, 8, and 1992 more\)/, "the message names the exact total and a bounded sample");
|
|
210
|
+
assert.ok(Buffer.byteLength(error.message, "utf8") < 300, "the message stays small however many lines matched");
|
|
211
|
+
return true;
|
|
212
|
+
});
|
|
213
|
+
assert.equal((await notes.read("many"))?.body.startsWith("beta\nbeta"), true, "the refused edit left the body alone");
|
|
214
|
+
});
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|