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,18 +1,23 @@
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, type Static } from "typebox";
7
7
  import { Check } from "typebox/value";
8
- import { sessionIdentity, type HistorySession, type HistorySessionData, type HistorySessionRepresentative } from "./corpus.js";
9
- import { HistoryRoleSchema, ToolCallStatusSchema } from "./history.js";
10
- import { sessionRepresentative } from "./query.js";
8
+ import { sessionIdentity, type HistorySession, type HistorySessionData, type HistorySessionRepresentative, type HistorySessionSummary } from "./corpus.js";
9
+ import { HistoryRoleSchema, ToolCallStatusSchema, type HistoryEvent, type HistoryRole } from "./history.js";
10
+ import { summarizeProjection } from "./query.js";
11
11
  import { validateCodexLineageSources, type CodexLineageSource } from "./codex-transcript.js";
12
12
 
13
13
  // Bump whenever strict decoding, representative selection, or cached event presentation changes.
14
- const VERSION = "strict-representative-v1";
14
+ const VERSION = "strict-summary-v3";
15
+ const VERSION_PREFIX = `{"version":${JSON.stringify(VERSION)}`;
15
16
  const MAX_ENTRY_BYTES = 8 * 1024 * 1024;
17
+ export const HISTORY_SUMMARY_CACHE_TTL_MS = 3 * 24 * 60 * 60 * 1000;
18
+ const SWEEP_INTERVAL_MS = 10 * 60 * 1000;
19
+ const TMP_TTL_MS = 60 * 60 * 1000;
20
+ const lastSweep = new Map<string, number>();
16
21
  const FingerprintSchema = Type.Object({
17
22
  path: Type.String(), dev: Type.String(), ino: Type.String(), size: Type.String(), mtimeNs: Type.String(), ctimeNs: Type.String(),
18
23
  }, { additionalProperties: false });
@@ -31,9 +36,20 @@ const EventSchema = Type.Object({
31
36
  }, { additionalProperties: false })) }, { additionalProperties: false })),
32
37
  }, { additionalProperties: false })),
33
38
  }, { additionalProperties: false });
39
+ const LatestByRoleSchema = Type.Object({
40
+ user: Type.Optional(EventSchema),
41
+ assistant: Type.Optional(EventSchema),
42
+ tool: Type.Optional(EventSchema),
43
+ context: Type.Optional(EventSchema),
44
+ }, { additionalProperties: false });
34
45
  const EntrySchema = Type.Object({
35
46
  version: Type.Literal(VERSION), path: Type.String(), session: Type.String(),
36
- event: Type.Union([EventSchema, Type.Null()]), notice: Type.Optional(Type.String()),
47
+ event: Type.Union([EventSchema, Type.Null()]),
48
+ latestByRole: LatestByRoleSchema,
49
+ minCreatedAt: Type.Union([Type.Number(), Type.Null()]),
50
+ maxCreatedAt: Type.Union([Type.Number(), Type.Null()]),
51
+ hasUntimed: Type.Boolean(),
52
+ notice: Type.Optional(Type.String()),
37
53
  fingerprints: Type.Array(FingerprintSchema, { minItems: 1, maxItems: 64 }),
38
54
  lineageSources: Type.Array(Type.Object({ home: Type.String(), rolloutId: Type.String(), path: Type.String() }, { additionalProperties: false }), { maxItems: 63 }),
39
55
  }, { additionalProperties: false });
@@ -60,24 +76,84 @@ function completeDependencies(path: string, harness: HistorySession["harness"],
60
76
  return sources.length === expected.length && new Set(expected).size === expected.length && sources.every((source, index) => source.path === expected[index]);
61
77
  }
62
78
 
