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
@@ -12,6 +12,69 @@ const PRESENTATION = `Codex unknown arguments not recorded output nested calls c
12
12
  FunctionCallOutput display without raw output encrypted content unavailable world_state snapshot patch omitted from
13
13
  the text projection not a newly spoken message native structured retained context not newly spoken dialogue`;
14
14
  const HISTORY_BASE = '"history_base"';
15
+ const STREAM_HIGH_WATER_MARK = 256 * 1024;
16
+ function isHex(code) {
17
+ return (code >= 48 && code <= 57) || (code >= 65 && code <= 70) || (code >= 97 && code <= 102);
18
+ }
19
+ /** Linear-time one-pass `\uXXXX` decoder: skips non-`\u` backslashes and bounds any trailing run to <= 6 chars. */
20
+ function decodeEscapes(source, final) {
21
+ const len = source.length;
22
+ let pending = "";
23
+ let limit = len;
24
+ if (!final && len > 0) {
25
+ let end = len;
26
+ let hexCount = 0;
27
+ while (end > 0 && hexCount < 3 && isHex(source.charCodeAt(end - 1))) {
28
+ end--;
29
+ hexCount++;
30
+ }
31
+ if (end >= 2 && source.charCodeAt(end - 1) === 117 && source.charCodeAt(end - 2) === 92) {
32
+ let slashStart = end - 2;
33
+ while (slashStart > 0 && source.charCodeAt(slashStart - 1) === 92)
34
+ slashStart--;
35
+ pending = `\\u${source.slice(end, len)}`;
36
+ limit = slashStart;
37
+ }
38
+ else if (source.charCodeAt(len - 1) === 92) {
39
+ let slashStart = len - 1;
40
+ while (slashStart > 0 && source.charCodeAt(slashStart - 1) === 92)
41
+ slashStart--;
42
+ pending = "\\";
43
+ limit = slashStart;
44
+ }
45
+ }
46
+ if (limit < 6) {
47
+ return { decoded: limit === len ? source : source.slice(0, limit), pending };
48
+ }
49
+ let pos = source.indexOf("\\u");
50
+ if (pos < 0 || pos >= limit) {
51
+ return { decoded: limit === len ? source : source.slice(0, limit), pending };
52
+ }
53
+ let out = "";
54
+ let cursor = 0;
55
+ while (pos >= 0 && pos < limit) {
56
+ if (pos + 6 <= limit
57
+ && isHex(source.charCodeAt(pos + 2))
58
+ && isHex(source.charCodeAt(pos + 3))
59
+ && isHex(source.charCodeAt(pos + 4))
60
+ && isHex(source.charCodeAt(pos + 5))) {
61
+ let slashStart = pos;
62
+ while (slashStart > cursor && source.charCodeAt(slashStart - 1) === 92)
63
+ slashStart--;
64
+ if (slashStart > cursor)
65
+ out += source.slice(cursor, slashStart);
66
+ out += String.fromCharCode(Number.parseInt(source.slice(pos + 2, pos + 6), 16));
67
+ cursor = pos + 6;
68
+ pos = source.indexOf("\\u", cursor);
69
+ }
70
+ else {
71
+ pos = source.indexOf("\\u", pos + 2);
72
+ }
73
+ }
74
+ if (cursor < limit)
75
+ out += source.slice(cursor, limit);
76
+ return { decoded: out, pending };
77
+ }
15
78
  /** Compile literal Unicode case matching once, then keep only per-file token bits and a bounded tail. */
