@equationalapplications/core-llm-wiki 9.20.2 → 9.21.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,6 +1,6 @@
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, createEventsForgottenIndex, writeNormalizeStamp, CURRENT_SCHEMA_VERSION, detectSchemaVersion, MIGRATIONS, runSourceRefNormalize, emitDiagnostic, normalizeSourceRef, normalizeSourceHash, canEngageWriteTyping, canEngageIngestTyping, 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-PLZNFRMM.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, resolveSystemOneTypeOnIngest, resolveSystemOneTypeOnWrite, resolveSystemOneTyping, resolveTypingMinConfidence, safeSlice, validUsage, validateManifest, warnOnce } from './chunk-PLZNFRMM.mjs';
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';
1
+ import { FACT_MAPPED_KEYS, TASK_MAPPED_KEYS, BaseRepository, WikiGraphNodeOwnershipConflict, serializeSourcePointer, serializeDerivedEvents, parseStoredDerivedEvents, parseStoredSourcePointer, parseJsonObject, parseJsonArray, liveAtSql, reanchorRebuildFingerprint, ENGINE_ACTOR, __privateAdd, warnChangedDefaultsOnce, resolveContextBudgetOrThrow, EdgeRepository, MetadataRepository, EmbeddingService, VectorRemovalRepository, VectorRemovalService, SearchService, TemporalService, JobManager, PromptService, resolveGrounding, IngestionService, MaintenanceService, ImportExportService, RetrievalService, SourceStoreService, WriteService, __privateGet, __privateSet, createLegacySourceTypeIndex, createEntriesDeletedIndex, createEventsForgottenIndex, writeNormalizeStamp, CURRENT_SCHEMA_VERSION, detectSchemaVersion, MIGRATIONS, runSourceRefNormalize, emitDiagnostic, normalizeSourceRef, normalizeSourceHash, canEngageWriteTyping, canEngageIngestTyping, 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, isValidRawBlockEntry, createdAtValue, isUsableDate, 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-EEVYPJCL.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, parseOkfBundle, resolveContextBudget, resolveDefaultChunkLength, resolveEdgesMinConfidence, resolveHealScreenMinConfidence, resolveMaxPromptChars, resolveResolveMinConfidence, resolveSystemOneEdges, resolveSystemOneHealScreen, resolveSystemOneResolve, resolveSystemOneTypeOnIngest, resolveSystemOneTypeOnWrite, resolveSystemOneTyping, resolveTypingMinConfidence, safeSlice, validUsage, validateManifest, warnOnce } from './chunk-EEVYPJCL.mjs';
3
+ import { deriveTrustTier, isStaleAfter, appendRelatedSection, buildConceptDocument, buildLogMd, buildEntityIndexMd, buildRootIndexMd, latestVerified, formatSourcesJson, appendEventIdComment } from '@equationalapplications/core-okf';
4
4
  import MiniSearch from 'minisearch';
5
5
 
6
6
  // src/db/migrationGate.ts