63
- async function readEntry(path: string): Promise<unknown> {
79
+ async function readEntry(path: string, now = Date.now()): Promise<unknown> {
64
80
  const file = await open(path, "r");
81
+ let expired = false;
65
82
  try {
66
83
  const info = await file.stat();
67
84
  if (!info.isFile() || info.size > MAX_ENTRY_BYTES) return undefined;
85
+ if (now - info.mtimeMs > HISTORY_SUMMARY_CACHE_TTL_MS) {
86
+ expired = true;
87
+ return undefined;
88
+ }
68
89
  const buffer = Buffer.alloc(info.size + 1);
69
90
  const { bytesRead } = await file.read(buffer, 0, buffer.length, 0);
70
91
  if (bytesRead > MAX_ENTRY_BYTES || (await file.stat()).size > MAX_ENTRY_BYTES) return undefined;
71
92
  return JSON.parse(buffer.toString("utf8", 0, bytesRead));
72
- } finally { await file.close(); }
93
+ } finally {
94
+ await file.close();
95
+ if (expired) await unlink(path).catch(() => {});
96
+ }
97
+ }
98
+
99
+ async function hasCurrentVersionPrefix(path: string): Promise<boolean> {
100
+ const file = await open(path, "r");
101
+ try {
102
+ const buffer = Buffer.alloc(VERSION_PREFIX.length);
103
+ const { bytesRead } = await file.read(buffer, 0, buffer.length, 0);
104
+ return bytesRead === VERSION_PREFIX.length && buffer.toString("utf8") === VERSION_PREFIX;
105
+ } catch { return false; }
106
+ finally { await file.close(); }
107
+ }
108
+
109
+ /** Remove expired (>3 days), obsolete-version (e.g. v1), and stale temporary cache files. */
110
+ export async function pruneHistorySummaryCache(cacheRoot: string, now = Date.now()): Promise<void> {
111
+ let entries;
112
+ try { entries = await readdir(cacheRoot, { withFileTypes: true }); }
113
+ catch { return; }
114
+ for (const entry of entries) {
115
+ if (!entry.isFile()) continue;
116
+ const full = join(cacheRoot, entry.name);
117
+ try {
118
+ const info = await stat(full);
119
+ if (entry.name.endsWith(".tmp")) {
120
+ if (now - info.mtimeMs > TMP_TTL_MS) await unlink(full).catch(() => {});
121
+ continue;
122
+ }
123
+ if (!entry.name.endsWith(".json")) continue;
124
+ if (now - info.mtimeMs > HISTORY_SUMMARY_CACHE_TTL_MS || !await hasCurrentVersionPrefix(full)) {
125
+ await unlink(full).catch(() => {});
126
+ }
127
+ } catch { /* Concurrent unlink or unreadable file: ignore. */ }
128
+ }
129
+ }
130
+
131
+ function maybeSweepCacheRoot(cacheRoot: string): void {
132
+ const now = Date.now();
133
+ const previous = lastSweep.get(cacheRoot);
134
+ if (previous !== undefined && now - previous < SWEEP_INTERVAL_MS) return;
135
+ lastSweep.set(cacheRoot, now);
136
+ void pruneHistorySummaryCache(cacheRoot, now).catch(() => {});
73
137
  }
74
138
 
75
139
  export type RepresentativeLoad = (track: (path: string) => Promise<void>) => Promise<{ data: HistorySessionData; lineageSources?: CodexLineageSource[] }>;
76
140
 
