@equationalapplications/core-llm-wiki 8.4.0 → 9.1.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, parseJsonObject, parseJsonArray, liveAtSql, reanchorRebuildFingerprint, __privateAdd, warnChangedDefaultsOnce, EdgeRepository, MetadataRepository, EmbeddingService, VectorRemovalRepository, VectorRemovalService, SearchService, TemporalService, JobManager, PromptService, resolveGrounding, IngestionService, MaintenanceService, ImportExportService, RetrievalService, WriteService, __privateGet, __privateSet, createLegacySourceTypeIndex, writeNormalizeStamp, CURRENT_SCHEMA_VERSION, detectSchemaVersion, MIGRATIONS, runSourceRefNormalize, emitDiagnostic, normalizeSourceRef, normalizeSourceHash, resolveLibrarianStrategy, entitySummaryMetaKey, WikiSourceRefHashCollision, DiagnosticBuffer, validateManifest, WikiDraftNotFound, generateId, emptyManifest, resolveNodeType, WikiStrictOntologyViolation, validateInlineEdges, resolveEdgeDefinitions, typeSatisfies, normalizeTitleKey, edgeTripleAllowed, MAX_EMBED_ATTEMPTS, UsageMeter, isWikiSearchUnavailableError, WikiBusyError, WikiInvalidReadOptions, isLiveAt, packFactsByBudget, factTokenCost, probePendingWork, WikiMigrationRequiredError, setupDatabase, UnavailableIndexStrategy, createdAtValue, isUsableDate, assertEntityId, assertEpochMs, FTS5_STATE_KEY, fts5LedgerDropSql, 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-EKYWAR2E.mjs';
2
- export { DEFAULT_CHUNK_OVERLAP, DEFAULT_MAX_CHUNK_LENGTH, DEFAULT_MAX_EMBED_CHARS, EMBED_CHARS_CEILING, HEAL_ANCHORS_PER_CANDIDATE, HEAL_BATCH_SIZE, HEAL_MAX_FACT_BODY_CHARS_L3, HEAL_MAX_TASKS, HEAL_RECHECK_MS, HOOK_TIMEOUT_MARKER, 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, isWikiSearchUnavailableError, parseEmbedding, safeSlice, validateManifest } from './chunk-EKYWAR2E.mjs';
1
+ import { BaseRepository, WikiGraphNodeOwnershipConflict, serializeSourcePointer, parseStoredSourcePointer, parseJsonObject, parseJsonArray, liveAtSql, reanchorRebuildFingerprint, __privateAdd, warnChangedDefaultsOnce, EdgeRepository, MetadataRepository, EmbeddingService, VectorRemovalRepository, VectorRemovalService, SearchService, TemporalService, JobManager, PromptService, resolveGrounding, IngestionService, MaintenanceService, ImportExportService, RetrievalService, WriteService, __privateGet, __privateSet, createLegacySourceTypeIndex, writeNormalizeStamp, CURRENT_SCHEMA_VERSION, detectSchemaVersion, MIGRATIONS, runSourceRefNormalize, emitDiagnostic, normalizeSourceRef, normalizeSourceHash, resolveLibrarianStrategy, entitySummaryMetaKey, WikiSourceRefHashCollision, DiagnosticBuffer, validateManifest, WikiDraftNotFound, generateId, emptyManifest, resolveNodeType, WikiStrictOntologyViolation, validateInlineEdges, resolveEdgeDefinitions, typeSatisfies, normalizeTitleKey, edgeTripleAllowed, MAX_EMBED_ATTEMPTS, UsageMeter, isWikiSearchUnavailableError, WikiBusyError, WikiInvalidReadOptions, isLiveAt, packFactsByBudget, factTokenCost, probePendingWork, WikiMigrationRequiredError, setupDatabase, UnavailableIndexStrategy, createdAtValue, isUsableDate, validateSourcePointerValue, assertEntityId, assertEpochMs, FTS5_STATE_KEY, fts5LedgerDropSql, 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-SIJD5GEF.mjs';
2
+ export { DEFAULT_CHUNK_OVERLAP, DEFAULT_MAX_CHUNK_LENGTH, DEFAULT_MAX_EMBED_CHARS, EMBED_CHARS_CEILING, HEAL_ANCHORS_PER_CANDIDATE, HEAL_BATCH_SIZE, HEAL_MAX_FACT_BODY_CHARS_L3, HEAL_MAX_TASKS, HEAL_RECHECK_MS, HOOK_TIMEOUT_MARKER, 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, isWikiSearchUnavailableError, parseEmbedding, safeSlice, validateManifest } from './chunk-SIJD5GEF.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
 
@@ -78,7 +78,8 @@ 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
- return {
81
+ const sourcePointer = parseStoredSourcePointer(row.source_pointer);
82
+ const mapped = {
82
83
  id: row.id,
83
84
  entity_id: row.entity_id,
84
85
  title: row.title,
@@ -111,8 +112,13 @@ function mapRowToFact(row) {
111
112
  ...row.valid_from != null ? { valid_from: Number(row.valid_from) } : {},
112
113
  ...row.valid_to != null ? { valid_to: Number(row.valid_to) } : {},
113
114
  ...row.superseded_by != null ? { superseded_by: String(row.superseded_by) } : {},
114
- ...row.superseded_at != null ? { superseded_at: Number(row.superseded_at) } : {}
115
+ ...row.superseded_at != null ? { superseded_at: Number(row.superseded_at) } : {},
116
+ // Source pointer (specs/source-pointers): key appears only when non-null,
117
+ // same temporal-fields pattern. Tolerant read: a malformed stored value
118
+ // reads as null without throwing (test 1).
119
+ ...sourcePointer ? { source_pointer: sourcePointer } : {}
115
120
  };
121
+ return mapped;
116
122
  }
117
123
  function normalizeEmbeddingBlobValue(blob) {
118
124
  if (blob instanceof Uint8Array) return blob;
@@ -227,7 +233,7 @@ var _EntryRepository = class _EntryRepository extends BaseRepository {
227
233
  const existingRow = await executor.getFirstAsync(
228
234
  `SELECT id, entity_id, lifecycle_status, stale_after, generated_by,
229
235
  okf_sources, okf_verified, okf_usage_window,
230
- last_verified_at, last_verified_by
236
+ last_verified_at, last_verified_by, source_pointer
231
237
  FROM ${this.prefix}entries WHERE id = ?`,
232
238
  [fact.id]
233
239
  );
@@ -241,8 +247,8 @@ var _EntryRepository = class _EntryRepository extends BaseRepository {
241
247
  source_hash, source_ref, created_at, updated_at, last_accessed_at, access_count,
242
248
  deleted_at, embedding_blob, embedding, okf_type,
243
249
  lifecycle_status, stale_after, generated_by, last_verified_at, last_verified_by,
244
- okf_sources, okf_verified, okf_usage_window
245
- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
250
+ okf_sources, okf_verified, okf_usage_window, source_pointer
251
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
246
252
  ON CONFLICT(id) DO UPDATE SET
247
253
  title = excluded.title,
248
254
  body = excluded.body,
@@ -290,7 +296,8 @@ var _EntryRepository = class _EntryRepository extends BaseRepository {
290
296
  fact.last_verified_by ?? null,
291
297
  fact.okf_sources ? JSON.stringify(fact.okf_sources) : null,
292
298
  fact.okf_verified ? JSON.stringify(fact.okf_verified) : null,
293
- fact.okf_usage_window ? JSON.stringify(fact.okf_usage_window) : null
299
+ fact.okf_usage_window ? JSON.stringify(fact.okf_usage_window) : null,
300
+ serializeSourcePointer(fact.source_pointer)
294
301
  ]
295
302
  );
296
303
  if (result.changes === 0) {
@@ -313,7 +320,8 @@ var _EntryRepository = class _EntryRepository extends BaseRepository {
313
320
  okf_verified: parseJsonArray(existingRow.okf_verified, []),
314
321
  okf_usage_window: parseJsonObject(existingRow.okf_usage_window),
315
322
  last_verified_at: existingRow.last_verified_at != null ? Number(existingRow.last_verified_at) : null,
316
- last_verified_by: existingRow.last_verified_by ?? null
323
+ last_verified_by: existingRow.last_verified_by ?? null,
324
+ source_pointer: parseStoredSourcePointer(existingRow.source_pointer)
317
325
  } : null;
318
326
  await this.outbox.push({
319
327
  entityId: fact.entity_id,
@@ -373,7 +381,7 @@ var _EntryRepository = class _EntryRepository extends BaseRepository {
373
381
  const rows = await executor.getAllAsync(sql, args);
374
382
  return rows.map((row) => row.id);
375
383
  }
376
- async upsertForImport(fact, tx) {
384
+ async upsertForImport(fact, tx, sourcePointerPresent = false) {
377
385
  const executor = this.getExecutor(tx);
378
386
  const tagsJson = JSON.stringify(fact.tags);
379
387
  const embeddingBlob = this.normalizeEmbeddingBlob(fact.embedding_blob);
@@ -383,8 +391,8 @@ var _EntryRepository = class _EntryRepository extends BaseRepository {
383
391
  source_hash, source_ref, created_at, updated_at, last_accessed_at, access_count,
384
392
  deleted_at, embedding_blob, embedding, okf_type,
385
393
  lifecycle_status, stale_after, generated_by, last_verified_at, last_verified_by,
386
- okf_sources, okf_verified, okf_usage_window
387
- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
394
+ okf_sources, okf_verified, okf_usage_window, source_pointer
395
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
388
396
  ON CONFLICT(id) DO UPDATE SET
389
397
  entity_id = excluded.entity_id,
390
398
  title = excluded.title,
@@ -412,7 +420,8 @@ var _EntryRepository = class _EntryRepository extends BaseRepository {
412
420
  last_verified_by = excluded.last_verified_by,
413
421
  okf_sources = excluded.okf_sources,
414
422
  okf_verified = excluded.okf_verified,
415
- okf_usage_window = excluded.okf_usage_window`,
423
+ okf_usage_window = excluded.okf_usage_window,
424
+ source_pointer = CASE WHEN ? THEN excluded.source_pointer ELSE source_pointer END`,
416
425
  [
417
426
  fact.id,
418
427
  fact.entity_id,
@@ -439,7 +448,11 @@ var _EntryRepository = class _EntryRepository extends BaseRepository {
439
448
  fact.last_verified_by ?? null,
440
449
  fact.okf_sources ? JSON.stringify(fact.okf_sources) : null,
441
450
  fact.okf_verified ? JSON.stringify(fact.okf_verified) : null,
442
- fact.okf_usage_window ? JSON.stringify(fact.okf_usage_window) : null
451
+ fact.okf_usage_window ? JSON.stringify(fact.okf_usage_window) : null,
452
+ serializeSourcePointer(fact.source_pointer),
453
+ // The presence flag binds to the SET clause's CASE, AFTER the INSERT
454
+ // values above.
455
+ sourcePointerPresent ? 1 : 0
443
456
  ]
444
457
  );
445
458
  return result;
@@ -4290,7 +4303,17 @@ var WikiMemory = class {
4290
4303
  async getInstructions(entityId) {
4291
4304
  assertEntityId2(entityId);
4292
4305
  const ontologyContext = await this.ontologyService.buildPromptContext(entityId);
4293
- return this.promptService.buildInstructionTemplates(ontologyContext, resolveLibrarianStrategy(this.options.config));
4306
+ const { guidance, diagnostic } = PromptService.resolveGuidance(this.options.config, entityId);
4307
+ if (diagnostic) {
4308
+ emitDiagnostic(this.options, {
4309
+ code: diagnostic.code,
4310
+ operation: "read",
4311
+ trigger: "call",
4312
+ entityId,
4313
+ detail: diagnostic.detail
4314
+ });
4315
+ }
4316
+ return this.promptService.buildInstructionTemplates(ontologyContext, resolveLibrarianStrategy(this.options.config), guidance);
4294
4317
  }
4295
4318
  /**
4296
4319
  * Returns the live source_refs for an entity, one row per ref, with the most
@@ -4404,7 +4427,7 @@ var WikiMemory = class {
4404
4427
  /**
4405
4428
  * @param options.promptOverride - Applies only to this manual call. Does NOT affect
4406
4429
  * WriteService-triggered auto-runs. For persistent prompt customization across auto-runs,
4407
- * set `options.config.prompts.librarianSystemPrompt` at WikiMemory construction time.
4430
+ * set `options.config.prompts.guidance` at WikiMemory construction time.
4408
4431
  */
4409
4432
  async runLibrarian(entityId, options) {
4410
4433
  return this.maintenanceService.runLibrarian(entityId, options);
@@ -5215,6 +5238,15 @@ function isoDateOrOmit(ms) {
5215
5238
  if (!Number.isFinite(d.getTime())) return void 0;
5216
5239
  return d.toISOString().slice(0, 10);
5217
5240
  }
5241
+ function sourcePointerFrontmatter(p) {
5242
+ if (!p) return void 0;
5243
+ return {
5244
+ ...p.event_id != null ? { event_id: p.event_id } : {},
5245
+ ...p.ref != null ? { ref: p.ref } : {},
5246
+ ...p.quote != null ? { quote: p.quote } : {},
5247
+ ...p.position != null ? { position: p.position } : {}
5248
+ };
5249
+ }
5218
5250
  function factFrontmatterV2(f) {
5219
5251
  return {
5220
5252
  type: f.okf_type ?? "fact",
@@ -5253,7 +5285,9 @@ function factFrontmatterV2(f) {
5253
5285
  ...f.valid_from != null ? { valid_from: f.valid_from } : {},
5254
5286
  ...f.valid_to != null ? { valid_to: f.valid_to } : {},
5255
5287
  ...f.superseded_by != null ? { superseded_by: f.superseded_by } : {},
5256
- ...f.superseded_at != null ? { superseded_at: f.superseded_at } : {}
5288
+ ...f.superseded_at != null ? { superseded_at: f.superseded_at } : {},
5289
+ // Source pointer (specs/source-pointers): map only when non-null; null slots omitted.
5290
+ ...sourcePointerFrontmatter(f.source_pointer) ? { source_pointer: sourcePointerFrontmatter(f.source_pointer) } : {}
5257
5291
  };
5258
5292
  }
5259
5293
  function taskFrontmatterV2(t) {
@@ -5297,7 +5331,9 @@ function factFrontmatterV1(f) {
5297
5331
  created_at: f.created_at,
5298
5332
  access_count: f.access_count,
5299
5333
  last_accessed_at: f.last_accessed_at,
5300
- deleted_at: f.deleted_at
5334
+ deleted_at: f.deleted_at,
5335
+ // Source pointer (specs/source-pointers): same map rule as the v2 path.
5336
+ ...sourcePointerFrontmatter(f.source_pointer) ? { source_pointer: sourcePointerFrontmatter(f.source_pointer) } : {}
5301
5337
  };
5302
5338
  }
5303
5339
  function taskFrontmatterV1(t) {
@@ -5553,7 +5589,7 @@ function parseLogEntryText(text) {
5553
5589
  }
5554
5590
  return { event_type, summary: unescapeLogSummary((plainSummary ?? "").trim()) };
5555
5591
  }
5556
- function frontmatterToFact(entityId, id, frontmatter, body, now) {
5592
+ function frontmatterToFact(entityId, id, frontmatter, body, now, droppedPointerValues) {
5557
5593
  const created_at = parseFrontmatterTimestamp(frontmatter.created_at, now);
5558
5594
  const updated_at = parseFrontmatterTimestamp(
5559
5595
  frontmatter.generated?.at,
@@ -5607,7 +5643,23 @@ function frontmatterToFact(entityId, id, frontmatter, body, now) {
5607
5643
  ...optionalEpoch("valid_from", frontmatter.valid_from),
5608
5644
  ...optionalEpoch("valid_to", frontmatter.valid_to),
5609
5645
  ...typeof frontmatter.superseded_by === "string" ? { superseded_by: frontmatter.superseded_by } : {},
5610
- ...optionalEpoch("superseded_at", frontmatter.superseded_at)
5646
+ ...optionalEpoch("superseded_at", frontmatter.superseded_at),
5647
+ // Source pointer (specs/source-pointers §Export, import, and OKF): the
5648
+ // parse path has no diagnostic channel, so it reports through the result.
5649
+ // ABSENT key → the property is omitted (not null), so the import
5650
+ // presence guard survives the parse. Malformed → the property is omitted
5651
+ // AND the drop is reported as entry id + reason slug — never the raw
5652
+ // value, which can carry quote text.
5653
+ ...(() => {
5654
+ const raw = frontmatter.source_pointer;
5655
+ if (raw === void 0) return {};
5656
+ const v = validateSourcePointerValue(raw);
5657
+ if (v === void 0) {
5658
+ droppedPointerValues.push({ factId: id, reason: "malformed" });
5659
+ return {};
5660
+ }
5661
+ return { source_pointer: v };
5662
+ })()
5611
5663
  };
5612
5664
  }
5613
5665
  function optionalEpoch(key, v) {
@@ -5728,6 +5780,7 @@ function parseOkfBundle(entityId, files, options) {
5728
5780
  }
5729
5781
  const facts = [];
5730
5782
  const tasks = [];
5783
+ const droppedPointerValues = [];
5731
5784
  const edges = [];
5732
5785
  let logContent = null;
5733
5786
  const logMdPath = findLogMdPath(allowedFiles);
@@ -5745,7 +5798,7 @@ function parseOkfBundle(entityId, files, options) {
5745
5798
  const edgeLinks = isProfile1 || isLegacyV1 ? relatedLinks : [...relatedLinks, ...extractMarkdownLinks(storedBody)];
5746
5799
  const usesV1StatusRule = isProfile1 || isLegacyV1 || profile === void 0 && okfVersion === void 0;
5747
5800
  if (route === "fact") {
5748
- facts.push(frontmatterToFact(entityId, resolvedId, frontmatter, storedBody, now));
5801
+ facts.push(frontmatterToFact(entityId, resolvedId, frontmatter, storedBody, now, droppedPointerValues));
5749
5802
  } else {
5750
5803
  tasks.push(frontmatterToTask(entityId, resolvedId, frontmatter, now, usesV1StatusRule));
5751
5804
  }
@@ -5812,7 +5865,8 @@ function parseOkfBundle(entityId, files, options) {
5812
5865
  generatedAt: now,
5813
5866
  entities: {
5814
5867
  [entityId]: { facts, tasks, events, edges, summary: entitySummary }
5815
- }
5868
+ },
5869
+ ...droppedPointerValues.length > 0 ? { dropped_pointer_values: droppedPointerValues } : {}
5816
5870
  };
5817
5871
  }
5818
5872
 
@@ -5860,6 +5914,6 @@ function createWiki(db, options) {
5860
5914
  return new WikiMemory(db, options);
5861
5915
  }
5862
5916
 
5863
- export { DEFAULT_LIBRARIAN_SYNTHESIS_PROMPT, DEFAULT_SETUP_BUDGET_MS, WikiMemory, createWiki, formatContext, formatGraphContext, formatMemoryDump, formatOkfBundle, hydrateLibrarianPrompt, mapLibrarianOptionsToReadOptions, parseOkfBundle, validateLibrarianPromptTemplate };
5917
+ export { DEFAULT_LIBRARIAN_SYNTHESIS_PROMPT, DEFAULT_SETUP_BUDGET_MS, WikiMemory, buildOntologyPromptAppendix, createWiki, formatContext, formatGraphContext, formatMemoryDump, formatOkfBundle, hydrateLibrarianPrompt, mapLibrarianOptionsToReadOptions, parseOkfBundle, validateLibrarianPromptTemplate };
5864
5918
  //# sourceMappingURL=index.mjs.map
5865
5919
  //# sourceMappingURL=index.mjs.map