notesoup 0.60.1 → 0.62.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 (200) hide show
  1. package/.agents/plugins/marketplace.json +15 -0
  2. package/README.md +14 -10
  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 +2 -1
  10. package/dist/plugins/codex/src/hooks.js +1 -0
  11. package/dist/plugins/codex/src/identity.d.ts +6 -1
  12. package/dist/plugins/codex/src/identity.js +13 -1
  13. package/dist/plugins/codex/src/mcp.d.ts +35 -7
  14. package/dist/plugins/codex/src/mcp.js +26 -88
  15. package/dist/plugins/codex/src/text.js +3 -3
  16. package/dist/plugins/dsh/tools.js +8 -4
  17. package/dist/plugins/mcp/operations.d.ts +15 -0
  18. package/dist/plugins/mcp/operations.js +43 -0
  19. package/dist/plugins/mcp/server.d.ts +14 -0
  20. package/dist/plugins/mcp/server.js +13 -0
  21. package/dist/plugins/pi/budget.d.ts +1 -1
  22. package/dist/plugins/pi/budget.js +3 -2
  23. package/dist/plugins/pi/entries.d.ts +1 -0
  24. package/dist/plugins/pi/entries.js +1 -0
  25. package/dist/plugins/pi/history-tools.js +2 -1
  26. package/dist/plugins/pi/history.js +18 -1
  27. package/dist/plugins/pi/notes/tools.js +7 -3
  28. package/dist/plugins/pi/render.d.ts +7 -1
  29. package/dist/plugins/pi/render.js +2 -2
  30. package/dist/plugins/pi/reset/lifecycle.d.ts +1 -1
  31. package/dist/plugins/pi/reset/lifecycle.js +8 -9
  32. package/dist/plugins/pi/runtime.js +102 -61
  33. package/dist/plugins/pi/tool-result.js +7 -7
  34. package/dist/plugins/pi/window.d.ts +33 -3
  35. package/dist/plugins/pi/window.js +209 -9
  36. package/dist/src/boot/render.d.ts +5 -0
  37. package/dist/src/boot/render.js +60 -28
  38. package/dist/src/boot/text.d.ts +3 -3
  39. package/dist/src/boot/text.js +27 -26
  40. package/dist/src/budget/text.d.ts +2 -2
  41. package/dist/src/budget/text.js +13 -13
  42. package/dist/src/history/claude.d.ts +2 -0
  43. package/dist/src/history/claude.js +46 -0
  44. package/dist/src/history/codex-transcript.js +7 -5
  45. package/dist/src/history/codex.js +3 -0
  46. package/dist/src/history/corpus.d.ts +28 -1
  47. package/dist/src/history/corpus.js +40 -0
  48. package/dist/src/history/history.d.ts +37 -46
  49. package/dist/src/history/history.js +21 -40
  50. package/dist/src/history/local.js +67 -32
  51. package/dist/src/history/pi.d.ts +2 -1
  52. package/dist/src/history/pi.js +122 -48
  53. package/dist/src/history/prefilter.js +76 -19
  54. package/dist/src/history/query.d.ts +28 -49
  55. package/dist/src/history/query.js +83 -68
  56. package/dist/src/history/summary-cache.d.ts +8 -1
  57. package/dist/src/history/summary-cache.js +138 -12
  58. package/dist/src/index.d.ts +1 -1
  59. package/dist/src/index.js +1 -1
  60. package/dist/src/notes/frontmatter.d.ts +4 -0
  61. package/dist/src/notes/frontmatter.js +15 -1
  62. package/dist/src/notes/index.d.ts +1 -1
  63. package/dist/src/notes/index.js +1 -1
  64. package/dist/src/notes/policy.d.ts +15 -1
  65. package/dist/src/notes/policy.js +47 -6
  66. package/dist/src/notes/store.d.ts +14 -0
  67. package/dist/src/notes/store.js +33 -12
  68. package/dist/src/text-match.d.ts +10 -1
  69. package/dist/src/text-match.js +42 -3
  70. package/dist/src/tools/dream.d.ts +22 -91
  71. package/dist/src/tools/dream.js +30 -27
  72. package/dist/src/tools/history.d.ts +33 -26
  73. package/dist/src/tools/history.js +257 -163
  74. package/dist/src/tools/notes.d.ts +58 -160
  75. package/dist/src/tools/notes.js +151 -99
  76. package/dist/src/tools/output.d.ts +2 -1
  77. package/dist/src/tools/output.js +2 -1
  78. package/dist/src/tools/result.d.ts +4 -7
  79. package/dist/src/tools/result.js +8 -9
  80. package/dist/src/tools/schema.d.ts +4 -1
  81. package/dist/src/tools/schema.js +25 -1
  82. package/dist/test/agent-loop.test.js +198 -16
  83. package/dist/test/antigravity-live.test.d.ts +1 -0
  84. package/dist/test/antigravity-live.test.js +142 -0
  85. package/dist/test/antigravity-plugin.test.d.ts +1 -0
  86. package/dist/test/antigravity-plugin.test.js +101 -0
  87. package/dist/test/boot.integration.test.js +133 -14
  88. package/dist/test/claude-history.test.js +14 -13
  89. package/dist/test/claude-mod.test.js +9 -6
  90. package/dist/test/codex-history.test.js +15 -3
  91. package/dist/test/codex-plugin.test.js +76 -38
  92. package/dist/test/dependencies.test.js +7 -3
  93. package/dist/test/dream-skill.test.js +3 -3
  94. package/dist/test/dream-tools.test.js +101 -56
  95. package/dist/test/dsh.test.js +34 -19
  96. package/dist/test/helpers/dependency-graph.js +2 -2
  97. package/dist/test/helpers/extension.d.ts +65 -2
  98. package/dist/test/helpers/extension.js +72 -3
  99. package/dist/test/history-corpus.test.js +79 -77
  100. package/dist/test/history-summary-cache.test.js +97 -9
  101. package/dist/test/history.integration.test.js +234 -168
  102. package/dist/test/host-neutral.test.js +69 -19
  103. package/dist/test/marker.test.js +1 -1
  104. package/dist/test/note-policy.test.js +189 -56
  105. package/dist/test/notes.integration.test.js +212 -94
  106. package/dist/test/notes.test.js +184 -113
  107. package/dist/test/pi-render.test.js +20 -12
  108. package/dist/test/project-namespace.test.js +3 -2
  109. package/dist/test/reset-lifecycle.test.js +2 -2
  110. package/docs/antigravity.md +44 -0
  111. package/docs/architecture.md +6 -4
  112. package/docs/claude-code-mod.md +2 -2
  113. package/docs/codex.md +36 -38
  114. package/docs/dsh.md +4 -4
  115. package/docs/history-sessions.md +28 -50
  116. package/docs/notes-library.md +6 -6
  117. package/docs/reset-lifecycle.md +1 -1
  118. package/docs/skills.md +3 -3
  119. package/docs/tool-results.md +47 -28
  120. package/package.json +3 -2
  121. package/playbook.md +3 -3
  122. package/plugins/antigravity/dist/antigravity/notesoup.js +26886 -0
  123. package/plugins/antigravity/hooks.json +7 -0
  124. package/plugins/antigravity/mcp_config.json +8 -0
  125. package/plugins/antigravity/plugin.json +6 -0
  126. package/plugins/antigravity/src/cli.ts +22 -0
  127. package/plugins/antigravity/src/hooks.ts +51 -0
  128. package/plugins/antigravity/src/identity.ts +127 -0
  129. package/plugins/claude/.claude-plugin/plugin.json +1 -1
  130. package/plugins/claude/dist/claude/helper.js +1129 -549
  131. package/plugins/claude/hooks/register.ts +2 -2
  132. package/plugins/claude/playbook.md +3 -3
  133. package/plugins/claude/skills/dream/SKILL.md +2 -2
  134. package/plugins/claude/skills/notesoup/SKILL.md +92 -0
  135. package/plugins/claude/src/helper.ts +2 -1
  136. package/plugins/codex/.codex-plugin/plugin.json +8 -0
  137. package/plugins/codex/.mcp.json +11 -0
  138. package/plugins/codex/README.md +5 -21
  139. package/plugins/codex/dist/codex/notesoup.js +18494 -17905
  140. package/plugins/codex/src/hooks.ts +1 -0
  141. package/plugins/codex/src/identity.ts +14 -1
  142. package/plugins/codex/src/mcp.ts +28 -98
  143. package/plugins/codex/src/text.ts +3 -3
  144. package/plugins/dsh/tools.ts +8 -4
  145. package/plugins/mcp/operations.ts +50 -0
  146. package/plugins/mcp/server.ts +23 -0
  147. package/plugins/paseo/README.md +5 -10
  148. package/plugins/paseo/client/brain-empty-card.tsx +3 -3
  149. package/plugins/paseo/client/markdown.tsx +50 -38
  150. package/plugins/paseo/client/notes-op-card.tsx +12 -9
  151. package/plugins/paseo/client/paper-card.tsx +6 -5
  152. package/plugins/paseo/client/paper-palette.ts +2 -9
  153. package/plugins/paseo/client/sticky-card.tsx +2 -2
  154. package/plugins/paseo/client/tool-result.ts +7 -14
  155. package/plugins/paseo/package-lock.json +3406 -0
  156. package/plugins/paseo/package.json +1 -0
  157. package/plugins/paseo/test/markdown-core.test.ts +73 -66
  158. package/plugins/pi/budget.ts +3 -3
  159. package/plugins/pi/entries.ts +1 -0
  160. package/plugins/pi/history-tools.ts +2 -1
  161. package/plugins/pi/history.ts +30 -1
  162. package/plugins/pi/notes/tools.ts +7 -3
  163. package/plugins/pi/render.ts +6 -6
  164. package/plugins/pi/reset/lifecycle.ts +9 -10
  165. package/plugins/pi/runtime.ts +96 -60
  166. package/plugins/pi/tool-result.ts +8 -8
  167. package/plugins/pi/window.ts +198 -9
  168. package/skills/dream/SKILL.md +2 -2
  169. package/skills/notesoup/SKILL.md +92 -0
  170. package/src/boot/render.ts +59 -25
  171. package/src/boot/text.ts +30 -27
  172. package/src/budget/text.ts +13 -13
  173. package/src/history/claude.ts +41 -0
  174. package/src/history/codex-transcript.ts +6 -4
  175. package/src/history/codex.ts +2 -0
  176. package/src/history/corpus.ts +51 -2
  177. package/src/history/history.ts +35 -44
  178. package/src/history/local.ts +67 -27
  179. package/src/history/pi.ts +113 -35
  180. package/src/history/prefilter.ts +73 -15
  181. package/src/history/query.ts +93 -73
  182. package/src/history/summary-cache.ts +142 -17
  183. package/src/index.ts +1 -1
  184. package/src/notes/frontmatter.ts +16 -1
  185. package/src/notes/index.ts +1 -1
  186. package/src/notes/policy.ts +45 -6
  187. package/src/notes/store.ts +30 -15
  188. package/src/text-match.ts +46 -4
  189. package/src/tools/dream.ts +29 -31
  190. package/src/tools/history.ts +249 -142
  191. package/src/tools/notes.ts +150 -112
  192. package/src/tools/output.ts +2 -1
  193. package/src/tools/result.ts +12 -11
  194. package/src/tools/schema.ts +24 -1
  195. package/plugins/claude/skills/memory/SKILL.md +0 -69
  196. package/plugins/codex/mcp.json +0 -10
  197. package/plugins/codex/plugin.json +0 -6
  198. package/plugins/paseo/client/markdown-core.tsx +0 -189
  199. package/plugins/paseo/client/typography.ts +0 -24
  200. package/skills/memory/SKILL.md +0 -69