77
- /** The loader always runs the strict decoder on misses; transcript errors deliberately escape. */
78
- export async function cachedSessionRepresentative(
79
- session: Pick<HistorySession, "harness" | "id">, transcriptPath: string, cacheRoot: string, load: RepresentativeLoad,
80
- ): Promise<HistorySessionRepresentative> {
141
+ function hydrateEvent(event: Static<typeof EventSchema>): HistoryEvent {
142
+ return { ...event, createdAt: event.createdAt };
143
+ }
144
+
145
+ function hydrateLatestByRole(raw: Static<typeof LatestByRoleSchema>): Partial<Record<HistoryRole, HistoryEvent>> {
146
+ const out: Partial<Record<HistoryRole, HistoryEvent>> = {};
147
+ for (const role of ["user", "assistant", "tool", "context"] as const) {
148
+ const ev = raw[role];
149
+ if (ev) out[role] = hydrateEvent(ev);
150
+ }
151
+ return out;
152
+ }
153
+
154
+ async function lookupCachedSummary(
155
+ session: Pick<HistorySession, "harness" | "id">, transcriptPath: string, cacheRoot: string,
156
+ ): Promise<{ summary?: HistorySessionSummary; canonical?: string; cachePath?: string }> {
81
157
  let canonical: string | undefined, cachePath: string | undefined;
82
158
  const identity = sessionIdentity(session);
83
159
  try {
@@ -88,9 +164,37 @@ export async function cachedSessionRepresentative(
88
164
  && completeDependencies(canonical, session.harness, entry.fingerprints, entry.lineageSources)
89
165
  && await validateCodexLineageSources(entry.lineageSources) && await unchanged(entry.fingerprints)
90
166
  && await realpath(transcriptPath) === canonical) {
91
- return { event: entry.event === null ? undefined : { ...entry.event, createdAt: entry.event.createdAt }, notice: entry.notice };
167
+ return {
168
+ canonical,
169
+ cachePath,
170
+ summary: {
171
+ event: entry.event === null ? undefined : hydrateEvent(entry.event),
172
+ latestByRole: hydrateLatestByRole(entry.latestByRole),
173
+ minCreatedAt: entry.minCreatedAt,
174
+ maxCreatedAt: entry.maxCreatedAt,
175
+ hasUntimed: entry.hasUntimed,
176
+ notice: entry.notice,
177
+ },
178
+ };
92
179
  }
93
- } catch { /* Absent/corrupt/unwritable cache or changed source: strict load below. */ }
180
+ } catch { /* Absent/corrupt/unwritable cache or changed source: miss. */ }
181
+ return { canonical, cachePath };
182
+ }
183
+
184
+ /** Read-only check of a warm, validated summary; never decodes on miss. */
185
+ export async function peekCachedSessionSummary(
186
+ session: Pick<HistorySession, "harness" | "id">, transcriptPath: string, cacheRoot: string,
187
+ ): Promise<HistorySessionSummary | undefined> {
188
+ return (await lookupCachedSummary(session, transcriptPath, cacheRoot)).summary;
189
+ }
190
+
191
+ /** The loader always runs the strict decoder on misses; transcript errors deliberately escape. */
192
+ export async function cachedSessionSummary(
193
+ session: Pick<HistorySession, "harness" | "id">, transcriptPath: string, cacheRoot: string, load: RepresentativeLoad,
194
+ ): Promise<HistorySessionSummary> {
195
+ const identity = sessionIdentity(session);
196
+ const { summary, canonical, cachePath } = await lookupCachedSummary(session, transcriptPath, cacheRoot);
197
+ if (summary) return summary;
94
198
 
95
199
  const fingerprints = new Map<string, Fingerprint>();
96
200
  let stable = canonical !== undefined;
@@ -100,20 +204,41 @@ export async function cachedSessionRepresentative(
100
204
  };
101
205
  if (canonical) await track(canonical);
102
206
  const { data, lineageSources = [] } = await load(track);
103
- const event = sessionRepresentative(data.projection, {});
104
- const result = { event, notice: data.notice };
207
+ const computed = summarizeProjection(data.projection);
208
+ const result: HistorySessionSummary = { ...computed, notice: data.notice, loaded: data };
105
209
  try {
106
210
  const sources = [...fingerprints.values()];
107
211
  if (!stable || !canonical || !cachePath || !completeDependencies(canonical, session.harness, sources, lineageSources)
108
212
  || !await validateCodexLineageSources(lineageSources) || !await unchanged(sources) || await realpath(transcriptPath) !== canonical) return result;
109
- const entry = JSON.stringify({ version: VERSION, path: canonical, session: identity, event: event ?? null, notice: data.notice, fingerprints: sources, lineageSources });
213
+ const entry = JSON.stringify({
214
+ version: VERSION,
215
+ path: canonical,
216
+ session: identity,
217
+ event: computed.event ?? null,
218
+ latestByRole: computed.latestByRole,
219
+ minCreatedAt: computed.minCreatedAt,
220
+ maxCreatedAt: computed.maxCreatedAt,
221
+ hasUntimed: computed.hasUntimed,
222
+ notice: data.notice,
223
+ fingerprints: sources,
224
+ lineageSources,
225
+ });
110
226
  if (Buffer.byteLength(entry) > MAX_ENTRY_BYTES) return result;
111
227
  await mkdir(cacheRoot, { recursive: true, mode: 0o700 });
112
228
  const temporary = `${cachePath}.${randomUUID()}.tmp`;
113
229
  try {
114
230
  await writeFile(temporary, entry, { flag: "wx", mode: 0o600 });
115
231
  await rename(temporary, cachePath);
232
+ maybeSweepCacheRoot(cacheRoot);
116
233
  } finally { await unlink(temporary).catch(() => {}); }
117
234
  } catch { /* The cache cannot turn readable history into a refusal. */ }
118
235
  return result;
119
236
  }
