@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.
@@ -471,6 +471,28 @@ interface ReadOptions {
471
471
  */
472
472
  tokenBudget?: number;
473
473
  }
474
+ /**
475
+ * A source pointer: the structured reference from a librarian fact to the
476
+ * event it came from, with its supporting quote and its position
477
+ * (specs/source-pointers §The pointer). Stored as JSON in the nullable
478
+ * `source_pointer` column on entries.
479
+ * - `event_id`: the batch event the fact was extracted from (ops strategy),
480
+ * or null when unresolved/unsupported.
481
+ * - `ref`: host-supplied ref slot; no producer exists in this release — always null.
482
+ * - `quote`: a grounding-verified, normalized, length-capped (on the ops
483
+ * write path; import restores verbatim) quote from the named event's
484
+ * own corpus part (ops only), or null.
485
+ * - `position`: offset slot; no producer exists in this release — always null.
486
+ */
487
+ type WikiSourcePointer = {
488
+ event_id: string | null;
489
+ ref: string | null;
490
+ quote: string | null;
491
+ position: {
492
+ start: number;
493
+ length: number;
494
+ } | null;
495
+ };
474
496
  interface WikiFact {
475
497
  id: string;
476
498
  entity_id: string;
@@ -552,6 +574,8 @@ interface WikiFact {
552
574
  superseded_by?: string | null;
553
575
  /** Epoch ms the supersession was recorded (transaction time). Audit only. */
554
576
  superseded_at?: number | null;
577
+ /** Structured provenance from this librarian fact to its source event, with the verified quote. Null for legacy/heal/ingest facts. */
578
+ source_pointer?: WikiSourcePointer | null;
555
579
  }
556
580
  interface WikiTask {
557
581
  id: string;
@@ -823,7 +847,7 @@ type WikiDiagnosticSeverity = 'info' | 'warn' | 'error';
823
847
  * Closed for this release series, but new codes are added in minor versions:
824
848
  * hosts must tolerate codes they do not recognize.
825
849
  */
826
- type WikiDiagnosticCode = 'ingest_chunk_failed' | 'fact_rejected' | 'task_rejected' | 'fact_deduplicated' | 'edge_dropped' | 'embedding_failed' | 'hook_failed' | 'background_job_failed' | 'heal_skipped' | 'grounding_missing' | 'grounding_failed' | 'classification_low_confidence' | 'classification_invalid' | 'llm_usage' | 'librarian_gate' | 'librarian_op_rejected' | 'contradicts_document' | 'resolve_failed' | 'read_budget' | 'event_retention_held' | 'event_created_at_clamped' | 'event_created_at_restamped' | 'external_deletion_pending' | 'external_deletion_discarded' | 'guidance_too_long' | 'guidance_resolver_failed';
850
+ type WikiDiagnosticCode = 'ingest_chunk_failed' | 'fact_rejected' | 'task_rejected' | 'fact_deduplicated' | 'edge_dropped' | 'embedding_failed' | 'hook_failed' | 'background_job_failed' | 'heal_skipped' | 'grounding_missing' | 'grounding_failed' | 'classification_low_confidence' | 'classification_invalid' | 'llm_usage' | 'librarian_gate' | 'librarian_op_rejected' | 'contradicts_document' | 'resolve_failed' | 'read_budget' | 'event_retention_held' | 'event_created_at_clamped' | 'event_created_at_restamped' | 'external_deletion_pending' | 'external_deletion_discarded' | 'guidance_too_long' | 'guidance_resolver_failed' | 'source_pointer_unresolved' | 'source_pointer_invalid';
827
851
  /** The service run that emitted the diagnostic. */
828
852
  type WikiDiagnosticOperation = 'ingest' | 'upsertGraph' | 'librarian' | 'heal' | 'ontologyBackfill' | 'reembed' | 'importDump' | 'write' | 'supersede' | 'remember' | 'read' | 'prune' | 'externalDeletion';
829
853
  /** `'auto'` when a write threshold started the run (auto-librarian / auto-heal); `'call'` when the host did. */
@@ -1004,6 +1028,16 @@ interface MemoryBundle {
1004
1028
  interface MemoryDump {
1005
1029
  generatedAt: number;
1006
1030
  entities: Record<string, MemoryBundle>;
1031
+ /**
1032
+ * Source-pointer parse report (specs/source-pointers §Export, import, and OKF).
1033
+ * Present ONLY when `parseOkfBundle` dropped a malformed `source_pointer`
1034
+ * value: entry ids and a reason slug — never raw pointer values, because a
1035
+ * pointer can carry quote text. Export-only metadata; `importDump` ignores it.
1036
+ */
1037
+ dropped_pointer_values?: Array<{
1038
+ factId: string;
1039
+ reason: string;
1040
+ }>;
1007
1041
  }
1008
1042
  interface FormattedMemoryDump {
1009
1043
  manifest: string;
@@ -1674,7 +1708,7 @@ declare class EntryRepository extends BaseRepository {
1674
1708
  }>>;
1675
1709
  findIdById(id: string, entityId: string, tx?: SQLiteAdapter): Promise<string | null>;
1676
1710
  findIdsBySource(entityId: string, sourceRef: string | null, sourceHash: string | null, tx?: SQLiteAdapter, includeDeleted?: boolean): Promise<string[]>;
1677
- upsertForImport(fact: WikiFact, tx: SQLiteAdapter): Promise<{
1711
+ upsertForImport(fact: WikiFact, tx: SQLiteAdapter, sourcePointerPresent?: boolean): Promise<{
1678
1712
  changes: number;
1679
1713
  lastInsertRowId: number;
1680
1714
  }>;
@@ -4558,5 +4592,5 @@ declare class WikiMemory {
4558
4592
  setGeneratedByTask(taskId: string, entityId: string, actor: string): Promise<void>;
4559
4593
  }
4560
4594
 
4561
- export { HEAL_BATCH_SIZE as H, ONTOLOGY_BACKFILL_BATCH_SIZE as K, ONTOLOGY_BACKFILL_MAX_PROMPT_CHARS as N, ONTOLOGY_BACKFILL_RECHECK_MS as P, PromptService as a2, PrunePartialFailureError as a3, WikiParseError as aB, WikiSearchUnavailableError as aC, WikiSourceRefHashCollision as aD, WikiStrictOntologyViolation as aE, WikiSupersedeError as aF, WikiTransactionError as aI, isWikiSearchUnavailableError as aJ, validateManifest as aK, EmbeddingService as aL, ImportExportService as aM, IngestionService as aN, JobManager as aO, MaintenanceService as aP, RetrievalService as aQ, SearchService as aR, WriteService as aS, WikiBusyError as ad, WikiDraftNotFound as an, WikiDuplicateHashError as ao, WikiExternalDeletionError as ar, WikiGraphNodeOwnershipConflict as at, WikiIngestEmptyError as au, WikiInvalidReadOptions as aw, WikiMigrationRequiredError as az, WikiMemory as c, HEAL_RECHECK_MS as u, HOOK_TIMEOUT_MARKER as v };
4562
- export type { PendingMigrationWork as $, MaintenanceJob as A, MaintenanceStopReason as B, ChunkFailure as C, DegradedRecord as D, EmbedFactResult as E, FormatContextOptions as F, GraphNeighborhood as G, IngestDocumentResult as I, MigrationPolicy as J, LLMProvider as L, MemoryBundle as M, OntologyMode as O, OntologyBackfillResult as Q, ReadOptions as R, SQLiteAdapter as S, OntologyConfig as T, OntologyEdgeType as U, OntologyManifest as V, WikiOptions as W, OntologyNodeType as X, OntologyPromptContext as Y, OntologyUpdates as Z, PendingMaintenance as _, MemoryDump as a, PendingSourceStatus as a0, PromptOverrides as a1, ReembedResult as a4, RememberInput as a5, RunPendingMaintenanceOptions as a6, RunPendingMaintenanceResult as a7, SupersedeReplacement as a8, VectorRanker as a9, WikiOutboxEvent as aA, WikiSupersedeReason as aG, WikiTask as aH, VectorRankerFallback as aa, VectorRankerRankArgs as ab, VectorRankerSemanticResult as ac, WikiBusyOperation as ae, WikiCheckpoint as af, WikiConfig as ag, WikiDiagnostic as ah, WikiDiagnosticCode as ai, WikiDiagnosticDetail as aj, WikiDiagnosticOperation as ak, WikiDiagnosticSeverity as al, WikiDiagnosticTrigger as am, WikiEdge as ap, WikiEvent as aq, WikiFact as as, WikiInstructions as av, WikiLintReport as ax, WikiMemoryTestAccess as ay, FormattedMemoryDump as b, ClassifierAnswer as d, ClassifierQuestion as e, ClassifyRequest as f, ClassifyResponse as g, DraftPage as h, EmbedFailureKind as i, EmbeddingMarkerKind as j, EntityMaintenanceReport as k, EntityStatus as l, ExtractedFact as m, ExtractedFactEdge as n, ExtractedFactWithOntology as o, ExtractedTask as p, ForgetParams as q, ForgetResult as r, GraphTraversalOptions as s, GroundingConfig as t, HealResult as w, LibrarianConfig as x, LibrarianGateConfig as y, LockedMaintenanceJob as z };
4595
+ export { HEAL_BATCH_SIZE as H, ONTOLOGY_BACKFILL_BATCH_SIZE as K, ONTOLOGY_BACKFILL_MAX_PROMPT_CHARS as N, ONTOLOGY_BACKFILL_RECHECK_MS as P, PromptService as a2, PrunePartialFailureError as a3, WikiParseError as aB, WikiSearchUnavailableError as aC, WikiSourceRefHashCollision as aE, WikiStrictOntologyViolation as aF, WikiSupersedeError as aG, WikiTransactionError as aJ, isWikiSearchUnavailableError as aK, validateManifest as aL, EmbeddingService as aM, ImportExportService as aN, IngestionService as aO, JobManager as aP, MaintenanceService as aQ, RetrievalService as aR, SearchService as aS, WriteService as aT, WikiBusyError as ad, WikiDraftNotFound as an, WikiDuplicateHashError as ao, WikiExternalDeletionError as ar, WikiGraphNodeOwnershipConflict as at, WikiIngestEmptyError as au, WikiInvalidReadOptions as aw, WikiMigrationRequiredError as az, WikiMemory as c, HEAL_RECHECK_MS as u, HOOK_TIMEOUT_MARKER as v };
4596
+ export type { PendingMigrationWork as $, MaintenanceJob as A, MaintenanceStopReason as B, ChunkFailure as C, DegradedRecord as D, EmbedFactResult as E, FormatContextOptions as F, GraphNeighborhood as G, IngestDocumentResult as I, MigrationPolicy as J, LLMProvider as L, MemoryBundle as M, OntologyMode as O, OntologyBackfillResult as Q, ReadOptions as R, SQLiteAdapter as S, OntologyConfig as T, OntologyEdgeType as U, OntologyManifest as V, WikiOptions as W, OntologyNodeType as X, OntologyPromptContext as Y, OntologyUpdates as Z, PendingMaintenance as _, MemoryDump as a, PendingSourceStatus as a0, PromptOverrides as a1, ReembedResult as a4, RememberInput as a5, RunPendingMaintenanceOptions as a6, RunPendingMaintenanceResult as a7, SupersedeReplacement as a8, VectorRanker as a9, WikiOutboxEvent as aA, WikiSourcePointer as aD, WikiSupersedeReason as aH, WikiTask as aI, VectorRankerFallback as aa, VectorRankerRankArgs as ab, VectorRankerSemanticResult as ac, WikiBusyOperation as ae, WikiCheckpoint as af, WikiConfig as ag, WikiDiagnostic as ah, WikiDiagnosticCode as ai, WikiDiagnosticDetail as aj, WikiDiagnosticOperation as ak, WikiDiagnosticSeverity as al, WikiDiagnosticTrigger as am, WikiEdge as ap, WikiEvent as aq, WikiFact as as, WikiInstructions as av, WikiLintReport as ax, WikiMemoryTestAccess as ay, FormattedMemoryDump as b, ClassifierAnswer as d, ClassifierQuestion as e, ClassifyRequest as f, ClassifyResponse as g, DraftPage as h, EmbedFailureKind as i, EmbeddingMarkerKind as j, EntityMaintenanceReport as k, EntityStatus as l, ExtractedFact as m, ExtractedFactEdge as n, ExtractedFactWithOntology as o, ExtractedTask as p, ForgetParams as q, ForgetResult as r, GraphTraversalOptions as s, GroundingConfig as t, HealResult as w, LibrarianConfig as x, LibrarianGateConfig as y, LockedMaintenanceJob as z };
@@ -471,6 +471,28 @@ interface ReadOptions {
471
471
  */
472
472
  tokenBudget?: number;
473
473
  }
474
+ /**
475
+ * A source pointer: the structured reference from a librarian fact to the
476
+ * event it came from, with its supporting quote and its position
477
+ * (specs/source-pointers §The pointer). Stored as JSON in the nullable
478
+ * `source_pointer` column on entries.
479
+ * - `event_id`: the batch event the fact was extracted from (ops strategy),
480
+ * or null when unresolved/unsupported.
481
+ * - `ref`: host-supplied ref slot; no producer exists in this release — always null.
482
+ * - `quote`: a grounding-verified, normalized, length-capped (on the ops
483
+ * write path; import restores verbatim) quote from the named event's
484
+ * own corpus part (ops only), or null.
485
+ * - `position`: offset slot; no producer exists in this release — always null.
486
+ */
487
+ type WikiSourcePointer = {
488
+ event_id: string | null;
489
+ ref: string | null;
490
+ quote: string | null;
491
+ position: {
492
+ start: number;
493
+ length: number;
494
+ } | null;
495
+ };
474
496
  interface WikiFact {
475
497
  id: string;
476
498
  entity_id: string;
@@ -552,6 +574,8 @@ interface WikiFact {
552
574
  superseded_by?: string | null;
553
575
  /** Epoch ms the supersession was recorded (transaction time). Audit only. */
554
576
  superseded_at?: number | null;
577
+ /** Structured provenance from this librarian fact to its source event, with the verified quote. Null for legacy/heal/ingest facts. */
578
+ source_pointer?: WikiSourcePointer | null;
555
579
  }
556
580
  interface WikiTask {
557
581
  id: string;
@@ -823,7 +847,7 @@ type WikiDiagnosticSeverity = 'info' | 'warn' | 'error';
823
847
  * Closed for this release series, but new codes are added in minor versions:
824
848
  * hosts must tolerate codes they do not recognize.
825
849
  */
826
- type WikiDiagnosticCode = 'ingest_chunk_failed' | 'fact_rejected' | 'task_rejected' | 'fact_deduplicated' | 'edge_dropped' | 'embedding_failed' | 'hook_failed' | 'background_job_failed' | 'heal_skipped' | 'grounding_missing' | 'grounding_failed' | 'classification_low_confidence' | 'classification_invalid' | 'llm_usage' | 'librarian_gate' | 'librarian_op_rejected' | 'contradicts_document' | 'resolve_failed' | 'read_budget' | 'event_retention_held' | 'event_created_at_clamped' | 'event_created_at_restamped' | 'external_deletion_pending' | 'external_deletion_discarded' | 'guidance_too_long' | 'guidance_resolver_failed';
850
+ type WikiDiagnosticCode = 'ingest_chunk_failed' | 'fact_rejected' | 'task_rejected' | 'fact_deduplicated' | 'edge_dropped' | 'embedding_failed' | 'hook_failed' | 'background_job_failed' | 'heal_skipped' | 'grounding_missing' | 'grounding_failed' | 'classification_low_confidence' | 'classification_invalid' | 'llm_usage' | 'librarian_gate' | 'librarian_op_rejected' | 'contradicts_document' | 'resolve_failed' | 'read_budget' | 'event_retention_held' | 'event_created_at_clamped' | 'event_created_at_restamped' | 'external_deletion_pending' | 'external_deletion_discarded' | 'guidance_too_long' | 'guidance_resolver_failed' | 'source_pointer_unresolved' | 'source_pointer_invalid';
827
851
  /** The service run that emitted the diagnostic. */
828
852
  type WikiDiagnosticOperation = 'ingest' | 'upsertGraph' | 'librarian' | 'heal' | 'ontologyBackfill' | 'reembed' | 'importDump' | 'write' | 'supersede' | 'remember' | 'read' | 'prune' | 'externalDeletion';
829
853
  /** `'auto'` when a write threshold started the run (auto-librarian / auto-heal); `'call'` when the host did. */
@@ -1004,6 +1028,16 @@ interface MemoryBundle {
1004
1028
  interface MemoryDump {
1005
1029
  generatedAt: number;
1006
1030
  entities: Record<string, MemoryBundle>;
1031
+ /**
1032
+ * Source-pointer parse report (specs/source-pointers §Export, import, and OKF).
1033
+ * Present ONLY when `parseOkfBundle` dropped a malformed `source_pointer`
1034
+ * value: entry ids and a reason slug — never raw pointer values, because a
1035
+ * pointer can carry quote text. Export-only metadata; `importDump` ignores it.
1036
+ */
1037
+ dropped_pointer_values?: Array<{
1038
+ factId: string;
1039
+ reason: string;
1040
+ }>;
1007
1041
  }
1008
1042
  interface FormattedMemoryDump {
1009
1043
  manifest: string;
@@ -1674,7 +1708,7 @@ declare class EntryRepository extends BaseRepository {
1674
1708
  }>>;
1675
1709
  findIdById(id: string, entityId: string, tx?: SQLiteAdapter): Promise<string | null>;
1676
1710
  findIdsBySource(entityId: string, sourceRef: string | null, sourceHash: string | null, tx?: SQLiteAdapter, includeDeleted?: boolean): Promise<string[]>;
1677
- upsertForImport(fact: WikiFact, tx: SQLiteAdapter): Promise<{
1711
+ upsertForImport(fact: WikiFact, tx: SQLiteAdapter, sourcePointerPresent?: boolean): Promise<{
1678
1712
  changes: number;
1679
1713
  lastInsertRowId: number;
1680
1714
  }>;
@@ -4558,5 +4592,5 @@ declare class WikiMemory {
4558
4592
  setGeneratedByTask(taskId: string, entityId: string, actor: string): Promise<void>;
4559
4593
  }
4560
4594
 
4561
- export { HEAL_BATCH_SIZE as H, ONTOLOGY_BACKFILL_BATCH_SIZE as K, ONTOLOGY_BACKFILL_MAX_PROMPT_CHARS as N, ONTOLOGY_BACKFILL_RECHECK_MS as P, PromptService as a2, PrunePartialFailureError as a3, WikiParseError as aB, WikiSearchUnavailableError as aC, WikiSourceRefHashCollision as aD, WikiStrictOntologyViolation as aE, WikiSupersedeError as aF, WikiTransactionError as aI, isWikiSearchUnavailableError as aJ, validateManifest as aK, EmbeddingService as aL, ImportExportService as aM, IngestionService as aN, JobManager as aO, MaintenanceService as aP, RetrievalService as aQ, SearchService as aR, WriteService as aS, WikiBusyError as ad, WikiDraftNotFound as an, WikiDuplicateHashError as ao, WikiExternalDeletionError as ar, WikiGraphNodeOwnershipConflict as at, WikiIngestEmptyError as au, WikiInvalidReadOptions as aw, WikiMigrationRequiredError as az, WikiMemory as c, HEAL_RECHECK_MS as u, HOOK_TIMEOUT_MARKER as v };
4562
- export type { PendingMigrationWork as $, MaintenanceJob as A, MaintenanceStopReason as B, ChunkFailure as C, DegradedRecord as D, EmbedFactResult as E, FormatContextOptions as F, GraphNeighborhood as G, IngestDocumentResult as I, MigrationPolicy as J, LLMProvider as L, MemoryBundle as M, OntologyMode as O, OntologyBackfillResult as Q, ReadOptions as R, SQLiteAdapter as S, OntologyConfig as T, OntologyEdgeType as U, OntologyManifest as V, WikiOptions as W, OntologyNodeType as X, OntologyPromptContext as Y, OntologyUpdates as Z, PendingMaintenance as _, MemoryDump as a, PendingSourceStatus as a0, PromptOverrides as a1, ReembedResult as a4, RememberInput as a5, RunPendingMaintenanceOptions as a6, RunPendingMaintenanceResult as a7, SupersedeReplacement as a8, VectorRanker as a9, WikiOutboxEvent as aA, WikiSupersedeReason as aG, WikiTask as aH, VectorRankerFallback as aa, VectorRankerRankArgs as ab, VectorRankerSemanticResult as ac, WikiBusyOperation as ae, WikiCheckpoint as af, WikiConfig as ag, WikiDiagnostic as ah, WikiDiagnosticCode as ai, WikiDiagnosticDetail as aj, WikiDiagnosticOperation as ak, WikiDiagnosticSeverity as al, WikiDiagnosticTrigger as am, WikiEdge as ap, WikiEvent as aq, WikiFact as as, WikiInstructions as av, WikiLintReport as ax, WikiMemoryTestAccess as ay, FormattedMemoryDump as b, ClassifierAnswer as d, ClassifierQuestion as e, ClassifyRequest as f, ClassifyResponse as g, DraftPage as h, EmbedFailureKind as i, EmbeddingMarkerKind as j, EntityMaintenanceReport as k, EntityStatus as l, ExtractedFact as m, ExtractedFactEdge as n, ExtractedFactWithOntology as o, ExtractedTask as p, ForgetParams as q, ForgetResult as r, GraphTraversalOptions as s, GroundingConfig as t, HealResult as w, LibrarianConfig as x, LibrarianGateConfig as y, LockedMaintenanceJob as z };
4595
+ export { HEAL_BATCH_SIZE as H, ONTOLOGY_BACKFILL_BATCH_SIZE as K, ONTOLOGY_BACKFILL_MAX_PROMPT_CHARS as N, ONTOLOGY_BACKFILL_RECHECK_MS as P, PromptService as a2, PrunePartialFailureError as a3, WikiParseError as aB, WikiSearchUnavailableError as aC, WikiSourceRefHashCollision as aE, WikiStrictOntologyViolation as aF, WikiSupersedeError as aG, WikiTransactionError as aJ, isWikiSearchUnavailableError as aK, validateManifest as aL, EmbeddingService as aM, ImportExportService as aN, IngestionService as aO, JobManager as aP, MaintenanceService as aQ, RetrievalService as aR, SearchService as aS, WriteService as aT, WikiBusyError as ad, WikiDraftNotFound as an, WikiDuplicateHashError as ao, WikiExternalDeletionError as ar, WikiGraphNodeOwnershipConflict as at, WikiIngestEmptyError as au, WikiInvalidReadOptions as aw, WikiMigrationRequiredError as az, WikiMemory as c, HEAL_RECHECK_MS as u, HOOK_TIMEOUT_MARKER as v };
4596
+ export type { PendingMigrationWork as $, MaintenanceJob as A, MaintenanceStopReason as B, ChunkFailure as C, DegradedRecord as D, EmbedFactResult as E, FormatContextOptions as F, GraphNeighborhood as G, IngestDocumentResult as I, MigrationPolicy as J, LLMProvider as L, MemoryBundle as M, OntologyMode as O, OntologyBackfillResult as Q, ReadOptions as R, SQLiteAdapter as S, OntologyConfig as T, OntologyEdgeType as U, OntologyManifest as V, WikiOptions as W, OntologyNodeType as X, OntologyPromptContext as Y, OntologyUpdates as Z, PendingMaintenance as _, MemoryDump as a, PendingSourceStatus as a0, PromptOverrides as a1, ReembedResult as a4, RememberInput as a5, RunPendingMaintenanceOptions as a6, RunPendingMaintenanceResult as a7, SupersedeReplacement as a8, VectorRanker as a9, WikiOutboxEvent as aA, WikiSourcePointer as aD, WikiSupersedeReason as aH, WikiTask as aI, VectorRankerFallback as aa, VectorRankerRankArgs as ab, VectorRankerSemanticResult as ac, WikiBusyOperation as ae, WikiCheckpoint as af, WikiConfig as ag, WikiDiagnostic as ah, WikiDiagnosticCode as ai, WikiDiagnosticDetail as aj, WikiDiagnosticOperation as ak, WikiDiagnosticSeverity as al, WikiDiagnosticTrigger as am, WikiEdge as ap, WikiEvent as aq, WikiFact as as, WikiInstructions as av, WikiLintReport as ax, WikiMemoryTestAccess as ay, FormattedMemoryDump as b, ClassifierAnswer as d, ClassifierQuestion as e, ClassifyRequest as f, ClassifyResponse as g, DraftPage as h, EmbedFailureKind as i, EmbeddingMarkerKind as j, EntityMaintenanceReport as k, EntityStatus as l, ExtractedFact as m, ExtractedFactEdge as n, ExtractedFactWithOntology as o, ExtractedTask as p, ForgetParams as q, ForgetResult as r, GraphTraversalOptions as s, GroundingConfig as t, HealResult as w, LibrarianConfig as x, LibrarianGateConfig as y, LockedMaintenanceJob as z };
@@ -1,2 +1,2 @@
1
- export { aL as EmbeddingService, aM as ImportExportService, aN as IngestionService, aO as JobManager, aO as JobManagerType, aP as MaintenanceService, aQ as RetrievalService, aR as SearchService, aR as SearchServiceType, ay as WikiMemoryTestAccess, aS as WriteService } from './testing-s6DBqXxQ.mjs';
1
+ export { aM as EmbeddingService, aN as ImportExportService, aO as IngestionService, aP as JobManager, aP as JobManagerType, aQ as MaintenanceService, aR as RetrievalService, aS as SearchService, aS as SearchServiceType, ay as WikiMemoryTestAccess, aT as WriteService } from './testing-CmcCGx0_.mjs';
2
2
  import '@equationalapplications/core-okf';
package/dist/testing.d.ts CHANGED
@@ -1,2 +1,2 @@
1
- export { aL as EmbeddingService, aM as ImportExportService, aN as IngestionService, aO as JobManager, aO as JobManagerType, aP as MaintenanceService, aQ as RetrievalService, aR as SearchService, aR as SearchServiceType, ay as WikiMemoryTestAccess, aS as WriteService } from './testing-s6DBqXxQ.js';
1
+ export { aM as EmbeddingService, aN as ImportExportService, aO as IngestionService, aP as JobManager, aP as JobManagerType, aQ as MaintenanceService, aR as RetrievalService, aS as SearchService, aS as SearchServiceType, ay as WikiMemoryTestAccess, aT as WriteService } from './testing-CmcCGx0_.js';
2
2
  import '@equationalapplications/core-okf';
package/dist/testing.js CHANGED
@@ -729,7 +729,9 @@ var SEVERITY = {
729
729
  external_deletion_pending: "warn",
730
730
  external_deletion_discarded: "warn",
731
731
  guidance_too_long: "warn",
732
- guidance_resolver_failed: "warn"
732
+ guidance_resolver_failed: "warn",
733
+ source_pointer_unresolved: "warn",
734
+ source_pointer_invalid: "warn"
733
735
  };
734
736
  var MESSAGE = {
735
737
  ingest_chunk_failed: "One or more document chunks failed to parse or generate.",
@@ -757,7 +759,9 @@ var MESSAGE = {
757
759
  external_deletion_pending: "Removals owed to the external vector index are still pending.",
758
760
  external_deletion_discarded: "Pending external vector removals were discarded because forceDeleteIgnoreRankerHook is set.",
759
761
  guidance_too_long: "The configured guidance exceeded the length cap and was not sent for this pass.",
760
- guidance_resolver_failed: "The per-entity guidance resolver failed; its value was not used for this pass."
762
+ guidance_resolver_failed: "The per-entity guidance resolver failed; its value was not used for this pass.",
763
+ source_pointer_unresolved: "A stored librarian fact carries no source pointer because the model answer could not yield one.",
764
+ source_pointer_invalid: "Import met a malformed source pointer value and stored a null pointer."
761
765
  };
762
766
  var warnedNonFunction = /* @__PURE__ */ new WeakSet();
763
767
  function copyDetail(detail) {
@@ -1238,6 +1242,44 @@ function entitySummaryMetaKey(entityId) {
1238
1242
  }
1239
1243
  var START_OF_LOG_WATERMARK = Object.freeze({ at: Number.MIN_SAFE_INTEGER, id: "" });
1240
1244
 
1245
+ // src/utils/sourcePointer.ts
1246
+ var POINTER_SLOTS = ["event_id", "ref", "quote", "position"];
1247
+ function isStringOrNull(v) {
1248
+ return v === null || typeof v === "string";
1249
+ }
1250
+ function isValidPosition(v) {
1251
+ if (v === null) return true;
1252
+ if (typeof v !== "object" || v === null || Array.isArray(v)) return false;
1253
+ const o = v;
1254
+ const keys = Object.keys(o);
1255
+ if (keys.length !== 2 || !("start" in o) || !("length" in o)) return false;
1256
+ const { start, length } = o;
1257
+ return typeof start === "number" && Number.isInteger(start) && start >= 0 && typeof length === "number" && Number.isInteger(length) && length >= 0;
1258
+ }
1259
+ function validateSourcePointerValue(v) {
1260
+ if (v === null) return null;
1261
+ if (typeof v !== "object" || Array.isArray(v)) return void 0;
1262
+ const o = v;
1263
+ const keys = Object.keys(o);
1264
+ for (const k of keys) {
1265
+ if (!POINTER_SLOTS.includes(k)) return void 0;
1266
+ }
1267
+ 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"])) {
1268
+ return void 0;
1269
+ }
1270
+ if (!isValidPosition(o["position"] === void 0 ? null : o["position"])) return void 0;
1271
+ const normalized = {
1272
+ event_id: o["event_id"] ?? null,
1273
+ ref: o["ref"] ?? null,
1274
+ quote: o["quote"] ?? null,
1275
+ position: o["position"] ?? null
1276
+ };
1277
+ if (normalized.event_id === null && normalized.ref === null && normalized.quote === null && normalized.position === null) {
1278
+ return null;
1279
+ }
1280
+ return normalized;
1281
+ }
1282
+
1241
1283
  // src/services/legacyWatermark.ts
1242
1284
  async function anchorAtLegacyBoundary(metadataRepo, eventRepo, entityId, checkpoint, total, db) {
1243
1285
  if (checkpoint <= 0 || total <= 0) return null;
@@ -1527,6 +1569,19 @@ var ImportExportService = class {
1527
1569
  );
1528
1570
  }
1529
1571
  }
1572
+ const hasSourcePointerKey = fact["source_pointer"] !== void 0;
1573
+ const rawPointerValue = hasSourcePointerKey ? fact["source_pointer"] : void 0;
1574
+ const pointerValidated = hasSourcePointerKey ? validateSourcePointerValue(rawPointerValue) : null;
1575
+ if (pointerValidated === void 0) {
1576
+ emitDiagnostic(this.options, {
1577
+ code: "source_pointer_invalid",
1578
+ operation: "importDump",
1579
+ trigger: "call",
1580
+ entityId,
1581
+ detail: { factId: fact.id }
1582
+ });
1583
+ }
1584
+ const sourcePointer = pointerValidated === void 0 ? null : pointerValidated;
1530
1585
  const factObj = {
1531
1586
  id: fact.id,
1532
1587
  entity_id: entityId,
@@ -1544,6 +1599,7 @@ var ImportExportService = class {
1544
1599
  deleted_at: fact.deleted_at,
1545
1600
  embedding_blob: blobData ?? void 0,
1546
1601
  okf_type: fact.okf_type ?? null,
1602
+ source_pointer: sourcePointer,
1547
1603
  // OKF v0.2 — forwarded as-is; parseOkfBundle / the caller is responsible for
1548
1604
  // populating these per spec, importDump does not derive or validate them.
1549
1605
  lifecycle_status: fact.lifecycle_status ?? "stable",
@@ -1561,7 +1617,7 @@ var ImportExportService = class {
1561
1617
  return { last_verified_at: latest?.at ?? null, last_verified_by: latest?.by ?? null };
1562
1618
  })()
1563
1619
  };
1564
- await this.entryRepo.upsertForImport(factObj, tx);
1620
+ await this.entryRepo.upsertForImport(factObj, tx, hasSourcePointerKey);
1565
1621
  await this.entryRepo.setTemporal(fact.id, entityId, {
1566
1622
  valid_from: fact.valid_from ?? null,
1567
1623
  valid_to: fact.valid_to ?? null,
@@ -2282,6 +2338,10 @@ ${JSON.stringify(facts, null, 2)}`
2282
2338
  systemPrompt: this.appendGrounding(this.appendGuidance(this.appendOntology(OPS_EXTRACT_SYSTEM_PROMPT, ontologyContext), guidance), "librarian"),
2283
2339
  userPrompt: `Events:
2284
2340
  ${lines.join("\n")}`,
2341
+ // Corpus entries are one-per-batch-event in batch order (summaries are
2342
+ // TEXT NOT NULL, so the filter inside buildGroundingCorpus drops
2343
+ // nothing): extract.ts stores a candidate's `sourcePartIndex` as the
2344
+ // batch index and buildSourcePointer reads the quote back by it.
2285
2345
  ...grounding ? { groundingCorpus: buildGroundingCorpus(events.map((l) => l.event.summary)) } : {}
2286
2346
  };
2287
2347
  }
@@ -3834,6 +3894,17 @@ var MIGRATIONS = [
3834
3894
  );
3835
3895
  if (row?.n) await db.execAsync(fts5PendingIndexesDdl(prefix));
3836
3896
  }
3897
+ },
3898
+ {
3899
+ version: 16,
3900
+ description: "Source pointers on librarian facts: nullable source_pointer TEXT on entries",
3901
+ run: async (db, prefix) => {
3902
+ const cols = await db.getAllAsync(`PRAGMA table_info(${prefix}entries)`);
3903
+ const existing = new Set(cols.map((c) => c.name));
3904
+ if (!existing.has("source_pointer")) {
3905
+ await db.execAsync(`ALTER TABLE ${prefix}entries ADD COLUMN source_pointer TEXT`);
3906
+ }
3907
+ }
3837
3908
  }
3838
3909
  ];
3839
3910
  async function createLegacySourceTypeIndex(db, prefix) {
@@ -3996,9 +4067,20 @@ var runLegacyLibrarianPass = async (deps, ctx) => {
3996
4067
  access_count: 0,
3997
4068
  deleted_at: null,
3998
4069
  okf_type: normalized.okf_type,
4070
+ // Legacy writes no pointer (spec §Legacy path): the column stays null
4071
+ // on every legacy fact, and the legacy prompt keeps its exact text.
4072
+ source_pointer: null,
3999
4073
  ...grounding?.trust
4000
4074
  };
4001
4075
  await deps.entryRepo.upsert(factObj, tx);
4076
+ const volunteeredSourceEvent = facts[validFactItemIndexes[k]]?.source_event;
4077
+ if (volunteeredSourceEvent !== void 0 && volunteeredSourceEvent !== null) {
4078
+ diagBuffer.push({
4079
+ ...diagBase,
4080
+ code: "source_pointer_unresolved",
4081
+ detail: { factId: id, itemIndex: validFactItemIndexes[k], reason: "unsupported_strategy" }
4082
+ });
4083
+ }
4002
4084
  insertedFacts.push({ id, entity_id: entityId, title: fact.title, body: fact.body, tags: JSON.stringify(fact.tags) });
4003
4085
  factsForDedupe.push(factObj);
4004
4086
  titleIndex.set(normalizeTitleKey(fact.title), { id, okf_type: normalized.okf_type });
@@ -4112,9 +4194,23 @@ async function runExtract(deps, ctx, batch) {
4112
4194
  return;
4113
4195
  }
4114
4196
  const r = raw;
4115
- const sourceLabel = typeof r.source_event === "string" && byLabel.has(r.source_event) ? r.source_event : null;
4197
+ let sourceEventId = null;
4198
+ let sourcePartIndex = null;
4199
+ let pointerUnresolved;
4200
+ const rawSourceEvent = r.source_event;
4201
+ if (rawSourceEvent === void 0 || rawSourceEvent === null) {
4202
+ pointerUnresolved = "missing";
4203
+ } else if (typeof rawSourceEvent === "string" && byLabel.has(rawSourceEvent)) {
4204
+ const labeled = byLabel.get(rawSourceEvent);
4205
+ sourceEventId = labeled.event.id;
4206
+ sourcePartIndex = batch.findIndex((b) => b.label === rawSourceEvent);
4207
+ pointerUnresolved = null;
4208
+ } else {
4209
+ pointerUnresolved = "unknown_label";
4210
+ }
4211
+ const sourceLabel = typeof rawSourceEvent === "string" && byLabel.has(rawSourceEvent) ? rawSourceEvent : null;
4116
4212
  const validFrom = parseValidFrom(r.valid_from) ?? (sourceLabel ? byLabel.get(sourceLabel).at : defaultValidFrom);
4117
- candidates.push({ index, fact, sourceLabel, validFrom });
4213
+ candidates.push({ index, fact, sourceLabel, sourceEventId, sourcePartIndex, pointerUnresolved, validFrom });
4118
4214
  });
4119
4215
  const tasks = [];
4120
4216
  (Array.isArray(parsed.tasks) ? parsed.tasks : []).forEach((raw, index) => {
@@ -4404,6 +4500,17 @@ var TemporalService = class {
4404
4500
  };
4405
4501
 
4406
4502
  // src/services/librarian/ops/apply.ts
4503
+ function buildSourcePointer(candidate, verdict, groundingOn, groundingCorpus) {
4504
+ if (candidate.sourceEventId === null) return null;
4505
+ let quote = null;
4506
+ if (groundingOn && verdict?.status === "grounded" && candidate.sourcePartIndex !== null) {
4507
+ const part = groundingCorpus?.[candidate.sourcePartIndex];
4508
+ if (part !== void 0) {
4509
+ quote = verdict.retained.find((q) => part.includes(q)) ?? null;
4510
+ }
4511
+ }
4512
+ return { event_id: candidate.sourceEventId, ref: null, quote, position: null };
4513
+ }
4407
4514
  async function applyOps(deps, ctx, input) {
4408
4515
  const { entityId, trigger } = ctx;
4409
4516
  const diagBase = { entityId, operation: "librarian", trigger };
@@ -4432,7 +4539,8 @@ async function applyOps(deps, ctx, input) {
4432
4539
  const drops = [];
4433
4540
  const normalized = deps.ontologyService?.validateAndNormalizeFact(fact, manifest, { strict: false, drops }) ?? { okf_type: null, edges: [] };
4434
4541
  for (const d of drops) input.diagnostics.push(edgeDropDiagnostic(d, { ...diagBase, factId: id }));
4435
- const g2 = grounding ? groundingOutcome(checkGrounding(fact.evidence, input.groundingCorpus ?? [], grounding), now) : null;
4542
+ const gVerdict = grounding ? checkGrounding(fact.evidence, input.groundingCorpus ?? [], grounding) : null;
4543
+ const g2 = gVerdict ? groundingOutcome(gVerdict, now) : null;
4436
4544
  if (g2?.diagnostic) {
4437
4545
  input.diagnostics.push({
4438
4546
  ...diagBase,
@@ -4440,6 +4548,7 @@ async function applyOps(deps, ctx, input) {
4440
4548
  detail: { factId: id, itemIndex: g.candidate.index, reason: g2.diagnostic.reason }
4441
4549
  });
4442
4550
  }
4551
+ const pointer = buildSourcePointer(g.candidate, gVerdict, grounding !== void 0 && grounding !== null, input.groundingCorpus);
4443
4552
  const row = {
4444
4553
  id,
4445
4554
  entity_id: entityId,
@@ -4456,11 +4565,19 @@ async function applyOps(deps, ctx, input) {
4456
4565
  access_count: 0,
4457
4566
  deleted_at: null,
4458
4567
  okf_type: normalized.okf_type,
4568
+ source_pointer: pointer,
4459
4569
  ...g2?.trust,
4460
4570
  ...draft ? { lifecycle_status: "draft" } : {}
4461
4571
  };
4462
4572
  await deps.entryRepo.upsert(row, tx);
4463
4573
  await deps.entryRepo.setTemporal(id, entityId, { valid_from: validFrom }, tx);
4574
+ if (g.candidate.pointerUnresolved !== null) {
4575
+ input.diagnostics.push({
4576
+ ...diagBase,
4577
+ code: "source_pointer_unresolved",
4578
+ detail: { factId: id, itemIndex: g.candidate.index, reason: g.candidate.pointerUnresolved }
4579
+ });
4580
+ }
4464
4581
  titleIndex.set(normalizeTitleKey(title), { id, okf_type: normalized.okf_type });
4465
4582
  if (normalized.edges.length > 0) pendingEdges.push({ sourceId: id, sourceType: normalized.okf_type, edges: normalized.edges });
4466
4583
  const textChanged = title !== fact.title || body !== fact.body;
@@ -5484,6 +5601,7 @@ var MaintenanceService = class {
5484
5601
  source_type: "librarian_inferred",
5485
5602
  source_hash: null,
5486
5603
  source_ref: null,
5604
+ source_pointer: null,
5487
5605
  created_at: now,
5488
5606
  updated_at: now,
5489
5607
  last_accessed_at: null,