@cchistory/lite 0.5.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 (190) hide show
  1. package/INSTALL.md +1 -1
  2. package/apps/lite-cli/dist/agent-contract.d.ts +5 -2
  3. package/apps/lite-cli/dist/agent-contract.d.ts.map +1 -1
  4. package/apps/lite-cli/dist/agent-contract.js +20 -9
  5. package/apps/lite-cli/dist/agent-contract.js.map +1 -1
  6. package/apps/lite-cli/dist/agent-journeys.test.d.ts +2 -0
  7. package/apps/lite-cli/dist/agent-journeys.test.d.ts.map +1 -0
  8. package/apps/lite-cli/dist/agent-journeys.test.js +403 -0
  9. package/apps/lite-cli/dist/agent-journeys.test.js.map +1 -0
  10. package/apps/lite-cli/dist/bin.js +3 -3
  11. package/apps/lite-cli/dist/bin.js.map +1 -1
  12. package/apps/lite-cli/dist/index.d.ts.map +1 -1
  13. package/apps/lite-cli/dist/index.js +55 -13
  14. package/apps/lite-cli/dist/index.js.map +1 -1
  15. package/apps/lite-cli/dist/index.test.js +34 -69
  16. package/apps/lite-cli/dist/index.test.js.map +1 -1
  17. package/apps/lite-cli/dist/query.d.ts +15 -2
  18. package/apps/lite-cli/dist/query.d.ts.map +1 -1
  19. package/apps/lite-cli/dist/query.js +79 -4
  20. package/apps/lite-cli/dist/query.js.map +1 -1
  21. package/apps/lite-cli/dist/shell.d.ts +2 -1
  22. package/apps/lite-cli/dist/shell.d.ts.map +1 -1
  23. package/apps/lite-cli/dist/shell.js +20 -16
  24. package/apps/lite-cli/dist/shell.js.map +1 -1
  25. package/apps/lite-cli/dist/version.d.ts +1 -1
  26. package/apps/lite-cli/dist/version.js +1 -1
  27. package/apps/lite-tui/dist/bin.js +3 -3
  28. package/apps/lite-tui/dist/bin.js.map +1 -1
  29. package/apps/lite-tui/dist/index.d.ts.map +1 -1
  30. package/apps/lite-tui/dist/index.js +4 -0
  31. package/apps/lite-tui/dist/index.js.map +1 -1
  32. package/apps/lite-tui/dist/index.test.js +5 -5
  33. package/apps/lite-tui/dist/index.test.js.map +1 -1
  34. package/apps/lite-tui/dist/model.d.ts.map +1 -1
  35. package/apps/lite-tui/dist/model.js +2 -1
  36. package/apps/lite-tui/dist/model.js.map +1 -1
  37. package/apps/lite-tui/dist/render.d.ts +1 -1
  38. package/apps/lite-tui/dist/version.d.ts +1 -1
  39. package/apps/lite-tui/dist/version.js +1 -1
  40. package/bin/cchistory-lite-tui.mjs +3 -3
  41. package/bin/cchistory-lite.mjs +3 -3
  42. package/docs/guide/agent-evidence.md +154 -0
  43. package/docs/guide/for-agents.md +45 -25
  44. package/docs/guide/lite.md +16 -4
  45. package/docs/guide/query.md +11 -2
  46. package/node_modules/@cchistory/canonical/dist/conversation-evidence.d.ts +85 -0
  47. package/node_modules/@cchistory/canonical/dist/conversation-evidence.d.ts.map +1 -0
  48. package/node_modules/@cchistory/canonical/dist/conversation-evidence.js +191 -0
  49. package/node_modules/@cchistory/canonical/dist/conversation-evidence.js.map +1 -0
  50. package/node_modules/@cchistory/canonical/dist/conversation-evidence.test.d.ts +2 -0
  51. package/node_modules/@cchistory/canonical/dist/conversation-evidence.test.d.ts.map +1 -0
  52. package/node_modules/@cchistory/canonical/dist/conversation-evidence.test.js +105 -0
  53. package/node_modules/@cchistory/canonical/dist/conversation-evidence.test.js.map +1 -0
  54. package/node_modules/@cchistory/canonical/dist/index.d.ts +2 -0
  55. package/node_modules/@cchistory/canonical/dist/index.d.ts.map +1 -1
  56. package/node_modules/@cchistory/canonical/dist/index.js +2 -0
  57. package/node_modules/@cchistory/canonical/dist/index.js.map +1 -1
  58. package/node_modules/@cchistory/canonical/dist/projection-audit.d.ts +4 -3
  59. package/node_modules/@cchistory/canonical/dist/projection-audit.d.ts.map +1 -1
  60. package/node_modules/@cchistory/canonical/dist/projection-audit.js +14 -0
  61. package/node_modules/@cchistory/canonical/dist/projection-audit.js.map +1 -1
  62. package/node_modules/@cchistory/canonical/dist/read-status.d.ts +11 -0
  63. package/node_modules/@cchistory/canonical/dist/read-status.d.ts.map +1 -0
  64. package/node_modules/@cchistory/canonical/dist/read-status.js +14 -0
  65. package/node_modules/@cchistory/canonical/dist/read-status.js.map +1 -0
  66. package/node_modules/@cchistory/canonical/dist/session-family.js +1 -1
  67. package/node_modules/@cchistory/canonical/dist/session-family.js.map +1 -1
  68. package/node_modules/@cchistory/canonical/dist/session-interpreter.d.ts +7 -3
  69. package/node_modules/@cchistory/canonical/dist/session-interpreter.d.ts.map +1 -1
  70. package/node_modules/@cchistory/canonical/dist/session-interpreter.js +15 -13
  71. package/node_modules/@cchistory/canonical/dist/session-interpreter.js.map +1 -1
  72. package/node_modules/@cchistory/canonical/package.json +1 -1
  73. package/node_modules/@cchistory/domain/dist/conversation-evidence.d.ts +24 -0
  74. package/node_modules/@cchistory/domain/dist/conversation-evidence.d.ts.map +1 -0
  75. package/node_modules/@cchistory/domain/dist/conversation-evidence.js +2 -0
  76. package/node_modules/@cchistory/domain/dist/conversation-evidence.js.map +1 -0
  77. package/node_modules/@cchistory/domain/dist/index.d.ts +5 -0
  78. package/node_modules/@cchistory/domain/dist/index.d.ts.map +1 -1
  79. package/node_modules/@cchistory/domain/dist/index.js.map +1 -1
  80. package/node_modules/@cchistory/domain/package.json +1 -1
  81. package/node_modules/@cchistory/live-runtime/dist/bootstrap.d.ts +1 -0
  82. package/node_modules/@cchistory/live-runtime/dist/bootstrap.d.ts.map +1 -1
  83. package/node_modules/@cchistory/live-runtime/dist/bootstrap.js +1 -0
  84. package/node_modules/@cchistory/live-runtime/dist/bootstrap.js.map +1 -1
  85. package/node_modules/@cchistory/live-runtime/dist/bounded-cache.d.ts +15 -0
  86. package/node_modules/@cchistory/live-runtime/dist/bounded-cache.d.ts.map +1 -0
  87. package/node_modules/@cchistory/live-runtime/dist/bounded-cache.js +44 -0
  88. package/node_modules/@cchistory/live-runtime/dist/bounded-cache.js.map +1 -0
  89. package/node_modules/@cchistory/live-runtime/dist/bounded-cache.test.d.ts +2 -0
  90. package/node_modules/@cchistory/live-runtime/dist/bounded-cache.test.d.ts.map +1 -0
  91. package/node_modules/@cchistory/live-runtime/dist/bounded-cache.test.js +45 -0
  92. package/node_modules/@cchistory/live-runtime/dist/bounded-cache.test.js.map +1 -0
  93. package/node_modules/@cchistory/live-runtime/dist/diagnostics.d.ts +7 -0
  94. package/node_modules/@cchistory/live-runtime/dist/diagnostics.d.ts.map +1 -0
  95. package/node_modules/@cchistory/live-runtime/dist/diagnostics.js +2 -0
  96. package/node_modules/@cchistory/live-runtime/dist/diagnostics.js.map +1 -0
  97. package/node_modules/@cchistory/live-runtime/dist/history-reader.d.ts +24 -0
  98. package/node_modules/@cchistory/live-runtime/dist/history-reader.d.ts.map +1 -0
  99. package/node_modules/@cchistory/live-runtime/dist/history-reader.js +155 -0
  100. package/node_modules/@cchistory/live-runtime/dist/history-reader.js.map +1 -0
  101. package/node_modules/@cchistory/live-runtime/dist/index.d.ts +92 -6
  102. package/node_modules/@cchistory/live-runtime/dist/index.d.ts.map +1 -1
  103. package/node_modules/@cchistory/live-runtime/dist/index.js +249 -70
  104. package/node_modules/@cchistory/live-runtime/dist/index.js.map +1 -1
  105. package/node_modules/@cchistory/live-runtime/dist/index.test.js +6 -1
  106. package/node_modules/@cchistory/live-runtime/dist/index.test.js.map +1 -1
  107. package/node_modules/@cchistory/live-runtime/dist/launcher-memory.d.ts +12 -0
  108. package/node_modules/@cchistory/live-runtime/dist/launcher-memory.d.ts.map +1 -0
  109. package/node_modules/@cchistory/live-runtime/dist/launcher-memory.js +44 -0
  110. package/node_modules/@cchistory/live-runtime/dist/launcher-memory.js.map +1 -0
  111. package/node_modules/@cchistory/live-runtime/dist/launcher-memory.test.d.ts +2 -0
  112. package/node_modules/@cchistory/live-runtime/dist/launcher-memory.test.d.ts.map +1 -0
  113. package/node_modules/@cchistory/live-runtime/dist/launcher-memory.test.js +20 -0
  114. package/node_modules/@cchistory/live-runtime/dist/launcher-memory.test.js.map +1 -0
  115. package/node_modules/@cchistory/live-runtime/dist/live-read-recovery.test.d.ts +2 -0
  116. package/node_modules/@cchistory/live-runtime/dist/live-read-recovery.test.d.ts.map +1 -0
  117. package/node_modules/@cchistory/live-runtime/dist/live-read-recovery.test.js +92 -0
  118. package/node_modules/@cchistory/live-runtime/dist/live-read-recovery.test.js.map +1 -0
  119. package/node_modules/@cchistory/live-runtime/dist/scan-guard.d.ts +1 -0
  120. package/node_modules/@cchistory/live-runtime/dist/scan-guard.d.ts.map +1 -1
  121. package/node_modules/@cchistory/live-runtime/dist/scan-guard.js +7 -13
  122. package/node_modules/@cchistory/live-runtime/dist/scan-guard.js.map +1 -1
  123. package/node_modules/@cchistory/live-runtime/dist/scan-guard.test.js +50 -55
  124. package/node_modules/@cchistory/live-runtime/dist/scan-guard.test.js.map +1 -1
  125. package/node_modules/@cchistory/live-runtime/dist/selective-query.d.ts +2 -1
  126. package/node_modules/@cchistory/live-runtime/dist/selective-query.d.ts.map +1 -1
  127. package/node_modules/@cchistory/live-runtime/dist/selective-query.js.map +1 -1
  128. package/node_modules/@cchistory/live-runtime/dist/selective-query.test.js +8 -3
  129. package/node_modules/@cchistory/live-runtime/dist/selective-query.test.js.map +1 -1
  130. package/node_modules/@cchistory/live-runtime/dist/system-memory.test.js +3 -3
  131. package/node_modules/@cchistory/live-runtime/dist/system-memory.test.js.map +1 -1
  132. package/node_modules/@cchistory/live-runtime/package.json +1 -1
  133. package/node_modules/@cchistory/source-adapters/dist/core/conversation-seeds.d.ts +3 -0
  134. package/node_modules/@cchistory/source-adapters/dist/core/conversation-seeds.d.ts.map +1 -1
  135. package/node_modules/@cchistory/source-adapters/dist/core/conversation-seeds.js.map +1 -1
  136. package/node_modules/@cchistory/source-adapters/dist/core/decoded-record.d.ts +12 -0
  137. package/node_modules/@cchistory/source-adapters/dist/core/decoded-record.d.ts.map +1 -0
  138. package/node_modules/@cchistory/source-adapters/dist/core/decoded-record.js +32 -0
  139. package/node_modules/@cchistory/source-adapters/dist/core/decoded-record.js.map +1 -0
  140. package/node_modules/@cchistory/source-adapters/dist/core/decoded-record.test.d.ts +2 -0
  141. package/node_modules/@cchistory/source-adapters/dist/core/decoded-record.test.d.ts.map +1 -0
  142. package/node_modules/@cchistory/source-adapters/dist/core/decoded-record.test.js +21 -0
  143. package/node_modules/@cchistory/source-adapters/dist/core/decoded-record.test.js.map +1 -0
  144. package/node_modules/@cchistory/source-adapters/dist/core/file-read-plan.js +3 -2
  145. package/node_modules/@cchistory/source-adapters/dist/core/file-read-plan.js.map +1 -1
  146. package/node_modules/@cchistory/source-adapters/dist/core/jsonl-records.d.ts +3 -1
  147. package/node_modules/@cchistory/source-adapters/dist/core/jsonl-records.d.ts.map +1 -1
  148. package/node_modules/@cchistory/source-adapters/dist/core/jsonl-records.js +56 -38
  149. package/node_modules/@cchistory/source-adapters/dist/core/jsonl-records.js.map +1 -1
  150. package/node_modules/@cchistory/source-adapters/dist/core/jsonl-records.test.js +76 -1
  151. package/node_modules/@cchistory/source-adapters/dist/core/jsonl-records.test.js.map +1 -1
  152. package/node_modules/@cchistory/source-adapters/dist/core/parser.d.ts +16 -5
  153. package/node_modules/@cchistory/source-adapters/dist/core/parser.d.ts.map +1 -1
  154. package/node_modules/@cchistory/source-adapters/dist/core/parser.js +136 -76
  155. package/node_modules/@cchistory/source-adapters/dist/core/parser.js.map +1 -1
  156. package/node_modules/@cchistory/source-adapters/dist/core/probe.d.ts.map +1 -1
  157. package/node_modules/@cchistory/source-adapters/dist/core/probe.js +75 -54
  158. package/node_modules/@cchistory/source-adapters/dist/core/probe.js.map +1 -1
  159. package/node_modules/@cchistory/source-adapters/dist/core/read-budget.d.ts +4 -1
  160. package/node_modules/@cchistory/source-adapters/dist/core/read-budget.d.ts.map +1 -1
  161. package/node_modules/@cchistory/source-adapters/dist/core/read-budget.js +5 -3
  162. package/node_modules/@cchistory/source-adapters/dist/core/read-budget.js.map +1 -1
  163. package/node_modules/@cchistory/source-adapters/dist/core/read-budget.test.js +61 -2
  164. package/node_modules/@cchistory/source-adapters/dist/core/read-budget.test.js.map +1 -1
  165. package/node_modules/@cchistory/source-adapters/dist/core/source-identity.d.ts +6 -2
  166. package/node_modules/@cchistory/source-adapters/dist/core/source-identity.d.ts.map +1 -1
  167. package/node_modules/@cchistory/source-adapters/dist/core/source-identity.js +5 -5
  168. package/node_modules/@cchistory/source-adapters/dist/core/source-identity.js.map +1 -1
  169. package/node_modules/@cchistory/source-adapters/dist/core/types.d.ts +4 -1
  170. package/node_modules/@cchistory/source-adapters/dist/core/types.d.ts.map +1 -1
  171. package/node_modules/@cchistory/source-adapters/dist/index.test.d.ts +1 -0
  172. package/node_modules/@cchistory/source-adapters/dist/index.test.d.ts.map +1 -1
  173. package/node_modules/@cchistory/source-adapters/dist/index.test.js +1 -0
  174. package/node_modules/@cchistory/source-adapters/dist/index.test.js.map +1 -1
  175. package/node_modules/@cchistory/source-adapters/dist/platforms/amp.test.js +49 -1
  176. package/node_modules/@cchistory/source-adapters/dist/platforms/amp.test.js.map +1 -1
  177. package/node_modules/@cchistory/source-adapters/dist/platforms/zcode/runtime.d.ts +2 -0
  178. package/node_modules/@cchistory/source-adapters/dist/platforms/zcode/runtime.d.ts.map +1 -1
  179. package/node_modules/@cchistory/source-adapters/dist/platforms/zcode/runtime.js +48 -29
  180. package/node_modules/@cchistory/source-adapters/dist/platforms/zcode/runtime.js.map +1 -1
  181. package/node_modules/@cchistory/source-adapters/package.json +1 -1
  182. package/package.json +5 -5
  183. package/schemas/cchistory-lite-agent-v1.schema.json +8 -5
  184. package/schemas/cchistory-lite-canonical-v1.schema.json +82 -0
  185. package/schemas/cchistory-lite-diagnostic-v1.schema.json +27 -0
  186. package/schemas/cchistory-lite-query-result-v2.schema.json +232 -4
  187. package/schemas/cchistory-lite-query-result-v3.schema.json +45 -1
  188. package/schemas/cchistory-lite-query-v2.schema.json +150 -8
  189. package/schemas/cchistory-lite-v2.schema.json +82 -0
  190. package/skills/using-cchistory-lite/SKILL.md +86 -127
