@remnic/core 10.0.68 → 10.0.69

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.
@@ -0,0 +1,319 @@
1
+ /**
2
+ * Promotion destination writes under the fact-dedup commit window (codex P2,
3
+ * PRRT_kwDORJXyws6zzdG4 / #3311). The persist-time promotion gates run
4
+ * OUTSIDE the window that serializes source writes, so with
5
+ * extractionQueueConcurrency > 1 two sessions promoting the same fact from
6
+ * different source namespaces can both gate-miss and both write the shared
7
+ * destination — duplicate active copies, because writeMemory mints a fresh id
8
+ * per write and does not coalesce active duplicates. This module wraps each
9
+ * promotion destination write in `persistUnderFactDedupWindow` keyed on the
10
+ * DESTINATION storage dir and rechecks with the same connector/content
11
+ * predicate the promotion gates confirm with, so a twin promotion committed
12
+ * between the gate and the write is suppressed instead of duplicated.
13
+ *
14
+ * Split out of extraction-persist.ts for the structural ratchet (#1995);
15
+ * behavior is a verbatim move of the wrapped writes the persist closure
16
+ * previously inlined.
17
+ */
18
+
19
+ import { ContentHashIndex, type StorageManager } from "../index.js";
20
+ import { log } from "../logger.js";
21
+ import type { ImportanceScore, MemoryFile, MemoryFrontmatter, ProvenanceSource } from "../types.js";
22
+ import type { SealedMemoryEnvelope } from "../write-envelope.js";
23
+ import type { SealedWriteExtras } from "../storage.js";
24
+ import { normalizeStoredHashSource } from "./extraction-persist-citation.js";
25
+ import { readActiveMemoriesBothTiers } from "./extraction-persist-promotion.js";
26
+ import { applyTemporalSupersession, normalizeSupersessionKey } from "../temporal-supersession.js";
27
+ import type { DependencyPropagationDeliveryPort } from "./dependency-propagation-delivery.js";
28
+ import { persistUnderFactDedupWindow, type FactDedupWindowOutcome } from "./fact-dedup-window.js";
29
+
30
+ /**
31
+ * The promotion fields the windowed write and its suppression-path bounds
32
+ * backfill read. Structurally satisfied by both promotion closures' options
33
+ * objects in extraction-persist.ts (profile-target and shared).
34
+ */
35
+ export interface PromotionDedupWriteFields {
36
+ category: string;
37
+ sourceMemoryId: string;
38
+ importance?: ImportanceScore;
39
+ intentGoal?: string;
40
+ intentActionType?: string;
41
+ intentEntityTypes?: string[];
42
+ memoryKind?: MemoryFrontmatter["memoryKind"];
43
+ validAt?: string;
44
+ invalidAt?: string;
45
+ observedAt?: string;
46
+ eventTimeSource?: "extracted" | "assumed";
47
+ sources?: ProvenanceSource[];
48
+ provenance?: "verified" | "unverified" | "none";
49
+ toolScoped?: true;
50
+ }
51
+
52
+ export interface PromotionDedupWriteArgs {
53
+ /** Promotion DESTINATION storage — the commit window is keyed on its dir. */
54
+ destination: StorageManager;
55
+ /** Composed sealed envelope for the promoted copy. */
56
+ envelope: SealedMemoryEnvelope;
57
+ /** The promotion closure's options (read structurally). */
58
+ promotion: PromotionDedupWriteFields;
59
+ /** Fact hash-key content (attrs-suffixed); pre-citation raw for others. */
60
+ dedupContent: string;
61
+ rawContent: string;
62
+ /** promotionWithholdsToolScope() result (shared) / forwarded marker (profile). */
63
+ toolScoped: boolean;
64
+ /** Raw source connector: trimmed for the recheck, raw for bounds backfill. */
65
+ connector: string | undefined;
66
+ citationEnabled: boolean;
67
+ citationTemplate: string;
68
+ /** lifecycleCaps.temporalSupersession on the shared path; false on the
69
+ * profile path (its gate predicate has no entity filter). When true AND the
70
+ * envelope carries an entityRef with non-empty surviving attrs, the recheck
71
+ * additionally requires the same entity (PR #402 Uybg guard parity). */
72
+ sameEntityGuardEnabled: boolean;
73
+ /** Envelope-surviving structured attributes (PR #402 Uybg guard input). */
74
+ survivingAttrs?: Record<string, string> | null;
75
+ /** When set, the suppression path runs the post-write supersession pass
76
+ * against the winning copy (PRRT_kwDORJXyws6z18qb): a suppressed
77
+ * later-dated promotion must still retire a conflicting shared fact dated
78
+ * between the events, mirroring the gate's hash-dedup-hit pass. */
79
+ supersession?: {
80
+ /** Caller's lifecycleCaps.temporalSupersession — without it the pass
81
+ * must not run even though the event-time `enabled` gate passes
82
+ * (PRRT_kwDORJXyws6z2o1t). */
83
+ supersessionEnabled: boolean;
84
+ dependencyPropagationDelivery?: DependencyPropagationDeliveryPort;
85
+ namespaceScope?: string;
86
+ };
87
+ backfillTemporalBoundsOnDedupHit: ExtractionPersistDeps["backfillTemporalBoundsOnDedupHit"];
88
+ }
89
+
90
+ type ExtractionPersistDeps = {
91
+ backfillTemporalBoundsOnDedupHit: (
92
+ targetStorage: StorageManager,
93
+ dedupContent: string,
94
+ bounds: {
95
+ invalidAt?: string;
96
+ validFrom?: string;
97
+ observedAt?: string;
98
+ eventTimeSource?: "extracted" | "assumed";
99
+ },
100
+ entityRef?: string,
101
+ sourceConnector?: string,
102
+ ) => Promise<void>;
103
+ };
104
+
105
+ /**
106
+ * Locate the active same-destination fact a raced promotion would duplicate:
107
+ * same connector/content predicate the promotion gates confirm with
108
+ * (`readActiveMemoriesBothTiers` + citation-aware stored normalization vs the
109
+ * normalized dedup key). The optional entity key mirrors the shared
110
+ * supersession branch's same-entity guard (PR #402 Uybg) so cross-entity
111
+ * same-content facts stay distinct. Returns undefined on scan error — an
112
+ * unverifiable state never suppresses (fail-open).
113
+ */
114
+ async function findPromotionRaceDuplicate(args: {
115
+ storage: StorageManager;
116
+ dedupContent: string;
117
+ category: string;
118
+ connector: string | undefined;
119
+ citationEnabled: boolean;
120
+ citationTemplate: string;
121
+ entityKeyNorm?: string;
122
+ }): Promise<MemoryFile | undefined> {
123
+ try {
124
+ const allMems = await readActiveMemoriesBothTiers(args.storage);
125
+ const nc = args.connector?.trim() || undefined;
126
+ const incomingNormalized = ContentHashIndex.normalizeContent(args.dedupContent);
127
+ return allMems.find((m: MemoryFile) => {
128
+ if (m.frontmatter.category !== args.category) return false;
129
+ if ((m.frontmatter.status ?? "active") !== "active") return false;
130
+ if (
131
+ normalizeStoredHashSource(m.content ?? "", args.citationEnabled, args.citationTemplate) !==
132
+ incomingNormalized
133
+ )
134
+ return false;
135
+ if (args.entityKeyNorm !== undefined) {
136
+ if (!m.frontmatter.entityRef) return false;
137
+ if (normalizeSupersessionKey(m.frontmatter.entityRef) !== args.entityKeyNorm) return false;
138
+ }
139
+ return (m.frontmatter.sourceConnector?.trim() || undefined) === nc;
140
+ });
141
+ } catch (err) {
142
+ log.warn(
143
+ `promotion race recheck scan failed for ${args.storage.dir}; writing fail-open: ${err instanceof Error ? err.message : String(err)}`,
144
+ );
145
+ return undefined;
146
+ }
147
+ }
148
+
149
+ /**
150
+ * In-window race confirm for a promotion destination. Authoritative index +
151
+ * miss is a clean NOT-duplicate answered WITHOUT the corpus scan, mirroring
152
+ * `confirmActiveFactDuplicate` and the window contract (one corpus confirm +
153
+ * one write, not a scan-length lock) — PRRT_kwDORJXyws6z18qS. On a hit, a
154
+ * non-authoritative index, or a probe failure, confirm against the corpus
155
+ * with the gates' predicate.
156
+ */
157
+ export async function confirmPromotionRaceDuplicate(args: {
158
+ storage: StorageManager;
159
+ dedupContent: string;
160
+ category: string;
161
+ connector: string | undefined;
162
+ citationEnabled: boolean;
163
+ citationTemplate: string;
164
+ entityKeyNorm?: string;
165
+ }): Promise<boolean> {
166
+ try {
167
+ if (await args.storage.isFactContentHashAuthoritative()) {
168
+ if (!(await args.storage.hasFactContentHash(args.dedupContent))) return false;
169
+ }
170
+ } catch (probeErr) {
171
+ log.warn(
172
+ `promotion race recheck authoritative probe failed for ${args.storage.dir}; confirming against corpus: ${probeErr instanceof Error ? probeErr.message : String(probeErr)}`,
173
+ );
174
+ }
175
+ return (await findPromotionRaceDuplicate(args)) !== undefined;
176
+ }
177
+
178
+ /**
179
+ * Presence-iff-set extras, byte-equivalent to the conditional spreads the
180
+ * persist closure previously inlined at both promotion call sites.
181
+ */
182
+ function buildPromotionWriteOptions(args: PromotionDedupWriteArgs): SealedWriteExtras {
183
+ const { promotion } = args;
184
+ const writeOptions: SealedWriteExtras = {
185
+ importance: promotion.importance,
186
+ lineage: [promotion.sourceMemoryId],
187
+ sourceMemoryId: promotion.sourceMemoryId,
188
+ intentGoal: promotion.intentGoal,
189
+ intentActionType: promotion.intentActionType,
190
+ intentEntityTypes: promotion.intentEntityTypes,
191
+ memoryKind: promotion.memoryKind,
192
+ contentHashSource: promotion.category === "fact" ? args.dedupContent : args.rawContent,
193
+ };
194
+ if (promotion.invalidAt) writeOptions.invalidAt = promotion.invalidAt;
195
+ // #1578 — forward bi-temporal bounds + ingestion provenance.
196
+ if (promotion.observedAt) writeOptions.observedAt = promotion.observedAt;
197
+ if (promotion.eventTimeSource) writeOptions.eventTimeSource = promotion.eventTimeSource;
198
+ if (promotion.sources && promotion.sources.length > 0) writeOptions.sources = promotion.sources;
199
+ if (promotion.provenance) writeOptions.provenance = promotion.provenance;
200
+ if (args.toolScoped) writeOptions.toolScoped = true;
201
+ return writeOptions;
202
+ }
203
+
204
+ /**
205
+ * Run one promotion destination write inside the destination-dir fact-dedup
206
+ * commit window: recheck (facts only; the same confirm the persist-time gate
207
+ * used, now under the lock) and suppress as a duplicate when a concurrent
208
+ * promotion committed the same content first. A suppressed promotion backfills
209
+ * temporal bounds onto the winning copy (#1671 parity with the gates' skip
210
+ * paths) and reports `{ suppressed: true }`. Lock contention throws
211
+ * fail-closed to the caller — never an unlocked write; the durable source
212
+ * fact is unaffected.
213
+ */
214
+ export async function writePromotionUnderFactDedupWindow(
215
+ args: PromotionDedupWriteArgs,
216
+ ): Promise<FactDedupWindowOutcome<Awaited<ReturnType<StorageManager["writeSealedMemory"]>>>> {
217
+ const { destination, envelope, promotion } = args;
218
+ // PRRT_kwDORJXyws6z2WsK: the recheck is fact-only, so for other categories
219
+ // the window would add lock acquisition and fail-closed throw risk with no
220
+ // dedup value. Write directly with the same extras.
221
+ if (promotion.category !== "fact") {
222
+ return {
223
+ suppressed: false,
224
+ result: await destination.writeSealedMemory(envelope, buildPromotionWriteOptions(args)),
225
+ };
226
+ }
227
+ const entityKeyNorm =
228
+ args.sameEntityGuardEnabled &&
229
+ envelope.entityRef &&
230
+ args.survivingAttrs &&
231
+ Object.keys(args.survivingAttrs).length > 0
232
+ ? normalizeSupersessionKey(envelope.entityRef)
233
+ : undefined;
234
+ const outcome = await persistUnderFactDedupWindow(
235
+ destination.dir,
236
+ () =>
237
+ promotion.category === "fact"
238
+ ? confirmPromotionRaceDuplicate({
239
+ storage: destination,
240
+ dedupContent: args.dedupContent,
241
+ category: promotion.category,
242
+ connector: args.connector,
243
+ citationEnabled: args.citationEnabled,
244
+ citationTemplate: args.citationTemplate,
245
+ entityKeyNorm,
246
+ })
247
+ : Promise.resolve(false),
248
+ () => destination.writeSealedMemory(envelope, buildPromotionWriteOptions(args)),
249
+ );
250
+ if (outcome.suppressed) {
251
+ log.info(`dedup: raced promotion duplicate suppressed in fact-dedup window for ${destination.dir}`);
252
+ if (promotion.invalidAt || promotion.validAt) {
253
+ await args.backfillTemporalBoundsOnDedupHit(
254
+ destination,
255
+ args.dedupContent,
256
+ {
257
+ invalidAt: promotion.invalidAt,
258
+ // #1707 thread 2 — carry the corrected start bound.
259
+ validFrom: promotion.validAt,
260
+ observedAt: promotion.observedAt,
261
+ eventTimeSource: promotion.eventTimeSource,
262
+ },
263
+ envelope.entityRef,
264
+ args.connector,
265
+ );
266
+ }
267
+ // PRRT_kwDORJXyws6z18qb: the unsuppressed path runs temporal supersession
268
+ // after the write; the suppressed promotion must too, or a later-dated
269
+ // raced promotion leaves a conflicting shared fact dated between the
270
+ // events active. Anchor to the winning copy with useCallerTimestamp —
271
+ // the gate's hash-dedup-hit shape (PR #402 Uyui/UvU1) — and fail open.
272
+ if (
273
+ args.supersession?.supersessionEnabled &&
274
+ promotion.category === "fact" &&
275
+ envelope.entityRef &&
276
+ args.survivingAttrs &&
277
+ Object.keys(args.survivingAttrs).length > 0
278
+ ) {
279
+ try {
280
+ const winning = await findPromotionRaceDuplicate({
281
+ storage: destination,
282
+ dedupContent: args.dedupContent,
283
+ category: promotion.category,
284
+ connector: args.connector,
285
+ citationEnabled: args.citationEnabled,
286
+ citationTemplate: args.citationTemplate,
287
+ // PRRT_kwDORJXyws6z2o11: the winner ANCHORS the pass, so the lookup
288
+ // is always entity-guarded — without it (profile path) it could
289
+ // match another entity's equal-content fact and combine that fact's
290
+ // id with the incoming entity's attributes (PR #402 Uybg hazard).
291
+ entityKeyNorm: normalizeSupersessionKey(envelope.entityRef),
292
+ });
293
+ if (winning) {
294
+ await applyTemporalSupersession({
295
+ storage: destination,
296
+ newMemoryId: winning.frontmatter.id,
297
+ entityRef: envelope.entityRef,
298
+ structuredAttributes: { ...args.survivingAttrs },
299
+ // Ordering anchor mirrors the gate's supersessionOrderingAt: an
300
+ // incoming event date orders the pass, wall clock otherwise.
301
+ createdAt:
302
+ promotion.validAt && promotion.validAt.length > 0
303
+ ? promotion.validAt
304
+ : new Date().toISOString(),
305
+ useCallerTimestamp: true,
306
+ enabled: !(promotion.eventTimeSource === "extracted" && !promotion.validAt),
307
+ namespaceScope: args.supersession.namespaceScope,
308
+ dependencyPropagationDelivery: args.supersession.dependencyPropagationDelivery,
309
+ });
310
+ }
311
+ } catch (supersessionErr) {
312
+ log.warn(
313
+ `promotion window supersession failed open for ${destination.dir}: ${supersessionErr instanceof Error ? supersessionErr.message : String(supersessionErr)}`,
314
+ );
315
+ }
316
+ }
317
+ }
318
+ return outcome;
319
+ }