@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.
package/dist/index.d.mts CHANGED
@@ -1,5 +1,5 @@
1
- import { M as MemoryBundle, F as FormatContextOptions, G as GraphNeighborhood, a as MemoryDump, b as FormattedMemoryDump, O as OntologyMode, R as ReadOptions, S as SQLiteAdapter, W as WikiOptions, c as WikiMemory } from './testing-s6DBqXxQ.mjs';
2
- export { C as ChunkFailure, d as ClassifierAnswer, e as ClassifierQuestion, f as ClassifyRequest, g as ClassifyResponse, D as DegradedRecord, h as DraftPage, E as EmbedFactResult, i as EmbedFailureKind, j as EmbeddingMarkerKind, k as EntityMaintenanceReport, l as EntityStatus, m as ExtractedFact, n as ExtractedFactEdge, o as ExtractedFactWithOntology, p as ExtractedTask, q as ForgetParams, r as ForgetResult, s as GraphTraversalOptions, t as GroundingConfig, H as HEAL_BATCH_SIZE, u as HEAL_RECHECK_MS, v as HOOK_TIMEOUT_MARKER, w as HealResult, I as IngestDocumentResult, L as LLMProvider, x as LibrarianConfig, y as LibrarianGateConfig, z as LockedMaintenanceJob, A as MaintenanceJob, B as MaintenanceStopReason, J as MigrationPolicy, K as ONTOLOGY_BACKFILL_BATCH_SIZE, N as ONTOLOGY_BACKFILL_MAX_PROMPT_CHARS, P as ONTOLOGY_BACKFILL_RECHECK_MS, Q as OntologyBackfillResult, T as OntologyConfig, U as OntologyEdgeType, V as OntologyManifest, X as OntologyNodeType, Y as OntologyPromptContext, Z as OntologyUpdates, _ as PendingMaintenance, $ as PendingMigrationWork, a0 as PendingSourceStatus, a1 as PromptOverrides, a2 as PromptService, a3 as PrunePartialFailureError, a4 as ReembedResult, a5 as RememberInput, a6 as RunPendingMaintenanceOptions, a7 as RunPendingMaintenanceResult, a8 as SupersedeReplacement, a9 as VectorRanker, aa as VectorRankerFallback, ab as VectorRankerRankArgs, ac as VectorRankerSemanticResult, ad as WikiBusyError, ae as WikiBusyOperation, af as WikiCheckpoint, ag as WikiConfig, ah as WikiDiagnostic, ai as WikiDiagnosticCode, aj as WikiDiagnosticDetail, ak as WikiDiagnosticOperation, al as WikiDiagnosticSeverity, am as WikiDiagnosticTrigger, an as WikiDraftNotFound, ao as WikiDuplicateHashError, ap as WikiEdge, aq as WikiEvent, ar as WikiExternalDeletionError, as as WikiFact, at as WikiGraphNodeOwnershipConflict, au as WikiIngestEmptyError, av as WikiInstructions, aw as WikiInvalidReadOptions, ax as WikiLintReport, ay as WikiMemoryTestAccess, az as WikiMigrationRequiredError, aA as WikiOutboxEvent, aB as WikiParseError, aC as WikiSearchUnavailableError, aD as WikiSourceRefHashCollision, aE as WikiStrictOntologyViolation, aF as WikiSupersedeError, aG as WikiSupersedeReason, aH as WikiTask, aI as WikiTransactionError, aJ as isWikiSearchUnavailableError, aK as validateManifest } from './testing-s6DBqXxQ.mjs';
1
+ import { M as MemoryBundle, F as FormatContextOptions, G as GraphNeighborhood, a as MemoryDump, b as FormattedMemoryDump, O as OntologyMode, R as ReadOptions, S as SQLiteAdapter, W as WikiOptions, c as WikiMemory } from './testing-CmcCGx0_.mjs';
2
+ export { C as ChunkFailure, d as ClassifierAnswer, e as ClassifierQuestion, f as ClassifyRequest, g as ClassifyResponse, D as DegradedRecord, h as DraftPage, E as EmbedFactResult, i as EmbedFailureKind, j as EmbeddingMarkerKind, k as EntityMaintenanceReport, l as EntityStatus, m as ExtractedFact, n as ExtractedFactEdge, o as ExtractedFactWithOntology, p as ExtractedTask, q as ForgetParams, r as ForgetResult, s as GraphTraversalOptions, t as GroundingConfig, H as HEAL_BATCH_SIZE, u as HEAL_RECHECK_MS, v as HOOK_TIMEOUT_MARKER, w as HealResult, I as IngestDocumentResult, L as LLMProvider, x as LibrarianConfig, y as LibrarianGateConfig, z as LockedMaintenanceJob, A as MaintenanceJob, B as MaintenanceStopReason, J as MigrationPolicy, K as ONTOLOGY_BACKFILL_BATCH_SIZE, N as ONTOLOGY_BACKFILL_MAX_PROMPT_CHARS, P as ONTOLOGY_BACKFILL_RECHECK_MS, Q as OntologyBackfillResult, T as OntologyConfig, U as OntologyEdgeType, V as OntologyManifest, X as OntologyNodeType, Y as OntologyPromptContext, Z as OntologyUpdates, _ as PendingMaintenance, $ as PendingMigrationWork, a0 as PendingSourceStatus, a1 as PromptOverrides, a2 as PromptService, a3 as PrunePartialFailureError, a4 as ReembedResult, a5 as RememberInput, a6 as RunPendingMaintenanceOptions, a7 as RunPendingMaintenanceResult, a8 as SupersedeReplacement, a9 as VectorRanker, aa as VectorRankerFallback, ab as VectorRankerRankArgs, ac as VectorRankerSemanticResult, ad as WikiBusyError, ae as WikiBusyOperation, af as WikiCheckpoint, ag as WikiConfig, ah as WikiDiagnostic, ai as WikiDiagnosticCode, aj as WikiDiagnosticDetail, ak as WikiDiagnosticOperation, al as WikiDiagnosticSeverity, am as WikiDiagnosticTrigger, an as WikiDraftNotFound, ao as WikiDuplicateHashError, ap as WikiEdge, aq as WikiEvent, ar as WikiExternalDeletionError, as as WikiFact, at as WikiGraphNodeOwnershipConflict, au as WikiIngestEmptyError, av as WikiInstructions, aw as WikiInvalidReadOptions, ax as WikiLintReport, ay as WikiMemoryTestAccess, az as WikiMigrationRequiredError, aA as WikiOutboxEvent, aB as WikiParseError, aC as WikiSearchUnavailableError, aD as WikiSourcePointer, aE as WikiSourceRefHashCollision, aF as WikiStrictOntologyViolation, aG as WikiSupersedeError, aH as WikiSupersedeReason, aI as WikiTask, aJ as WikiTransactionError, aK as isWikiSearchUnavailableError, aL as validateManifest } from './testing-CmcCGx0_.mjs';
3
3
  import { OkfFile } from '@equationalapplications/core-okf';