@@ -4,13 +4,14 @@ 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
- 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_LOCK_WAIT_MS, SCAN_WATCHDOG_AVAILABLE_RESERVE_FRACTION, ScanGuardAbortedError, ScanGuardRefusedError, } from "./scan-guard.js";
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";
15
16
  export { SourceReadBudgetExceededError } from "@cchistory/source-adapters";
16
17
  export { readAvailableMemory, 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) {
@@ -400,7 +455,15 @@ export async function scanLiteQuery(query, options = {}) {
400
455
  }
401
456
  if (isSelectiveLatestQuery(query) && sources.length === 1 && sources[0].platform === "codex" && !options.sample && !options.sessionRefs?.length) {
402
457
  const source = sources[0], plan = await getPlan(source, options);
403
- selection = await prepareSelectiveGroups(plan, query, work, scanGuard);
458
+ try {
459
+ selection = await prepareSelectiveGroups(plan, query, work, scanGuard, guardedOptions.readBudget);
460
+ }
461
+ catch (error) {
462
+ const { SourceFileReadPlanChangedError } = await import("@cchistory/source-adapters");
463
+ if (!(error instanceof SourceFileReadPlanChangedError))
464
+ throw error;
465
+ work.fallbackReason = "source_changed";
466
+ }
404
467
  }
405
468
  else
406
469
  work.fallbackReason = query.complete ? "complete_requested" : "query_or_source_shape";
@@ -410,45 +473,92 @@ export async function scanLiteQuery(query, options = {}) {
410
473
  result.coverage = { execution: "selective", rows: "exact", diagnostics: "observed" };
411
474
  work.retainedSessions = snapshot.data.sessions.length;
412
475
  work.retainedTurns = snapshot.data.turns.length;
413
- 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,
414
477
  result, projectionIssues: snapshot.projectionIssues, sources: snapshot.data.sources, lossAudits: snapshot.data.loss_audits, directoryScopeDiagnostics: snapshot.getDirectoryScopeDiagnostics(options.directoryScope), work };
415
478
  });
