@graphorin/memory 0.6.1 → 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 (227) hide show
  1. package/CHANGELOG.md +71 -0
  2. package/README.md +1 -1
  3. package/dist/conflict/index.js +0 -1
  4. package/dist/conflict/pipeline.js +0 -1
  5. package/dist/conflict/pipeline.js.map +1 -1
  6. package/dist/conflict/stages/stage3-heuristic-regex.js +0 -1
  7. package/dist/conflict/stages/stage3-heuristic-regex.js.map +1 -1
  8. package/dist/conflict/types.d.ts +1 -1
  9. package/dist/conflict/types.js.map +1 -1
  10. package/dist/consolidator/index.js +2 -0
  11. package/dist/consolidator/index.js.map +1 -1
  12. package/dist/consolidator/lock.js +7 -1
  13. package/dist/consolidator/lock.js.map +1 -1
  14. package/dist/consolidator/phases/deep.js +19 -12
  15. package/dist/consolidator/phases/deep.js.map +1 -1
  16. package/dist/consolidator/phases/induce.d.ts.map +1 -1
  17. package/dist/consolidator/phases/induce.js +2 -3
  18. package/dist/consolidator/phases/induce.js.map +1 -1
  19. package/dist/consolidator/phases/reflect.js +35 -8
  20. package/dist/consolidator/phases/reflect.js.map +1 -1
  21. package/dist/consolidator/phases/standard.js +199 -28
  22. package/dist/consolidator/phases/standard.js.map +1 -1
  23. package/dist/consolidator/reconcile.js +16 -15
  24. package/dist/consolidator/reconcile.js.map +1 -1
  25. package/dist/consolidator/runtime.d.ts.map +1 -1
  26. package/dist/consolidator/runtime.js +129 -47
  27. package/dist/consolidator/runtime.js.map +1 -1
  28. package/dist/consolidator/scheduler.d.ts +17 -3
  29. package/dist/consolidator/scheduler.d.ts.map +1 -1
  30. package/dist/consolidator/scheduler.js.map +1 -1
  31. package/dist/consolidator/types.d.ts +30 -1
  32. package/dist/consolidator/types.d.ts.map +1 -1
  33. package/dist/consolidator/types.js +10 -0
  34. package/dist/consolidator/types.js.map +1 -1
  35. package/dist/context-engine/compaction/clear-tool-results.d.ts +1 -1
  36. package/dist/context-engine/compaction/clear-tool-results.js +1 -1
  37. package/dist/context-engine/compaction/clear-tool-results.js.map +1 -1
  38. package/dist/context-engine/compaction/compactor.d.ts +1 -0
  39. package/dist/context-engine/compaction/compactor.d.ts.map +1 -1
  40. package/dist/context-engine/compaction/compactor.js +32 -8
  41. package/dist/context-engine/compaction/compactor.js.map +1 -1
  42. package/dist/context-engine/compaction/hooks/types.d.ts +1 -1
  43. package/dist/context-engine/compaction/index.d.ts +1 -0
  44. package/dist/context-engine/compaction/templates/marker.d.ts +33 -0
  45. package/dist/context-engine/compaction/templates/marker.d.ts.map +1 -0
  46. package/dist/context-engine/compaction/templates/marker.js +34 -0
  47. package/dist/context-engine/compaction/templates/marker.js.map +1 -0
  48. package/dist/context-engine/compaction/templates/summary-9-section.d.ts +1 -1
  49. package/dist/context-engine/compaction/templates/summary-9-section.d.ts.map +1 -1
  50. package/dist/context-engine/compaction/templates/summary-9-section.js +4 -3
  51. package/dist/context-engine/compaction/templates/summary-9-section.js.map +1 -1
  52. package/dist/context-engine/engine.d.ts +7 -176
  53. package/dist/context-engine/engine.d.ts.map +1 -1
  54. package/dist/context-engine/engine.js +0 -2
  55. package/dist/context-engine/engine.js.map +1 -1
  56. package/dist/context-engine/index.d.ts +8 -49
  57. package/dist/context-engine/io-types.d.ts +144 -0
  58. package/dist/context-engine/io-types.d.ts.map +1 -0
  59. package/dist/context-engine/locale-packs/types.d.ts +1 -1
  60. package/dist/context-engine/locale-packs/types.js.map +1 -1
  61. package/dist/context-engine/privacy-filter.d.ts +1 -2
  62. package/dist/context-engine/privacy-filter.d.ts.map +1 -1
  63. package/dist/context-engine/privacy-filter.js +1 -2
  64. package/dist/context-engine/privacy-filter.js.map +1 -1
  65. package/dist/errors/index.d.ts +2 -2
  66. package/dist/errors/index.js +2 -2
  67. package/dist/errors/index.js.map +1 -1
  68. package/dist/facade.d.ts +43 -52
  69. package/dist/facade.d.ts.map +1 -1
  70. package/dist/facade.js +5 -3
  71. package/dist/facade.js.map +1 -1
  72. package/dist/graph/entity-resolver.js +1 -1
  73. package/dist/graph/entity-resolver.js.map +1 -1
  74. package/dist/index.d.ts +16 -13
  75. package/dist/index.d.ts.map +1 -1
  76. package/dist/index.js +2 -5
  77. package/dist/index.js.map +1 -1
  78. package/dist/internal/envelope.js +57 -0
  79. package/dist/internal/envelope.js.map +1 -0
  80. package/dist/internal/injection-heuristics.js +0 -0
  81. package/dist/internal/injection-heuristics.js.map +1 -1
  82. package/dist/internal/llm-json.js +40 -0
  83. package/dist/internal/llm-json.js.map +1 -0
  84. package/dist/internal/storage-adapter.d.ts +23 -10
  85. package/dist/internal/storage-adapter.d.ts.map +1 -1
  86. package/dist/memory-interface.d.ts +131 -0
  87. package/dist/memory-interface.d.ts.map +1 -0
  88. package/dist/package.js +1 -1
  89. package/dist/package.js.map +1 -1
  90. package/dist/search/iterative.d.ts.map +1 -1
  91. package/dist/search/iterative.js +2 -3
  92. package/dist/search/iterative.js.map +1 -1
  93. package/dist/search/query-transform.d.ts.map +1 -1
  94. package/dist/search/query-transform.js +2 -3
  95. package/dist/search/query-transform.js.map +1 -1
  96. package/dist/tiers/episodic-memory.js +3 -3
  97. package/dist/tiers/episodic-memory.js.map +1 -1
  98. package/dist/tiers/index.d.ts +2 -2
  99. package/dist/tiers/insight-memory.js +1 -1
  100. package/dist/tiers/insight-memory.js.map +1 -1
  101. package/dist/tiers/procedural-memory.d.ts +1 -1
  102. package/dist/tiers/procedural-memory.js +2 -2
  103. package/dist/tiers/procedural-memory.js.map +1 -1
  104. package/dist/tiers/semantic-memory.d.ts +58 -4
  105. package/dist/tiers/semantic-memory.d.ts.map +1 -1
  106. package/dist/tiers/semantic-memory.js +103 -20
  107. package/dist/tiers/semantic-memory.js.map +1 -1
  108. package/dist/tools/block-tools.d.ts +19 -57
  109. package/dist/tools/block-tools.d.ts.map +1 -1
  110. package/dist/tools/block-tools.js.map +1 -1
  111. package/dist/tools/fact-tools.d.ts +53 -214
  112. package/dist/tools/fact-tools.d.ts.map +1 -1
  113. package/dist/tools/fact-tools.js +3 -2
  114. package/dist/tools/fact-tools.js.map +1 -1
  115. package/dist/tools/recall-tools.d.ts +34 -175
  116. package/dist/tools/recall-tools.d.ts.map +1 -1
  117. package/dist/tools/recall-tools.js +5 -4
  118. package/dist/tools/recall-tools.js.map +1 -1
  119. package/dist/tools/runbook-tools.d.ts +15 -58
  120. package/dist/tools/runbook-tools.d.ts.map +1 -1
  121. package/dist/tools/runbook-tools.js.map +1 -1
  122. package/dist/tools/types.d.ts +1 -1
  123. package/package.json +18 -17
  124. package/src/conflict/index.ts +29 -0
  125. package/src/conflict/locale-packs/en.ts +142 -0
  126. package/src/conflict/locale-packs/index.ts +17 -0
  127. package/src/conflict/locale-packs/types.ts +138 -0
  128. package/src/conflict/pipeline.ts +371 -0
  129. package/src/conflict/stages/helpers.ts +65 -0
  130. package/src/conflict/stages/stage1-exact-dedup.ts +40 -0
  131. package/src/conflict/stages/stage2-embedding-three-zone.ts +54 -0
  132. package/src/conflict/stages/stage3-heuristic-regex.ts +51 -0
  133. package/src/conflict/stages/stage4-subject-predicate.ts +46 -0
  134. package/src/conflict/stages/stage5-defer-to-deep.ts +34 -0
  135. package/src/conflict/types.ts +263 -0
  136. package/src/consolidator/budget.ts +312 -0
  137. package/src/consolidator/decay.ts +246 -0
  138. package/src/consolidator/dlq.ts +61 -0
  139. package/src/consolidator/errors.ts +87 -0
  140. package/src/consolidator/idempotency.ts +27 -0
  141. package/src/consolidator/index.ts +269 -0
  142. package/src/consolidator/lock.ts +141 -0
  143. package/src/consolidator/noise-filter.ts +235 -0
  144. package/src/consolidator/phases/deep.ts +308 -0
  145. package/src/consolidator/phases/induce.ts +423 -0
  146. package/src/consolidator/phases/learned-context.ts +233 -0
  147. package/src/consolidator/phases/light.ts +166 -0
  148. package/src/consolidator/phases/reflect.ts +504 -0
  149. package/src/consolidator/phases/standard.ts +1002 -0
  150. package/src/consolidator/reconcile.ts +273 -0
  151. package/src/consolidator/runtime.ts +1049 -0
  152. package/src/consolidator/scheduler.ts +182 -0
  153. package/src/consolidator/triggers.ts +134 -0
  154. package/src/consolidator/types.ts +622 -0
  155. package/src/context-engine/annotations.ts +161 -0
  156. package/src/context-engine/auto-recall.ts +92 -0
  157. package/src/context-engine/compaction/clear-tool-results.ts +232 -0
  158. package/src/context-engine/compaction/compactor.ts +403 -0
  159. package/src/context-engine/compaction/hooks/reanchor-persona-block.ts +55 -0
  160. package/src/context-engine/compaction/hooks/reanchor-pinned-facts.ts +66 -0
  161. package/src/context-engine/compaction/hooks/reanchor-project-rules.ts +57 -0
  162. package/src/context-engine/compaction/hooks/reanchor-recent-results.ts +116 -0
  163. package/src/context-engine/compaction/hooks/types.ts +68 -0
  164. package/src/context-engine/compaction/index.ts +60 -0
  165. package/src/context-engine/compaction/templates/marker.ts +33 -0
  166. package/src/context-engine/compaction/templates/summary-9-section.ts +223 -0
  167. package/src/context-engine/compaction/thresholds.ts +107 -0
  168. package/src/context-engine/compaction/types.ts +255 -0
  169. package/src/context-engine/engine.ts +970 -0
  170. package/src/context-engine/index.ts +118 -0
  171. package/src/context-engine/io-types.ts +162 -0
  172. package/src/context-engine/locale-packs/en.ts +107 -0
  173. package/src/context-engine/locale-packs/index.ts +19 -0
  174. package/src/context-engine/locale-packs/resolver.ts +197 -0
  175. package/src/context-engine/locale-packs/types.ts +177 -0
  176. package/src/context-engine/metadata.ts +114 -0
  177. package/src/context-engine/preambles/inbound-en.ts +19 -0
  178. package/src/context-engine/privacy-filter.ts +190 -0
  179. package/src/context-engine/templates/base-en.ts +19 -0
  180. package/src/context-engine/templates/composer.ts +91 -0
  181. package/src/context-engine/token-budget.ts +319 -0
  182. package/src/context-engine/token-counter.ts +157 -0
  183. package/src/errors/index.ts +273 -0
  184. package/src/facade.ts +750 -0
  185. package/src/graph/entity-resolver.ts +364 -0
  186. package/src/graph/index.ts +24 -0
  187. package/src/index.ts +259 -0
  188. package/src/internal/contextualize.ts +173 -0
  189. package/src/internal/embedder-binding.ts +53 -0
  190. package/src/internal/envelope.ts +70 -0
  191. package/src/internal/id.ts +23 -0
  192. package/src/internal/injection-heuristics.ts +0 -0
  193. package/src/internal/llm-json.ts +38 -0
  194. package/src/internal/spans.ts +35 -0
  195. package/src/internal/storage-adapter.ts +963 -0
  196. package/src/memory-interface.ts +158 -0
  197. package/src/migration/embedder-migration.ts +237 -0
  198. package/src/migration/index.ts +13 -0
  199. package/src/search/explain.ts +123 -0
  200. package/src/search/fit-weights.ts +109 -0
  201. package/src/search/graph-ppr.ts +38 -0
  202. package/src/search/index.ts +55 -0
  203. package/src/search/iterative.ts +658 -0
  204. package/src/search/query-transform.ts +285 -0
  205. package/src/search/rrf.ts +225 -0
  206. package/src/search/trust.ts +55 -0
  207. package/src/search/types.ts +50 -0
  208. package/src/tiers/episodic-memory.ts +463 -0
  209. package/src/tiers/index.ts +50 -0
  210. package/src/tiers/insight-memory.ts +208 -0
  211. package/src/tiers/procedural-memory.ts +482 -0
  212. package/src/tiers/semantic-memory.ts +1729 -0
  213. package/src/tiers/session-memory.ts +271 -0
  214. package/src/tiers/shared-memory.ts +62 -0
  215. package/src/tiers/working-memory.ts +368 -0
  216. package/src/tools/block-tools.ts +172 -0
  217. package/src/tools/fact-tools.ts +473 -0
  218. package/src/tools/index.ts +109 -0
  219. package/src/tools/recall-tools.ts +303 -0
  220. package/src/tools/runbook-tools.ts +107 -0
  221. package/src/tools/taint.ts +39 -0
  222. package/src/tools/types.ts +37 -0
  223. package/dist/conflict/locale-packs/index.js +0 -4
  224. package/dist/context-engine/compaction/index.js +0 -10
  225. package/dist/context-engine/index.d.ts.map +0 -1
  226. package/dist/context-engine/index.js +0 -25
  227. package/dist/context-engine/locale-packs/index.js +0 -4
