notesoup 0.61.0 → 0.63.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.
Files changed (210) hide show
  1. package/.agents/plugins/marketplace.json +15 -0
  2. package/README.md +14 -11
  3. package/dist/plugins/antigravity/src/cli.d.ts +1 -0
  4. package/dist/plugins/antigravity/src/cli.js +23 -0
  5. package/dist/plugins/antigravity/src/hooks.d.ts +18 -0
  6. package/dist/plugins/antigravity/src/hooks.js +53 -0
  7. package/dist/plugins/antigravity/src/identity.d.ts +26 -0
  8. package/dist/plugins/antigravity/src/identity.js +129 -0
  9. package/dist/plugins/claude/src/helper.js +24 -5
  10. package/dist/plugins/claude/src/text.d.ts +7 -0
  11. package/dist/plugins/claude/src/text.js +12 -1
  12. package/dist/plugins/codex/src/hooks.js +1 -0
  13. package/dist/plugins/codex/src/identity.d.ts +6 -1
  14. package/dist/plugins/codex/src/identity.js +13 -1
  15. package/dist/plugins/codex/src/mcp.d.ts +35 -7
  16. package/dist/plugins/codex/src/mcp.js +26 -88
  17. package/dist/plugins/codex/src/text.js +3 -3
  18. package/dist/plugins/dsh/tools.js +8 -4
  19. package/dist/plugins/mcp/operations.d.ts +15 -0
  20. package/dist/plugins/mcp/operations.js +43 -0
  21. package/dist/plugins/mcp/server.d.ts +14 -0
  22. package/dist/plugins/mcp/server.js +13 -0
  23. package/dist/plugins/pi/budget.d.ts +4 -1
  24. package/dist/plugins/pi/budget.js +35 -8
  25. package/dist/plugins/pi/entries.d.ts +2 -0
  26. package/dist/plugins/pi/entries.js +2 -0
  27. package/dist/plugins/pi/history-tools.js +2 -1
  28. package/dist/plugins/pi/history.js +18 -1
  29. package/dist/plugins/pi/notes/tools.js +7 -3
  30. package/dist/plugins/pi/render.d.ts +7 -1
  31. package/dist/plugins/pi/render.js +2 -2
  32. package/dist/plugins/pi/reset/artifacts.d.ts +1 -1
  33. package/dist/plugins/pi/reset/artifacts.js +4 -4
  34. package/dist/plugins/pi/reset/lifecycle.d.ts +9 -2
  35. package/dist/plugins/pi/reset/lifecycle.js +109 -31
  36. package/dist/plugins/pi/runtime.js +104 -63
  37. package/dist/plugins/pi/tool-result.js +7 -7
  38. package/dist/plugins/pi/window.d.ts +25 -3
  39. package/dist/plugins/pi/window.js +219 -9
  40. package/dist/src/boot/render.js +18 -15
  41. package/dist/src/boot/text.d.ts +3 -1
  42. package/dist/src/boot/text.js +22 -20
  43. package/dist/src/budget/text.d.ts +7 -3
  44. package/dist/src/budget/text.js +24 -15
  45. package/dist/src/history/claude.d.ts +2 -0
  46. package/dist/src/history/claude.js +46 -0
  47. package/dist/src/history/codex-transcript.js +7 -5
  48. package/dist/src/history/codex.js +3 -0
  49. package/dist/src/history/corpus.d.ts +28 -1
  50. package/dist/src/history/corpus.js +40 -0
  51. package/dist/src/history/history.d.ts +37 -46
  52. package/dist/src/history/history.js +21 -40
  53. package/dist/src/history/local.js +67 -32
  54. package/dist/src/history/pi.d.ts +2 -1
  55. package/dist/src/history/pi.js +122 -48
  56. package/dist/src/history/prefilter.js +76 -19
  57. package/dist/src/history/query.d.ts +28 -49
  58. package/dist/src/history/query.js +83 -68
  59. package/dist/src/history/summary-cache.d.ts +8 -1
  60. package/dist/src/history/summary-cache.js +138 -12
  61. package/dist/src/index.d.ts +2 -2
  62. package/dist/src/index.js +1 -1
  63. package/dist/src/notes/errors.d.ts +1 -1
  64. package/dist/src/notes/frontmatter.d.ts +0 -2
  65. package/dist/src/notes/frontmatter.js +0 -2
  66. package/dist/src/notes/index.d.ts +1 -1
  67. package/dist/src/notes/index.js +1 -1
  68. package/dist/src/notes/policy.d.ts +15 -1
  69. package/dist/src/notes/policy.js +46 -5
  70. package/dist/src/notes/store.d.ts +12 -0
  71. package/dist/src/notes/store.js +16 -20
  72. package/dist/src/text-match.d.ts +10 -1
  73. package/dist/src/text-match.js +42 -3
  74. package/dist/src/tools/dream.d.ts +22 -93
  75. package/dist/src/tools/dream.js +30 -27
  76. package/dist/src/tools/history.d.ts +33 -26
  77. package/dist/src/tools/history.js +257 -163
  78. package/dist/src/tools/notes.d.ts +51 -163
  79. package/dist/src/tools/notes.js +146 -100
  80. package/dist/src/tools/output.d.ts +2 -1
  81. package/dist/src/tools/output.js +2 -1
  82. package/dist/src/tools/result.d.ts +4 -7
  83. package/dist/src/tools/result.js +8 -9
  84. package/dist/src/tools/schema.d.ts +4 -1
  85. package/dist/src/tools/schema.js +25 -1
  86. package/dist/test/agent-loop.test.js +394 -56
  87. package/dist/test/antigravity-live.test.d.ts +1 -0
  88. package/dist/test/antigravity-live.test.js +142 -0
  89. package/dist/test/antigravity-plugin.test.d.ts +1 -0
  90. package/dist/test/antigravity-plugin.test.js +101 -0
  91. package/dist/test/boot.integration.test.js +156 -15
  92. package/dist/test/budget-settings.integration.test.js +4 -4
  93. package/dist/test/claude-history.test.js +14 -13
  94. package/dist/test/claude-mod.test.js +199 -16
  95. package/dist/test/claude-validation.test.js +69 -2
  96. package/dist/test/codex-history.test.js +15 -3
  97. package/dist/test/codex-plugin.test.js +76 -38
  98. package/dist/test/dependencies.test.js +7 -3
  99. package/dist/test/dream-skill.test.js +3 -3
  100. package/dist/test/dream-tools.test.js +101 -56
  101. package/dist/test/dsh.test.js +34 -19
  102. package/dist/test/helpers/dependency-graph.js +2 -2
  103. package/dist/test/helpers/extension.d.ts +68 -3
  104. package/dist/test/helpers/extension.js +74 -5
  105. package/dist/test/history-corpus.test.js +79 -77
  106. package/dist/test/history-summary-cache.test.js +97 -9
  107. package/dist/test/history.integration.test.js +234 -168
  108. package/dist/test/host-neutral.test.js +69 -19
  109. package/dist/test/marker.test.js +1 -1
  110. package/dist/test/model-facing-text.test.js +13 -3
  111. package/dist/test/note-policy.test.js +96 -77
  112. package/dist/test/notes.integration.test.js +212 -94
  113. package/dist/test/notes.test.js +184 -113
  114. package/dist/test/pi-render.test.js +20 -12
  115. package/dist/test/project-namespace.test.js +3 -2
  116. package/dist/test/reset-lifecycle.test.js +12 -2
  117. package/docs/antigravity.md +44 -0
  118. package/docs/architecture.md +6 -4
  119. package/docs/claude-code-mod.md +7 -7
  120. package/docs/codex.md +36 -38
  121. package/docs/dsh.md +3 -3
  122. package/docs/history-sessions.md +28 -50
  123. package/docs/notes-library.md +4 -4
  124. package/docs/reset-lifecycle.md +1 -1
  125. package/docs/skills.md +3 -3
  126. package/docs/tool-results.md +47 -28
  127. package/package.json +3 -2
  128. package/playbook.md +1 -1
  129. package/plugins/antigravity/dist/antigravity/notesoup.js +26886 -0
  130. package/plugins/antigravity/hooks.json +7 -0
  131. package/plugins/antigravity/mcp_config.json +8 -0
  132. package/plugins/antigravity/plugin.json +6 -0
  133. package/plugins/antigravity/src/cli.ts +22 -0
  134. package/plugins/antigravity/src/hooks.ts +51 -0
  135. package/plugins/antigravity/src/identity.ts +127 -0
  136. package/plugins/claude/.claude-plugin/plugin.json +1 -1
  137. package/plugins/claude/dist/claude/helper.js +1108 -539
  138. package/plugins/claude/hooks/register.ts +202 -62
  139. package/plugins/claude/playbook.md +1 -1
  140. package/plugins/claude/skills/dream/SKILL.md +1 -1
  141. package/plugins/claude/skills/notesoup-guide/SKILL.md +92 -0
  142. package/plugins/claude/src/helper.ts +24 -5
  143. package/plugins/claude/src/text.ts +14 -1
  144. package/plugins/codex/.codex-plugin/plugin.json +8 -0
  145. package/plugins/codex/.mcp.json +11 -0
  146. package/plugins/codex/README.md +5 -21
  147. package/plugins/codex/dist/codex/notesoup.js +18480 -17946
  148. package/plugins/codex/src/hooks.ts +1 -0
  149. package/plugins/codex/src/identity.ts +14 -1
  150. package/plugins/codex/src/mcp.ts +28 -98
  151. package/plugins/codex/src/text.ts +3 -3
  152. package/plugins/dsh/tools.ts +8 -4
  153. package/plugins/mcp/operations.ts +50 -0
  154. package/plugins/mcp/server.ts +23 -0
  155. package/plugins/paseo/README.md +5 -10
  156. package/plugins/paseo/client/brain-empty-card.tsx +3 -3
  157. package/plugins/paseo/client/markdown.tsx +50 -38
  158. package/plugins/paseo/client/notes-op-card.tsx +12 -9
  159. package/plugins/paseo/client/paper-card.tsx +6 -5
  160. package/plugins/paseo/client/paper-palette.ts +2 -9
  161. package/plugins/paseo/client/sticky-card.tsx +2 -2
  162. package/plugins/paseo/client/tool-result.ts +7 -14
  163. package/plugins/paseo/package-lock.json +3406 -0
  164. package/plugins/paseo/package.json +1 -0
  165. package/plugins/paseo/test/markdown-core.test.ts +73 -66
  166. package/plugins/pi/budget.ts +31 -8
  167. package/plugins/pi/entries.ts +2 -0
  168. package/plugins/pi/history-tools.ts +2 -1
  169. package/plugins/pi/history.ts +30 -1
  170. package/plugins/pi/notes/tools.ts +7 -3
  171. package/plugins/pi/render.ts +6 -6
  172. package/plugins/pi/reset/artifacts.ts +4 -3
  173. package/plugins/pi/reset/lifecycle.ts +125 -32
  174. package/plugins/pi/runtime.ts +98 -62
  175. package/plugins/pi/tool-result.ts +8 -8
  176. package/plugins/pi/window.ts +210 -10
  177. package/skills/dream/SKILL.md +1 -1
  178. package/skills/notesoup-guide/SKILL.md +92 -0
  179. package/src/boot/render.ts +18 -15
  180. package/src/boot/text.ts +23 -19
  181. package/src/budget/text.ts +27 -15
  182. package/src/history/claude.ts +41 -0
  183. package/src/history/codex-transcript.ts +6 -4
  184. package/src/history/codex.ts +2 -0
  185. package/src/history/corpus.ts +51 -2
  186. package/src/history/history.ts +35 -44
  187. package/src/history/local.ts +67 -27
  188. package/src/history/pi.ts +113 -35
  189. package/src/history/prefilter.ts +73 -15
  190. package/src/history/query.ts +93 -73
  191. package/src/history/summary-cache.ts +142 -17
  192. package/src/index.ts +2 -2
  193. package/src/notes/errors.ts +1 -1
  194. package/src/notes/frontmatter.ts +0 -3
  195. package/src/notes/index.ts +1 -1
  196. package/src/notes/policy.ts +44 -5
  197. package/src/notes/store.ts +17 -20
  198. package/src/text-match.ts +46 -4
  199. package/src/tools/dream.ts +29 -31
  200. package/src/tools/history.ts +249 -142
  201. package/src/tools/notes.ts +145 -113
  202. package/src/tools/output.ts +2 -1
  203. package/src/tools/result.ts +12 -11
  204. package/src/tools/schema.ts +24 -1
  205. package/plugins/claude/skills/memory/SKILL.md +0 -69
  206. package/plugins/codex/mcp.json +0 -10
  207. package/plugins/codex/plugin.json +0 -6
  208. package/plugins/paseo/client/markdown-core.tsx +0 -189
  209. package/plugins/paseo/client/typography.ts +0 -24
  210. package/skills/memory/SKILL.md +0 -69