416
479
  }
417
480
  async function withPreparedScan(options, run) {
418
- if (options.contextMode === "matching" && resolveContextTargets(options).length === 0) {
419
- throw new Error("matching context mode requires at least one context target.");
420
- }
421
- let sources = await resolveLiteSources(options);
422
- const exactPlatforms = exactCanonicalSessionPlatforms(options.sessionRefs ?? []);
423
- if (exactPlatforms.size > 0) {
424
- sources = sources.filter((source) => exactPlatforms.has(source.platform));
425
- if (sources.length === 0) {
426
- 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.");
427
506
  }
428
- }
429
- const sourceAdapters = await import("@cchistory/source-adapters");
430
- const metadata = new PreparationMetadata();
431
- const plans = new Map();
432
- const getPlan = (source, scanOptions) => {
433
- const key = JSON.stringify([source.id, scanOptions.sessionRefs ?? []]);
434
- let pending = plans.get(key);
435
- if (!pending) {
436
- pending = prepareSourceScan(source, scanOptions, sourceAdapters, metadata);
437
- 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
+ }
438
514
  }
439
- return pending;
440
- };
441
- const scanGuard = await beginScanGuard(options, sources, getPlan);
442
- try {
443
- 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;
444
554
  }
445
555
  finally {
446
- await scanGuard.release();
556
+ await scanGuard?.release();
447
557
  }