@@ -0,0 +1,1002 @@
1
+ /**
2
+ * Standard phase - extracts new facts from session messages via the
3
+ * configured cheap-tier provider. The phase is gated by the active
4
+ * tier (DEC-144 / ADR-038) and the budget tracker; it never runs
5
+ * under `tier: 'free'`.
6
+ *
7
+ * The extraction prompt asks the model to return a JSON array of
8
+ * `{ text, subject?, predicate?, object?, confidence? }` objects;
9
+ * malformed responses are tolerated (counted as `emptyExtractions`)
10
+ * so a flaky cheap model never wedges the pipeline.
11
+ *
12
+ * @packageDocumentation
13
+ */
14
+
15
+ import type { Provider, ProviderRequest, SessionScope, Tracer } from '@graphorin/core';
16
+ import {
17
+ type ConflictDecision,
18
+ type ReconcileDecision,
19
+ reconcileToConflictDecision,
20
+ } from '../../conflict/index.js';
21
+ import {
22
+ type ContextualRetrievalMode,
23
+ contextualizeWithLlm,
24
+ } from '../../internal/contextualize.js';
25
+ import { newMemoryId } from '../../internal/id.js';
26
+ import { sliceJsonObject, stripFence } from '../../internal/llm-json.js';
27
+ import { withMemorySpan } from '../../internal/spans.js';
28
+ import type {
29
+ ConsolidatorMemoryStoreExt,
30
+ MemoryStoreAdapter,
31
+ SessionMessageRecord,
32
+ } from '../../internal/storage-adapter.js';
33
+ import type { EpisodicMemory } from '../../tiers/episodic-memory.js';
34
+ import type { FactInput, SemanticMemory } from '../../tiers/semantic-memory.js';
35
+ import type { BudgetTracker } from '../budget.js';
36
+ import { applyNoiseFilters, type NoiseFilterPreset, renderText } from '../noise-filter.js';
37
+ import { preFilterCandidate, reconcileCandidate } from '../reconcile.js';
38
+ import type { PhaseOutcome } from '../types.js';
39
+
40
+ /** Top-s nearest neighbours surfaced to the reconcile pre-filter + LLM. */
41
+ const RECONCILE_TOP_K = 10;
42
+
43
+ /** Inputs accepted by {@link runStandardPhase}. */
44
+ export interface StandardPhaseDeps {
45
+ readonly semantic: SemanticMemory;
46
+ /**
47
+ * Episodic tier used for auto-episode-formation (P1-2). Omitted /
48
+ * `null` ⇒ episode formation is skipped regardless of `formEpisodes`.
49
+ */
50
+ readonly episodic?: EpisodicMemory | null;
51
+ /** Auto-form a quarantined episode per processed slice (P1-2). */
52
+ readonly formEpisodes: boolean;
53
+ /** Ask the episode summary call for a `[1, 10]` importance score (P1-2). */
54
+ readonly importanceScoring: boolean;
55
+ /**
56
+ * Auto-promotion policy (MCON-2). When `true`, an injection-clean extraction
57
+ * fact is admitted `active` instead of quarantined. Injection-flagged facts
58
+ * always stay quarantined. Off by default.
59
+ */
60
+ readonly autoPromoteExtraction: boolean;
61
+ /**
62
+ * Contextual-retrieval mode for additive fact writes (P1-3). `'llm'`
63
+ * spends one budgeted cheap-model call per `add` to author a situating
64
+ * prefix; `'late-chunk'` / `'off'` defer to the shared
65
+ * {@link SemanticMemory} instance (no extra call here).
66
+ */
67
+ readonly contextualRetrieval: ContextualRetrievalMode;
68
+ readonly store: MemoryStoreAdapter;
69
+ readonly consolidatorStore: ConsolidatorMemoryStoreExt | null;
70
+ readonly provider: Provider;
71
+ readonly tracer: Tracer;
72
+ readonly scope: SessionScope;
73
+ readonly cheapModel: string | null;
74
+ readonly noiseFilters: ReadonlyArray<NoiseFilterPreset>;
75
+ readonly maxBatchSize: number;
76
+ /**
77
+ * W-081: input transcript budget in characters (chars/4 token proxy).
78
+ * A multi-message slice whose rendered transcript exceeds it is
79
+ * half-split BEFORE the provider call; a single message that alone
80
+ * exceeds it is tail-truncated (recorded on the phase span).
81
+ */
82
+ readonly maxTranscriptChars: number;
83
+ readonly lastProcessedMessageId: string | null;
84
+ readonly budget: BudgetTracker;
85
+ /** Computes USD cost for the recorded usage. Defaults to 0 when omitted. */
86
+ readonly priceUsage?: (usage: { promptTokens: number; completionTokens: number }) => number;
87
+ readonly tier: 'cheap' | 'standard' | 'full' | 'custom';
88
+ /** Override the wall clock - used by tests + the runtime clock seam. */
89
+ readonly now?: () => number;
90
+ /**
91
+ * Pre-fetched message batch - when supplied, the phase skips its
92
+ * own `listMessagesSince(...)` call and operates on the supplied
93
+ * rows. The runtime always pre-fetches the batch so the cursor
94
+ * advance can use the same data the phase processed.
95
+ */
96
+ readonly batch?: ReadonlyArray<SessionMessageRecord>;
97
+ }
98
+
99
+ interface ExtractedFact {
100
+ readonly text: string;
101
+ readonly subject?: string;
102
+ readonly predicate?: string;
103
+ readonly object?: string;
104
+ readonly confidence?: number;
105
+ /** Raw `[1, 10]` importance as returned by the model, pre-normalization (MCON-12). */
106
+ readonly importance?: number;
107
+ }
108
+
109
+ /** Parsed episode-summary payload (P1-2). */
110
+ interface ExtractedEpisode {
111
+ readonly summary: string;
112
+ /** Raw `[1, 10]` importance as returned by the model, pre-normalization. */
113
+ readonly importance?: number;
114
+ }
115
+
116
+ const EXTRACTION_SYSTEM_PROMPT = [
117
+ 'You are a memory-extraction assistant for a long-running personal-assistant runtime.',
118
+ 'Read the supplied conversation slice and return the durable facts it asserts about the user, the world, or stable preferences.',
119
+ 'Skip greetings, banter, transient state, and anything the assistant produced as boilerplate.',
120
+ // C5 (memory-consolidation-08): decontextualization - proposition-
121
+ // granular retrieval only works when each stored fact stands alone.
122
+ 'Each fact text MUST be a self-contained proposition understandable with no surrounding context: resolve pronouns and ellipses to the named person or thing ("she" -> "Maria"), inline the concrete entities, and never write a fact that needs a neighbouring fact to make sense.',
123
+ 'For each fact also rate how important it is for remembering the user, on an integer scale from 1 (incidental detail) to 10 (identity-defining).',
124
+ 'Return a single JSON object: { "facts": [{ "text": string, "subject"?: string, "predicate"?: string, "object"?: string, "confidence"?: number, "importance"?: number }] }.',
125
+ 'If the slice contains no durable facts, return { "facts": [] }.',
126
+ ].join(' ');
127
+
128
+ /**
129
+ * Per-call output-token ceilings (MCON-14). `BudgetTracker.record()`
130
+ * only runs AFTER `provider.generate` returns, so without a request cap
131
+ * a degenerate model response could blow through the daily ceiling in a
132
+ * single call before `pause` can take effect. All consolidator output
133
+ * shapes are small and well-defined; the caps are deliberately roomy.
134
+ */
135
+ const EXTRACTION_MAX_TOKENS = 1024;
136
+ const EPISODE_MAX_TOKENS = 512;
137
+
138
+ const EPISODE_SUMMARY_SYSTEM_PROMPT = [
139
+ 'You are an episode-summarization assistant for a long-running personal-assistant runtime.',
140
+ 'Read the supplied conversation slice and write one concise third-person summary of what happened - the episode.',
141
+ 'Return a single JSON object: { "summary": string }.',
142
+ ].join(' ');
143
+
144
+ const EPISODE_SUMMARY_IMPORTANCE_SYSTEM_PROMPT = [
145
+ 'You are an episode-summarization assistant for a long-running personal-assistant runtime.',
146
+ 'Read the supplied conversation slice and write one concise third-person summary of what happened - the episode.',
147
+ 'Also rate how important / poignant this episode is for remembering the user, on an integer scale from 1 (mundane) to 10 (deeply significant).',
148
+ 'Return a single JSON object: { "summary": string, "importance": number }.',
149
+ ].join(' ');
150
+
151
+ /**
152
+ * Run the standard phase. Returns a {@link PhaseOutcome}; errors are
153
+ * surfaced via `status: 'failed'` + `errorMessage` so the caller can
154
+ * land the batch in the DLQ.
155
+ *
156
+ * @stable
157
+ */
158
+ export async function runStandardPhase(deps: StandardPhaseDeps): Promise<PhaseOutcome> {
159
+ return withMemorySpan(
160
+ deps.tracer,
161
+ 'memory.consolidate.standard',
162
+ deps.scope,
163
+ {
164
+ 'consolidator.phase': 'standard',
165
+ 'consolidator.tier': deps.tier,
166
+ 'consolidator.cheap_model': deps.cheapModel ?? deps.provider.modelId,
167
+ },
168
+ async (span) => {
169
+ const startedAt = (typeof deps.now === 'function' ? deps.now : Date.now)();
170
+ const session = deps.store.session;
171
+ let rawBatch: ReadonlyArray<SessionMessageRecord>;
172
+ if (deps.batch !== undefined) {
173
+ rawBatch = deps.batch;
174
+ } else {
175
+ if (typeof session.listMessagesSince !== 'function') {
176
+ span.setAttributes({
177
+ 'consolidator.standard.skipped': 'no-cursor-support',
178
+ 'consolidator.duration_ms': 0,
179
+ 'consolidator.facts_extracted': 0,
180
+ 'consolidator.budget_used_usd': 0,
181
+ });
182
+ return emptyOutcome('completed');
183
+ }
184
+ rawBatch = await session.listMessagesSince(
185
+ deps.scope,
186
+ deps.lastProcessedMessageId,
187
+ deps.maxBatchSize,
188
+ );
189
+ }
190
+ const filtered = applyNoiseFilters(
191
+ rawBatch as ReadonlyArray<SessionMessageRecord>,
192
+ deps.noiseFilters,
193
+ );
194
+ span.setAttributes({
195
+ 'consolidator.standard.batch_size': rawBatch.length,
196
+ 'consolidator.standard.kept_count': filtered.kept.length,
197
+ 'consolidator.standard.noise_filtered': filtered.droppedCount,
198
+ });
199
+ if (filtered.kept.length === 0) {
200
+ span.setAttributes({
201
+ 'consolidator.duration_ms': Math.max(
202
+ 0,
203
+ (typeof deps.now === 'function' ? deps.now : Date.now)() - startedAt,
204
+ ),
205
+ 'consolidator.facts_extracted': 0,
206
+ 'consolidator.budget_used_usd': 0,
207
+ });
208
+ return {
209
+ ...emptyOutcome('completed'),
210
+ noiseFilteredCount: filtered.droppedCount,
211
+ };
212
+ }
213
+
214
+ const transcript = renderTranscript(filtered.kept);
215
+ // W-020: the extraction handles `finishReason: 'length'` by
216
+ // half-splitting the batch (or salvaging the complete prefix of a
217
+ // single-message slice) instead of letting a truncated JSON parse
218
+ // to `[]` and the runtime advance the cursor over a lossy slice.
219
+ // Budget recording happens per generate call inside the helper.
220
+ const extraction = await extractFactsFromSlice(deps, filtered.kept);
221
+ const facts = extraction.facts;
222
+ const cost = extraction.costUsd;
223
+ let factsCreated = 0;
224
+ let factsUpdated = 0;
225
+ let conflictsResolved = 0;
226
+ let reconcileTokens = 0;
227
+ let reconcileCost = 0;
228
+ let contextualTokens = 0;
229
+ let contextualCost = 0;
230
+ const extractionTokens = extraction.tokens;
231
+
232
+ for (const fact of facts) {
233
+ if (fact.text.trim().length === 0) continue;
234
+ const input = buildFactInput(fact);
235
+
236
+ // Neighbour-aware reconciliation (P0-3). A cheap, LLM-free pre-filter
237
+ // (Stage 1 exact-dedup + Stage 2 embedding zones) classifies the
238
+ // candidate against its nearest neighbours; only the ambiguous
239
+ // CONFLICT-CHECK mid-zone spends a reconcile LLM call. With no
240
+ // embedder configured `neighbors` is empty → every candidate is a
241
+ // fresh `add`, preserving the pre-reconcile behaviour.
242
+ const neighbors = await deps.semantic.neighbors(deps.scope, fact.text, {
243
+ topK: RECONCILE_TOP_K,
244
+ });
245
+ let route = await preFilterCandidate(fact.text, neighbors);
246
+ // memory-consolidation-07: without an embedder `neighbors` is
247
+ // always empty, so dedup never fires and a DLQ replay (or plain
248
+ // re-run) of a partially-committed slice re-writes every
249
+ // already-committed fact verbatim. Guard with an
250
+ // embedder-independent exact-text lookup: FTS top hits +
251
+ // string equality. Skipped in the mainline (embedder) config,
252
+ // where the KNN stages already catch exact duplicates.
253
+ if (route.route !== 'noop' && neighbors.length === 0) {
254
+ const exactId = await findExactTextDuplicate(deps.semantic, deps.scope, fact.text);
255
+ if (exactId !== null) {
256
+ route = { route: 'noop', targetId: exactId, reason: 'exact-text-fts' };
257
+ }
258
+ }
259
+
260
+ let decision: ReconcileDecision;
261
+ let audited: ConflictDecision;
262
+ if (route.route === 'reconcile' && !deps.budget.snapshot().paused) {
263
+ const result = await reconcileCandidate({
264
+ candidateText: fact.text,
265
+ neighbors: neighbors.map((h) => ({
266
+ id: h.record.id,
267
+ text: h.record.text,
268
+ ...(h.record.validFrom !== undefined ? { validFrom: h.record.validFrom } : {}),
269
+ })),
270
+ provider: deps.provider,
271
+ scope: deps.scope,
272
+ });
273
+ decision = result.decision;
274
+ audited = reconcileToConflictDecision(decision);
275
+ reconcileTokens += result.usage.totalTokens;
276
+ const callCost =
277
+ deps.priceUsage?.({
278
+ promptTokens: result.usage.promptTokens,
279
+ completionTokens: result.usage.completionTokens,
280
+ }) ?? 0;
281
+ reconcileCost += callCost;
282
+ deps.budget.record({
283
+ phase: 'standard',
284
+ tokens: result.usage.totalTokens,
285
+ costUsd: callCost,
286
+ });
287
+ } else if (route.route === 'reconcile') {
288
+ // Mid-zone but the budget is exhausted - fall back to a safe
289
+ // additive write rather than spending an over-budget LLM call.
290
+ decision = { action: 'add', reason: 'reconcile-budget-paused' };
291
+ audited = { kind: 'admit', stage: 'defer-to-deep', reason: 'reconcile-budget-paused' };
292
+ } else if (route.route === 'noop') {
293
+ decision = { action: 'noop', targetId: route.targetId, reason: route.reason };
294
+ audited = {
295
+ kind: 'dedup',
296
+ stage:
297
+ route.reason === 'exact-hash-match' || route.reason === 'exact-text-fts'
298
+ ? 'exact-dedup'
299
+ : 'embedding-three-zone',
300
+ existingId: route.targetId,
301
+ ...(route.similarity !== undefined ? { similarity: route.similarity } : {}),
302
+ reason: route.reason,
303
+ };
304
+ } else {
305
+ decision = { action: 'add', reason: route.reason };
306
+ audited = { kind: 'admit', stage: 'embedding-three-zone', reason: route.reason };
307
+ }
308
+
309
+ // Apply the decision. Updates / conflicts route through the
310
+ // bi-temporal supersede (close the old interval, insert the new) -
311
+ // never a destructive delete (P0-3).
312
+ let candidateId: string;
313
+ switch (decision.action) {
314
+ case 'add': {
315
+ // Contextual retrieval (P1-3). In `'llm'` mode (and only when
316
+ // the budget is not exhausted) spend one cheap-model call to
317
+ // author a situating prefix and pass it as the write's index
318
+ // text; the helper degrades to the deterministic late-chunk
319
+ // prefix on any failure. `'late-chunk'` / `'off'` add nothing
320
+ // here - the shared SemanticMemory instance contextualizes the
321
+ // write. This LLM call is the only contextualization that
322
+ // touches a provider, keeping `'llm'` strictly consolidator-only.
323
+ let indexText: string | undefined;
324
+ if (deps.contextualRetrieval === 'llm' && !deps.budget.snapshot().paused) {
325
+ const ctx = await contextualizeWithLlm(
326
+ {
327
+ text: input.text,
328
+ ...(input.subject !== undefined ? { subject: input.subject } : {}),
329
+ ...(input.predicate !== undefined ? { predicate: input.predicate } : {}),
330
+ ...(input.object !== undefined ? { object: input.object } : {}),
331
+ },
332
+ deps.provider,
333
+ );
334
+ indexText = ctx.indexText;
335
+ const ctxTokens =
336
+ (ctx.usage.promptTokens ?? 0) +
337
+ (ctx.usage.completionTokens ?? 0) +
338
+ (ctx.usage.reasoningTokens ?? 0);
339
+ const ctxCost =
340
+ deps.priceUsage?.({
341
+ promptTokens: ctx.usage.promptTokens,
342
+ completionTokens: ctx.usage.completionTokens,
343
+ }) ?? 0;
344
+ contextualTokens += ctxTokens;
345
+ contextualCost += ctxCost;
346
+ deps.budget.record({ phase: 'standard', tokens: ctxTokens, costUsd: ctxCost });
347
+ }
348
+ // `pipeline: 'off'` - the standard phase has already made the
349
+ // conflict decision; a second inline pass would re-search +
350
+ // double-audit.
351
+ const stored = await deps.semantic.remember(deps.scope, input, {
352
+ pipeline: 'off',
353
+ ...(indexText !== undefined ? { indexText } : {}),
354
+ ...(deps.autoPromoteExtraction ? { autoPromoteSynthesized: true } : {}),
355
+ });
356
+ candidateId = stored.id;
357
+ factsCreated += 1;
358
+ break;
359
+ }
360
+ case 'noop': {
361
+ // Duplicate of `targetId` - record the dedup, write nothing.
362
+ candidateId = newMemoryId('fact');
363
+ break;
364
+ }
365
+ case 'update': {
366
+ // W-019: the escape hatch applies to update/conflict routes
367
+ // exactly like the 'add' route (the documented contract of
368
+ // autoPromoteExtraction); without it the successor stays
369
+ // quarantined and the supersede is PENDING - the old fact
370
+ // remains recall-visible until fact_validate promotes the
371
+ // successor.
372
+ const { new: stored } = await deps.semantic.supersede(
373
+ deps.scope,
374
+ decision.targetId,
375
+ input,
376
+ decision.reason,
377
+ { autoPromoteSynthesized: deps.autoPromoteExtraction },
378
+ );
379
+ candidateId = stored.id;
380
+ factsUpdated += 1;
381
+ break;
382
+ }
383
+ case 'conflict': {
384
+ const { new: stored } = await deps.semantic.supersede(
385
+ deps.scope,
386
+ decision.targetId,
387
+ input,
388
+ decision.reason,
389
+ { autoPromoteSynthesized: deps.autoPromoteExtraction },
390
+ );
391
+ candidateId = stored.id;
392
+ factsUpdated += 1;
393
+ conflictsResolved += 1;
394
+ break;
395
+ }
396
+ }
397
+
398
+ // Every decision is auditable in `fact_conflicts` (best-effort -
399
+ // a store without the conflict surface simply skips it).
400
+ await recordConflictDecision(deps.store, deps.scope, candidateId, audited);
401
+ }
402
+
403
+ // Episode formation (P1-2). Summarize the processed slice into one
404
+ // quarantined episode carrying an LLM importance score, so the
405
+ // episodic triple-signal ranking (recency × relevance × importance)
406
+ // runs on all three signals. Budget-gated + provenance-tagged
407
+ // (P1-4): skipped when `formEpisodes` is off, no episodic tier is
408
+ // wired, or the budget is exhausted - the slice still advanced the
409
+ // cursor, so the phase degrades to fact-only behaviour.
410
+ let episodesFormed = 0;
411
+ let episodeTokens = 0;
412
+ let episodeCost = 0;
413
+ if (
414
+ deps.formEpisodes &&
415
+ deps.episodic != null &&
416
+ filtered.kept.length > 0 &&
417
+ !deps.budget.snapshot().paused
418
+ ) {
419
+ const episodeRes = await deps.provider.generate(
420
+ buildEpisodeRequest(deps, transcript, deps.importanceScoring),
421
+ );
422
+ const epUsage = episodeRes.usage;
423
+ episodeTokens =
424
+ (epUsage.promptTokens ?? 0) +
425
+ (epUsage.completionTokens ?? 0) +
426
+ (epUsage.reasoningTokens ?? 0);
427
+ episodeCost =
428
+ deps.priceUsage?.({
429
+ promptTokens: epUsage.promptTokens,
430
+ completionTokens: epUsage.completionTokens,
431
+ }) ?? 0;
432
+ deps.budget.record({ phase: 'standard', tokens: episodeTokens, costUsd: episodeCost });
433
+
434
+ const parsed = parseEpisode(episodeRes.text);
435
+ if (parsed !== null && parsed.summary.trim().length > 0) {
436
+ const importance = deps.importanceScoring
437
+ ? normalizeImportance(parsed.importance)
438
+ : undefined;
439
+ const nowFallback = new Date(
440
+ (typeof deps.now === 'function' ? deps.now : Date.now)(),
441
+ ).toISOString();
442
+ const startedAt = filtered.kept[0]?.createdAt ?? nowFallback;
443
+ const endedAt = filtered.kept[filtered.kept.length - 1]?.createdAt ?? startedAt;
444
+ await deps.episodic.record(deps.scope, {
445
+ summary: parsed.summary,
446
+ startedAt,
447
+ endedAt,
448
+ ...(importance !== undefined ? { importance } : {}),
449
+ provenance: 'extraction',
450
+ status: 'quarantined',
451
+ // D3: an auto-formed episode is the agent's own synthesis.
452
+ owner: 'agent',
453
+ });
454
+ episodesFormed = 1;
455
+ }
456
+ }
457
+
458
+ const totalTokens = extractionTokens + reconcileTokens + episodeTokens + contextualTokens;
459
+ const totalCost = cost + reconcileCost + episodeCost + contextualCost;
460
+ const snapshot = deps.budget.snapshot();
461
+
462
+ span.setAttributes({
463
+ 'consolidator.duration_ms': Math.max(
464
+ 0,
465
+ (typeof deps.now === 'function' ? deps.now : Date.now)() - startedAt,
466
+ ),
467
+ 'consolidator.facts_extracted': factsCreated,
468
+ 'consolidator.budget_used_usd': totalCost,
469
+ 'consolidator.standard.facts_extracted': factsCreated,
470
+ 'consolidator.standard.facts_updated': factsUpdated,
471
+ 'consolidator.standard.conflicts_resolved': conflictsResolved,
472
+ 'consolidator.standard.episodes_formed': episodesFormed,
473
+ 'consolidator.standard.reconcile_tokens': reconcileTokens,
474
+ 'consolidator.standard.episode_tokens': episodeTokens,
475
+ 'consolidator.standard.contextual_tokens': contextualTokens,
476
+ // W-020: 'empty slice' vs 'truncated output' must be
477
+ // distinguishable - these attrs stay 0 on the ordinary path.
478
+ 'consolidator.standard.extraction_calls': extraction.generateCalls,
479
+ 'consolidator.standard.length_splits': extraction.lengthSplits,
480
+ 'consolidator.standard.truncated_salvage': extraction.truncatedSalvages,
481
+ // W-081: input-budget splits / single-message tail truncations.
482
+ 'consolidator.standard.budget_splits': extraction.budgetSplits,
483
+ 'consolidator.standard.input_truncations': extraction.inputTruncations,
484
+ 'consolidator.standard.tokens.input': extraction.promptTokens,
485
+ 'consolidator.standard.tokens.output': extraction.completionTokens,
486
+ 'consolidator.standard.cost.estimate.usd': totalCost,
487
+ 'consolidator.budget.remaining.tokens': snapshot.tokensRemaining,
488
+ 'consolidator.budget.remaining.usd': snapshot.costRemaining,
489
+ 'consolidator.exceeded': snapshot.paused,
490
+ });
491
+
492
+ return {
493
+ phase: 'standard',
494
+ status: 'completed',
495
+ factsCreated,
496
+ factsUpdated,
497
+ conflictsResolved,
498
+ episodesFormed,
499
+ insightsCreated: 0,
500
+ noiseFilteredCount: filtered.droppedCount,
501
+ emptyExtractions: facts.length === 0 ? 1 : 0,
502
+ llmTokensUsed: totalTokens,
503
+ llmCostUsd: totalCost,
504
+ errorMessage: null,
505
+ };
506
+ },
507
+ );
508
+ }
509
+
510
+ /** Aggregated result of {@link extractFactsFromSlice}. */
511
+ interface SliceExtraction {
512
+ readonly facts: ReadonlyArray<ExtractedFact>;
513
+ /** Total extraction tokens across every generate call. */
514
+ readonly tokens: number;
515
+ readonly costUsd: number;
516
+ readonly promptTokens: number;
517
+ readonly completionTokens: number;
518
+ readonly generateCalls: number;
519
+ /** Number of batches that were half-split on `finishReason: 'length'`. */
520
+ readonly lengthSplits: number;
521
+ /** Number of single-message slices salvaged from a truncated output. */
522
+ readonly truncatedSalvages: number;
523
+ /** W-081: number of batches half-split on the INPUT transcript budget. */
524
+ readonly budgetSplits: number;
525
+ /** W-081: number of lone over-budget messages that were tail-truncated. */
526
+ readonly inputTruncations: number;
527
+ }
528
+
529
+ /**
530
+ * W-020: run 'render transcript -> generate -> record budget -> parse'
531
+ * for one slice, handling `finishReason: 'length'`:
532
+ *
533
+ * - multi-message slice: split in half (message order preserved) and
534
+ * recurse - depth is bounded by log2(maxStandardBatchSize) and each
535
+ * call passes `deps.budget.record`, with a pause check before every
536
+ * sub-call (a paused budget THROWS, so the runtime lands the batch in
537
+ * the DLQ WITHOUT advancing the cursor - the established failure
538
+ * semantics). A DLQ route on truncation itself was rejected: replay
539
+ * re-reads the same slice with the same output cap and deterministically
540
+ * truncates again (the W-081 wedge shape); half-splitting converges.
541
+ * - single message: salvage the complete prefix of the truncated JSON
542
+ * ({@link salvageTruncatedExtraction}) - a lone message that overflows
543
+ * the cap cannot be split further, and losing its parseable facts is
544
+ * strictly worse than keeping them.
545
+ *
546
+ * Facts are only RETURNED here; the caller writes them after every
547
+ * sub-slice extracted successfully, so a mid-split failure leaves no
548
+ * partially-committed slice (replay is additionally guarded by the
549
+ * exact-text dedup, memory-consolidation-07).
550
+ */
551
+ async function extractFactsFromSlice(
552
+ deps: StandardPhaseDeps,
553
+ messages: ReadonlyArray<SessionMessageRecord>,
554
+ ): Promise<SliceExtraction> {
555
+ // W-081: input-side transcript budget. `maxStandardBatchSize` bounds
556
+ // only the MESSAGE COUNT; a batch of near-noise-cap messages can render
557
+ // to hundreds of kilobytes and overflow a cheap-tier context on EVERY
558
+ // retry - the permanent cursor wedge W-081 describes. Split BEFORE
559
+ // spending a provider call that would deterministically fail.
560
+ if (messages.length > 1 && renderTranscript(messages).length > deps.maxTranscriptChars) {
561
+ return extractHalves(deps, messages, {
562
+ tokens: 0,
563
+ costUsd: 0,
564
+ promptTokens: 0,
565
+ completionTokens: 0,
566
+ generateCalls: 0,
567
+ lengthSplits: 0,
568
+ truncatedSalvages: 0,
569
+ budgetSplits: 1,
570
+ inputTruncations: 0,
571
+ });
572
+ }
573
+
574
+ // W-081: a lone message that alone exceeds the budget cannot be split
575
+ // further - truncate its tail (the phase span records the count) so
576
+ // extraction keeps whatever facts the head carries instead of failing
577
+ // on the same oversized message forever.
578
+ let effective = messages;
579
+ let inputTruncations = 0;
580
+ const sole = messages.length === 1 ? messages[0] : undefined;
581
+ if (sole !== undefined) {
582
+ const rendered = renderTranscript(messages);
583
+ if (rendered.length > deps.maxTranscriptChars) {
584
+ const overshoot = rendered.length - deps.maxTranscriptChars;
585
+ const text = renderText(sole.message);
586
+ const keep = Math.max(0, text.length - overshoot);
587
+ effective = [{ ...sole, message: { ...sole.message, content: text.slice(0, keep) } }];
588
+ inputTruncations = 1;
589
+ }
590
+ }
591
+
592
+ const request = buildRequest(deps, renderTranscript(effective));
593
+ const response = await deps.provider.generate(request);
594
+ const usage = response.usage;
595
+ const costUsd =
596
+ deps.priceUsage?.({
597
+ promptTokens: usage.promptTokens,
598
+ completionTokens: usage.completionTokens,
599
+ }) ?? 0;
600
+ const tokens =
601
+ (usage.promptTokens ?? 0) + (usage.completionTokens ?? 0) + (usage.reasoningTokens ?? 0);
602
+ deps.budget.record({ phase: 'standard', tokens, costUsd });
603
+ const base = {
604
+ tokens,
605
+ costUsd,
606
+ promptTokens: usage.promptTokens ?? 0,
607
+ completionTokens: usage.completionTokens ?? 0,
608
+ generateCalls: 1,
609
+ budgetSplits: 0,
610
+ inputTruncations,
611
+ };
612
+
613
+ if (response.finishReason !== 'length') {
614
+ return {
615
+ ...base,
616
+ facts: parseExtraction(response.text),
617
+ lengthSplits: 0,
618
+ truncatedSalvages: 0,
619
+ };
620
+ }
621
+
622
+ if (messages.length === 1) {
623
+ return {
624
+ ...base,
625
+ facts: salvageTruncatedExtraction(response.text),
626
+ lengthSplits: 0,
627
+ truncatedSalvages: 1,
628
+ };
629
+ }
630
+
631
+ return extractHalves(deps, messages, { ...base, lengthSplits: 1, truncatedSalvages: 0 });
632
+ }
633
+
634
+ /**
635
+ * Split `messages` in half (order preserved) and extract each half
636
+ * recursively, folding counters into `seed`. Shared by the two split
637
+ * triggers: output truncation (W-020, `finishReason: 'length'`) and the
638
+ * W-081 input budget (transcript over `maxTranscriptChars`). Depth is
639
+ * bounded by log2(maxStandardBatchSize); a paused budget THROWS so the
640
+ * runtime lands the batch in the DLQ WITHOUT advancing the cursor (the
641
+ * established failure semantics - see the {@link extractFactsFromSlice}
642
+ * docblock for why a DLQ route on truncation itself was rejected).
643
+ */
644
+ async function extractHalves(
645
+ deps: StandardPhaseDeps,
646
+ messages: ReadonlyArray<SessionMessageRecord>,
647
+ seed: Omit<SliceExtraction, 'facts'>,
648
+ ): Promise<SliceExtraction> {
649
+ const mid = Math.ceil(messages.length / 2);
650
+ const halves = [messages.slice(0, mid), messages.slice(mid)];
651
+ const merged: ExtractedFact[] = [];
652
+ let acc = seed;
653
+ for (const half of halves) {
654
+ if (deps.budget.snapshot().paused) {
655
+ throw new Error(
656
+ 'standard extraction needs a sub-slice split and the budget is paused - aborting ' +
657
+ 'the split so the batch lands in the DLQ without advancing the cursor',
658
+ );
659
+ }
660
+ const sub = await extractFactsFromSlice(deps, half);
661
+ merged.push(...sub.facts);
662
+ acc = {
663
+ tokens: acc.tokens + sub.tokens,
664
+ costUsd: acc.costUsd + sub.costUsd,
665
+ promptTokens: acc.promptTokens + sub.promptTokens,
666
+ completionTokens: acc.completionTokens + sub.completionTokens,
667
+ generateCalls: acc.generateCalls + sub.generateCalls,
668
+ lengthSplits: acc.lengthSplits + sub.lengthSplits,
669
+ truncatedSalvages: acc.truncatedSalvages + sub.truncatedSalvages,
670
+ budgetSplits: acc.budgetSplits + sub.budgetSplits,
671
+ inputTruncations: acc.inputTruncations + sub.inputTruncations,
672
+ };
673
+ }
674
+ return { ...acc, facts: merged };
675
+ }
676
+
677
+ /**
678
+ * W-020: recover the complete prefix of a length-truncated extraction.
679
+ * Walks the `facts` array with string/escape-aware bracket tracking,
680
+ * cuts the trailing incomplete object, closes the array, and delegates
681
+ * field validation to {@link parseExtraction}. A salvaged half-formed
682
+ * fact is acceptable: everything returned here still flows through the
683
+ * ordinary reconcile / quarantine path. Returns `[]` when nothing
684
+ * complete survived.
685
+ *
686
+ * @internal
687
+ */
688
+ export function salvageTruncatedExtraction(text: string | undefined): ReadonlyArray<ExtractedFact> {
689
+ if (text === undefined || text.length === 0) return [];
690
+ const candidate = stripFence(text);
691
+ const arrayStart = candidate.indexOf('[');
692
+ if (arrayStart < 0) return [];
693
+ let inString = false;
694
+ let escaped = false;
695
+ let depth = 0;
696
+ let lastCompleteEnd = -1;
697
+ let closedProperly = false;
698
+ for (let i = arrayStart + 1; i < candidate.length; i += 1) {
699
+ const ch = candidate[i];
700
+ if (inString) {
701
+ if (escaped) escaped = false;
702
+ else if (ch === '\\') escaped = true;
703
+ else if (ch === '"') inString = false;
704
+ continue;
705
+ }
706
+ if (ch === '"') {
707
+ inString = true;
708
+ continue;
709
+ }
710
+ if (ch === '{' || ch === '[') {
711
+ depth += 1;
712
+ continue;
713
+ }
714
+ if (ch === '}' || ch === ']') {
715
+ if (ch === ']' && depth === 0) {
716
+ // The array itself closed - the truncation happened later.
717
+ lastCompleteEnd = i;
718
+ closedProperly = true;
719
+ break;
720
+ }
721
+ depth -= 1;
722
+ if (depth === 0) lastCompleteEnd = i;
723
+ }
724
+ }
725
+ if (lastCompleteEnd < 0) return [];
726
+ const arrayText = candidate.slice(arrayStart, lastCompleteEnd + 1);
727
+ const repaired = `{"facts":${arrayText}${closedProperly ? '' : ']'}}`;
728
+ try {
729
+ JSON.parse(repaired);
730
+ } catch {
731
+ return [];
732
+ }
733
+ return parseExtraction(repaired);
734
+ }
735
+
736
+ function buildRequest(deps: StandardPhaseDeps, transcript: string): ProviderRequest {
737
+ // memory-consolidation-08: temporal anchoring - state today's date and
738
+ // instruct the model to resolve relative time into absolute dates, so
739
+ // "I'm interviewing next Friday" becomes a dated, durable fact.
740
+ const today = new Date(deps.now?.() ?? Date.now()).toISOString().slice(0, 10);
741
+ return {
742
+ messages: [
743
+ {
744
+ role: 'user',
745
+ content: `Conversation slice:\n${transcript}`,
746
+ },
747
+ ],
748
+ systemMessage:
749
+ `${EXTRACTION_SYSTEM_PROMPT} Today is ${today}. Each transcript line carries its ` +
750
+ 'timestamp in parentheses; resolve relative dates ("next Friday", "last month") ' +
751
+ 'into absolute ISO dates in the extracted fact text.',
752
+ temperature: 0,
753
+ maxTokens: EXTRACTION_MAX_TOKENS,
754
+ metadata: {
755
+ userId: deps.scope.userId,
756
+ ...(deps.scope.sessionId !== undefined ? { sessionId: deps.scope.sessionId } : {}),
757
+ ...(deps.scope.agentId !== undefined ? { agentId: deps.scope.agentId } : {}),
758
+ },
759
+ outputType: { kind: 'structured' },
760
+ };
761
+ }
762
+
763
+ /**
764
+ * Build the episode-summarization request (P1-2). Uses the same
765
+ * transcript + structured-output seam as {@link buildRequest}; the
766
+ * system prompt switches on `withImportance` so a poignancy score is
767
+ * only requested when importance scoring is enabled.
768
+ */
769
+ function buildEpisodeRequest(
770
+ deps: StandardPhaseDeps,
771
+ transcript: string,
772
+ withImportance: boolean,
773
+ ): ProviderRequest {
774
+ return {
775
+ messages: [
776
+ {
777
+ role: 'user',
778
+ content: `Conversation slice:\n${transcript}`,
779
+ },
780
+ ],
781
+ systemMessage: withImportance
782
+ ? EPISODE_SUMMARY_IMPORTANCE_SYSTEM_PROMPT
783
+ : EPISODE_SUMMARY_SYSTEM_PROMPT,
784
+ temperature: 0,
785
+ maxTokens: EPISODE_MAX_TOKENS,
786
+ metadata: {
787
+ userId: deps.scope.userId,
788
+ ...(deps.scope.sessionId !== undefined ? { sessionId: deps.scope.sessionId } : {}),
789
+ ...(deps.scope.agentId !== undefined ? { agentId: deps.scope.agentId } : {}),
790
+ },
791
+ outputType: { kind: 'structured' },
792
+ };
793
+ }
794
+
795
+ function renderTranscript(messages: ReadonlyArray<SessionMessageRecord>): string {
796
+ return messages
797
+ .map((m) => {
798
+ const role = m.message.role;
799
+ const text = renderText(m.message);
800
+ // memory-consolidation-08: per-message timestamps anchor the
801
+ // extraction - without them relative time ("next Friday", "last
802
+ // month") distils into facts with no resolvable timeframe.
803
+ const stamp = typeof m.createdAt === 'string' && m.createdAt.length > 0 ? m.createdAt : '';
804
+ return stamp.length > 0
805
+ ? `[${m.sequence}] (${stamp}) ${role}: ${text}`
806
+ : `[${m.sequence}] ${role}: ${text}`;
807
+ })
808
+ .join('\n');
809
+ }
810
+
811
+ /**
812
+ * Parse the model output into the structured fact list. Tolerates
813
+ * fenced blocks + trailing commentary so a chatty model does not
814
+ * wedge the cursor.
815
+ *
816
+ * @internal
817
+ */
818
+ export function parseExtraction(text: string | undefined): ReadonlyArray<ExtractedFact> {
819
+ if (text === undefined || text.length === 0) return [];
820
+ const candidate = stripFence(text).trim();
821
+ if (candidate.length === 0) return [];
822
+ let parsed: unknown;
823
+ try {
824
+ parsed = JSON.parse(candidate);
825
+ } catch {
826
+ const slice = sliceJsonObject(candidate);
827
+ if (slice === null) return [];
828
+ try {
829
+ parsed = JSON.parse(slice);
830
+ } catch {
831
+ return [];
832
+ }
833
+ }
834
+ if (parsed === null || typeof parsed !== 'object') return [];
835
+ const root = parsed as { facts?: unknown };
836
+ const facts = Array.isArray(root.facts) ? root.facts : Array.isArray(parsed) ? parsed : [];
837
+ const out: ExtractedFact[] = [];
838
+ for (const item of facts) {
839
+ if (item === null || typeof item !== 'object') continue;
840
+ const obj = item as Record<string, unknown>;
841
+ const text = typeof obj.text === 'string' ? obj.text : null;
842
+ if (text === null || text.trim().length === 0) continue;
843
+ const fact: ExtractedFact = {
844
+ text,
845
+ ...(typeof obj.subject === 'string' ? { subject: obj.subject } : {}),
846
+ ...(typeof obj.predicate === 'string' ? { predicate: obj.predicate } : {}),
847
+ ...(typeof obj.object === 'string' ? { object: obj.object } : {}),
848
+ ...(typeof obj.confidence === 'number' ? { confidence: obj.confidence } : {}),
849
+ ...(typeof obj.importance === 'number' ? { importance: obj.importance } : {}),
850
+ };
851
+ out.push(fact);
852
+ }
853
+ return out;
854
+ }
855
+
856
+ /**
857
+ * Parse the episode-summary model output into `{ summary, importance? }`
858
+ * (P1-2). Tolerates fenced blocks + an optional `{ episode: {...} }`
859
+ * wrapper; returns `null` when no usable `summary` string is present
860
+ * (so an extraction-shaped `{ facts: [...] }` payload is rejected, not
861
+ * mistaken for an episode).
862
+ *
863
+ * @internal
864
+ */
865
+ export function parseEpisode(text: string | undefined): ExtractedEpisode | null {
866
+ if (text === undefined || text.length === 0) return null;
867
+ const candidate = stripFence(text).trim();
868
+ if (candidate.length === 0) return null;
869
+ let parsed: unknown;
870
+ try {
871
+ parsed = JSON.parse(candidate);
872
+ } catch {
873
+ const slice = sliceJsonObject(candidate);
874
+ if (slice === null) return null;
875
+ try {
876
+ parsed = JSON.parse(slice);
877
+ } catch {
878
+ return null;
879
+ }
880
+ }
881
+ if (parsed === null || typeof parsed !== 'object') return null;
882
+ const root = parsed as Record<string, unknown>;
883
+ const inner =
884
+ typeof root.summary === 'string'
885
+ ? root
886
+ : root.episode !== null && typeof root.episode === 'object'
887
+ ? (root.episode as Record<string, unknown>)
888
+ : root;
889
+ const summary = typeof inner.summary === 'string' ? inner.summary : null;
890
+ if (summary === null || summary.trim().length === 0) return null;
891
+ return {
892
+ summary,
893
+ ...(typeof inner.importance === 'number' ? { importance: inner.importance } : {}),
894
+ };
895
+ }
896
+
897
+ /**
898
+ * Normalize a raw `[1, 10]` poignancy score into the episodic
899
+ * `importance` field's `[0, 1]` range (P1-2). Out-of-range values are
900
+ * clamped to `[1, 10]` first (so `15 → 1.0`, `0 → 0.1`); non-finite /
901
+ * missing scores return `undefined` so the episode is recorded without
902
+ * an importance signal rather than a bogus one.
903
+ *
904
+ * @internal
905
+ */
906
+ export function normalizeImportance(raw: number | undefined): number | undefined {
907
+ if (typeof raw !== 'number' || !Number.isFinite(raw)) return undefined;
908
+ const clamped = Math.min(10, Math.max(1, raw));
909
+ return clamped / 10;
910
+ }
911
+
912
+ /**
913
+ * Build the {@link FactInput} for an extracted candidate. P1-4:
914
+ * distilled-from-transcript facts are synthesized memory - tagged
915
+ * `extraction` so they land quarantined (excluded from action-driving
916
+ * recall until validated).
917
+ */
918
+ /**
919
+ * Embedder-independent exact-duplicate lookup
920
+ * (memory-consolidation-07): FTS top hits + strict string equality.
921
+ * Returns the existing fact's id or `null`. Failures are swallowed -
922
+ * the guard is an optimization, never a reason to fail the slice.
923
+ */
924
+ async function findExactTextDuplicate(
925
+ semantic: SemanticMemory,
926
+ scope: SessionScope,
927
+ text: string,
928
+ ): Promise<string | null> {
929
+ try {
930
+ // Extraction output lands quarantined (P1-4) - the committed copy a
931
+ // replay would duplicate is exactly a quarantined row, so the guard
932
+ // must look past the retrieval gate.
933
+ const hits = await semantic.search(scope, text, { topK: 5, includeQuarantined: true });
934
+ return hits.find((h) => h.record.text === text)?.record.id ?? null;
935
+ } catch {
936
+ return null;
937
+ }
938
+ }
939
+
940
+ function buildFactInput(fact: ExtractedFact): FactInput {
941
+ // MCON-12: normalize the model's raw [1, 10] importance into the
942
+ // [0.1, 1.0] store scale (same contract as episodes); non-finite raw
943
+ // scores drop the signal rather than fabricating one.
944
+ const importance = normalizeImportance(fact.importance);
945
+ return {
946
+ text: fact.text,
947
+ provenance: 'extraction',
948
+ // D3: an extracted fact is the agent's own inference about the user.
949
+ owner: 'agent',
950
+ ...(fact.subject !== undefined ? { subject: fact.subject } : {}),
951
+ ...(fact.predicate !== undefined ? { predicate: fact.predicate } : {}),
952
+ ...(fact.object !== undefined ? { object: fact.object } : {}),
953
+ ...(fact.confidence !== undefined ? { confidence: fact.confidence } : {}),
954
+ ...(importance !== undefined ? { importance } : {}),
955
+ };
956
+ }
957
+
958
+ /**
959
+ * Record a reconcile / pre-filter decision into `fact_conflicts` so every
960
+ * write-path decision stays auditable (P0-3). Best-effort: a storage
961
+ * adapter without the conflict surface simply skips it.
962
+ */
963
+ async function recordConflictDecision(
964
+ store: MemoryStoreAdapter,
965
+ scope: SessionScope,
966
+ candidateId: string,
967
+ decision: ConflictDecision,
968
+ ): Promise<void> {
969
+ const conflicts = store.conflicts;
970
+ if (conflicts === undefined) return;
971
+ await conflicts.recordDecision({
972
+ scope,
973
+ candidateId,
974
+ decision: decision.kind,
975
+ stage: decision.stage,
976
+ ...(decision.kind === 'dedup' || decision.kind === 'supersede'
977
+ ? { existingId: decision.existingId }
978
+ : {}),
979
+ ...(decision.kind === 'dedup' && decision.similarity !== undefined
980
+ ? { similarity: decision.similarity }
981
+ : {}),
982
+ ...(decision.reason !== undefined ? { reason: decision.reason } : {}),
983
+ detectedBy: 'reconcile',
984
+ });
985
+ }
986
+
987
+ function emptyOutcome(status: PhaseOutcome['status']): PhaseOutcome {
988
+ return {
989
+ phase: 'standard',
990
+ status,
991
+ factsCreated: 0,
992
+ factsUpdated: 0,
993
+ conflictsResolved: 0,
994
+ episodesFormed: 0,
995
+ insightsCreated: 0,
996
+ noiseFilteredCount: 0,
997
+ emptyExtractions: 0,
998
+ llmTokensUsed: 0,
999
+ llmCostUsd: null,
1000
+ errorMessage: null,
1001
+ };
1002
+ }