@@ -1,21 +1,7 @@
1
1
  /** Stable-anchor paging, folding and literal matching. The operation supplies the full-response budget check. */
2
- import { Type } from "typebox";
3
2
  import { success } from "../result.js";
4
- import { earliestMatchOffsetChars, prefixFit } from "../text-match.js";
5
- import { eventDocument, filteredItems, matchesFilter, visibleItem, HistoryFoldedRowSchema, HistoryPageItemSchema, MAX_FOLD_TOOL_NAMES, MAX_FOLD_TOOL_NAME_CHARS } from "./history.js";
6
- const multiPages = new WeakSet();
7
- export function isMultiPage(page) { return multiPages.has(page); }
8
- export function markMultiPage(page) {
9
- multiPages.add(page);
10
- return page;
11
- }
12
- export const HistoryPageSchema = Type.Object({
13
- notice: Type.Optional(Type.String()),
14
- items: Type.Array(HistoryPageItemSchema),
15
- folded_after: Type.Optional(HistoryFoldedRowSchema),
16
- has_older: Type.Boolean(),
17
- has_newer: Type.Boolean(),
18
- }, { additionalProperties: false });
3
+ import { compileSearchQueries, earliestMatchOffsetChars, prefixFit } from "../text-match.js";
4
+ import { eventDocument, eventTimestampMs, filteredItems, matchesFilter, visibleItem, MAX_FOLD_TOOL_NAMES, MAX_FOLD_TOOL_NAME_CHARS } from "./history.js";
19
5
  /** Shorten preview text first; omit an oversized tool name rather than invent a partial name. */
