@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.
@@ -39,9 +39,18 @@ interface SQLiteAdapter {
39
39
  }
40
40
  interface PromptOverrides {
41
41
  ingestSystemPrompt?: string;
42
- librarianSystemPrompt?: string;
43
42
  healSystemPrompt?: string;
44
43
  ontologyBackfillSystemPrompt?: string;
44
+ /**
45
+ * Short domain guidance added, in a marked section, to the prompts that
46
+ * author fact text (ingest, legacy librarian, ops extract), plus the
47
+ * general leave-out rule sentence. Database-level default; per entity,
48
+ * `librarian.guidanceForEntity` wins when it returns a non-empty string.
49
+ * Capped at 2,000 characters (UTF-16 units); over-cap guidance is not
50
+ * sent and emits `guidance_too_long`. Holds no secrets: it is sent to
51
+ * the model on every authoring call.
52
+ */
53
+ guidance?: string;
45
54
  }
46
55
  type OntologyMode = 'strict' | 'emergent' | 'off';
47
56
  interface OntologyNodeType {
@@ -257,6 +266,16 @@ interface LibrarianGateConfig {
257
266
  interface LibrarianConfig {
258
267
  strategy?: 'legacy' | 'ops';
259
268
  gate?: LibrarianGateConfig;
269
+ /**
270
+ * Per-entity librarian guidance (specs/librarian-guidance). Returns the
271
+ * short domain instruction for `entityId`, or `undefined`/empty to fall
272
+ * back to `config.prompts.guidance`. Called synchronously once per
273
+ * librarian pass / ingest call; a throw or non-string return is treated
274
+ * as no value (fallback + `guidance_resolver_failed` diagnostic). The
275
+ * engine stores neither value. Lives under `librarian`, not `prompts`,
276
+ * so `WikiConfig.prompts` stays a struct of plain strings.
277
+ */
278
+ guidanceForEntity?: (entityId: string) => string | undefined;
260
279
  }
261
280
  interface WikiConfig {
262
281
  /**
@@ -452,6 +471,28 @@ interface ReadOptions {
452
471
  */
453
472
  tokenBudget?: number;
454
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
+ };
455
496
  interface WikiFact {
456
497
  id: string;
457
498
  entity_id: string;
@@ -533,6 +574,8 @@ interface WikiFact {
533
574
  superseded_by?: string | null;
534
575
  /** Epoch ms the supersession was recorded (transaction time). Audit only. */
535
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;
536
579
  }
537
580
  interface WikiTask {
538
581
  id: string;
@@ -804,7 +847,7 @@ type WikiDiagnosticSeverity = 'info' | 'warn' | 'error';
804
847
  * Closed for this release series, but new codes are added in minor versions:
805
848
  * hosts must tolerate codes they do not recognize.
806
849
  */
807
- 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';
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';
808
851
  /** The service run that emitted the diagnostic. */
809
852
  type WikiDiagnosticOperation = 'ingest' | 'upsertGraph' | 'librarian' | 'heal' | 'ontologyBackfill' | 'reembed' | 'importDump' | 'write' | 'supersede' | 'remember' | 'read' | 'prune' | 'externalDeletion';
810
853
  /** `'auto'` when a write threshold started the run (auto-librarian / auto-heal); `'call'` when the host did. */
@@ -849,6 +892,10 @@ interface WikiDiagnosticDetail {
849
892
  oldestEnqueuedAt?: number;
850
893
  /** external_deletion_pending only: highest attempt count among pending rows. */
851
894
  maxAttempts?: number;
895
+ /** guidance_too_long only: length of the refused value in UTF-16 code units. */
896
+ guidanceLength?: number;
897
+ /** guidance_too_long only: which configured value was refused. */
898
+ guidanceSource?: 'per_entity' | 'default';
852
899
  }
853
900
  interface WikiDiagnostic {
854
901
  code: WikiDiagnosticCode;
@@ -981,6 +1028,16 @@ interface MemoryBundle {
981
1028
  interface MemoryDump {
982
1029
  generatedAt: number;
983
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
+ }>;
984
1041
  }
985
1042
  interface FormattedMemoryDump {
986
1043
  manifest: string;
@@ -1651,7 +1708,7 @@ declare class EntryRepository extends BaseRepository {
1651
1708
  }>>;
1652
1709
  findIdById(id: string, entityId: string, tx?: SQLiteAdapter): Promise<string | null>;
1653
1710
  findIdsBySource(entityId: string, sourceRef: string | null, sourceHash: string | null, tx?: SQLiteAdapter, includeDeleted?: boolean): Promise<string[]>;
1654
- upsertForImport(fact: WikiFact, tx: SQLiteAdapter): Promise<{
1711
+ upsertForImport(fact: WikiFact, tx: SQLiteAdapter, sourcePointerPresent?: boolean): Promise<{
1655
1712
  changes: number;
1656
1713
  lastInsertRowId: number;
1657
1714
  }>;
@@ -3007,25 +3064,58 @@ type LabeledEvent = {
3007
3064
  at: number;
3008
3065
  };
3009
3066
 
3067
+ /** Why a pass or call will not carry guidance (specs/librarian-guidance). */
3068
+ interface GuidanceDiagnostic {
3069
+ code: 'guidance_too_long' | 'guidance_resolver_failed';
3070
+ detail?: {
3071
+ guidanceLength?: number;
3072
+ guidanceSource?: 'per_entity' | 'default';
3073
+ reason?: 'threw' | 'non_string';
3074
+ };
3075
+ }
3076
+
3010
3077
  declare class PromptService {
3011
3078
  private globalOverrides?;
3012
3079
  private grounding;
3013
3080
  constructor(globalOverrides?: PromptOverrides | undefined, grounding?: ResolvedGrounding | null);
3081
+ /**
3082
+ * Specs/librarian-guidance: resolve the effective guidance for one pass
3083
+ * or call — default `config.prompts.guidance`, per-entity
3084
+ * `config.librarian.guidanceForEntity` winning when it returns a
3085
+ * non-empty (trimmed) string. Synchronous: a resolver that throws,
3086
+ * returns a thenable (its rejection is swallowed with a no-op handler;
3087
+ * a throwing `then` counts too), or returns any non-string value is
3088
+ * treated as "no value" and reported in `diagnostic`. Over-cap text
3089
+ * (UTF-16 units, verbatim) is not sent and reported in `diagnostic`.
3090
+ * Emits nothing itself; the caller emits, immediately at resolution.
3091
+ */
3092
+ static resolveGuidance(config: WikiConfig | undefined, entityId: string): {
3093
+ guidance?: string;
3094
+ diagnostic?: GuidanceDiagnostic;
3095
+ };
3014
3096
  /** The resolved grounding config when `writer` is in `grounding.writers`; otherwise null (spec §6.2). */
3015
3097
  groundingFor(writer: GroundingWriter): ResolvedGrounding | null;
3016
3098
  /** Appended after any override and after ontology context, so it is always last. */
3017
3099
  private appendGrounding;
3100
+ /**
3101
+ * Specs/librarian-guidance: append the marked guidance section (with the
3102
+ * general leave-out rule) to the ALREADY-HYDRATED system prompt — after
3103
+ * ontology, immediately before grounding. The guidance text is never
3104
+ * run through hydration, so `{{…}}` inside it cannot change a builder's
3105
+ * template branch or be expanded with data. No-op on empty input.
3106
+ */
3107
+ private appendGuidance;
3018
3108
  private hydrate;
3019
3109
  private hasOntologyPlaceholders;
3020
3110
  /** Removes ontology placeholders until none remain, so a nested form cannot reassemble one (closes CodeQL #11). */
3021
3111
  private stripOntologyPlaceholders;
3022
3112
  private buildSystemPrompt;
3023
3113
  private appendOntology;
3024
- buildIngestPrompt(documentChunk: string, runtimeOverride?: string, ontologyContext?: OntologyPromptContext | null): {
3114
+ buildIngestPrompt(documentChunk: string, runtimeOverride?: string, ontologyContext?: OntologyPromptContext | null, guidance?: string): {
3025
3115
  systemPrompt: string;
3026
3116
  userPrompt: string;
3027
3117
  };
3028
- buildLibrarianPrompt(events: unknown[], currentFacts: unknown[], runtimeOverride?: string, ontologyContext?: OntologyPromptContext | null): {
3118
+ buildLibrarianPrompt(events: unknown[], currentFacts: unknown[], runtimeOverride?: string, ontologyContext?: OntologyPromptContext | null, guidance?: string): {
3029
3119
  systemPrompt: string;
3030
3120
  userPrompt: string;
3031
3121
  groundingCorpus?: string[];
@@ -3065,7 +3155,7 @@ declare class PromptService {
3065
3155
  userPrompt: string;
3066
3156
  };
3067
3157
  /** Ops extract (spec §5.2): events only — no existing facts. */
3068
- buildOpsExtractPrompt(events: LabeledEvent[], ontologyContext?: OntologyPromptContext | null): {
3158
+ buildOpsExtractPrompt(events: LabeledEvent[], ontologyContext?: OntologyPromptContext | null, guidance?: string): {
3069
3159
  systemPrompt: string;
3070
3160
  userPrompt: string;
3071
3161
  groundingCorpus?: string[];
@@ -3092,7 +3182,7 @@ declare class PromptService {
3092
3182
  * placeholders and leaves data placeholders verbatim; heal never receives
3093
3183
  * ontology context, matching `buildHealPrompt`.
3094
3184
  */
3095
- buildInstructionTemplates(ontologyContext: OntologyPromptContext | null, librarianStrategy: 'legacy' | 'ops'): WikiInstructions;
3185
+ buildInstructionTemplates(ontologyContext: OntologyPromptContext | null, librarianStrategy: 'legacy' | 'ops', guidance?: string): WikiInstructions;
3096
3186
  }
3097
3187
 
3098
3188
  declare class IngestionService {
@@ -3435,6 +3525,14 @@ interface LibrarianContext {
3435
3525
  entityId: string;
3436
3526
  trigger: WikiDiagnosticTrigger;
3437
3527
  promptOverride?: string;
3528
+ /**
3529
+ * Specs/librarian-guidance: the effective guidance for this pass, resolved
3530
+ * by `MaintenanceService.runLibrarianPass` (never read as caller input —
3531
+ * that method overwrites whatever a caller supplies here, so "resolved
3532
+ * once per pass" holds for every caller). Strategies pass it to the
3533
+ * prompt builders verbatim.
3534
+ */
3535
+ guidance?: string;
3438
3536
  /** Optional meter (Phase C budgeted maintenance). Legacy honors it:
3439
3537
  * `callLlm` pre-flights the prompt estimate against it, usage is recorded
3440
3538
  * on every call, and the pass returns `budgetStop` when the budget is
@@ -4140,7 +4238,7 @@ declare class WikiMemory {
4140
4238
  /**
4141
4239
  * @param options.promptOverride - Applies only to this manual call. Does NOT affect
4142
4240
  * WriteService-triggered auto-runs. For persistent prompt customization across auto-runs,
4143
- * set `options.config.prompts.librarianSystemPrompt` at WikiMemory construction time.
4241
+ * set `options.config.prompts.guidance` at WikiMemory construction time.
4144
4242
  */
4145
4243
  runLibrarian(entityId: string, options?: {
4146
4244
  promptOverride?: string;
@@ -4494,5 +4592,5 @@ declare class WikiMemory {
4494
4592
  setGeneratedByTask(taskId: string, entityId: string, actor: string): Promise<void>;
4495
4593
  }
4496
4594
 
4497
- export { HEAL_BATCH_SIZE as H, ONTOLOGY_BACKFILL_MAX_PROMPT_CHARS as K, ONTOLOGY_BACKFILL_RECHECK_MS as N, ONTOLOGY_BACKFILL_BATCH_SIZE as O, 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 };
4498
- 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, OntologyBackfillResult as P, OntologyConfig as Q, ReadOptions as R, SQLiteAdapter as S, OntologyEdgeType as T, OntologyManifest as U, OntologyMode 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 };
@@ -39,9 +39,18 @@ interface SQLiteAdapter {
39
39
  }
40
40
  interface PromptOverrides {
41
41
  ingestSystemPrompt?: string;
42
- librarianSystemPrompt?: string;
43
42
  healSystemPrompt?: string;
44
43
  ontologyBackfillSystemPrompt?: string;
44
+ /**
45
+ * Short domain guidance added, in a marked section, to the prompts that
46
+ * author fact text (ingest, legacy librarian, ops extract), plus the
47
+ * general leave-out rule sentence. Database-level default; per entity,
48
+ * `librarian.guidanceForEntity` wins when it returns a non-empty string.
49
+ * Capped at 2,000 characters (UTF-16 units); over-cap guidance is not
50
+ * sent and emits `guidance_too_long`. Holds no secrets: it is sent to
51
+ * the model on every authoring call.
52
+ */
53
+ guidance?: string;
45
54
  }
46
55
  type OntologyMode = 'strict' | 'emergent' | 'off';
47
56
  interface OntologyNodeType {
@@ -257,6 +266,16 @@ interface LibrarianGateConfig {
257
266
  interface LibrarianConfig {
258
267
  strategy?: 'legacy' | 'ops';
259
268
  gate?: LibrarianGateConfig;
269
+ /**
270
+ * Per-entity librarian guidance (specs/librarian-guidance). Returns the
271
+ * short domain instruction for `entityId`, or `undefined`/empty to fall
272
+ * back to `config.prompts.guidance`. Called synchronously once per
273
+ * librarian pass / ingest call; a throw or non-string return is treated
274
+ * as no value (fallback + `guidance_resolver_failed` diagnostic). The
275
+ * engine stores neither value. Lives under `librarian`, not `prompts`,
276
+ * so `WikiConfig.prompts` stays a struct of plain strings.
277
+ */
278
+ guidanceForEntity?: (entityId: string) => string | undefined;
260
279
  }
261
280
  interface WikiConfig {
262
281
  /**
@@ -452,6 +471,28 @@ interface ReadOptions {
452
471
  */
453
472
  tokenBudget?: number;
454
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
+ };
455
496
  interface WikiFact {
456
497
  id: string;
457
498
  entity_id: string;
@@ -533,6 +574,8 @@ interface WikiFact {
533
574
  superseded_by?: string | null;
534
575
  /** Epoch ms the supersession was recorded (transaction time). Audit only. */
535
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;
536
579
  }
537
580
  interface WikiTask {
538
581
  id: string;
@@ -804,7 +847,7 @@ type WikiDiagnosticSeverity = 'info' | 'warn' | 'error';
804
847
  * Closed for this release series, but new codes are added in minor versions:
805
848
  * hosts must tolerate codes they do not recognize.
806
849
  */
807
- 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';
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';
808
851
  /** The service run that emitted the diagnostic. */
809
852
  type WikiDiagnosticOperation = 'ingest' | 'upsertGraph' | 'librarian' | 'heal' | 'ontologyBackfill' | 'reembed' | 'importDump' | 'write' | 'supersede' | 'remember' | 'read' | 'prune' | 'externalDeletion';
810
853
  /** `'auto'` when a write threshold started the run (auto-librarian / auto-heal); `'call'` when the host did. */
@@ -849,6 +892,10 @@ interface WikiDiagnosticDetail {
849
892
  oldestEnqueuedAt?: number;
850
893
  /** external_deletion_pending only: highest attempt count among pending rows. */
851
894
  maxAttempts?: number;
895
+ /** guidance_too_long only: length of the refused value in UTF-16 code units. */
896
+ guidanceLength?: number;
897
+ /** guidance_too_long only: which configured value was refused. */
898
+ guidanceSource?: 'per_entity' | 'default';
852
899
  }
853
900
  interface WikiDiagnostic {
854
901
  code: WikiDiagnosticCode;
@@ -981,6 +1028,16 @@ interface MemoryBundle {
981
1028
  interface MemoryDump {
982
1029
  generatedAt: number;
983
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
+ }>;
984
1041
  }
985
1042
  interface FormattedMemoryDump {
986
1043
  manifest: string;
@@ -1651,7 +1708,7 @@ declare class EntryRepository extends BaseRepository {
1651
1708
  }>>;
1652
1709
  findIdById(id: string, entityId: string, tx?: SQLiteAdapter): Promise<string | null>;
1653
1710
  findIdsBySource(entityId: string, sourceRef: string | null, sourceHash: string | null, tx?: SQLiteAdapter, includeDeleted?: boolean): Promise<string[]>;
1654
- upsertForImport(fact: WikiFact, tx: SQLiteAdapter): Promise<{
1711
+ upsertForImport(fact: WikiFact, tx: SQLiteAdapter, sourcePointerPresent?: boolean): Promise<{
1655
1712
  changes: number;
1656
1713
  lastInsertRowId: number;
1657
1714
  }>;
@@ -3007,25 +3064,58 @@ type LabeledEvent = {
3007
3064
  at: number;
3008
3065
  };
3009
3066
 
3067
+ /** Why a pass or call will not carry guidance (specs/librarian-guidance). */
3068
+ interface GuidanceDiagnostic {
3069
+ code: 'guidance_too_long' | 'guidance_resolver_failed';
3070
+ detail?: {
3071
+ guidanceLength?: number;
3072
+ guidanceSource?: 'per_entity' | 'default';
3073
+ reason?: 'threw' | 'non_string';
3074
+ };
3075
+ }
3076
+
3010
3077
  declare class PromptService {
3011
3078
  private globalOverrides?;
3012
3079
  private grounding;
3013
3080
  constructor(globalOverrides?: PromptOverrides | undefined, grounding?: ResolvedGrounding | null);
3081
+ /**
3082
+ * Specs/librarian-guidance: resolve the effective guidance for one pass
3083
+ * or call — default `config.prompts.guidance`, per-entity
3084
+ * `config.librarian.guidanceForEntity` winning when it returns a
3085
+ * non-empty (trimmed) string. Synchronous: a resolver that throws,
3086
+ * returns a thenable (its rejection is swallowed with a no-op handler;
3087
+ * a throwing `then` counts too), or returns any non-string value is
3088
+ * treated as "no value" and reported in `diagnostic`. Over-cap text
3089
+ * (UTF-16 units, verbatim) is not sent and reported in `diagnostic`.
3090
+ * Emits nothing itself; the caller emits, immediately at resolution.
3091
+ */
3092
+ static resolveGuidance(config: WikiConfig | undefined, entityId: string): {
3093
+ guidance?: string;
3094
+ diagnostic?: GuidanceDiagnostic;
3095
+ };
3014
3096
  /** The resolved grounding config when `writer` is in `grounding.writers`; otherwise null (spec §6.2). */
3015
3097
  groundingFor(writer: GroundingWriter): ResolvedGrounding | null;
3016
3098
  /** Appended after any override and after ontology context, so it is always last. */
3017
3099
  private appendGrounding;
3100
+ /**
3101
+ * Specs/librarian-guidance: append the marked guidance section (with the
3102
+ * general leave-out rule) to the ALREADY-HYDRATED system prompt — after
3103
+ * ontology, immediately before grounding. The guidance text is never
3104
+ * run through hydration, so `{{…}}` inside it cannot change a builder's
3105
+ * template branch or be expanded with data. No-op on empty input.
3106
+ */
3107
+ private appendGuidance;
3018
3108
  private hydrate;
3019
3109
  private hasOntologyPlaceholders;
3020
3110
  /** Removes ontology placeholders until none remain, so a nested form cannot reassemble one (closes CodeQL #11). */
3021
3111
  private stripOntologyPlaceholders;
3022
3112
  private buildSystemPrompt;
3023
3113
  private appendOntology;
3024
- buildIngestPrompt(documentChunk: string, runtimeOverride?: string, ontologyContext?: OntologyPromptContext | null): {
3114
+ buildIngestPrompt(documentChunk: string, runtimeOverride?: string, ontologyContext?: OntologyPromptContext | null, guidance?: string): {
3025
3115
  systemPrompt: string;
3026
3116
  userPrompt: string;
3027
3117
  };
3028
- buildLibrarianPrompt(events: unknown[], currentFacts: unknown[], runtimeOverride?: string, ontologyContext?: OntologyPromptContext | null): {
3118
+ buildLibrarianPrompt(events: unknown[], currentFacts: unknown[], runtimeOverride?: string, ontologyContext?: OntologyPromptContext | null, guidance?: string): {
3029
3119
  systemPrompt: string;
3030
3120
  userPrompt: string;
3031
3121
  groundingCorpus?: string[];
@@ -3065,7 +3155,7 @@ declare class PromptService {
3065
3155
  userPrompt: string;
3066
3156
  };
3067
3157
  /** Ops extract (spec §5.2): events only — no existing facts. */
3068
- buildOpsExtractPrompt(events: LabeledEvent[], ontologyContext?: OntologyPromptContext | null): {
3158
+ buildOpsExtractPrompt(events: LabeledEvent[], ontologyContext?: OntologyPromptContext | null, guidance?: string): {
3069
3159
  systemPrompt: string;
3070
3160
  userPrompt: string;
3071
3161
  groundingCorpus?: string[];
@@ -3092,7 +3182,7 @@ declare class PromptService {
3092
3182
  * placeholders and leaves data placeholders verbatim; heal never receives
3093
3183
  * ontology context, matching `buildHealPrompt`.
3094
3184
  */
3095
- buildInstructionTemplates(ontologyContext: OntologyPromptContext | null, librarianStrategy: 'legacy' | 'ops'): WikiInstructions;
3185
+ buildInstructionTemplates(ontologyContext: OntologyPromptContext | null, librarianStrategy: 'legacy' | 'ops', guidance?: string): WikiInstructions;
3096
3186
  }
3097
3187
 
3098
3188
  declare class IngestionService {
@@ -3435,6 +3525,14 @@ interface LibrarianContext {
3435
3525
  entityId: string;
3436
3526
  trigger: WikiDiagnosticTrigger;
3437
3527
  promptOverride?: string;
3528
+ /**
3529
+ * Specs/librarian-guidance: the effective guidance for this pass, resolved
3530
+ * by `MaintenanceService.runLibrarianPass` (never read as caller input —
3531
+ * that method overwrites whatever a caller supplies here, so "resolved
3532
+ * once per pass" holds for every caller). Strategies pass it to the
3533
+ * prompt builders verbatim.
3534
+ */
3535
+ guidance?: string;
3438
3536
  /** Optional meter (Phase C budgeted maintenance). Legacy honors it:
3439
3537
  * `callLlm` pre-flights the prompt estimate against it, usage is recorded
3440
3538
  * on every call, and the pass returns `budgetStop` when the budget is
@@ -4140,7 +4238,7 @@ declare class WikiMemory {
4140
4238
  /**
4141
4239
  * @param options.promptOverride - Applies only to this manual call. Does NOT affect
4142
4240
  * WriteService-triggered auto-runs. For persistent prompt customization across auto-runs,
4143
- * set `options.config.prompts.librarianSystemPrompt` at WikiMemory construction time.
4241
+ * set `options.config.prompts.guidance` at WikiMemory construction time.
4144
4242
  */
4145
4243
  runLibrarian(entityId: string, options?: {
4146
4244
  promptOverride?: string;
@@ -4494,5 +4592,5 @@ declare class WikiMemory {
4494
4592
  setGeneratedByTask(taskId: string, entityId: string, actor: string): Promise<void>;
4495
4593
  }
4496
4594
 
4497
- export { HEAL_BATCH_SIZE as H, ONTOLOGY_BACKFILL_MAX_PROMPT_CHARS as K, ONTOLOGY_BACKFILL_RECHECK_MS as N, ONTOLOGY_BACKFILL_BATCH_SIZE as O, 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 };
4498
- 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, OntologyBackfillResult as P, OntologyConfig as Q, ReadOptions as R, SQLiteAdapter as S, OntologyEdgeType as T, OntologyManifest as U, OntologyMode 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-Og5x9rFu.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-Og5x9rFu.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';