notesoup 0.51.8 → 0.52.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (78) hide show
  1. package/README.md +3 -10
  2. package/dist/plugins/claude/src/history.js +3 -7
  3. package/dist/plugins/pi/notes/tools.d.ts +1 -1
  4. package/dist/plugins/pi/notes/tools.js +27 -7
  5. package/dist/plugins/pi/render.d.ts +40 -0
  6. package/dist/plugins/pi/render.js +168 -0
  7. package/dist/plugins/pi/runtime.js +3 -0
  8. package/dist/plugins/pi/tool-result.d.ts +5 -2
  9. package/dist/plugins/pi/tool-result.js +4 -1
  10. package/dist/src/dream/git.d.ts +2 -3
  11. package/dist/src/dream/git.js +3 -8
  12. package/dist/src/dream/lock.d.ts +10 -27
  13. package/dist/src/dream/lock.js +16 -79
  14. package/dist/src/notes/errors.d.ts +1 -1
  15. package/dist/src/notes/identity.d.ts +2 -0
  16. package/dist/src/notes/identity.js +3 -1
  17. package/dist/src/notes/store.d.ts +2 -0
  18. package/dist/src/notes/store.js +40 -4
  19. package/dist/src/tools/dream.d.ts +113 -0
  20. package/dist/src/tools/dream.js +112 -0
  21. package/dist/src/tools/notes.d.ts +15 -1
  22. package/dist/src/tools/notes.js +4 -4
  23. package/dist/test/claude-history.test.js +18 -2
  24. package/dist/test/claude-mod.test.js +115 -30
  25. package/dist/test/dependencies.test.js +3 -6
  26. package/dist/test/dream-skill.test.js +2 -3
  27. package/dist/test/dream-tools.test.js +67 -0
  28. package/dist/test/pi-render.test.js +89 -0
  29. package/docs/claude-code-mod.md +1 -1
  30. package/docs/notes-library.md +1 -1
  31. package/docs/skills.md +12 -15
  32. package/package.json +151 -149
  33. package/plugins/claude/.claude-plugin/plugin.json +1 -1
  34. package/plugins/claude/dist/claude/helper.js +30 -22
  35. package/plugins/claude/hooks/register.ts +52 -33
  36. package/plugins/claude/src/history.ts +3 -6
  37. package/plugins/pi/notes/tools.ts +26 -8
  38. package/plugins/pi/render.ts +165 -0
  39. package/plugins/pi/runtime.ts +3 -0
  40. package/plugins/pi/tool-result.ts +9 -1
  41. package/src/dream/git.ts +3 -8
  42. package/src/dream/lock.ts +18 -66
  43. package/src/notes/errors.ts +1 -1
  44. package/src/notes/identity.ts +4 -1
  45. package/src/notes/store.ts +37 -4
  46. package/src/tools/dream.ts +112 -0
  47. package/src/tools/notes.ts +4 -4
  48. package/dist/plugins/pi/dream/cli.d.ts +0 -10
  49. package/dist/plugins/pi/dream/cli.js +0 -173
  50. package/dist/plugins/pi/dream/runner.d.ts +0 -27
  51. package/dist/plugins/pi/dream/runner.js +0 -91
  52. package/dist/plugins/pi/dream/settings.d.ts +0 -7
  53. package/dist/plugins/pi/dream/settings.js +0 -17
  54. package/dist/src/dream/doctor.d.ts +0 -2
  55. package/dist/src/dream/doctor.js +0 -161
  56. package/dist/src/dream/gates.d.ts +0 -10
  57. package/dist/src/dream/gates.js +0 -26
  58. package/dist/src/dream/jail.d.ts +0 -11
  59. package/dist/src/dream/jail.js +0 -71
  60. package/dist/src/dream/report.d.ts +0 -7
  61. package/dist/src/dream/report.js +0 -34
  62. package/dist/src/dream/result.d.ts +0 -9
  63. package/dist/src/dream/settings.d.ts +0 -9
  64. package/dist/src/dream/settings.js +0 -16
  65. package/dist/test/doctor.test.js +0 -37
  66. package/dist/test/dream.test.d.ts +0 -1
  67. package/dist/test/dream.test.js +0 -150
  68. package/plugins/pi/dream/cli.ts +0 -118
  69. package/plugins/pi/dream/runner.ts +0 -92
  70. package/plugins/pi/dream/settings.ts +0 -17
  71. package/src/dream/doctor.ts +0 -118
  72. package/src/dream/gates.ts +0 -26
  73. package/src/dream/jail.ts +0 -62
  74. package/src/dream/report.ts +0 -32
  75. package/src/dream/result.ts +0 -2
  76. package/src/dream/settings.ts +0 -19
  77. /package/dist/{src/dream/result.js → test/dream-tools.test.d.ts} +0 -0
  78. /package/dist/test/{doctor.test.d.ts → pi-render.test.d.ts} +0 -0