448
558
  }
449
559
  /**
450
560
  * Runs the guard layer around a scan: serialize full scans on this machine,
451
- * refuse when the conservative peak estimate risks swap-death, and arm the
561
+ * warn when the conservative peak estimate is high, and arm the
452
562
  * watchdog that aborts the scan if available memory collapses mid-probe. The
453
563
  * kill-switch env is read here — the live-runtime entry — so the guard module
454
564
  * and its tests stay explicit about behavior.
@@ -496,10 +606,7 @@ async function beginScanGuard(options, sources, getPlan) {
496
606
  profile: request.profile,
497
607
  ...(directoryScoped ? { directoryScoped: true } : {}),
498
608
  }, { walkRootBytes, readAvailableBytes: deps.readAvailableBytes, readHeapBytes: deps.readHeapBytes });
499
- if (assessment.status === "refuse") {
500
- throw new ScanGuardRefusedError({ reason: "estimated_memory", assessment });
501
- }
502
- if (assessment.status === "warn") {
609
+ if (assessment.status !== "ok") {
503
610
  options.onScanGuardEvent?.({ type: "warn", assessment });
504
611
  }
505
612
  };
@@ -519,15 +626,26 @@ async function beginScanGuard(options, sources, getPlan) {
519
626
  }
520
627
  catch { /* use heap */ }