16
79
  export function createHistoryPrefilter(queries) {
17
80
  let overlap = HISTORY_BASE.length;
@@ -28,24 +91,18 @@ export function createHistoryPrefilter(queries) {
28
91
  const decoder = new StringDecoder("utf8");
29
92
  const seen = alternatives.map((tokens) => tokens.map(() => false));
30
93
  let rawTail = "", normalizedTail = "", pending = "", possible = fallback;
31
- // Unlike /\\+u(hex{4})/, this cannot backtrack quadratically over a long invalid run.
32
- const escapes = /\\+(?:u([0-9a-fA-F]{0,4}))?/g;
33
94
  const scan = (chunk, final = false) => {
34
- const raw = rawTail + chunk, source = pending + chunk;
35
- const needsNormalization = pending.length > 0 || chunk.includes("\\u") || chunk.endsWith("\\");
36
- pending = "";
37
- const decoded = needsNormalization ? source.replace(escapes, (match, hex, offset) => {
38
- if (hex?.length === 4)
39
- return String.fromCharCode(Number.parseInt(hex, 16));
40
- // Tokens cannot include backslashes: an unresolved run needs only one separator,
41
- // plus at most 'u' and three hex digits, even if it spans arbitrarily many chunks.
42
- const literal = hex === undefined ? "\\" : `\\u${hex}`;
43
- if (!final && offset + match.length === source.length) {
44
- pending = literal;
45
- return "";
46
- }
47
- return literal;
48
- }) : chunk;
95
+ const raw = rawTail + chunk;
96
+ const needsNormalization = pending.length > 0 || chunk.includes("\\u") || (!final && chunk.endsWith("\\"));
97
+ let decoded = chunk;
98
+ if (needsNormalization) {
99
+ const result = decodeEscapes(pending + chunk, final);
100
+ decoded = result.decoded;
101
+ pending = result.pending;
102
+ }
103
+ else {
104
+ pending = "";
105
+ }
49
106
  const normalized = decoded === chunk && normalizedTail === rawTail ? raw : normalizedTail + decoded;
50
107
  if (codex && raw.includes(HISTORY_BASE))
51
108
  possible = true;
@@ -75,7 +132,7 @@ export async function historyFileMayMatch(path, prefilter, codex = false, maxByt
75
132
  // Plain Pi/Claude files will be read and validated by the strict decoder on a possible
76
133
  // hit. Don't drain a potentially huge file just to read it from the beginning again.
77
134
  if (!codex)
78
- return prefilter(createReadStream(path), false, true);
135
+ return prefilter(createReadStream(path, { highWaterMark: STREAM_HIGH_WATER_MARK }), false, true);
79
136
  const info = await stat(path);
80
137
  if (!info.isFile() || info.size > maxBytes)
81
138
  throw new Error("Unavailable Codex transcript: read size limit exceeded or not a regular file");
@@ -83,7 +140,7 @@ export async function historyFileMayMatch(path, prefilter, codex = false, maxByt
83
140
  const compressed = path.endsWith(".jsonl.zst");
84
141
  if (compressed && typeof zlib.createZstdDecompress !== "function")
85
142
  throw new Error("Compressed Codex rollouts require Node >=22.15 (createZstdDecompress)");
86
- const input = createReadStream(path);
143
+ const input = createReadStream(path, { highWaterMark: STREAM_HIGH_WATER_MARK });
87
144
  const consume = async (chunks) => {
88
145
  let size = 0;
89
146
  async function* bounded() {
@@ -1,59 +1,36 @@
1
1
  /** Stable-anchor paging, folding and literal matching. The operation supplies the full-response budget check. */
2
- import { Type, type Static } from "typebox";
3
2
  import { type Outcome } from "../result.js";
4
- import { type HistoryEvent, type HistoryFilter, type HistoryProjection } from "./history.js";
5
- export declare function isMultiPage(page: HistoryPage): boolean;
6
- export declare function markMultiPage(page: HistoryPage): HistoryPage;
7
- export type HistorySelection = HistoryFilter & {
8
- session?: string;
3
+ import { type HistoryEvent, type HistoryFilter, type HistoryFoldedRow, type HistoryPageItem, type HistoryProjection, type HistoryRole } from "./history.js";
4
+ type TimelineSelection = HistoryFilter & {
9
5
  limit?: number;
6
+ };
7
+ export type HistorySelection = TimelineSelection & {
10
8
  query?: string[];
11
9
  context?: number;
12
10
  };
13
- export declare const HistoryPageSchema: Type.TObject<{
14
- notice: Type.TOptional<Type.TString>;
15
- items: Type.TArray<Type.TObject<{
16
- content: Type.TString;
17
- truncated: Type.TBoolean;
18
- offset_chars: Type.TOptional<Type.TInteger>;
19
- tool: Type.TOptional<Type.TString>;
20
- tool_status: Type.TOptional<Type.TUnion<[Type.TLiteral<"ok">, Type.TLiteral<"error">, Type.TLiteral<"unfinished">]>>;
21
- output_truncated: Type.TOptional<Type.TLiteral<true>>;
22
- full_output_path: Type.TOptional<Type.TString>;
23
- session: Type.TOptional<Type.TString>;
24
- folded_before: Type.TOptional<Type.TObject<{
25
- session: Type.TOptional<Type.TString>;
26
- first_seq: Type.TInteger;
27
- last_seq: Type.TInteger;
28
- count: Type.TInteger;
29
- tools: Type.TRecord<"^.*$", Type.TInteger>;
30
- }>>;
31
- context: Type.TOptional<Type.TLiteral<true>>;
32
- seq: Type.TInteger;
33
- role: Type.TUnion<[Type.TLiteral<"user">, Type.TLiteral<"assistant">, Type.TLiteral<"tool">, Type.TLiteral<"context">]>;
34
- created_at: Type.TUnion<[Type.TString, Type.TNull]>;
35
- }>>;
36
- folded_after: Type.TOptional<Type.TObject<{
37
- session: Type.TOptional<Type.TString>;
38
- first_seq: Type.TInteger;
39
- last_seq: Type.TInteger;
40
- count: Type.TInteger;
41
- tools: Type.TRecord<"^.*$", Type.TInteger>;
42
- }>>;
43
- has_older: Type.TBoolean;
44
- has_newer: Type.TBoolean;
45
- }>;
46
11
  /** One whole page payload, before it becomes an outcome. */
47
- export type HistoryPage = Static<typeof HistoryPageSchema>;
12
+ export type HistoryPage = {
13
+ notice?: string;
14
+ items: HistoryPageItem[];
15
+ folded_after?: HistoryFoldedRow;
16
+ has_older: boolean;
17
+ has_newer: boolean;
18
+ };
48
19
  /** A caller's budget rejected even the shortest page; tool limits and refusal copy belong to the caller. */
49
20
  export type HistoryPageResult = Outcome<HistoryPage> | {
50
21
  ok: false;
51
- pageTooLarge: {
52
- count: number;
53
- multi: boolean;
54
- };
22
+ pageTooLarge: true;
23
+ };
24
+ export declare function selectPage(projection: HistoryProjection, params: TimelineSelection, fits: (page: HistoryPage) => boolean, maxChars: number): HistoryPageResult;
25
+ /** Strict single-pass overview summary: default representative, latest per role, and exact time span. */
26
+ export type ProjectionSummary = {
27
+ event: HistoryEvent | undefined;
28
+ latestByRole: Partial<Record<HistoryRole, HistoryEvent>>;
29
+ minCreatedAt: number | null;
30
+ maxCreatedAt: number | null;
31
+ hasUntimed: boolean;
55
32
  };
56
- export declare function selectPage(projection: HistoryProjection, params: HistorySelection, fits: (page: HistoryPage) => boolean, maxChars: number): HistoryPageResult;
33
+ export declare function summarizeProjection(projection: HistoryProjection): ProjectionSummary;
57
34
  /** One topic per session, after role/time filtering; empty dialogue envelopes are not visible. */
58
35
  export declare function sessionRepresentative(projection: HistoryProjection, scoped: HistorySelection): HistoryEvent | undefined;
59
36
  /** Keep only the requested end of the globally ordered selection while sessions are released. */
@@ -61,12 +38,14 @@ export declare class CorpusCollector {
61
38
  private readonly scoped;
62
39
  private readonly candidates;
63
40
  private readonly limit;
41
+ private readonly compiledQuery;
64
42
  private discarded;
65
43
  constructor(scoped: HistorySelection);
66
44
  private admit;
67
- /** Admit an already selected strict overview event without selecting it a second time. */
68
- addRepresentative(session: string, event: HistoryEvent | undefined): boolean;
69
- /** Returns whether this session contributes an overview representative. */
70
- add(session: string, projection: HistoryProjection): boolean;
45
+ /** Admit a session's overview representative (pre-selected or picked from a projection). */
46
+ addRepresentative(session: string, source: HistoryEvent | HistoryProjection | undefined): boolean;
47
+ /** Admit every query match from one session; an empty query matches nothing. */
48
+ addMatches(session: string, projection: HistoryProjection): void;
71
49
  page(fits: (page: HistoryPage) => boolean, maxChars: number, unvisited?: boolean): HistoryPageResult;
72
50
  }
51
+ export {};
@@ -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>;