@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.mjs CHANGED
@@ -1,5 +1,5 @@
1
- import { BaseRepository, WikiGraphNodeOwnershipConflict, serializeSourcePointer, parseStoredSourcePointer, parseJsonObject, parseJsonArray, liveAtSql, reanchorRebuildFingerprint, __privateAdd, warnChangedDefaultsOnce, resolveContextBudgetOrThrow, EdgeRepository, MetadataRepository, EmbeddingService, VectorRemovalRepository, VectorRemovalService, SearchService, TemporalService, JobManager, PromptService, resolveGrounding, IngestionService, MaintenanceService, ImportExportService, RetrievalService, SourceStoreService, WriteService, __privateGet, __privateSet, createLegacySourceTypeIndex, writeNormalizeStamp, CURRENT_SCHEMA_VERSION, detectSchemaVersion, MIGRATIONS, runSourceRefNormalize, emitDiagnostic, normalizeSourceRef, normalizeSourceHash, canEngageWriteTyping, resolveLibrarianStrategy, entitySummaryMetaKey, WikiSourceRefHashCollision, DiagnosticBuffer, validateManifest, isReservedAbstainSlug, ONTOLOGY_ABSTAIN_SENTINEL, WikiDraftNotFound, generateId, emptyManifest, resolveNodeTypeMatch, WikiStrictOntologyViolation, validateInlineEdges, resolveEdgeDefinitions, typeSatisfies, normalizeTitleKey, edgeTripleAllowed, resolveNodeType, shouldEmitOntologyReceipt, nodeTypeReceipts, MAX_EMBED_ATTEMPTS, UsageMeter, isWikiSearchUnavailableError, WikiBusyError, WikiInvalidReadOptions, isLiveAt, packFactsByBudget, factTokenCost, probePendingWork, WikiMigrationRequiredError, setupDatabase, UnavailableIndexStrategy, createdAtValue, isUsableDate, validateSourcePointerValue, assertEntityId, assertEpochMs, passageFtsTriggerNames, FTS5_STATE_KEY, fts5LedgerDropSql, passageFtsTablesDdl, passageFtsTriggersDdl, fts5TablesDdl, fts5PendingIndexesDdl, fts5TriggersDdl, writeRebuildStart, FTS5_RETIRED_COUNTER_KEY, retiredTableName, FTS5_RETIRED_TABLES_KEY, isRetiredTableName, idReindexChunkSql, readRebuildProgress, FTS5_DRAIN_CHUNK, FTS5_RECLAIM_MERGE_PAGES, windowHiSql, windowChunkSql, FTS5_REBUILD_WM_KEY, sweepHiSql, sweepChunkSql, FTS5_SWEEP_CURSOR_KEY, drainHiSql, drainChunkSql, FTS5_REBUILD_SNAPSHOT_KEY, idDrainChunkSql, entityDrainHiSql, entityDrainChunkSql, fts5TriggerNames, extractSqliteCode, WikiTransactionError } from './chunk-JCMA74YK.mjs';
2
- export { CLASSIFIER_MAX_CHOICES, CheckpointIncompleteError, DEFAULT_CHUNK_OVERLAP, DEFAULT_MAX_CHUNK_LENGTH, DEFAULT_MAX_EMBED_CHARS, DEFAULT_TYPING_MIN_CONFIDENCE, EMBED_CHARS_CEILING, EraseStepError, HEAL_ANCHORS_PER_CANDIDATE, HEAL_BATCH_SIZE, HEAL_MAX_FACT_BODY_CHARS_L3, HEAL_MAX_TASKS, HEAL_RECHECK_MS, HOOK_TIMEOUT_MARKER, ONTOLOGY_ABSTAIN_SENTINEL, ONTOLOGY_BACKFILL_BATCH_SIZE, ONTOLOGY_BACKFILL_MAX_PROMPT_CHARS, ONTOLOGY_BACKFILL_RECHECK_MS, ONTOLOGY_BACKFILL_SYSTEM_PROMPT, PromptService, PrunePartialFailureError, WikiBusyError, WikiDraftNotFound, WikiDuplicateHashError, WikiExternalDeletionError, WikiGraphNodeOwnershipConflict, WikiIngestEmptyError, WikiInvalidReadOptions, WikiMigrationRequiredError, WikiParseError, WikiSearchUnavailableError, WikiSourceRefHashCollision, WikiStrictOntologyViolation, WikiSupersedeError, WikiTransactionError, chunkText, configureRandomSource, isReservedAbstainSlug, isWikiSearchUnavailableError, parseEmbedding, resolveContextBudget, resolveDefaultChunkLength, resolveEdgesMinConfidence, resolveHealScreenMinConfidence, resolveMaxPromptChars, resolveResolveMinConfidence, resolveSystemOneEdges, resolveSystemOneHealScreen, resolveSystemOneResolve, resolveSystemOneTypeOnWrite, resolveSystemOneTyping, resolveTypingMinConfidence, safeSlice, validUsage, validateManifest, warnOnce } from './chunk-JCMA74YK.mjs';
1
+ import { BaseRepository, WikiGraphNodeOwnershipConflict, serializeSourcePointer, serializeDerivedEvents, parseStoredDerivedEvents, parseStoredSourcePointer, parseJsonObject, parseJsonArray, liveAtSql, reanchorRebuildFingerprint, __privateAdd, warnChangedDefaultsOnce, resolveContextBudgetOrThrow, EdgeRepository, MetadataRepository, EmbeddingService, VectorRemovalRepository, VectorRemovalService, SearchService, TemporalService, JobManager, PromptService, resolveGrounding, IngestionService, MaintenanceService, ImportExportService, RetrievalService, SourceStoreService, WriteService, __privateGet, __privateSet, createLegacySourceTypeIndex, createEntriesDeletedIndex, writeNormalizeStamp, CURRENT_SCHEMA_VERSION, detectSchemaVersion, MIGRATIONS, runSourceRefNormalize, emitDiagnostic, normalizeSourceRef, normalizeSourceHash, canEngageWriteTyping, resolveLibrarianStrategy, entitySummaryMetaKey, WikiSourceRefHashCollision, DiagnosticBuffer, validateManifest, isReservedAbstainSlug, ONTOLOGY_ABSTAIN_SENTINEL, WikiDraftNotFound, generateId, emptyManifest, resolveNodeTypeMatch, WikiStrictOntologyViolation, validateInlineEdges, resolveEdgeDefinitions, typeSatisfies, normalizeTitleKey, edgeTripleAllowed, resolveNodeType, shouldEmitOntologyReceipt, nodeTypeReceipts, MAX_EMBED_ATTEMPTS, UsageMeter, isWikiSearchUnavailableError, WikiBusyError, WikiInvalidReadOptions, isLiveAt, packFactsByBudget, factTokenCost, probePendingWork, WikiMigrationRequiredError, setupDatabase, UnavailableIndexStrategy, createdAtValue, isUsableDate, validateDerivedEventsValue, validateSourcePointerValue, assertEntityId, assertEpochMs, passageFtsTriggerNames, FTS5_STATE_KEY, fts5LedgerDropSql, passageFtsTablesDdl, passageFtsTriggersDdl, fts5TablesDdl, fts5PendingIndexesDdl, fts5TriggersDdl, writeRebuildStart, FTS5_RETIRED_COUNTER_KEY, retiredTableName, FTS5_RETIRED_TABLES_KEY, isRetiredTableName, idReindexChunkSql, readRebuildProgress, FTS5_DRAIN_CHUNK, FTS5_RECLAIM_MERGE_PAGES, windowHiSql, windowChunkSql, FTS5_REBUILD_WM_KEY, sweepHiSql, sweepChunkSql, FTS5_SWEEP_CURSOR_KEY, drainHiSql, drainChunkSql, FTS5_REBUILD_SNAPSHOT_KEY, idDrainChunkSql, entityDrainHiSql, entityDrainChunkSql, fts5TriggerNames, extractSqliteCode, WikiTransactionError } from './chunk-7DBDJBN3.mjs';
2
+ export { CLASSIFIER_MAX_CHOICES, CheckpointIncompleteError, DEFAULT_CHUNK_OVERLAP, DEFAULT_MAX_CHUNK_LENGTH, DEFAULT_MAX_EMBED_CHARS, DEFAULT_TYPING_MIN_CONFIDENCE, EMBED_CHARS_CEILING, EraseStepError, HEAL_ANCHORS_PER_CANDIDATE, HEAL_BATCH_SIZE, HEAL_MAX_FACT_BODY_CHARS_L3, HEAL_MAX_TASKS, HEAL_RECHECK_MS, HOOK_TIMEOUT_MARKER, ONTOLOGY_ABSTAIN_SENTINEL, ONTOLOGY_BACKFILL_BATCH_SIZE, ONTOLOGY_BACKFILL_MAX_PROMPT_CHARS, ONTOLOGY_BACKFILL_RECHECK_MS, ONTOLOGY_BACKFILL_SYSTEM_PROMPT, PromptService, PrunePartialFailureError, WikiBusyError, WikiDraftNotFound, WikiDuplicateHashError, WikiExternalDeletionError, WikiGraphNodeOwnershipConflict, WikiIngestEmptyError, WikiInvalidReadOptions, WikiMigrationRequiredError, WikiParseError, WikiSearchUnavailableError, WikiSourceRefHashCollision, WikiStrictOntologyViolation, WikiSupersedeError, WikiTransactionError, chunkText, configureRandomSource, isReservedAbstainSlug, isWikiSearchUnavailableError, parseEmbedding, resolveContextBudget, resolveDefaultChunkLength, resolveEdgesMinConfidence, resolveHealScreenMinConfidence, resolveMaxPromptChars, resolveResolveMinConfidence, resolveSystemOneEdges, resolveSystemOneHealScreen, resolveSystemOneResolve, resolveSystemOneTypeOnWrite, resolveSystemOneTyping, resolveTypingMinConfidence, safeSlice, validUsage, validateManifest, warnOnce } from './chunk-7DBDJBN3.mjs';
3
3
  import { deriveTrustTier, isStaleAfter, appendRelatedSection, buildConceptDocument, buildLogMd, buildEntityIndexMd, buildRootIndexMd, isAllowedOkfPath, parseRootIndexMd, parseEntityIndexMd, parseConcept, splitRelatedSection, extractMarkdownLinks, parseLogMd, parseEventIdComment, createEventIdDeriver, latestVerified, formatSourcesJson, appendEventIdComment, parseVerifiedFlexible, parseCitationsList } from '@equationalapplications/core-okf';