@@ -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";
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";
@@ -21,8 +21,12 @@ export type NoteMeta = NotePolicyFields & {
21
21
  recurrenceWindows?: string[];
22
22
  /** Project ownership on newly-created session notes; legacy/invalid values are preserved as-is. */
23
23
  project?: unknown;
24
+ /** One-line index entry: what the note holds and when to open it. */
25
+ description?: string;
24
26
  [key: string]: unknown;
25
27
  };
28
+ /** Collapse any whitespace run to one space and trim; an empty result is no description. */
29
+ export declare function collapseDescription(value: string): string | undefined;
26
30
  /**
27
31
  * Format epoch milliseconds as an ISO 8601 string in the host's local time zone with an
28
32
  * explicit numeric offset (e.g. 2026-09-15T17:31:45.392+08:00). A UTC host renders
@@ -3,7 +3,12 @@ const SCOPES = ["session", "project", "human", "agent", "model"];
3
3
  const ORIGINS = ["user", "self", "external"];
4
4
  const TIMESTAMP_KEYS = ["createdAt", "updatedAt", "lastAccessed"];
5
5
  /** Emission order, exactly the Design's key list. */
6
- const KNOWN_KEYS = ["pinned", "budget", "readonly", "origin", "crumpledAt", "createdAt", "updatedAt", "lastAccessed", "accessCount", "sourceWindow", "supersedes", "recurrenceCount", "recurrenceWindows"];
6
+ const KNOWN_KEYS = ["pinned", "budget", "readonly", "description", "origin", "crumpledAt", "createdAt", "updatedAt", "lastAccessed", "accessCount", "sourceWindow", "supersedes", "recurrenceCount", "recurrenceWindows"];
7
+ /** Collapse any whitespace run to one space and trim; an empty result is no description. */
8
+ export function collapseDescription(value) {
9
+ const collapsed = value.replace(/\s+/g, " ").trim();
10
+ return collapsed.length === 0 ? undefined : collapsed;
11
+ }
7
12
  const pad2 = (value) => String(value).padStart(2, "0");
