notesoup 0.52.5 → 0.52.7

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 (44) hide show
  1. package/dist/plugins/claude/src/helper.js +34 -7
  2. package/dist/plugins/claude/src/history.d.ts +7 -2
  3. package/dist/plugins/claude/src/history.js +53 -22
  4. package/dist/plugins/claude/src/text.d.ts +5 -0
  5. package/dist/plugins/claude/src/text.js +12 -0
  6. package/dist/src/history/history.js +12 -11
  7. package/dist/src/notes/store.d.ts +2 -0
  8. package/dist/src/notes/store.js +2 -2
  9. package/dist/src/tools/dream.d.ts +2 -0
  10. package/dist/src/tools/history.d.ts +5 -3
  11. package/dist/src/tools/history.js +9 -11
  12. package/dist/src/tools/notes.d.ts +7 -0
  13. package/dist/src/tools/notes.js +8 -3
  14. package/dist/test/claude-history.test.js +135 -3
  15. package/dist/test/dream-skill.test.js +5 -0
  16. package/dist/test/dream-tools.test.js +15 -0
  17. package/dist/test/history.integration.test.js +26 -1
  18. package/dist/test/notes-library.test.js +1 -1
  19. package/dist/test/notes.test.js +1 -1
  20. package/dist/test/pi-render.test.js +2 -2
  21. package/docs/claude-code-mod.md +6 -2
  22. package/docs/tool-results.md +2 -2
  23. package/package.json +1 -1
  24. package/playbook.md +24 -13
  25. package/plugins/claude/.claude-plugin/plugin.json +1 -1
  26. package/plugins/claude/dist/claude/helper.js +105 -44
  27. package/plugins/claude/playbook.md +24 -13
  28. package/plugins/claude/skills/dream/SKILL.md +8 -0
  29. package/plugins/claude/src/helper.ts +34 -9
  30. package/plugins/claude/src/history.ts +54 -22
  31. package/plugins/claude/src/text.ts +13 -0
  32. package/plugins/paseo/OVERVIEW.md +6 -2
  33. package/plugins/paseo/client/brain-empty-card.tsx +3 -1
  34. package/plugins/paseo/client/brain-empty-transformer.ts +7 -14
  35. package/plugins/paseo/client/notes-op-transformer.ts +10 -18
  36. package/plugins/paseo/client/tool-result.ts +31 -0
  37. package/plugins/paseo/test/brain-empty.test.ts +24 -1
  38. package/plugins/paseo/test/fixtures/claude-tool-calls.ts +86 -0
  39. package/plugins/paseo/test/notes-op.test.ts +39 -1
  40. package/skills/dream/SKILL.md +8 -0
  41. package/src/history/history.ts +12 -10
  42. package/src/notes/store.ts +4 -3
  43. package/src/tools/history.ts +14 -13
  44. package/src/tools/notes.ts +8 -3
@@ -7,7 +7,7 @@ import { readClaudeHistory } from "./history.js";
7
7
  import { loadNotesSnapshot } from "../../../src/boot/snapshot.js";
8
8
  import { renderBootBlock } from "../../../src/boot/render.js";
9
9
  import { selectContinuation } from "../../../src/budget/text.js";
10
- import { CLAUDE_HISTORY_UNAVAILABLE_SENTENCE, CLAUDE_WARNING_PROMPT } from "./text.js";
10
+ import { claudeHistoryGapNotice, claudeHistoryUnconfirmedSeq, CLAUDE_HISTORY_UNKNOWN_PREVIOUS, CLAUDE_HISTORY_UNKNOWN_WINDOW, CLAUDE_HISTORY_UNAVAILABLE_SENTENCE, CLAUDE_WARNING_PROMPT } from "./text.js";
11
11
  import { resolveClaudeLimits } from "./thresholds.js";
12
12
  import { projectKey, snapshotNotesIdentity } from "../../../src/notes/index.js";
13
13
  const MAX_REQUEST_BYTES = 512 * 1024;