4
4
  import MiniSearch from 'minisearch';
5
5
 
@@ -79,6 +79,7 @@ function mapRowToFact(row) {
79
79
  const now = Date.now();
80
80
  const staleAfterRaw = row.stale_after != null ? Number(row.stale_after) : null;
81
81
  const sourcePointer = parseStoredSourcePointer(row.source_pointer);
82
+ const derivedEvents = parseStoredDerivedEvents(row.derived_events);
82
83
  const mapped = {
83
84
  id: row.id,
84
85
  entity_id: row.entity_id,
@@ -113,10 +114,14 @@ function mapRowToFact(row) {
113
114
  ...row.valid_to != null ? { valid_to: Number(row.valid_to) } : {},
114
115
  ...row.superseded_by != null ? { superseded_by: String(row.superseded_by) } : {},
115
116
  ...row.superseded_at != null ? { superseded_at: Number(row.superseded_at) } : {},
117
+ ...row.prior_valid_to != null ? { prior_valid_to: Number(row.prior_valid_to) } : {},
116
118
  // Source pointer (specs/source-pointers): key appears only when non-null,
117
119
  // same temporal-fields pattern. Tolerant read: a malformed stored value
118
120
  // reads as null without throwing (test 1).
119
- ...sourcePointer ? { source_pointer: sourcePointer } : {}
121
+ ...sourcePointer ? { source_pointer: sourcePointer } : {},
122
+ // derived_events (specs/inplace-update-provenance §5): present only when
123
+ // non-empty; a malformed stored value reads as absent without throwing.
124
+ ...derivedEvents ? { derived_events: derivedEvents } : {}
120
125
  };
121
126
  return mapped;
122
127
  }
@@ -233,7 +238,7 @@ var _EntryRepository = class _EntryRepository extends BaseRepository {
233
238
  const existingRow = await executor.getFirstAsync(
234
239
  `SELECT id, entity_id, lifecycle_status, stale_after, generated_by,
235
240
  okf_sources, okf_verified, okf_usage_window,
236
- last_verified_at, last_verified_by, source_pointer
241
+ last_verified_at, last_verified_by, source_pointer, derived_events
237
242
  FROM ${this.prefix}entries WHERE id = ?`,
238
243
  [fact.id]
239
244
  );
@@ -247,8 +252,8 @@ var _EntryRepository = class _EntryRepository extends BaseRepository {
247
252
  source_hash, source_ref, created_at, updated_at, last_accessed_at, access_count,
248
253
  deleted_at, embedding_blob, embedding, okf_type,
249
254
  lifecycle_status, stale_after, generated_by, last_verified_at, last_verified_by,
250
- okf_sources, okf_verified, okf_usage_window, source_pointer
251
- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
255
+ okf_sources, okf_verified, okf_usage_window, source_pointer, derived_events
256
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
252
257
  ON CONFLICT(id) DO UPDATE SET
253
258
  title = excluded.title,
254
259
  body = excluded.body,
@@ -266,7 +271,8 @@ var _EntryRepository = class _EntryRepository extends BaseRepository {
266
271
  embedding_failed_at = CASE WHEN excluded.embedding_blob IS NOT NULL THEN NULL ELSE embedding_failed_at END,
267
272
  embedding_failure_kind = CASE WHEN excluded.embedding_blob IS NOT NULL THEN NULL ELSE embedding_failure_kind END,
268
273
  embedding_attempts = CASE WHEN excluded.embedding_blob IS NOT NULL THEN 0 ELSE embedding_attempts END,
269
- okf_type = excluded.okf_type
274
+ okf_type = excluded.okf_type,
275
+ derived_events = CASE WHEN ? THEN excluded.derived_events ELSE derived_events END
270
276
  WHERE ${this.prefix}entries.entity_id = excluded.entity_id`,
271
277
  [
272
278
  fact.id,
@@ -297,7 +303,12 @@ var _EntryRepository = class _EntryRepository extends BaseRepository {
297
303
  fact.okf_sources ? JSON.stringify(fact.okf_sources) : null,
298
304
  fact.okf_verified ? JSON.stringify(fact.okf_verified) : null,
299
305
  fact.okf_usage_window ? JSON.stringify(fact.okf_usage_window) : null,
300
- serializeSourcePointer(fact.source_pointer)
306
+ serializeSourcePointer(fact.source_pointer),
307
+ serializeDerivedEvents(fact.derived_events),
308
+ // derived_events is writable on conflict (the librarian's in-place
309
+ // UPDATE merges events into it), but only when the caller supplied the
310
+ // key: an undefined key leaves a stored list untouched.
311
+ fact.derived_events !== void 0 ? 1 : 0
301
312
  ]
302
313
  );
303
314
  if (result.changes === 0) {
@@ -321,7 +332,11 @@ var _EntryRepository = class _EntryRepository extends BaseRepository {
321
332
  okf_usage_window: parseJsonObject(existingRow.okf_usage_window),
322
333
  last_verified_at: existingRow.last_verified_at != null ? Number(existingRow.last_verified_at) : null,
323
334
  last_verified_by: existingRow.last_verified_by ?? null,
324
- source_pointer: parseStoredSourcePointer(existingRow.source_pointer)
335
+ source_pointer: parseStoredSourcePointer(existingRow.source_pointer),
336
+ ...fact.derived_events === void 0 ? (() => {
337
+ const stored = parseStoredDerivedEvents(existingRow.derived_events);
338
+ return stored ? { derived_events: stored } : {};
339
+ })() : {}
325
340
  } : null;
326
341
  await this.outbox.push({
327
342
  entityId: fact.entity_id,
@@ -386,7 +401,7 @@ var _EntryRepository = class _EntryRepository extends BaseRepository {
386
401
  const rows = await executor.getAllAsync(sql, args);
387
402
  return rows.map((row) => row.id);
388
403
  }
389
- async upsertForImport(fact, tx, sourcePointerPresent = false) {
404
+ async upsertForImport(fact, tx, sourcePointerPresent = false, derivedEventsPresent = false) {
390
405
  const executor = this.getExecutor(tx);
391
406
  const tagsJson = JSON.stringify(fact.tags);
392
407
  const embeddingBlob = this.normalizeEmbeddingBlob(fact.embedding_blob);
@@ -396,8 +411,8 @@ var _EntryRepository = class _EntryRepository extends BaseRepository {
396
411
  source_hash, source_ref, created_at, updated_at, last_accessed_at, access_count,
397
412
  deleted_at, embedding_blob, embedding, okf_type,
398
413
  lifecycle_status, stale_after, generated_by, last_verified_at, last_verified_by,
399
- okf_sources, okf_verified, okf_usage_window, source_pointer
400
- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
414
+ okf_sources, okf_verified, okf_usage_window, source_pointer, derived_events
415
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
401
416
  ON CONFLICT(id) DO UPDATE SET
402
417
  entity_id = excluded.entity_id,
403
418
  title = excluded.title,
@@ -426,7 +441,8 @@ var _EntryRepository = class _EntryRepository extends BaseRepository {
426
441
  okf_sources = excluded.okf_sources,
427
442
  okf_verified = excluded.okf_verified,
428
443
  okf_usage_window = excluded.okf_usage_window,
429
- source_pointer = CASE WHEN ? THEN excluded.source_pointer ELSE source_pointer END`,
444
+ source_pointer = CASE WHEN ? THEN excluded.source_pointer ELSE source_pointer END,
445
+ derived_events = CASE WHEN ? THEN excluded.derived_events ELSE derived_events END`,
430
446
  [
431
447
  fact.id,
432
448
  fact.entity_id,
@@ -455,9 +471,13 @@ var _EntryRepository = class _EntryRepository extends BaseRepository {
455
471
  fact.okf_verified ? JSON.stringify(fact.okf_verified) : null,
456
472
  fact.okf_usage_window ? JSON.stringify(fact.okf_usage_window) : null,
457
473
  serializeSourcePointer(fact.source_pointer),
474
+ serializeDerivedEvents(fact.derived_events),
458
475
  // The presence flag binds to the SET clause's CASE, AFTER the INSERT
459
476
  // values above.
460
- sourcePointerPresent ? 1 : 0
477
+ sourcePointerPresent ? 1 : 0,
478
+ // derived_events follows the same presence-flag pattern: a pre-v18
479
+ // dump (no key) never nulls a stored list.
480
+ derivedEventsPresent ? 1 : 0
461
481
  ]
462
482
  );
463
483
  return result;
@@ -524,15 +544,19 @@ var _EntryRepository = class _EntryRepository extends BaseRepository {
524
544
  }
525
545
  return result.changes;
526
546
  }
547
+ /** Bind values for `EVENT_MATCH_SQL` after an `entity_id = ?` term: the event id twice. */
548
+ static eventMatchArgs(entityId, eventId) {
549
+ return [entityId, eventId, eventId];
550
+ }
527
551
  /**
528
- * IDs of the entity's entries whose source_pointer names the event id.
552
+ * IDs of the entity's entries whose source_pointer names the event id or whose derived_events list contains it.
529
553
  * `includeDeleted = true` returns live + tombstoned rows (the forget
530
554
  * enumeration superset for index sync and the ledger backstop).
531
555
  */
532
556
  async findIdsByPointerEvent(entityId, eventId, tx, includeDeleted = false) {
533
557
  const executor = this.getExecutor(tx);
534
558
  let sql = `SELECT id FROM ${this.prefix}entries WHERE entity_id = ? AND ${_EntryRepository.POINTER_EVENT_MATCH_SQL}`;
535
- const args = [entityId, eventId];
559
+ const args = _EntryRepository.eventMatchArgs(entityId, eventId);
536
560
  if (!includeDeleted) sql += ` AND deleted_at IS NULL`;
537
561
  const rows = await executor.getAllAsync(sql, args);
538
562
  return rows.map((r) => r.id);
@@ -542,7 +566,7 @@ var _EntryRepository = class _EntryRepository extends BaseRepository {
542
566
  const executor = this.getExecutor(tx);
543
567
  const row = await executor.getFirstAsync(
544
568
  `SELECT COUNT(*) AS n FROM ${this.prefix}entries WHERE entity_id = ? AND deleted_at IS NULL AND ${_EntryRepository.POINTER_EVENT_MATCH_SQL}`,
545
- [entityId, eventId]
569
+ _EntryRepository.eventMatchArgs(entityId, eventId)
546
570
  );
547
571
  return row?.n ?? 0;
548
572
  }
@@ -560,11 +584,11 @@ var _EntryRepository = class _EntryRepository extends BaseRepository {
560
584
  const now = Date.now();
561
585
  const idsToDelete = await executor.getAllAsync(
562
586
  `SELECT id FROM ${this.prefix}entries WHERE entity_id = ? AND deleted_at IS NULL AND ${_EntryRepository.POINTER_EVENT_MATCH_SQL}`,
563
- [entityId, eventId]
587
+ _EntryRepository.eventMatchArgs(entityId, eventId)
564
588
  );
565
589
  const result = await executor.runAsync(
566
590
  `UPDATE ${this.prefix}entries SET deleted_at = ?, updated_at = ? WHERE entity_id = ? AND deleted_at IS NULL AND ${_EntryRepository.POINTER_EVENT_MATCH_SQL}`,
567
- [now, now, entityId, eventId]
591
+ [now, now, ..._EntryRepository.eventMatchArgs(entityId, eventId)]
568
592
  );
569
593
  for (const row of idsToDelete) {
570
594
  await this.outbox.push({
@@ -884,9 +908,9 @@ var _EntryRepository = class _EntryRepository extends BaseRepository {
884
908
  }, tx);
885
909
  }
886
910
  }
887
- /** Spec §4: write any subset of the four temporal columns. Absent key = untouched; null = clear. */
911
+ /** Spec §4: write any subset of the five temporal columns. Absent key = untouched; null = clear. */
888
912
  async setTemporal(id, entityId, fields, tx, opts) {
889
- const keys = ["valid_from", "valid_to", "superseded_by", "superseded_at"].filter((k) => k in fields);
913
+ const keys = ["valid_from", "valid_to", "superseded_by", "superseded_at", "prior_valid_to"].filter((k) => k in fields);
890
914
  if (keys.length === 0) return 0;
891
915
  const executor = this.getExecutor(tx);
892
916
  const result = await executor.runAsync(
@@ -903,7 +927,7 @@ var _EntryRepository = class _EntryRepository extends BaseRepository {
903
927
  async findTemporalRow(id, tx) {
904
928
  const executor = this.getExecutor(tx);
905
929
  const row = await executor.getFirstAsync(
906
- `SELECT id, entity_id, source_type, deleted_at, created_at, valid_from, valid_to, superseded_by
930
+ `SELECT id, entity_id, source_type, deleted_at, created_at, valid_from, valid_to, superseded_by, prior_valid_to
907
931
  FROM ${this.prefix}entries WHERE id = ?`,
908
932
  [id]
909
933
  );
@@ -916,7 +940,8 @@ var _EntryRepository = class _EntryRepository extends BaseRepository {
916
940
  created_at: Number(row.created_at),
917
941
  valid_from: row.valid_from != null ? Number(row.valid_from) : null,
918
942
  valid_to: row.valid_to != null ? Number(row.valid_to) : null,
919
- superseded_by: row.superseded_by != null ? String(row.superseded_by) : null
943
+ superseded_by: row.superseded_by != null ? String(row.superseded_by) : null,
944
+ prior_valid_to: row.prior_valid_to != null ? Number(row.prior_valid_to) : null
920
945
  };
921
946
  }
922
947
  /**
@@ -1621,17 +1646,30 @@ var _EntryRepository = class _EntryRepository extends BaseRepository {
1621
1646
  _EntryRepository.MINI_SEARCH_COLUMNS = "id, entity_id, title, body, tags";
1622
1647
  _EntryRepository.MINI_SEARCH_LIVE_WHERE = "WHERE deleted_at IS NULL";
1623
1648
  /**
1624
- * Shared JSON match predicate for source_pointer event ids
1625
- * (specs/forget-by-event-id §D1). Every JSON call sits under the single
1649
+ * Shared JSON match predicate for an event id
1650
+ * (specs/forget-by-event-id §D1, widened by specs/inplace-update-provenance
1651
+ * §4): a row matches when its `source_pointer` names the event OR its
1652
+ * `derived_events` list contains it. Every JSON call sits under its own
1626
1653
  * `json_valid` guard: unguarded JSON functions RAISE on malformed text, and
1627
1654
  * three-valued logic forces evaluation of AND operands after a NULL-guarded
1628
1655
  * term — a two-term form is only as safe as the planner's term-splitting.
1656
+ * The `json_each` term additionally requires `json_type = 'array'` (a JSON
1657
+ * object or scalar would otherwise iterate its members). The event id binds
1658
+ * TWICE (pointer term, then derived_events term); use `eventMatchArgs`.
1629
1659
  * The tombstone guard (`deleted_at IS NULL`) is added per-method.
1630
1660
  */
1631
- _EntryRepository.POINTER_EVENT_MATCH_SQL = `CASE WHEN json_valid(source_pointer)
1661
+ _EntryRepository.EVENT_MATCH_SQL = `((CASE WHEN json_valid(source_pointer)
1632
1662
  THEN json_type(source_pointer, '$.event_id') = 'text'
1633
1663
  AND json_extract(source_pointer, '$.event_id') = ?
1634
- ELSE 0 END`;
1664
+ ELSE 0 END)
1665
+ OR
1666
+ (CASE WHEN json_valid(derived_events)
1667
+ THEN (CASE WHEN json_type(derived_events) = 'array'
1668
+ THEN EXISTS (SELECT 1 FROM json_each(derived_events) WHERE json_each.type = 'text' AND json_each.value = ?)
1669
+ ELSE 0 END)
1670
+ ELSE 0 END))`;
1671
+ /** Old name kept as an alias (tests and external references). */
1672
+ _EntryRepository.POINTER_EVENT_MATCH_SQL = _EntryRepository.EVENT_MATCH_SQL;
1635
1673
  var EntryRepository = _EntryRepository;
1636
1674
 
1637
1675
  // src/repositories/OutboxRepository.ts
@@ -2144,6 +2182,24 @@ var EventRepository = class extends BaseRepository {
2144
2182
  );
2145
2183
  return result.changes > 0;
2146
2184
  }
2185
+ /**
2186
+ * The subset of `ids` that exist as events of `entityId` (specs/
2187
+ * inplace-update-provenance §3). Chunked so a large batch stays under the
2188
+ * bound-variable limit. Pass `tx` to read inside the caller's transaction.
2189
+ */
2190
+ async findExistingIds(entityId, ids, tx) {
2191
+ const executor = this.getExecutor(tx);
2192
+ const found = /* @__PURE__ */ new Set();
2193
+ for (let i = 0; i < ids.length; i += 500) {
2194
+ const chunk = ids.slice(i, i + 500);
2195
+ const rows = await executor.getAllAsync(
2196
+ `SELECT id FROM ${this.prefix}events WHERE entity_id = ? AND id IN (${chunk.map(() => "?").join(",")})`,
2197
+ [entityId, ...chunk]
2198
+ );
2199
+ for (const r of rows) found.add(r.id);
2200
+ }
2201
+ return found;
2202
+ }
2147
2203
  /**
2148
2204
  * Return the most recent events for an entity, newest first.
2149
2205
  * Defaults to a limit of 50.
@@ -4679,6 +4735,7 @@ var WikiMemory = class {
4679
4735
  if (!entriesExistedBeforeSetup) {
4680
4736
  await this.db.withTransactionAsync(async (tx) => {
4681
4737
  await createLegacySourceTypeIndex(tx, this.prefix);
4738
+ await createEntriesDeletedIndex(tx, this.prefix);
4682
4739
  await writeNormalizeStamp(this.metadataRepo, tx);
4683
4740
  await this.metadataRepo.setMeta("schema_version", String(CURRENT_SCHEMA_VERSION), tx);
4684
4741
  });
@@ -5259,7 +5316,10 @@ var WikiMemory = class {
5259
5316
  * End `oldId`'s validity and link it to its replacement (spec §4.3). One
5260
5317
  * transaction. Throws `WikiSupersedeError` for missing, foreign, already
5261
5318
  * superseded, already expired, immutable-document, or cyclic targets, and
5262
- * for an inverted or empty interval (`invalid_interval`).
5319
+ * for an inverted or empty interval (`invalid_interval`). When the old
5320
+ * fact carried a future `valid_to`, that scheduled end is overwritten but
5321
+ * kept in `prior_valid_to` (restored by `reopen()`) and reported as the
5322
+ * `supersede_scheduled_end_replaced` diagnostic.
5263
5323
  */
5264
5324
  async supersede(entityId, oldId, replacement, options) {
5265
5325
  return this.temporalService.supersede(entityId, oldId, replacement, options);
@@ -5276,6 +5336,20 @@ var WikiMemory = class {
5276
5336
  async expire(entityId, factId, options) {
5277
5337
  return this.temporalService.expire(entityId, factId, options);
5278
5338
  }
5339
+ /**
5340
+ * Return a superseded fact to live once its replacement has been forgotten
5341
+ * or hard-deleted (INTENT rule 12). Clears `superseded_by`/`superseded_at`
5342
+ * and restores `valid_to` to the scheduled end `supersede()` overwrote
5343
+ * (`prior_valid_to`), or null when the fact was open-ended. Resolves with
5344
+ * the restored `valid_to`. Throws `WikiSupersedeError` for a missing or
5345
+ * foreign fact, one that is not superseded (an `expire()`-ended fact is
5346
+ * not reopened), an immutable-document fact, or `successor_live` while the
5347
+ * direct replacement is still live. A restored end that has already passed
5348
+ * leaves the fact expired.
5349
+ */
5350
+ async reopen(entityId, factId) {
5351
+ return this.temporalService.reopen(entityId, factId);
5352
+ }
5279
5353
  /** The supersession chain containing `factId`, oldest first. [] when unknown. */
5280
5354
  async history(entityId, factId) {
5281
5355
  return this.temporalService.history(entityId, factId);
@@ -5964,8 +6038,11 @@ function factFrontmatterV2(f) {
5964
6038
  ...f.valid_to != null ? { valid_to: f.valid_to } : {},
5965
6039
  ...f.superseded_by != null ? { superseded_by: f.superseded_by } : {},
5966
6040
  ...f.superseded_at != null ? { superseded_at: f.superseded_at } : {},
6041
+ ...f.prior_valid_to != null ? { prior_valid_to: f.prior_valid_to } : {},
5967
6042
  // Source pointer (specs/source-pointers): map only when non-null; null slots omitted.
5968
- ...sourcePointerFrontmatter(f.source_pointer) ? { source_pointer: sourcePointerFrontmatter(f.source_pointer) } : {}
6043
+ ...sourcePointerFrontmatter(f.source_pointer) ? { source_pointer: sourcePointerFrontmatter(f.source_pointer) } : {},
6044
+ // derived_events (specs/inplace-update-provenance §5): optional list, only when non-empty.
6045
+ ...f.derived_events && f.derived_events.length > 0 ? { derived_events: f.derived_events } : {}
5969
6046
  };
5970
6047
  }
5971
6048
  function taskFrontmatterV2(t) {
@@ -6011,7 +6088,9 @@ function factFrontmatterV1(f) {
6011
6088
  last_accessed_at: f.last_accessed_at,
6012
6089
  deleted_at: f.deleted_at,
6013
6090
  // Source pointer (specs/source-pointers): same map rule as the v2 path.
6014
- ...sourcePointerFrontmatter(f.source_pointer) ? { source_pointer: sourcePointerFrontmatter(f.source_pointer) } : {}
6091
+ ...sourcePointerFrontmatter(f.source_pointer) ? { source_pointer: sourcePointerFrontmatter(f.source_pointer) } : {},
6092
+ // derived_events (specs/inplace-update-provenance §5): optional list, only when non-empty.
6093
+ ...f.derived_events && f.derived_events.length > 0 ? { derived_events: f.derived_events } : {}
6015
6094
  };
6016
6095
  }
6017
6096
  function taskFrontmatterV1(t) {
@@ -6322,6 +6401,7 @@ function frontmatterToFact(entityId, id, frontmatter, body, now, droppedPointerV
6322
6401
  ...optionalEpoch("valid_to", frontmatter.valid_to),
6323
6402
  ...typeof frontmatter.superseded_by === "string" ? { superseded_by: frontmatter.superseded_by } : {},
6324
6403
  ...optionalEpoch("superseded_at", frontmatter.superseded_at),
6404
+ ...optionalEpoch("prior_valid_to", frontmatter.prior_valid_to),
6325
6405
  // Source pointer (specs/source-pointers §Export, import, and OKF): the
6326
6406
  // parse path has no diagnostic channel, so it reports through the result.
6327
6407
  // ABSENT key → the property is omitted (not null), so the import
@@ -6337,6 +6417,19 @@ function frontmatterToFact(entityId, id, frontmatter, body, now, droppedPointerV
6337
6417
  return {};
6338
6418
  }
6339
6419
  return { source_pointer: v };
6420
+ })(),
6421
+ // derived_events (specs/inplace-update-provenance §5): a well-formed list
6422
+ // is restored; absent or empty omits the property (import presence rule);
6423
+ // malformed omits it AND is reported by id + slug, never the raw value.
6424
+ ...(() => {
6425
+ const raw = frontmatter.derived_events;
6426
+ if (raw === void 0) return {};
6427
+ const v = validateDerivedEventsValue(raw);
6428
+ if (v === void 0) {
6429
+ droppedPointerValues.push({ factId: id, reason: "derived_events_malformed" });
6430
+ return {};
6431
+ }
6432
+ return v ? { derived_events: v } : {};
6340
6433
  })()
6341
6434
  };
6342
6435
  }