4
4
 
5
5
  /**
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { M as MemoryBundle, F as FormatContextOptions, G as GraphNeighborhood, a as MemoryDump, b as FormattedMemoryDump, O as OntologyMode, R as ReadOptions, S as SQLiteAdapter, W as WikiOptions, c as WikiMemory } from './testing-s6DBqXxQ.js';
2
- export { C as ChunkFailure, d as ClassifierAnswer, e as ClassifierQuestion, f as ClassifyRequest, g as ClassifyResponse, D as DegradedRecord, h as DraftPage, E as EmbedFactResult, i as EmbedFailureKind, j as EmbeddingMarkerKind, k as EntityMaintenanceReport, l as EntityStatus, m as ExtractedFact, n as ExtractedFactEdge, o as ExtractedFactWithOntology, p as ExtractedTask, q as ForgetParams, r as ForgetResult, s as GraphTraversalOptions, t as GroundingConfig, H as HEAL_BATCH_SIZE, u as HEAL_RECHECK_MS, v as HOOK_TIMEOUT_MARKER, w as HealResult, I as IngestDocumentResult, L as LLMProvider, x as LibrarianConfig, y as LibrarianGateConfig, z as LockedMaintenanceJob, A as MaintenanceJob, B as MaintenanceStopReason, J as MigrationPolicy, K as ONTOLOGY_BACKFILL_BATCH_SIZE, N as ONTOLOGY_BACKFILL_MAX_PROMPT_CHARS, P as ONTOLOGY_BACKFILL_RECHECK_MS, Q as OntologyBackfillResult, T as OntologyConfig, U as OntologyEdgeType, V as OntologyManifest, X as OntologyNodeType, Y as OntologyPromptContext, Z as OntologyUpdates, _ as PendingMaintenance, $ as PendingMigrationWork, a0 as PendingSourceStatus, a1 as PromptOverrides, a2 as PromptService, a3 as PrunePartialFailureError, a4 as ReembedResult, a5 as RememberInput, a6 as RunPendingMaintenanceOptions, a7 as RunPendingMaintenanceResult, a8 as SupersedeReplacement, a9 as VectorRanker, aa as VectorRankerFallback, ab as VectorRankerRankArgs, ac as VectorRankerSemanticResult, ad as WikiBusyError, ae as WikiBusyOperation, af as WikiCheckpoint, ag as WikiConfig, ah as WikiDiagnostic, ai as WikiDiagnosticCode, aj as WikiDiagnosticDetail, ak as WikiDiagnosticOperation, al as WikiDiagnosticSeverity, am as WikiDiagnosticTrigger, an as WikiDraftNotFound, ao as WikiDuplicateHashError, ap as WikiEdge, aq as WikiEvent, ar as WikiExternalDeletionError, as as WikiFact, at as WikiGraphNodeOwnershipConflict, au as WikiIngestEmptyError, av as WikiInstructions, aw as WikiInvalidReadOptions, ax as WikiLintReport, ay as WikiMemoryTestAccess, az as WikiMigrationRequiredError, aA as WikiOutboxEvent, aB as WikiParseError, aC as WikiSearchUnavailableError, aD as WikiSourceRefHashCollision, aE as WikiStrictOntologyViolation, aF as WikiSupersedeError, aG as WikiSupersedeReason, aH as WikiTask, aI as WikiTransactionError, aJ as isWikiSearchUnavailableError, aK as validateManifest } from './testing-s6DBqXxQ.js';
1
+ import { M as MemoryBundle, F as FormatContextOptions, G as GraphNeighborhood, a as MemoryDump, b as FormattedMemoryDump, O as OntologyMode, R as ReadOptions, S as SQLiteAdapter, W as WikiOptions, c as WikiMemory } from './testing-CmcCGx0_.js';
2
+ export { C as ChunkFailure, d as ClassifierAnswer, e as ClassifierQuestion, f as ClassifyRequest, g as ClassifyResponse, D as DegradedRecord, h as DraftPage, E as EmbedFactResult, i as EmbedFailureKind, j as EmbeddingMarkerKind, k as EntityMaintenanceReport, l as EntityStatus, m as ExtractedFact, n as ExtractedFactEdge, o as ExtractedFactWithOntology, p as ExtractedTask, q as ForgetParams, r as ForgetResult, s as GraphTraversalOptions, t as GroundingConfig, H as HEAL_BATCH_SIZE, u as HEAL_RECHECK_MS, v as HOOK_TIMEOUT_MARKER, w as HealResult, I as IngestDocumentResult, L as LLMProvider, x as LibrarianConfig, y as LibrarianGateConfig, z as LockedMaintenanceJob, A as MaintenanceJob, B as MaintenanceStopReason, J as MigrationPolicy, K as ONTOLOGY_BACKFILL_BATCH_SIZE, N as ONTOLOGY_BACKFILL_MAX_PROMPT_CHARS, P as ONTOLOGY_BACKFILL_RECHECK_MS, Q as OntologyBackfillResult, T as OntologyConfig, U as OntologyEdgeType, V as OntologyManifest, X as OntologyNodeType, Y as OntologyPromptContext, Z as OntologyUpdates, _ as PendingMaintenance, $ as PendingMigrationWork, a0 as PendingSourceStatus, a1 as PromptOverrides, a2 as PromptService, a3 as PrunePartialFailureError, a4 as ReembedResult, a5 as RememberInput, a6 as RunPendingMaintenanceOptions, a7 as RunPendingMaintenanceResult, a8 as SupersedeReplacement, a9 as VectorRanker, aa as VectorRankerFallback, ab as VectorRankerRankArgs, ac as VectorRankerSemanticResult, ad as WikiBusyError, ae as WikiBusyOperation, af as WikiCheckpoint, ag as WikiConfig, ah as WikiDiagnostic, ai as WikiDiagnosticCode, aj as WikiDiagnosticDetail, ak as WikiDiagnosticOperation, al as WikiDiagnosticSeverity, am as WikiDiagnosticTrigger, an as WikiDraftNotFound, ao as WikiDuplicateHashError, ap as WikiEdge, aq as WikiEvent, ar as WikiExternalDeletionError, as as WikiFact, at as WikiGraphNodeOwnershipConflict, au as WikiIngestEmptyError, av as WikiInstructions, aw as WikiInvalidReadOptions, ax as WikiLintReport, ay as WikiMemoryTestAccess, az as WikiMigrationRequiredError, aA as WikiOutboxEvent, aB as WikiParseError, aC as WikiSearchUnavailableError, aD as WikiSourcePointer, aE as WikiSourceRefHashCollision, aF as WikiStrictOntologyViolation, aG as WikiSupersedeError, aH as WikiSupersedeReason, aI as WikiTask, aJ as WikiTransactionError, aK as isWikiSearchUnavailableError, aL as validateManifest } from './testing-CmcCGx0_.js';
3
3
  import { OkfFile } from '@equationalapplications/core-okf';
4
4
 
5
5
  /**
package/dist/index.js CHANGED
@@ -42,7 +42,9 @@ var SEVERITY = {
42
42
  external_deletion_pending: "warn",
43
43
  external_deletion_discarded: "warn",
44
44
  guidance_too_long: "warn",
45
- guidance_resolver_failed: "warn"
45
+ guidance_resolver_failed: "warn",
46
+ source_pointer_unresolved: "warn",
47
+ source_pointer_invalid: "warn"
46
48
  };
47
49
  var MESSAGE = {
48
50
  ingest_chunk_failed: "One or more document chunks failed to parse or generate.",
@@ -70,7 +72,9 @@ var MESSAGE = {
70
72
  external_deletion_pending: "Removals owed to the external vector index are still pending.",
71
73
  external_deletion_discarded: "Pending external vector removals were discarded because forceDeleteIgnoreRankerHook is set.",
72
74
  guidance_too_long: "The configured guidance exceeded the length cap and was not sent for this pass.",
73
- guidance_resolver_failed: "The per-entity guidance resolver failed; its value was not used for this pass."
75
+ guidance_resolver_failed: "The per-entity guidance resolver failed; its value was not used for this pass.",
76
+ source_pointer_unresolved: "A stored librarian fact carries no source pointer because the model answer could not yield one.",
77
+ source_pointer_invalid: "Import met a malformed source pointer value and stored a null pointer."
74
78
  };
75
79
  var warnedNonFunction = /* @__PURE__ */ new WeakSet();