521
628
  const heap = (deps.readHeapBytes ?? readRemainingHeapBytes)();
522
- 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 };
523
630
  };
524
- let remaining = readHeadroom();
631
+ let largestAdmittedUnit = -1;
525
632
  const readBudget = {
633
+ maximumUnitBytes: () => Math.floor(readHeadroom().bytes),
526
634
  admit(bytes, unit) {
527
- const allowed = Math.floor(Math.min(remaining, readHeadroom()));
528
- if (!Number.isSafeInteger(bytes) || bytes < 0 || bytes > allowed)
635
+ // Parsed temporary payloads are released between groups. Lifetime input
636
+ // bytes are not resident memory; price the next allocation against live headroom.
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)
529
648
  throw new SourceReadBudgetExceededError(unit, bytes, allowed);
530
- remaining -= bytes;
531
649
  },
532
650
  };
533
651
  const watchdog = createScanWatchdog({
@@ -562,16 +680,37 @@ async function scanResolvedSources(options, sources, scanGuard, getPlan, work, s
562
680
  // runtime never infers independence from a file-oriented source shape.
563
681
  for (const source of sources) {
564
682
  const plan = await getPlan(source, scanOptions);
565
- for (const evidence of plan.selectionEvidence)
566
- await sourceAdapters.assertSourceFileReadPlanCurrent(evidence);
567
- await sourceAdapters.assertSourceFileReadPlanCurrent(plan.readPlan);
568
- const result = plan.groups
569
- ? await scanLogicalSessionGroups(source, scanOptions, contextMode, sourceAdapters, plan, () => scanGuard.assess(scanOptions), work, selection)
570
- : await scanSourceWithCollector(source, scanOptions, contextMode, sourceAdapters, plan.readPlan.files, plan.readPlan, plan.selectSessionFiles, work);
571
- for (const evidence of plan.selectionEvidence)
572
- await sourceAdapters.assertSourceFileReadPlanCurrent(evidence);
573
- if (selection)
574
- await sourceAdapters.assertSourceFileReadPlanCurrent(plan.readPlan);
683
+ let result;
684
+ try {
685
+ for (const evidence of plan.selectionEvidence)
686
+ await sourceAdapters.assertSourceFileReadPlanCurrent(evidence);
687
+ if (selection)
688
+ await sourceAdapters.assertSourceFileReadPlanCurrent(plan.readPlan);
689
+ result = plan.groups
690
+ ? await scanLogicalSessionGroups(source, scanOptions, contextMode, sourceAdapters, plan, () => scanGuard.assess(scanOptions), work, selection)
691
+ : await scanSourceWithCollector(source, scanOptions, contextMode, sourceAdapters, plan.readPlan.files, plan.readPlan, plan.selectSessionFiles, work);
692
+ for (const evidence of plan.selectionEvidence)
693
+ await sourceAdapters.assertSourceFileReadPlanCurrent(evidence);
694
+ if (selection)
695
+ await sourceAdapters.assertSourceFileReadPlanCurrent(plan.readPlan);
696
+ }
697
+ catch (error) {
698
+ if (!(error instanceof sourceAdapters.SourceFileReadPlanChangedError))
699
+ throw error;
700
+ if (selection)
701
+ selection.stopped = false;
702
+ if (work) {
703
+ work.fallbackReason = "source_changed";
704
+ work.skippedPrimaryFiles = 0;
705
+ }
706
+ // Re-read this source without version-dependent grouping/pruning. Keep
707
+ // this attempt's inventory, including files excluded by stale metadata.
708
+ const inventory = [...new Set([...plan.readPlan.files, ...plan.selectionEvidence.flatMap(e => [...e.files])])];
709
+ const files = scanOptions.sample
710
+ ? await selectSampleSourceFiles(source, inventory, scanOptions.sample.perSource, sourceAdapters) : inventory;
711
+ const readPlan = await sourceAdapters.createSourceFileReadPlan(source, files, scanOptions.safeMode ?? false);
712
+ result = await scanSourceWithCollector(source, scanOptions, contextMode, sourceAdapters, files, readPlan, false, work);
713
+ }
575
714
  nextHost ??= result.host;
576
715
  nextPayloads.push(result.payload);
577
716
  // Watchdog backstop: breaches recorded inside adapter progress callbacks
@@ -587,27 +726,28 @@ async function scanResolvedSources(options, sources, scanGuard, getPlan, work, s
587
726
  };
588
727
  let { host, payloads } = await scanSources(options);
589
728
  const requestedSessionRefs = options.sessionRefs?.filter((ref) => ref.trim().length > 0) ?? [];
729
+ const limitedScan = options.sample !== undefined || options.limitFiles !== undefined;
590
730
  if (requestedSessionRefs.length === 0)
591
- return buildLiveSnapshot({ host, sources: payloads });
731
+ return buildLiveSnapshot({ host, sources: payloads }, limitedScan);
592
732
  const missingChildRefs = missingDelegatedChildSessionRefs(payloads, requestedSessionRefs);
593
733
  if (missingChildRefs.length > 0) {
594
734
  const expandedOptions = { ...options, sessionRefs: [...requestedSessionRefs, ...missingChildRefs] };
595
735
  await scanGuard.assess(expandedOptions);
596
736
  ({ host, payloads } = await scanSources(expandedOptions));
597
737
  }
598
- const combined = buildLiveSnapshot({ host, sources: payloads });
738
+ const combined = buildLiveSnapshot({ host, sources: payloads }, limitedScan);
599
739
  const resolvedSessionRefs = requestedSessionRefs.map((ref) => {
600
740
  const session = combined.getSession(ref);
601
741
  if (!session)
602
- throw new Error(`Lite scan did not find requested session ${ref}.`);
742
+ throw new SessionReferenceNotFoundError(`Lite scan did not find requested session ${ref}.`);
603
743
  return session.id;
604
744
  });
605
745
  return buildLiveSnapshot({
606
746
  host,
607
747
  sources: payloads.map((payload) => filterLiveSourcePayloadBySessions(payload, resolvedSessionRefs)),
608
- });
748
+ }, limitedScan);
609
749
  }
610
- export function buildLiveSnapshot(probe) {
750
+ export function buildLiveSnapshot(probe, limitedScan = false) {
611
751
  const sources = probe.sources.map((payload) => payload.source);
612
752
  const turns = probe.sources
613
753
  .flatMap((payload) => payload.turns)
@@ -649,7 +789,9 @@ export function buildLiveSnapshot(probe) {
649
789
  contexts: probe.sources.flatMap((payload) => payload.contexts),
650
790
  ask_user_question_turns: probe.sources.flatMap((payload) => payload.ask_user_question_turns),
651
791
  loss_audits: probe.sources.flatMap((payload) => payload.loss_audits),
652
- }), candidates);
792
+ ...(probe.sources.some(p => p.conversation_evidence !== undefined)
793
+ ? { conversation_evidence: probe.sources.flatMap(p => p.conversation_evidence ?? []) } : {}),
794
+ }), candidates, limitedScan);
653
795
  }