8
13
  /**
9
14
  * Format epoch milliseconds as an ISO 8601 string in the host's local time zone with an
@@ -107,6 +112,15 @@ export function parseNote(raw, now = Date.now()) {
107
112
  for (const key of TIMESTAMP_KEYS)
108
113
  meta[key] = toEpoch(meta[key], now);
109
114
  meta.accessCount = typeof meta.accessCount === "number" && Number.isFinite(meta.accessCount) ? meta.accessCount : 0;
115
+ // A hand-edited description is never allowed to break a boot: non-strings are absent, empty
116
+ // ones are dropped, and an oversized one is cut only when rendered.
117
+ if (meta.description !== undefined) {
118
+ const description = typeof meta.description === "string" ? collapseDescription(meta.description) : undefined;
119
+ if (description === undefined)
120
+ delete meta.description;
121
+ else
122
+ meta.description = description;
123
+ }
110
124
  return { meta: meta, body };
111
125
  }
112
126
  /**
@@ -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;
@@ -1,15 +1,20 @@
1
1
  import { NoteError } from "./errors.js";
2
- export const DEFAULT_NOTE_BUDGET = 4096;
2
+ export const DEFAULT_NOTE_BUDGET = 8192;
3
+ export const DEFAULT_CHEATSHEET_BUDGET = 4096;
3
4
  export const MAX_PINNED_NOTES = 5;
5
+ export const WARNING_OPEN_TAG = "<notesoup:warning>";
6
+ export const WARNING_CLOSE_TAG = "</notesoup:warning>";
7
+ /** Boot index truncates descriptions past this code-point cap; longer values still save with a warning. */
8
+ export const MAX_DESCRIPTION_CHARS = 160;
4
9
  /** Defaults and ordering live here; no other layer assigns behavior by page name. */