@@ -78,8 +78,11 @@ function mapRowToFact(row) {
78
78
  const okf_verified = parseJsonArray(row.okf_verified, []);
79
79
  const now = Date.now();
80
80
  const staleAfterRaw = row.stale_after != null ? Number(row.stale_after) : null;
81
+ const staleAfterRawText = row.stale_after_raw != null ? String(row.stale_after_raw) : null;
81
82
  const sourcePointer = parseStoredSourcePointer(row.source_pointer);
82
83
  const derivedEvents = parseStoredDerivedEvents(row.derived_events);
84
+ const generatedAt = row.generated_by != null ? Number(row.updated_at) : null;
85
+ const okfExtra = parseJsonObject(row.okf_extra);
83
86
  const mapped = {
84
87
  id: row.id,
85
88
  entity_id: row.entity_id,
@@ -105,9 +108,19 @@ function mapRowToFact(row) {
105
108
  okf_usage_window: parseJsonObject(row.okf_usage_window),
106
109
  last_verified_at: row.last_verified_at != null ? Number(row.last_verified_at) : null,
107
110
  last_verified_by: row.last_verified_by ?? null,
108
- // Spec §2.7 + §5.3: hydrate so read() consumers don't re-call the helpers.
109
- isStale: isStaleAfter(staleAfterRaw, now),
110
- trustTier: deriveTrustTier(okf_verified),
111
+ // Spec §2.7 + §5.3: hydrate so read() consumers don't re-call the
112
+ // helpers. §B3 read rule (refinement 37): a stored raw value means the
113
+ // wire value never parsed, so it is stale — never fresh (§5.5) — even
114
+ // beside an epoch column the writers would not have paired with it.
115
+ isStale: staleAfterRawText != null ? true : isStaleAfter(staleAfterRaw, now),
116
+ trustTier: deriveTrustTier(okf_verified, generatedAt),
117
+ // v0.3 columns (specs/okf-v03 §F): keys appear only when set — same
118
+ // rationale as the temporal fields below (existing deep-equality
119
+ // assertions and host snapshots stay unchanged; NULL = nothing to
120
+ // preserve). A malformed stored okf_extra reads as absent without
121
+ // throwing (parseJsonObject).
122
+ ...staleAfterRawText != null ? { stale_after_raw: staleAfterRawText } : {},
123
+ ...okfExtra ? { okf_extra: okfExtra } : {},
111
124
  // Temporal (spec 2026-09-29 §4, §10.8): keys appear only when set so
112
125
  // existing deep-equality assertions and host snapshots are unchanged.
113
126
  ...row.valid_from != null ? { valid_from: Number(row.valid_from) } : {},
@@ -229,16 +242,37 @@ var _EntryRepository = class _EntryRepository extends BaseRepository {
229
242
  * `WikiGraphNodeOwnershipConflict` (no owner, node ID, or stored content
230
243
  * is disclosed). Upserts that pass both gates retain existing same-entity
231
244
  * update + resurrection semantics.
232
- */
233
- async upsert(fact, tx) {
245
+ *
246
+ * §C2 content gate (specs/okf-v03): the ON CONFLICT SET computes one
247
+ * `unchanged` predicate — null-safe `IS` over `title`, `body`, `tags`
248
+ * (serialized) and `confidence` — and gates `updated_at` and `generated_by`
249
+ * on it. A byte-identical re-upsert is a true no-op for exactly those two
250
+ * columns (refinement 27), so a resync or replay can never falsely
251
+ * de-current a human verification (§5.3); a real content change takes the
252
+ * new instant and fills a NULL row actor from the caller (COALESCE — a
253
+ * stored actor, foreign included, is never overwritten). Everything else
254
+ * in the SET still runs and the outbox event still publishes.
255
+ * Caller note (review T3-tail2 #2): `deleted_at` is NOT in the compared
256
+ * set — a tombstone or resurrection over otherwise identical content
257
+ * keeps the prior `updated_at`. Callers syncing by last-write-wins on
258
+ * `updated_at` must consult `deleted_at` too (the plan's `hasChanged`
259
+ * note says the same).
260
+ * `upsertGraph` replays still advance `updated_at` (refinement 10: it
261
+ * soft-deletes rows first; the DELETE-then-UPDATE outbox shape is kept).
262
+ * §C5: pass `at` to share one instant between the write and a same-pass
263
+ * verification event so the event reads current (`>=`, §A2).
264
+ */
265
+ async upsert(fact, tx, at) {
234
266
  const executor = this.getExecutor(tx);
235
- const now = Date.now();
267
+ const now = typeof at === "number" && Number.isFinite(at) ? at : Date.now();
236
268
  const tagsJson = JSON.stringify(fact.tags);
237
269
  const embeddingBlob = this.normalizeEmbeddingBlob(fact.embedding_blob);
238
270
  const existingRow = await executor.getFirstAsync(
239
271
  `SELECT id, entity_id, lifecycle_status, stale_after, generated_by,
240
272
  okf_sources, okf_verified, okf_usage_window,
241
- last_verified_at, last_verified_by, source_pointer, derived_events
273
+ stale_after_raw, okf_extra,
274
+ last_verified_at, last_verified_by, source_pointer, derived_events,
275
+ title, body, tags, confidence, updated_at
242
276
  FROM ${this.prefix}entries WHERE id = ?`,
243
277
  [fact.id]
244
278
  );
@@ -246,14 +280,16 @@ var _EntryRepository = class _EntryRepository extends BaseRepository {
246
280
  throw new WikiGraphNodeOwnershipConflict();
247
281
  }
248
282
  const operation = fact.deleted_at ? "DELETE" : existingRow ? "UPDATE" : "INSERT";
283
+ const unchanged = existingRow != null && (existingRow.title ?? null) === (fact.title ?? null) && (existingRow.body ?? null) === (fact.body ?? null) && (existingRow.tags ?? null) === tagsJson && (existingRow.confidence ?? null) === (fact.confidence ?? null);
249
284
  const result = await executor.runAsync(
250
285
  `INSERT INTO ${this.prefix}entries (
251
286
  id, entity_id, title, body, tags, confidence, source_type,
252
287
  source_hash, source_ref, created_at, updated_at, last_accessed_at, access_count,
253
288
  deleted_at, embedding_blob, embedding, okf_type,
254
289
  lifecycle_status, stale_after, generated_by, last_verified_at, last_verified_by,
255
- okf_sources, okf_verified, okf_usage_window, source_pointer, derived_events
256
- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
290
+ okf_sources, okf_verified, okf_usage_window, stale_after_raw, okf_extra,
291
+ source_pointer, derived_events
292
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
257
293
  ON CONFLICT(id) DO UPDATE SET
258
294
  title = excluded.title,
259
295
  body = excluded.body,
@@ -262,7 +298,8 @@ var _EntryRepository = class _EntryRepository extends BaseRepository {
262
298
  source_type = excluded.source_type,
263
299
  source_hash = excluded.source_hash,
264
300
  source_ref = excluded.source_ref,
265
- updated_at = excluded.updated_at,
301
+ updated_at = CASE WHEN title IS excluded.title AND body IS excluded.body AND tags IS excluded.tags AND confidence IS excluded.confidence
302
+ THEN updated_at ELSE excluded.updated_at END,
266
303
  last_accessed_at = excluded.last_accessed_at,
267
304
  access_count = excluded.access_count,
268
305
  deleted_at = excluded.deleted_at,
@@ -272,6 +309,8 @@ var _EntryRepository = class _EntryRepository extends BaseRepository {
272
309
  embedding_failure_kind = CASE WHEN excluded.embedding_blob IS NOT NULL THEN NULL ELSE embedding_failure_kind END,
273
310
  embedding_attempts = CASE WHEN excluded.embedding_blob IS NOT NULL THEN 0 ELSE embedding_attempts END,
274
311
  okf_type = excluded.okf_type,
312
+ generated_by = CASE WHEN title IS excluded.title AND body IS excluded.body AND tags IS excluded.tags AND confidence IS excluded.confidence
313
+ THEN generated_by ELSE COALESCE(generated_by, excluded.generated_by) END,
275
314
  derived_events = CASE WHEN ? THEN excluded.derived_events ELSE derived_events END
276
315
  WHERE ${this.prefix}entries.entity_id = excluded.entity_id`,
277
316
  [
@@ -294,7 +333,10 @@ var _EntryRepository = class _EntryRepository extends BaseRepository {
294
333
  fact.okf_type ?? null,
295
334
  // OKF v0.2 metadata — bound for INSERT only; ON CONFLICT UPDATE
296
335
  // preserves the existing row values (these columns are intentionally
297
- // absent from the SET clause above).
336
+ // absent from the SET clause above) — with one exception:
337
+ // `generated_by` IS in the SET, gated by the §C2 CASE (a real
338
+ // content change fills a NULL row actor from this bind; a stored
339
+ // actor is never overwritten).
298
340
  fact.lifecycle_status ?? "stable",
299
341
  fact.stale_after ?? null,
300
342
  fact.generated_by ?? null,
@@ -303,6 +345,11 @@ var _EntryRepository = class _EntryRepository extends BaseRepository {
303
345
  fact.okf_sources ? JSON.stringify(fact.okf_sources) : null,
304
346
  fact.okf_verified ? JSON.stringify(fact.okf_verified) : null,
305
347
  fact.okf_usage_window ? JSON.stringify(fact.okf_usage_window) : null,
348
+ // v0.3 columns (specs/okf-v03 §B8, §C3) — same INSERT-only policy:
349
+ // an in-place engine write preserves both; only upsertForImport
350
+ // overwrites them.
351
+ fact.stale_after_raw ?? null,
352
+ fact.okf_extra ? JSON.stringify(fact.okf_extra) : null,
306
353
  serializeSourcePointer(fact.source_pointer),
307
354
  serializeDerivedEvents(fact.derived_events),
308
355
  // derived_events is writable on conflict (the librarian's in-place
@@ -330,6 +377,12 @@ var _EntryRepository = class _EntryRepository extends BaseRepository {
330
377
  okf_sources: parseJsonArray(existingRow.okf_sources, []),
331
378
  okf_verified: parseJsonArray(existingRow.okf_verified, []),
332
379
  okf_usage_window: parseJsonObject(existingRow.okf_usage_window),
380
+ // Always report the stored values, null when the column is NULL
381
+ // (review 2026-12-04) — same rule as TaskRepository's overlay: a
382
+ // conditional spread leaves the caller's value in the payload when
383
+ // the stored column is NULL, publishing state the row does not hold.
384
+ stale_after_raw: existingRow.stale_after_raw,
385
+ okf_extra: parseJsonObject(existingRow.okf_extra),
333
386
  last_verified_at: existingRow.last_verified_at != null ? Number(existingRow.last_verified_at) : null,
334
387
  last_verified_by: existingRow.last_verified_by ?? null,
335
388
  source_pointer: parseStoredSourcePointer(existingRow.source_pointer),
@@ -338,12 +391,14 @@ var _EntryRepository = class _EntryRepository extends BaseRepository {
338
391
  return stored ? { derived_events: stored } : {};
339
392
  })() : {}
340
393
  } : null;
394
+ const persistedUpdatedAt = existingRow && unchanged ? Number(existingRow.updated_at) : now;
395
+ const persistedGeneratedBy = existingRow ? unchanged ? existingRow.generated_by ?? null : existingRow.generated_by ?? fact.generated_by ?? null : fact.generated_by ?? null;
341
396
  await this.outbox.push({
342
397
  entityId: fact.entity_id,
343
398
  tableName: "entries",
344
399
  recordId: fact.id,
345
400
  operation,
346
- payload: persistedOkf ? { ...fact, ...persistedOkf } : fact
401
+ payload: { ...fact, ...persistedOkf ?? {}, updated_at: persistedUpdatedAt, generated_by: persistedGeneratedBy }
347
402
  }, tx);
348
403
  return result;
349
404
  }
@@ -411,8 +466,9 @@ var _EntryRepository = class _EntryRepository extends BaseRepository {
411
466
  source_hash, source_ref, created_at, updated_at, last_accessed_at, access_count,
412
467
  deleted_at, embedding_blob, embedding, okf_type,
413
468
  lifecycle_status, stale_after, generated_by, last_verified_at, last_verified_by,
414
- okf_sources, okf_verified, okf_usage_window, source_pointer, derived_events
415
- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
469
+ okf_sources, okf_verified, okf_usage_window, stale_after_raw, okf_extra,
470
+ source_pointer, derived_events
471
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
416
472
  ON CONFLICT(id) DO UPDATE SET
417
473
  entity_id = excluded.entity_id,
418
474
  title = excluded.title,
@@ -441,6 +497,8 @@ var _EntryRepository = class _EntryRepository extends BaseRepository {
441
497
  okf_sources = excluded.okf_sources,
442
498
  okf_verified = excluded.okf_verified,
443
499
  okf_usage_window = excluded.okf_usage_window,
500
+ stale_after_raw = excluded.stale_after_raw,
501
+ okf_extra = excluded.okf_extra,
444
502
  source_pointer = CASE WHEN ? THEN excluded.source_pointer ELSE source_pointer END,
445
503
  derived_events = CASE WHEN ? THEN excluded.derived_events ELSE derived_events END`,
446
504
  [
@@ -470,6 +528,12 @@ var _EntryRepository = class _EntryRepository extends BaseRepository {
470
528
  fact.okf_sources ? JSON.stringify(fact.okf_sources) : null,
471
529
  fact.okf_verified ? JSON.stringify(fact.okf_verified) : null,
472
530
  fact.okf_usage_window ? JSON.stringify(fact.okf_usage_window) : null,
531
+ // v0.3 columns (specs/okf-v03 §B8): bound for INSERT and overwritten
532
+ // on conflict — the dump is authoritative here, same replace
533
+ // semantics as the okf columns above. The engine's in-place `upsert`
534
+ // keeps its INSERT-only policy for both (§C3).
535
+ fact.stale_after_raw ?? null,
536
+ fact.okf_extra ? JSON.stringify(fact.okf_extra) : null,
473
537
  serializeSourcePointer(fact.source_pointer),
474
538
  serializeDerivedEvents(fact.derived_events),
475
539
  // The presence flag binds to the SET clause's CASE, AFTER the INSERT
@@ -838,7 +902,7 @@ var _EntryRepository = class _EntryRepository extends BaseRepository {
838
902
  const executor = this.getExecutor(tx);
839
903
  const now = Date.now();
840
904
  const eligibleRows = await executor.getAllAsync(
841
- `SELECT id FROM ${this.prefix}entries
905
+ `SELECT id, generated_by FROM ${this.prefix}entries
842
906
  WHERE entity_id = ? AND confidence = 'inferred'
843
907
  AND (last_accessed_at <= ? OR (last_accessed_at IS NULL AND created_at <= ?))
844
908
  AND source_type != 'immutable_document' AND deleted_at IS NULL`,
@@ -847,9 +911,9 @@ var _EntryRepository = class _EntryRepository extends BaseRepository {
847
911
  if (eligibleRows.length === 0) return [];
848
912
  await executor.runAsync(
849
913
  `UPDATE ${this.prefix}entries
850
- SET confidence = 'tentative', updated_at = ?
914
+ SET confidence = 'tentative', updated_at = ?, generated_by = COALESCE(generated_by, ?)
851
915
  WHERE entity_id = ? AND confidence = 'inferred' AND (last_accessed_at <= ? OR (last_accessed_at IS NULL AND created_at <= ?)) AND source_type != 'immutable_document' AND deleted_at IS NULL`,
852
- [now, entityId, staleThreshold, staleThreshold]
916
+ [now, ENGINE_ACTOR, entityId, staleThreshold, staleThreshold]
853
917
  );
854
918
  for (const row of eligibleRows) {
855
919
  await this.outbox.push({
@@ -857,7 +921,7 @@ var _EntryRepository = class _EntryRepository extends BaseRepository {
857
921
  tableName: "entries",
858
922
  recordId: row.id,
859
923
  operation: "UPDATE",
860
- payload: { id: row.id, entity_id: entityId, confidence: "tentative", updated_at: now }
924
+ payload: { id: row.id, entity_id: entityId, confidence: "tentative", updated_at: now, generated_by: row.generated_by ?? ENGINE_ACTOR }
861
925
  }, tx);
862
926
  }
863
927
  return eligibleRows.map((r) => r.id);
@@ -865,25 +929,38 @@ var _EntryRepository = class _EntryRepository extends BaseRepository {
865
929
  /**
866
930
  * Downgrade specific entries to 'tentative' by IDs.
867
931
  * Used by MaintenanceService.doRunHeal().
932
+ *
933
+ * §C4 (specs/okf-v03, refinement 12): the same COALESCE stamp rule as
934
+ * {@link downgradeStaleInferred}, and only rows whose confidence is not
935
+ * already 'tentative' change — `RETURNING` scopes the staged outbox UPDATEs
936
+ * to the rows actually written, so a repeated verdict against an
937
+ * already-downgraded fact publishes nothing. The row write and its outbox
938
+ * event are skipped; heal's `heal_downgraded` receipt still fires (the
939
+ * model's verdict was applied — MaintenanceService owns the receipt).
940
+ * Returns the ids that changed.
868
941
  */
869
942
  async downgradeByIds(ids, entityId, tx) {
870
- if (ids.length === 0) return;
943
+ if (ids.length === 0) return [];
871
944
  const executor = this.getExecutor(tx);
872
945
  const now = Date.now();
873
946
  const placeholders = ids.map(() => "?").join(",");
874
- await executor.runAsync(
875
- `UPDATE ${this.prefix}entries SET confidence = 'tentative', updated_at = ? WHERE id IN (${placeholders}) AND entity_id = ?`,
876
- [now, ...ids, entityId]
947
+ const changedRows = await executor.getAllAsync(
948
+ `UPDATE ${this.prefix}entries
949
+ SET confidence = 'tentative', updated_at = ?, generated_by = COALESCE(generated_by, ?)
950
+ WHERE id IN (${placeholders}) AND entity_id = ? AND confidence != 'tentative'
951
+ RETURNING id, generated_by`,
952
+ [now, ENGINE_ACTOR, ...ids, entityId]
877
953
  );
878
- for (const id of ids) {
954
+ for (const row of changedRows) {
879
955
  await this.outbox.push({
880
956
  entityId,
881
957
  tableName: "entries",
882
- recordId: id,
958
+ recordId: row.id,
883
959
  operation: "UPDATE",
884
- payload: { id, entity_id: entityId, confidence: "tentative", updated_at: now }
960
+ payload: { id: row.id, entity_id: entityId, confidence: "tentative", updated_at: now, generated_by: row.generated_by ?? ENGINE_ACTOR }
885
961
  }, tx);
886
962
  }
963
+ return changedRows.map((r) => r.id);
887
964
  }
888
965
  /**
889
966
  * Soft-delete specific entries by IDs.
@@ -1179,6 +1256,13 @@ var _EntryRepository = class _EntryRepository extends BaseRepository {
1179
1256
  * come from the exact row that wins MAX(updated_at). The `id ASC` tie-break
1180
1257
  * keeps selection deterministic when two live rows share `updated_at`.
1181
1258
  *
1259
+ * §C2 dependency (specs/okf-v03 refinement 27): the content gate lets an
1260
+ * `upsert` change `source_hash` on a row whose `updated_at` stays put, so
1261
+ * "most recently updated" is no longer guaranteed to mean "most recently
1262
+ * content-written". No shipped caller re-hashes a row in place through
1263
+ * `upsert` today; any future caller that does must be checked against
1264
+ * this ordering.
1265
+ *
1182
1266
  * Source refs are de-duplicated and processed in chunks so the per-query bind
1183
1267
  * parameter count stays under SQLite's `SQLITE_MAX_VARIABLE_NUMBER` (default
1184
1268
  * 999, leaving one slot for `entity_id`).
@@ -1431,7 +1515,7 @@ var _EntryRepository = class _EntryRepository extends BaseRepository {
1431
1515
  if (entityIds.length === 0) return [];
1432
1516
  const executor = this.getExecutor(tx);
1433
1517
  const placeholders = entityIds.map(() => "?").join(",");
1434
- const draftClause = opts?.excludeDrafts === true ? ` AND lifecycle_status != 'draft'` : "";
1518
+ const draftClause = opts?.excludeDrafts === true ? ` AND lifecycle_status IN ('stable','deprecated')` : "";
1435
1519
  const liveClause = opts?.live ? ` AND ${liveAtSql(opts.live.mode)}` : "";
1436
1520
  const liveArgs = opts?.live ? [opts.live.t, opts.live.t] : [];
1437
1521
  const rows = await executor.getAllAsync(
@@ -1440,14 +1524,21 @@ var _EntryRepository = class _EntryRepository extends BaseRepository {
1440
1524
  );
1441
1525
  return rows.map(mapRowToFact);
1442
1526
  }
1443
- /** IDs of live draft facts for the given entities (spec §5.1). Callers pass ≤ 100 entity ids. */
1444
- async findDraftIdsByEntityIds(entityIds, tx) {
1527
+ /**
1528
+ * IDs of live facts that are NOT current knowledge for the given entities
1529
+ * (spec §5.1 drafts, §B4 reads): `lifecycle_status` outside
1530
+ * `('stable','deprecated')` — drafts and unknown statuses. This is the
1531
+ * exclusion set scored search subtracts; `lint().unknownStatus` counts the
1532
+ * non-draft strays and `setLifecycleStatus(id, entityId, 'stable')` clears
1533
+ * them. Callers pass ≤ 100 entity ids.
1534
+ */
1535
+ async findNotCurrentIdsByEntityIds(entityIds, tx) {
1445
1536
  if (entityIds.length === 0) return /* @__PURE__ */ new Set();
1446
1537
  const executor = this.getExecutor(tx);
1447
1538
  const placeholders = entityIds.map(() => "?").join(",");
1448
1539
  const rows = await executor.getAllAsync(
1449
1540
  `SELECT id FROM ${this.prefix}entries
1450
- WHERE entity_id IN (${placeholders}) AND deleted_at IS NULL AND lifecycle_status = 'draft'`,
1541
+ WHERE entity_id IN (${placeholders}) AND deleted_at IS NULL AND lifecycle_status NOT IN ('stable','deprecated')`,
1451
1542
  [...entityIds]
1452
1543
  );
1453
1544
  return new Set(rows.map((r) => r.id));
@@ -1791,6 +1882,9 @@ function mapRowToTask(row) {
1791
1882
  const okf_verified = parseJsonArray(row.okf_verified, []);
1792
1883
  const now = Date.now();
1793
1884
  const staleAfterRaw = row.stale_after != null ? Number(row.stale_after) : null;
1885
+ const staleAfterRawText = row.stale_after_raw != null ? String(row.stale_after_raw) : null;
1886
+ const generatedAt = row.generated_by != null ? Number(row.updated_at) : null;
1887
+ const okfExtra = parseJsonObject(row.okf_extra);
1794
1888
  return {
1795
1889
  id: row.id,
1796
1890
  entity_id: row.entity_id,
@@ -1811,9 +1905,15 @@ function mapRowToTask(row) {
1811
1905
  okf_usage_window: parseJsonObject(row.okf_usage_window),
1812
1906
  last_verified_at: row.last_verified_at != null ? Number(row.last_verified_at) : null,
1813
1907
  last_verified_by: row.last_verified_by ?? null,
1814
- // Spec §2.7 + §5.3: hydrate so read() consumers don't re-call the helpers.
1815
- isStale: isStaleAfter(staleAfterRaw, now),
1816
- trustTier: deriveTrustTier(okf_verified)
1908
+ // v0.3 columns (specs/okf-v03 §F): keys appear only when set; NULL =
1909
+ // nothing to preserve. A malformed stored okf_extra reads as absent.
1910
+ ...staleAfterRawText != null ? { stale_after_raw: staleAfterRawText } : {},
1911
+ ...okfExtra ? { okf_extra: okfExtra } : {},
1912
+ // Spec §2.7 + §5.3: hydrate so read() consumers don't re-call the
1913
+ // helpers. §B3 read rule (refinement 37): raw non-null ⇒ stale — mirror
1914
+ // of the fact side.
1915
+ isStale: staleAfterRawText != null ? true : isStaleAfter(staleAfterRaw, now),
1916
+ trustTier: deriveTrustTier(okf_verified, generatedAt)
1817
1917
  };
1818
1918
  }
1819
1919
  var TaskRepository = class extends BaseRepository {
@@ -1874,6 +1974,14 @@ var TaskRepository = class extends BaseRepository {
1874
1974
  * See {@link EntryRepository.upsert} for the rationale — the same applies
1875
1975
  * symmetrically to tasks (spec §2.5). Callers that need to overwrite OKF
1876
1976
  * metadata should use {@link upsertForImport}.
1977
+ *
1978
+ * §C2/§C5 (specs/okf-v03): the SET gates `updated_at` and `generated_by`
1979
+ * on an `unchanged` predicate over `description`, `priority`, `status`,
1980
+ * `resolved_at` (null-safe `IS`; the `deleted_at` tombstone is outside the
1981
+ * tuple), so a byte-identical re-upsert leaves both untouched. `updatedAt`
1982
+ * is the shared write instant: a write that carries a same-pass
1983
+ * verification passes its event's `at` here so the event reads current
1984
+ * (`>=`, §A2).
1877
1985
  */
1878
1986
  async upsert(task, tx, updatedAt) {
1879
1987
  const executor = this.getExecutor(tx);
@@ -1881,26 +1989,37 @@ var TaskRepository = class extends BaseRepository {
1881
1989
  const existingRow = await executor.getFirstAsync(
1882
1990
  `SELECT id, lifecycle_status, stale_after, generated_by,
1883
1991
  okf_sources, okf_verified, okf_usage_window,
1884
- last_verified_at, last_verified_by
1992
+ stale_after_raw, okf_extra,
1993
+ last_verified_at, last_verified_by,
1994
+ description, status, priority, resolved_at, updated_at
1885
1995
  FROM ${this.prefix}tasks WHERE id = ?`,
1886
1996
  [task.id]
1887
1997
  );
1888
1998
  const operation = task.deleted_at != null ? "DELETE" : existingRow ? "UPDATE" : "INSERT";
1999
+ const storedPriority = (v) => {
2000
+ if (v === null || v === void 0) return null;
2001
+ const n = Number(v);
2002
+ return Number.isFinite(n) ? n : String(v);
2003
+ };
2004
+ const unchanged = existingRow != null && (existingRow.description ?? null) === (task.description ?? null) && Object.is(storedPriority(existingRow.priority), storedPriority(task.priority)) && (existingRow.status ?? null) === (task.status ?? null) && (existingRow.resolved_at != null ? Number(existingRow.resolved_at) : null) === (task.resolved_at != null ? Number(task.resolved_at) : null);
1889
2005
  await executor.runAsync(
1890
2006
  `INSERT INTO ${this.prefix}tasks (
1891
2007
  id, entity_id, description, status, priority,
1892
2008
  created_at, updated_at, resolved_at, deleted_at,
1893
2009
  lifecycle_status, stale_after, generated_by, last_verified_at, last_verified_by,
1894
- okf_sources, okf_verified, okf_usage_window
1895
- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
2010
+ okf_sources, okf_verified, okf_usage_window, stale_after_raw, okf_extra
2011
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
1896
2012
  ON CONFLICT(id) DO UPDATE SET
1897
2013
  entity_id = excluded.entity_id,
1898
2014
  description = excluded.description,
1899
2015
  status = excluded.status,
1900
2016
  priority = excluded.priority,
1901
- updated_at = excluded.updated_at,
2017
+ updated_at = CASE WHEN description IS excluded.description AND priority IS excluded.priority AND status IS excluded.status AND resolved_at IS excluded.resolved_at
2018
+ THEN updated_at ELSE excluded.updated_at END,
1902
2019
  resolved_at = excluded.resolved_at,
1903
- deleted_at = excluded.deleted_at`,
2020
+ deleted_at = excluded.deleted_at,
2021
+ generated_by = CASE WHEN description IS excluded.description AND priority IS excluded.priority AND status IS excluded.status AND resolved_at IS excluded.resolved_at
2022
+ THEN generated_by ELSE COALESCE(generated_by, excluded.generated_by) END`,
1904
2023
  [
1905
2024
  task.id,
1906
2025
  task.entity_id,
@@ -1914,7 +2033,10 @@ var TaskRepository = class extends BaseRepository {
1914
2033
  task.deleted_at ?? null,
1915
2034
  // OKF v0.2 metadata — bound for INSERT only; ON CONFLICT UPDATE
1916
2035
  // preserves the existing row values (these columns are intentionally
1917
- // absent from the SET clause above).
2036
+ // absent from the SET clause above) — with one exception:
2037
+ // `generated_by` IS in the SET, gated by the §C2 CASE (a real
2038
+ // content change fills a NULL row actor from this bind; a stored
2039
+ // actor is never overwritten).
1918
2040
  task.lifecycle_status ?? "stable",
1919
2041
  task.stale_after ?? null,
1920
2042
  task.generated_by ?? null,
@@ -1922,7 +2044,12 @@ var TaskRepository = class extends BaseRepository {
1922
2044
  task.last_verified_by ?? null,
1923
2045
  task.okf_sources ? JSON.stringify(task.okf_sources) : null,
1924
2046
  task.okf_verified ? JSON.stringify(task.okf_verified) : null,
1925
- task.okf_usage_window ? JSON.stringify(task.okf_usage_window) : null
2047
+ task.okf_usage_window ? JSON.stringify(task.okf_usage_window) : null,
2048
+ // v0.3 columns (specs/okf-v03 §B8, §C3) — same INSERT-only policy:
2049
+ // an in-place engine write preserves both; only upsertForImport
2050
+ // overwrites them.
2051
+ task.stale_after_raw ?? null,
2052
+ task.okf_extra ? JSON.stringify(task.okf_extra) : null
1926
2053
  ]
1927
2054
  );
1928
2055
  const persistedOkf = existingRow ? {
@@ -1932,16 +2059,25 @@ var TaskRepository = class extends BaseRepository {
1932
2059
  okf_sources: parseJsonArray(existingRow.okf_sources, []),
1933
2060
  okf_verified: parseJsonArray(existingRow.okf_verified, []),
1934
2061
  okf_usage_window: parseJsonObject(existingRow.okf_usage_window),
2062
+ // Always report the stored values, null when the column is NULL
2063
+ // (review 2026-12-04): the conditional spreads left the caller's
2064
+ // `task.stale_after_raw`/`task.okf_extra` in the payload when the
2065
+ // stored column was NULL — publishing metadata the row does not
2066
+ // contain, against the mirror rule the overlay exists for.
2067
+ stale_after_raw: existingRow.stale_after_raw,
2068
+ okf_extra: parseJsonObject(existingRow.okf_extra),
1935
2069
  last_verified_at: existingRow.last_verified_at != null ? Number(existingRow.last_verified_at) : null,
1936
2070
  last_verified_by: existingRow.last_verified_by ?? null
1937
2071
  } : null;
2072
+ const persistedUpdatedAt = existingRow && unchanged ? Number(existingRow.updated_at) : now;
2073
+ const persistedGeneratedBy = existingRow ? unchanged ? existingRow.generated_by ?? null : existingRow.generated_by ?? task.generated_by ?? null : task.generated_by ?? null;
1938
2074
  await this.outbox.push(
1939
2075
  {
1940
2076
  entityId: task.entity_id,
1941
2077
  tableName: "tasks",
1942
2078
  recordId: task.id,
1943
2079
  operation,
1944
- payload: persistedOkf ? { ...task, ...persistedOkf } : task
2080
+ payload: { ...task, ...persistedOkf ?? {}, updated_at: persistedUpdatedAt, generated_by: persistedGeneratedBy }
1945
2081
  },
1946
2082
  tx
1947
2083
  );
@@ -1954,8 +2090,8 @@ var TaskRepository = class extends BaseRepository {
1954
2090
  id, entity_id, description, status, priority,
1955
2091
  created_at, updated_at, resolved_at, deleted_at, okf_type,
1956
2092
  lifecycle_status, stale_after, generated_by, last_verified_at, last_verified_by,
1957
- okf_sources, okf_verified, okf_usage_window
1958
- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
2093
+ okf_sources, okf_verified, okf_usage_window, stale_after_raw, okf_extra
2094
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
1959
2095
  ON CONFLICT(id) DO UPDATE SET
1960
2096
  entity_id = excluded.entity_id,
1961
2097
  description = excluded.description,
@@ -1972,7 +2108,9 @@ var TaskRepository = class extends BaseRepository {
1972
2108
  last_verified_by = excluded.last_verified_by,
1973
2109
  okf_sources = excluded.okf_sources,
1974
2110
  okf_verified = excluded.okf_verified,
1975
- okf_usage_window = excluded.okf_usage_window`,
2111
+ okf_usage_window = excluded.okf_usage_window,
2112
+ stale_after_raw = excluded.stale_after_raw,
2113
+ okf_extra = excluded.okf_extra`,
1976
2114
  [
1977
2115
  task.id,
1978
2116
  task.entity_id,
@@ -1991,7 +2129,13 @@ var TaskRepository = class extends BaseRepository {
1991
2129
  task.last_verified_by ?? null,
1992
2130
  task.okf_sources ? JSON.stringify(task.okf_sources) : null,
1993
2131
  task.okf_verified ? JSON.stringify(task.okf_verified) : null,
1994
- task.okf_usage_window ? JSON.stringify(task.okf_usage_window) : null
2132
+ task.okf_usage_window ? JSON.stringify(task.okf_usage_window) : null,
2133
+ // v0.3 columns (specs/okf-v03 §B8): bound for INSERT and overwritten
2134
+ // on conflict — the dump is authoritative here, mirroring
2135
+ // EntryRepository.upsertForImport. The engine's in-place `upsert`
2136
+ // keeps its INSERT-only policy for both (§C3).
2137
+ task.stale_after_raw ?? null,
2138
+ task.okf_extra ? JSON.stringify(task.okf_extra) : null
1995
2139
  ]
1996
2140
  );
1997
2141
  }
@@ -4107,6 +4251,7 @@ var LintRepository = class extends BaseRepository {
4107
4251
  `SELECT
4108
4252
  SUM(CASE WHEN okf_type IS NULL THEN 1 ELSE 0 END) AS untyped,
4109
4253
  SUM(CASE WHEN lifecycle_status = 'draft' THEN 1 ELSE 0 END) AS drafts,
4254
+ SUM(CASE WHEN lifecycle_status NOT IN ('stable','draft','deprecated') THEN 1 ELSE 0 END) AS unknown_status,
4110
4255
  SUM(CASE WHEN source_type = 'librarian_inferred'
4111
4256
  AND COALESCE(json_array_length(CASE WHEN json_valid(okf_verified) THEN okf_verified END), 0) = 0
4112
4257
  THEN 1 ELSE 0 END) AS unverified
@@ -4117,6 +4262,7 @@ var LintRepository = class extends BaseRepository {
4117
4262
  return {
4118
4263
  untypedFacts: Number(row?.untyped ?? 0),
4119
4264
  drafts: Number(row?.drafts ?? 0),
4265
+ unknownStatus: Number(row?.unknown_status ?? 0),
4120
4266
  unverifiedInferred: Number(row?.unverified ?? 0)
4121
4267
  };
4122
4268
  }
@@ -4245,8 +4391,21 @@ var OkfTrustWritesRepository = class {
4245
4391
  * other's events (the previous implementation serialized only the supplied
4246
4392
  * array and overwrote, dropping any pre-existing history).
4247
4393
  *
4248
- * Sets the `last_verified_*` convenience columns from the latest event in
4249
- * the union (computed in code; see {@link latestVerified}).
4394
+ * Each element is rebuilt as `json_patch(old_entry, {by, at})`, not
4395
+ * `json_object('by', …, 'at', …)`, so stored entries keep their `x-` extras
4396
+ * across appends (spec okf-v03 §C landmine, refinement 29).
4397
+ *
4398
+ * Sets the `last_verified_*` convenience columns from the CALLER-PASSED
4399
+ * event list (review T3-tail7 #3 — the columns mirror the append batch,
4400
+ * not the post-merge history: a host that backfills an older event owns
4401
+ * the resulting value).
4402
+ *
4403
+ * Two §B8/§13.4 behaviors worth stating (review T4-R2 #4): the append is a
4404
+ * JSON merge-patch, so a stored event member patched with an absent `by` /
4405
+ * `at` loses that key (merge-patch null-deletes) rather than persisting an
4406
+ * explicit `null`; and every extra key the caller passes on an event rides
4407
+ * the stored JSON verbatim — inline extras for `verified[]` are the
4408
+ * documented §13.4 home, validated only by the §A3c wire bound at import.
4250
4409
  */
4251
4410
  async writeOkfTrust(entryId, entityId, verified, tx) {
4252
4411
  const executor = this.getExecutor(tx);
@@ -4256,13 +4415,15 @@ var OkfTrustWritesRepository = class {
4256
4415
  await executor.runAsync(
4257
4416
  `UPDATE ${this.prefix}entries
4258
4417
  SET okf_verified = COALESCE(
4259
- (SELECT json_group_array(json_object('by', s.by_val, 'at', s.at_val))
4418
+ (SELECT json_group_array(json_patch(s.old_entry, json_object('by', s.by_val, 'at', s.at_val)))
4260
4419
  FROM (
4261
- SELECT json_extract(value, '$.by') AS by_val,
4420
+ SELECT value AS old_entry,
4421
+ json_extract(value, '$.by') AS by_val,
4262
4422
  json_extract(value, '$.at') AS at_val
4263
4423
  FROM json_each(okf_verified)
4264
4424
  UNION ALL
4265
- SELECT json_extract(value, '$.by'),
4425
+ SELECT value,
4426
+ json_extract(value, '$.by'),
4266
4427
  json_extract(value, '$.at')
4267
4428
  FROM json_each(?)
4268
4429
  ) AS s
@@ -4296,12 +4457,19 @@ var OkfTrustWritesRepository = class {
4296
4457
  [status, entryId, entityId]
4297
4458
  );
4298
4459
  }
4299
- /** Set the absolute cutoff (epoch ms) for staleness, or NULL to clear. */
4460
+ /**
4461
+ * Set the absolute cutoff (epoch ms) for staleness, or NULL to clear.
4462
+ * §B3 mutual exclusivity (owner review fix 5): a valid cutoff clears
4463
+ * `stale_after_raw` — an old unparseable value must never survive a later
4464
+ * valid write and pin `isStale` true forever — and clearing NULLs both.
4465
+ * Does NOT touch `updated_at`.
4466
+ */
4300
4467
  async setStaleAfter(entryId, entityId, date, tx) {
4301
4468
  const executor = this.getExecutor(tx);
4302
4469
  await executor.runAsync(
4303
4470
  `UPDATE ${this.prefix}entries
4304
- SET stale_after = ?
4471
+ SET stale_after = ?,
4472
+ stale_after_raw = NULL
4305
4473
  WHERE id = ? AND entity_id = ?`,
4306
4474
  [date, entryId, entityId]
4307
4475
  );
@@ -4327,13 +4495,15 @@ var OkfTrustWritesRepository = class {
4327
4495
  await executor.runAsync(
4328
4496
  `UPDATE ${this.prefix}tasks
4329
4497
  SET okf_verified = COALESCE(
4330
- (SELECT json_group_array(json_object('by', s.by_val, 'at', s.at_val))
4498
+ (SELECT json_group_array(json_patch(s.old_entry, json_object('by', s.by_val, 'at', s.at_val)))
4331
4499
  FROM (
4332
- SELECT json_extract(value, '$.by') AS by_val,
4500
+ SELECT value AS old_entry,
4501
+ json_extract(value, '$.by') AS by_val,
4333
4502
  json_extract(value, '$.at') AS at_val
4334
4503
  FROM json_each(okf_verified)
4335
4504
  UNION ALL
4336
- SELECT json_extract(value, '$.by'),
4505
+ SELECT value,
4506
+ json_extract(value, '$.by'),
4337
4507
  json_extract(value, '$.at')
4338
4508
  FROM json_each(?)
4339
4509
  ) AS s
@@ -4365,11 +4535,13 @@ var OkfTrustWritesRepository = class {
4365
4535
  [status, taskId, entityId]
4366
4536
  );
4367
4537
  }
4538
+ /** Task variant of {@link setStaleAfter} — §B3 pair exclusivity included. */
4368
4539
  async setStaleAfterTask(taskId, entityId, date, tx) {
4369
4540
  const executor = this.getExecutor(tx);
4370
4541
  await executor.runAsync(
4371
4542
  `UPDATE ${this.prefix}tasks
4372
- SET stale_after = ?
4543
+ SET stale_after = ?,
4544
+ stale_after_raw = NULL
4373
4545
  WHERE id = ? AND entity_id = ?`,
4374
4546
  [date, taskId, entityId]
4375
4547
  );
@@ -6052,7 +6224,10 @@ function formatMemoryDump(dump) {
6052
6224
  files
6053
6225
  };
6054
6226
  }
6055
- var DEFAULT_PROFILE = "llm-wiki/2";
6227
+ var DEFAULT_PROFILE = "llm-wiki/3";
6228
+ var FACT_MAPPED = new Set(FACT_MAPPED_KEYS);
6229
+ var TASK_MAPPED = new Set(TASK_MAPPED_KEYS);
6230
+ var RAW_SLOT_KEY = "x-llm-wiki-raw";
6056
6231
  function isoOrFallback(updatedAt) {
6057
6232
  if (!Number.isFinite(updatedAt)) return (/* @__PURE__ */ new Date(0)).toISOString();
6058
6233
  const d = new Date(updatedAt);
@@ -6065,6 +6240,62 @@ function isoDateOrOmit(ms) {
6065
6240
  if (!Number.isFinite(d.getTime())) return void 0;
6066
6241
  return d.toISOString().slice(0, 10);
6067
6242
  }
6243
+ function staleAfterFrontmatterV3(staleAfter, staleAfterRaw) {
6244
+ if (staleAfterRaw != null && staleAfterRaw !== "") return { stale_after: staleAfterRaw };
6245
+ if (staleAfter == null || !Number.isFinite(staleAfter)) return {};
6246
+ const d = new Date(staleAfter);
6247
+ if (!Number.isFinite(d.getTime())) return {};
6248
+ const utcMidnight = d.getUTCHours() === 0 && d.getUTCMinutes() === 0 && d.getUTCSeconds() === 0 && d.getUTCMilliseconds() === 0;
6249
+ return { stale_after: utcMidnight ? d.toISOString().slice(0, 10) : d.toISOString() };
6250
+ }
6251
+ function plainObjectOrNull(value) {
6252
+ return value !== null && typeof value === "object" && !Array.isArray(value) ? value : null;
6253
+ }
6254
+ function okfExtraEmission(okfExtra, mapped) {
6255
+ const emission = { extras: {}, generatedNested: {}, rawBlocks: [] };
6256
+ const extra = plainObjectOrNull(okfExtra);
6257
+ if (!extra) return emission;
6258
+ for (const [key, value] of Object.entries(extra)) {
6259
+ if (key === RAW_SLOT_KEY) continue;
6260
+ if (key === "generated") {
6261
+ const nested = plainObjectOrNull(value);
6262
+ if (nested) {
6263
+ for (const [k, v] of Object.entries(nested)) {
6264
+ if (k === "by" || k === "at") continue;
6265
+ if (k === "__proto__") continue;
6266
+ emission.generatedNested[k] = v;
6267
+ }
6268
+ }
6269
+ continue;
6270
+ }
6271
+ if (mapped.has(key)) continue;
6272
+ if (key === "__proto__") continue;
6273
+ emission.extras[key] = value;
6274
+ }
6275
+ for (const [key, value] of Object.entries(extra)) {
6276
+ if (key !== RAW_SLOT_KEY) continue;
6277
+ const slot = plainObjectOrNull(value);
6278
+ if (slot) {
6279
+ for (const [blockKey, lines] of Object.entries(slot)) {
6280
+ if (mapped.has(blockKey)) continue;
6281
+ if (Object.prototype.hasOwnProperty.call(emission.extras, blockKey)) {
6282
+ const value2 = emission.extras[blockKey];
6283
+ const text = typeof lines === "string" ? lines.slice(lines.indexOf(":") + 1).trim() : "";
6284
+ const same = typeof value2 === "number" && text !== "" && Number(text) === value2 || typeof value2 === "string" && text === value2.trim();
6285
+ if (same && typeof lines === "string" && lines.length > 0) {
6286
+ emission.rawBlocks.push(lines);
6287
+ }
6288
+ continue;
6289
+ }
6290
+ if (typeof lines === "string" && lines.length > 0 && isValidRawBlockEntry(blockKey, lines, mapped)) {
6291
+ emission.rawBlocks.push(lines);
6292
+ }
6293
+ }
6294
+ }
6295
+ continue;
6296
+ }
6297
+ return emission;
6298
+ }
6068
6299
  function sourcePointerFrontmatter(p) {
6069
6300
  if (!p) return void 0;
6070
6301
  return {
@@ -6076,7 +6307,7 @@ function sourcePointerFrontmatter(p) {
6076
6307
  }
6077
6308
  function factFrontmatterV2(f) {
6078
6309
  return {
6079
- type: f.okf_type ?? "fact",
6310
+ type: f.okf_type || "fact",
6080
6311
  title: f.title,
6081
6312
  tags: f.tags,
6082
6313
  // `timestamp` rides along deliberately even on the v0.2 path — a naive
@@ -6122,7 +6353,7 @@ function factFrontmatterV2(f) {
6122
6353
  }
6123
6354
  function taskFrontmatterV2(t) {
6124
6355
  return {
6125
- type: t.okf_type ?? "task",
6356
+ type: t.okf_type || "task",
6126
6357
  title: t.description,
6127
6358
  timestamp: isoOrFallback(t.updated_at),
6128
6359
  // see factFrontmatterV2 comment — deliberate back-compat duplication
@@ -6146,9 +6377,34 @@ function taskFrontmatterV2(t) {
6146
6377
  ...t.okf_usage_window ? { usage_window: t.okf_usage_window } : {}
6147
6378
  };
6148
6379
  }
6380
+ function wireProjectionV3(f, dumpGeneratedAt, idToConceptPath) {
6381
+ const stored = f.lifecycle_status ?? "stable";
6382
+ const ended = Number.isFinite(dumpGeneratedAt) && f.valid_to != null && f.valid_to <= dumpGeneratedAt;
6383
+ return {
6384
+ ...f.superseded_by != null && idToConceptPath.has(f.superseded_by) ? { superseded_by: `/${idToConceptPath.get(f.superseded_by)}` } : {},
6385
+ ...ended && stored !== "deprecated" ? { status: "deprecated", "x-llm-wiki-lifecycle": stored } : {}
6386
+ };
6387
+ }
6388
+ function factFrontmatterV3(f, emission, projection = {}) {
6389
+ return {
6390
+ ...factFrontmatterV2(f),
6391
+ ...projection,
6392
+ ...staleAfterFrontmatterV3(f.stale_after, f.stale_after_raw),
6393
+ ...f.generated_by ? { generated: { by: f.generated_by, at: isoOrFallback(f.updated_at), ...emission.generatedNested } } : {},
6394
+ ...emission.extras
6395
+ };
6396
+ }
6397
+ function taskFrontmatterV3(t, emission) {
6398
+ return {
6399
+ ...taskFrontmatterV2(t),
6400
+ ...staleAfterFrontmatterV3(t.stale_after, t.stale_after_raw),
6401
+ ...t.generated_by ? { generated: { by: t.generated_by, at: isoOrFallback(t.updated_at), ...emission.generatedNested } } : {},
6402
+ ...emission.extras
6403
+ };
6404
+ }
6149
6405
  function factFrontmatterV1(f) {
6150
6406
  return {
6151
- type: f.okf_type ?? "fact",
6407
+ type: f.okf_type || "fact",
6152
6408
  title: f.title,
6153
6409
  tags: f.tags,
6154
6410
  timestamp: isoOrFallback(f.updated_at),
@@ -6170,7 +6426,7 @@ function factFrontmatterV1(f) {
6170
6426
  }
6171
6427
  function taskFrontmatterV1(t) {
6172
6428
  return {
6173
- type: t.okf_type ?? "task",
6429
+ type: t.okf_type || "task",
6174
6430
  title: t.description,
6175
6431
  timestamp: isoOrFallback(t.updated_at),
6176
6432
  id: t.id,
@@ -6208,11 +6464,15 @@ var OKF_DATE_MIN = -621672192e5;
6208
6464
  var OKF_DATE_MAX = 253402300799999;
6209
6465
  function formatOkfBundle(dump, options) {
6210
6466
  const profile = options?.profile ?? DEFAULT_PROFILE;
6211
- const okfVersion = profile === "llm-wiki/2" ? "0.2" : "0.1";
6212
- const factFm = profile === "llm-wiki/2" ? factFrontmatterV2 : factFrontmatterV1;
6213
- const taskFm = profile === "llm-wiki/2" ? taskFrontmatterV2 : taskFrontmatterV1;
6467
+ const isV3 = profile === "llm-wiki/3";
6468
+ const okfVersion = profile === "llm-wiki/1" ? "0.1" : profile === "llm-wiki/2" ? "0.2" : "0.3";
6469
+ const factFm = profile === "llm-wiki/1" ? factFrontmatterV1 : factFrontmatterV2;
6470
+ const taskFm = profile === "llm-wiki/1" ? taskFrontmatterV1 : taskFrontmatterV2;
6214
6471
  const files = [];
6215
6472
  const rootEntries = [];
6473
+ const entityBundles = Object.values(dump.entities);
6474
+ const carried = entityBundles.map((b) => b.bundleMetadata).filter((m) => m !== void 0);
6475
+ const bundleMetadata = dump.bundleMetadata !== void 0 ? dump.bundleMetadata : entityBundles.length === 1 && carried.length === 1 ? carried[0] : void 0;
6216
6476
  for (const [entityId, bundle] of Object.entries(dump.entities)) {
6217
6477
  let relatedLinksFor2 = function(sourcePath, sourceId) {
6218
6478
  return (edgesBySource.get(sourceId) ?? []).map((edge) => {
@@ -6245,10 +6505,21 @@ function formatOkfBundle(dump, options) {
6245
6505
  for (const f of bundle.facts) {
6246
6506
  const factPath = `entities/${dir}/facts/${factIdToFilename.get(f.id)}.md`;
6247
6507
  const factBody = appendRelatedSection(f.body, relatedLinksFor2(factPath, f.id));
6248
- files.push({
6249
- path: factPath,
6250
- content: buildConceptDocument(factFm(f), factBody)
6251
- });
6508
+ let content;
6509
+ if (isV3) {
6510
+ const emission = okfExtraEmission(f.okf_extra, FACT_MAPPED);
6511
+ content = buildConceptDocument(
6512
+ factFrontmatterV3(f, emission, wireProjectionV3(f, dump.generatedAt, idToConceptPath)),
6513
+ factBody,
6514
+ // §A7/§B8: the stored raw lines go out verbatim, after the builder's
6515
+ // keys; the option is omitted so an extras-free row keeps the exact
6516
+ // pre-v0.3 bytes.
6517
+ emission.rawBlocks.length > 0 ? { rawBlocks: emission.rawBlocks } : void 0
6518
+ );
6519
+ } else {
6520
+ content = buildConceptDocument(factFm(f), factBody);
6521
+ }
6522
+ files.push({ path: factPath, content });
6252
6523
  }
6253
6524
  const taskEntries = bundle.tasks.map((t) => ({
6254
6525
  path: `tasks/${sanitizeConceptId(t.id)}.md`,
@@ -6257,10 +6528,18 @@ function formatOkfBundle(dump, options) {
6257
6528
  for (const t of bundle.tasks) {
6258
6529
  const taskPath = `entities/${dir}/tasks/${sanitizeConceptId(t.id)}.md`;
6259
6530
  const taskBody = appendRelatedSection("", relatedLinksFor2(taskPath, t.id));
6260
- files.push({
6261
- path: taskPath,
6262
- content: buildConceptDocument(taskFm(t), taskBody)
6263
- });
6531
+ let content;
6532
+ if (isV3) {
6533
+ const emission = okfExtraEmission(t.okf_extra, TASK_MAPPED);
6534
+ content = buildConceptDocument(
6535
+ taskFrontmatterV3(t, emission),
6536
+ taskBody,
6537
+ emission.rawBlocks.length > 0 ? { rawBlocks: emission.rawBlocks } : void 0
6538
+ );
6539
+ } else {
6540
+ content = buildConceptDocument(taskFm(t), taskBody);
6541
+ }
6542
+ files.push({ path: taskPath, content });
6264
6543
  }
6265
6544
  files.push({
6266
6545
  path: `entities/${dir}/log.md`,
@@ -6284,437 +6563,13 @@ function formatOkfBundle(dump, options) {
6284
6563
  content: buildRootIndexMd(
6285
6564
  okfVersion,
6286
6565
  rootEntries.length > 0 ? [{ heading: "Entities", entries: rootEntries }] : [],
6287
- { profile }
6566
+ // Omitted when no record is emitted — a metadata-free dump keeps its
6567
+ // exact current root index, byte for byte.
6568
+ { profile, ...bundleMetadata !== void 0 ? { bundleMetadata } : {} }
6288
6569
  )
6289
6570
  });
6290
6571
  return { files };
6291
6572
  }
6292
- var CONFIDENCE_VALUES2 = /* @__PURE__ */ new Set(["certain", "inferred", "tentative"]);
6293
- var SOURCE_TYPES = /* @__PURE__ */ new Set([
6294
- "user_stated",
6295
- "librarian_inferred",
6296
- "user_confirmed",
6297
- "immutable_document"
6298
- ]);
6299
- var TASK_STATUSES = /* @__PURE__ */ new Set(["pending", "in_progress", "done", "abandoned"]);
6300
- var EVENT_TYPES = /* @__PURE__ */ new Set(["observation", "decision", "action", "outcome"]);
6301
- function basenameMd(filePath) {
6302
- const name = filePath.slice(filePath.lastIndexOf("/") + 1);
6303
- return name.endsWith(".md") ? name.slice(0, -3) : name;
6304
- }
6305
- function isConceptFile(filePath) {
6306
- if (!filePath.endsWith(".md")) return false;
6307
- if (filePath.endsWith("/index.md") || filePath === "index.md") return false;
6308
- if (filePath.endsWith("/log.md") || filePath === "log.md") return false;
6309
- return true;
6310
- }
6311
- function isStructuralPath(filePath) {
6312
- return filePath.endsWith("/index.md") || filePath === "index.md" || filePath.endsWith("/log.md") || filePath === "log.md";
6313
- }
6314
- function posixDirname(filePath) {
6315
- const idx = filePath.lastIndexOf("/");
6316
- return idx === -1 ? "" : filePath.slice(0, idx);
6317
- }
6318
- function resolveRelativePath(fromFile, linkPath) {
6319
- const baseDir = posixDirname(fromFile);
6320
- const segments = [...baseDir ? baseDir.split("/") : [], ...linkPath.split("/")];
6321
- const resolved = [];
6322
- for (const seg of segments) {
6323
- if (seg === "" || seg === ".") continue;
6324
- if (seg === "..") {
6325
- resolved.pop();
6326
- continue;
6327
- }
6328
- resolved.push(seg);
6329
- }
6330
- return resolved.join("/");
6331
- }
6332
- function decodeLinkPath(path) {
6333
- if (!path.includes("%")) return path;
6334
- try {
6335
- return decodeURIComponent(path);
6336
- } catch {
6337
- return path;
6338
- }
6339
- }
6340
- function addPathAliases(map, filePath, resolvedId) {
6341
- map.set(filePath, resolvedId);
6342
- const withoutDot = filePath.replace(/^\.\//, "");
6343
- if (withoutDot !== filePath) map.set(withoutDot, resolvedId);
6344
- const entityRelative = filePath.replace(/^entities\/[^/]+\//, "");
6345
- if (entityRelative !== filePath) {
6346
- map.set(entityRelative, resolvedId);
6347
- map.set(`./${entityRelative}`, resolvedId);
6348
- }
6349
- }
6350
- function lookupResolvedId(map, path) {
6351
- const normalized = path.replace(/^\.\//, "");
6352
- return map.get(path) ?? map.get(normalized) ?? map.get(`./${normalized}`);
6353
- }
6354
- function stripLinkSuffix(linkPath) {
6355
- const hashIdx = linkPath.indexOf("#");
6356
- const queryIdx = linkPath.indexOf("?");
6357
- if (hashIdx === -1 && queryIdx === -1) return linkPath;
6358
- const cut = hashIdx === -1 ? queryIdx : queryIdx === -1 ? hashIdx : Math.min(hashIdx, queryIdx);
6359
- return linkPath.slice(0, cut);
6360
- }
6361
- function resolveRoute(filePath, frontmatterType, options) {
6362
- if (options?.typeMapping && Object.prototype.hasOwnProperty.call(options.typeMapping, frontmatterType)) {
6363
- return options.typeMapping[frontmatterType];
6364
- }
6365
- if (filePath.includes("/facts/")) return "fact";
6366
- if (filePath.includes("/tasks/")) return "task";
6367
- return options?.defaultSchema ?? "fact";
6368
- }
6369
- function parseFrontmatterTimestamp(value, fallback) {
6370
- if (typeof value === "number" && Number.isFinite(value)) return value;
6371
- if (typeof value === "string") {
6372
- const parsed = Date.parse(value);
6373
- if (Number.isFinite(parsed)) return parsed;
6374
- }
6375
- return fallback;
6376
- }
6377
- function parseStaleAfterRaw(raw) {
6378
- if (typeof raw !== "string") return null;
6379
- const m = /^(\d{4})-(\d{2})-(\d{2})$/.exec(raw);
6380
- if (!m) return null;
6381
- const year = Number(m[1]);
6382
- const month = Number(m[2]);
6383
- const day = Number(m[3]);
6384
- const ms = Date.UTC(year, month - 1, day);
6385
- if (!Number.isFinite(ms)) return null;
6386
- const d = new Date(ms);
6387
- if (d.getUTCFullYear() !== year || d.getUTCMonth() + 1 !== month || d.getUTCDate() !== day) {
6388
- return null;
6389
- }
6390
- return ms;
6391
- }
6392
- function replaceLoneSurrogates(s) {
6393
- let out = "";
6394
- for (let i = 0; i < s.length; i++) {
6395
- const c = s.charCodeAt(i);
6396
- if (c >= 55296 && c <= 56319) {
6397
- const n = i + 1 < s.length ? s.charCodeAt(i + 1) : 0;
6398
- if (n >= 56320 && n <= 57343) {
6399
- out += s[i] + s[i + 1];
6400
- i++;
6401
- } else out += "\uFFFD";
6402
- } else if (c >= 56320 && c <= 57343) {
6403
- out += "\uFFFD";
6404
- } else {
6405
- out += s[i];
6406
- }
6407
- }
6408
- return out;
6409
- }
6410
- function unescapeLogSummary(summary) {
6411
- return summary.replace(/\\\]/g, "]").replace(/\\\[/g, "[").replace(/\\\\/g, "\\");
6412
- }
6413
- var LOG_LINE_PATTERN = /^\(([^)]+)\)\s*(?:\[((?:\\.|[^\[\]\\])*)\]\(([^)]+)\)|(\S.*))$/;
6414
- function parseLogEntryText(text) {
6415
- const match = LOG_LINE_PATTERN.exec(text.trim());
6416
- if (!match) return null;
6417
- const [, rawType, linkedSummary, linkPath, plainSummary] = match;
6418
- const event_type = EVENT_TYPES.has(rawType) ? rawType : "observation";
6419
- if (linkPath) {
6420
- return { event_type, summary: unescapeLogSummary(linkedSummary), linkPath };
6421
- }
6422
- return { event_type, summary: unescapeLogSummary((plainSummary ?? "").trim()) };
6423
- }
6424
- function frontmatterToFact(entityId, id, frontmatter, body, now, droppedPointerValues) {
6425
- const created_at = parseFrontmatterTimestamp(frontmatter.created_at, now);
6426
- const updated_at = parseFrontmatterTimestamp(
6427
- frontmatter.generated?.at,
6428
- parseFrontmatterTimestamp(
6429
- frontmatter.timestamp,
6430
- parseFrontmatterTimestamp(frontmatter.updated_at, now)
6431
- )
6432
- );
6433
- const verified = parseVerifiedFlexible(frontmatter.verified);
6434
- const rawSources = frontmatter.sources;
6435
- const hasSourcesKey = rawSources !== void 0;
6436
- const sources = Array.isArray(rawSources) ? rawSources : [];
6437
- const usageWindow = frontmatter.usage_window && typeof frontmatter.usage_window === "object" ? frontmatter.usage_window : null;
6438
- const lastV = latestVerified(verified, now);
6439
- const lifecycleRaw = frontmatter.status;
6440
- const lifecycle_status = lifecycleRaw === "draft" || lifecycleRaw === "stable" || lifecycleRaw === "deprecated" ? lifecycleRaw : "stable";
6441
- const staleAfterRaw = frontmatter.stale_after;
6442
- const stale_after = parseStaleAfterRaw(staleAfterRaw);
6443
- const generated_by = frontmatter.generated?.by ?? null;
6444
- if (!hasSourcesKey) {
6445
- const urls = parseCitationsList(body);
6446
- for (const url of urls) {
6447
- sources.push({ resource: url });
6448
- }
6449
- }
6450
- return {
6451
- id,
6452
- entity_id: entityId,
6453
- title: typeof frontmatter.title === "string" ? frontmatter.title : "",
6454
- body,
6455
- tags: Array.isArray(frontmatter.tags) ? frontmatter.tags.filter((t) => typeof t === "string") : [],
6456
- confidence: CONFIDENCE_VALUES2.has(String(frontmatter.confidence)) ? frontmatter.confidence : "tentative",
6457
- source_type: SOURCE_TYPES.has(String(frontmatter.source_type)) ? frontmatter.source_type : "user_stated",
6458
- source_hash: typeof frontmatter.source_hash === "string" ? frontmatter.source_hash : null,
6459
- source_ref: typeof frontmatter.resource === "string" ? frontmatter.resource : null,
6460
- created_at,
6461
- updated_at,
6462
- last_accessed_at: frontmatter.last_accessed_at != null ? parseFrontmatterTimestamp(frontmatter.last_accessed_at, now) : null,
6463
- access_count: typeof frontmatter.access_count === "number" ? frontmatter.access_count : 0,
6464
- deleted_at: frontmatter.deleted_at != null ? parseFrontmatterTimestamp(frontmatter.deleted_at, 0) : null,
6465
- okf_type: frontmatter.type,
6466
- // OKF v0.2
6467
- lifecycle_status,
6468
- stale_after,
6469
- generated_by,
6470
- okf_sources: sources,
6471
- okf_verified: verified,
6472
- okf_usage_window: usageWindow,
6473
- last_verified_at: lastV?.at ?? null,
6474
- last_verified_by: lastV?.by ?? null,
6475
- ...optionalEpoch("valid_from", frontmatter.valid_from),
6476
- ...optionalEpoch("valid_to", frontmatter.valid_to),
6477
- ...typeof frontmatter.superseded_by === "string" ? { superseded_by: frontmatter.superseded_by } : {},
6478
- ...optionalEpoch("superseded_at", frontmatter.superseded_at),
6479
- ...optionalEpoch("prior_valid_to", frontmatter.prior_valid_to),
6480
- // Source pointer (specs/source-pointers §Export, import, and OKF): the
6481
- // parse path has no diagnostic channel, so it reports through the result.
6482
- // ABSENT key → the property is omitted (not null), so the import
6483
- // presence guard survives the parse. Malformed → the property is omitted
6484
- // AND the drop is reported as entry id + reason slug — never the raw
6485
- // value, which can carry quote text.
6486
- ...(() => {
6487
- const raw = frontmatter.source_pointer;
6488
- if (raw === void 0) return {};
6489
- const v = validateSourcePointerValue(raw);
6490
- if (v === void 0) {
6491
- droppedPointerValues.push({ factId: id, reason: "malformed" });
6492
- return {};
6493
- }
6494
- return { source_pointer: v };
6495
- })(),
6496
- // derived_events (specs/inplace-update-provenance §5): a well-formed list
6497
- // is restored; absent or empty omits the property (import presence rule);
6498
- // malformed omits it AND is reported by id + slug, never the raw value.
6499
- ...(() => {
6500
- const raw = frontmatter.derived_events;
6501
- if (raw === void 0) return {};
6502
- const v = validateDerivedEventsValue(raw);
6503
- if (v === void 0) {
6504
- droppedPointerValues.push({ factId: id, reason: "derived_events_malformed" });
6505
- return {};
6506
- }
6507
- return v ? { derived_events: v } : {};
6508
- })()
6509
- };
6510
- }
6511
- function optionalEpoch(key, v) {
6512
- return typeof v === "number" && Number.isFinite(v) && v >= 0 ? { [key]: Math.trunc(v) } : {};
6513
- }
6514
- function frontmatterToTask(entityId, id, frontmatter, now, usesV1StatusRule) {
6515
- const created_at = parseFrontmatterTimestamp(frontmatter.created_at, now);
6516
- const updated_at = parseFrontmatterTimestamp(
6517
- frontmatter.generated?.at,
6518
- parseFrontmatterTimestamp(
6519
- frontmatter.timestamp,
6520
- parseFrontmatterTimestamp(frontmatter.updated_at, now)
6521
- )
6522
- );
6523
- const verified = parseVerifiedFlexible(frontmatter.verified);
6524
- const sources = Array.isArray(frontmatter.sources) ? frontmatter.sources : [];
6525
- const usageWindow = frontmatter.usage_window && typeof frontmatter.usage_window === "object" ? frontmatter.usage_window : null;
6526
- const lastV = latestVerified(verified, now);
6527
- const lifecycleRaw = frontmatter.status;
6528
- const lifecycle_status = lifecycleRaw === "draft" || lifecycleRaw === "stable" || lifecycleRaw === "deprecated" ? lifecycleRaw : "stable";
6529
- const staleAfterRaw = frontmatter.stale_after;
6530
- const stale_after = parseStaleAfterRaw(staleAfterRaw);
6531
- const executionRaw = frontmatter.execution_status;
6532
- let executionState;
6533
- if (usesV1StatusRule) {
6534
- executionState = TASK_STATUSES.has(String(frontmatter.status)) ? frontmatter.status : "pending";
6535
- } else {
6536
- executionState = TASK_STATUSES.has(String(executionRaw)) ? executionRaw : TASK_STATUSES.has(String(frontmatter.status)) ? frontmatter.status : "pending";
6537
- }
6538
- return {
6539
- id,
6540
- entity_id: entityId,
6541
- description: typeof frontmatter.title === "string" ? frontmatter.title : "",
6542
- status: executionState,
6543
- priority: typeof frontmatter.priority === "number" ? frontmatter.priority : 0,
6544
- created_at,
6545
- updated_at,
6546
- resolved_at: frontmatter.resolved_at != null ? parseFrontmatterTimestamp(frontmatter.resolved_at, now) : null,
6547
- deleted_at: frontmatter.deleted_at != null ? parseFrontmatterTimestamp(frontmatter.deleted_at, 0) : null,
6548
- okf_type: frontmatter.type,
6549
- // OKF v0.2
6550
- lifecycle_status,
6551
- stale_after,
6552
- generated_by: frontmatter.generated?.by ?? null,
6553
- okf_sources: sources,
6554
- okf_verified: verified,
6555
- okf_usage_window: usageWindow,
6556
- last_verified_at: lastV?.at ?? null,
6557
- last_verified_by: lastV?.by ?? null
6558
- };
6559
- }
6560
- function findLogMdPath(files) {
6561
- return files.find((f) => f.path.endsWith("/log.md") || f.path === "log.md")?.path;
6562
- }
6563
- function extractEdgesFromLinks(filePath, resolvedId, links, pathToResolvedId, entityId, now, seenEdges, edges) {
6564
- for (const link of links) {
6565
- const strippedPath = stripLinkSuffix(decodeLinkPath(link.path));
6566
- const directTargetId = lookupResolvedId(pathToResolvedId, strippedPath);
6567
- const resolvedTargetPath = resolveRelativePath(filePath, strippedPath);
6568
- if (isStructuralPath(strippedPath) || isStructuralPath(resolvedTargetPath)) continue;
6569
- const targetId = directTargetId ?? lookupResolvedId(pathToResolvedId, resolvedTargetPath);
6570
- if (!targetId) continue;
6571
- const edgeKey = `${resolvedId}\0${targetId}\0${link.text}`;
6572
- if (seenEdges.has(edgeKey)) continue;
6573
- seenEdges.add(edgeKey);
6574
- edges.push({
6575
- id: generateId(),
6576
- entity_id: entityId,
6577
- source_id: resolvedId,
6578
- target_id: targetId,
6579
- edge_type: link.text,
6580
- created_at: now
6581
- });
6582
- }
6583
- }
6584
- function parseOkfBundle(entityId, files, options) {
6585
- const now = Date.now();
6586
- const normalizeOkfPath = (p) => p.replace(/^\.\//, "").replace(/\\/g, "/");
6587
- const normalizedFiles = files.map((f) => ({ ...f, path: normalizeOkfPath(f.path) }));
6588
- const allowlistedFiles = normalizedFiles.filter((f) => isAllowedOkfPath(f.path));
6589
- const entityDirs = new Set(
6590
- allowlistedFiles.map((f) => /^entities\/([^/]+)\//.exec(f.path)?.[1]).filter((dir) => !!dir)
6591
- );
6592
- if (entityDirs.size > 1) {
6593
- throw new Error(
6594
- `parseOkfBundle: expected a single-entity bundle for "${entityId}", found entities: ${Array.from(entityDirs).join(", ")}`
6595
- );
6596
- }
6597
- const entityDir = entityDirs.values().next().value ?? entityId;
6598
- const entityPrefix = `entities/${entityDir}/`;
6599
- const allowedFiles = allowlistedFiles.filter(
6600
- (f) => f.path === "index.md" || f.path.startsWith(entityPrefix)
6601
- );
6602
- const rootIndex = allowedFiles.find((f) => f.path === "index.md");
6603
- const profileMeta = rootIndex ? parseRootIndexMd(rootIndex.content) : {};
6604
- const okfVersion = profileMeta.okf_version;
6605
- const profile = profileMeta.profile;
6606
- const isProfile1 = profile === "llm-wiki/1";
6607
- const isProfile2 = profile === "llm-wiki/2";
6608
- const isLegacyV1 = profile === void 0 && okfVersion === "0.1";
6609
- const isVersionOnlyV2 = profile === void 0 && okfVersion === "0.2";
6610
- const isUnknownProfileV2 = profile !== void 0 && profile !== "llm-wiki/1" && profile !== "llm-wiki/2" && okfVersion === "0.2";
6611
- const summaryEligible = isProfile1 || isProfile2 || isLegacyV1 || isVersionOnlyV2 || isUnknownProfileV2;
6612
- let entitySummary;
6613
- const entityIndex = allowedFiles.find((f) => f.path === `${entityPrefix}index.md`);
6614
- if (summaryEligible && entityIndex) {
6615
- const summary = parseEntityIndexMd(entityIndex.content).summary;
6616
- entitySummary = summary || void 0;
6617
- }
6618
- const pathToResolvedId = /* @__PURE__ */ new Map();
6619
- for (const file of allowedFiles) {
6620
- if (!isConceptFile(file.path)) continue;
6621
- const { frontmatter } = parseConcept(file.content);
6622
- const route = resolveRoute(file.path, frontmatter.type ?? "", options);
6623
- if (route === "ignore") continue;
6624
- const resolvedId = typeof frontmatter.id === "string" && frontmatter.id ? frontmatter.id : basenameMd(file.path);
6625
- addPathAliases(pathToResolvedId, file.path, resolvedId);
6626
- }
6627
- const facts = [];
6628
- const tasks = [];
6629
- const droppedPointerValues = [];
6630
- const edges = [];
6631
- let logContent = null;
6632
- const logMdPath = findLogMdPath(allowedFiles);
6633
- for (const file of allowedFiles) {
6634
- if (file.path.endsWith("/log.md") || file.path === "log.md") {
6635
- logContent = file.content;
6636
- continue;
6637
- }
6638
- if (!isConceptFile(file.path)) continue;
6639
- const { frontmatter, body } = parseConcept(file.content);
6640
- const route = resolveRoute(file.path, frontmatter.type ?? "", options);
6641
- if (route === "ignore") continue;
6642
- const resolvedId = typeof frontmatter.id === "string" && frontmatter.id ? frontmatter.id : basenameMd(file.path);
6643
- const { body: storedBody, relatedLinks } = splitRelatedSection(body);
6644
- const edgeLinks = isProfile1 || isLegacyV1 ? relatedLinks : [...relatedLinks, ...extractMarkdownLinks(storedBody)];
6645
- const usesV1StatusRule = isProfile1 || isLegacyV1 || profile === void 0 && okfVersion === void 0;
6646
- if (route === "fact") {
6647
- facts.push(frontmatterToFact(entityId, resolvedId, frontmatter, storedBody, now, droppedPointerValues));
6648
- } else {
6649
- tasks.push(frontmatterToTask(entityId, resolvedId, frontmatter, now, usesV1StatusRule));
6650
- }
6651
- const seenEdges = /* @__PURE__ */ new Set();
6652
- extractEdgesFromLinks(
6653
- file.path,
6654
- resolvedId,
6655
- edgeLinks,
6656
- pathToResolvedId,
6657
- entityId,
6658
- now,
6659
- seenEdges,
6660
- edges
6661
- );
6662
- }
6663
- const events = [];
6664
- if (logContent != null) {
6665
- const pending = [];
6666
- const logPath = logMdPath ?? `entities/${entityId}/log.md`;
6667
- for (const entry of parseLogMd(logContent)) {
6668
- const { text, eventId } = parseEventIdComment(entry.text);
6669
- const parsed = parseLogEntryText(text);
6670
- if (!parsed) continue;
6671
- let related_entry_id = null;
6672
- if (parsed.linkPath) {
6673
- const targetPath = resolveRelativePath(
6674
- logPath,
6675
- stripLinkSuffix(decodeLinkPath(parsed.linkPath))
6676
- );
6677
- if (!isStructuralPath(targetPath) && targetPath.includes("/facts/")) {
6678
- related_entry_id = lookupResolvedId(pathToResolvedId, targetPath) ?? null;
6679
- }
6680
- }
6681
- const created_at = (/* @__PURE__ */ new Date(`${entry.date}T00:00:00.000Z`)).getTime();
6682
- if (!Number.isFinite(created_at)) continue;
6683
- if (eventId === void 0) pending.push({ index: events.length, date: entry.date });
6684
- events.push({
6685
- id: eventId ?? "",
6686
- entity_id: entityId,
6687
- event_type: parsed.event_type,
6688
- summary: parsed.summary,
6689
- related_entry_id,
6690
- created_at
6691
- });
6692
- }
6693
- const taken = new Set(events.map((e) => e.id).filter((id) => id !== ""));
6694
- const nextOccurrence = /* @__PURE__ */ new Map();
6695
- for (const { index, date } of pending) {
6696
- const e = events[index];
6697
- const key = JSON.stringify([date, e.event_type, replaceLoneSurrogates(e.summary)]);
6698
- let occurrence = nextOccurrence.get(key) ?? 0;
6699
- const derive = createEventIdDeriver({ entityId, date, eventType: e.event_type, summary: e.summary });
6700
- let id = derive(occurrence);
6701
- while (taken.has(id)) {
6702
- occurrence += 1;
6703
- id = derive(occurrence);
6704
- }
6705
- taken.add(id);
6706
- nextOccurrence.set(key, occurrence + 1);
6707
- e.id = id;
6708
- }
6709
- }
6710
- return {
6711
- generatedAt: now,
6712
- entities: {
6713
- [entityId]: { facts, tasks, events, edges, summary: entitySummary }
6714
- },
6715
- ...droppedPointerValues.length > 0 ? { dropped_pointer_values: droppedPointerValues } : {}
6716
- };
6717
- }
6718
6573
 
6719
6574
  // src/utils/contextBudget.ts
6720
6575
  function estimateTokensWith(budget, text) {
@@ -6765,6 +6620,6 @@ function createWiki(db, options) {
6765
6620
  return new WikiMemory(db, options);
6766
6621
  }
6767
6622
 
6768
- export { DEFAULT_LIBRARIAN_SYNTHESIS_PROMPT, DEFAULT_ONTOLOGY_JOB_BATCH_SIZE, DEFAULT_SETUP_BUDGET_MS, WikiMemory, buildOntologyPromptAppendix, createWiki, estimateTokensWith, formatContext, formatGraphContext, formatMemoryDump, formatOkfBundle, hydrateLibrarianPrompt, mapLibrarianOptionsToReadOptions, parseOkfBundle, resolveOntologyJobDefaults, validateLibrarianPromptTemplate };
6623
+ export { DEFAULT_LIBRARIAN_SYNTHESIS_PROMPT, DEFAULT_ONTOLOGY_JOB_BATCH_SIZE, DEFAULT_SETUP_BUDGET_MS, WikiMemory, buildOntologyPromptAppendix, createWiki, estimateTokensWith, formatContext, formatGraphContext, formatMemoryDump, formatOkfBundle, hydrateLibrarianPrompt, mapLibrarianOptionsToReadOptions, resolveOntologyJobDefaults, validateLibrarianPromptTemplate };
6769
6624
  //# sourceMappingURL=index.mjs.map
6770
6625
  //# sourceMappingURL=index.mjs.map