@@ -1,5 +1,5 @@
1
1
  import { randomUUID } from "node:crypto";
2
- import { mkdir, readdir, readFile, realpath, rename, rm, writeFile } from "node:fs/promises";
2
+ import { mkdir, readdir, readFile, realpath, rename, rm, unlink, writeFile } from "node:fs/promises";
3
3
  import { dirname, join, resolve } from "node:path";
4
4
  import { earliestMatchOffsetChars } from "../text-match.js";
5
5
  import { assertAddress, assertGlobPattern, addressFor, canonicalAddressFor, globToRegExp, HOME_HEADS } from "./address.js";
@@ -218,10 +218,13 @@ function assertSerializedSize(content) {
218
218
  function frontmatterOf(meta) {
219
219
  return serializeNote(meta, "").slice(0, -2);
220
220
  }
221
- /** Explicit session/project homes are always read-only; agent/model homes allow their owner. */
221
+ /** Explicit session/project homes are read-only unless dreamed over; agent/model homes allow their owner. */
222
222
  function assertWritableHome(scope, who, identity) {
223
223
  if (who === undefined)
224
224
  return;
225
+ // A dreamed project is writable whole; its other sessions are checked per note by assertDreamSessionNote.
226
+ if (identity.dreaming !== undefined && (scope === "session" || (scope === "project" && who === identity.dreaming)))
227
+ return;
225
228
  if (scope === "session")
226
229
  throw new NoteError("invalid_scope", `@sessions/${who}/ is read-only; use a bare path to write to this session.`);
227
230
  if (scope === "project")
@@ -232,6 +235,16 @@ function assertWritableHome(scope, who, identity) {
232
235
  const home = scope === "agent" ? `@agents/${who}/` : `@models/${who}/`;
233
236
  throw new NoteError("invalid_scope", `${home} is someone else's home; you can write to this session, @project/, @human/, @self/, or @model/.`);
234
237
  }
238
+ /** A dream reaches another session's note only when that note was born in the dreamed project. */
239
+ function assertDreamSessionNote(scope, who, identity, raw, address) {
240
+ if (scope !== "session" || who === undefined || identity.dreaming === undefined)
241
+ return;
242
+ if (raw !== undefined && parseNote(raw).meta.project === identity.dreaming)
243
+ return;
244
+ throw new NoteError("invalid_scope", raw === undefined
245
+ ? `${address}: a dream edits other sessions' existing notes, it doesn't create new ones there.`
246
+ : `${address} belongs to another project, not the one being dreamed over (${identity.dreaming}).`);
247
+ }
235
248
  /** Create a store over one validated, immutable snapshot of the supplied explicit identity. */
236
249
  export function createNotesStore(input) {
237
250
  const identity = snapshotNotesIdentity(input);
@@ -249,6 +262,7 @@ export function createNotesStore(input) {
249
262
  const now = writeStamp();
250
263
  const cleanBody = stripLeadingFrontmatter(content);
251
264
  const existingRaw = await readFileIfExists(path);
265
+ assertDreamSessionNote(scope, destination.who, identity, existingRaw, address);
252
266
  const existing = existingRaw === undefined ? undefined : parseNote(existingRaw, now).meta;
253
267
  const outcome = existing === undefined ? "created" : existing.crumpledAt === undefined ? "overwrote" : "uncrumpled";
254
268
  const meta = existing ?? {
@@ -281,7 +295,8 @@ export function createNotesStore(input) {
281
295
  return undefined;
282
296
  const now = Date.now();
283
297
  const parsed = parseNote(raw, now);
284
- if ((scope === "project" || scope === "session") && destination.who !== undefined)
298
+ // Named homes, and every read during a dream, leave no access stamp.
299
+ if (identity.dreaming !== undefined || ((scope === "project" || scope === "session") && destination.who !== undefined))
285
300
  return { meta: { ...parsed.meta, scope }, body: parsed.body, resolvedScope: scope };
286
301
  // A read records its own access, exactly as a write records an edit.
287
302
  const meta = { ...parsed.meta, scope, lastAccessed: now, accessCount: (typeof parsed.meta.accessCount === "number" ? parsed.meta.accessCount : 0) + 1 };
@@ -309,6 +324,9 @@ export function createNotesStore(input) {
309
324
  if (raw === undefined)
310
325
  throw new NoteError("not_found", `No note at ${noteIdentity(identity, address).address}.`);
311
326
  const targetRaw = differentPaths ? await readFileIfExists(path) : undefined;
327
+ assertDreamSessionNote(from.scope, from.who, identity, raw, address);
328
+ if (differentPaths)
329
+ assertDreamSessionNote(scope, destination.who, identity, targetRaw, stableOptions.renameTo);
312
330
  // Case and symlink aliases must not turn write-then-remove into deleting the result.
313
331
  const sourceReal = targetRaw === undefined ? undefined : await realpath(fromPath);
314
332
  const sameFile = sourceReal !== undefined && sourceReal === await realpath(path);
@@ -388,6 +406,24 @@ export function createNotesStore(input) {
388
406
  const { meta, replacedCrumpledTarget } = await update(fromAddress, undefined, { renameTo: toAddress });
389
407
  return { meta, replacedCrumpledTarget };
390
408
  }
409
+ async function forget(address) {
410
+ if (identity.dreaming === undefined)
411
+ throw new NoteError("invalid_scope", "Only a dream can delete notes; begin one first.");
412
+ const target = assertAddress(address);
413
+ assertWritableHome(target.scope, target.who, identity);
414
+ const path = physicalPath(target.scope, target.path, identity, target.who);
415
+ return withPathQueue(path, async () => {
416
+ const raw = await readFileIfExists(path);
417
+ if (raw === undefined)
418
+ throw new NoteError("not_found", `No note at ${noteIdentity(identity, address).address}.`);
419
+ assertDreamSessionNote(target.scope, target.who, identity, raw, address);
420
+ const { meta } = parseNote(raw);
421
+ if (meta.crumpledAt === undefined)
422
+ throw new NoteError("not_crumpled", `${noteIdentity(identity, address).address} isn't crumpled; crumple it before deleting.`);
423
+ await unlink(path);
424
+ return { ...meta, scope: target.scope };
425
+ });
426
+ }
391
427
  async function* scan(options, status) {
392
428
  const glob = assertGlobPattern(options.glob);
393
429
  const pattern = glob === "@default" ? undefined : glob;
@@ -480,5 +516,5 @@ export function createNotesStore(input) {
480
516
  function searchWithStatus(queries, options = {}) {
481
517
  return searchRows(queries, options, { homesUnavailable: [] });
482
518
  }
483
- return { write, read, update, rename, list, search, listWithStatus, searchWithStatus };
519
+ return { write, read, update, rename, forget, list, search, listWithStatus, searchWithStatus };
484
520
  }
@@ -0,0 +1,113 @@
1
+ /** Dream operations: open one project's notes for consolidation, delete crumpled notes, close. */
2
+ import { Type, type Static } from "typebox";
3
+ import { type NotesIdentity } from "../notes/index.js";
4
+ import { type DreamLock } from "../dream/lock.js";
5
+ import { type Outcome } from "./result.js";
6
+ /** The one open dream per session; the host owns where it lives. */
7
+ export type DreamState = {
8
+ project?: string;
9
+ lock?: DreamLock;
10
+ };
11
+ /** Drop an open dream without an end commit, e.g. when its session shuts down. */
12
+ export declare function abandonDream(state: DreamState): void;
13
+ /** The identity a store uses while `state` holds an open dream. */
14
+ export declare function dreamingIdentity(identity: NotesIdentity, state: DreamState): NotesIdentity;
15
+ export declare const dreamBeginParameters: Type.TObject<{
16
+ project: Type.TOptional<Type.TString>;
17
+ }>;
18
+ export declare const DreamBeginDataSchema: Type.TObject<{
19
+ more: Type.TInteger;
20
+ homes_unavailable: Type.TArray<Type.TString>;
21
+ files: Type.TArray<Type.TObject<{
22
+ updated_at: Type.TString;
23
+ crumpled_at: Type.TOptional<Type.TString>;
24
+ project_root: Type.TOptional<Type.TString>;
25
+ project_siblings: Type.TOptional<Type.TArray<Type.TObject<{
26
+ name: Type.TString;
27
+ path: Type.TString;
28
+ }>>>;
29
+ address: Type.TString;
30
+ project_key: Type.TOptional<Type.TString>;
31
+ }>>;
32
+ project: Type.TString;
33
+ baseline: Type.TString;
34
+ }>;
35
+ export type DreamBeginData = Static<typeof DreamBeginDataSchema>;
36
+ export declare const dreamBegin: {
37
+ readonly name: "dream_begin";
38
+ readonly label: "Dream begin";
39
+ readonly description: "Dream: open one project's notes for consolidation, one project at a time. Lists its @projects/<name>/ notes and every session note born in it, crumpled ones included. Until dream_end, notes_write/notes_update can edit those addresses and reads leave no access stamp. Takes the project's dream lock and commits a Git baseline of the notes home.";
40
+ readonly parameters: Type.TObject<{
41
+ project: Type.TOptional<Type.TString>;
42
+ }>;
43
+ readonly outputSchema: Type.TUnion<[Type.TObject<{
44
+ more: Type.TInteger;
45
+ homes_unavailable: Type.TArray<Type.TString>;
46
+ files: Type.TArray<Type.TObject<{
47
+ updated_at: Type.TString;
48
+ crumpled_at: Type.TOptional<Type.TString>;
49
+ project_root: Type.TOptional<Type.TString>;
50
+ project_siblings: Type.TOptional<Type.TArray<Type.TObject<{
51
+ name: Type.TString;
52
+ path: Type.TString;
53
+ }>>>;
54
+ address: Type.TString;
55
+ project_key: Type.TOptional<Type.TString>;
56
+ }>>;
57
+ project: Type.TString;
58
+ baseline: Type.TString;
59
+ }>, Type.TObject<{
60
+ error: Type.TString;
61
+ code: Type.TString;
62
+ }>]>;
63
+ readonly execute: (params: Static<typeof dreamBeginParameters>, identity: NotesIdentity, state: DreamState) => Promise<Outcome<DreamBeginData>>;
64
+ readonly render: (result: Outcome<DreamBeginData>) => string;
65
+ };
66
+ export declare const dreamForgetParameters: Type.TObject<{
67
+ address: Type.TString;
68
+ }>;
69
+ export declare const DreamForgetDataSchema: Type.TObject<{
70
+ address: Type.TString;
71
+ project_key: Type.TOptional<Type.TString>;
72
+ }>;
73
+ export type DreamForgetData = Static<typeof DreamForgetDataSchema>;
74
+ export declare const dreamForget: {
75
+ readonly name: "dream_forget";
76
+ readonly label: "Dream forget";
77
+ readonly description: "Dream: permanently delete one crumpled note in the project being dreamed over, or in @human/, @self/, @model/. Crumple it first; live notes refuse.";
78
+ readonly parameters: Type.TObject<{
79
+ address: Type.TString;
80
+ }>;
81
+ readonly outputSchema: Type.TUnion<[Type.TObject<{
82
+ address: Type.TString;
83
+ project_key: Type.TOptional<Type.TString>;
84
+ }>, Type.TObject<{
85
+ error: Type.TString;
86
+ code: Type.TString;
87
+ }>]>;
88
+ readonly execute: (params: Static<typeof dreamForgetParameters>, identity: NotesIdentity, state: DreamState) => Promise<Outcome<DreamForgetData>>;
89
+ readonly render: (result: Outcome<DreamForgetData>) => string;
90
+ };
91
+ export declare const dreamEndParameters: Type.TObject<{}>;
92
+ export declare const DreamEndDataSchema: Type.TObject<{
93
+ project: Type.TString;
94
+ commit: Type.TOptional<Type.TString>;
95
+ audit_error: Type.TOptional<Type.TString>;
96
+ }>;
97
+ export type DreamEndData = Static<typeof DreamEndDataSchema>;
98
+ export declare const dreamEnd: {
99
+ readonly name: "dream_end";
100
+ readonly label: "Dream end";
101
+ readonly description: "Dream: close the open dream. Commits the dream's changes to the notes home's Git and releases the lock; the project's notes are read-only again and reads stamp access again.";
102
+ readonly parameters: Type.TObject<{}>;
103
+ readonly outputSchema: Type.TUnion<[Type.TObject<{
104
+ project: Type.TString;
105
+ commit: Type.TOptional<Type.TString>;
106
+ audit_error: Type.TOptional<Type.TString>;
107
+ }>, Type.TObject<{
108
+ error: Type.TString;
109
+ code: Type.TString;
110
+ }>]>;
111
+ readonly execute: (_params: Static<typeof dreamEndParameters>, identity: NotesIdentity, state: DreamState) => Promise<Outcome<DreamEndData>>;
112
+ readonly render: (result: Outcome<DreamEndData>) => string;
113
+ };
@@ -0,0 +1,112 @@
1
+ /** Dream operations: open one project's notes for consolidation, delete crumpled notes, close. */
2
+ import { Type } from "typebox";
3
+ import { createNotesStore, noteIdentity } from "../notes/index.js";
4
+ import { projectHomes } from "../notes/project-home.js";
5
+ import { gitCommit } from "../dream/git.js";
6
+ import { acquireDreamLock, dreamLockPath, releaseDreamLock } from "../dream/lock.js";
7
+ import { failure, renderOutcome, resultSchema, success } from "./result.js";
8
+ import { failureOf, listedFile, NotesListDataSchema, renderListData, snapshot } from "./notes.js";
9
+ /** Drop an open dream without an end commit, e.g. when its session shuts down. */
10
+ export function abandonDream(state) {
11
+ if (state.lock)
12
+ releaseDreamLock(state.lock);
13
+ delete state.project;
14
+ delete state.lock;
15
+ }
16
+ /** The identity a store uses while `state` holds an open dream. */
17
+ export function dreamingIdentity(identity, state) {
18
+ return state.project === undefined ? identity : { ...identity, dreaming: state.project };
19
+ }
20
+ const NOT_DREAMING = "No dream is open; call dream_begin first.";
21
+ export const dreamBeginParameters = Type.Object({
22
+ project: Type.Optional(Type.String({ description: "(optional, default this project) Project name, as in @projects/<name>/." })),
23
+ }, { additionalProperties: false });
24
+ export const DreamBeginDataSchema = Type.Object({ project: Type.String(), baseline: Type.String(), ...NotesListDataSchema.properties }, { additionalProperties: false });
25
+ function renderBeginData(data) {
26
+ return `dreaming over ${data.project} (baseline ${data.baseline})\n${renderListData(data)}`;
27
+ }
28
+ export const dreamBegin = {
29
+ name: "dream_begin", label: "Dream begin",
30
+ description: "Dream: open one project's notes for consolidation, one project at a time. Lists its @projects/<name>/ notes and every session note born in it, crumpled ones included. Until dream_end, notes_write/notes_update can edit those addresses and reads leave no access stamp. Takes the project's dream lock and commits a Git baseline of the notes home.",
31
+ parameters: dreamBeginParameters, outputSchema: resultSchema(DreamBeginDataSchema),
32
+ async execute(params, identity, state) {
33
+ if (state.project !== undefined)
34
+ return failure("already_dreaming", `Already dreaming over ${state.project}; call dream_end before opening another project.`);
35
+ const project = params.project ?? identity.projectKey;
36
+ if (project !== identity.projectKey && !projectHomes(identity.home).some(home => home.name === project)) {
37
+ return failure("not_found", `No project named ${JSON.stringify(project)}; notes_list with glob @projects/*/** shows the names.`);
38
+ }
39
+ const lock = acquireDreamLock(dreamLockPath(identity.home, project));
40
+ if (!lock)
41
+ return failure("already_dreaming", `Another dream holds ${dreamLockPath(identity.home, project)}. If none is running, delete that file by hand.`);
42
+ try {
43
+ const store = createNotesStore({ ...identity, dreaming: project });
44
+ const rows = [];
45
+ const unavailable = [];
46
+ for (const crumpled of [false, true]) {
47
+ for (const glob of [`@projects/${project}/**`, "@sessions/*/**"]) {
48
+ const result = await store.listWithStatus({ glob, crumpled });
49
+ rows.push(...result.rows.filter(row => row.scope === "project" || row.meta.project === project));
50
+ unavailable.push(...result.status.homesUnavailable);
51
+ }
52
+ }
53
+ rows.sort((a, b) => b.meta.updatedAt - a.meta.updatedAt || a.address.localeCompare(b.address));
54
+ const listed = snapshot(rows.map(row => listedFile(row, identity)), undefined, { homesUnavailable: unavailable }, renderListData);
55
+ if (!listed.ok) {
56
+ releaseDreamLock(lock);
57
+ return listed;
58
+ }
59
+ const baseline = gitCommit(identity.home, `dream baseline ${project}`);
60
+ if (!baseline.ok) {
61
+ releaseDreamLock(lock);
62
+ return failure("audit_failed", `Couldn't commit the Git baseline, so nothing could be rolled back; no dream was opened: ${baseline.error}`);
63
+ }
64
+ Object.assign(state, { project, lock });
65
+ return success({ project, baseline: baseline.commit, ...listed.data });
66
+ }
67
+ catch (error) {
68
+ releaseDreamLock(lock);
69
+ return failureOf(error);
70
+ }
71
+ },
72
+ render: (result) => renderOutcome(result, renderBeginData),
73
+ };
74
+ export const dreamForgetParameters = Type.Object({ address: Type.String() }, { additionalProperties: false });
75
+ export const DreamForgetDataSchema = Type.Object({ address: Type.String(), project_key: Type.Optional(Type.String()) }, { additionalProperties: false });
76
+ export const dreamForget = {
77
+ name: "dream_forget", label: "Dream forget",
78
+ description: "Dream: permanently delete one crumpled note in the project being dreamed over, or in @human/, @self/, @model/. Crumple it first; live notes refuse.",
79
+ parameters: dreamForgetParameters, outputSchema: resultSchema(DreamForgetDataSchema),
80
+ async execute(params, identity, state) {
81
+ if (state.project === undefined)
82
+ return failure("not_dreaming", NOT_DREAMING);
83
+ try {
84
+ const dreaming = dreamingIdentity(identity, state);
85
+ await createNotesStore(dreaming).forget(params.address);
86
+ return success(noteIdentity(dreaming, params.address));
87
+ }
88
+ catch (error) {
89
+ return failureOf(error);
90
+ }
91
+ },
92
+ render: (result) => renderOutcome(result, data => `forgot ${data.address}`),
93
+ };
94
+ export const dreamEndParameters = Type.Object({}, { additionalProperties: false });
95
+ export const DreamEndDataSchema = Type.Object({ project: Type.String(), commit: Type.Optional(Type.String()), audit_error: Type.Optional(Type.String()) }, { additionalProperties: false });
96
+ export const dreamEnd = {
97
+ name: "dream_end", label: "Dream end",
98
+ description: "Dream: close the open dream. Commits the dream's changes to the notes home's Git and releases the lock; the project's notes are read-only again and reads stamp access again.",
99
+ parameters: dreamEndParameters, outputSchema: resultSchema(DreamEndDataSchema),
100
+ async execute(_params, identity, state) {
101
+ const project = state.project;
102
+ if (project === undefined)
103
+ return failure("not_dreaming", NOT_DREAMING);
104
+ // The dream closes even when the audit commit fails; the uncommitted changes stay in the work tree.
105
+ const audit = gitCommit(identity.home, `dream ${project}`);
106
+ abandonDream(state);
107
+ return success(audit.ok ? { project, commit: audit.commit } : { project, audit_error: audit.error });
108
+ },
109
+ render: (result) => renderOutcome(result, data => data.commit !== undefined
110
+ ? `woke from ${data.project} (commit ${data.commit})`
111
+ : `woke from ${data.project}; the Git commit failed, changes are uncommitted: ${data.audit_error}`),
112
+ };
@@ -1,7 +1,12 @@
1
1
  import type { NotesIdentity } from "../notes/identity.js";
2
2
  import { Type, type Static } from "typebox";
3
- import { type NoteChange } from "../notes/index.js";
3
+ import { type NoteChange, type NoteQueryStatus, type NoteRow } from "../notes/index.js";
4
4
  import { type Outcome } from "./result.js";
5
+ /**
6
+ * Typed refusal. Every fact a caller needs is already in the message; there is no separate context.
7
+ * Convert expected refusals; unexpected errors propagate unchanged.
8
+ */
9
+ export declare function failureOf(error: unknown): Outcome<never>;
5
10
  export declare const NoteMetadataSchema: Type.TObject<{
6
11
  origin: Type.TUnion<[Type.TLiteral<"user">, Type.TLiteral<"self">, Type.TLiteral<"external">]>;
7
12
  created_at: Type.TString;
@@ -83,6 +88,14 @@ export declare const NotesSearchDataSchema: Type.TObject<{
83
88
  }>>;
84
89
  }>;
85
90
  export type NotesSearchData = Static<typeof NotesSearchDataSchema>;
91
+ type Snapshot<T> = Omit<NotesListData, "files"> & {
92
+ files: T[];
93
+ };
94
+ /** Keep identities intact. Only search previews may shrink to make the first row fit. */
95
+ export declare function snapshot<T extends {
96
+ address: string;
97
+ }>(rows: T[], limit: number | undefined, status: NoteQueryStatus, renderData: (data: Snapshot<T>) => string, shrink?: (item: T, fits: (candidate: T) => boolean) => T): Outcome<Snapshot<T>>;
98
+ export declare function listedFile(row: Pick<NoteRow, "address" | "meta">, identity: NotesIdentity): NotesListData["files"][number];
86
99
  export declare const notesWriteParameters: Type.TObject<{
87
100
  address: Type.TString;
88
101
  content: Type.TString;
@@ -197,6 +210,7 @@ export declare const notesListParameters: Type.TObject<{
197
210
  limit: Type.TOptional<Type.TInteger>;
198
211
  crumpled: Type.TOptional<Type.TBoolean>;
199
212
  }>;
213
+ export declare function renderListData(data: NotesListData): string;
200
214
  export declare const notesList: {
201
215
  readonly name: "notes_list";
202
216
  readonly label: "Notes list";
@@ -19,7 +19,7 @@ const ADDRESS_DESCRIPTION = "Addresses: a bare path is this session's note; `@pr
19
19
  * Typed refusal. Every fact a caller needs is already in the message; there is no separate context.
20
20
  * Convert expected refusals; unexpected errors propagate unchanged.
21
21
  */
22
- function failureOf(error) {
22
+ export function failureOf(error) {
23
23
  if (error instanceof NoteError)
24
24
  return failure(error.code, error.message);
25
25
  // Address, glob, and query guards raise declared types; nothing else is converted.
@@ -150,7 +150,7 @@ export const NotesSearchDataSchema = Type.Object({
150
150
  ...SnapshotSchema,
151
151
  }, { additionalProperties: false });
152
152
  /** Keep identities intact. Only search previews may shrink to make the first row fit. */
153
- function snapshot(rows, limit, status, renderData, shrink) {
153
+ export function snapshot(rows, limit, status, renderData, shrink) {
154
154
  const files = [];
155
155
  const data = (selected) => ({ files: selected, more: rows.length - selected.length, homes_unavailable: status.homesUnavailable });
156
156
  const render = (outcome) => renderOutcome(outcome, renderData);
@@ -172,7 +172,7 @@ function snapshot(rows, limit, status, renderData, shrink) {
172
172
  const outcome = success(data(files));
173
173
  return fitsResult(outcome, render) ? outcome : failure("output_too_large", `The list of unreachable homes is itself over ${TOOL_OUTPUT_LIMIT}; narrow \`glob\` to fewer homes.`);
174
174
  }
175
- function listedFile(row, identity) {
175
+ export function listedFile(row, identity) {
176
176
  return { ...noteIdentity(identity, row.address), updated_at: localIso(row.meta.updatedAt), ...(row.meta.crumpledAt === undefined ? {} : { crumpled_at: row.meta.crumpledAt }) };
177
177
  }
178
178
  export const notesWriteParameters = Type.Object({ address: Type.String(), content: Type.String(), origin: ORIGIN }, { additionalProperties: false });
@@ -275,7 +275,7 @@ export const notesRead = {
275
275
  render: (result) => renderOutcome(result, renderReadData),
276
276
  };
277
277
  export const notesListParameters = Type.Object({ glob: GLOB_PARAMETER, limit: FILE_LIMIT_PARAMETER, crumpled: CRUMPLED_LIST_PARAMETER }, { additionalProperties: false });
278
- function renderListData(data) {
278
+ export function renderListData(data) {
279
279
  const lines = [`${data.files.length} ${data.files.length === 1 ? "note" : "notes"}`];
280
280
  for (const file of data.files) {
281
281
  lines.push(`- ${renderIdentity(file)} | updated ${file.updated_at}${file.crumpled_at === undefined ? "" : ` | crumpled ${file.crumpled_at}`}`);
@@ -52,6 +52,20 @@ test("Claude append and result arrival preserve call addresses and use the share
52
52
  assert.ok(search.ok);
53
53
  assert.deepEqual(search.data.items.map((item) => "seq" in item ? item.seq : -1), [3]);
54
54
  });
55
+ test("Claude file-history deltas do not become events or change history addresses", () => {
56
+ const rows = [user("u", null, "hello"), assistant("a", "u", [{ type: "text", text: "reply" }])];
57
+ const delta = { type: "file-history-delta", messageId: "u", snapshotMessageId: "u", trackingPath: "private-file.txt",
58
+ backup: { backupFileName: "private-backup", version: 1, backupTime: "2026-01-01T00:00:00Z", realParentDir: "/private" }, timestamp: "2026-01-01T00:00:00Z" };
59
+ const baseline = project(rows, "a");
60
+ assert.deepEqual(project([delta, rows[0], delta, rows[1], delta], "a"), baseline);
61
+ assert.equal(baseline.highestSeq, 2);
62
+ });
63
+ test("Claude skips unknown record types unless selected ancestry requires them", () => {
64
+ const u = user("u", null, "hello"), a = assistant("a", "u", [{ type: "text", text: "reply" }]);
65
+ const unknown = { type: "future-record", uuid: "future", parentUuid: "not-on-disk", content: "private metadata" };
66
+ assert.deepEqual(project([unknown, u, unknown, a, unknown], "a"), project([u, a], "a"));
67
+ assert.throws(() => project([u, unknown, { ...a, parentUuid: "future" }], "a"), /missing Claude transcript ancestor: future/);
68
+ });
55
69
  test("Claude duplicate UUID records do not allocate again or move addresses on reload", () => {
56
70
  const u = user("u", null, "hello"), a = assistant("a", "u", [call("one")]);
57
71
  const original = project([u, a], "a");
@@ -154,7 +168,6 @@ test("Claude tolerates only the uncommitted JSONL tail, not malformed committed
154
168
  assert.deepEqual(claudeHistoryFromJsonl(`${text}{\"type\":\"user\"`, { sessionId, headUuid: "u" }), project([user("u", null, "first")], "u"));
155
169
  assert.equal(claudeHistoryFromJsonl(text.trimEnd(), { sessionId, headUuid: "u" }).highestSeq, 1);
156
170
  assert.throws(() => claudeHistoryFromJsonl(`${text}{broken}\n`, { sessionId, headUuid: "u" }), /malformed.*line 2/);
157
- assert.throws(() => project([user("u", null, "first"), { type: "new-message-schema", uuid: "unknown" }], "u"), /unsupported.*record type/);
158
171
  assert.throws(() => project([row("u", null, "user", [{ type: "new-block-schema" }])], "u"), /unsupported.*content block/);
159
172
  assert.throws(() => project([row("u", null, "user", { type: "text", text: "not an array" })], "u"), /message content/);
160
173
  assert.throws(() => project([user("u", null, "first"), user("u", null, "conflict")], "u"), /conflicting.*duplicate UUID/);
@@ -165,7 +178,10 @@ test("Claude helper history tools reuse shared schemas, outcomes and text render
165
178
  const root = mkdtempSync(join(tmpdir(), "claude-history-"));
166
179
  t.after(() => rmSync(root, { recursive: true, force: true }));
167
180
  const transcriptPath = join(root, "transcript.jsonl"), rows = [user("u", null, "remember this"), assistant("a", "u", [call("one")]), row("r", "a", "user", [result("one", "recorded output")])];
168
- writeFileSync(transcriptPath, jsonl(rows));
181
+ writeFileSync(transcriptPath, jsonl([...rows,
182
+ { type: "file-history-delta", messageId: "r", snapshotMessageId: "u", trackingPath: "file.txt", backup: null, timestamp: "2026-01-01T00:00:00Z" },
183
+ { type: "future-record", content: "private metadata" },
184
+ ]));
169
185
  const identity = { home: join(root, "notes"), sessionId, cwd: root, agent: "claude", model: "claude" };
170
186
  const history = { sessionId, transcriptPath, headUuid: "r" };
171
187
  const projection = await readClaudeHistory(history);