@cchistory/lite 0.6.0 → 0.7.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 (150) hide show
  1. package/INSTALL.md +1 -1
  2. package/apps/lite-cli/dist/agent-contract.d.ts.map +1 -1
  3. package/apps/lite-cli/dist/agent-contract.js +12 -5
  4. package/apps/lite-cli/dist/agent-contract.js.map +1 -1
  5. package/apps/lite-cli/dist/agent-journeys.test.d.ts +2 -0
  6. package/apps/lite-cli/dist/agent-journeys.test.d.ts.map +1 -0
  7. package/apps/lite-cli/dist/agent-journeys.test.js +403 -0
  8. package/apps/lite-cli/dist/agent-journeys.test.js.map +1 -0
  9. package/apps/lite-cli/dist/index.d.ts.map +1 -1
  10. package/apps/lite-cli/dist/index.js +51 -13
  11. package/apps/lite-cli/dist/index.js.map +1 -1
  12. package/apps/lite-cli/dist/index.test.js +16 -5
  13. package/apps/lite-cli/dist/index.test.js.map +1 -1
  14. package/apps/lite-cli/dist/query.d.ts +15 -2
  15. package/apps/lite-cli/dist/query.d.ts.map +1 -1
  16. package/apps/lite-cli/dist/query.js +79 -4
  17. package/apps/lite-cli/dist/query.js.map +1 -1
  18. package/apps/lite-cli/dist/shell.d.ts +2 -1
  19. package/apps/lite-cli/dist/shell.d.ts.map +1 -1
  20. package/apps/lite-cli/dist/shell.js +20 -16
  21. package/apps/lite-cli/dist/shell.js.map +1 -1
  22. package/apps/lite-cli/dist/version.d.ts +1 -1
  23. package/apps/lite-cli/dist/version.js +1 -1
  24. package/apps/lite-tui/dist/model.d.ts.map +1 -1
  25. package/apps/lite-tui/dist/model.js +2 -1
  26. package/apps/lite-tui/dist/model.js.map +1 -1
  27. package/apps/lite-tui/dist/render.d.ts +1 -1
  28. package/apps/lite-tui/dist/version.d.ts +1 -1
  29. package/apps/lite-tui/dist/version.js +1 -1
  30. package/docs/guide/agent-evidence.md +154 -0
  31. package/docs/guide/for-agents.md +29 -10
  32. package/docs/guide/lite.md +8 -0
  33. package/docs/guide/query.md +10 -1
  34. package/node_modules/@cchistory/canonical/dist/conversation-evidence.d.ts +85 -0
  35. package/node_modules/@cchistory/canonical/dist/conversation-evidence.d.ts.map +1 -0
  36. package/node_modules/@cchistory/canonical/dist/conversation-evidence.js +191 -0
  37. package/node_modules/@cchistory/canonical/dist/conversation-evidence.js.map +1 -0
  38. package/node_modules/@cchistory/canonical/dist/conversation-evidence.test.d.ts +2 -0
  39. package/node_modules/@cchistory/canonical/dist/conversation-evidence.test.d.ts.map +1 -0
  40. package/node_modules/@cchistory/canonical/dist/conversation-evidence.test.js +105 -0
  41. package/node_modules/@cchistory/canonical/dist/conversation-evidence.test.js.map +1 -0
  42. package/node_modules/@cchistory/canonical/dist/index.d.ts +2 -0
  43. package/node_modules/@cchistory/canonical/dist/index.d.ts.map +1 -1
  44. package/node_modules/@cchistory/canonical/dist/index.js +2 -0
  45. package/node_modules/@cchistory/canonical/dist/index.js.map +1 -1
  46. package/node_modules/@cchistory/canonical/dist/projection-audit.d.ts +4 -3
  47. package/node_modules/@cchistory/canonical/dist/projection-audit.d.ts.map +1 -1
  48. package/node_modules/@cchistory/canonical/dist/projection-audit.js +14 -0
  49. package/node_modules/@cchistory/canonical/dist/projection-audit.js.map +1 -1
  50. package/node_modules/@cchistory/canonical/dist/read-status.d.ts +11 -0
  51. package/node_modules/@cchistory/canonical/dist/read-status.d.ts.map +1 -0
  52. package/node_modules/@cchistory/canonical/dist/read-status.js +14 -0
  53. package/node_modules/@cchistory/canonical/dist/read-status.js.map +1 -0
  54. package/node_modules/@cchistory/canonical/dist/session-family.js +1 -1
  55. package/node_modules/@cchistory/canonical/dist/session-family.js.map +1 -1
  56. package/node_modules/@cchistory/canonical/dist/session-interpreter.d.ts +7 -3
  57. package/node_modules/@cchistory/canonical/dist/session-interpreter.d.ts.map +1 -1
  58. package/node_modules/@cchistory/canonical/dist/session-interpreter.js +15 -13
  59. package/node_modules/@cchistory/canonical/dist/session-interpreter.js.map +1 -1
  60. package/node_modules/@cchistory/canonical/package.json +1 -1
  61. package/node_modules/@cchistory/domain/dist/conversation-evidence.d.ts +24 -0
  62. package/node_modules/@cchistory/domain/dist/conversation-evidence.d.ts.map +1 -0
  63. package/node_modules/@cchistory/domain/dist/conversation-evidence.js +2 -0
  64. package/node_modules/@cchistory/domain/dist/conversation-evidence.js.map +1 -0
  65. package/node_modules/@cchistory/domain/dist/index.d.ts +5 -0
  66. package/node_modules/@cchistory/domain/dist/index.d.ts.map +1 -1
  67. package/node_modules/@cchistory/domain/dist/index.js.map +1 -1
  68. package/node_modules/@cchistory/domain/package.json +1 -1
  69. package/node_modules/@cchistory/live-runtime/dist/bounded-cache.d.ts +15 -0
  70. package/node_modules/@cchistory/live-runtime/dist/bounded-cache.d.ts.map +1 -0
  71. package/node_modules/@cchistory/live-runtime/dist/bounded-cache.js +44 -0
  72. package/node_modules/@cchistory/live-runtime/dist/bounded-cache.js.map +1 -0
  73. package/node_modules/@cchistory/live-runtime/dist/bounded-cache.test.d.ts +2 -0
  74. package/node_modules/@cchistory/live-runtime/dist/bounded-cache.test.d.ts.map +1 -0
  75. package/node_modules/@cchistory/live-runtime/dist/bounded-cache.test.js +45 -0
  76. package/node_modules/@cchistory/live-runtime/dist/bounded-cache.test.js.map +1 -0
  77. package/node_modules/@cchistory/live-runtime/dist/diagnostics.d.ts +7 -0
  78. package/node_modules/@cchistory/live-runtime/dist/diagnostics.d.ts.map +1 -0
  79. package/node_modules/@cchistory/live-runtime/dist/diagnostics.js +2 -0
  80. package/node_modules/@cchistory/live-runtime/dist/diagnostics.js.map +1 -0
  81. package/node_modules/@cchistory/live-runtime/dist/history-reader.d.ts +24 -0
  82. package/node_modules/@cchistory/live-runtime/dist/history-reader.d.ts.map +1 -0
  83. package/node_modules/@cchistory/live-runtime/dist/history-reader.js +155 -0
  84. package/node_modules/@cchistory/live-runtime/dist/history-reader.js.map +1 -0
  85. package/node_modules/@cchistory/live-runtime/dist/index.d.ts +91 -5
  86. package/node_modules/@cchistory/live-runtime/dist/index.d.ts.map +1 -1
  87. package/node_modules/@cchistory/live-runtime/dist/index.js +186 -57
  88. package/node_modules/@cchistory/live-runtime/dist/index.js.map +1 -1
  89. package/node_modules/@cchistory/live-runtime/dist/index.test.js +6 -1
  90. package/node_modules/@cchistory/live-runtime/dist/index.test.js.map +1 -1
  91. package/node_modules/@cchistory/live-runtime/dist/selective-query.d.ts +2 -1
  92. package/node_modules/@cchistory/live-runtime/dist/selective-query.d.ts.map +1 -1
  93. package/node_modules/@cchistory/live-runtime/dist/selective-query.js.map +1 -1
  94. package/node_modules/@cchistory/live-runtime/package.json +1 -1
  95. package/node_modules/@cchistory/source-adapters/dist/core/conversation-seeds.d.ts +3 -0
  96. package/node_modules/@cchistory/source-adapters/dist/core/conversation-seeds.d.ts.map +1 -1
  97. package/node_modules/@cchistory/source-adapters/dist/core/conversation-seeds.js.map +1 -1
  98. package/node_modules/@cchistory/source-adapters/dist/core/decoded-record.d.ts +12 -0
  99. package/node_modules/@cchistory/source-adapters/dist/core/decoded-record.d.ts.map +1 -0
  100. package/node_modules/@cchistory/source-adapters/dist/core/decoded-record.js +32 -0
  101. package/node_modules/@cchistory/source-adapters/dist/core/decoded-record.js.map +1 -0
  102. package/node_modules/@cchistory/source-adapters/dist/core/decoded-record.test.d.ts +2 -0
  103. package/node_modules/@cchistory/source-adapters/dist/core/decoded-record.test.d.ts.map +1 -0
  104. package/node_modules/@cchistory/source-adapters/dist/core/decoded-record.test.js +21 -0
  105. package/node_modules/@cchistory/source-adapters/dist/core/decoded-record.test.js.map +1 -0
  106. package/node_modules/@cchistory/source-adapters/dist/core/jsonl-records.d.ts +3 -1
  107. package/node_modules/@cchistory/source-adapters/dist/core/jsonl-records.d.ts.map +1 -1
  108. package/node_modules/@cchistory/source-adapters/dist/core/jsonl-records.js +56 -38
  109. package/node_modules/@cchistory/source-adapters/dist/core/jsonl-records.js.map +1 -1
  110. package/node_modules/@cchistory/source-adapters/dist/core/jsonl-records.test.js +46 -1
  111. package/node_modules/@cchistory/source-adapters/dist/core/jsonl-records.test.js.map +1 -1
  112. package/node_modules/@cchistory/source-adapters/dist/core/parser.d.ts +15 -4
  113. package/node_modules/@cchistory/source-adapters/dist/core/parser.d.ts.map +1 -1
  114. package/node_modules/@cchistory/source-adapters/dist/core/parser.js +110 -69
  115. package/node_modules/@cchistory/source-adapters/dist/core/parser.js.map +1 -1
  116. package/node_modules/@cchistory/source-adapters/dist/core/probe.d.ts.map +1 -1
  117. package/node_modules/@cchistory/source-adapters/dist/core/probe.js +68 -30
  118. package/node_modules/@cchistory/source-adapters/dist/core/probe.js.map +1 -1
  119. package/node_modules/@cchistory/source-adapters/dist/core/read-budget.d.ts +4 -1
  120. package/node_modules/@cchistory/source-adapters/dist/core/read-budget.d.ts.map +1 -1
  121. package/node_modules/@cchistory/source-adapters/dist/core/read-budget.js +4 -2
  122. package/node_modules/@cchistory/source-adapters/dist/core/read-budget.js.map +1 -1
  123. package/node_modules/@cchistory/source-adapters/dist/core/read-budget.test.js +58 -0
  124. package/node_modules/@cchistory/source-adapters/dist/core/read-budget.test.js.map +1 -1
  125. package/node_modules/@cchistory/source-adapters/dist/core/source-identity.d.ts +6 -2
  126. package/node_modules/@cchistory/source-adapters/dist/core/source-identity.d.ts.map +1 -1
  127. package/node_modules/@cchistory/source-adapters/dist/core/source-identity.js +5 -5
  128. package/node_modules/@cchistory/source-adapters/dist/core/source-identity.js.map +1 -1
  129. package/node_modules/@cchistory/source-adapters/dist/core/types.d.ts +4 -1
  130. package/node_modules/@cchistory/source-adapters/dist/core/types.d.ts.map +1 -1
  131. package/node_modules/@cchistory/source-adapters/dist/index.test.d.ts +1 -0
  132. package/node_modules/@cchistory/source-adapters/dist/index.test.d.ts.map +1 -1
  133. package/node_modules/@cchistory/source-adapters/dist/index.test.js +1 -0
  134. package/node_modules/@cchistory/source-adapters/dist/index.test.js.map +1 -1
  135. package/node_modules/@cchistory/source-adapters/dist/platforms/amp.test.js +49 -1
  136. package/node_modules/@cchistory/source-adapters/dist/platforms/amp.test.js.map +1 -1
  137. package/node_modules/@cchistory/source-adapters/dist/platforms/zcode/runtime.d.ts +2 -0
  138. package/node_modules/@cchistory/source-adapters/dist/platforms/zcode/runtime.d.ts.map +1 -1
  139. package/node_modules/@cchistory/source-adapters/dist/platforms/zcode/runtime.js +48 -29
  140. package/node_modules/@cchistory/source-adapters/dist/platforms/zcode/runtime.js.map +1 -1
  141. package/node_modules/@cchistory/source-adapters/package.json +1 -1
  142. package/package.json +5 -5
  143. package/schemas/cchistory-lite-agent-v1.schema.json +8 -5
  144. package/schemas/cchistory-lite-canonical-v1.schema.json +82 -0
  145. package/schemas/cchistory-lite-diagnostic-v1.schema.json +27 -0
  146. package/schemas/cchistory-lite-query-result-v2.schema.json +232 -4
  147. package/schemas/cchistory-lite-query-result-v3.schema.json +45 -1
  148. package/schemas/cchistory-lite-query-v2.schema.json +150 -8
  149. package/schemas/cchistory-lite-v2.schema.json +82 -0
  150. package/skills/using-cchistory-lite/SKILL.md +86 -128