20
6
  function truncateHistoryItem(item, fits) {
21
7
  if (fits(item))
@@ -34,7 +20,7 @@ function truncateHistoryItem(item, fits) {
34
20
  return fits(withoutName) ? withoutName : shrinkContent(withoutName);
35
21
  }
36
22
  /** Summarize one already ordered gap; omitted tool names never change its exact count. */
37
- function foldedRun(events, session) {
23
+ function foldedRun(events) {
38
24
  if (events.length === 0)
39
25
  return undefined;
40
26
  const counts = new Map();
@@ -47,36 +33,34 @@ function foldedRun(events, session) {
47
33
  const entries = [...counts].filter(([name]) => name.length <= MAX_FOLD_TOOL_NAME_CHARS).slice(0, MAX_FOLD_TOOL_NAMES);
48
34
  // fromEntries preserves __proto__ as an ordinary key without mutating the prototype.
49
35
  const tools = Object.fromEntries(entries);
50
- return { ...(session === undefined ? {} : { session }), first_seq: events[0].seq, last_seq: events.at(-1).seq, count: events.length, tools };
36
+ return { first_seq: events[0].seq, last_seq: events.at(-1).seq, count: events.length, tools };
51
37
  }
52
38
  // Tool/thinking-only envelopes are not dialogue, even with explicit roles.
53
39
  const visible = (event) => (event.role !== "user" && event.role !== "assistant") || eventDocument(event) !== "";
54
- function* queryHits(projection, params, session) {
55
- const { query, context } = params;
40
+ function* queryHits(projection, params, patterns, session) {
41
+ const { context } = params;
56
42
  const events = filteredItems(projection, context ? {} : params).filter(visible);
57
43
  for (const [index, event] of events.entries()) {
58
44
  if (context && !matchesFilter(event, params))
59
45
  continue;
60
- const matchOffset = earliestMatchOffsetChars(eventDocument(event), query);
46
+ const matchOffset = earliestMatchOffsetChars(eventDocument(event), patterns);
61
47
  if (matchOffset >= 0)
62
48
  yield { event, session, matchOffset, neighbors: context ? { events, index } : undefined };
63
49
  }
64
50
  }
65
51
  function prepareSelection(projection, params) {
66
- const { query, roles, session } = params;
67
- if (query)
68
- return { candidates: [...queryHits(projection, params, session)] };
52
+ const { roles } = params;
69
53
  const candidates = [];
70
54
  let run = [];
71
55
  for (const event of filteredItems(projection, params).filter(visible)) {
72
56
  if (!roles && (event.role === "tool" || event.role === "context"))
73
57
  run.push(event);
74
58
  else {
75
- candidates.push({ event, session, before: foldedRun(run, session) });
59
+ candidates.push({ event, before: foldedRun(run) });
76
60
  run = [];
77
61
  }
78
62
  }
79
- return { candidates, tail: foldedRun(run, session) };
63
+ return { candidates, tail: foldedRun(run) };
80
64
  }
81
65
  /** Assemble only the admitted interval. Edge folds belong only to a page reaching that edge. */
82
66
  function pageData(prepared, start, end, maxChars, preview) {
@@ -87,17 +71,48 @@ function pageData(prepared, start, end, maxChars, preview) {
87
71
  const item = preview ?? (candidate.preview ??= { ...visibleItem(candidate.event, maxChars, candidate.matchOffset), ...(candidate.session === undefined ? {} : { session: candidate.session }) });
88
72
  items.push(candidate.before && (index > start || start === 0) ? { ...item, folded_before: candidate.before } : item);
89
73
  }
90
- const page = {
74
+ return {
91
75
  items,
92
76
  ...(end === candidates.length && tail ? { folded_after: tail } : {}),
93
77
  has_older: (start > 0 && start < end) || (!!prepared.discarded && !prepared.forward),
94
78
  has_newer: (end < candidates.length && start < end) || (!!prepared.discarded && !!prepared.forward),
95
79
  };
96
- return prepared.multi ? markMultiPage(page) : page;
97
80
  }
98
81
  export function selectPage(projection, params, fits, maxChars) {
99
82
  return selectPrepared(prepareSelection(projection, params), params, fits, maxChars);
100
83
  }
84
+ export function summarizeProjection(projection) {
85
+ const events = filteredItems(projection, {}).filter(visible);
86
+ let firstUser;
87
+ let lastAssistant;
88
+ const latestByRole = {};
89
+ let minCreatedAt = Infinity;
90
+ let maxCreatedAt = -Infinity;
91
+ let hasUntimed = false;
92
+ for (const event of events) {
93
+ if (firstUser === undefined && event.role === "user")
94
+ firstUser = event;
95
+ if (event.role === "assistant")
96
+ lastAssistant = event;
97
+ latestByRole[event.role] = event;
98
+ const at = eventTimestampMs(event);
99
+ if (Number.isNaN(at))
100
+ hasUntimed = true;
101
+ else {
102
+ if (at < minCreatedAt)
103
+ minCreatedAt = at;
104
+ if (at > maxCreatedAt)
105
+ maxCreatedAt = at;
106
+ }
107
+ }
108
+ return {
109
+ event: firstUser ?? lastAssistant ?? events.at(-1),
110
+ latestByRole,
111
+ minCreatedAt: Number.isFinite(minCreatedAt) ? minCreatedAt : null,
112
+ maxCreatedAt: Number.isFinite(maxCreatedAt) ? maxCreatedAt : null,
113
+ hasUntimed,
114
+ };
115
+ }
101
116
  /** One topic per session, after role/time filtering; empty dialogue envelopes are not visible. */
102
117
  export function sessionRepresentative(projection, scoped) {
103
118
  const events = filteredItems(projection, scoped).filter(visible);
@@ -107,16 +122,13 @@ export function sessionRepresentative(projection, scoped) {
107
122
  ?? events.filter((event) => event.role === "assistant").at(-1)
108
123
  ?? events.at(-1);
109
124
  }
110
- function eventTime(timestamp) {
111
- const at = Date.parse(timestamp ?? "");
112
- return Number.isNaN(at) ? -Infinity : at;
113
- }
114
- const compareCorpus = (a, b) => eventTime(a.event.createdAt) - eventTime(b.event.createdAt) || a.session.localeCompare(b.session) || a.event.seq - b.event.seq;
125
+ const earliestIfUntimed = (at) => Number.isNaN(at) ? -Infinity : at;
126
+ const compareCorpus = (a, b) => earliestIfUntimed(eventTimestampMs(a.event)) - earliestIfUntimed(eventTimestampMs(b.event)) || (a.session ?? "").localeCompare(b.session ?? "") || a.event.seq - b.event.seq;
115
127
  /** Fill the remaining budget nearest first. Shared session/seq keys merge overlapping windows. */
116
128
  function addContext(page, hits, radius, fits, maxChars) {
117
129
  const key = (session, seq) => `${session ?? ""}\0${seq}`;
118
130
  const seen = new Set(page.items.map(item => key(item.session, item.seq)));
119
- const compare = (a, b) => (isMultiPage(page) ? eventTime(a.created_at) - eventTime(b.created_at) || a.session.localeCompare(b.session) : 0) || a.seq - b.seq;
131
+ const compare = (a, b) => earliestIfUntimed(Date.parse(a.created_at ?? "")) - earliestIfUntimed(Date.parse(b.created_at ?? "")) || (a.session ?? "").localeCompare(b.session ?? "") || a.seq - b.seq;
120
132
  for (let distance = 1; distance <= radius; distance++) {
121
133
  let found = false;
122
134
  for (const { neighbors, session } of hits) {
@@ -149,10 +161,12 @@ export class CorpusCollector {
149
161
  scoped;
150
162
  candidates = [];
151
163
  limit;
164
+ compiledQuery;
152
165
  discarded = false;
153
166
  constructor(scoped) {
154
167
  this.scoped = scoped;
155
168
  this.limit = Math.min(500, Math.max(1, scoped.limit ?? 20));
169
+ this.compiledQuery = scoped.query?.length ? compileSearchQueries(scoped.query) : [];
156
170
  }
157
171
  admit(candidate) {
158
172
  // Upper bound preserves the stable ordering of equal candidates.
@@ -180,52 +194,53 @@ export class CorpusCollector {
180
194
  }
181
195
  this.candidates.splice(low, 0, candidate);
182
196
  }
183
- /** Admit an already selected strict overview event without selecting it a second time. */
184
- addRepresentative(session, event) {
197
+ /** Admit a session's overview representative (pre-selected or picked from a projection). */
198
+ addRepresentative(session, source) {
199
+ const event = source && "windows" in source ? sessionRepresentative(source, this.scoped) : source;
185
200
  if (!event)
186
201
  return false;
187
- this.admit({ session, event });
202
+ this.admit({ session: session || undefined, event });
188
203
  return true;
189
204
  }
190
- /** Returns whether this session contributes an overview representative. */
191
- add(session, projection) {
192
- if (this.scoped.query === undefined)
193
- return this.addRepresentative(session, sessionRepresentative(projection, this.scoped));
194
- for (const hit of queryHits(projection, this.scoped, session))
205
+ /** Admit every query match from one session; an empty query matches nothing. */
206
+ addMatches(session, projection) {
207
+ if (this.compiledQuery.length === 0)
208
+ return;
209
+ for (const hit of queryHits(projection, this.scoped, this.compiledQuery, session || undefined))
195
210
  this.admit(hit);
196
- return true;
197
211
  }
198
212
  page(fits, maxChars, unvisited = false) {
199
- return selectPrepared({ candidates: this.candidates, multi: true, discarded: this.discarded || unvisited, forward: !!this.scoped.after }, this.scoped, fits, maxChars);
213
+ const result = selectPrepared({ candidates: this.candidates, discarded: this.discarded || unvisited, forward: !!this.scoped.after }, this.scoped, fits, maxChars);
214
+ if (result.ok && this.compiledQuery.length > 0 && this.scoped.context) {
215
+ const count = result.data.items.length;
216
+ const hits = this.scoped.after ? this.candidates.slice(0, count) : this.candidates.slice(this.candidates.length - count);
217
+ addContext(result.data, hits, this.scoped.context, fits, maxChars);
218
+ }
219
+ return result;
200
220
  }
201
221
  }
202
222
  function selectPrepared(prepared, scoped, fits, maxChars) {
203
223
  const { candidates } = prepared;
204
- // Grow a contiguous interval from the requested end; even a byte-limited newest page stays ascending.
205
- const newest = scoped.after === undefined;
206
- let start = newest ? candidates.length : 0;
207
- let end = start;
208
- const limit = Math.max(1, scoped.limit ?? 20);
209
- for (let count = 0; count < limit && (newest ? start > 0 : end < candidates.length); count++) {
210
- const nextStart = newest ? start - 1 : start;
211
- const nextEnd = newest ? end : end + 1;
212
- if (fits(pageData(prepared, nextStart, nextEnd, maxChars))) {
213
- start = nextStart;
214
- end = nextEnd;
215
- continue;
224
+ // Keep a contiguous interval from the requested end, always presented oldest first.
225
+ const newest = scoped.after === undefined && (scoped.before !== undefined || scoped.since === undefined);
226
+ const start = (count) => newest ? candidates.length - count : 0;
227
+ const pageFor = (count, preview) => pageData(prepared, start(count), start(count) + count, maxChars, preview);
228
+ let count = Math.min(Math.max(1, scoped.limit ?? 20), candidates.length);
229
+ if (count > 0 && !fits(pageFor(count))) {
230
+ let low = 0, high = count - 1;
231
+ while (low < high) {
232
+ const mid = Math.ceil((low + high) / 2);
233
+ if (fits(pageFor(mid)))
234
+ low = mid;
235
+ else
236
+ high = mid - 1;
216
237
  }
217
- if (start === end) {
218
- start = nextStart;
219
- end = nextEnd;
220
- const candidate = candidates[start];
221
- candidate.preview = truncateHistoryItem(candidate.preview, (preview) => fits(pageData(prepared, start, end, maxChars, preview)));
238
+ count = Math.max(1, low);
239
+ if (low === 0) {
240
+ const candidate = candidates[start(1)];
241
+ candidate.preview = truncateHistoryItem(candidate.preview, preview => fits(pageFor(1, preview)));
222
242
  }
223
- break;
224
243
  }
225
- const page = pageData(prepared, start, end, maxChars);
226
- if (!fits(page))
227
- return { ok: false, pageTooLarge: { count: page.items.length, multi: prepared.multi === true } };
228
- if (scoped.context)
229
- addContext(page, candidates.slice(start, end), scoped.context, fits, maxChars);
230
- return success(page);
244
+ const page = pageFor(count);
245
+ return fits(page) ? success(page) : { ok: false, pageTooLarge: true };
231
246
  }
@@ -1,10 +1,17 @@
1
- import { type HistorySession, type HistorySessionData, type HistorySessionRepresentative } from "./corpus.js";
1
+ import { type HistorySession, type HistorySessionData, type HistorySessionRepresentative, type HistorySessionSummary } from "./corpus.js";
2
2
  import { type CodexLineageSource } from "./codex-transcript.js";
3
+ export declare const HISTORY_SUMMARY_CACHE_TTL_MS: number;
3
4
  /** Internal root selection; the host's home/env seams also keep filesystem tests hermetic. */
4
5
  export declare function historySummaryCacheRoot(home?: string, env?: NodeJS.ProcessEnv, platform?: NodeJS.Platform): string;
6
+ /** Remove expired (>3 days), obsolete-version (e.g. v1), and stale temporary cache files. */
7
+ export declare function pruneHistorySummaryCache(cacheRoot: string, now?: number): Promise<void>;
5
8
  export type RepresentativeLoad = (track: (path: string) => Promise<void>) => Promise<{
6
9
  data: HistorySessionData;
7
10
  lineageSources?: CodexLineageSource[];
8
11
  }>;
12
+ /** Read-only check of a warm, validated summary; never decodes on miss. */
13
+ export declare function peekCachedSessionSummary(session: Pick<HistorySession, "harness" | "id">, transcriptPath: string, cacheRoot: string): Promise<HistorySessionSummary | undefined>;
14
+ /** The loader always runs the strict decoder on misses; transcript errors deliberately escape. */
15
+ export declare function cachedSessionSummary(session: Pick<HistorySession, "harness" | "id">, transcriptPath: string, cacheRoot: string, load: RepresentativeLoad): Promise<HistorySessionSummary>;
9
16
  /** The loader always runs the strict decoder on misses; transcript errors deliberately escape. */
10
17
  export declare function cachedSessionRepresentative(session: Pick<HistorySession, "harness" | "id">, transcriptPath: string, cacheRoot: string, load: RepresentativeLoad): Promise<HistorySessionRepresentative>;
@@ -1,17 +1,22 @@
1
1
  /** Strict offline overview summaries, never projections or search indexes. Cache failures are misses. */
2
2
  import { createHash, randomUUID } from "node:crypto";
3
- import { mkdir, open, realpath, rename, stat, unlink, writeFile } from "node:fs/promises";
3
+ import { mkdir, open, readdir, realpath, rename, stat, unlink, writeFile } from "node:fs/promises";
4
4
  import { homedir } from "node:os";
5
5
  import { join } from "node:path";
6
6
  import { Type } from "typebox";
7
7
  import { Check } from "typebox/value";
8
8
  import { sessionIdentity } from "./corpus.js";
9
9
  import { HistoryRoleSchema, ToolCallStatusSchema } from "./history.js";
10
- import { sessionRepresentative } from "./query.js";
10
+ import { summarizeProjection } from "./query.js";
11
11
  import { validateCodexLineageSources } from "./codex-transcript.js";
12
12
  // Bump whenever strict decoding, representative selection, or cached event presentation changes.
13
- const VERSION = "strict-representative-v1";
13
+ const VERSION = "strict-summary-v3";
14
+ const VERSION_PREFIX = `{"version":${JSON.stringify(VERSION)}`;
14
15
  const MAX_ENTRY_BYTES = 8 * 1024 * 1024;
16
+ export const HISTORY_SUMMARY_CACHE_TTL_MS = 3 * 24 * 60 * 60 * 1000;
17
+ const SWEEP_INTERVAL_MS = 10 * 60 * 1000;
18
+ const TMP_TTL_MS = 60 * 60 * 1000;
19
+ const lastSweep = new Map();
15
20
  const FingerprintSchema = Type.Object({
16
21
  path: Type.String(), dev: Type.String(), ino: Type.String(), size: Type.String(), mtimeNs: Type.String(), ctimeNs: Type.String(),
17
22
  }, { additionalProperties: false });
@@ -29,9 +34,20 @@ const EventSchema = Type.Object({
29
34
  }, { additionalProperties: false })) }, { additionalProperties: false })),
30
35
  }, { additionalProperties: false })),
31
36
  }, { additionalProperties: false });
37
+ const LatestByRoleSchema = Type.Object({
38
+ user: Type.Optional(EventSchema),
39
+ assistant: Type.Optional(EventSchema),
40
+ tool: Type.Optional(EventSchema),
41
+ context: Type.Optional(EventSchema),
42
+ }, { additionalProperties: false });
32
43
  const EntrySchema = Type.Object({
33
44
  version: Type.Literal(VERSION), path: Type.String(), session: Type.String(),
34
- event: Type.Union([EventSchema, Type.Null()]), notice: Type.Optional(Type.String()),
45
+ event: Type.Union([EventSchema, Type.Null()]),
46
+ latestByRole: LatestByRoleSchema,
47
+ minCreatedAt: Type.Union([Type.Number(), Type.Null()]),
48
+ maxCreatedAt: Type.Union([Type.Number(), Type.Null()]),
49
+ hasUntimed: Type.Boolean(),
50
+ notice: Type.Optional(Type.String()),
35
51
  fingerprints: Type.Array(FingerprintSchema, { minItems: 1, maxItems: 64 }),
36
52
  lineageSources: Type.Array(Type.Object({ home: Type.String(), rolloutId: Type.String(), path: Type.String() }, { additionalProperties: false }), { maxItems: 63 }),
37
53
  }, { additionalProperties: false });
@@ -58,12 +74,17 @@ function completeDependencies(path, harness, sources, lineage) {
58
74
  const expected = [path, ...lineage.map((source) => source.path)];
59
75
  return sources.length === expected.length && new Set(expected).size === expected.length && sources.every((source, index) => source.path === expected[index]);
60
76
  }
61
- async function readEntry(path) {
77
+ async function readEntry(path, now = Date.now()) {
62
78
  const file = await open(path, "r");
79
+ let expired = false;
63
80
  try {
64
81
  const info = await file.stat();
65
82
  if (!info.isFile() || info.size > MAX_ENTRY_BYTES)
66
83
  return undefined;
84
+ if (now - info.mtimeMs > HISTORY_SUMMARY_CACHE_TTL_MS) {
85
+ expired = true;
86
+ return undefined;
87
+ }
67
88
  const buffer = Buffer.alloc(info.size + 1);
68
89
  const { bytesRead } = await file.read(buffer, 0, buffer.length, 0);
69
90
  if (bytesRead > MAX_ENTRY_BYTES || (await file.stat()).size > MAX_ENTRY_BYTES)
@@ -72,10 +93,74 @@ async function readEntry(path) {
72
93
  }
73
94
  finally {
74
95
  await file.close();
96
+ if (expired)
97
+ await unlink(path).catch(() => { });
75
98
  }
76
99
  }
77
- /** The loader always runs the strict decoder on misses; transcript errors deliberately escape. */
78
- export async function cachedSessionRepresentative(session, transcriptPath, cacheRoot, load) {
100
+ async function hasCurrentVersionPrefix(path) {
101
+ const file = await open(path, "r");
102
+ try {
103
+ const buffer = Buffer.alloc(VERSION_PREFIX.length);
104
+ const { bytesRead } = await file.read(buffer, 0, buffer.length, 0);
105
+ return bytesRead === VERSION_PREFIX.length && buffer.toString("utf8") === VERSION_PREFIX;
106
+ }
107
+ catch {
108
+ return false;
109
+ }
110
+ finally {
111
+ await file.close();
112
+ }
113
+ }
114
+ /** Remove expired (>3 days), obsolete-version (e.g. v1), and stale temporary cache files. */
115
+ export async function pruneHistorySummaryCache(cacheRoot, now = Date.now()) {
116
+ let entries;
117
+ try {
118
+ entries = await readdir(cacheRoot, { withFileTypes: true });
119
+ }
120
+ catch {
121
+ return;
122
+ }
123
+ for (const entry of entries) {
124
+ if (!entry.isFile())
125
+ continue;
126
+ const full = join(cacheRoot, entry.name);
127
+ try {
128
+ const info = await stat(full);
129
+ if (entry.name.endsWith(".tmp")) {
130
+ if (now - info.mtimeMs > TMP_TTL_MS)
131
+ await unlink(full).catch(() => { });
132
+ continue;
133
+ }
134
+ if (!entry.name.endsWith(".json"))
135
+ continue;
136
+ if (now - info.mtimeMs > HISTORY_SUMMARY_CACHE_TTL_MS || !await hasCurrentVersionPrefix(full)) {
137
+ await unlink(full).catch(() => { });
138
+ }
139
+ }
140
+ catch { /* Concurrent unlink or unreadable file: ignore. */ }
141
+ }
142
+ }
143
+ function maybeSweepCacheRoot(cacheRoot) {
144
+ const now = Date.now();
145
+ const previous = lastSweep.get(cacheRoot);
146
+ if (previous !== undefined && now - previous < SWEEP_INTERVAL_MS)
147
+ return;
148
+ lastSweep.set(cacheRoot, now);
149
+ void pruneHistorySummaryCache(cacheRoot, now).catch(() => { });
150
+ }
151
+ function hydrateEvent(event) {
152
+ return { ...event, createdAt: event.createdAt };
153
+ }
154
+ function hydrateLatestByRole(raw) {
155
+ const out = {};
156
+ for (const role of ["user", "assistant", "tool", "context"]) {
157
+ const ev = raw[role];
158
+ if (ev)
159
+ out[role] = hydrateEvent(ev);
160
+ }
161
+ return out;
162
+ }
163
+ async function lookupCachedSummary(session, transcriptPath, cacheRoot) {
79
164
  let canonical, cachePath;
80
165
  const identity = sessionIdentity(session);
81
166
  try {
@@ -86,10 +171,33 @@ export async function cachedSessionRepresentative(session, transcriptPath, cache
86
171
  && completeDependencies(canonical, session.harness, entry.fingerprints, entry.lineageSources)
87
172
  && await validateCodexLineageSources(entry.lineageSources) && await unchanged(entry.fingerprints)
88
173
  && await realpath(transcriptPath) === canonical) {
89
- return { event: entry.event === null ? undefined : { ...entry.event, createdAt: entry.event.createdAt }, notice: entry.notice };
174
+ return {
175
+ canonical,
176
+ cachePath,
177
+ summary: {
178
+ event: entry.event === null ? undefined : hydrateEvent(entry.event),
179
+ latestByRole: hydrateLatestByRole(entry.latestByRole),
180
+ minCreatedAt: entry.minCreatedAt,
181
+ maxCreatedAt: entry.maxCreatedAt,
182
+ hasUntimed: entry.hasUntimed,
183
+ notice: entry.notice,
184
+ },
185
+ };
90
186
  }
91
187
  }
92
- catch { /* Absent/corrupt/unwritable cache or changed source: strict load below. */ }
188
+ catch { /* Absent/corrupt/unwritable cache or changed source: miss. */ }
189
+ return { canonical, cachePath };
190
+ }
191
+ /** Read-only check of a warm, validated summary; never decodes on miss. */
192
+ export async function peekCachedSessionSummary(session, transcriptPath, cacheRoot) {
193
+ return (await lookupCachedSummary(session, transcriptPath, cacheRoot)).summary;
194
+ }
195
+ /** The loader always runs the strict decoder on misses; transcript errors deliberately escape. */
196
+ export async function cachedSessionSummary(session, transcriptPath, cacheRoot, load) {
197
+ const identity = sessionIdentity(session);
198
+ const { summary, canonical, cachePath } = await lookupCachedSummary(session, transcriptPath, cacheRoot);
199
+ if (summary)
200
+ return summary;
93
201
  const fingerprints = new Map();
94
202
  let stable = canonical !== undefined;
95
203
  const track = async (path) => {
@@ -104,14 +212,26 @@ export async function cachedSessionRepresentative(session, transcriptPath, cache
104
212
  if (canonical)
105
213
  await track(canonical);
106
214
  const { data, lineageSources = [] } = await load(track);
107
- const event = sessionRepresentative(data.projection, {});
108
- const result = { event, notice: data.notice };
215
+ const computed = summarizeProjection(data.projection);
216
+ const result = { ...computed, notice: data.notice, loaded: data };
109
217
  try {
110
218
  const sources = [...fingerprints.values()];
111
219
  if (!stable || !canonical || !cachePath || !completeDependencies(canonical, session.harness, sources, lineageSources)
112
220
  || !await validateCodexLineageSources(lineageSources) || !await unchanged(sources) || await realpath(transcriptPath) !== canonical)
113
221
  return result;
114
- const entry = JSON.stringify({ version: VERSION, path: canonical, session: identity, event: event ?? null, notice: data.notice, fingerprints: sources, lineageSources });
222
+ const entry = JSON.stringify({
223
+ version: VERSION,
224
+ path: canonical,
225
+ session: identity,
226
+ event: computed.event ?? null,
227
+ latestByRole: computed.latestByRole,
228
+ minCreatedAt: computed.minCreatedAt,
229
+ maxCreatedAt: computed.maxCreatedAt,
230
+ hasUntimed: computed.hasUntimed,
231
+ notice: data.notice,
232
+ fingerprints: sources,
233
+ lineageSources,
234
+ });
115
235
  if (Buffer.byteLength(entry) > MAX_ENTRY_BYTES)
116
236
  return result;
117
237
  await mkdir(cacheRoot, { recursive: true, mode: 0o700 });
@@ -119,6 +239,7 @@ export async function cachedSessionRepresentative(session, transcriptPath, cache
119
239
  try {
120
240
  await writeFile(temporary, entry, { flag: "wx", mode: 0o600 });
121
241
  await rename(temporary, cachePath);
242
+ maybeSweepCacheRoot(cacheRoot);
122
243
  }
123
244
  finally {
124
245
  await unlink(temporary).catch(() => { });
@@ -127,3 +248,8 @@ export async function cachedSessionRepresentative(session, transcriptPath, cache
127
248
  catch { /* The cache cannot turn readable history into a refusal. */ }
128
249
  return result;
129
250
  }
251
+ /** The loader always runs the strict decoder on misses; transcript errors deliberately escape. */
252
+ export async function cachedSessionRepresentative(session, transcriptPath, cacheRoot, load) {
253
+ const { event, notice } = await cachedSessionSummary(session, transcriptPath, cacheRoot, load);
254
+ return { event, notice };
255
+ }
@@ -21,7 +21,7 @@ export { DEFAULT_BOOT_TOOL_NAMES, renderProtocolBlock } from "./boot/text.js";
21
21
  export type { BootToolNames } from "./boot/text.js";
22
22
  export { notesList, notesRead, notesUpdate, notesWrite } from "./tools/notes.js";
23
23
  export { notesIdentityForCall, notesToolContext, type NotesToolContext } from "./tools/notes-context.js";
24
- export { historyList, historyRead } from "./tools/history.js";
24
+ export { historyList, historySearch, historyRead } from "./tools/history.js";
25
25
  export { projectHistory } from "./history/history.js";
26
26
  export type { HistoryProjection } from "./history/history.js";
27
27
  export type { HistoryContext, HistoryCorpus, HistoryHarness, HistorySession, HistorySessionData } from "./history/corpus.js";
@@ -30,4 +30,4 @@ export type { Operation, Renderer, TextWindow } from "./tools/result.js";
30
30
  export { deriveThresholds, remainingBudget } from "./budget/policy.js";
31
31
  export type { ResolvedThresholds } from "./budget/policy.js";
32
32
  export { selectContinuation, tokenBudgetGuidance, warningPrompt, WARNING_BODY } from "./budget/text.js";
33
- export type { ResetOrigin } from "./budget/text.js";
33
+ export type { ContinuationOptions, ResetOrigin } from "./budget/text.js";
package/dist/src/index.js CHANGED
@@ -21,7 +21,7 @@ export { DEFAULT_BOOT_TOOL_NAMES, renderProtocolBlock } from "./boot/text.js";
21
21
  // host-supplied notes tool context or decoded history projection/lazy corpus context.
22
22
  export { notesList, notesRead, notesUpdate, notesWrite } from "./tools/notes.js";
23
23
  export { notesIdentityForCall, notesToolContext } from "./tools/notes-context.js";
24
- export { historyList, historyRead } from "./tools/history.js";
24
+ export { historyList, historySearch, historyRead } from "./tools/history.js";
25
25
  export { projectHistory } from "./history/history.js";
26
26
  // Budget: pure thresholds and the approved reset prose.
27
27
  export { deriveThresholds, remainingBudget } from "./budget/policy.js";
@@ -1,4 +1,4 @@
1
- export type NoteErrorCode = "invalid_policy" | "invalid_description" | "pin_limit" | "readonly" | "not_found" | "already_exists" | "ambiguous_edit" | "no_match" | "invalid_edit" | "nothing_to_do" | "not_crumpled" | "too_large" | "invalid_scope" | "invalid_origin" | "invalid_address" | "invalid_pattern" | "invalid_query" | "invalid_offset" | "invalid_cwd" | "io_error" | "internal_error";
1
+ export type NoteErrorCode = "invalid_policy" | "pin_limit" | "readonly" | "not_found" | "already_exists" | "ambiguous_edit" | "no_match" | "invalid_edit" | "nothing_to_do" | "not_crumpled" | "too_large" | "invalid_scope" | "invalid_origin" | "invalid_address" | "invalid_pattern" | "invalid_query" | "invalid_offset" | "invalid_cwd" | "io_error" | "internal_error";
2
2
  /** Typed store refusal. Edit locations are exposed in camelCase. */
3
3
  export declare class NoteError extends Error {
4
4
  readonly code: NoteErrorCode;
@@ -25,8 +25,6 @@ export type NoteMeta = NotePolicyFields & {
25
25
  description?: string;
26
26
  [key: string]: unknown;
27
27
  };
28
- /** A note description is one line; longer is not a description, it is prose in the wrong place. */
29
- export declare const MAX_DESCRIPTION_CHARS = 160;
30
28
  /** Collapse any whitespace run to one space and trim; an empty result is no description. */
31
29
  export declare function collapseDescription(value: string): string | undefined;
32
30
  /**
@@ -4,8 +4,6 @@ const ORIGINS = ["user", "self", "external"];
4
4
  const TIMESTAMP_KEYS = ["createdAt", "updatedAt", "lastAccessed"];
5
5
  /** Emission order, exactly the Design's key list. */
6
6
  const KNOWN_KEYS = ["pinned", "budget", "readonly", "description", "origin", "crumpledAt", "createdAt", "updatedAt", "lastAccessed", "accessCount", "sourceWindow", "supersedes", "recurrenceCount", "recurrenceWindows"];
7
- /** A note description is one line; longer is not a description, it is prose in the wrong place. */
8
- export const MAX_DESCRIPTION_CHARS = 160;
9
7
  /** Collapse any whitespace run to one space and trim; an empty result is no description. */
10
8
  export function collapseDescription(value) {
11
9
  const collapsed = value.replace(/\s+/g, " ").trim();
@@ -1,4 +1,4 @@
1
- export { createNotesStore, noteIdentity } from "./store.js";
1
+ export { createNotesStore, noteIdentity, compareNoteRows } from "./store.js";
2
2
  export { effectiveNotePolicy, type NotePolicy, type NotePolicyFields } from "./policy.js";
3
3
  export { NoteError, type NoteErrorCode } from "./errors.js";
4
4
  export { projectKey } from "./project-namespace.js";
@@ -1,4 +1,4 @@
1
- export { createNotesStore, noteIdentity } from "./store.js";
1
+ export { createNotesStore, noteIdentity, compareNoteRows } from "./store.js";
2
2
  export { effectiveNotePolicy } from "./policy.js";
3
3
  export { NoteError } from "./errors.js";
4
4
  export { projectKey } from "./project-namespace.js";
@@ -4,13 +4,27 @@ export type NotePolicyFields = {
4
4
  readonly?: boolean;
5
5
  };
6
6
  export type NotePolicy = Required<NotePolicyFields>;
7
- export declare const DEFAULT_NOTE_BUDGET = 4096;
7
+ export declare const DEFAULT_NOTE_BUDGET = 8192;
8
+ export declare const DEFAULT_CHEATSHEET_BUDGET = 4096;
8
9
  export declare const MAX_PINNED_NOTES = 5;
10
+ export declare const WARNING_OPEN_TAG = "<notesoup:warning>";
11
+ export declare const WARNING_CLOSE_TAG = "</notesoup:warning>";
12
+ /** Boot index truncates descriptions past this code-point cap; longer values still save with a warning. */
13
+ export declare const MAX_DESCRIPTION_CHARS = 160;
9
14
  export declare function validateNotePolicy(fields: NotePolicyFields): void;
10
15
  /** Only root default pages are pinned implicitly; an explicit false always wins. */
11
16
  export declare function effectiveNotePolicy(fields: NotePolicyFields, path: string): NotePolicy;
12
17
  export declare function pinnedPageOrder(path: string): number;
18
+ export declare function truncateToUtf8Bytes(text: string, maxBytes: number): {
19
+ text: string;
20
+ shownChars: number;
21
+ totalChars: number;
22
+ truncated: boolean;
23
+ };
24
+ export declare function renderWarnings(warnings: readonly string[]): string;
13
25
  export declare function noteBudgetWarnings(body: string, policy: NotePolicy): string[];
26
+ export declare function noteDescriptionWarnings(description?: string): string[];
27
+ export declare function noteWarnings(body: string, policy: NotePolicy, description?: string): string[];
14
28
  export declare function assertNoteUnlocked(fields: NotePolicyFields, unlock?: boolean): void;
15
29
  /** Apply only explicit values, leaving absent on-disk defaults absent across moves. */
16
30
  export declare function applyNotePolicy(target: NotePolicyFields, fields: NotePolicyFields): void;