237
+
238
+ /** The loader always runs the strict decoder on misses; transcript errors deliberately escape. */
239
+ export async function cachedSessionRepresentative(
240
+ session: Pick<HistorySession, "harness" | "id">, transcriptPath: string, cacheRoot: string, load: RepresentativeLoad,
241
+ ): Promise<HistorySessionRepresentative> {
242
+ const { event, notice } = await cachedSessionSummary(session, transcriptPath, cacheRoot, load);
243
+ return { event, notice };
244
+ }
package/src/index.ts CHANGED
@@ -44,7 +44,7 @@ export type { BootToolNames } from "./boot/text.js";
44
44
  // host-supplied notes tool context or decoded history projection/lazy corpus context.
45
45
  export { notesList, notesRead, notesUpdate, notesWrite } from "./tools/notes.js";
46
46
  export { notesIdentityForCall, notesToolContext, type NotesToolContext } from "./tools/notes-context.js";
47
- export { historyList, historyRead } from "./tools/history.js";
47
+ export { historyList, historySearch, historyRead } from "./tools/history.js";
48
48
  export { projectHistory } from "./history/history.js";
49
49
  export type { HistoryProjection } from "./history/history.js";
50
50
  export type { HistoryContext, HistoryCorpus, HistoryHarness, HistorySession, HistorySessionData } from "./history/corpus.js";
@@ -55,4 +55,4 @@ export type { Operation, Renderer, TextWindow } from "./tools/result.js";
55
55
  export { deriveThresholds, remainingBudget } from "./budget/policy.js";
56
56
  export type { ResolvedThresholds } from "./budget/policy.js";
57
57
  export { selectContinuation, tokenBudgetGuidance, warningPrompt, WARNING_BODY } from "./budget/text.js";
58
- export type { ResetOrigin } from "./budget/text.js";
58
+ export type { ContinuationOptions, ResetOrigin } from "./budget/text.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
 
3
3
  /** Typed store refusal. Edit locations are exposed in camelCase. */
4
4
  export class NoteError extends Error {
@@ -34,9 +34,6 @@ const TIMESTAMP_KEYS = ["createdAt", "updatedAt", "lastAccessed"] as const;
34
34
  /** Emission order, exactly the Design's key list. */
35
35
  const KNOWN_KEYS = ["pinned", "budget", "readonly", "description", "origin", "crumpledAt", "createdAt", "updatedAt", "lastAccessed", "accessCount", "sourceWindow", "supersedes", "recurrenceCount", "recurrenceWindows"] as const;
36
36
 
37
- /** A note description is one line; longer is not a description, it is prose in the wrong place. */
38
- export const MAX_DESCRIPTION_CHARS = 160;
39
-
40
37
  /** Collapse any whitespace run to one space and trim; an empty result is no description. */
41
38
  export function collapseDescription(value: string): string | undefined {
42
39
  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";
@@ -2,8 +2,13 @@ import { NoteError } from "./errors.js";
2
2
 
3
3
  export type NotePolicyFields = { pinned?: boolean; budget?: number; readonly?: boolean };
4
4
  export type NotePolicy = Required<NotePolicyFields>;
5
- export const DEFAULT_NOTE_BUDGET = 4096;
5
+ export const DEFAULT_NOTE_BUDGET = 8192;
6
+ export const DEFAULT_CHEATSHEET_BUDGET = 4096;
6
7
  export const MAX_PINNED_NOTES = 5;
8
+ export const WARNING_OPEN_TAG = "<notesoup:warning>";
9
+ export const WARNING_CLOSE_TAG = "</notesoup:warning>";
10
+ /** Boot index truncates descriptions past this code-point cap; longer values still save with a warning. */
11
+ export const MAX_DESCRIPTION_CHARS = 160;
7
12
  /** Defaults and ordering live here; no other layer assigns behavior by page name. */
8
13
  const DEFAULT_PINNED_PAGES = ["CHEATSHEET.md"] as const;
9
14
 
@@ -12,7 +17,7 @@ export function validateNotePolicy(fields: NotePolicyFields): void {
12
17
  if (fields[key] !== undefined && typeof fields[key] !== "boolean") throw new NoteError("invalid_policy", `${key} must be a boolean.`);
13
18
  }
14
19
  if (fields.budget !== undefined && (!Number.isSafeInteger(fields.budget) || fields.budget <= 0)) {
15
- throw new NoteError("invalid_policy", "budget must be a positive safe integer of Unicode code points.");
20
+ throw new NoteError("invalid_policy", "budget must be a positive integer.");
16
21
  }
17
22
  }
18
23
 
@@ -22,7 +27,7 @@ export function effectiveNotePolicy(fields: NotePolicyFields, path: string): Not
22
27
  const defaultPage = DEFAULT_PINNED_PAGES.some(page => page === path);
23
28
  return {
24
29
  pinned: fields.pinned ?? defaultPage,
25
- budget: fields.budget ?? (defaultPage ? 2048 : DEFAULT_NOTE_BUDGET),
30
+ budget: fields.budget ?? (defaultPage ? DEFAULT_CHEATSHEET_BUDGET : DEFAULT_NOTE_BUDGET),
26
31
  readonly: fields.readonly ?? false,
27
32
  };
28
33
  }