@@ -4,11 +4,12 @@ import os from "node:os";
4
4
  import path from "node:path";
5
5
  import process from "node:process";
6
6
  import { deriveHostId, deriveSourceInstanceId, normalizeLocalPathIdentity, } from "@cchistory/domain";
7
- import { executeCanonicalQuery, collectionQueryTemplate, hasSessionFamilyLinkTool, auditProjectionConsistency, interpretSessionEvidence, buildSessionLastMessageIndex, buildDirectoryScopedProjectTreeProjection, buildFallbackProjectObservationCandidates, buildProjectDisplayList, buildSessionRelatedWorkIndex, compareTurnsByChronology, compareTurnsByRecency, computeUsageOverview, computeUsageRollup, deriveProjectLinkSnapshot, filterProjectsByDirectoryScope, selectSampleSessions, summarizeDirectoryScope, filterSessionsByDirectoryScope, filterTopLevelSessions, filterTurnsByDirectoryScope, buildSessionFamilyInventory, FAMILY_IO_PREVIEW_CHARS, listDelegatedRelationsForFamilyChildren, listSessionFamilies, mergeSessionFamilyInventories, installRuntimeWarningFilter, orderSessionsByLastMessage, pathMatchesDirectoryScope, searchSessionsInMemory, searchTurnsInMemory, resolveTurnUsage, summarizeSessionUsage, } from "@cchistory/canonical";
7
+ import { buildConversationEvidence, prepareConversationEvidence, searchConversationEvidence, summarizeReadStatus, executeCanonicalQuery, collectionQueryTemplate, hasSessionFamilyLinkTool, auditProjectionConsistency, interpretSessionEvidence, buildSessionLastMessageIndex, buildDirectoryScopedProjectTreeProjection, buildFallbackProjectObservationCandidates, buildProjectDisplayList, buildSessionRelatedWorkIndex, compareTurnsByChronology, compareTurnsByRecency, computeUsageOverview, computeUsageRollup, deriveProjectLinkSnapshot, filterProjectsByDirectoryScope, selectSampleSessions, summarizeDirectoryScope, filterSessionsByDirectoryScope, filterTopLevelSessions, filterTurnsByDirectoryScope, buildSessionFamilyInventory, FAMILY_IO_PREVIEW_CHARS, listDelegatedRelationsForFamilyChildren, listSessionFamilies, mergeSessionFamilyInventories, installRuntimeWarningFilter, orderSessionsByLastMessage, pathMatchesDirectoryScope, searchSessionsInMemory, searchTurnsInMemory, resolveTurnUsage, summarizeSessionUsage, } from "@cchistory/canonical";
8
8
  import { SourceReadBudgetExceededError, applyMaskTemplates } from "@cchistory/source-adapters";