76
80
  function copyDetail(detail) {
@@ -945,7 +949,8 @@ async function setupDatabase(db, prefix) {
945
949
  valid_from INTEGER,
946
950
  valid_to INTEGER,
947
951
  superseded_by TEXT,
948
- superseded_at INTEGER
952
+ superseded_at INTEGER,
953
+ source_pointer TEXT
949
954
  );
950
955
 
951
956
  CREATE INDEX IF NOT EXISTS ${prefix}entries_entity_idx ON ${prefix}entries(entity_id);
@@ -1594,6 +1599,17 @@ var MIGRATIONS = [
1594
1599
  );
1595
1600
  if (row?.n) await db.execAsync(fts5PendingIndexesDdl(prefix));
1596
1601
  }
1602
+ },
1603
+ {
1604
+ version: 16,
1605
+ description: "Source pointers on librarian facts: nullable source_pointer TEXT on entries",
1606
+ run: async (db, prefix) => {
1607
+ const cols = await db.getAllAsync(`PRAGMA table_info(${prefix}entries)`);
1608
+ const existing = new Set(cols.map((c) => c.name));
1609
+ if (!existing.has("source_pointer")) {
1610
+ await db.execAsync(`ALTER TABLE ${prefix}entries ADD COLUMN source_pointer TEXT`);
1611
+ }
1612
+ }
1597
1613
  }