654
796
  async function prepareSourceScan(source, options, adapters, metadata) {
655
797
  const adapter = adapters.listPlatformAdapters().find((entry) => entry.platform === source.platform);
@@ -685,7 +827,7 @@ async function prepareSourceScan(source, options, adapters, metadata) {
685
827
  && !options.directoryScope && !options.sample && Boolean(options.sessionRefs?.length);
686
828
  return { discoveredPrimaryFiles, readPlan, selectionEvidence: [...selectionEvidence], selectSessionFiles, groups, fallbackFiles: groups ? files : undefined };
687
829
  }
688
- async function prepareSelectiveGroups(plan, query, work, guard) {
830
+ async function prepareSelectiveGroups(plan, query, work, guard, budget) {
689
831
  if (!plan.groups?.length) {
690
832
  work.fallbackReason = "uncertain_grouping";
691
833
  return undefined;
@@ -696,6 +838,15 @@ async function prepareSelectiveGroups(plan, query, work, guard) {
696
838
  await adapters.assertSourceFileReadPlanCurrent(plan.readPlan);
697
839
  const byFile = new Map();
698
840
  for (const file of plan.readPlan.files) {
841
+ try {
842
+ budget?.admit(plan.readPlan.versions[file]?.size ?? 0, file);
843
+ }
844
+ catch (error) {
845
+ if (!(error instanceof SourceReadBudgetExceededError))
846
+ throw error;
847
+ work.fallbackReason = "read_budget";
848
+ return undefined;
849
+ }
699
850
  const evidence = await adapters.inspectCodexActivityEvidence(plan.readPlan, file);
700
851
  work.inventoryFiles++;
701
852
  work.inventoryBytesRead += evidence.bytesRead;
@@ -719,11 +870,14 @@ async function prepareSelectiveGroups(plan, query, work, guard) {
719
870
  return { groups: ranked.map(x => x.group), upperBounds: ranked.map(x => x.bound), query, stopped: false };
720
871
  }
721
872
  async function scanSourceWithCollector(source, options, contextMode, sourceAdapters, sourceFiles, readPlan, selectSessionFiles = false, work) {
722
- if (selectSessionFiles) {
873
+ if (selectSessionFiles && !options.readBudget) {
723
874
  sourceFiles = await sourceAdapters.selectSourceSessionFiles(source, sourceFiles, options.sessionRefs);
724
- await sourceAdapters.assertSourceFileReadPlanCurrent(readPlan);
725
875
  }
726
- 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
+ }, {
727
881
  ...buildProbeOptions(source, options),
728
882
  source_file_paths: { [source.id]: sourceFiles },
729
883
  source_file_plans: { [source.id]: readPlan },
@@ -736,7 +890,7 @@ async function scanSourceWithCollector(source, options, contextMode, sourceAdapt
736
890
  work.payloadFilesProcessed += sourceFiles.length;
737
891
  work.payloadRecordsProcessed += payload.source.total_records;
738
892
  }
739
- const compacted = compactSourcePayload(payload, contextMode, resolveContextTargets(options));
893
+ const compacted = compactSourcePayload(payload, contextMode, resolveContextTargets(options), options.retainConversationEvidence);
740
894
  return {
741
895
  host: probe.host,
742
896
  payload: options.sessionRefs?.length
@@ -837,6 +991,7 @@ async function scanLogicalSessionGroups(source, options, contextMode, sourceAdap
837
991
  const sessionsById = new Map();
838
992
  const turnsById = new Map();
839
993
  const contextsByTurnId = new Map();
994
+ const evidenceBySessionId = new Map();
840
995
  const askTurnsById = new Map();
841
996
  const sessionRelationFragments = [];
842
997
  const familyInventories = [];
@@ -849,7 +1004,11 @@ async function scanLogicalSessionGroups(source, options, contextMode, sourceAdap
849
1004
  let forwardedSourceStart = false;
850
1005
  let host;
851
1006
  for (const [groupIndex, group] of selectedGroupFiles.entries()) {
852
- 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
+ }, {
853
1012
  ...buildProbeOptions(source, options, group.targetSessionRefs),
854
1013
  source_file_paths: { [source.id]: group.files },
855
1014
  source_file_plans: { [source.id]: plan.readPlan },
@@ -896,11 +1055,25 @@ async function scanLogicalSessionGroups(source, options, contextMode, sourceAdap
896
1055
  for (const context of selectPayloadContexts(groupPayload, contextMode, resolveContextTargets(options))) {
897
1056
  contextsByTurnId.set(context.turn_id, context);
898
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
+ }
899
1065
  for (const askTurn of groupPayload.ask_user_question_turns)
900
1066
  askTurnsById.set(askTurn.id, askTurn);
901
1067
  sessionRelationFragments.push(...groupPayload.fragments.filter((fragment) => fragment.fragment_kind === "session_relation"));
902
1068
  familyInventories.push(familyInventoryFromPayload(groupPayload, flattenRelatedWorkIndex(buildSessionRelatedWorkIndex(groupPayload.sessions, groupPayload.fragments))));
903
1069
  lossAudits.push(...groupPayload.loss_audits);
1070
+ if (selection && groupPayload.loss_audits.length > 0) {
1071
+ // Missing payloads cannot prove a latest-row cutoff even with stable metadata.
1072
+ selection.stopped = false;
1073
+ selection = undefined;
1074
+ if (work)
1075
+ work.fallbackReason = "read_loss";
1076
+ }
904
1077
  if (selection && !requiresSourceCollector) {
905
1078
  // Unexpected cross-session relationships invalidate the narrow independence proof.
906
1079
  if (sessionRelationFragments.length || familyInventories.some(f => f.children.length > 0)) {
@@ -926,7 +1099,6 @@ async function scanLogicalSessionGroups(source, options, contextMode, sourceAdap
926
1099
  if (requiresSourceCollector) {
927
1100
  plan.readPlan = await sourceAdapters.createSourceFileReadPlan(source, plan.fallbackFiles, options.safeMode ?? false);
928
1101
  await assessExpandedPlan();
929
- await sourceAdapters.assertSourceFileReadPlanCurrent(plan.readPlan);
930
1102
  if (selection)
931
1103
  selection.stopped = false;
932
1104
  if (work)
@@ -975,6 +1147,7 @@ async function scanLogicalSessionGroups(source, options, contextMode, sourceAdap
975
1147
  delegated_children: family.children,
976
1148
  turns,
977
1149
  contexts: [...contextsByTurnId.values()],
1150
+ ...(options.retainConversationEvidence ? { conversation_evidence: [...evidenceBySessionId.values()].flat() } : {}),
978
1151
  ask_user_question_turns: [...askTurnsById.values()],
979
1152
  loss_audits: lossAudits,
980
1153
  },
@@ -1064,6 +1237,7 @@ function sourceFileMayBeInDirectoryScope(sourceAdapters, source, filePath, direc
1064
1237
  function buildProbeOptions(source, options, targetSessionRefs = options.sessionRefs) {
1065
1238
  return {
1066
1239
  source_ids: [source.id],
1240
+ retain_raw_records: false,
1067
1241
  read_budget: options.readBudget,
1068
1242
  target_session_refs: targetSessionRefs,
1069
1243
  limit_files_per_source: options.limitFiles,
@@ -1071,7 +1245,7 @@ function buildProbeOptions(source, options, targetSessionRefs = options.sessionR
1071
1245
  on_progress: options.onProgress,
1072
1246
  };
1073
1247
  }
1074
- function compactSourcePayload(payload, contextMode, contextTargets = []) {
1248
+ function compactSourcePayload(payload, contextMode, contextTargets = [], retainConversationEvidence = false) {
1075
1249
  const relatedWork = flattenRelatedWorkIndex(buildSessionRelatedWorkIndex(payload.sessions, payload.fragments));
1076
1250
  const family = familyInventoryFromPayload(payload, relatedWork);
1077
1251
  return {
@@ -1084,6 +1258,7 @@ function compactSourcePayload(payload, contextMode, contextTargets = []) {
1084
1258
  delegated_children: family.children,
1085
1259
  turns: payload.turns,
1086
1260
  contexts: selectPayloadContexts(payload, contextMode, contextTargets),
1261
+ ...(retainConversationEvidence ? { conversation_evidence: buildConversationEvidence(payload.turns, payload.contexts, payload.atoms, payload.sessions) } : {}),
1087
1262
  ask_user_question_turns: payload.ask_user_question_turns,
1088
1263
  loss_audits: payload.loss_audits,
1089
1264
  };
@@ -1196,6 +1371,7 @@ function filterLiveSourcePayloadBySessions(payload, sessionRefs) {
1196
1371
  turns,
1197
1372
  candidates: payload.candidates.filter((candidate) => sessionIds.has(candidate.session_ref)),
1198
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)) } : {}),
1199
1375
  ask_user_question_turns: payload.ask_user_question_turns.filter((turn) => sessionIds.has(turn.session_id)),
1200
1376
  related_work: relatedWork,
1201
1377
  session_contributions: payload.session_contributions?.filter((entry) => familySessionIds.has(entry.session_ref)),
@@ -1471,4 +1647,7 @@ function normalizeJsonShapeForJsonOutputMutating(value) {
1471
1647
  return value;
1472
1648
  }
1473
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";
1474
1653
  //# sourceMappingURL=index.js.map