9
9
  import { SAMPLE_RANK_CONCURRENCY, mapPool } from "./async-pool.js";
10
10
  import { isSelectiveLatestQuery, newQueryReadWork } from "./selective-query.js";
11
11
  import { PreparationMetadata } from "./preparation-metadata.js";
12
+ import { BoundedCache } from "./bounded-cache.js";
12
13
  import { readRemainingHeapBytes, LIGHT_SCAN_MEMORY_MULTIPLIER, FULL_SCAN_MEMORY_MULTIPLIER, SCAN_GUARD_REFUSE_AVAILABLE_FRACTION, acquireScanLock, assessScanRisk, createScanWatchdog, isScanGuardEnabled, ScanGuardRefusedError, } from "./scan-guard.js";
13
14
  export { acquireScanLock, assessScanRisk, createScanWatchdog, defaultScanLockPath, formatScanGuardBytes, formatScanGuardWarning, FULL_SCAN_MEMORY_MULTIPLIER, isScanGuardEnabled, LIGHT_SCAN_MEMORY_MULTIPLIER, SCAN_GUARD_REFUSE_AVAILABLE_FRACTION, SCAN_GUARD_WARN_AVAILABLE_FRACTION, SCAN_WATCHDOG_MAX_RESERVE_BYTES, SCAN_LOCK_WAIT_MS, SCAN_WATCHDOG_AVAILABLE_RESERVE_FRACTION, ScanGuardAbortedError, ScanGuardRefusedError, } from "./scan-guard.js";
