@remnic/core 10.0.67 → 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.
@@ -1,5 +1,6 @@
1
1
  import { classifyExtractionOrigin, type ExtractionSourceContext } from "./extraction-origin-context.js";
2
2
  import { confirmActiveFactDuplicate, persistUnderFactDedupWindow } from "./fact-dedup-window.js";
3
+ import { writePromotionUnderFactDedupWindow } from "./promotion-dedup-window.js";
3
4
  import { evaluateInjectionScreen, screenEntityForIndex, screenPersistStrings } from "./extraction-injection-gate.js";
4
5
  /**
5
6
  * Extraction persistence coordinator (issue #1526, seam 16).
@@ -464,25 +465,26 @@ export class ExtractionPersistCoordinator {
464
465
  continue;
465
466
  }
466
467
  }
467
- // Sealed-envelope write (issue #1989 PR2): cross-cutting fields ride
468
- // the composed envelope (built above, before the dedup gate).
469
- const targetPromotion = await targetStorage.writeSealedMemory(targetPromotionEnvelope, {
470
- importance: options.importance,
471
- lineage: [options.sourceMemoryId],
472
- sourceMemoryId: options.sourceMemoryId,
473
- intentGoal: options.intentGoal,
474
- intentActionType: options.intentActionType,
475
- intentEntityTypes: options.intentEntityTypes,
476
- memoryKind: options.memoryKind,
477
- // #1578 — forward bi-temporal bounds + ingestion provenance.
478
- ...(options.invalidAt ? { invalidAt: options.invalidAt } : {}),
479
- ...(options.observedAt ? { observedAt: options.observedAt } : {}),
480
- ...(options.eventTimeSource ? { eventTimeSource: options.eventTimeSource } : {}),
481
- contentHashSource: options.category === "fact" ? dedupContent : rawContent,
482
- ...(options.sources && options.sources.length > 0 ? { sources: options.sources } : {}),
483
- ...(options.provenance ? { provenance: options.provenance } : {}),
484
- ...(options.toolScoped ? { toolScoped: true as const } : {}),
468
+ // Windowed destination write (PRRT_kwDORJXyws6zzdG4): the gate above
469
+ // ran outside the window; a twin committing meanwhile is suppressed
470
+ // by the in-window recheck. Contention throws fail-closed below.
471
+ const promotionWrite = await writePromotionUnderFactDedupWindow({
472
+ destination: targetStorage,
473
+ envelope: targetPromotionEnvelope,
474
+ promotion: options,
475
+ dedupContent,
476
+ rawContent,
477
+ toolScoped: options.toolScoped === true,
478
+ connector: sourceContext?.sourceConnector,
479
+ citationEnabled,
480
+ citationTemplate,
481
+ sameEntityGuardEnabled: false,
482
+ survivingAttrs: targetSurvivingAttrs,
483
+ supersession: { supersessionEnabled: lifecycleCaps.temporalSupersession, dependencyPropagationDelivery: this.dependencyPropagationDelivery, namespaceScope: this.deps.storageDirNamespace(targetStorage.dir) },
484
+ backfillTemporalBoundsOnDedupHit: this.deps.backfillTemporalBoundsOnDedupHit,
485
485
  });
486
+ if (promotionWrite.suppressed) continue;
487
+ const targetPromotion = promotionWrite.result;
486
488
  const promotedId = targetPromotion.id;
487
489
  // #1645: if the TARGET namespace's own tombstone blocked this promotion,
488
490
  // the row lands pending_review — do NOT supersede active target memories.
@@ -860,24 +862,27 @@ export class ExtractionPersistCoordinator {
860
862
  // No same-connector active shared fact — fall through to write.
861
863
  }
862
864
  }
863
- const sharedPromotion = await sharedStorage.writeSealedMemory(sharedPromotionEnvelope, {
864
- importance: options.importance,
865
- lineage: [options.sourceMemoryId],
866
- sourceMemoryId: options.sourceMemoryId,
867
- intentGoal: options.intentGoal,
868
- intentActionType: options.intentActionType,
869
- intentEntityTypes: options.intentEntityTypes,
870
- memoryKind: options.memoryKind,
871
- // #1578 — forward bi-temporal bounds + ingestion provenance.
872
- ...(options.invalidAt ? { invalidAt: options.invalidAt } : {}),
873
- ...(options.observedAt ? { observedAt: options.observedAt } : {}),
874
- ...(options.eventTimeSource ? { eventTimeSource: options.eventTimeSource } : {}),
875
- contentHashSource: options.category === "fact" ? dedupContent : rawContent,
876
- // Claim-level provenance spans (issue #1575 PR 2).
877
- ...(options.sources && options.sources.length > 0 ? { sources: options.sources } : {}),
878
- ...(options.provenance ? { provenance: options.provenance } : {}),
879
- ...(toolScoped ? { toolScoped: true as const } : {}),
865
+ // Windowed destination write (PRRT_kwDORJXyws6zzdG4): the shared gate
866
+ // ran outside the window; a twin committing meanwhile is suppressed by
867
+ // the in-window recheck; contention throws fail-closed to the outer
868
+ // catch. Supersession rides along for the suppressed branch.
869
+ const sharedWrite = await writePromotionUnderFactDedupWindow({
870
+ destination: sharedStorage,
871
+ envelope: sharedPromotionEnvelope,
872
+ promotion: options,
873
+ dedupContent,
874
+ rawContent,
875
+ toolScoped,
876
+ connector: sourceContext?.sourceConnector,
877
+ citationEnabled,
878
+ citationTemplate,
879
+ sameEntityGuardEnabled: lifecycleCaps.temporalSupersession,
880
+ survivingAttrs: sharedSurvivingAttrs,
881
+ supersession: { supersessionEnabled: lifecycleCaps.temporalSupersession, dependencyPropagationDelivery: this.dependencyPropagationDelivery, namespaceScope: this.deps.storageDirNamespace(sharedStorage.dir) },
882
+ backfillTemporalBoundsOnDedupHit: this.deps.backfillTemporalBoundsOnDedupHit,
880
883
  });
884
+ if (sharedWrite.suppressed) return promotedCopyId;
885
+ const sharedPromotion = sharedWrite.result;
881
886
  const promotedId = sharedPromotion.id;
882
887
  // #1645: if the shared namespace's own tombstone blocked this promotion,
883
888
  // leave the row pending_review but do NOT supersede active shared memories.
@@ -2581,8 +2586,8 @@ export class ExtractionPersistCoordinator {
2581
2586
  const factWriteOutcome = await persistUnderFactDedupWindow(
2582
2587
  targetStorage.dir,
2583
2588
  raceRecheck(targetStorage, contentHashDedupKey),
2584
- async () =>
2585
- targetStorage.writeSealedMemory(factWriteEnvelope, {
2589
+ async () => {
2590
+ const factWrite = await targetStorage.writeSealedMemory(factWriteEnvelope, {
2586
2591
  importance,
2587
2592
  supersedes,
2588
2593
  links: links.length > 0 ? links : undefined,
@@ -2605,7 +2610,22 @@ export class ExtractionPersistCoordinator {
2605
2610
  // must see this hash, or its recheck misses and duplicates it.
2606
2611
  deferHashIndexSave: false,
2607
2612
  ...(factToolScoped ? { toolScoped: true as const } : {}),
2608
- }),
2613
+ });
2614
+ // Register the dedup hash inside the same commit window: writeMemory
2615
+ // indexes facts only (rule 44 #1579), so non-fact categories
2616
+ // previously registered after the window released, letting a
2617
+ // concurrent session's in-window recheck miss and both write the
2618
+ // same content (issue #3312). Fail-open, like the post-write
2619
+ // registration this replaces.
2620
+ if (!factWrite.tombstoneBlocked) {
2621
+ try {
2622
+ await this.deps.addContentHashDedup(targetStorage, contentHashDedupKey);
2623
+ } catch (err) {
2624
+ log.warn(`content-hash dedup registration failed for memory ${factWrite.id}: ${err}`);
2625
+ }
2626
+ }
2627
+ return factWrite;
2628
+ },
2609
2629
  ).catch(finalizeOnWindowFailure);
2610
2630
  if (factWriteOutcome.suppressed) {
2611
2631
  // Codex P2: backfill bounds onto the window's winning copy first.
@@ -2800,29 +2820,6 @@ export class ExtractionPersistCoordinator {
2800
2820
  ...(factToolScoped ? { toolScoped: true as const } : {}),
2801
2821
  });
2802
2822
  }
2803
- // Register in the target storage content-hash index after successful
2804
- // write. Thread 3 fix: canonicalize by stripping any pre-existing
2805
- // citation so the stored hash matches what the dedup check computes.
2806
- try {
2807
- const canonicalFactContent =
2808
- citationEnabled &&
2809
- hasCitationForTemplate(fact.content, citationTemplate)
2810
- ? stripCitationForTemplate(fact.content, citationTemplate)
2811
- : fact.content;
2812
- const hashRegisterKey =
2813
- writeCategory === "procedure"
2814
- ? buildProcedurePersistBody(fact.content, fact.procedureSteps)
2815
- : canonicalFactContent;
2816
- // #1645: do NOT register a tombstone-blocked fact's content in the dedup
2817
- // index (rule 44 defeat) — see chunked path comment.
2818
- if (!tombstoneBlocked) {
2819
- await this.deps.addContentHashDedup(targetStorage, hashRegisterKey);
2820
- }
2821
- } catch (err) {
2822
- log.warn(
2823
- `content-hash dedup registration failed for memory ${memoryId}: ${err}`,
2824
- );
2825
- }
2826
2823
  } catch (err) {
2827
2824
  // PR #2016 / #3231: finalize deferred side effects for facts already
2828
2825
  // durable before propagating so hash/behavior/harmonic/temporal/QMD
@@ -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
+ }
@@ -87,3 +87,25 @@ test("an unowned forced outcome neither trips the half-open threshold nor settle
87
87
  breaker.success(probe.token);
88
88
  assert.deepEqual(breaker.acquire(6_500).suppressed, false, "owner success closes the breaker");
89
89
  });
90
+
91
+ test("an unowned auth_config failure does not reopen over a held probe", () => {
92
+ const breaker = new ProviderCircuitBreaker();
93
+ breaker.failure("provider_retryable", 1_000, CONFIG);
94
+ breaker.failure("provider_retryable", 1_050, CONFIG);
95
+ breaker.failure("provider_retryable", 1_100, CONFIG);
96
+ const probe = breaker.acquire(6_100);
97
+ assert.equal(probe.probe, true);
98
+
99
+ // A forced extraction reporting auth_config while the probe runs must not
100
+ // flip the breaker open over the still-held owner token (PRRT_kwDORJXyws6z07Mu).
101
+ breaker.failure("auth_config", 1_200, CONFIG);
102
+ assert.deepEqual(breaker.acquire(1_300), { suppressed: true, probe: false }, "probe stays held");
103
+
104
+ // The owner's own auth_config failure settles it with the auth cooldown.
105
+ breaker.failure("auth_config", 1_400, CONFIG, probe.token);
106
+ assert.deepEqual(breaker.acquire(1_500).suppressed, true, "owned auth_config failure reopens at once");
107
+ assert.deepEqual(breaker.acquire(60_000).suppressed, true, "auth cooldown still gates the next probe");
108
+ // The stranded-owner hazard: after the auth cooldown elapses, no SECOND
109
+ // probe may mint while the original owner is still held.
110
+ assert.deepEqual(breaker.acquire(60_001), { suppressed: true, probe: false }, "no second probe over a held one");
111
+ });