5
- const DEFAULT_PINNED_PAGES = ["CHEATSHEET.md", "MAP.md"];
10
+ const DEFAULT_PINNED_PAGES = ["CHEATSHEET.md"];
6
11
  export function validateNotePolicy(fields) {
7
12
  for (const key of ["pinned", "readonly"]) {
8
13
  if (fields[key] !== undefined && typeof fields[key] !== "boolean")
9
14
  throw new NoteError("invalid_policy", `${key} must be a boolean.`);
10
15
  }
11
16
  if (fields.budget !== undefined && (!Number.isSafeInteger(fields.budget) || fields.budget <= 0)) {
12
- throw new NoteError("invalid_policy", "budget must be a positive safe integer of Unicode code points.");
17
+ throw new NoteError("invalid_policy", "budget must be a positive integer.");
13
18
  }
14
19
  }
15
20
  /** Only root default pages are pinned implicitly; an explicit false always wins. */
@@ -18,7 +23,7 @@ export function effectiveNotePolicy(fields, path) {
18
23
  const defaultPage = DEFAULT_PINNED_PAGES.some(page => page === path);
19
24
  return {
20
25
  pinned: fields.pinned ?? defaultPage,
21
- budget: fields.budget ?? (defaultPage ? 2048 : DEFAULT_NOTE_BUDGET),
26
+ budget: fields.budget ?? (defaultPage ? DEFAULT_CHEATSHEET_BUDGET : DEFAULT_NOTE_BUDGET),
22
27
  readonly: fields.readonly ?? false,
23
28
  };
24
29
  }