@@ -27,15 +27,12 @@ function paramProblem(schema, params) {
27
27
  const field = first.instancePath.replace(/^\//, "").replaceAll("/", ".");
28
28
  return `${field ? `${field} ` : ""}${first.message}${extra}`;
29
29
  }
30
- /** Bind one shared operation to the identity Claude supplies. Validate untyped Claude parameters against the shared operation schema before execution. */
30
+ /** Bind shared execution/rendering to a host context; dispatch validates parameters before calling. */
31
31
  function boundOperation(operation) {
32
32
  return {
33
33
  description: operation.description,
34
34
  parameters: operation.parameters,
35
35
  async call(params, ...context) {
36
- // Refuse before the operation can act: a rejected shape never reaches a write.
37
- if (!Check(operation.parameters, params))
38
- throw new Error(`invalid ${operation.name} parameters: ${paramProblem(operation.parameters, params)}`);
39
36
  // The same business outcome and the same renderer as the Pi tool; only the envelope differs.
40
37
  const outcome = await operation.execute(params, ...context);
41
38
  return { text: operation.render(outcome), ok: outcome.ok };
@@ -85,17 +82,47 @@ export async function dispatch(request) {
85
82
  if (value.op === "tool") {
86
83
  if (typeof value.tool !== "string" || (!Object.hasOwn(OPERATIONS, value.tool) && !Object.hasOwn(HISTORY_OPERATIONS, value.tool)))
87
84
  throw new Error("unknown tool");
85
+ const operation = Object.hasOwn(OPERATIONS, value.tool) ? OPERATIONS[value.tool] : HISTORY_OPERATIONS[value.tool];
86
+ // Refuse before any operation can act: a rejected shape never reaches a write.
87
+ if (!Check(operation.parameters, value.params))
88
+ throw new Error(`invalid ${value.tool} parameters: ${paramProblem(operation.parameters, value.params)}`);
88
89
  const id = identity(value.identity);
89
90
  if (Object.hasOwn(HISTORY_OPERATIONS, value.tool)) {
91
+ const tool = value.tool;
90
92
  const projection = await readClaudeHistory(historySource(value.history, id.sessionId));
91
- return HISTORY_OPERATIONS[value.tool].call(value.params, projection, id.sessionId);
93
+ const notice = claudeHistoryGapNotice(projection.missingAncestors);
94
+ const wrapText = (text) => notice + text;
95
+ let params = value.params;
96
+ if (projection.missingAncestors.length > 0) {
97
+ // An unknown segment is not evidence for the window before the current
98
+ // one. Resolve the exact ordinal, never array adjacency across a gap.
99
+ if (params.window_id === "@previous") {
100
+ const previous = projection.currentWindowOrdinal === undefined ? undefined : `claude:${id.sessionId}:${projection.currentWindowOrdinal - 1}`;
101
+ if (!projection.windows.some((window) => window.windowId === previous)) {
102
+ return { ok: false, text: wrapText(CLAUDE_HISTORY_UNKNOWN_PREVIOUS) };
103
+ }
104
+ params = { ...params, window_id: previous };
105
+ }
106
+ if (value.tool === "history_read") {
107
+ const { seq } = params;
108
+ if (seq <= projection.highestSeq && !projection.branchSeqs.has(seq)) {
109
+ return { ok: false, text: wrapText(claudeHistoryUnconfirmedSeq(seq)) };
110
+ }
111
+ }
112
+ }
113
+ const result = tool === "history_windows"
114
+ ? await HISTORY_OPERATIONS[tool].call(params, projection, id.sessionId, wrapText)
115
+ : await HISTORY_OPERATIONS[tool].call(params, projection, wrapText);
116
+ return { ...result, text: wrapText(result.text) };
92
117
  }
93
118
  return OPERATIONS[value.tool].call(value.params, id);
94
119
  }
95
120
  if (value.op === "history_state") {
96
121
  const id = identity(value.identity);
97
122
  const projection = await readClaudeHistory(historySource(value.history, id.sessionId));
98
- return { window: projection.windows.length - 1 };
123
+ if (projection.currentWindowOrdinal === undefined)
124
+ throw new Error(CLAUDE_HISTORY_UNKNOWN_WINDOW);
125
+ return { window: projection.currentWindowOrdinal };
99
126
  }
100
127
  if (value.op === "boot") {
101
128
  const id = identity(value.identity);
@@ -4,6 +4,11 @@ export type ClaudeHistorySource = {
4
4
  transcriptPath: string;
5
5
  headUuid?: string;
6
6
  };
7
+ /** Claude graph evidence stays in the adapter; shared queries only see addressed windows. */
8
+ export type ClaudeHistoryProjection = HistoryProjection & {
9
+ missingAncestors: string[];
10
+ currentWindowOrdinal: number | undefined;
11
+ };
7
12
  /** All addresses are allocated on the full first-occurrence log, before branch selection. */
8
- export declare function claudeHistoryFromJsonl(text: string, source: Omit<ClaudeHistorySource, "transcriptPath">): HistoryProjection;
9
- export declare function readClaudeHistory(source: ClaudeHistorySource): Promise<HistoryProjection>;
13
+ export declare function claudeHistoryFromJsonl(text: string, source: Omit<ClaudeHistorySource, "transcriptPath">): ClaudeHistoryProjection;
14
+ export declare function readClaudeHistory(source: ClaudeHistorySource): Promise<ClaudeHistoryProjection>;
@@ -132,8 +132,8 @@ export function claudeHistoryFromJsonl(text, source) {
132
132
  const nodes = new Map();
133
133
  let nextSeq = 1;
134
134
  for (const row of rowsOf(text)) {
135
- // Ignore non-message records, including future metadata. A skipped UUID that
136
- // the selected branch actually requires still fails ancestry resolution below.
135
+ // Ignore non-message records, including future metadata. If selected ancestry
136
+ // reaches a skipped UUID, it becomes a gap, never permission to expose its payload.
137
137
  if (!MESSAGE_TYPES.has(row.type))
138
138
  continue;
139
139
  const uuid = requiredString(row.uuid, "uuid");
@@ -160,32 +160,39 @@ export function claudeHistoryFromJsonl(text, source) {
160
160
  nextSeq += items.length;
161
161
  nodes.set(uuid, { first: version, latest: version, items });
162
162
  }
163
- function ordinalOf(version) {
164
- // Persisted history is not limited to the host's newest 4096 inference rows.
165
- // Resolve long parent chains iteratively, not with the JavaScript call stack.
163
+ const missingAncestors = new Set();
164
+ function positionOf(version) {
165
+ // Resolve long chains iteratively. A gap destroys ordinal evidence, not the
166
+ // confirmed suffix. Only a retained boot can re-anchor that suffix's ordinal.
166
167
  const chain = [], calculating = new Set();
167
168
  let cursor = version;
168
- while (cursor.ordinal === undefined) {
169
- // A notice can precede its parent on disk; use that parent's first eventual version.
169
+ let before = { ordinal: 0 };
170
+ while (cursor.position === undefined) {
171
+ // Forward references use the parent's first eventual version, not a rewrite.
170
172
  cursor.ancestor ??= cursor.ancestorUuid === undefined ? undefined : nodes.get(cursor.ancestorUuid)?.first;
171
173
  if (calculating.has(cursor))
172
174
  throw new Error("cyclic Claude transcript ancestry");
173
- if (cursor.ancestorUuid !== undefined && cursor.ancestor === undefined)
174
- throw new Error(`missing Claude transcript ancestor: ${cursor.ancestorUuid}`);
175
175
  calculating.add(cursor);
176
176
  chain.push(cursor);
177
+ if (cursor.ancestorUuid !== undefined && cursor.ancestor === undefined) {
178
+ missingAncestors.add(cursor.ancestorUuid);
179
+ before = { unknownAncestor: cursor.ancestorUuid };
180
+ break;
181
+ }
177
182
  if (cursor.ancestor === undefined)
178
183
  break;
179
184
  cursor = cursor.ancestor;
180
185
  }
181
- let before = cursor.ordinal ?? 0;
186
+ before = cursor.position ?? before;
182
187
  for (const current of chain.reverse()) {
183
188
  const retained = current.row.isCompactSummary === true || (current.ancestor !== undefined && boundary(current.ancestor.row));
184
189
  const marked = bootOrdinal(current.row, retained);
185
- current.ordinal = marked === undefined ? before + (boundary(current.row) ? 1 : 0) : Math.max(before, marked);
186
- before = current.ordinal;
190
+ current.position = marked !== undefined
191
+ ? { ordinal: "ordinal" in before ? Math.max(before.ordinal, marked) : marked }
192
+ : "ordinal" in before ? { ordinal: before.ordinal + (boundary(current.row) ? 1 : 0) } : before;
193
+ before = current.position;
187
194
  }
188
- return version.ordinal;
195
+ return version.position;
189
196
  }
190
197
  if (!source.headUuid)
191
198
  throw new Error("Claude history has no confirmed active head yet; wait for a main-session append after startup/resume");
@@ -210,8 +217,10 @@ export function claudeHistoryFromJsonl(text, source) {
210
217
  visiting.add(key);
211
218
  stack.push({ ...step, exit: true });
212
219
  const node = nodes.get(uuid);
213
- if (!node)
214
- throw new Error(`missing Claude transcript ancestor: ${uuid}`);
220
+ if (!node) {
221
+ missingAncestors.add(uuid);
222
+ continue;
223
+ }
215
224
  selected.add(uuid);
216
225
  const row = (historical ? node.first : node.latest).row;
217
226
  const ancestor = parent(row);
@@ -244,22 +253,44 @@ export function claudeHistoryFromJsonl(text, source) {
244
253
  }
245
254
  }
246
255
  }
247
- let maxOrdinal = ordinalOf(nodes.get(source.headUuid).latest);
248
- for (const uuid of selected)
249
- maxOrdinal = Math.max(maxOrdinal, ordinalOf(nodes.get(uuid).first));
250
- const windows = Array.from({ length: maxOrdinal + 1 }, (_, index) => ({ windowId: `claude:${source.sessionId}:${index}`, items: [] }));
256
+ const current = positionOf(nodes.get(source.headUuid).latest);
257
+ const windowId = (position) => `claude:${source.sessionId}:${"ordinal" in position ? position.ordinal : `unknown:${position.unknownAncestor}`}`;
258
+ const windowsById = new Map();
251
259
  const branchSeqs = new Set();
260
+ let maxOrdinal = "ordinal" in current ? current.ordinal : 0;
252
261
  for (const [uuid, node] of nodes) {
253
262
  if (!selected.has(uuid))
254
263
  continue;
255
- const window = windows[ordinalOf(node.first)];
264
+ const position = positionOf(node.first);
265
+ if ("ordinal" in position)
266
+ maxOrdinal = Math.max(maxOrdinal, position.ordinal);
267
+ const id = windowId(position);
268
+ let window = windowsById.get(id);
269
+ if (!window) {
270
+ window = { windowId: id, ...("ordinal" in position ? { ordinal: position.ordinal } : {}), items: [] };
271
+ windowsById.set(id, window);
272
+ }
256
273
  window.createdAt ??= node.items[0]?.createdAt;
257
274
  for (const item of node.items) {
258
275
  branchSeqs.add(item.seq);
259
- window.items.push({ ...item, windowId: window.windowId });
276
+ window.items.push({ ...item, windowId: id });
277
+ }
278
+ }
279
+ // Preserve complete-history empty windows (including copied boot ordinals).
280
+ // With gaps, report only evidenced windows, never invent the missing ordinals.
281
+ if (missingAncestors.size === 0) {
282
+ for (let ordinal = 0; ordinal <= maxOrdinal; ordinal++) {
283
+ const id = windowId({ ordinal });
284
+ if (!windowsById.has(id))
285
+ windowsById.set(id, { windowId: id, ordinal, items: [] });
260
286
  }
261
287
  }
262
- return projectHistory(windows, nextSeq - 1, branchSeqs);
288
+ // Forward references can put a newer numbered window on disk first. Unknown
289
+ // segments are a separate, unordered group, not an inferred place in that timeline.
290
+ const windows = [...windowsById.values()].sort((a, b) => a.ordinal === undefined
291
+ ? b.ordinal === undefined ? 0 : 1
292
+ : b.ordinal === undefined ? -1 : a.ordinal - b.ordinal);
293
+ return { ...projectHistory(windows, nextSeq - 1, branchSeqs), missingAncestors: [...missingAncestors], currentWindowOrdinal: "ordinal" in current ? current.ordinal : undefined };
263
294
  }
264
295
  export async function readClaudeHistory(source) {
265
296
  if (!source || typeof source.transcriptPath !== "string" || !source.transcriptPath || typeof source.sessionId !== "string")
@@ -2,3 +2,8 @@
2
2
  export declare const CLAUDE_HISTORY_UNAVAILABLE_SENTENCE = "History isn't available in this Claude session: no main transcript_path was supplied. Keep essential state in notes; don't pretend those notes are the missing transcript.";
3
3
  /** The same notice as Pi; empty_brain's result explains Claude's deferred reset. */
4
4
  export declare const CLAUDE_WARNING_PROMPT: string;
5
+ export declare const CLAUDE_HISTORY_UNKNOWN_WINDOW = "Claude history cannot determine the current window ordinal across a missing ancestor; restore the ancestry or use a retained notesoup boot to re-anchor it.";
6
+ export declare const CLAUDE_HISTORY_UNKNOWN_PREVIOUS = "Cannot resolve \"@previous\": the immediately preceding window is not confirmed across the ancestry gap. Use an explicit window id from history_windows.";
7
+ export declare function claudeHistoryUnconfirmedSeq(seq: number): string;
8
+ /** Bounded host-only evidence, outside event documents/search offsets and shared schemas. */
9
+ export declare function claudeHistoryGapNotice(missing: readonly string[]): string;
@@ -3,3 +3,15 @@ import { warningNotice } from "../../../src/budget/text.js";
3
3
  export const CLAUDE_HISTORY_UNAVAILABLE_SENTENCE = "History isn't available in this Claude session: no main transcript_path was supplied. Keep essential state in notes; don't pretend those notes are the missing transcript.";
4
4
  /** The same notice as Pi; empty_brain's result explains Claude's deferred reset. */
5
5
  export const CLAUDE_WARNING_PROMPT = warningNotice();
6
+ export const CLAUDE_HISTORY_UNKNOWN_WINDOW = "Claude history cannot determine the current window ordinal across a missing ancestor; restore the ancestry or use a retained notesoup boot to re-anchor it.";
7
+ export const CLAUDE_HISTORY_UNKNOWN_PREVIOUS = 'Cannot resolve "@previous": the immediately preceding window is not confirmed across the ancestry gap. Use an explicit window id from history_windows.';
8
+ export function claudeHistoryUnconfirmedSeq(seq) {
9
+ return `Seq ${seq} is outside the confirmed selected history; it may be on another branch or beyond an unresolved ancestry gap.`;
10
+ }
11
+ /** Bounded host-only evidence, outside event documents/search offsets and shared schemas. */
12
+ export function claudeHistoryGapNotice(missing) {
13
+ if (missing.length === 0)
14
+ return "";
15
+ const evidence = missing.slice(0, 5).map((uuid) => JSON.stringify(uuid.length > 160 ? `${uuid.slice(0, 160)}…` : uuid)).join(", ");
16
+ return `Claude history is incomplete: missing ancestor UUID(s): ${evidence}${missing.length > 5 ? `; ${missing.length - 5} more` : ""}. Only confirmed selected ancestry is returned; disconnected prefixes and unrelated branches are excluded. Window IDs containing :unknown: have unconfirmed ordinal/ownership and may span native compactions; they are listed separately after numbered windows, not placed in a chronological order. A later retained boot can re-anchor window numbering, but cannot fill the history gap.\n\n`;
17
+ }
@@ -75,31 +75,32 @@ function toolEvent(item, result) {
75
75
  }
76
76
  /** Pair results into call events; consumed result seqs are not alternate read addresses. */
77
77
  export function projectHistory(rawWindows, highestSeq, branchSeqs) {
78
- const raw = rawWindows.flatMap((current) => current.items);
78
+ // Pair in durable address order, not window presentation order. Unnumbered
79
+ // segments need not have a provable chronological order relative to each other.
80
+ const raw = rawWindows.flatMap((current) => current.items).sort((a, b) => a.seq - b.seq);
79
81
  const resultsById = new Map();
80
82
  for (const item of raw) {
81
83
  if (item.role === "tool" && item.toolCallId && !resultsById.has(item.toolCallId))
82
84
  resultsById.set(item.toolCallId, item);
83
85
  }
84
86
  const pairedResults = new Map();
85
- const consumed = new Set();
87
+ for (const item of raw) {
88
+ const result = item.role === "tool_call" && item.toolCallId ? resultsById.get(item.toolCallId) : undefined;
89
+ if (result && result.seq > item.seq && !pairedResults.has(result.seq)) {
90
+ pairedResults.set(result.seq, item.seq);
91
+ }
92
+ }
86
93
  const windows = rawWindows.map((current) => ({
87
94
  windowId: current.windowId,
88
95
  ...(current.createdAt ? { createdAt: current.createdAt } : {}),
89
96
  items: current.items.flatMap((item) => {
90
- if (consumed.has(item.seq))
97
+ if (pairedResults.has(item.seq))
91
98
  return [];
92
- if (item.role === "tool_call") {
99
+ if (item.role === "tool_call" || item.role === "tool") {
93
100
  const result = item.toolCallId ? resultsById.get(item.toolCallId) : undefined;
94
- const paired = result && result.seq > item.seq && !consumed.has(result.seq) ? result : undefined;
95
- if (paired) {
96
- consumed.add(paired.seq);
97
- pairedResults.set(paired.seq, item.seq);
98
- }
101
+ const paired = result && pairedResults.get(result.seq) === item.seq ? result : undefined;
99
102
  return [toolEvent(item, paired)];
100
103
  }
101
- if (item.role === "tool")
102
- return [toolEvent(item)];
103
104
  return [{ seq: item.seq, windowId: item.windowId, role: item.role === "system" || item.role === "developer" ? "context" : item.role, text: item.text, createdAt: item.createdAt }];
104
105
  }),
105
106
  }));
@@ -44,10 +44,12 @@ export type NotesQuery = {
44
44
  crumpled?: boolean;
45
45
  };
46
46
  /** A read exposes metadata and the pure body; the serialized frontmatter is never part of the body. */
47
+ /** `accessedBefore` is the last access before this read, so a read never hides how long a note sat unread. */
47
48
  export type NoteReadResult = {
48
49
  meta: NoteMeta;
49
50
  body: string;
50
51
  resolvedScope: Scope;
52
+ accessedBefore: number;
51
53
  };
52
54
  export type NoteWriteResult = {
53
55
  meta: NoteMeta;
@@ -297,11 +297,11 @@ export function createNotesStore(input) {
297
297
  const parsed = parseNote(raw, now);
298
298
  // Named homes, and every read during a dream, leave no access stamp.
299
299
  if (identity.dreaming !== undefined || ((scope === "project" || scope === "session") && destination.who !== undefined))
300
- return { meta: { ...parsed.meta, scope }, body: parsed.body, resolvedScope: scope };
300
+ return { meta: { ...parsed.meta, scope }, body: parsed.body, resolvedScope: scope, accessedBefore: parsed.meta.lastAccessed };
301
301
  // A read records its own access, exactly as a write records an edit.
302
302
  const meta = { ...parsed.meta, scope, lastAccessed: now, accessCount: (typeof parsed.meta.accessCount === "number" ? parsed.meta.accessCount : 0) + 1 };
303
303
  await atomicWrite(path, serializeNote(meta, parsed.body));
304
- return { meta, body: parsed.body, resolvedScope: scope };
304
+ return { meta, body: parsed.body, resolvedScope: scope, accessedBefore: parsed.meta.lastAccessed };
305
305
  });
306
306
  }
307
307
  async function update(address, edits, options = {}) {
@@ -20,6 +20,7 @@ export declare const DreamBeginDataSchema: Type.TObject<{
20
20
  homes_unavailable: Type.TArray<Type.TString>;
21
21
  files: Type.TArray<Type.TObject<{
22
22
  updated_at: Type.TString;
23
+ last_accessed: Type.TString;
23
24
  crumpled_at: Type.TOptional<Type.TString>;
24
25
  project_root: Type.TOptional<Type.TString>;
25
26
  project_siblings: Type.TOptional<Type.TArray<Type.TObject<{
@@ -45,6 +46,7 @@ export declare const dreamBegin: {
45
46
  homes_unavailable: Type.TArray<Type.TString>;
46
47
  files: Type.TArray<Type.TObject<{
47
48
  updated_at: Type.TString;
49
+ last_accessed: Type.TString;
48
50
  crumpled_at: Type.TOptional<Type.TString>;
49
51
  project_root: Type.TOptional<Type.TString>;
50
52
  project_siblings: Type.TOptional<Type.TArray<Type.TObject<{
@@ -33,9 +33,11 @@ declare const HistoryWindowsDataSchema: Type.TObject<{
33
33
  more: Type.TInteger;
34
34
  }>;
35
35
  type HistoryWindowsData = Static<typeof HistoryWindowsDataSchema>;
36
+ /** Pure host decoration, measured during selection and applied unchanged by the caller at delivery. */
37
+ export type HistoryTextWrapper = (text: string) => string;
36
38
  export declare const PREVIOUS_WINDOW = "@previous";
37
39
  export declare const historyWindowsParameters: Type.TObject<{}>;
38
- export declare const historyWindows: Operation<typeof historyWindowsParameters, HistoryWindowsData, [HistoryProjection, string]>;
40
+ export declare const historyWindows: Operation<typeof historyWindowsParameters, HistoryWindowsData, [HistoryProjection, string, HistoryTextWrapper?]>;
39
41
  export declare const historyListParameters: Type.TObject<{
40
42
  query: Type.TOptional<Type.TUnion<[Type.TString, Type.TArray<Type.TString>]>>;
41
43
  roles: Type.TOptional<Type.TArray<Type.TUnion<[Type.TLiteral<"user">, Type.TLiteral<"assistant">, Type.TLiteral<"tool">, Type.TLiteral<"context">]>>>;
@@ -48,11 +50,11 @@ export declare const historyListParameters: Type.TObject<{
48
50
  limit: Type.TOptional<Type.TInteger>;
49
51
  max_chars_per_item: Type.TOptional<Type.TInteger>;
50
52
  }>;
51
- export declare const historyList: Operation<typeof historyListParameters, HistoryPage, [HistoryProjection]>;
53
+ export declare const historyList: Operation<typeof historyListParameters, HistoryPage, [HistoryProjection, HistoryTextWrapper?]>;
52
54
  export declare const historyReadParameters: Type.TObject<{
53
55
  offset_chars: Type.TOptional<Type.TInteger>;
54
56
  max_chars: Type.TOptional<Type.TInteger>;
55
57
  seq: Type.TInteger;
56
58
  }>;
57
- export declare const historyRead: Operation<typeof historyReadParameters, HistoryReadData, [HistoryProjection]>;
59
+ export declare const historyRead: Operation<typeof historyReadParameters, HistoryReadData, [HistoryProjection, HistoryTextWrapper?]>;
58
60
  export {};
@@ -70,11 +70,7 @@ function renderRead(data) {
70
70
  const neighborhood = `neighborhood → \`history_list\`(${JSON.stringify({ ...(afterSeq >= 1 ? { after_seq: afterSeq } : {}), before_seq: data.seq + 10 })})`;
71
71
  return [header(data), ...(tool ? [tool] : []), neighborhood, "", data.total_chars === 0 ? "No visible text recorded for this event." : renderTextWindow(data)].join("\n");
72
72
  }
73
- /* ------------------------------------------------------------------ shared bounding */
74
- /** Include rendering and cursors in the budget, not just row contents. */
75
- function pageFits(page) {
76
- return fitsResult(success(page), (result) => renderOutcome(result, renderPage));
77
- }
73
+ const plainText = (text) => text;
78
74
  // Sample known ids in the refusal message itself, never as a second listing.
79
75
  const MAX_REPORTED_WINDOWS = 5;
80
76
  /** At most `MAX_REPORTED_WINDOWS` known ids, appended to an unknown_window_id message. */
@@ -106,9 +102,9 @@ export const historyWindows = {
106
102
  description: "List this session's context windows, oldest first, with seq ranges.",
107
103
  parameters: historyWindowsParameters,
108
104
  outputSchema: resultSchema(HistoryWindowsDataSchema),
109
- async execute(_params, projection, sessionId) {
105
+ async execute(_params, projection, sessionId, wrapText = plainText) {
110
106
  const data = { session_id: sessionId, windows: [], more: projection.windows.length };
111
- const fits = (candidate) => fitsResult(success(candidate), (result) => renderOutcome(result, renderWindows));
107
+ const fits = (candidate) => fitsResult(success(candidate), (result) => wrapText(renderOutcome(result, renderWindows)));
112
108
  for (const window of projection.windows) {
113
109
  let first = null;
114
110
  let last = null;
@@ -151,7 +147,7 @@ export const historyList = {
151
147
  description: "Browse or search this session's events, a page at a time. Read one in full with `history_read`.",
152
148
  parameters: historyListParameters,
153
149
  outputSchema: resultSchema(HistoryPageSchema),
154
- async execute(params, projection) {
150
+ async execute(params, projection, wrapText = plainText) {
155
151
  const resolved = resolveWindowId(projection, params.window_id);
156
152
  if (!resolved.ok)
157
153
  return resolved.outcome;
@@ -159,7 +155,9 @@ export const historyList = {
159
155
  const badWindow = badWindowId(projection, scoped);
160
156
  if (badWindow)
161
157
  return badWindow;
162
- return selectPage(projection, scoped, pageFits, scoped.max_chars_per_item ?? HISTORY_PREVIEW_CHARS);
158
+ // Charge wrapped rendering and cursors, not only event previews.
159
+ const fits = (page) => fitsResult(success(page), (result) => wrapText(renderOutcome(result, renderPage)));
160
+ return selectPage(projection, scoped, fits, scoped.max_chars_per_item ?? HISTORY_PREVIEW_CHARS);
163
161
  },
164
162
  render: (result) => renderOutcome(result, renderPage),
165
163
  };
@@ -171,7 +169,7 @@ export const historyRead = {
171
169
  description: "Read one event in full: tool arguments, output, and nested calls.",
172
170
  parameters: historyReadParameters,
173
171
  outputSchema: resultSchema(HistoryReadDataSchema),
174
- async execute(params, projection) {
172
+ async execute(params, projection, wrapText = plainText) {
175
173
  const item = allItems(projection).find((event) => event.seq === params.seq);
176
174
  // Address checks run in one order: past the end of the file, off this branch, then
177
175
  // consumed by a pairing. Only the last two can mention what is at the address.
@@ -201,7 +199,7 @@ export const historyRead = {
201
199
  ...toolSummary(item),
202
200
  ...nestedCallSummary(item),
203
201
  ...window,
204
- }), (result) => renderOutcome(result, renderRead));
202
+ }), (result) => wrapText(renderOutcome(result, renderRead)));
205
203
  },
206
204
  render: (result) => renderOutcome(result, renderRead),
207
205
  };
@@ -11,6 +11,7 @@ export declare const NoteMetadataSchema: Type.TObject<{
11
11
  origin: Type.TUnion<[Type.TLiteral<"user">, Type.TLiteral<"self">, Type.TLiteral<"external">]>;
12
12
  created_at: Type.TString;
13
13
  updated_at: Type.TString;
14
+ last_accessed: Type.TString;
14
15
  crumpled_at: Type.TOptional<Type.TString>;
15
16
  project: Type.TOptional<Type.TString>;
16
17
  extra: Type.TRecord<"^.*$", Type.TUnknown>;
@@ -38,6 +39,7 @@ export declare const NotesReadDataSchema: Type.TObject<{
38
39
  origin: Type.TUnion<[Type.TLiteral<"user">, Type.TLiteral<"self">, Type.TLiteral<"external">]>;
39
40
  created_at: Type.TString;
40
41
  updated_at: Type.TString;
42
+ last_accessed: Type.TString;
41
43
  crumpled_at: Type.TOptional<Type.TString>;
42
44
  project: Type.TOptional<Type.TString>;
43
45
  extra: Type.TRecord<"^.*$", Type.TUnknown>;
@@ -56,6 +58,7 @@ export declare const NotesListDataSchema: Type.TObject<{
56
58
  homes_unavailable: Type.TArray<Type.TString>;
57
59
  files: Type.TArray<Type.TObject<{
58
60
  updated_at: Type.TString;
61
+ last_accessed: Type.TString;
59
62
  crumpled_at: Type.TOptional<Type.TString>;
60
63
  project_root: Type.TOptional<Type.TString>;
61
64
  project_siblings: Type.TOptional<Type.TArray<Type.TObject<{
@@ -77,6 +80,7 @@ export declare const NotesSearchDataSchema: Type.TObject<{
77
80
  offset_chars: Type.TInteger;
78
81
  }>>;
79
82
  updated_at: Type.TString;
83
+ last_accessed: Type.TString;
80
84
  crumpled_at: Type.TOptional<Type.TString>;
81
85
  project_root: Type.TOptional<Type.TString>;
82
86
  project_siblings: Type.TOptional<Type.TArray<Type.TObject<{
@@ -187,6 +191,7 @@ export declare const notesRead: {
187
191
  origin: Type.TUnion<[Type.TLiteral<"user">, Type.TLiteral<"self">, Type.TLiteral<"external">]>;
188
192
  created_at: Type.TString;
189
193
  updated_at: Type.TString;
194
+ last_accessed: Type.TString;
190
195
  crumpled_at: Type.TOptional<Type.TString>;
191
196
  project: Type.TOptional<Type.TString>;
192
197
  extra: Type.TRecord<"^.*$", Type.TUnknown>;
@@ -225,6 +230,7 @@ export declare const notesList: {
225
230
  homes_unavailable: Type.TArray<Type.TString>;
226
231
  files: Type.TArray<Type.TObject<{
227
232
  updated_at: Type.TString;
233
+ last_accessed: Type.TString;
228
234
  crumpled_at: Type.TOptional<Type.TString>;
229
235
  project_root: Type.TOptional<Type.TString>;
230
236
  project_siblings: Type.TOptional<Type.TArray<Type.TObject<{
@@ -271,6 +277,7 @@ export declare const notesSearch: {
271
277
  offset_chars: Type.TInteger;
272
278
  }>>;
273
279
  updated_at: Type.TString;
280
+ last_accessed: Type.TString;
274
281
  crumpled_at: Type.TOptional<Type.TString>;
275
282
  project_root: Type.TOptional<Type.TString>;
276
283
  project_siblings: Type.TOptional<Type.TArray<Type.TObject<{
@@ -40,6 +40,7 @@ export const NoteMetadataSchema = Type.Object({
40
40
  origin: Type.Union([...ORIGIN_VALUES]),
41
41
  created_at: Type.String(),
42
42
  updated_at: Type.String(),
43
+ last_accessed: Type.String(),
43
44
  crumpled_at: Type.Optional(Type.String()),
44
45
  project: Type.Optional(Type.String()),
45
46
  extra: Type.Record(Type.String(), Type.Unknown()),
@@ -71,6 +72,7 @@ function noteMetadata(meta) {
71
72
  origin: meta.origin,
72
73
  created_at: localIso(meta.createdAt),
73
74
  updated_at: localIso(meta.updatedAt),
75
+ last_accessed: localIso(meta.lastAccessed),
74
76
  ...(typeof meta.crumpledAt === "string" ? { crumpled_at: meta.crumpledAt } : {}),
75
77
  ...(typeof meta.project === "string" ? { project: meta.project } : {}),
76
78
  extra,
@@ -81,6 +83,7 @@ function renderMetadata(metadata) {
81
83
  `origin ${metadata.origin}`,
82
84
  `created ${metadata.created_at}`,
83
85
  `updated ${metadata.updated_at}`,
86
+ `accessed ${metadata.last_accessed}`,
84
87
  ...(metadata.crumpled_at === undefined ? [] : [`crumpled ${metadata.crumpled_at}`]),
85
88
  ...(metadata.project === undefined ? [] : [`project ${metadata.project}`]),
86
89
  ];
@@ -107,6 +110,7 @@ const ListedFileSchema = Type.Object({
107
110
  project_key: Type.Optional(Type.String()),
108
111
  ...ProjectReceiptSchema,
109
112
  updated_at: Type.String(),
113
+ last_accessed: Type.String(),
110
114
  crumpled_at: Type.Optional(Type.String()),
111
115
  }, { additionalProperties: false });
112
116
  const MatchSchema = Type.Object({
@@ -173,7 +177,7 @@ export function snapshot(rows, limit, status, renderData, shrink) {
173
177
  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
178
  }
175
179
  export function listedFile(row, identity) {
176
- return { ...noteIdentity(identity, row.address), updated_at: localIso(row.meta.updatedAt), ...(row.meta.crumpledAt === undefined ? {} : { crumpled_at: row.meta.crumpledAt }) };
180
+ return { ...noteIdentity(identity, row.address), updated_at: localIso(row.meta.updatedAt), last_accessed: localIso(row.meta.lastAccessed), ...(row.meta.crumpledAt === undefined ? {} : { crumpled_at: row.meta.crumpledAt }) };
177
181
  }
178
182
  export const notesWriteParameters = Type.Object({ address: Type.String(), content: Type.String(), origin: ORIGIN }, { additionalProperties: false });
179
183
  function renderWriteData(data) {
@@ -265,7 +269,8 @@ export const notesRead = {
265
269
  const totalChars = Array.from(note.body).length;
266
270
  if (params.offset_chars !== undefined && params.offset_chars > totalChars)
267
271
  return failure("invalid_offset", `This note ends at char ${totalChars}; offset_chars ${params.offset_chars} is past the last word.`);
268
- const metadata = noteMetadata(note.meta);
272
+ // Report the access before this one: the read itself must not make a long-unread note look fresh.
273
+ const metadata = noteMetadata({ ...note.meta, lastAccessed: note.accessedBefore });
269
274
  return readTextWindow(note.body, params.offset_chars, params.max_chars, (window) => ({ ...resolved, metadata, ...window }), (result) => renderOutcome(result, renderReadData));
270
275
  }
271
276
  catch (error) {
@@ -278,7 +283,7 @@ export const notesListParameters = Type.Object({ glob: GLOB_PARAMETER, limit: FI
278
283
  export function renderListData(data) {
279
284
  const lines = [`${data.files.length} ${data.files.length === 1 ? "note" : "notes"}`];
280
285
  for (const file of data.files) {
281
- lines.push(`- ${renderIdentity(file)} | updated ${file.updated_at}${file.crumpled_at === undefined ? "" : ` | crumpled ${file.crumpled_at}`}`);
286
+ lines.push(`- ${renderIdentity(file)} | updated ${file.updated_at} | accessed ${file.last_accessed}${file.crumpled_at === undefined ? "" : ` | crumpled ${file.crumpled_at}`}`);
282
287
  }
283
288
  if (data.more > 0)
284
289
  lines.push(`${data.more} more matching notes omitted; narrow with glob`);