14
15
  import { readAvailableMemoryBytes } from "./system-memory.js";
@@ -35,7 +36,15 @@ export class AmbiguousReferenceError extends Error {
35
36
  this.candidateIds = [...candidateIds];
36
37
  }
37
38
  }
39
+ /** An exact session scan could not resolve one of its requested targets. */
40
+ export class SessionReferenceNotFoundError extends Error {
41
+ constructor(message) {
42
+ super(message);
43
+ this.name = "SessionReferenceNotFoundError";
44
+ }
45
+ }
38
46
  export class LiveHistorySnapshot {
47
+ limitedScan;
39
48
  selectSampleSessions(perSource, directoryScope) {
40
49
  return selectSampleSessions(this.data, perSource, directoryScope);
41
50
  }
@@ -44,6 +53,7 @@ export class LiveHistorySnapshot {
44
53
  }
45
54
  data;
46
55
  readIdentity = { id: randomUUID(), prepared_at: new Date().toISOString() };
56
+ searchNowMs = Date.parse(this.readIdentity.prepared_at);
47
57
  /** Non-fatal projection diagnostics kept visible to read-only surfaces. */
48
58
  projectionIssues;
49
59
  sourcesById;
@@ -62,9 +72,11 @@ export class LiveHistorySnapshot {
62
72
  // memoized for the lifetime of the instance (a refresh builds a new one).
63
73
  turnsBySessionId;
64
74
  turnsByProjectId;
65
- searchRankCache;
66
- sessionSearchRankCache;
67
- constructor(data, searchCandidates = []) {
75
+ searchRankCache = new BoundedCache(32, 20_000, (rows, key) => rows.reduce((total, row) => total + 1 + row.highlights.length * 2, Math.ceil(key.length / 128)));
76
+ sessionSearchRankCache = new BoundedCache(32, 20_000, (rows, key) => rows.reduce((total, row) => total + 1 + row.highlights.length * 2, Math.ceil(key.length / 128)));
77
+ evidencePages = new BoundedCache(32, 100_000, (entry, key) => entry.messageCount + Math.ceil(key.length / 128));
78
+ constructor(data, searchCandidates = [], limitedScan = false) {
79
+ this.limitedScan = limitedScan;
68
80
  this.data = {
69
81
  ...data,
70
82
  related_work: data.related_work ?? [],
@@ -101,6 +113,48 @@ export class LiveHistorySnapshot {
101
113
  this.childrenByParentId.set(child.parent_session_ref, siblings);
102
114
  }
103
115
  }
116
+ getReadStatus(directoryScope, diagnostics = "complete") {
117
+ return summarizeReadStatus({ sources: this.data.sources, lossAudits: this.data.loss_audits,
118
+ projectionIssueCount: this.projectionIssues.length,
119
+ unknownDirectorySessions: this.getDirectoryScopeDiagnostics(directoryScope)?.unknown_directory_sessions,
120
+ limitedScan: this.limitedScan, observedDiagnostics: diagnostics === "observed" });
121
+ }
122
+ getCacheStats() {
123
+ const state = (cache) => ({ entries: cache.size, retained_units: cache.weight });
124
+ return { search: state(this.searchRankCache), session_search: state(this.sessionSearchRankCache),
125
+ evidence_pages: state(this.evidencePages) };
126
+ }
127
+ readEvidence(target, options = {}, directoryScope) {
128
+ const session = target.kind === "session" ? this.getSession(target.ref) : undefined;
129
+ const turn = target.kind === "turn" ? this.getTurn(target.ref) : undefined;
130
+ if (!(session || turn))
131
+ return undefined;
132
+ const allowed = new Set(this.listResolvedSessions({ directoryScope }).map(s => s.id));
133
+ if (!allowed.has(session?.id ?? turn.session_id))
134
+ return undefined;
135
+ const turns = session ? this.listSessionTurns(session.id) : [turn];
136
+ if (!this.data.conversation_evidence && turns.some(t => t.context_summary.assistant_reply_count > 0 && !this.getTurnContext(t.id))) {
137
+ throw new Error("Conversation detail is not loaded for this read.");
138
+ }
139
+ const selector = JSON.stringify([target.kind, session?.id ?? turn.id, directoryScope ?? null]);
140
+ let pages = this.evidencePages.get(selector);
141
+ if (!pages) {
142
+ const ids = new Set(turns.map(t => t.id));
143
+ const messages = this.data.conversation_evidence?.filter(m => session ? m.session_id === session.id : m.turn_id !== null && ids.has(m.turn_id))
144
+ ?? buildConversationEvidence(turns, this.data.contexts);
145
+ pages = prepareConversationEvidence(messages, selector);
146
+ this.evidencePages.set(selector, pages);
147
+ }
148
+ return { target: { kind: target.kind, id: session?.id ?? turn.id },
149
+ ...pages.read(options) };
150
+ }
151
+ searchConversation(options) {
152
+ if (!this.data.conversation_evidence)
153
+ throw new Error("Conversation search evidence is not loaded.");
154
+ return searchConversationEvidence({ ...options, messages: this.data.conversation_evidence,
155
+ sessions: this.data.sessions, related_work: this.data.related_work,
156
+ projectTurnIds: options.projectId ? new Set(this.listProjectTurns(options.projectId).map(t => t.id)) : undefined });
157
+ }
104
158
  listSources() {
105
159
  return [...this.data.sources];
106
160
  }
@@ -284,7 +338,6 @@ export class LiveHistorySnapshot {
284
338
  options.sourceIds ?? null,
285
339
  options.directoryScope ?? null,
286
340
  ]);
287
- this.searchRankCache ??= new Map();
288
341
  let ranked = this.searchRankCache.get(cacheKey);
289
342
  if (!ranked) {
290
343
  ranked = searchTurnsInMemory({
@@ -292,6 +345,7 @@ export class LiveHistorySnapshot {
292
345
  sessions: this.data.sessions,
293
346
  projects: this.data.projects,
294
347
  candidates: this.searchCandidates,
348
+ now_ms: this.searchNowMs,
295
349
  query: options.query,
296
350
  project_id: options.projectId,
297
351
  source_ids: options.sourceIds,
@@ -311,7 +365,6 @@ export class LiveHistorySnapshot {
311
365
  options.sourceIds ?? null,
312
366
  options.directoryScope ?? null,
313
367
  ]);
314
- this.sessionSearchRankCache ??= new Map();
315
368
  let ranked = this.sessionSearchRankCache.get(cacheKey);
316
369
  if (!ranked) {
317
370
  ranked = searchSessionsInMemory({
@@ -319,6 +372,7 @@ export class LiveHistorySnapshot {
319
372
  sessions: filterSessionsByDirectoryScope(this.data.sessions, options.directoryScope),
320
373
  projects: this.data.projects,
321
374
  candidates: this.searchCandidates,
375
+ now_ms: this.searchNowMs,
322
376
  related_work: this.data.related_work,
323
377
  query: options.query,
324
378
  project_id: options.projectId,
@@ -383,13 +437,14 @@ export class LiveHistorySnapshot {
383
437
  }
384
438
  }
385
439
  export async function scanLiteHistory(options = {}) {
386
- return withPreparedScan(options, (sources, scanGuard, getPlan) => scanResolvedSources(scanGuard.guardedOptions(options), sources, scanGuard, getPlan));
440
+ return withPreparedScan(options, (sources, scanGuard, getPlan, tracedOptions) => scanResolvedSources(scanGuard.guardedOptions(tracedOptions), sources, scanGuard, getPlan));
387
441
  }
388
442
  /** Query-only selective reads never escape as a reusable full snapshot. */
389
443
  export async function scanLiteQuery(query, options = {}) {
390
444
  const work = newQueryReadWork();
391
445
  options = { ...options, contextMode: "none" };
392
- return withPreparedScan(options, async (sources, scanGuard, getPlan) => {
446
+ return withPreparedScan(options, async (sources, scanGuard, getPlan, tracedOptions) => {
447
+ options = tracedOptions;
393
448
  const guardedOptions = scanGuard.guardedOptions(options);
394
449
  let selection;
395
450
  for (const source of sources) {
@@ -418,50 +473,87 @@ export async function scanLiteQuery(query, options = {}) {
418
473
  result.coverage = { execution: "selective", rows: "exact", diagnostics: "observed" };
419
474
  work.retainedSessions = snapshot.data.sessions.length;
420
475
  work.retainedTurns = snapshot.data.turns.length;
421
- return { identity: snapshot.readIdentity, sourceIds: snapshot.data.sources.map(s => s.id), directoryScope: options.directoryScope,
476
+ return { identity: snapshot.readIdentity, readStatus: snapshot.getReadStatus(options.directoryScope, result.coverage.diagnostics), sourceIds: snapshot.data.sources.map(s => s.id), directoryScope: options.directoryScope,
422
477
  result, projectionIssues: snapshot.projectionIssues, sources: snapshot.data.sources, lossAudits: snapshot.data.loss_audits, directoryScopeDiagnostics: snapshot.getDirectoryScopeDiagnostics(options.directoryScope), work };
423
478
  });
424
479
  }
425
480
  async function withPreparedScan(options, run) {
426
- if (options.contextMode === "matching" && resolveContextTargets(options).length === 0) {
427
- throw new Error("matching context mode requires at least one context target.");
428
- }
429
- let sources = await resolveLiteSources(options);
430
- const exactPlatforms = exactCanonicalSessionPlatforms(options.sessionRefs ?? []);
431
- if (exactPlatforms.size > 0) {
432
- sources = sources.filter((source) => exactPlatforms.has(source.platform));
433
- if (sources.length === 0) {
434
- throw new Error(`No selected Lite source can resolve requested session ${options.sessionRefs?.join(", ")}.`);
481
+ const sink = options.onDiagnostic;
482
+ const attemptId = sink ? randomUUID() : undefined;
483
+ const startedAt = performance.now();
484
+ if (sink) {
485
+ const progress = options.onProgress;
486
+ const report = event => {
487
+ const memory = process.memoryUsage();
488
+ sink({ ...event, attempt_id: attemptId, elapsed_ms: performance.now() - startedAt,
489
+ heap_used_bytes: memory.heapUsed, rss_bytes: memory.rss,
490
+ process_peak_rss_bytes: process.resourceUsage().maxRSS * 1024 });
491
+ };
492
+ options = { ...options, onDiagnostic: report, onProgress: event => {
493
+ report({ kind: "progress", stage: event.stage, source_id: event.source_id, slot_id: event.slot_id,
494
+ file_index: event.file_index, file_count: event.file_count, size_bytes: event.size_bytes,
495
+ count: event.count, count_unit: event.count_unit,
496
+ stage_elapsed_ms: event.elapsed_ms === undefined ? undefined : Math.max(0, event.elapsed_ms) });
497
+ progress?.(event);
498
+ } };
499
+ report({ kind: "read_start", directory: options.directoryScope ?? null, source_refs: options.sourceRefs ?? [],
500
+ context_mode: options.contextMode ?? "full", conversation: options.retainConversationEvidence ?? false });
501
+ }
502
+ let scanGuard;
503
+ try {
504
+ if (options.contextMode === "matching" && resolveContextTargets(options).length === 0) {
505
+ throw new Error("matching context mode requires at least one context target.");
435
506
  }
436
- }
437
- const sourceAdapters = await import("@cchistory/source-adapters");
438
- const metadata = new PreparationMetadata();
439
- const plans = new Map();
440
- const getPlan = (source, scanOptions) => {
441
- const key = JSON.stringify([source.id, scanOptions.sessionRefs ?? []]);
442
- let pending = plans.get(key);
443
- if (!pending) {
444
- pending = prepareSourceScan(source, scanOptions, sourceAdapters, metadata).catch(async (error) => {
445
- if (!(error instanceof sourceAdapters.SourceFileReadPlanChangedError))
446
- throw error;
447
- // Live metadata is an optimization, not a prerequisite for reading history.
448
- const files = await sourceAdapters.listSourceFiles(source.platform, source.base_dir, scanOptions.limitFiles);
449
- const selected = scanOptions.sample
450
- ? await selectSampleSourceFiles(source, files, scanOptions.sample.perSource, sourceAdapters) : files;
451
- return { discoveredPrimaryFiles: files.length,
452
- readPlan: await sourceAdapters.createSourceFileReadPlan(source, selected, scanOptions.safeMode ?? false),
453
- selectionEvidence: [] };
454
- });
455
- plans.set(key, pending);
507
+ let sources = await resolveLiteSources(options);
508
+ const exactPlatforms = exactCanonicalSessionPlatforms(options.sessionRefs ?? []);
509
+ if (exactPlatforms.size > 0) {
510
+ sources = sources.filter((source) => exactPlatforms.has(source.platform));
511
+ if (sources.length === 0) {
512
+ throw new SessionReferenceNotFoundError(`No selected Lite source can resolve requested session ${options.sessionRefs?.join(", ")}.`);
513
+ }
456
514
  }
457
- return pending;
458
- };
459
- const scanGuard = await beginScanGuard(options, sources, getPlan);
460
- try {
461
- return await run(sources, scanGuard, getPlan);
515
+ const sourceAdapters = await import("@cchistory/source-adapters");
516
+ const metadata = new PreparationMetadata();
517
+ const plans = new Map();
518
+ const getPlan = (source, scanOptions) => {
519
+ const key = JSON.stringify([source.id, scanOptions.sessionRefs ?? []]);
520
+ let pending = plans.get(key);
521
+ if (!pending) {
522
+ pending = prepareSourceScan(source, scanOptions, sourceAdapters, metadata).catch(async (error) => {
523
+ if (!(error instanceof sourceAdapters.SourceFileReadPlanChangedError))
524
+ throw error;
525
+ // Live metadata is an optimization, not a prerequisite for reading history.
526
+ const files = await sourceAdapters.listSourceFiles(source.platform, source.base_dir, scanOptions.limitFiles);
527
+ const selected = scanOptions.sample
528
+ ? await selectSampleSourceFiles(source, files, scanOptions.sample.perSource, sourceAdapters) : files;
529
+ return { discoveredPrimaryFiles: files.length,
530
+ readPlan: await sourceAdapters.createSourceFileReadPlan(source, selected, scanOptions.safeMode ?? false),
531
+ selectionEvidence: [] };
532
+ });
533
+ plans.set(key, pending);
534
+ }
535
+ return pending;
536
+ };
537
+ scanGuard = await beginScanGuard(options, sources, getPlan);
538
+ const result = await run(sources, scanGuard, getPlan, options);
539
+ if (result instanceof LiveHistorySnapshot) {
540
+ options.onDiagnostic?.({ kind: "read_done", read_id: result.readIdentity.id,
541
+ sessions: result.data.sessions.length, turns: result.data.turns.length,
542
+ read_status: result.getReadStatus(options.directoryScope) });
543
+ }
544
+ else if (result && typeof result === "object" && "work" in result) {
545
+ const read = result;
546
+ options.onDiagnostic?.({ kind: "query_work", ...read.work });
547
+ options.onDiagnostic?.({ kind: "read_done", read_id: read.identity.id, read_status: read.readStatus });
548
+ }
549
+ return result;
550
+ }
551
+ catch (error) {
552
+ options.onDiagnostic?.({ kind: "read_error", error_class: error instanceof Error ? error.name : "unknown" });
553
+ throw error;
462
554
  }
463
555
  finally {
464
- await scanGuard.release();
556
+ await scanGuard?.release();
465
557
  }
466
558
  }
467
559
  /**
@@ -534,14 +626,25 @@ async function beginScanGuard(options, sources, getPlan) {
534
626
  }
535
627
  catch { /* use heap */ }
536
628
  const heap = (deps.readHeapBytes ?? readRemainingHeapBytes)();
537
- return Math.max(0, Math.min(heap, available ?? heap)) * SCAN_GUARD_REFUSE_AVAILABLE_FRACTION / multiplier;
629
+ return { heap, available, bytes: Math.max(0, Math.min(heap, available ?? heap)) * SCAN_GUARD_REFUSE_AVAILABLE_FRACTION / multiplier };
538
630
  };
631
+ let largestAdmittedUnit = -1;
539
632
  const readBudget = {
633
+ maximumUnitBytes: () => Math.floor(readHeadroom().bytes),
540
634
  admit(bytes, unit) {
541
635
  // Parsed temporary payloads are released between groups. Lifetime input
542
636
  // bytes are not resident memory; price the next allocation against live headroom.
543
- const allowed = Math.floor(readHeadroom());
544
- if (!Number.isSafeInteger(bytes) || bytes < 0 || bytes > allowed)
637
+ const headroom = readHeadroom();
638
+ const allowed = Math.floor(headroom.bytes);
639
+ const refused = !Number.isSafeInteger(bytes) || bytes < 0 || bytes > allowed;
640
+ if (refused || bytes > largestAdmittedUnit) {
641
+ options.onDiagnostic?.({ kind: "budget", decision: refused ? "refused" : "admitted", unit,
642
+ requested_bytes: bytes, allowed_native_bytes: allowed, profile: request.profile,
643
+ heap_available_bytes: headroom.heap, system_available_bytes: headroom.available ?? null });
644
+ if (!refused)
645
+ largestAdmittedUnit = bytes;
646
+ }
647
+ if (refused)
545
648
  throw new SourceReadBudgetExceededError(unit, bytes, allowed);
546
649
  },
547
650
  };
@@ -623,27 +726,28 @@ async function scanResolvedSources(options, sources, scanGuard, getPlan, work, s
623
726
  };
624
727
  let { host, payloads } = await scanSources(options);
625
728
  const requestedSessionRefs = options.sessionRefs?.filter((ref) => ref.trim().length > 0) ?? [];
729
+ const limitedScan = options.sample !== undefined || options.limitFiles !== undefined;
626
730
  if (requestedSessionRefs.length === 0)
627
- return buildLiveSnapshot({ host, sources: payloads });
731
+ return buildLiveSnapshot({ host, sources: payloads }, limitedScan);
628
732
  const missingChildRefs = missingDelegatedChildSessionRefs(payloads, requestedSessionRefs);
629
733
  if (missingChildRefs.length > 0) {
630
734
  const expandedOptions = { ...options, sessionRefs: [...requestedSessionRefs, ...missingChildRefs] };
631
735
  await scanGuard.assess(expandedOptions);
632
736
  ({ host, payloads } = await scanSources(expandedOptions));
633
737
  }
634
- const combined = buildLiveSnapshot({ host, sources: payloads });
738
+ const combined = buildLiveSnapshot({ host, sources: payloads }, limitedScan);
635
739
  const resolvedSessionRefs = requestedSessionRefs.map((ref) => {
636
740
  const session = combined.getSession(ref);
637
741
  if (!session)
638
- throw new Error(`Lite scan did not find requested session ${ref}.`);
742
+ throw new SessionReferenceNotFoundError(`Lite scan did not find requested session ${ref}.`);
639
743
  return session.id;
640
744
  });
641
745
  return buildLiveSnapshot({
642
746
  host,
643
747
  sources: payloads.map((payload) => filterLiveSourcePayloadBySessions(payload, resolvedSessionRefs)),
644
- });
748
+ }, limitedScan);
645
749
  }
646
- export function buildLiveSnapshot(probe) {
750
+ export function buildLiveSnapshot(probe, limitedScan = false) {
647
751
  const sources = probe.sources.map((payload) => payload.source);
648
752
  const turns = probe.sources
649
753
  .flatMap((payload) => payload.turns)
@@ -685,7 +789,9 @@ export function buildLiveSnapshot(probe) {
685
789
  contexts: probe.sources.flatMap((payload) => payload.contexts),
686
790
  ask_user_question_turns: probe.sources.flatMap((payload) => payload.ask_user_question_turns),
687
791
  loss_audits: probe.sources.flatMap((payload) => payload.loss_audits),
688
- }), candidates);
792
+ ...(probe.sources.some(p => p.conversation_evidence !== undefined)
793
+ ? { conversation_evidence: probe.sources.flatMap(p => p.conversation_evidence ?? []) } : {}),
794
+ }), candidates, limitedScan);
689
795
  }
690
796
  async function prepareSourceScan(source, options, adapters, metadata) {
691
797
  const adapter = adapters.listPlatformAdapters().find((entry) => entry.platform === source.platform);
@@ -767,7 +873,11 @@ async function scanSourceWithCollector(source, options, contextMode, sourceAdapt
767
873
  if (selectSessionFiles && !options.readBudget) {
768
874
  sourceFiles = await sourceAdapters.selectSourceSessionFiles(source, sourceFiles, options.sessionRefs);
769
875
  }
770
- const probe = await sourceAdapters.runSourceProbe(work ? evidence => { work.canonicalInterpretations++; return interpretSessionEvidence(evidence); } : interpretSessionEvidence, {
876
+ const probe = await sourceAdapters.runSourceProbe(evidence => {
877
+ if (work)
878
+ work.canonicalInterpretations++;
879
+ return interpretSessionEvidence(evidence, { formatContextBodies: contextMode !== "none" });
880
+ }, {
771
881
  ...buildProbeOptions(source, options),
772
882
  source_file_paths: { [source.id]: sourceFiles },
773
883
  source_file_plans: { [source.id]: readPlan },
@@ -780,7 +890,7 @@ async function scanSourceWithCollector(source, options, contextMode, sourceAdapt
780
890
  work.payloadFilesProcessed += sourceFiles.length;
781
891
  work.payloadRecordsProcessed += payload.source.total_records;
782
892
  }
783
- const compacted = compactSourcePayload(payload, contextMode, resolveContextTargets(options));
893
+ const compacted = compactSourcePayload(payload, contextMode, resolveContextTargets(options), options.retainConversationEvidence);
784
894
  return {
785
895
  host: probe.host,
786
896
  payload: options.sessionRefs?.length
@@ -881,6 +991,7 @@ async function scanLogicalSessionGroups(source, options, contextMode, sourceAdap
881
991
  const sessionsById = new Map();
882
992
  const turnsById = new Map();
883
993
  const contextsByTurnId = new Map();
994
+ const evidenceBySessionId = new Map();
884
995
  const askTurnsById = new Map();
885
996
  const sessionRelationFragments = [];
886
997
  const familyInventories = [];
@@ -893,7 +1004,11 @@ async function scanLogicalSessionGroups(source, options, contextMode, sourceAdap
893
1004
  let forwardedSourceStart = false;
894
1005
  let host;
895
1006
  for (const [groupIndex, group] of selectedGroupFiles.entries()) {
896
- const probe = await sourceAdapters.runSourceProbe(work ? evidence => { work.canonicalInterpretations++; return interpretSessionEvidence(evidence); } : interpretSessionEvidence, {
1007
+ const probe = await sourceAdapters.runSourceProbe(evidence => {
1008
+ if (work)
1009
+ work.canonicalInterpretations++;
1010
+ return interpretSessionEvidence(evidence, { formatContextBodies: contextMode !== "none" });
1011
+ }, {
897
1012
  ...buildProbeOptions(source, options, group.targetSessionRefs),
898
1013
  source_file_paths: { [source.id]: group.files },
899
1014
  source_file_plans: { [source.id]: plan.readPlan },
@@ -940,6 +1055,13 @@ async function scanLogicalSessionGroups(source, options, contextMode, sourceAdap
940
1055
  for (const context of selectPayloadContexts(groupPayload, contextMode, resolveContextTargets(options))) {
941
1056
  contextsByTurnId.set(context.turn_id, context);
942
1057
  }
1058
+ if (options.retainConversationEvidence) {
1059
+ const evidence = buildConversationEvidence(groupPayload.turns, groupPayload.contexts, groupPayload.atoms, groupPayload.sessions);
1060
+ for (const session of groupPayload.sessions)
1061
+ evidenceBySessionId.set(session.id, []);
1062
+ for (const message of evidence)
1063
+ evidenceBySessionId.get(message.session_id).push(message);
1064
+ }
943
1065
  for (const askTurn of groupPayload.ask_user_question_turns)
944
1066
  askTurnsById.set(askTurn.id, askTurn);
945
1067
  sessionRelationFragments.push(...groupPayload.fragments.filter((fragment) => fragment.fragment_kind === "session_relation"));
@@ -1025,6 +1147,7 @@ async function scanLogicalSessionGroups(source, options, contextMode, sourceAdap
1025
1147
  delegated_children: family.children,
1026
1148
  turns,
1027
1149
  contexts: [...contextsByTurnId.values()],
1150
+ ...(options.retainConversationEvidence ? { conversation_evidence: [...evidenceBySessionId.values()].flat() } : {}),
1028
1151
  ask_user_question_turns: [...askTurnsById.values()],
1029
1152
  loss_audits: lossAudits,
1030
1153
  },
@@ -1114,6 +1237,7 @@ function sourceFileMayBeInDirectoryScope(sourceAdapters, source, filePath, direc
1114
1237
  function buildProbeOptions(source, options, targetSessionRefs = options.sessionRefs) {
1115
1238
  return {
1116
1239
  source_ids: [source.id],
1240
+ retain_raw_records: false,
1117
1241
  read_budget: options.readBudget,
1118
1242
  target_session_refs: targetSessionRefs,
1119
1243
  limit_files_per_source: options.limitFiles,
@@ -1121,7 +1245,7 @@ function buildProbeOptions(source, options, targetSessionRefs = options.sessionR
1121
1245
  on_progress: options.onProgress,
1122
1246
  };
1123
1247
  }
1124
- function compactSourcePayload(payload, contextMode, contextTargets = []) {
1248
+ function compactSourcePayload(payload, contextMode, contextTargets = [], retainConversationEvidence = false) {
1125
1249
  const relatedWork = flattenRelatedWorkIndex(buildSessionRelatedWorkIndex(payload.sessions, payload.fragments));
1126
1250
  const family = familyInventoryFromPayload(payload, relatedWork);
1127
1251
  return {
@@ -1134,6 +1258,7 @@ function compactSourcePayload(payload, contextMode, contextTargets = []) {
1134
1258
  delegated_children: family.children,
1135
1259
  turns: payload.turns,
1136
1260
  contexts: selectPayloadContexts(payload, contextMode, contextTargets),
1261
+ ...(retainConversationEvidence ? { conversation_evidence: buildConversationEvidence(payload.turns, payload.contexts, payload.atoms, payload.sessions) } : {}),
1137
1262
  ask_user_question_turns: payload.ask_user_question_turns,
1138
1263
  loss_audits: payload.loss_audits,
1139
1264
  };
@@ -1246,6 +1371,7 @@ function filterLiveSourcePayloadBySessions(payload, sessionRefs) {
1246
1371
  turns,
1247
1372
  candidates: payload.candidates.filter((candidate) => sessionIds.has(candidate.session_ref)),
1248
1373
  contexts: payload.contexts.filter((context) => turnIds.has(context.turn_id)),
1374
+ ...(payload.conversation_evidence ? { conversation_evidence: payload.conversation_evidence.filter(m => sessionIds.has(m.session_id)) } : {}),
1249
1375
  ask_user_question_turns: payload.ask_user_question_turns.filter((turn) => sessionIds.has(turn.session_id)),
1250
1376
  related_work: relatedWork,
1251
1377
  session_contributions: payload.session_contributions?.filter((entry) => familySessionIds.has(entry.session_ref)),
@@ -1521,4 +1647,7 @@ function normalizeJsonShapeForJsonOutputMutating(value) {
1521
1647
  return value;
1522
1648
  }
1523
1649
  export { compileSql, compileSqlRequest, parseSqlRequest, QueryValidationError, SQL_REQUEST_SCHEMA, SQL_RESULT_SCHEMA, MAX_SQL_BYTES, MAX_QUERY_REQUEST_BYTES } from "./sql-query.js";
1650
+ export { BoundedCache } from "./bounded-cache.js";
1651
+ export { LiveHistoryReader } from "./history-reader.js";
1652
+ export { EvidenceCursorError, validateEvidenceBudget, DEFAULT_EVIDENCE_CHARS, MAX_EVIDENCE_CHARS } from "@cchistory/canonical";
1524
1653
  //# sourceMappingURL=index.js.map