@@ -26,9 +31,45 @@ export function pinnedPageOrder(path) {
26
31
  const index = DEFAULT_PINNED_PAGES.findIndex(page => page === path);
27
32
  return index === -1 ? DEFAULT_PINNED_PAGES.length : index;
28
33
  }
34
+ export function truncateToUtf8Bytes(text, maxBytes) {
35
+ if (Buffer.byteLength(text, "utf8") <= maxBytes)
36
+ return { text, shownChars: 0, totalChars: 0, truncated: false };
37
+ const chars = Array.from(text);
38
+ let bytes = 0;
39
+ let shown = 0;
40
+ for (const char of chars) {
41
+ const size = Buffer.byteLength(char, "utf8");
42
+ if (bytes + size > maxBytes)
43
+ break;
44
+ bytes += size;
45
+ shown++;
46
+ }
47
+ return { text: chars.slice(0, shown).join(""), shownChars: shown, totalChars: chars.length, truncated: true };
48
+ }
49
+ export function renderWarnings(warnings) {
50
+ if (warnings.length === 0)
51
+ return "";
52
+ if (warnings.length === 1)
53
+ return `${WARNING_OPEN_TAG}${warnings[0]}${WARNING_CLOSE_TAG}`;
54
+ return `${WARNING_OPEN_TAG}\n${warnings.join("\n")}\n${WARNING_CLOSE_TAG}`;
55
+ }
29
56
  export function noteBudgetWarnings(body, policy) {
30
- const count = Array.from(body).length;
31
- return count > policy.budget ? [`Warning: note body is ${count} Unicode code points, over budget ${policy.budget} — boil it down.`] : [];
57
+ const bytes = Buffer.byteLength(body, "utf8");
58
+ if (bytes <= policy.budget)
59
+ return [];
60
+ const action = policy.pinned ? "boot truncates it to budget — trim, split, or unpin." : "trim or split it.";
61
+ return [`note body is ${bytes} bytes (budget ${policy.budget}); ${action}`];
62
+ }
63
+ export function noteDescriptionWarnings(description) {
64
+ if (description === undefined)
65
+ return [];
66
+ const count = Array.from(description).length;
67
+ return count > MAX_DESCRIPTION_CHARS
68
+ ? [`description is ${count} chars (max ${MAX_DESCRIPTION_CHARS}); boot index truncates it.`]
69
+ : [];
70
+ }
71
+ export function noteWarnings(body, policy, description) {
72
+ return [...noteBudgetWarnings(body, policy), ...noteDescriptionWarnings(description)];
32
73
  }