@@ -32,9 +37,43 @@ export function pinnedPageOrder(path: string): number {
32
37
  return index === -1 ? DEFAULT_PINNED_PAGES.length : index;
33
38
  }
34
39
 
40
+ export function truncateToUtf8Bytes(text: string, maxBytes: number): { text: string; shownChars: number; totalChars: number; truncated: boolean } {
41
+ if (Buffer.byteLength(text, "utf8") <= maxBytes) return { text, shownChars: 0, totalChars: 0, truncated: false };
42
+ const chars = Array.from(text);
43
+ let bytes = 0;
44
+ let shown = 0;
45
+ for (const char of chars) {
46
+ const size = Buffer.byteLength(char, "utf8");
47
+ if (bytes + size > maxBytes) break;
48
+ bytes += size;
49
+ shown++;
50
+ }
51
+ return { text: chars.slice(0, shown).join(""), shownChars: shown, totalChars: chars.length, truncated: true };
52
+ }
53
+
54
+ export function renderWarnings(warnings: readonly string[]): string {
55
+ if (warnings.length === 0) return "";
56
+ if (warnings.length === 1) return `${WARNING_OPEN_TAG}${warnings[0]}${WARNING_CLOSE_TAG}`;
57
+ return `${WARNING_OPEN_TAG}\n${warnings.join("\n")}\n${WARNING_CLOSE_TAG}`;
58
+ }
59
+
35
60
  export function noteBudgetWarnings(body: string, policy: NotePolicy): string[] {
36
- const count = Array.from(body).length;
37
- return count > policy.budget ? [`Warning: note body is ${count} Unicode code points, over budget ${policy.budget} — boil it down.`] : [];
61
+ const bytes = Buffer.byteLength(body, "utf8");
62
+ if (bytes <= policy.budget) return [];
63
+ const action = policy.pinned ? "boot truncates it to budget — trim, split, or unpin." : "trim or split it.";
64
+ return [`note body is ${bytes} bytes (budget ${policy.budget}); ${action}`];
65
+ }
66
+
67
+ export function noteDescriptionWarnings(description?: string): string[] {
68
+ if (description === undefined) return [];
69
+ const count = Array.from(description).length;
70
+ return count > MAX_DESCRIPTION_CHARS
71
+ ? [`description is ${count} chars (max ${MAX_DESCRIPTION_CHARS}); boot index truncates it.`]
72
+ : [];
73
+ }
74
+
75
+ export function noteWarnings(body: string, policy: NotePolicy, description?: string): string[] {
76
+ return [...noteBudgetWarnings(body, policy), ...noteDescriptionWarnings(description)];
38
77
  }
39
78
 