1598
1614
  ];
1599
1615
  async function createLegacySourceTypeIndex(db, prefix) {
@@ -1834,6 +1850,61 @@ function assertEpochMs(name, v) {
1834
1850
  }
1835
1851
  return Math.trunc(v);
1836
1852
  }
1853
+
1854
+ // src/utils/sourcePointer.ts
1855
+ var POINTER_SLOTS = ["event_id", "ref", "quote", "position"];
1856
+ function isStringOrNull(v) {
1857
+ return v === null || typeof v === "string";
1858
+ }
1859
+ function isValidPosition(v) {
1860
+ if (v === null) return true;
1861
+ if (typeof v !== "object" || v === null || Array.isArray(v)) return false;
1862
+ const o = v;
1863
+ const keys = Object.keys(o);
1864
+ if (keys.length !== 2 || !("start" in o) || !("length" in o)) return false;
1865
+ const { start, length } = o;
1866
+ return typeof start === "number" && Number.isInteger(start) && start >= 0 && typeof length === "number" && Number.isInteger(length) && length >= 0;
1867
+ }
1868
+ function validateSourcePointerValue(v) {
1869
+ if (v === null) return null;
1870
+ if (typeof v !== "object" || Array.isArray(v)) return void 0;
1871
+ const o = v;
1872
+ const keys = Object.keys(o);
1873
+ for (const k of keys) {
1874
+ if (!POINTER_SLOTS.includes(k)) return void 0;
1875
+ }
1876
+ 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"])) {
1877
+ return void 0;
1878
+ }
1879
+ if (!isValidPosition(o["position"] === void 0 ? null : o["position"])) return void 0;
1880
+ const normalized = {
1881
+ event_id: o["event_id"] ?? null,
1882
+ ref: o["ref"] ?? null,
1883
+ quote: o["quote"] ?? null,
1884
+ position: o["position"] ?? null
1885
+ };
1886
+ if (normalized.event_id === null && normalized.ref === null && normalized.quote === null && normalized.position === null) {
1887
+ return null;
1888
+ }
1889
+ return normalized;
1890
+ }
1891
+ function parseStoredSourcePointer(raw) {
1892
+ if (raw === null || raw === void 0) return null;
1893
+ if (typeof raw !== "string") return null;
1894
+ let parsed;
1895
+ try {
1896
+ parsed = JSON.parse(raw);
1897
+ } catch {
1898
+ return null;
1899
+ }
1900
+ const v = validateSourcePointerValue(parsed);
1901
+ return v === void 0 ? null : v;
1902
+ }
1903
+ function serializeSourcePointer(p) {
1904
+ return p ? JSON.stringify(p) : null;
1905
+ }
1906
+
1907
+ // src/repositories/EntryRepository.ts
1837
1908
  function mapRowToFact(row) {
1838
1909
  const tags = (() => {
1839
1910
  if (Array.isArray(row.tags)) return row.tags;
@@ -1847,7 +1918,8 @@ function mapRowToFact(row) {
1847
1918
  const okf_verified = parseJsonArray(row.okf_verified, []);
1848
1919
  const now = Date.now();
1849
1920
  const staleAfterRaw = row.stale_after != null ? Number(row.stale_after) : null;
1850
- return {
1921
+ const sourcePointer = parseStoredSourcePointer(row.source_pointer);
1922
+ const mapped = {
1851
1923
  id: row.id,
1852
1924
  entity_id: row.entity_id,
1853
1925
  title: row.title,
@@ -1880,8 +1952,13 @@ function mapRowToFact(row) {
1880
1952
  ...row.valid_from != null ? { valid_from: Number(row.valid_from) } : {},
1881
1953
  ...row.valid_to != null ? { valid_to: Number(row.valid_to) } : {},
1882
1954
  ...row.superseded_by != null ? { superseded_by: String(row.superseded_by) } : {},
1883
- ...row.superseded_at != null ? { superseded_at: Number(row.superseded_at) } : {}
1955
+ ...row.superseded_at != null ? { superseded_at: Number(row.superseded_at) } : {},
1956
+ // Source pointer (specs/source-pointers): key appears only when non-null,
1957
+ // same temporal-fields pattern. Tolerant read: a malformed stored value
1958
+ // reads as null without throwing (test 1).
1959
+ ...sourcePointer ? { source_pointer: sourcePointer } : {}
1884
1960
  };
1961
+ return mapped;
1885
1962
  }
1886
1963
  function normalizeEmbeddingBlobValue(blob) {
1887
1964
  if (blob instanceof Uint8Array) return blob;
@@ -1996,7 +2073,7 @@ var _EntryRepository = class _EntryRepository extends BaseRepository {
1996
2073
  const existingRow = await executor.getFirstAsync(
1997
2074
  `SELECT id, entity_id, lifecycle_status, stale_after, generated_by,
1998
2075
  okf_sources, okf_verified, okf_usage_window,
1999
- last_verified_at, last_verified_by
2076
+ last_verified_at, last_verified_by, source_pointer
2000
2077
  FROM ${this.prefix}entries WHERE id = ?`,
2001
2078
  [fact.id]
2002
2079
  );
@@ -2010,8 +2087,8 @@ var _EntryRepository = class _EntryRepository extends BaseRepository {
2010
2087
  source_hash, source_ref, created_at, updated_at, last_accessed_at, access_count,
2011
2088
  deleted_at, embedding_blob, embedding, okf_type,
2012
2089
  lifecycle_status, stale_after, generated_by, last_verified_at, last_verified_by,
2013
- okf_sources, okf_verified, okf_usage_window
2014
- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
2090
+ okf_sources, okf_verified, okf_usage_window, source_pointer
2091
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
2015
2092
  ON CONFLICT(id) DO UPDATE SET
2016
2093
  title = excluded.title,
2017
2094
  body = excluded.body,
@@ -2059,7 +2136,8 @@ var _EntryRepository = class _EntryRepository extends BaseRepository {
2059
2136
  fact.last_verified_by ?? null,
2060
2137
  fact.okf_sources ? JSON.stringify(fact.okf_sources) : null,
2061
2138
  fact.okf_verified ? JSON.stringify(fact.okf_verified) : null,
2062
- fact.okf_usage_window ? JSON.stringify(fact.okf_usage_window) : null
2139
+ fact.okf_usage_window ? JSON.stringify(fact.okf_usage_window) : null,
2140
+ serializeSourcePointer(fact.source_pointer)
2063
2141
  ]
2064
2142
  );
2065
2143
  if (result.changes === 0) {
@@ -2082,7 +2160,8 @@ var _EntryRepository = class _EntryRepository extends BaseRepository {
2082
2160
  okf_verified: parseJsonArray(existingRow.okf_verified, []),
2083
2161
  okf_usage_window: parseJsonObject(existingRow.okf_usage_window),
2084
2162
  last_verified_at: existingRow.last_verified_at != null ? Number(existingRow.last_verified_at) : null,
2085
- last_verified_by: existingRow.last_verified_by ?? null
2163
+ last_verified_by: existingRow.last_verified_by ?? null,
2164
+ source_pointer: parseStoredSourcePointer(existingRow.source_pointer)
2086
2165
  } : null;
2087
2166
  await this.outbox.push({
2088
2167
  entityId: fact.entity_id,
@@ -2142,7 +2221,7 @@ var _EntryRepository = class _EntryRepository extends BaseRepository {
2142
2221
  const rows = await executor.getAllAsync(sql, args);
2143
2222
  return rows.map((row) => row.id);
2144
2223
  }
2145
- async upsertForImport(fact, tx) {
2224
+ async upsertForImport(fact, tx, sourcePointerPresent = false) {
2146
2225
  const executor = this.getExecutor(tx);
2147
2226
  const tagsJson = JSON.stringify(fact.tags);
2148
2227
  const embeddingBlob = this.normalizeEmbeddingBlob(fact.embedding_blob);
@@ -2152,8 +2231,8 @@ var _EntryRepository = class _EntryRepository extends BaseRepository {
2152
2231
  source_hash, source_ref, created_at, updated_at, last_accessed_at, access_count,
2153
2232
  deleted_at, embedding_blob, embedding, okf_type,
2154
2233
  lifecycle_status, stale_after, generated_by, last_verified_at, last_verified_by,
2155
- okf_sources, okf_verified, okf_usage_window
2156
- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
2234
+ okf_sources, okf_verified, okf_usage_window, source_pointer
2235
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
2157
2236
  ON CONFLICT(id) DO UPDATE SET
2158
2237
  entity_id = excluded.entity_id,
2159
2238
  title = excluded.title,
@@ -2181,7 +2260,8 @@ var _EntryRepository = class _EntryRepository extends BaseRepository {
2181
2260
  last_verified_by = excluded.last_verified_by,
2182
2261
  okf_sources = excluded.okf_sources,
2183
2262
  okf_verified = excluded.okf_verified,
2184
- okf_usage_window = excluded.okf_usage_window`,
2263
+ okf_usage_window = excluded.okf_usage_window,
2264
+ source_pointer = CASE WHEN ? THEN excluded.source_pointer ELSE source_pointer END`,
2185
2265
  [
2186
2266
  fact.id,
2187
2267
  fact.entity_id,
@@ -2208,7 +2288,11 @@ var _EntryRepository = class _EntryRepository extends BaseRepository {
2208
2288
  fact.last_verified_by ?? null,
2209
2289
  fact.okf_sources ? JSON.stringify(fact.okf_sources) : null,
2210
2290
  fact.okf_verified ? JSON.stringify(fact.okf_verified) : null,
2211
- fact.okf_usage_window ? JSON.stringify(fact.okf_usage_window) : null
2291
+ fact.okf_usage_window ? JSON.stringify(fact.okf_usage_window) : null,
2292
+ serializeSourcePointer(fact.source_pointer),
2293
+ // The presence flag binds to the SET clause's CASE, AFTER the INSERT
2294
+ // values above.
2295
+ sourcePointerPresent ? 1 : 0
2212
2296
  ]
2213
2297
  );
2214
2298
  return result;
@@ -6553,6 +6637,10 @@ ${JSON.stringify(facts, null, 2)}`
6553
6637
  systemPrompt: this.appendGrounding(this.appendGuidance(this.appendOntology(OPS_EXTRACT_SYSTEM_PROMPT, ontologyContext), guidance), "librarian"),
6554
6638
  userPrompt: `Events:
6555
6639
  ${lines.join("\n")}`,
6640
+ // Corpus entries are one-per-batch-event in batch order (summaries are
6641
+ // TEXT NOT NULL, so the filter inside buildGroundingCorpus drops
6642
+ // nothing): extract.ts stores a candidate's `sourcePartIndex` as the
6643
+ // batch index and buildSourcePointer reads the quote back by it.
6556
6644
  ...grounding ? { groundingCorpus: buildGroundingCorpus(events.map((l) => l.event.summary)) } : {}
6557
6645
  };
6558
6646
  }
@@ -8258,9 +8346,20 @@ var runLegacyLibrarianPass = async (deps, ctx) => {
8258
8346
  access_count: 0,
8259
8347
  deleted_at: null,
8260
8348
  okf_type: normalized.okf_type,
8349
+ // Legacy writes no pointer (spec §Legacy path): the column stays null
8350
+ // on every legacy fact, and the legacy prompt keeps its exact text.
8351
+ source_pointer: null,
8261
8352
  ...grounding?.trust
8262
8353
  };
8263
8354
  await deps.entryRepo.upsert(factObj, tx);
8355
+ const volunteeredSourceEvent = facts[validFactItemIndexes[k]]?.source_event;
8356
+ if (volunteeredSourceEvent !== void 0 && volunteeredSourceEvent !== null) {
8357
+ diagBuffer.push({
8358
+ ...diagBase,
8359
+ code: "source_pointer_unresolved",
8360
+ detail: { factId: id, itemIndex: validFactItemIndexes[k], reason: "unsupported_strategy" }
8361
+ });
8362
+ }
8264
8363
  insertedFacts.push({ id, entity_id: entityId, title: fact.title, body: fact.body, tags: JSON.stringify(fact.tags) });
8265
8364
  factsForDedupe.push(factObj);
8266
8365
  titleIndex.set(normalizeTitleKey(fact.title), { id, okf_type: normalized.okf_type });
@@ -8374,9 +8473,23 @@ async function runExtract(deps, ctx, batch) {
8374
8473
  return;
8375
8474
  }
8376
8475
  const r = raw;
8377
- const sourceLabel = typeof r.source_event === "string" && byLabel.has(r.source_event) ? r.source_event : null;
8476
+ let sourceEventId = null;
8477
+ let sourcePartIndex = null;
8478
+ let pointerUnresolved;
8479
+ const rawSourceEvent = r.source_event;
8480
+ if (rawSourceEvent === void 0 || rawSourceEvent === null) {
8481
+ pointerUnresolved = "missing";
8482
+ } else if (typeof rawSourceEvent === "string" && byLabel.has(rawSourceEvent)) {
8483
+ const labeled = byLabel.get(rawSourceEvent);
8484
+ sourceEventId = labeled.event.id;
8485
+ sourcePartIndex = batch.findIndex((b) => b.label === rawSourceEvent);
8486
+ pointerUnresolved = null;
8487
+ } else {
8488
+ pointerUnresolved = "unknown_label";
8489
+ }
8490
+ const sourceLabel = typeof rawSourceEvent === "string" && byLabel.has(rawSourceEvent) ? rawSourceEvent : null;
8378
8491
  const validFrom = parseValidFrom(r.valid_from) ?? (sourceLabel ? byLabel.get(sourceLabel).at : defaultValidFrom);
8379
- candidates.push({ index, fact, sourceLabel, validFrom });
8492
+ candidates.push({ index, fact, sourceLabel, sourceEventId, sourcePartIndex, pointerUnresolved, validFrom });
8380
8493
  });
8381
8494
  const tasks = [];
8382
8495
  (Array.isArray(parsed.tasks) ? parsed.tasks : []).forEach((raw, index) => {
@@ -8653,6 +8766,17 @@ var TemporalService = class {
8653
8766
  };
8654
8767
 
8655
8768
  // src/services/librarian/ops/apply.ts
8769
+ function buildSourcePointer(candidate, verdict, groundingOn, groundingCorpus) {
8770
+ if (candidate.sourceEventId === null) return null;
8771
+ let quote = null;
8772
+ if (groundingOn && verdict?.status === "grounded" && candidate.sourcePartIndex !== null) {
8773
+ const part = groundingCorpus?.[candidate.sourcePartIndex];
8774
+ if (part !== void 0) {
8775
+ quote = verdict.retained.find((q) => part.includes(q)) ?? null;
8776
+ }
8777
+ }
8778
+ return { event_id: candidate.sourceEventId, ref: null, quote, position: null };
8779
+ }
8656
8780
  async function applyOps(deps, ctx, input) {
8657
8781
  const { entityId, trigger } = ctx;
8658
8782
  const diagBase = { entityId, operation: "librarian", trigger };
@@ -8681,7 +8805,8 @@ async function applyOps(deps, ctx, input) {
8681
8805
  const drops = [];
8682
8806
  const normalized = deps.ontologyService?.validateAndNormalizeFact(fact, manifest, { strict: false, drops }) ?? { okf_type: null, edges: [] };
8683
8807
  for (const d of drops) input.diagnostics.push(edgeDropDiagnostic(d, { ...diagBase, factId: id }));
8684
- const g2 = grounding ? groundingOutcome(checkGrounding(fact.evidence, input.groundingCorpus ?? [], grounding), now) : null;
8808
+ const gVerdict = grounding ? checkGrounding(fact.evidence, input.groundingCorpus ?? [], grounding) : null;
8809
+ const g2 = gVerdict ? groundingOutcome(gVerdict, now) : null;
8685
8810
  if (g2?.diagnostic) {
8686
8811
  input.diagnostics.push({
8687
8812
  ...diagBase,
@@ -8689,6 +8814,7 @@ async function applyOps(deps, ctx, input) {
8689
8814
  detail: { factId: id, itemIndex: g.candidate.index, reason: g2.diagnostic.reason }
8690
8815
  });
8691
8816
  }
8817
+ const pointer = buildSourcePointer(g.candidate, gVerdict, grounding !== void 0 && grounding !== null, input.groundingCorpus);
8692
8818
  const row = {
8693
8819
  id,
8694
8820
  entity_id: entityId,
@@ -8705,11 +8831,19 @@ async function applyOps(deps, ctx, input) {
8705
8831
  access_count: 0,
8706
8832
  deleted_at: null,
8707
8833
  okf_type: normalized.okf_type,
8834
+ source_pointer: pointer,
8708
8835
  ...g2?.trust,
8709
8836
  ...draft ? { lifecycle_status: "draft" } : {}
8710
8837
  };
8711
8838
  await deps.entryRepo.upsert(row, tx);
8712
8839
  await deps.entryRepo.setTemporal(id, entityId, { valid_from: validFrom }, tx);
8840
+ if (g.candidate.pointerUnresolved !== null) {
8841
+ input.diagnostics.push({
8842
+ ...diagBase,
8843
+ code: "source_pointer_unresolved",
8844
+ detail: { factId: id, itemIndex: g.candidate.index, reason: g.candidate.pointerUnresolved }
8845
+ });
8846
+ }
8713
8847
  titleIndex.set(normalizeTitleKey(title), { id, okf_type: normalized.okf_type });
8714
8848
  if (normalized.edges.length > 0) pendingEdges.push({ sourceId: id, sourceType: normalized.okf_type, edges: normalized.edges });
8715
8849
  const textChanged = title !== fact.title || body !== fact.body;
@@ -9733,6 +9867,7 @@ var MaintenanceService = class {
9733
9867
  source_type: "librarian_inferred",
9734
9868
  source_hash: null,
9735
9869
  source_ref: null,
9870
+ source_pointer: null,
9736
9871
  created_at: now,
9737
9872
  updated_at: now,
9738
9873
  last_accessed_at: null,
@@ -10652,6 +10787,19 @@ var ImportExportService = class {
10652
10787
  );
10653
10788
  }
10654
10789
  }
10790
+ const hasSourcePointerKey = fact["source_pointer"] !== void 0;
10791
+ const rawPointerValue = hasSourcePointerKey ? fact["source_pointer"] : void 0;
10792
+ const pointerValidated = hasSourcePointerKey ? validateSourcePointerValue(rawPointerValue) : null;
10793
+ if (pointerValidated === void 0) {
10794
+ emitDiagnostic(this.options, {
10795
+ code: "source_pointer_invalid",
10796
+ operation: "importDump",
10797
+ trigger: "call",
10798
+ entityId,
10799
+ detail: { factId: fact.id }
10800
+ });
10801
+ }
10802
+ const sourcePointer = pointerValidated === void 0 ? null : pointerValidated;
10655
10803
  const factObj = {
10656
10804
  id: fact.id,
10657
10805
  entity_id: entityId,
@@ -10669,6 +10817,7 @@ var ImportExportService = class {
10669
10817
  deleted_at: fact.deleted_at,
10670
10818
  embedding_blob: blobData ?? void 0,
10671
10819
  okf_type: fact.okf_type ?? null,
10820
+ source_pointer: sourcePointer,
10672
10821
  // OKF v0.2 — forwarded as-is; parseOkfBundle / the caller is responsible for
10673
10822
  // populating these per spec, importDump does not derive or validate them.
10674
10823
  lifecycle_status: fact.lifecycle_status ?? "stable",
@@ -10686,7 +10835,7 @@ var ImportExportService = class {
10686
10835
  return { last_verified_at: latest?.at ?? null, last_verified_by: latest?.by ?? null };
10687
10836
  })()
10688
10837
  };
10689
- await this.entryRepo.upsertForImport(factObj, tx);
10838
+ await this.entryRepo.upsertForImport(factObj, tx, hasSourcePointerKey);
10690
10839
  await this.entryRepo.setTemporal(fact.id, entityId, {
10691
10840
  valid_from: fact.valid_from ?? null,
10692
10841
  valid_to: fact.valid_to ?? null,
@@ -14327,6 +14476,15 @@ function isoDateOrOmit(ms) {
14327
14476
  if (!Number.isFinite(d.getTime())) return void 0;
14328
14477
  return d.toISOString().slice(0, 10);
14329
14478
  }
14479
+ function sourcePointerFrontmatter(p) {
14480
+ if (!p) return void 0;
14481
+ return {
14482
+ ...p.event_id != null ? { event_id: p.event_id } : {},
14483
+ ...p.ref != null ? { ref: p.ref } : {},
14484
+ ...p.quote != null ? { quote: p.quote } : {},
14485
+ ...p.position != null ? { position: p.position } : {}
14486
+ };
14487
+ }
14330
14488
  function factFrontmatterV2(f) {
14331
14489
  return {
14332
14490
  type: f.okf_type ?? "fact",
@@ -14365,7 +14523,9 @@ function factFrontmatterV2(f) {
14365
14523
  ...f.valid_from != null ? { valid_from: f.valid_from } : {},
14366
14524
  ...f.valid_to != null ? { valid_to: f.valid_to } : {},
14367
14525
  ...f.superseded_by != null ? { superseded_by: f.superseded_by } : {},
14368
- ...f.superseded_at != null ? { superseded_at: f.superseded_at } : {}
14526
+ ...f.superseded_at != null ? { superseded_at: f.superseded_at } : {},
14527
+ // Source pointer (specs/source-pointers): map only when non-null; null slots omitted.
14528
+ ...sourcePointerFrontmatter(f.source_pointer) ? { source_pointer: sourcePointerFrontmatter(f.source_pointer) } : {}
14369
14529
  };
14370
14530
  }
14371
14531
  function taskFrontmatterV2(t) {
@@ -14409,7 +14569,9 @@ function factFrontmatterV1(f) {
14409
14569
  created_at: f.created_at,
14410
14570
  access_count: f.access_count,
14411
14571
  last_accessed_at: f.last_accessed_at,
14412
- deleted_at: f.deleted_at
14572
+ deleted_at: f.deleted_at,
14573
+ // Source pointer (specs/source-pointers): same map rule as the v2 path.
14574
+ ...sourcePointerFrontmatter(f.source_pointer) ? { source_pointer: sourcePointerFrontmatter(f.source_pointer) } : {}
14413
14575
  };
14414
14576
  }
14415
14577
  function taskFrontmatterV1(t) {
@@ -14665,7 +14827,7 @@ function parseLogEntryText(text) {
14665
14827
  }
14666
14828
  return { event_type, summary: unescapeLogSummary((plainSummary ?? "").trim()) };
14667
14829
  }
14668
- function frontmatterToFact(entityId, id, frontmatter, body, now) {
14830
+ function frontmatterToFact(entityId, id, frontmatter, body, now, droppedPointerValues) {
14669
14831
  const created_at = parseFrontmatterTimestamp(frontmatter.created_at, now);
14670
14832
  const updated_at = parseFrontmatterTimestamp(
14671
14833
  frontmatter.generated?.at,
@@ -14719,7 +14881,23 @@ function frontmatterToFact(entityId, id, frontmatter, body, now) {
14719
14881
  ...optionalEpoch("valid_from", frontmatter.valid_from),
14720
14882
  ...optionalEpoch("valid_to", frontmatter.valid_to),
14721
14883
  ...typeof frontmatter.superseded_by === "string" ? { superseded_by: frontmatter.superseded_by } : {},
14722
- ...optionalEpoch("superseded_at", frontmatter.superseded_at)
14884
+ ...optionalEpoch("superseded_at", frontmatter.superseded_at),
14885
+ // Source pointer (specs/source-pointers §Export, import, and OKF): the
14886
+ // parse path has no diagnostic channel, so it reports through the result.
14887
+ // ABSENT key → the property is omitted (not null), so the import
14888
+ // presence guard survives the parse. Malformed → the property is omitted
14889
+ // AND the drop is reported as entry id + reason slug — never the raw
14890
+ // value, which can carry quote text.
14891
+ ...(() => {
14892
+ const raw = frontmatter.source_pointer;
14893
+ if (raw === void 0) return {};
14894
+ const v = validateSourcePointerValue(raw);
14895
+ if (v === void 0) {
14896
+ droppedPointerValues.push({ factId: id, reason: "malformed" });
14897
+ return {};
14898
+ }
14899
+ return { source_pointer: v };
14900
+ })()
14723
14901
  };
14724
14902
  }
14725
14903
  function optionalEpoch(key, v) {
@@ -14840,6 +15018,7 @@ function parseOkfBundle(entityId, files, options) {
14840
15018
  }
14841
15019
  const facts = [];
14842
15020
  const tasks = [];
15021
+ const droppedPointerValues = [];
14843
15022
  const edges = [];
14844
15023
  let logContent = null;
14845
15024
  const logMdPath = findLogMdPath(allowedFiles);
@@ -14857,7 +15036,7 @@ function parseOkfBundle(entityId, files, options) {
14857
15036
  const edgeLinks = isProfile1 || isLegacyV1 ? relatedLinks : [...relatedLinks, ...coreOkf.extractMarkdownLinks(storedBody)];
14858
15037
  const usesV1StatusRule = isProfile1 || isLegacyV1 || profile === void 0 && okfVersion === void 0;
14859
15038
  if (route === "fact") {
14860
- facts.push(frontmatterToFact(entityId, resolvedId, frontmatter, storedBody, now));
15039
+ facts.push(frontmatterToFact(entityId, resolvedId, frontmatter, storedBody, now, droppedPointerValues));
14861
15040
  } else {
14862
15041
  tasks.push(frontmatterToTask(entityId, resolvedId, frontmatter, now, usesV1StatusRule));
14863
15042
  }
@@ -14924,7 +15103,8 @@ function parseOkfBundle(entityId, files, options) {
14924
15103
  generatedAt: now,
14925
15104
  entities: {
14926
15105
  [entityId]: { facts, tasks, events, edges, summary: entitySummary }
14927
- }
15106
+ },
15107
+ ...droppedPointerValues.length > 0 ? { dropped_pointer_values: droppedPointerValues } : {}
14928
15108
  };
14929
15109
  }
14930
15110