@equationalapplications/core-llm-wiki 9.0.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.
@@ -2177,6 +2177,10 @@ ${JSON.stringify(facts, null, 2)}`
2177
2177
  systemPrompt: this.appendGrounding(this.appendGuidance(this.appendOntology(OPS_EXTRACT_SYSTEM_PROMPT, ontologyContext), guidance), "librarian"),
2178
2178
  userPrompt: `Events:
2179
2179
  ${lines.join("\n")}`,
2180
+ // Corpus entries are one-per-batch-event in batch order (summaries are
2181
+ // TEXT NOT NULL, so the filter inside buildGroundingCorpus drops
2182
+ // nothing): extract.ts stores a candidate's `sourcePartIndex` as the
2183
+ // batch index and buildSourcePointer reads the quote back by it.
2180
2184
  ...grounding ? { groundingCorpus: buildGroundingCorpus(events.map((l) => l.event.summary)) } : {}
2181
2185
  };
2182
2186
  }
@@ -2276,7 +2280,9 @@ var SEVERITY = {
2276
2280
  external_deletion_pending: "warn",
2277
2281
  external_deletion_discarded: "warn",
2278
2282
  guidance_too_long: "warn",
2279
- guidance_resolver_failed: "warn"
2283
+ guidance_resolver_failed: "warn",
2284
+ source_pointer_unresolved: "warn",
2285
+ source_pointer_invalid: "warn"
2280
2286
  };
2281
2287
  var MESSAGE = {
2282
2288
  ingest_chunk_failed: "One or more document chunks failed to parse or generate.",
@@ -2304,7 +2310,9 @@ var MESSAGE = {
2304
2310
  external_deletion_pending: "Removals owed to the external vector index are still pending.",
2305
2311
  external_deletion_discarded: "Pending external vector removals were discarded because forceDeleteIgnoreRankerHook is set.",
2306
2312
  guidance_too_long: "The configured guidance exceeded the length cap and was not sent for this pass.",
2307
- guidance_resolver_failed: "The per-entity guidance resolver failed; its value was not used for this pass."
2313
+ guidance_resolver_failed: "The per-entity guidance resolver failed; its value was not used for this pass.",
2314
+ source_pointer_unresolved: "A stored librarian fact carries no source pointer because the model answer could not yield one.",
2315
+ source_pointer_invalid: "Import met a malformed source pointer value and stored a null pointer."
2308
2316
  };
2309
2317
  var warnedNonFunction = /* @__PURE__ */ new WeakSet();
2310
2318
  function copyDetail(detail) {
@@ -4374,7 +4382,8 @@ async function setupDatabase(db, prefix) {
4374
4382
  valid_from INTEGER,
4375
4383
  valid_to INTEGER,
4376
4384
  superseded_by TEXT,
4377
- superseded_at INTEGER
4385
+ superseded_at INTEGER,
4386
+ source_pointer TEXT
4378
4387
  );
4379
4388
 
4380
4389
  CREATE INDEX IF NOT EXISTS ${prefix}entries_entity_idx ON ${prefix}entries(entity_id);
@@ -5023,6 +5032,17 @@ var MIGRATIONS = [
5023
5032
  );
5024
5033
  if (row?.n) await db.execAsync(fts5PendingIndexesDdl(prefix));
5025
5034
  }
5035
+ },
5036
+ {
5037
+ version: 16,
5038
+ description: "Source pointers on librarian facts: nullable source_pointer TEXT on entries",
5039
+ run: async (db, prefix) => {
5040
+ const cols = await db.getAllAsync(`PRAGMA table_info(${prefix}entries)`);
5041
+ const existing = new Set(cols.map((c) => c.name));
5042
+ if (!existing.has("source_pointer")) {
5043
+ await db.execAsync(`ALTER TABLE ${prefix}entries ADD COLUMN source_pointer TEXT`);
5044
+ }
5045
+ }
5026
5046
  }
5027
5047
  ];
5028
5048
  async function createLegacySourceTypeIndex(db, prefix) {
@@ -5291,9 +5311,20 @@ var runLegacyLibrarianPass = async (deps, ctx) => {
5291
5311
  access_count: 0,
5292
5312
  deleted_at: null,
5293
5313
  okf_type: normalized.okf_type,
5314
+ // Legacy writes no pointer (spec §Legacy path): the column stays null
5315
+ // on every legacy fact, and the legacy prompt keeps its exact text.
5316
+ source_pointer: null,
5294
5317
  ...grounding?.trust
5295
5318
  };
5296
5319
  await deps.entryRepo.upsert(factObj, tx);
5320
+ const volunteeredSourceEvent = facts[validFactItemIndexes[k]]?.source_event;
5321
+ if (volunteeredSourceEvent !== void 0 && volunteeredSourceEvent !== null) {
5322
+ diagBuffer.push({
5323
+ ...diagBase,
5324
+ code: "source_pointer_unresolved",
5325
+ detail: { factId: id, itemIndex: validFactItemIndexes[k], reason: "unsupported_strategy" }
5326
+ });
5327
+ }
5297
5328
  insertedFacts.push({ id, entity_id: entityId, title: fact.title, body: fact.body, tags: JSON.stringify(fact.tags) });
5298
5329
  factsForDedupe.push(factObj);
5299
5330
  titleIndex.set(normalizeTitleKey(fact.title), { id, okf_type: normalized.okf_type });
@@ -5407,9 +5438,23 @@ async function runExtract(deps, ctx, batch) {
5407
5438
  return;
5408
5439
  }
5409
5440
  const r = raw;
5410
- const sourceLabel = typeof r.source_event === "string" && byLabel.has(r.source_event) ? r.source_event : null;
5441
+ let sourceEventId = null;
5442
+ let sourcePartIndex = null;
5443
+ let pointerUnresolved;
5444
+ const rawSourceEvent = r.source_event;
5445
+ if (rawSourceEvent === void 0 || rawSourceEvent === null) {
5446
+ pointerUnresolved = "missing";
5447
+ } else if (typeof rawSourceEvent === "string" && byLabel.has(rawSourceEvent)) {
5448
+ const labeled = byLabel.get(rawSourceEvent);
5449
+ sourceEventId = labeled.event.id;
5450
+ sourcePartIndex = batch.findIndex((b) => b.label === rawSourceEvent);
5451
+ pointerUnresolved = null;
5452
+ } else {
5453
+ pointerUnresolved = "unknown_label";
5454
+ }
5455
+ const sourceLabel = typeof rawSourceEvent === "string" && byLabel.has(rawSourceEvent) ? rawSourceEvent : null;
5411
5456
  const validFrom = parseValidFrom(r.valid_from) ?? (sourceLabel ? byLabel.get(sourceLabel).at : defaultValidFrom);
5412
- candidates.push({ index, fact, sourceLabel, validFrom });
5457
+ candidates.push({ index, fact, sourceLabel, sourceEventId, sourcePartIndex, pointerUnresolved, validFrom });
5413
5458
  });
5414
5459
  const tasks = [];
5415
5460
  (Array.isArray(parsed.tasks) ? parsed.tasks : []).forEach((raw, index) => {
@@ -5686,6 +5731,17 @@ var TemporalService = class {
5686
5731
  };
5687
5732
 
5688
5733
  // src/services/librarian/ops/apply.ts
5734
+ function buildSourcePointer(candidate, verdict, groundingOn, groundingCorpus) {
5735
+ if (candidate.sourceEventId === null) return null;
5736
+ let quote = null;
5737
+ if (groundingOn && verdict?.status === "grounded" && candidate.sourcePartIndex !== null) {
5738
+ const part = groundingCorpus?.[candidate.sourcePartIndex];
5739
+ if (part !== void 0) {
5740
+ quote = verdict.retained.find((q) => part.includes(q)) ?? null;
5741
+ }
5742
+ }
5743
+ return { event_id: candidate.sourceEventId, ref: null, quote, position: null };
5744
+ }
5689
5745
  async function applyOps(deps, ctx, input) {
5690
5746
  const { entityId, trigger } = ctx;
5691
5747
  const diagBase = { entityId, operation: "librarian", trigger };
@@ -5714,7 +5770,8 @@ async function applyOps(deps, ctx, input) {
5714
5770
  const drops = [];
5715
5771
  const normalized = deps.ontologyService?.validateAndNormalizeFact(fact, manifest, { strict: false, drops }) ?? { okf_type: null, edges: [] };
5716
5772
  for (const d of drops) input.diagnostics.push(edgeDropDiagnostic(d, { ...diagBase, factId: id }));
5717
- const g2 = grounding ? groundingOutcome(checkGrounding(fact.evidence, input.groundingCorpus ?? [], grounding), now) : null;
5773
+ const gVerdict = grounding ? checkGrounding(fact.evidence, input.groundingCorpus ?? [], grounding) : null;
5774
+ const g2 = gVerdict ? groundingOutcome(gVerdict, now) : null;
5718
5775
  if (g2?.diagnostic) {
5719
5776
  input.diagnostics.push({
5720
5777
  ...diagBase,
@@ -5722,6 +5779,7 @@ async function applyOps(deps, ctx, input) {
5722
5779
  detail: { factId: id, itemIndex: g.candidate.index, reason: g2.diagnostic.reason }
5723
5780
  });
5724
5781
  }
5782
+ const pointer = buildSourcePointer(g.candidate, gVerdict, grounding !== void 0 && grounding !== null, input.groundingCorpus);
5725
5783
  const row = {
5726
5784
  id,
5727
5785
  entity_id: entityId,
@@ -5738,11 +5796,19 @@ async function applyOps(deps, ctx, input) {
5738
5796
  access_count: 0,
5739
5797
  deleted_at: null,
5740
5798
  okf_type: normalized.okf_type,
5799
+ source_pointer: pointer,
5741
5800
  ...g2?.trust,
5742
5801
  ...draft ? { lifecycle_status: "draft" } : {}
5743
5802
  };
5744
5803
  await deps.entryRepo.upsert(row, tx);
5745
5804
  await deps.entryRepo.setTemporal(id, entityId, { valid_from: validFrom }, tx);
5805
+ if (g.candidate.pointerUnresolved !== null) {
5806
+ input.diagnostics.push({
5807
+ ...diagBase,
5808
+ code: "source_pointer_unresolved",
5809
+ detail: { factId: id, itemIndex: g.candidate.index, reason: g.candidate.pointerUnresolved }
5810
+ });
5811
+ }
5746
5812
  titleIndex.set(normalizeTitleKey(title), { id, okf_type: normalized.okf_type });
5747
5813
  if (normalized.edges.length > 0) pendingEdges.push({ sourceId: id, sourceType: normalized.okf_type, edges: normalized.edges });
5748
5814
  const textChanged = title !== fact.title || body !== fact.body;
@@ -6766,6 +6832,7 @@ var MaintenanceService = class {
6766
6832
  source_type: "librarian_inferred",
6767
6833
  source_hash: null,
6768
6834
  source_ref: null,
6835
+ source_pointer: null,
6769
6836
  created_at: now,
6770
6837
  updated_at: now,
6771
6838
  last_accessed_at: null,
@@ -7167,6 +7234,59 @@ var MaintenanceService = class {
7167
7234
  }
7168
7235
  };
7169
7236
 
7237
+ // src/utils/sourcePointer.ts
7238
+ var POINTER_SLOTS = ["event_id", "ref", "quote", "position"];
7239
+ function isStringOrNull(v) {
7240
+ return v === null || typeof v === "string";
7241
+ }
7242
+ function isValidPosition(v) {
7243
+ if (v === null) return true;
7244
+ if (typeof v !== "object" || v === null || Array.isArray(v)) return false;
7245
+ const o = v;
7246
+ const keys = Object.keys(o);
7247
+ if (keys.length !== 2 || !("start" in o) || !("length" in o)) return false;
7248
+ const { start, length } = o;
7249
+ return typeof start === "number" && Number.isInteger(start) && start >= 0 && typeof length === "number" && Number.isInteger(length) && length >= 0;
7250
+ }
7251
+ function validateSourcePointerValue(v) {
7252
+ if (v === null) return null;
7253
+ if (typeof v !== "object" || Array.isArray(v)) return void 0;
7254
+ const o = v;
7255
+ const keys = Object.keys(o);
7256
+ for (const k of keys) {
7257
+ if (!POINTER_SLOTS.includes(k)) return void 0;
7258
+ }
7259
+ if (!isStringOrNull(o["event_id"] === void 0 ? null : o["event_id"]) || !isStringOrNull(o["ref"] === void 0 ? null : o["ref"]) || !isStringOrNull(o["quote"] === void 0 ? null : o["quote"])) {
7260
+ return void 0;
7261
+ }
7262
+ if (!isValidPosition(o["position"] === void 0 ? null : o["position"])) return void 0;
7263
+ const normalized = {
7264
+ event_id: o["event_id"] ?? null,
7265
+ ref: o["ref"] ?? null,
7266
+ quote: o["quote"] ?? null,
7267
+ position: o["position"] ?? null
7268
+ };
7269
+ if (normalized.event_id === null && normalized.ref === null && normalized.quote === null && normalized.position === null) {
7270
+ return null;
7271
+ }
7272
+ return normalized;
7273
+ }
7274
+ function parseStoredSourcePointer(raw) {
7275
+ if (raw === null || raw === void 0) return null;
7276
+ if (typeof raw !== "string") return null;
7277
+ let parsed;
7278
+ try {
7279
+ parsed = JSON.parse(raw);
7280
+ } catch {
7281
+ return null;
7282
+ }
7283
+ const v = validateSourcePointerValue(parsed);
7284
+ return v === void 0 ? null : v;
7285
+ }
7286
+ function serializeSourcePointer(p) {
7287
+ return p ? JSON.stringify(p) : null;
7288
+ }
7289
+
7170
7290
  // src/services/importEventStamps.ts
7171
7291
  var DATE_MAX = 864e13;
7172
7292
  var DECIMAL_TEXT = /^\s*[+-]?(\d+(\.\d*)?|\.\d+)([eE][+-]?\d+)?\s*$/;
@@ -7434,6 +7554,19 @@ var ImportExportService = class {
7434
7554
  );
7435
7555
  }
7436
7556
  }
7557
+ const hasSourcePointerKey = fact["source_pointer"] !== void 0;
7558
+ const rawPointerValue = hasSourcePointerKey ? fact["source_pointer"] : void 0;
7559
+ const pointerValidated = hasSourcePointerKey ? validateSourcePointerValue(rawPointerValue) : null;
7560
+ if (pointerValidated === void 0) {
7561
+ emitDiagnostic(this.options, {
7562
+ code: "source_pointer_invalid",
7563
+ operation: "importDump",
7564
+ trigger: "call",
7565
+ entityId,
7566
+ detail: { factId: fact.id }
7567
+ });
7568
+ }
7569
+ const sourcePointer = pointerValidated === void 0 ? null : pointerValidated;
7437
7570
  const factObj = {
7438
7571
  id: fact.id,
7439
7572
  entity_id: entityId,
@@ -7451,6 +7584,7 @@ var ImportExportService = class {
7451
7584
  deleted_at: fact.deleted_at,
7452
7585
  embedding_blob: blobData ?? void 0,
7453
7586
  okf_type: fact.okf_type ?? null,
7587
+ source_pointer: sourcePointer,
7454
7588
  // OKF v0.2 — forwarded as-is; parseOkfBundle / the caller is responsible for
7455
7589
  // populating these per spec, importDump does not derive or validate them.
7456
7590
  lifecycle_status: fact.lifecycle_status ?? "stable",
@@ -7468,7 +7602,7 @@ var ImportExportService = class {
7468
7602
  return { last_verified_at: latest?.at ?? null, last_verified_by: latest?.by ?? null };
7469
7603
  })()
7470
7604
  };
7471
- await this.entryRepo.upsertForImport(factObj, tx);
7605
+ await this.entryRepo.upsertForImport(factObj, tx, hasSourcePointerKey);
7472
7606
  await this.entryRepo.setTemporal(fact.id, entityId, {
7473
7607
  valid_from: fact.valid_from ?? null,
7474
7608
  valid_to: fact.valid_to ?? null,
@@ -9098,6 +9232,6 @@ var WriteService = class {
9098
9232
  }
9099
9233
  };
9100
9234
 
9101
- export { BaseRepository, CURRENT_SCHEMA_VERSION, DEFAULT_CHUNK_OVERLAP, DEFAULT_MAX_CHUNK_LENGTH, DEFAULT_MAX_EMBED_CHARS, DiagnosticBuffer, EMBED_CHARS_CEILING, EdgeRepository, EmbeddingService, FTS5_DRAIN_CHUNK, FTS5_REBUILD_SNAPSHOT_KEY, FTS5_REBUILD_WM_KEY, FTS5_RECLAIM_MERGE_PAGES, FTS5_RETIRED_COUNTER_KEY, FTS5_RETIRED_TABLES_KEY, FTS5_STATE_KEY, FTS5_SWEEP_CURSOR_KEY, HEAL_ANCHORS_PER_CANDIDATE, HEAL_BATCH_SIZE, HEAL_MAX_FACT_BODY_CHARS_L3, HEAL_MAX_TASKS, HEAL_RECHECK_MS, HOOK_TIMEOUT_MARKER, ImportExportService, IngestionService, JobManager, MAX_EMBED_ATTEMPTS, MIGRATIONS, MaintenanceService, MetadataRepository, ONTOLOGY_BACKFILL_BATCH_SIZE, ONTOLOGY_BACKFILL_MAX_PROMPT_CHARS, ONTOLOGY_BACKFILL_RECHECK_MS, ONTOLOGY_BACKFILL_SYSTEM_PROMPT, PromptService, PrunePartialFailureError, RetrievalService, SearchService, TemporalService, UnavailableIndexStrategy, UsageMeter, VectorRemovalRepository, VectorRemovalService, WikiBusyError, WikiDraftNotFound, WikiDuplicateHashError, WikiExternalDeletionError, WikiGraphNodeOwnershipConflict, WikiIngestEmptyError, WikiInvalidReadOptions, WikiMigrationRequiredError, WikiParseError, WikiSearchUnavailableError, WikiSourceRefHashCollision, WikiStrictOntologyViolation, WikiSupersedeError, WikiTransactionError, WriteService, __privateAdd, __privateGet, __privateSet, assertEntityId, assertEpochMs, chunkText, configureRandomSource, createLegacySourceTypeIndex, createdAtValue, detectSchemaVersion, drainChunkSql, drainHiSql, edgeTripleAllowed, emitDiagnostic, emptyManifest, entityDrainChunkSql, entityDrainHiSql, entitySummaryMetaKey, extractSqliteCode, factTokenCost, fts5LedgerDropSql, fts5PendingIndexesDdl, fts5TablesDdl, fts5TriggerNames, fts5TriggersDdl, generateId, idDrainChunkSql, idReindexChunkSql, isLiveAt, isRetiredTableName, isUsableDate, isWikiSearchUnavailableError, liveAtSql, normalizeSourceHash, normalizeSourceRef, normalizeTitleKey, packFactsByBudget, parseEmbedding, parseJsonArray, parseJsonObject, probePendingWork, readRebuildProgress, reanchorRebuildFingerprint, resolveEdgeDefinitions, resolveGrounding, resolveLibrarianStrategy, resolveNodeType, retiredTableName, runSourceRefNormalize, safeSlice, setupDatabase, sweepChunkSql, sweepHiSql, typeSatisfies, validateInlineEdges, validateManifest, warnChangedDefaultsOnce, windowChunkSql, windowHiSql, writeNormalizeStamp, writeRebuildStart };
9102
- //# sourceMappingURL=chunk-G2H6TJUC.mjs.map
9103
- //# sourceMappingURL=chunk-G2H6TJUC.mjs.map
9235
+ export { BaseRepository, CURRENT_SCHEMA_VERSION, DEFAULT_CHUNK_OVERLAP, DEFAULT_MAX_CHUNK_LENGTH, DEFAULT_MAX_EMBED_CHARS, DiagnosticBuffer, EMBED_CHARS_CEILING, EdgeRepository, EmbeddingService, FTS5_DRAIN_CHUNK, FTS5_REBUILD_SNAPSHOT_KEY, FTS5_REBUILD_WM_KEY, FTS5_RECLAIM_MERGE_PAGES, FTS5_RETIRED_COUNTER_KEY, FTS5_RETIRED_TABLES_KEY, FTS5_STATE_KEY, FTS5_SWEEP_CURSOR_KEY, HEAL_ANCHORS_PER_CANDIDATE, HEAL_BATCH_SIZE, HEAL_MAX_FACT_BODY_CHARS_L3, HEAL_MAX_TASKS, HEAL_RECHECK_MS, HOOK_TIMEOUT_MARKER, ImportExportService, IngestionService, JobManager, MAX_EMBED_ATTEMPTS, MIGRATIONS, MaintenanceService, MetadataRepository, ONTOLOGY_BACKFILL_BATCH_SIZE, ONTOLOGY_BACKFILL_MAX_PROMPT_CHARS, ONTOLOGY_BACKFILL_RECHECK_MS, ONTOLOGY_BACKFILL_SYSTEM_PROMPT, PromptService, PrunePartialFailureError, RetrievalService, SearchService, TemporalService, UnavailableIndexStrategy, UsageMeter, VectorRemovalRepository, VectorRemovalService, WikiBusyError, WikiDraftNotFound, WikiDuplicateHashError, WikiExternalDeletionError, WikiGraphNodeOwnershipConflict, WikiIngestEmptyError, WikiInvalidReadOptions, WikiMigrationRequiredError, WikiParseError, WikiSearchUnavailableError, WikiSourceRefHashCollision, WikiStrictOntologyViolation, WikiSupersedeError, WikiTransactionError, WriteService, __privateAdd, __privateGet, __privateSet, assertEntityId, assertEpochMs, chunkText, configureRandomSource, createLegacySourceTypeIndex, createdAtValue, detectSchemaVersion, drainChunkSql, drainHiSql, edgeTripleAllowed, emitDiagnostic, emptyManifest, entityDrainChunkSql, entityDrainHiSql, entitySummaryMetaKey, extractSqliteCode, factTokenCost, fts5LedgerDropSql, fts5PendingIndexesDdl, fts5TablesDdl, fts5TriggerNames, fts5TriggersDdl, generateId, idDrainChunkSql, idReindexChunkSql, isLiveAt, isRetiredTableName, isUsableDate, isWikiSearchUnavailableError, liveAtSql, normalizeSourceHash, normalizeSourceRef, normalizeTitleKey, packFactsByBudget, parseEmbedding, parseJsonArray, parseJsonObject, parseStoredSourcePointer, probePendingWork, readRebuildProgress, reanchorRebuildFingerprint, resolveEdgeDefinitions, resolveGrounding, resolveLibrarianStrategy, resolveNodeType, retiredTableName, runSourceRefNormalize, safeSlice, serializeSourcePointer, setupDatabase, sweepChunkSql, sweepHiSql, typeSatisfies, validateInlineEdges, validateManifest, validateSourcePointerValue, warnChangedDefaultsOnce, windowChunkSql, windowHiSql, writeNormalizeStamp, writeRebuildStart };
9236
+ //# sourceMappingURL=chunk-SIJD5GEF.mjs.map
9237
+ //# sourceMappingURL=chunk-SIJD5GEF.mjs.map