40
79
  export function assertNoteUnlocked(fields: NotePolicyFields, unlock?: boolean): void {
@@ -8,13 +8,17 @@ import { isFilesystemError } from "./fs-error.js";
8
8
  import { snapshotNotesIdentity, type NotesIdentity } from "./identity.js";
9
9
  import { NoteError } from "./errors.js";
10
10
  import { MAX_NOTE_BYTES, MAX_NOTE_PATH_BYTES } from "./constants.js";
11
- import { collapseDescription, isOrigin, localIso, MAX_DESCRIPTION_CHARS, parseNote, serializeNote, stripLeadingFrontmatter, type NoteMeta, type Origin } from "./frontmatter.js";
11
+ import { collapseDescription, isOrigin, localIso, parseNote, serializeNote, stripLeadingFrontmatter, type NoteMeta, type Origin } from "./frontmatter.js";
12
12
  import { namespaceSlugs, noteFileName, physicalPath, scopeDir, isSessionId, SLUG_PATTERN, type Scope } from "./paths.js";
13
13
  import { projectReceipt, type ProjectReceipt } from "./project-namespace.js";
14
- import { applyNotePolicy, assertNoteUnlocked, effectiveNotePolicy, MAX_PINNED_NOTES, noteBudgetWarnings, validateNotePolicy, type NotePolicyFields } from "./policy.js";
14
+ import { applyNotePolicy, assertNoteUnlocked, effectiveNotePolicy, MAX_PINNED_NOTES, noteWarnings, validateNotePolicy, type NotePolicyFields } from "./policy.js";
15
15
 
16
16
  export type { NoteMeta, Origin, Scope };
17
17
 
18
+ export function compareNoteRows(a: { address: string; meta: { updatedAt: number } }, b: { address: string; meta: { updatedAt: number } }): number {
19
+ return b.meta.updatedAt - a.meta.updatedAt || a.address.localeCompare(b.address);
20
+ }
21
+
18
22
  export type NoteRow = { address: string; scope: Scope; path: string; meta: NoteMeta; body: string; sizeBytes: number };
19
23
 
20
24
  // 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.
@@ -26,7 +30,7 @@ function writeStamp(): number {
26
30
  }
27
31
  export type NoteMatch = { line: number; text: string; /** Code-point offset into the note body, not into the serialized file. */ offsetChars: number };
28
32
  export type NoteSearchRow = { address: string; scope: Scope; path: string; meta: NoteMeta; warnings: string[]; matches: NoteMatch[] };
29
- export type EditOperation = { oldText: string; newText: string };
33
+ export type EditOperation = { oldText: string; newText: string; replaceAll?: boolean };
30
34
  export type WriteOptions = NotePolicyFields & { origin?: Origin; description?: string };
31
35
  export type EditOptions = NotePolicyFields & { origin?: Origin; description?: string; crumpled?: boolean; replaceAll?: boolean; renameTo?: string };
32
36
  /** Omit glob for current notebooks. A pattern without `@` or `/` matches filenames at any depth. */
@@ -188,15 +192,6 @@ function assertOrigin(value: unknown): Origin {
188
192
  return value;
189
193
  }
190
194
 
191
- /** A description is one normalized line; empty clears it. Only the authored value is refused, never read. */
192
- function normalizeDescription(value: string): string | undefined {
193
- const collapsed = collapseDescription(value);
194
- if (collapsed === undefined) return undefined;
195
- const count = Array.from(collapsed).length;
196
- if (count > MAX_DESCRIPTION_CHARS) throw new NoteError("invalid_description", `description is ${count} characters; limit is ${MAX_DESCRIPTION_CHARS}.`);
197
- return collapsed;
198
- }
199
-
200
195
  function assertWho(value: unknown, scope: Scope): string {
201
196
  if (typeof value !== "string" || !(scope === "session" ? isSessionId(value) : SLUG_PATTERN.test(value))) {
202
197
  throw new NoteError("invalid_scope", scope === "session" ? "session id must be a safe single directory component" : "who must be a canonical lowercase slug");
@@ -319,7 +314,7 @@ export function createNotesStore(input: NotesIdentity): NotesStore {
319
314
  async function write(address: string, content: string, options: WriteOptions = {}): Promise<NoteWriteResult> {
320
315
  const stableOptions = { ...options };
321
316
  validateNotePolicy(stableOptions);
322
- const description = stableOptions.description === undefined ? undefined : normalizeDescription(stableOptions.description);
317
+ const description = stableOptions.description === undefined ? undefined : collapseDescription(stableOptions.description);
323
318
  const destination = assertAddress(address);
324
319
  assertWritablePath(destination.path);
325
320
  const scope = destination.scope;
@@ -359,7 +354,7 @@ export function createNotesStore(input: NotesIdentity): NotesStore {
359
354
  assertSerializedSize(serialized);
360
355
  await assertPinAdmission(root, noteFileName(destination.path), meta, previous);
361
356
  await atomicWrite(path, serialized);
362
- return { meta, outcome, warnings: noteBudgetWarnings(cleanBody, effectiveNotePolicy(meta, noteFileName(destination.path))) };
357
+ return { meta, outcome, warnings: noteWarnings(cleanBody, effectiveNotePolicy(meta, noteFileName(destination.path)), meta.description) };
363
358
  }));
364
359
  }
365
360
 
@@ -385,7 +380,7 @@ export function createNotesStore(input: NotesIdentity): NotesStore {
385
380
  const operations = edits === undefined ? [] : edits.map((operation) => ({ ...operation }));
386
381
  const stableOptions = { ...options };
387
382
  validateNotePolicy(stableOptions);
388
- const description = stableOptions.description === undefined ? undefined : normalizeDescription(stableOptions.description);
383
+ const description = stableOptions.description === undefined ? undefined : collapseDescription(stableOptions.description);
389
384
  const from = assertAddress(address);
390
385
  const destination = stableOptions.renameTo === undefined ? from : assertAddress(stableOptions.renameTo);
391
386
  assertWritablePath(destination.path);
@@ -432,14 +427,16 @@ export function createNotesStore(input: NotesIdentity): NotesStore {
432
427
  const newText = operation?.newText;
433
428
  if (typeof oldText !== "string" || oldText.length === 0) throw new NoteError("invalid_edit", `edits[${index}].oldText must be a non-empty string.`, { editIndex: index });
434
429
  if (typeof newText !== "string") throw new NoteError("invalid_edit", `edits[${index}].newText must be a string.`, { editIndex: index });
430
+ if (operation.replaceAll !== undefined && typeof operation.replaceAll !== "boolean") throw new NoteError("invalid_edit", `edits[${index}].replaceAll must be a boolean.`, { editIndex: index });
431
+ const replaceAll = operation.replaceAll ?? stableOptions.replaceAll ?? false;
435
432
  const lines = matchLineNumbers(next, oldText);
436
433
  if (lines.length === 0) throw new NoteError("no_match", `edits[${index}].oldText isn't in the note${index > 0 ? " (after the earlier edits)" : ""}. Nothing was saved.`, { editIndex: index });
437
- if (lines.length > 1 && !stableOptions.replaceAll) {
434
+ if (lines.length > 1 && !replaceAll) {
438
435
  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 });
439
436
  }
440
437
  if (oldText !== newText) applied++;
441
438
  // Positional splicing preserves user replacement text byte-for-byte.
442
- if (stableOptions.replaceAll) next = next.split(oldText).join(newText);
439
+ if (replaceAll) next = next.split(oldText).join(newText);
443
440
  else {
444
441
  const matchIndex = next.indexOf(oldText);
445
442
  next = next.substring(0, matchIndex) + newText + next.substring(matchIndex + oldText.length);
@@ -467,7 +464,7 @@ export function createNotesStore(input: NotesIdentity): NotesStore {
467
464
  moved ? { root: fromRoot, path: noteFileName(from.path), meta: beforeMeta } : undefined);
468
465
  await atomicWrite(sameFile ? sourceReal! : path, serialized);
469
466
  if (moved) await rm(fromPath, { force: true });
470
- return { meta, warnings: noteBudgetWarnings(next, effectiveNotePolicy(meta, noteFileName(destination.path))), applied, resolvedScope: scope, change, moved, replacedCrumpledTarget: moved && targetRaw !== undefined };
467
+ return { meta, warnings: noteWarnings(next, effectiveNotePolicy(meta, noteFileName(destination.path)), meta.description), applied, resolvedScope: scope, change, moved, replacedCrumpledTarget: moved && targetRaw !== undefined };
471
468
  };
472
469
  return withPathQueues([fromRoot, root], () => withPathQueues([fromPath, path], mutate));
473
470
  }
@@ -543,7 +540,7 @@ export function createNotesStore(input: NotesIdentity): NotesStore {
543
540
  for await (const row of scan(stableOptions, status)) {
544
541
  rows.push({ ...row, sizeBytes: Buffer.byteLength(row.body, "utf8") });
545
542
  }
546
- rows.sort((a, b) => b.meta.updatedAt - a.meta.updatedAt || a.address.localeCompare(b.address));
543
+ rows.sort(compareNoteRows);
547
544
  return { rows, status: status ?? { namespacesUnavailable: [] } };
548
545
  }
549
546
 
@@ -561,7 +558,7 @@ export function createNotesStore(input: NotesIdentity): NotesStore {
561
558
  const rows: NoteSearchRow[] = [];
562
559
  for await (const note of scan(stableOptions, status)) {
563
560
  const { address, path, scope, meta, body } = note;
564
- const warnings = noteBudgetWarnings(body, effectiveNotePolicy(meta, path));
561
+ const warnings = noteWarnings(body, effectiveNotePolicy(meta, path), meta.description);
565
562
  if (stableQueries.length === 0) {
566
563
  rows.push({ address, path, scope, meta, warnings, matches: [] });
567
564
  continue;
package/src/text-match.ts CHANGED
@@ -30,17 +30,59 @@ export function prefixFit(text: string, fits: (content: string) => boolean): str
30
30
  return chars.slice(0, low).join("");
31
31
  }
32
32
 
33
+ /** Compile literal Unicode case-insensitive patterns once per search operation. */
34
+ export function compileSearchQueries(queries: readonly string[]): RegExp[] {
35
+ return queries.map((query) => new RegExp(query.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"), "iu"));
36
+ }
37
+
38
+ /** Count Unicode code points in `text.slice(0, utf16End)` without allocating an array. */
39
+ export function codePointCount(text: string, utf16End = text.length): number {
40
+ let count = utf16End;
41
+ for (let i = 0; i < utf16End - 1; i++) {
42
+ const code = text.charCodeAt(i);
43
+ if (code >= 0xd800 && code <= 0xdbff) {
44
+ const next = text.charCodeAt(i + 1);
45
+ if (next >= 0xdc00 && next <= 0xdfff) {
46
+ count--;
47
+ i++;
48
+ }
49
+ }
50
+ }
51
+ return count;
52
+ }
53
+
54
+ /** Slice `[start, start + limit)` code points without splitting the entire string into an array. */
55
+ export function sliceCodePoints(text: string, start: number, limit: number): { text: string; truncated: boolean } {
56
+ const len = text.length;
57
+ let utf16Start = 0;
58
+ let cp = 0;
59
+ while (cp < start && utf16Start < len) {
60
+ const code = text.charCodeAt(utf16Start);
61
+ utf16Start += code >= 0xd800 && code <= 0xdbff && utf16Start + 1 < len && text.charCodeAt(utf16Start + 1) >= 0xdc00 && text.charCodeAt(utf16Start + 1) <= 0xdfff ? 2 : 1;
62
+ cp++;
63
+ }
64
+ let utf16End = utf16Start;
65
+ let taken = 0;
66
+ while (taken < limit && utf16End < len) {
67
+ const code = text.charCodeAt(utf16End);
68
+ utf16End += code >= 0xd800 && code <= 0xdbff && utf16End + 1 < len && text.charCodeAt(utf16End + 1) >= 0xdc00 && text.charCodeAt(utf16End + 1) <= 0xdfff ? 2 : 1;
69
+ taken++;
70
+ }
71
+ const truncated = start > 0 || utf16End < len;
72
+ return { text: truncated ? text.slice(utf16Start, utf16End) : text, truncated };
73
+ }
74
+
33
75
  /**
34
76
  * Code-point offset of the earliest case-insensitive literal match, or -1 when
35
77
  * none occurs. Match against the original text so Unicode casing cannot shift offsets.
36
78
  */
37
- export function earliestMatchOffsetChars(text: string, queries: string[]): number {
79
+ export function earliestMatchOffsetChars(text: string, queries: readonly (string | RegExp)[]): number {
38
80
  let earliest = -1;
39
81
  for (const query of queries) {
40
- const literal = query.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
41
- const index = new RegExp(literal, "iu").exec(text)?.index ?? -1;
82
+ const pattern = typeof query === "string" ? new RegExp(query.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"), "iu") : query;
83
+ const index = pattern.exec(text)?.index ?? -1;
42
84
  if (index < 0) continue;
43
85
  if (earliest < 0 || index < earliest) earliest = index;
44
86
  }
45
- return earliest < 0 ? -1 : Array.from(text.slice(0, earliest)).length;
87
+ return earliest < 0 ? -1 : codePointCount(text, earliest);
46
88
  }