@equationalapplications/core-llm-wiki 9.14.1 → 9.16.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
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, 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-JX7VMQ55.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, resolveSystemOneTyping, resolveTypingMinConfidence, safeSlice, validUsage, validateManifest, warnOnce } from './chunk-JX7VMQ55.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-DD5G4VRF.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-DD5G4VRF.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.
@@ -3477,8 +3533,8 @@ var MaintenanceScheduler = class {
3477
3533
  * `budget_too_small` > `complete`. `budget_too_small` means a job's smallest
3478
3534
  * unit needs more than the WHOLE budget — that job is skipped this run and
3479
3535
  * the run continues; `budget_exhausted` means a unit needs more than what
3480
- * REMAINS — the run stops. The token budget meters `generateText` calls
3481
- * only; embeddings are never metered.
3536
+ * REMAINS — the run stops. The token budget meters generation and classify
3537
+ * calls; embeddings are never metered.
3482
3538
  */
3483
3539
  async run(opts = {}) {
3484
3540
  if (opts.deadlineMs !== void 0 && (typeof opts.deadlineMs !== "number" || !Number.isFinite(opts.deadlineMs) || opts.deadlineMs < 0)) {
@@ -3559,7 +3615,12 @@ var MaintenanceScheduler = class {
3559
3615
  }
3560
3616
  st.report.librarianPasses++;
3561
3617
  st.report.factsWritten += r.factsWritten;
3618
+ if (r.typing) st.report.typedOnWrite = (st.report.typedOnWrite ?? 0) + r.typing.typed;
3562
3619
  progressed = true;
3620
+ if ((r.typing?.unattempted ?? 0) > 0) {
3621
+ stopped = exhaustedStop();
3622
+ break rounds;
3623
+ }
3563
3624
  const wm = await this.metadataRepo.getLibrarianWatermark(entityId, this.db);
3564
3625
  if (await this.eventRepo.countAfter(entityId, wm) === 0) st.librarian = false;
3565
3626
  continue;
@@ -3725,6 +3786,33 @@ function buildOntologyPromptAppendix(mode, manifestJson) {
3725
3786
  ].filter(Boolean).join("\n");
3726
3787
  return { ontologyManifest: manifestJson, ontologyModeInstructions };
3727
3788
  }
3789
+ var WRITE_FACT_ONTOLOGY_FIELDS = `
3790
+ Each fact may optionally include:
3791
+ - "okf_type": string \u2014 must be one of the node_types in the manifest
3792
+ - "edges": [{ "edge_type": string, "target_title": string }] \u2014 target_title must match another fact's title in this response or existing memory
3793
+ - An edge_type may appear in the manifest multiple times with different source_type/target_type; use the row whose types match your fact and target.
3794
+ Each node is a fact. To link two things with an edge, each must exist as its own fact, titled by the same name you use in \`target_title\`.`;
3795
+ var WRITE_EMERGENT_EXTRA = `
3796
+ You may also return "ontology_updates" to propose new types:
3797
+ "ontology_updates": {
3798
+ "node_types": [{ "type": "slug", "description": "...", "parent_type": "optional existing slug" }],
3799
+ "edge_types": [{ "type": "slug", "source_type": "...", "target_type": "...", "description": "..." }]
3800
+ }
3801
+ Only propose types not already in the manifest. Do not redefine existing types.`;
3802
+ function buildWriteOntologyAppendix(mode, manifestJson) {
3803
+ const strictRules = mode === "strict" ? "STRICT MODE: Use ONLY types defined in the manifest. If a fact does not fit a node_type, choose the closest type the fact is an example of; omit only when none applies even broadly." : "EMERGENT MODE: Prefer manifest types. You may propose new types via ontology_updates when necessary.";
3804
+ const fallback = "If okf_type or an edge is invalid, omit them rather than inventing unlisted types.";
3805
+ const ontologyModeInstructions = [
3806
+ "## Ontology constraints",
3807
+ strictRules,
3808
+ fallback,
3809
+ WRITE_FACT_ONTOLOGY_FIELDS,
3810
+ mode === "emergent" ? WRITE_EMERGENT_EXTRA : "",
3811
+ "Manifest:",
3812
+ manifestJson
3813
+ ].filter(Boolean).join("\n");
3814
+ return { site: "write", ontologyManifest: manifestJson, ontologyModeInstructions };
3815
+ }
3728
3816
 
3729
3817
  // src/services/OntologyService.ts
3730
3818
  var OntologyService = class {
@@ -3773,6 +3861,17 @@ var OntologyService = class {
3773
3861
  const manifestJson = JSON.stringify(manifest, null, 2);
3774
3862
  return buildOntologyPromptAppendix(mode, manifestJson);
3775
3863
  }
3864
+ /**
3865
+ * Ontology prompt context for the WRITE builders (specs/type-on-write §5).
3866
+ * `null` when the mode is `'off'` or when write-time typing is `engaged`
3867
+ * (the classifier types the fact, so the manifest leaves the write prompt).
3868
+ * Backfill keeps `buildPromptContext`.
3869
+ */
3870
+ async buildWritePromptContext(entityId, opts) {
3871
+ const { mode, manifest } = await this.getEffectiveState(entityId);
3872
+ if (mode === "off" || opts.engaged) return null;
3873
+ return buildWriteOntologyAppendix(mode, JSON.stringify(manifest, null, 2));
3874
+ }
3776
3875
  async mergeEmergentUpdates(entityId, updates, tx) {
3777
3876
  const filtered = updates.node_types ? { ...updates, node_types: updates.node_types.filter((nt) => !isReservedAbstainSlug(nt.type)) } : updates;
3778
3877
  const { manifest: merged, rejected } = await this.metadataRepo.mergeManifestUpdates(entityId, filtered, tx);
@@ -4636,6 +4735,7 @@ var WikiMemory = class {
4636
4735
  if (!entriesExistedBeforeSetup) {
4637
4736
  await this.db.withTransactionAsync(async (tx) => {
4638
4737
  await createLegacySourceTypeIndex(tx, this.prefix);
4738
+ await createEntriesDeletedIndex(tx, this.prefix);
4639
4739
  await writeNormalizeStamp(this.metadataRepo, tx);
4640
4740
  await this.metadataRepo.setMeta("schema_version", String(CURRENT_SCHEMA_VERSION), tx);
4641
4741
  });
@@ -4843,7 +4943,11 @@ var WikiMemory = class {
4843
4943
  */
4844
4944
  async getInstructions(entityId) {
4845
4945
  assertEntityId2(entityId);
4846
- const ontologyContext = await this.ontologyService.buildPromptContext(entityId);
4946
+ const state = await this.ontologyService.getEffectiveState(entityId);
4947
+ const engaged = canEngageWriteTyping(this.options.config, this.options.llmProvider, state.mode, state.manifest);
4948
+ const writeContext = await this.ontologyService.buildWritePromptContext(entityId, { engaged });
4949
+ const ingestContext = engaged ? await this.ontologyService.buildWritePromptContext(entityId, { engaged: false }) : writeContext;
4950
+ const backfillContext = await this.ontologyService.buildPromptContext(entityId);
4847
4951
  const { guidance, diagnostic } = PromptService.resolveGuidance(this.options.config, entityId);
4848
4952
  if (diagnostic) {
4849
4953
  emitDiagnostic(this.options, {
@@ -4854,7 +4958,7 @@ var WikiMemory = class {
4854
4958
  detail: diagnostic.detail
4855
4959
  });
4856
4960
  }
4857
- return this.promptService.buildInstructionTemplates(ontologyContext, resolveLibrarianStrategy(this.options.config), guidance);
4961
+ return this.promptService.buildInstructionTemplates(writeContext, resolveLibrarianStrategy(this.options.config), guidance, backfillContext, ingestContext);
4858
4962
  }
4859
4963
  /**
4860
4964
  * Returns the live source_refs for an entity, one row per ref, with the most
@@ -5212,7 +5316,10 @@ var WikiMemory = class {
5212
5316
  * End `oldId`'s validity and link it to its replacement (spec §4.3). One
5213
5317
  * transaction. Throws `WikiSupersedeError` for missing, foreign, already
5214
5318
  * superseded, already expired, immutable-document, or cyclic targets, and
5215
- * 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.
5216
5323
  */
5217
5324
  async supersede(entityId, oldId, replacement, options) {
5218
5325
  return this.temporalService.supersede(entityId, oldId, replacement, options);
@@ -5229,6 +5336,20 @@ var WikiMemory = class {
5229
5336
  async expire(entityId, factId, options) {
5230
5337
  return this.temporalService.expire(entityId, factId, options);
5231
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
+ }
5232
5353
  /** The supersession chain containing `factId`, oldest first. [] when unknown. */
5233
5354
  async history(entityId, factId) {
5234
5355
  return this.temporalService.history(entityId, factId);
@@ -5917,8 +6038,11 @@ function factFrontmatterV2(f) {
5917
6038
  ...f.valid_to != null ? { valid_to: f.valid_to } : {},
5918
6039
  ...f.superseded_by != null ? { superseded_by: f.superseded_by } : {},
5919
6040
  ...f.superseded_at != null ? { superseded_at: f.superseded_at } : {},
6041
+ ...f.prior_valid_to != null ? { prior_valid_to: f.prior_valid_to } : {},
5920
6042
  // Source pointer (specs/source-pointers): map only when non-null; null slots omitted.
5921
- ...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 } : {}
5922
6046
  };
5923
6047
  }
5924
6048
  function taskFrontmatterV2(t) {
@@ -5964,7 +6088,9 @@ function factFrontmatterV1(f) {
5964
6088
  last_accessed_at: f.last_accessed_at,
5965
6089
  deleted_at: f.deleted_at,
5966
6090
  // Source pointer (specs/source-pointers): same map rule as the v2 path.
5967
- ...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 } : {}
5968
6094
  };
5969
6095
  }
5970
6096
  function taskFrontmatterV1(t) {
@@ -6275,6 +6401,7 @@ function frontmatterToFact(entityId, id, frontmatter, body, now, droppedPointerV
6275
6401
  ...optionalEpoch("valid_to", frontmatter.valid_to),
6276
6402
  ...typeof frontmatter.superseded_by === "string" ? { superseded_by: frontmatter.superseded_by } : {},
6277
6403
  ...optionalEpoch("superseded_at", frontmatter.superseded_at),
6404
+ ...optionalEpoch("prior_valid_to", frontmatter.prior_valid_to),
6278
6405
  // Source pointer (specs/source-pointers §Export, import, and OKF): the
6279
6406
  // parse path has no diagnostic channel, so it reports through the result.
6280
6407
  // ABSENT key → the property is omitted (not null), so the import
@@ -6290,6 +6417,19 @@ function frontmatterToFact(entityId, id, frontmatter, body, now, droppedPointerV
6290
6417
  return {};
6291
6418
  }
6292
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 } : {};
6293
6433
  })()
6294
6434
  };
6295
6435
  }