33
74
  export function assertNoteUnlocked(fields, unlock) {
34
75
  if (fields.readonly === true && unlock !== false)
@@ -4,6 +4,17 @@ import { type Scope } from "./paths.js";
4
4
  import { type ProjectReceipt } from "./project-namespace.js";
5
5
  import { type NotePolicyFields } from "./policy.js";
6
6
  export type { NoteMeta, Origin, Scope };
7
+ export declare function compareNoteRows(a: {
8
+ address: string;
9
+ meta: {
10
+ updatedAt: number;
11
+ };
12
+ }, b: {
13
+ address: string;
14
+ meta: {
15
+ updatedAt: number;
16
+ };
17
+ }): number;
7
18
  export type NoteRow = {
8
19
  address: string;
9
20
  scope: Scope;
@@ -28,12 +39,15 @@ export type NoteSearchRow = {
28
39
  export type EditOperation = {
29
40
  oldText: string;
30
41
  newText: string;
42
+ replaceAll?: boolean;
31
43
  };
32
44
  export type WriteOptions = NotePolicyFields & {
33
45
  origin?: Origin;
46
+ description?: string;
34
47
  };
35
48
  export type EditOptions = NotePolicyFields & {
36
49
  origin?: Origin;
50
+ description?: string;
37
51
  crumpled?: boolean;
38
52
  replaceAll?: boolean;
39
53
  renameTo?: string;
@@ -7,10 +7,13 @@ import { isFilesystemError } from "./fs-error.js";
7
7
  import { snapshotNotesIdentity } from "./identity.js";
8
8
  import { NoteError } from "./errors.js";
9
9
  import { MAX_NOTE_BYTES, MAX_NOTE_PATH_BYTES } from "./constants.js";
10
- import { isOrigin, localIso, parseNote, serializeNote, stripLeadingFrontmatter } from "./frontmatter.js";
10
+ import { collapseDescription, isOrigin, localIso, parseNote, serializeNote, stripLeadingFrontmatter } from "./frontmatter.js";
11
11
  import { namespaceSlugs, noteFileName, physicalPath, scopeDir, isSessionId, SLUG_PATTERN } from "./paths.js";
12
12
  import { projectReceipt } from "./project-namespace.js";
13
- import { applyNotePolicy, assertNoteUnlocked, effectiveNotePolicy, MAX_PINNED_NOTES, noteBudgetWarnings, validateNotePolicy } from "./policy.js";
13
+ import { applyNotePolicy, assertNoteUnlocked, effectiveNotePolicy, MAX_PINNED_NOTES, noteWarnings, validateNotePolicy } from "./policy.js";
14
+ export function compareNoteRows(a, b) {
15
+ return b.meta.updatedAt - a.meta.updatedAt || a.address.localeCompare(b.address);
16
+ }
14
17
  // Recency sorts tie-break by address, so two writes sharing one Date.now() tick would silently invert the recent-first contract. Write stamps are strictly increasing per process.
15
18
  let lastWriteStamp = 0;
16
19
  function writeStamp() {
@@ -283,6 +286,7 @@ export function createNotesStore(input) {
283
286
  async function write(address, content, options = {}) {
284
287
  const stableOptions = { ...options };
285
288
  validateNotePolicy(stableOptions);
289
+ const description = stableOptions.description === undefined ? undefined : collapseDescription(stableOptions.description);
286
290
  const destination = assertAddress(address);
287
291
  assertWritablePath(destination.path);
288
292
  const scope = destination.scope;
@@ -313,6 +317,12 @@ export function createNotesStore(input) {
313
317
  };
314
318
  meta.scope = scope;
315
319
  applyNotePolicy(meta, stableOptions);
320
+ if (description === undefined) {
321
+ if (stableOptions.description !== undefined)
322
+ delete meta.description;
323
+ }
324
+ else
325
+ meta.description = description;
316
326
  if (origin !== undefined)
317
327
  meta.origin = origin;
318
328
  delete meta.crumpledAt;
@@ -321,7 +331,7 @@ export function createNotesStore(input) {
321
331
  assertSerializedSize(serialized);
322
332
  await assertPinAdmission(root, noteFileName(destination.path), meta, previous);
323
333
  await atomicWrite(path, serialized);
324
- return { meta, outcome, warnings: noteBudgetWarnings(cleanBody, effectiveNotePolicy(meta, noteFileName(destination.path))) };
334
+ return { meta, outcome, warnings: noteWarnings(cleanBody, effectiveNotePolicy(meta, noteFileName(destination.path)), meta.description) };
325
335
  }));
326
336
  }
327
337
  async function read(address) {
@@ -347,14 +357,15 @@ export function createNotesStore(input) {
347
357
  const operations = edits === undefined ? [] : edits.map((operation) => ({ ...operation }));
348
358
  const stableOptions = { ...options };
349
359
  validateNotePolicy(stableOptions);
360
+ const description = stableOptions.description === undefined ? undefined : collapseDescription(stableOptions.description);
350
361
  const from = assertAddress(address);
351
362
  const destination = stableOptions.renameTo === undefined ? from : assertAddress(stableOptions.renameTo);
352
363
  assertWritablePath(destination.path);
353
364
  const scope = destination.scope;
354
365
  assertWritableNamespace(from.scope, from.who, identity);
355
366
  assertWritableNamespace(scope, destination.who, identity);
356
- if (operations.length === 0 && stableOptions.origin === undefined && stableOptions.crumpled === undefined && stableOptions.renameTo === undefined && stableOptions.pinned === undefined && stableOptions.budget === undefined && stableOptions.readonly === undefined) {
357
- throw new NoteError("nothing_to_do", "Nothing to change: provide edits, policy, an origin, a crumpled state, or a new address.");
367
+ if (operations.length === 0 && stableOptions.origin === undefined && stableOptions.description === undefined && stableOptions.crumpled === undefined && stableOptions.renameTo === undefined && stableOptions.pinned === undefined && stableOptions.budget === undefined && stableOptions.readonly === undefined) {
368
+ throw new NoteError("nothing_to_do", "Nothing to change: provide edits, a description, policy, an origin, a crumpled state, or a new address.");
358
369
  }
359
370
  const fromPath = physicalPath(from.scope, from.path, identity, from.who);
360
371
  const path = physicalPath(scope, destination.path, identity, destination.who);
@@ -383,6 +394,12 @@ export function createNotesStore(input) {
383
394
  assertNoteUnlocked(parseNote(targetRaw).meta, stableOptions.readonly);
384
395
  const beforeMeta = { ...meta };
385
396
  applyNotePolicy(meta, stableOptions);
397
+ if (description === undefined) {
398
+ if (stableOptions.description !== undefined)
399
+ delete meta.description;
400
+ }
401
+ else
402
+ meta.description = description;
386
403
  meta.scope = scope;
387
404
  if (from.scope !== "session" && scope === "session")
388
405
  meta.project = identity.projectKey;
@@ -397,16 +414,19 @@ export function createNotesStore(input) {
397
414
  throw new NoteError("invalid_edit", `edits[${index}].oldText must be a non-empty string.`, { editIndex: index });
398
415
  if (typeof newText !== "string")
399
416
  throw new NoteError("invalid_edit", `edits[${index}].newText must be a string.`, { editIndex: index });
417
+ if (operation.replaceAll !== undefined && typeof operation.replaceAll !== "boolean")
418
+ throw new NoteError("invalid_edit", `edits[${index}].replaceAll must be a boolean.`, { editIndex: index });
419
+ const replaceAll = operation.replaceAll ?? stableOptions.replaceAll ?? false;
400
420
  const lines = matchLineNumbers(next, oldText);
401
421
  if (lines.length === 0)
402
422
  throw new NoteError("no_match", `edits[${index}].oldText isn't in the note${index > 0 ? " (after the earlier edits)" : ""}. Nothing was saved.`, { editIndex: index });
403
- if (lines.length > 1 && !stableOptions.replaceAll) {
423
+ if (lines.length > 1 && !replaceAll) {
404
424
  throw new NoteError("ambiguous_edit", `edits[${index}].oldText appears ${lines.length} times (${anchorLines(lines)}); add surrounding text to pick one, or set replace_all. Nothing was saved.`, { lineNumbers: lines, editIndex: index });
405
425
  }
406
426
  if (oldText !== newText)
407
427
  applied++;
408
428
  // Positional splicing preserves user replacement text byte-for-byte.
409
- if (stableOptions.replaceAll)
429
+ if (replaceAll)
410
430
  next = next.split(oldText).join(newText);
411
431
  else {
412
432
  const matchIndex = next.indexOf(oldText);
@@ -422,11 +442,12 @@ export function createNotesStore(input) {
422
442
  const bodyChanged = body !== next;
423
443
  const originChanged = beforeMeta.origin !== meta.origin;
424
444
  const policyChanged = beforeMeta.pinned !== meta.pinned || beforeMeta.budget !== meta.budget || beforeMeta.readonly !== meta.readonly;
425
- if (bodyChanged || originChanged || policyChanged || moved)
445
+ const descriptionChanged = beforeMeta.description !== meta.description;
446
+ if (bodyChanged || originChanged || policyChanged || descriptionChanged || moved)
426
447
  meta.updatedAt = writeStamp();
427
448
  const serialized = serializeNote(meta, next);
428
449
  assertSerializedSize(serialized);
429
- const metadataChanged = originChanged || policyChanged || beforeMeta.crumpledAt !== meta.crumpledAt;
450
+ const metadataChanged = originChanged || policyChanged || descriptionChanged || beforeMeta.crumpledAt !== meta.crumpledAt;
430
451
  let change;
431
452
  // A body edit that also rewrites frontmatter is still a body change; its diff inputs span the
432
453
  // whole serialized file, so the frontmatter part stays visible in the diff.
@@ -442,7 +463,7 @@ export function createNotesStore(input) {
442
463
  await atomicWrite(sameFile ? sourceReal : path, serialized);
443
464
  if (moved)
444
465
  await rm(fromPath, { force: true });
445
- return { meta, warnings: noteBudgetWarnings(next, effectiveNotePolicy(meta, noteFileName(destination.path))), applied, resolvedScope: scope, change, moved, replacedCrumpledTarget: moved && targetRaw !== undefined };
466
+ return { meta, warnings: noteWarnings(next, effectiveNotePolicy(meta, noteFileName(destination.path)), meta.description), applied, resolvedScope: scope, change, moved, replacedCrumpledTarget: moved && targetRaw !== undefined };
446
467
  };
447
468
  return withPathQueues([fromRoot, root], () => withPathQueues([fromPath, path], mutate));
448
469
  }
@@ -522,7 +543,7 @@ export function createNotesStore(input) {
522
543
  for await (const row of scan(stableOptions, status)) {
523
544
  rows.push({ ...row, sizeBytes: Buffer.byteLength(row.body, "utf8") });
524
545
  }
525
- rows.sort((a, b) => b.meta.updatedAt - a.meta.updatedAt || a.address.localeCompare(b.address));
546
+ rows.sort(compareNoteRows);
526
547
  return { rows, status: status ?? { namespacesUnavailable: [] } };
527
548
  }
528
549
  function listWithStatus(options = {}) {
@@ -537,7 +558,7 @@ export function createNotesStore(input) {
537
558
  const rows = [];
538
559
  for await (const note of scan(stableOptions, status)) {
539
560
  const { address, path, scope, meta, body } = note;
540
- const warnings = noteBudgetWarnings(body, effectiveNotePolicy(meta, path));
561
+ const warnings = noteWarnings(body, effectiveNotePolicy(meta, path), meta.description);
541
562
  if (stableQueries.length === 0) {
542
563
  rows.push({ address, path, scope, meta, warnings, matches: [] });
543
564
  continue;
@@ -6,8 +6,17 @@ export declare class InvalidQueryError extends Error {
6
6
  export declare function searchQueries(query: unknown): string[];
7
7
  /** Longest fitting code-point prefix, without inserted markers. Callers report omissions. */
8
8
  export declare function prefixFit(text: string, fits: (content: string) => boolean): string;
9
+ /** Compile literal Unicode case-insensitive patterns once per search operation. */
10
+ export declare function compileSearchQueries(queries: readonly string[]): RegExp[];
11
+ /** Count Unicode code points in `text.slice(0, utf16End)` without allocating an array. */
12
+ export declare function codePointCount(text: string, utf16End?: number): number;
13
+ /** Slice `[start, start + limit)` code points without splitting the entire string into an array. */
14
+ export declare function sliceCodePoints(text: string, start: number, limit: number): {
15
+ text: string;
16
+ truncated: boolean;
17
+ };
9
18
  /**
10
19
  * Code-point offset of the earliest case-insensitive literal match, or -1 when
11
20
  * none occurs. Match against the original text so Unicode casing cannot shift offsets.
12
21
  */
13
- export declare function earliestMatchOffsetChars(text: string, queries: string[]): number;
22
+ export declare function earliestMatchOffsetChars(text: string, queries: readonly (string | RegExp)[]): number;