@equationalapplications/core-llm-wiki 9.15.0 → 9.16.1

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.
package/dist/index.js CHANGED
@@ -351,11 +351,14 @@ var SEVERITY = {
351
351
  event_created_at_clamped: "warn",
352
352
  event_created_at_restamped: "info",
353
353
  external_deletion_pending: "warn",
354
+ supersede_scheduled_end_replaced: "info",
354
355
  external_deletion_discarded: "warn",
355
356
  guidance_too_long: "warn",
356
357
  guidance_resolver_failed: "warn",
357
358
  source_pointer_unresolved: "warn",
358
359
  source_pointer_invalid: "warn",
360
+ source_event_gone: "warn",
361
+ derived_events_invalid: "warn",
359
362
  source_store_source_too_large: "warn",
360
363
  source_store_budget_exceeded: "warn",
361
364
  source_store_hash_mismatch: "warn",
@@ -407,12 +410,15 @@ var MESSAGE = {
407
410
  import_tombstone_skipped: "Import skipped live dump rows (facts and tasks) whose ids were forgotten locally. The protection holds while the tombstone is retained; once a prune hard-deletes the row, an old dump can import the fact again \u2014 see the OKF guide\u2019s restore caveat.",
408
411
  event_created_at_clamped: "Imported events dated in the future were re-dated just after the current time, or after the librarian position if that is later, keeping their order.",
409
412
  event_created_at_restamped: "Imported events that would have sorted behind the librarian position, or had an unusable date, were adjusted: an affected created_at was re-dated just after the current time, or after the librarian position if that is later, keeping their order; an unusable occurred_at was cleared.",
413
+ supersede_scheduled_end_replaced: "A supersede replaced a scheduled end date on the old fact; the prior end is kept in prior_valid_to and reopen() can restore it.",
410
414
  external_deletion_pending: "Removals owed to the external vector index are still pending.",
411
415
  external_deletion_discarded: "Pending external vector removals were discarded because forceDeleteIgnoreRankerHook is set.",
412
416
  guidance_too_long: "The configured guidance exceeded the length cap and was not sent for this pass.",
413
417
  guidance_resolver_failed: "The per-entity guidance resolver failed; its value was not used for this pass.",
414
- source_pointer_unresolved: "A stored librarian fact carries no source pointer because the model answer could not yield one.",
418
+ source_pointer_unresolved: "A stored librarian fact carries no source pointer because the model answer could not yield one, or the librarian merged such an unattributed candidate into this fact in place (its derived_events list was not extended).",
415
419
  source_pointer_invalid: "Import met a malformed source pointer value and stored a null pointer.",
420
+ source_event_gone: "A librarian candidate was dropped at apply time because the event it came from no longer exists (deleted outside the engine while the pass ran).",
421
+ derived_events_invalid: "Import met a malformed derived_events value and stored null.",
416
422
  source_store_source_too_large: "A source document exceeded the per-document size cap and was not stored.",
417
423
  source_store_budget_exceeded: "Storing a source document would exceed the store UTF-16 code-unit budget and it was not stored.",
418
424
  source_store_hash_mismatch: "A source document text did not match its recorded hash and was not stored.",
@@ -1960,7 +1966,9 @@ async function setupDatabase(db, prefix) {
1960
1966
  valid_to INTEGER,
1961
1967
  superseded_by TEXT,
1962
1968
  superseded_at INTEGER,
1963
- source_pointer TEXT
1969
+ prior_valid_to INTEGER,
1970
+ source_pointer TEXT,
1971
+ derived_events TEXT
1964
1972
  );
1965
1973
 
1966
1974
  CREATE INDEX IF NOT EXISTS ${prefix}entries_entity_idx ON ${prefix}entries(entity_id);
@@ -2744,8 +2752,34 @@ var MIGRATIONS = [
2744
2752
  );`
2745
2753
  );
2746
2754
  }
2755
+ },
2756
+ {
2757
+ version: 18,
2758
+ description: "Partial index on entries(entity_id, deleted_at) for prune and tombstone probes; nullable prior_valid_to column recording the scheduled end a supersede overwrote; nullable derived_events column listing the events an in-place librarian merge drew on",
2759
+ run: async (db, prefix) => {
2760
+ await createEntriesDeletedIndex(db, prefix);
2761
+ await addPriorValidToColumn(db, prefix);
2762
+ await addDerivedEventsColumn(db, prefix);
2763
+ }
2747
2764
  }
2748
2765
  ];
2766
+ async function addPriorValidToColumn(db, prefix) {
2767
+ const cols = await db.getAllAsync(`PRAGMA table_info(${prefix}entries)`);
2768
+ if (!cols.some((c) => c.name === "prior_valid_to")) {
2769
+ await db.execAsync(`ALTER TABLE ${prefix}entries ADD COLUMN prior_valid_to INTEGER`);
2770
+ }
2771
+ }
2772
+ async function createEntriesDeletedIndex(db, prefix) {
2773
+ await db.execAsync(
2774
+ `CREATE INDEX IF NOT EXISTS ${prefix}entries_deleted_idx ON ${prefix}entries(entity_id, deleted_at) WHERE deleted_at IS NOT NULL`
2775
+ );
2776
+ }
2777
+ async function addDerivedEventsColumn(db, prefix) {
2778
+ const cols = await db.getAllAsync(`PRAGMA table_info(${prefix}entries)`);
2779
+ if (!cols.some((c) => c.name === "derived_events")) {
2780
+ await db.execAsync(`ALTER TABLE ${prefix}entries ADD COLUMN derived_events TEXT`);
2781
+ }
2782
+ }
2749
2783
  async function createLegacySourceTypeIndex(db, prefix) {
2750
2784
  await db.execAsync(
2751
2785
  `CREATE INDEX IF NOT EXISTS ${prefix}entries_legacy_source_type_idx ON ${prefix}entries(source_type) WHERE source_type IN ('user_document', 'agent_inferred')`
@@ -3038,6 +3072,43 @@ function serializeSourcePointer(p) {
3038
3072
  return p ? JSON.stringify(p) : null;
3039
3073
  }
3040
3074
 
3075
+ // src/utils/derivedEvents.ts
3076
+ function validateDerivedEventsValue(v) {
3077
+ if (v === null) return null;
3078
+ if (!Array.isArray(v)) return void 0;
3079
+ for (const x of v) {
3080
+ if (typeof x !== "string" || x.length === 0) return void 0;
3081
+ }
3082
+ const out = dedupeEventIds(v);
3083
+ return out.length === 0 ? null : out;
3084
+ }
3085
+ function parseStoredDerivedEvents(raw) {
3086
+ if (typeof raw !== "string") return null;
3087
+ let parsed;
3088
+ try {
3089
+ parsed = JSON.parse(raw);
3090
+ } catch {
3091
+ return null;
3092
+ }
3093
+ if (!Array.isArray(parsed)) return null;
3094
+ const kept = dedupeEventIds(parsed.filter((x) => typeof x === "string"));
3095
+ return kept.length === 0 ? null : kept;
3096
+ }
3097
+ function serializeDerivedEvents(list) {
3098
+ if (!list || list.length === 0) return null;
3099
+ return JSON.stringify(list);
3100
+ }
3101
+ function dedupeEventIds(ids) {
3102
+ const seen = /* @__PURE__ */ new Set();
3103
+ const out = [];
3104
+ for (const id of ids) {
3105
+ if (typeof id !== "string" || id.length === 0 || seen.has(id)) continue;
3106
+ seen.add(id);
3107
+ out.push(id);
3108
+ }
3109
+ return out;
3110
+ }
3111
+
3041
3112
  // src/repositories/EntryRepository.ts
3042
3113
  function mapRowToFact(row) {
3043
3114
  const tags = (() => {
@@ -3053,6 +3124,7 @@ function mapRowToFact(row) {
3053
3124
  const now = Date.now();
3054
3125
  const staleAfterRaw = row.stale_after != null ? Number(row.stale_after) : null;
3055
3126
  const sourcePointer = parseStoredSourcePointer(row.source_pointer);
3127
+ const derivedEvents = parseStoredDerivedEvents(row.derived_events);
3056
3128
  const mapped = {
3057
3129
  id: row.id,
3058
3130
  entity_id: row.entity_id,
@@ -3087,10 +3159,14 @@ function mapRowToFact(row) {
3087
3159
  ...row.valid_to != null ? { valid_to: Number(row.valid_to) } : {},
3088
3160
  ...row.superseded_by != null ? { superseded_by: String(row.superseded_by) } : {},
3089
3161
  ...row.superseded_at != null ? { superseded_at: Number(row.superseded_at) } : {},
3162
+ ...row.prior_valid_to != null ? { prior_valid_to: Number(row.prior_valid_to) } : {},
3090
3163
  // Source pointer (specs/source-pointers): key appears only when non-null,
3091
3164
  // same temporal-fields pattern. Tolerant read: a malformed stored value
3092
3165
  // reads as null without throwing (test 1).
3093
- ...sourcePointer ? { source_pointer: sourcePointer } : {}
3166
+ ...sourcePointer ? { source_pointer: sourcePointer } : {},
3167
+ // derived_events (specs/inplace-update-provenance §5): present only when
3168
+ // non-empty; a malformed stored value reads as absent without throwing.
3169
+ ...derivedEvents ? { derived_events: derivedEvents } : {}
3094
3170
  };
3095
3171
  return mapped;
3096
3172
  }
@@ -3207,7 +3283,7 @@ var _EntryRepository = class _EntryRepository extends BaseRepository {
3207
3283
  const existingRow = await executor.getFirstAsync(
3208
3284
  `SELECT id, entity_id, lifecycle_status, stale_after, generated_by,
3209
3285
  okf_sources, okf_verified, okf_usage_window,
3210
- last_verified_at, last_verified_by, source_pointer
3286
+ last_verified_at, last_verified_by, source_pointer, derived_events
3211
3287
  FROM ${this.prefix}entries WHERE id = ?`,
3212
3288
  [fact.id]
3213
3289
  );
@@ -3221,8 +3297,8 @@ var _EntryRepository = class _EntryRepository extends BaseRepository {
3221
3297
  source_hash, source_ref, created_at, updated_at, last_accessed_at, access_count,
3222
3298
  deleted_at, embedding_blob, embedding, okf_type,
3223
3299
  lifecycle_status, stale_after, generated_by, last_verified_at, last_verified_by,
3224
- okf_sources, okf_verified, okf_usage_window, source_pointer
3225
- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
3300
+ okf_sources, okf_verified, okf_usage_window, source_pointer, derived_events
3301
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
3226
3302
  ON CONFLICT(id) DO UPDATE SET
3227
3303
  title = excluded.title,
3228
3304
  body = excluded.body,
@@ -3240,7 +3316,8 @@ var _EntryRepository = class _EntryRepository extends BaseRepository {
3240
3316
  embedding_failed_at = CASE WHEN excluded.embedding_blob IS NOT NULL THEN NULL ELSE embedding_failed_at END,
3241
3317
  embedding_failure_kind = CASE WHEN excluded.embedding_blob IS NOT NULL THEN NULL ELSE embedding_failure_kind END,
3242
3318
  embedding_attempts = CASE WHEN excluded.embedding_blob IS NOT NULL THEN 0 ELSE embedding_attempts END,
3243
- okf_type = excluded.okf_type
3319
+ okf_type = excluded.okf_type,
3320
+ derived_events = CASE WHEN ? THEN excluded.derived_events ELSE derived_events END
3244
3321
  WHERE ${this.prefix}entries.entity_id = excluded.entity_id`,
3245
3322
  [
3246
3323
  fact.id,
@@ -3271,7 +3348,12 @@ var _EntryRepository = class _EntryRepository extends BaseRepository {
3271
3348
  fact.okf_sources ? JSON.stringify(fact.okf_sources) : null,
3272
3349
  fact.okf_verified ? JSON.stringify(fact.okf_verified) : null,
3273
3350
  fact.okf_usage_window ? JSON.stringify(fact.okf_usage_window) : null,
3274
- serializeSourcePointer(fact.source_pointer)
3351
+ serializeSourcePointer(fact.source_pointer),
3352
+ serializeDerivedEvents(fact.derived_events),
3353
+ // derived_events is writable on conflict (the librarian's in-place
3354
+ // UPDATE merges events into it), but only when the caller supplied the
3355
+ // key: an undefined key leaves a stored list untouched.
3356
+ fact.derived_events !== void 0 ? 1 : 0
3275
3357
  ]
3276
3358
  );
3277
3359
  if (result.changes === 0) {
@@ -3295,7 +3377,11 @@ var _EntryRepository = class _EntryRepository extends BaseRepository {
3295
3377
  okf_usage_window: parseJsonObject(existingRow.okf_usage_window),
3296
3378
  last_verified_at: existingRow.last_verified_at != null ? Number(existingRow.last_verified_at) : null,
3297
3379
  last_verified_by: existingRow.last_verified_by ?? null,
3298
- source_pointer: parseStoredSourcePointer(existingRow.source_pointer)
3380
+ source_pointer: parseStoredSourcePointer(existingRow.source_pointer),
3381
+ ...fact.derived_events === void 0 ? (() => {
3382
+ const stored = parseStoredDerivedEvents(existingRow.derived_events);
3383
+ return stored ? { derived_events: stored } : {};
3384
+ })() : {}
3299
3385
  } : null;
3300
3386
  await this.outbox.push({
3301
3387
  entityId: fact.entity_id,
@@ -3360,7 +3446,7 @@ var _EntryRepository = class _EntryRepository extends BaseRepository {
3360
3446
  const rows = await executor.getAllAsync(sql, args);
3361
3447
  return rows.map((row) => row.id);
3362
3448
  }
3363
- async upsertForImport(fact, tx, sourcePointerPresent = false) {
3449
+ async upsertForImport(fact, tx, sourcePointerPresent = false, derivedEventsPresent = false) {
3364
3450
  const executor = this.getExecutor(tx);
3365
3451
  const tagsJson = JSON.stringify(fact.tags);
3366
3452
  const embeddingBlob = this.normalizeEmbeddingBlob(fact.embedding_blob);
@@ -3370,8 +3456,8 @@ var _EntryRepository = class _EntryRepository extends BaseRepository {
3370
3456
  source_hash, source_ref, created_at, updated_at, last_accessed_at, access_count,
3371
3457
  deleted_at, embedding_blob, embedding, okf_type,
3372
3458
  lifecycle_status, stale_after, generated_by, last_verified_at, last_verified_by,
3373
- okf_sources, okf_verified, okf_usage_window, source_pointer
3374
- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
3459
+ okf_sources, okf_verified, okf_usage_window, source_pointer, derived_events
3460
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
3375
3461
  ON CONFLICT(id) DO UPDATE SET
3376
3462
  entity_id = excluded.entity_id,
3377
3463
  title = excluded.title,
@@ -3400,7 +3486,8 @@ var _EntryRepository = class _EntryRepository extends BaseRepository {
3400
3486
  okf_sources = excluded.okf_sources,
3401
3487
  okf_verified = excluded.okf_verified,
3402
3488
  okf_usage_window = excluded.okf_usage_window,
3403
- source_pointer = CASE WHEN ? THEN excluded.source_pointer ELSE source_pointer END`,
3489
+ source_pointer = CASE WHEN ? THEN excluded.source_pointer ELSE source_pointer END,
3490
+ derived_events = CASE WHEN ? THEN excluded.derived_events ELSE derived_events END`,
3404
3491
  [
3405
3492
  fact.id,
3406
3493
  fact.entity_id,
@@ -3429,9 +3516,13 @@ var _EntryRepository = class _EntryRepository extends BaseRepository {
3429
3516
  fact.okf_verified ? JSON.stringify(fact.okf_verified) : null,
3430
3517
  fact.okf_usage_window ? JSON.stringify(fact.okf_usage_window) : null,
3431
3518
  serializeSourcePointer(fact.source_pointer),
3519
+ serializeDerivedEvents(fact.derived_events),
3432
3520
  // The presence flag binds to the SET clause's CASE, AFTER the INSERT
3433
3521
  // values above.
3434
- sourcePointerPresent ? 1 : 0
3522
+ sourcePointerPresent ? 1 : 0,
3523
+ // derived_events follows the same presence-flag pattern: a pre-v18
3524
+ // dump (no key) never nulls a stored list.
3525
+ derivedEventsPresent ? 1 : 0
3435
3526
  ]
3436
3527
  );
3437
3528
  return result;
@@ -3498,15 +3589,19 @@ var _EntryRepository = class _EntryRepository extends BaseRepository {
3498
3589
  }
3499
3590
  return result.changes;
3500
3591
  }
3592
+ /** Bind values for `EVENT_MATCH_SQL` after an `entity_id = ?` term: the event id twice. */
3593
+ static eventMatchArgs(entityId, eventId) {
3594
+ return [entityId, eventId, eventId];
3595
+ }
3501
3596
  /**
3502
- * IDs of the entity's entries whose source_pointer names the event id.
3597
+ * IDs of the entity's entries whose source_pointer names the event id or whose derived_events list contains it.
3503
3598
  * `includeDeleted = true` returns live + tombstoned rows (the forget
3504
3599
  * enumeration superset for index sync and the ledger backstop).
3505
3600
  */
3506
3601
  async findIdsByPointerEvent(entityId, eventId, tx, includeDeleted = false) {
3507
3602
  const executor = this.getExecutor(tx);
3508
3603
  let sql = `SELECT id FROM ${this.prefix}entries WHERE entity_id = ? AND ${_EntryRepository.POINTER_EVENT_MATCH_SQL}`;
3509
- const args = [entityId, eventId];
3604
+ const args = _EntryRepository.eventMatchArgs(entityId, eventId);
3510
3605
  if (!includeDeleted) sql += ` AND deleted_at IS NULL`;
3511
3606
  const rows = await executor.getAllAsync(sql, args);
3512
3607
  return rows.map((r) => r.id);
@@ -3516,7 +3611,7 @@ var _EntryRepository = class _EntryRepository extends BaseRepository {
3516
3611
  const executor = this.getExecutor(tx);
3517
3612
  const row = await executor.getFirstAsync(
3518
3613
  `SELECT COUNT(*) AS n FROM ${this.prefix}entries WHERE entity_id = ? AND deleted_at IS NULL AND ${_EntryRepository.POINTER_EVENT_MATCH_SQL}`,
3519
- [entityId, eventId]
3614
+ _EntryRepository.eventMatchArgs(entityId, eventId)
3520
3615
  );
3521
3616
  return row?.n ?? 0;
3522
3617
  }
@@ -3534,11 +3629,11 @@ var _EntryRepository = class _EntryRepository extends BaseRepository {
3534
3629
  const now = Date.now();
3535
3630
  const idsToDelete = await executor.getAllAsync(
3536
3631
  `SELECT id FROM ${this.prefix}entries WHERE entity_id = ? AND deleted_at IS NULL AND ${_EntryRepository.POINTER_EVENT_MATCH_SQL}`,
3537
- [entityId, eventId]
3632
+ _EntryRepository.eventMatchArgs(entityId, eventId)
3538
3633
  );
3539
3634
  const result = await executor.runAsync(
3540
3635
  `UPDATE ${this.prefix}entries SET deleted_at = ?, updated_at = ? WHERE entity_id = ? AND deleted_at IS NULL AND ${_EntryRepository.POINTER_EVENT_MATCH_SQL}`,
3541
- [now, now, entityId, eventId]
3636
+ [now, now, ..._EntryRepository.eventMatchArgs(entityId, eventId)]
3542
3637
  );
3543
3638
  for (const row of idsToDelete) {
3544
3639
  await this.outbox.push({
@@ -3858,9 +3953,9 @@ var _EntryRepository = class _EntryRepository extends BaseRepository {
3858
3953
  }, tx);
3859
3954
  }
3860
3955
  }
3861
- /** Spec §4: write any subset of the four temporal columns. Absent key = untouched; null = clear. */
3956
+ /** Spec §4: write any subset of the five temporal columns. Absent key = untouched; null = clear. */
3862
3957
  async setTemporal(id, entityId, fields, tx, opts) {
3863
- const keys = ["valid_from", "valid_to", "superseded_by", "superseded_at"].filter((k) => k in fields);
3958
+ const keys = ["valid_from", "valid_to", "superseded_by", "superseded_at", "prior_valid_to"].filter((k) => k in fields);
3864
3959
  if (keys.length === 0) return 0;
3865
3960
  const executor = this.getExecutor(tx);
3866
3961
  const result = await executor.runAsync(
@@ -3877,7 +3972,7 @@ var _EntryRepository = class _EntryRepository extends BaseRepository {
3877
3972
  async findTemporalRow(id, tx) {
3878
3973
  const executor = this.getExecutor(tx);
3879
3974
  const row = await executor.getFirstAsync(
3880
- `SELECT id, entity_id, source_type, deleted_at, created_at, valid_from, valid_to, superseded_by
3975
+ `SELECT id, entity_id, source_type, deleted_at, created_at, valid_from, valid_to, superseded_by, prior_valid_to
3881
3976
  FROM ${this.prefix}entries WHERE id = ?`,
3882
3977
  [id]
3883
3978
  );
@@ -3890,7 +3985,8 @@ var _EntryRepository = class _EntryRepository extends BaseRepository {
3890
3985
  created_at: Number(row.created_at),
3891
3986
  valid_from: row.valid_from != null ? Number(row.valid_from) : null,
3892
3987
  valid_to: row.valid_to != null ? Number(row.valid_to) : null,
3893
- superseded_by: row.superseded_by != null ? String(row.superseded_by) : null
3988
+ superseded_by: row.superseded_by != null ? String(row.superseded_by) : null,
3989
+ prior_valid_to: row.prior_valid_to != null ? Number(row.prior_valid_to) : null
3894
3990
  };
3895
3991
  }
3896
3992
  /**
@@ -4595,17 +4691,30 @@ var _EntryRepository = class _EntryRepository extends BaseRepository {
4595
4691
  _EntryRepository.MINI_SEARCH_COLUMNS = "id, entity_id, title, body, tags";
4596
4692
  _EntryRepository.MINI_SEARCH_LIVE_WHERE = "WHERE deleted_at IS NULL";
4597
4693
  /**
4598
- * Shared JSON match predicate for source_pointer event ids
4599
- * (specs/forget-by-event-id §D1). Every JSON call sits under the single
4694
+ * Shared JSON match predicate for an event id
4695
+ * (specs/forget-by-event-id §D1, widened by specs/inplace-update-provenance
4696
+ * §4): a row matches when its `source_pointer` names the event OR its
4697
+ * `derived_events` list contains it. Every JSON call sits under its own
4600
4698
  * `json_valid` guard: unguarded JSON functions RAISE on malformed text, and
4601
4699
  * three-valued logic forces evaluation of AND operands after a NULL-guarded
4602
4700
  * term — a two-term form is only as safe as the planner's term-splitting.
4701
+ * The `json_each` term additionally requires `json_type = 'array'` (a JSON
4702
+ * object or scalar would otherwise iterate its members). The event id binds
4703
+ * TWICE (pointer term, then derived_events term); use `eventMatchArgs`.
4603
4704
  * The tombstone guard (`deleted_at IS NULL`) is added per-method.
4604
4705
  */
4605
- _EntryRepository.POINTER_EVENT_MATCH_SQL = `CASE WHEN json_valid(source_pointer)
4706
+ _EntryRepository.EVENT_MATCH_SQL = `((CASE WHEN json_valid(source_pointer)
4606
4707
  THEN json_type(source_pointer, '$.event_id') = 'text'
4607
4708
  AND json_extract(source_pointer, '$.event_id') = ?
4608
- ELSE 0 END`;
4709
+ ELSE 0 END)
4710
+ OR
4711
+ (CASE WHEN json_valid(derived_events)
4712
+ THEN (CASE WHEN json_type(derived_events) = 'array'
4713
+ THEN EXISTS (SELECT 1 FROM json_each(derived_events) WHERE json_each.type = 'text' AND json_each.value = ?)
4714
+ ELSE 0 END)
4715
+ ELSE 0 END))`;
4716
+ /** Old name kept as an alias (tests and external references). */
4717
+ _EntryRepository.POINTER_EVENT_MATCH_SQL = _EntryRepository.EVENT_MATCH_SQL;
4609
4718
  var EntryRepository = _EntryRepository;
4610
4719
 
4611
4720
  // src/utils/ids.ts
@@ -5142,6 +5251,24 @@ var EventRepository = class extends BaseRepository {
5142
5251
  );
5143
5252
  return result.changes > 0;
5144
5253
  }
5254
+ /**
5255
+ * The subset of `ids` that exist as events of `entityId` (specs/
5256
+ * inplace-update-provenance §3). Chunked so a large batch stays under the
5257
+ * bound-variable limit. Pass `tx` to read inside the caller's transaction.
5258
+ */
5259
+ async findExistingIds(entityId, ids, tx) {
5260
+ const executor = this.getExecutor(tx);
5261
+ const found = /* @__PURE__ */ new Set();
5262
+ for (let i = 0; i < ids.length; i += 500) {
5263
+ const chunk = ids.slice(i, i + 500);
5264
+ const rows = await executor.getAllAsync(
5265
+ `SELECT id FROM ${this.prefix}events WHERE entity_id = ? AND id IN (${chunk.map(() => "?").join(",")})`,
5266
+ [entityId, ...chunk]
5267
+ );
5268
+ for (const r of rows) found.add(r.id);
5269
+ }
5270
+ return found;
5271
+ }
5145
5272
  /**
5146
5273
  * Return the most recent events for an entity, newest first.
5147
5274
  * Defaults to a limit of 50.
@@ -9516,10 +9643,17 @@ var TemporalService = class {
9516
9643
  if (predecessors.some((r) => r.id === newId)) throw new WikiSupersedeError("cycle");
9517
9644
  const start = old.valid_from ?? old.created_at;
9518
9645
  if (t <= start) throw new WikiSupersedeError("invalid_interval");
9519
- await this.entryRepo.setTemporal(oldId, entityId, { valid_to: t, superseded_by: newId, superseded_at: now }, tx);
9646
+ const replacedScheduledEnd = old.valid_to;
9647
+ await this.entryRepo.setTemporal(oldId, entityId, {
9648
+ valid_to: t,
9649
+ superseded_by: newId,
9650
+ superseded_at: now,
9651
+ prior_valid_to: replacedScheduledEnd
9652
+ }, tx);
9520
9653
  if (repl.valid_from == null) {
9521
9654
  await this.entryRepo.setTemporal(newId, entityId, { valid_from: t }, tx);
9522
9655
  }
9656
+ return { replacedScheduledEnd };
9523
9657
  }
9524
9658
  async supersede(entityId, oldId, replacement, options) {
9525
9659
  const now = Date.now();
@@ -9548,6 +9682,7 @@ var TemporalService = class {
9548
9682
  }
9549
9683
  const newId = typeof replacement === "string" ? replacement : created.id;
9550
9684
  const newValidFrom = typeof replacement !== "string" && replacement.valid_from !== void 0 ? assertEpochMs("replacement.valid_from", replacement.valid_from) : void 0;
9685
+ let replacedScheduledEnd = null;
9551
9686
  await this.db.withTransactionAsync(async (tx) => {
9552
9687
  if (created) {
9553
9688
  await this.entryRepo.upsert(created, tx);
@@ -9555,8 +9690,17 @@ var TemporalService = class {
9555
9690
  await this.entryRepo.setTemporal(created.id, entityId, { valid_from: newValidFrom }, tx);
9556
9691
  }
9557
9692
  }
9558
- await this.supersedeInTx(tx, entityId, oldId, newId, t, now);
9693
+ ({ replacedScheduledEnd } = await this.supersedeInTx(tx, entityId, oldId, newId, t, now));
9559
9694
  });
9695
+ if (replacedScheduledEnd != null) {
9696
+ emitDiagnostic(this.options, {
9697
+ code: "supersede_scheduled_end_replaced",
9698
+ operation: "supersede",
9699
+ trigger: "call",
9700
+ entityId,
9701
+ detail: { factId: oldId, priorValidTo: replacedScheduledEnd }
9702
+ });
9703
+ }
9560
9704
  await this.searchService.syncEntries(entityId, [oldId, newId]);
9561
9705
  if (created) {
9562
9706
  await this.embeddingService.embedFact(
@@ -9588,6 +9732,35 @@ var TemporalService = class {
9588
9732
  await this.searchService.syncEntries(entityId, [factId]);
9589
9733
  this.searchService.evictCache(entityId);
9590
9734
  }
9735
+ /**
9736
+ * Return a superseded fact to live once its replacement is forgotten or gone
9737
+ * (INTENT rule 12, specs/supersede-future-valid-to D4). Restores `valid_to`
9738
+ * to `prior_valid_to` (null when none was recorded).
9739
+ */
9740
+ async reopen(entityId, factId) {
9741
+ let restored = null;
9742
+ await this.db.withTransactionAsync(async (tx) => {
9743
+ const row = await this.entryRepo.findTemporalRow(factId, tx);
9744
+ if (!row || row.deleted_at != null) throw new WikiSupersedeError("not_found", "reopen()");
9745
+ if (row.entity_id !== entityId) throw new WikiSupersedeError("cross_entity", "reopen()");
9746
+ if (row.superseded_by == null) throw new WikiSupersedeError("not_superseded", "reopen()");
9747
+ if (row.source_type === "immutable_document") throw new WikiSupersedeError("immutable_target", "reopen()");
9748
+ const successor = await this.entryRepo.findTemporalRow(row.superseded_by, tx);
9749
+ if (successor && successor.deleted_at == null) throw new WikiSupersedeError("successor_live", "reopen()");
9750
+ const p = row.prior_valid_to;
9751
+ restored = p != null && Number.isInteger(p) && p > (row.valid_from ?? row.created_at) ? p : null;
9752
+ const changes = await this.entryRepo.setTemporal(factId, entityId, {
9753
+ valid_to: restored,
9754
+ superseded_by: null,
9755
+ superseded_at: null,
9756
+ prior_valid_to: null
9757
+ }, tx);
9758
+ if (changes === 0) throw new WikiSupersedeError("cross_entity", "reopen()");
9759
+ });
9760
+ await this.searchService.syncEntries(entityId, [factId]);
9761
+ this.searchService.evictCache(entityId);
9762
+ return { valid_to: restored };
9763
+ }
9591
9764
  async history(entityId, factId) {
9592
9765
  const start = await this.entryRepo.findTemporalRow(factId);
9593
9766
  if (!start || start.entity_id !== entityId || start.deleted_at != null) return [];
@@ -10875,6 +11048,17 @@ function buildSourcePointer(candidate, verdict, groundingOn, groundingCorpus) {
10875
11048
  }
10876
11049
  return { event_id: candidate.sourceEventId, ref: null, quote, position: null };
10877
11050
  }
11051
+ function mergeDerivedEvents(existing, contributing) {
11052
+ if (contributing === null || contributing === existing.source_pointer?.event_id) return void 0;
11053
+ const prior = existing.derived_events ?? [];
11054
+ if (prior.includes(contributing)) return void 0;
11055
+ return dedupeEventIds([...prior, contributing]);
11056
+ }
11057
+ function inheritedDerivedEvents(target, ownEventId) {
11058
+ if (!target) return {};
11059
+ const list = dedupeEventIds([target.source_pointer?.event_id, ...target.derived_events ?? []]).filter((id) => id !== ownEventId);
11060
+ return list.length > 0 ? { derived_events: list } : {};
11061
+ }
10878
11062
  async function applyOps(deps, ctx, input) {
10879
11063
  const { entityId, trigger } = ctx;
10880
11064
  const diagBase = { entityId, operation: "librarian", trigger };
@@ -10905,7 +11089,7 @@ async function applyOps(deps, ctx, input) {
10905
11089
  titleIndex.set(normalizeTitleKey(f.title), { id: f.id, okf_type: f.okf_type ?? null });
10906
11090
  }
10907
11091
  const pendingEdges = [];
10908
- const insert = async (g, draft, validFrom, overrides) => {
11092
+ const insert = async (g, draft, validFrom, overrides, inheritFrom) => {
10909
11093
  const fact = g.candidate.fact;
10910
11094
  const title = overrides?.title ?? fact.title;
10911
11095
  const body = overrides?.body ?? fact.body;
@@ -10949,6 +11133,9 @@ async function applyOps(deps, ctx, input) {
10949
11133
  deleted_at: null,
10950
11134
  okf_type: normalized.okf_type,
10951
11135
  source_pointer: pointer,
11136
+ // §2: only an UPDATE converted to SUPERSEDE inherits (the merged text
11137
+ // rests on the target); ADD and plain SUPERSEDE carry no list.
11138
+ ...inheritedDerivedEvents(inheritFrom, pointer?.event_id ?? null),
10952
11139
  ...g2?.trust,
10953
11140
  ...draft ? { lifecycle_status: "draft" } : {}
10954
11141
  };
@@ -10967,7 +11154,18 @@ async function applyOps(deps, ctx, input) {
10967
11154
  written.push({ id, vector: textChanged ? null : g.vector, fact: { id, entity_id: entityId, title, body, tags: fact.tags } });
10968
11155
  return id;
10969
11156
  };
11157
+ const sourceIds = [...new Set(input.gated.map((g) => g.candidate.sourceEventId).filter((x) => x !== null))];
11158
+ const presentIds = sourceIds.length > 0 ? await deps.eventRepo.findExistingIds(entityId, sourceIds, tx) : /* @__PURE__ */ new Set();
11159
+ const gatedLive = [];
10970
11160
  for (const g of input.gated) {
11161
+ const ev = g.candidate.sourceEventId;
11162
+ if (ev !== null && !presentIds.has(ev)) {
11163
+ input.diagnostics.push({ ...diagBase, code: "source_event_gone", detail: { itemIndex: g.candidate.index, sourceRef: ev } });
11164
+ continue;
11165
+ }
11166
+ gatedLive.push(g);
11167
+ }
11168
+ for (const g of gatedLive) {
10971
11169
  const idx = g.candidate.index;
10972
11170
  const vf = g.candidate.validFrom;
10973
11171
  if (g.decision.kind === "noop") continue;
@@ -10996,11 +11194,21 @@ async function applyOps(deps, ctx, input) {
10996
11194
  const [existing] = await deps.entryRepo.findByIds([op.targetId], [entityId], tx);
10997
11195
  if (existing) {
10998
11196
  const newTitle = op.title ?? g.candidate.fact.title;
11197
+ const contributing = g.candidate.sourceEventId;
11198
+ if (contributing === null && g.candidate.pointerUnresolved !== null) {
11199
+ input.diagnostics.push({
11200
+ ...diagBase,
11201
+ code: "source_pointer_unresolved",
11202
+ detail: { factId: existing.id, itemIndex: idx, reason: g.candidate.pointerUnresolved }
11203
+ });
11204
+ }
11205
+ const derived = mergeDerivedEvents(existing, contributing);
10999
11206
  await deps.entryRepo.upsert({
11000
11207
  ...existing,
11001
11208
  title: newTitle,
11002
11209
  body: op.body ?? g.candidate.fact.body,
11003
- updated_at: now
11210
+ updated_at: now,
11211
+ ...derived ? { derived_events: derived } : {}
11004
11212
  }, tx);
11005
11213
  titleIndex.delete(normalizeTitleKey(existing.title));
11006
11214
  titleIndex.set(normalizeTitleKey(newTitle), { id: existing.id, okf_type: existing.okf_type ?? null });
@@ -11012,15 +11220,24 @@ async function applyOps(deps, ctx, input) {
11012
11220
  const supersedeFrom = op.op === "SUPERSEDE" && op.validFrom !== void 0 ? op.validFrom : vf;
11013
11221
  const overrides = op.op === "UPDATE" ? { title: op.title, body: op.body } : void 0;
11014
11222
  if (target.source_type === "immutable_document") {
11015
- const id = await insert(g, true, supersedeFrom, overrides);
11223
+ const docTarget = op.op === "UPDATE" ? (await deps.entryRepo.findByIds([op.targetId], [entityId], tx))[0] : void 0;
11224
+ const id = await insert(g, true, supersedeFrom, overrides, docTarget);
11016
11225
  input.diagnostics.push({ ...diagBase, code: "contradicts_document", detail: { factId: id, itemIndex: idx } });
11017
11226
  continue;
11018
11227
  }
11019
- const newId = await insert(g, false, supersedeFrom, overrides);
11228
+ const inheritFrom = op.op === "UPDATE" ? (await deps.entryRepo.findByIds([op.targetId], [entityId], tx))[0] : void 0;
11229
+ const newId = await insert(g, false, supersedeFrom, overrides, inheritFrom);
11020
11230
  try {
11021
- await temporal.supersedeInTx(tx, entityId, op.targetId, newId, supersedeFrom, now);
11231
+ const { replacedScheduledEnd } = await temporal.supersedeInTx(tx, entityId, op.targetId, newId, supersedeFrom, now);
11022
11232
  supersededIds.push(op.targetId);
11023
11233
  input.diagnostics.push({ ...diagBase, code: "librarian_superseded", detail: { factId: op.targetId, replacementId: newId } });
11234
+ if (replacedScheduledEnd != null) {
11235
+ input.diagnostics.push({
11236
+ ...diagBase,
11237
+ code: "supersede_scheduled_end_replaced",
11238
+ detail: { factId: op.targetId, priorValidTo: replacedScheduledEnd }
11239
+ });
11240
+ }
11024
11241
  } catch (err) {
11025
11242
  if (!(err instanceof WikiSupersedeError)) throw err;
11026
11243
  input.diagnostics.push({
@@ -14128,7 +14345,7 @@ var ImportExportService = class {
14128
14345
  const rawPointerValue = hasSourcePointerKey ? fact["source_pointer"] : void 0;
14129
14346
  const pointerValidated = hasSourcePointerKey ? validateSourcePointerValue(rawPointerValue) : null;
14130
14347
  if (pointerValidated === void 0) {
14131
- emitDiagnostic(this.options, {
14348
+ refusalDiagnostics.push({
14132
14349
  code: "source_pointer_invalid",
14133
14350
  operation: "importDump",
14134
14351
  trigger: "call",
@@ -14137,6 +14354,19 @@ var ImportExportService = class {
14137
14354
  });
14138
14355
  }
14139
14356
  const sourcePointer = pointerValidated === void 0 ? null : pointerValidated;
14357
+ const rawDerived = fact["derived_events"];
14358
+ const hasDerivedEventsKey = rawDerived !== void 0;
14359
+ const derivedValidated = hasDerivedEventsKey ? validateDerivedEventsValue(rawDerived) : null;
14360
+ if (derivedValidated === void 0) {
14361
+ refusalDiagnostics.push({
14362
+ code: "derived_events_invalid",
14363
+ operation: "importDump",
14364
+ trigger: "call",
14365
+ entityId,
14366
+ detail: { factId: fact.id }
14367
+ });
14368
+ }
14369
+ const derivedEvents = derivedValidated ?? null;
14140
14370
  const factObj = {
14141
14371
  id: fact.id,
14142
14372
  entity_id: entityId,
@@ -14155,6 +14385,7 @@ var ImportExportService = class {
14155
14385
  embedding_blob: blobData ?? void 0,
14156
14386
  okf_type: fact.okf_type ?? null,
14157
14387
  source_pointer: sourcePointer,
14388
+ ...derivedEvents ? { derived_events: derivedEvents } : {},
14158
14389
  // OKF v0.2 — forwarded as-is; parseOkfBundle / the caller is responsible for
14159
14390
  // populating these per spec, importDump does not derive or validate them.
14160
14391
  lifecycle_status: fact.lifecycle_status ?? "stable",
@@ -14172,12 +14403,15 @@ var ImportExportService = class {
14172
14403
  return { last_verified_at: latest?.at ?? null, last_verified_by: latest?.by ?? null };
14173
14404
  })()
14174
14405
  };
14175
- await this.entryRepo.upsertForImport(factObj, tx, hasSourcePointerKey);
14406
+ await this.entryRepo.upsertForImport(factObj, tx, hasSourcePointerKey, hasDerivedEventsKey);
14176
14407
  await this.entryRepo.setTemporal(fact.id, entityId, {
14177
14408
  valid_from: fact.valid_from ?? null,
14178
14409
  valid_to: fact.valid_to ?? null,
14179
14410
  superseded_by: fact.superseded_by ?? null,
14180
- superseded_at: fact.superseded_at ?? null
14411
+ superseded_at: fact.superseded_at ?? null,
14412
+ // prior_valid_to (spec D5): replace semantics like the four siblings;
14413
+ // null whenever the row is not superseded (the column's invariant).
14414
+ prior_valid_to: fact.superseded_by == null ? null : fact.prior_valid_to ?? null
14181
14415
  }, tx, { outbox: false });
14182
14416
  if (blobData != null) {
14183
14417
  factsWithPreservedBlob.set(fact.id, blobData);
@@ -16900,6 +17134,7 @@ var WikiMemory = class {
16900
17134
  if (!entriesExistedBeforeSetup) {
16901
17135
  await this.db.withTransactionAsync(async (tx) => {
16902
17136
  await createLegacySourceTypeIndex(tx, this.prefix);
17137
+ await createEntriesDeletedIndex(tx, this.prefix);
16903
17138
  await writeNormalizeStamp(this.metadataRepo, tx);
16904
17139
  await this.metadataRepo.setMeta("schema_version", String(CURRENT_SCHEMA_VERSION), tx);
16905
17140
  });
@@ -17480,7 +17715,10 @@ var WikiMemory = class {
17480
17715
  * End `oldId`'s validity and link it to its replacement (spec §4.3). One
17481
17716
  * transaction. Throws `WikiSupersedeError` for missing, foreign, already
17482
17717
  * superseded, already expired, immutable-document, or cyclic targets, and
17483
- * for an inverted or empty interval (`invalid_interval`).
17718
+ * for an inverted or empty interval (`invalid_interval`). When the old
17719
+ * fact carried a future `valid_to`, that scheduled end is overwritten but
17720
+ * kept in `prior_valid_to` (restored by `reopen()`) and reported as the
17721
+ * `supersede_scheduled_end_replaced` diagnostic.
17484
17722
  */
17485
17723
  async supersede(entityId, oldId, replacement, options) {
17486
17724
  return this.temporalService.supersede(entityId, oldId, replacement, options);
@@ -17497,6 +17735,20 @@ var WikiMemory = class {
17497
17735
  async expire(entityId, factId, options) {
17498
17736
  return this.temporalService.expire(entityId, factId, options);
17499
17737
  }
17738
+ /**
17739
+ * Return a superseded fact to live once its replacement has been forgotten
17740
+ * or hard-deleted (INTENT rule 12). Clears `superseded_by`/`superseded_at`
17741
+ * and restores `valid_to` to the scheduled end `supersede()` overwrote
17742
+ * (`prior_valid_to`), or null when the fact was open-ended. Resolves with
17743
+ * the restored `valid_to`. Throws `WikiSupersedeError` for a missing or
17744
+ * foreign fact, one that is not superseded (an `expire()`-ended fact is
17745
+ * not reopened), an immutable-document fact, or `successor_live` while the
17746
+ * direct replacement is still live. A restored end that has already passed
17747
+ * leaves the fact expired.
17748
+ */
17749
+ async reopen(entityId, factId) {
17750
+ return this.temporalService.reopen(entityId, factId);
17751
+ }
17500
17752
  /** The supersession chain containing `factId`, oldest first. [] when unknown. */
17501
17753
  async history(entityId, factId) {
17502
17754
  return this.temporalService.history(entityId, factId);
@@ -18185,8 +18437,11 @@ function factFrontmatterV2(f) {
18185
18437
  ...f.valid_to != null ? { valid_to: f.valid_to } : {},
18186
18438
  ...f.superseded_by != null ? { superseded_by: f.superseded_by } : {},
18187
18439
  ...f.superseded_at != null ? { superseded_at: f.superseded_at } : {},
18440
+ ...f.prior_valid_to != null ? { prior_valid_to: f.prior_valid_to } : {},
18188
18441
  // Source pointer (specs/source-pointers): map only when non-null; null slots omitted.
18189
- ...sourcePointerFrontmatter(f.source_pointer) ? { source_pointer: sourcePointerFrontmatter(f.source_pointer) } : {}
18442
+ ...sourcePointerFrontmatter(f.source_pointer) ? { source_pointer: sourcePointerFrontmatter(f.source_pointer) } : {},
18443
+ // derived_events (specs/inplace-update-provenance §5): optional list, only when non-empty.
18444
+ ...f.derived_events && f.derived_events.length > 0 ? { derived_events: f.derived_events } : {}
18190
18445
  };
18191
18446
  }
18192
18447
  function taskFrontmatterV2(t) {
@@ -18232,7 +18487,9 @@ function factFrontmatterV1(f) {
18232
18487
  last_accessed_at: f.last_accessed_at,
18233
18488
  deleted_at: f.deleted_at,
18234
18489
  // Source pointer (specs/source-pointers): same map rule as the v2 path.
18235
- ...sourcePointerFrontmatter(f.source_pointer) ? { source_pointer: sourcePointerFrontmatter(f.source_pointer) } : {}
18490
+ ...sourcePointerFrontmatter(f.source_pointer) ? { source_pointer: sourcePointerFrontmatter(f.source_pointer) } : {},
18491
+ // derived_events (specs/inplace-update-provenance §5): optional list, only when non-empty.
18492
+ ...f.derived_events && f.derived_events.length > 0 ? { derived_events: f.derived_events } : {}
18236
18493
  };
18237
18494
  }
18238
18495
  function taskFrontmatterV1(t) {
@@ -18543,6 +18800,7 @@ function frontmatterToFact(entityId, id, frontmatter, body, now, droppedPointerV
18543
18800
  ...optionalEpoch("valid_to", frontmatter.valid_to),
18544
18801
  ...typeof frontmatter.superseded_by === "string" ? { superseded_by: frontmatter.superseded_by } : {},
18545
18802
  ...optionalEpoch("superseded_at", frontmatter.superseded_at),
18803
+ ...optionalEpoch("prior_valid_to", frontmatter.prior_valid_to),
18546
18804
  // Source pointer (specs/source-pointers §Export, import, and OKF): the
18547
18805
  // parse path has no diagnostic channel, so it reports through the result.
18548
18806
  // ABSENT key → the property is omitted (not null), so the import
@@ -18558,6 +18816,19 @@ function frontmatterToFact(entityId, id, frontmatter, body, now, droppedPointerV
18558
18816
  return {};
18559
18817
  }
18560
18818
  return { source_pointer: v };
18819
+ })(),
18820
+ // derived_events (specs/inplace-update-provenance §5): a well-formed list
18821
+ // is restored; absent or empty omits the property (import presence rule);
18822
+ // malformed omits it AND is reported by id + slug, never the raw value.
18823
+ ...(() => {
18824
+ const raw = frontmatter.derived_events;
18825
+ if (raw === void 0) return {};
18826
+ const v = validateDerivedEventsValue(raw);
18827
+ if (v === void 0) {
18828
+ droppedPointerValues.push({ factId: id, reason: "derived_events_malformed" });
18829
+ return {};
18830
+ }
18831
+ return v ? { derived_events: v } : {};
18561
18832
  })()
18562
18833
  };
18563
18834
  }