@equationalapplications/core-llm-wiki 8.4.0 → 9.0.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
  /**
@@ -804,7 +823,7 @@ type WikiDiagnosticSeverity = 'info' | 'warn' | 'error';
804
823
  * Closed for this release series, but new codes are added in minor versions:
805
824
  * hosts must tolerate codes they do not recognize.
806
825
  */
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';
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';
808
827
  /** The service run that emitted the diagnostic. */
809
828
  type WikiDiagnosticOperation = 'ingest' | 'upsertGraph' | 'librarian' | 'heal' | 'ontologyBackfill' | 'reembed' | 'importDump' | 'write' | 'supersede' | 'remember' | 'read' | 'prune' | 'externalDeletion';
810
829
  /** `'auto'` when a write threshold started the run (auto-librarian / auto-heal); `'call'` when the host did. */
@@ -849,6 +868,10 @@ interface WikiDiagnosticDetail {
849
868
  oldestEnqueuedAt?: number;
850
869
  /** external_deletion_pending only: highest attempt count among pending rows. */
851
870
  maxAttempts?: number;
871
+ /** guidance_too_long only: length of the refused value in UTF-16 code units. */
872
+ guidanceLength?: number;
873
+ /** guidance_too_long only: which configured value was refused. */
874
+ guidanceSource?: 'per_entity' | 'default';
852
875
  }
853
876
  interface WikiDiagnostic {
854
877
  code: WikiDiagnosticCode;
@@ -3007,25 +3030,58 @@ type LabeledEvent = {
3007
3030
  at: number;
3008
3031
  };
3009
3032
 
3033
+ /** Why a pass or call will not carry guidance (specs/librarian-guidance). */
3034
+ interface GuidanceDiagnostic {
3035
+ code: 'guidance_too_long' | 'guidance_resolver_failed';
3036
+ detail?: {
3037
+ guidanceLength?: number;
3038
+ guidanceSource?: 'per_entity' | 'default';
3039
+ reason?: 'threw' | 'non_string';
3040
+ };
3041
+ }
3042
+
3010
3043
  declare class PromptService {
3011
3044
  private globalOverrides?;
3012
3045
  private grounding;
3013
3046
  constructor(globalOverrides?: PromptOverrides | undefined, grounding?: ResolvedGrounding | null);
3047
+ /**
3048
+ * Specs/librarian-guidance: resolve the effective guidance for one pass
3049
+ * or call — default `config.prompts.guidance`, per-entity
3050
+ * `config.librarian.guidanceForEntity` winning when it returns a
3051
+ * non-empty (trimmed) string. Synchronous: a resolver that throws,
3052
+ * returns a thenable (its rejection is swallowed with a no-op handler;
3053
+ * a throwing `then` counts too), or returns any non-string value is
3054
+ * treated as "no value" and reported in `diagnostic`. Over-cap text
3055
+ * (UTF-16 units, verbatim) is not sent and reported in `diagnostic`.
3056
+ * Emits nothing itself; the caller emits, immediately at resolution.
3057
+ */
3058
+ static resolveGuidance(config: WikiConfig | undefined, entityId: string): {
3059
+ guidance?: string;
3060
+ diagnostic?: GuidanceDiagnostic;
3061
+ };
3014
3062
  /** The resolved grounding config when `writer` is in `grounding.writers`; otherwise null (spec §6.2). */
3015
3063
  groundingFor(writer: GroundingWriter): ResolvedGrounding | null;
3016
3064
  /** Appended after any override and after ontology context, so it is always last. */
3017
3065
  private appendGrounding;
3066
+ /**
3067
+ * Specs/librarian-guidance: append the marked guidance section (with the
3068
+ * general leave-out rule) to the ALREADY-HYDRATED system prompt — after
3069
+ * ontology, immediately before grounding. The guidance text is never
3070
+ * run through hydration, so `{{…}}` inside it cannot change a builder's
3071
+ * template branch or be expanded with data. No-op on empty input.
3072
+ */
3073
+ private appendGuidance;
3018
3074
  private hydrate;
3019
3075
  private hasOntologyPlaceholders;
3020
3076
  /** Removes ontology placeholders until none remain, so a nested form cannot reassemble one (closes CodeQL #11). */
3021
3077
  private stripOntologyPlaceholders;
3022
3078
  private buildSystemPrompt;
3023
3079
  private appendOntology;
3024
- buildIngestPrompt(documentChunk: string, runtimeOverride?: string, ontologyContext?: OntologyPromptContext | null): {
3080
+ buildIngestPrompt(documentChunk: string, runtimeOverride?: string, ontologyContext?: OntologyPromptContext | null, guidance?: string): {
3025
3081
  systemPrompt: string;
3026
3082
  userPrompt: string;
3027
3083
  };
3028
- buildLibrarianPrompt(events: unknown[], currentFacts: unknown[], runtimeOverride?: string, ontologyContext?: OntologyPromptContext | null): {
3084
+ buildLibrarianPrompt(events: unknown[], currentFacts: unknown[], runtimeOverride?: string, ontologyContext?: OntologyPromptContext | null, guidance?: string): {
3029
3085
  systemPrompt: string;
3030
3086
  userPrompt: string;
3031
3087
  groundingCorpus?: string[];
@@ -3065,7 +3121,7 @@ declare class PromptService {
3065
3121
  userPrompt: string;
3066
3122
  };
3067
3123
  /** Ops extract (spec §5.2): events only — no existing facts. */
3068
- buildOpsExtractPrompt(events: LabeledEvent[], ontologyContext?: OntologyPromptContext | null): {
3124
+ buildOpsExtractPrompt(events: LabeledEvent[], ontologyContext?: OntologyPromptContext | null, guidance?: string): {
3069
3125
  systemPrompt: string;
3070
3126
  userPrompt: string;
3071
3127
  groundingCorpus?: string[];
@@ -3092,7 +3148,7 @@ declare class PromptService {
3092
3148
  * placeholders and leaves data placeholders verbatim; heal never receives
3093
3149
  * ontology context, matching `buildHealPrompt`.
3094
3150
  */
3095
- buildInstructionTemplates(ontologyContext: OntologyPromptContext | null, librarianStrategy: 'legacy' | 'ops'): WikiInstructions;
3151
+ buildInstructionTemplates(ontologyContext: OntologyPromptContext | null, librarianStrategy: 'legacy' | 'ops', guidance?: string): WikiInstructions;
3096
3152
  }
3097
3153
 
3098
3154
  declare class IngestionService {
@@ -3435,6 +3491,14 @@ interface LibrarianContext {
3435
3491
  entityId: string;
3436
3492
  trigger: WikiDiagnosticTrigger;
3437
3493
  promptOverride?: string;
3494
+ /**
3495
+ * Specs/librarian-guidance: the effective guidance for this pass, resolved
3496
+ * by `MaintenanceService.runLibrarianPass` (never read as caller input —
3497
+ * that method overwrites whatever a caller supplies here, so "resolved
3498
+ * once per pass" holds for every caller). Strategies pass it to the
3499
+ * prompt builders verbatim.
3500
+ */
3501
+ guidance?: string;
3438
3502
  /** Optional meter (Phase C budgeted maintenance). Legacy honors it:
3439
3503
  * `callLlm` pre-flights the prompt estimate against it, usage is recorded
3440
3504
  * on every call, and the pass returns `budgetStop` when the budget is
@@ -4140,7 +4204,7 @@ declare class WikiMemory {
4140
4204
  /**
4141
4205
  * @param options.promptOverride - Applies only to this manual call. Does NOT affect
4142
4206
  * WriteService-triggered auto-runs. For persistent prompt customization across auto-runs,
4143
- * set `options.config.prompts.librarianSystemPrompt` at WikiMemory construction time.
4207
+ * set `options.config.prompts.guidance` at WikiMemory construction time.
4144
4208
  */
4145
4209
  runLibrarian(entityId: string, options?: {
4146
4210
  promptOverride?: string;
@@ -4494,5 +4558,5 @@ declare class WikiMemory {
4494
4558
  setGeneratedByTask(taskId: string, entityId: string, actor: string): Promise<void>;
4495
4559
  }
4496
4560
 
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 };
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 };
@@ -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
  /**
@@ -804,7 +823,7 @@ type WikiDiagnosticSeverity = 'info' | 'warn' | 'error';
804
823
  * Closed for this release series, but new codes are added in minor versions:
805
824
  * hosts must tolerate codes they do not recognize.
806
825
  */
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';
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';
808
827
  /** The service run that emitted the diagnostic. */
809
828
  type WikiDiagnosticOperation = 'ingest' | 'upsertGraph' | 'librarian' | 'heal' | 'ontologyBackfill' | 'reembed' | 'importDump' | 'write' | 'supersede' | 'remember' | 'read' | 'prune' | 'externalDeletion';
810
829
  /** `'auto'` when a write threshold started the run (auto-librarian / auto-heal); `'call'` when the host did. */
@@ -849,6 +868,10 @@ interface WikiDiagnosticDetail {
849
868
  oldestEnqueuedAt?: number;
850
869
  /** external_deletion_pending only: highest attempt count among pending rows. */
851
870
  maxAttempts?: number;
871
+ /** guidance_too_long only: length of the refused value in UTF-16 code units. */
872
+ guidanceLength?: number;
873
+ /** guidance_too_long only: which configured value was refused. */
874
+ guidanceSource?: 'per_entity' | 'default';
852
875
  }
853
876
  interface WikiDiagnostic {
854
877
  code: WikiDiagnosticCode;
@@ -3007,25 +3030,58 @@ type LabeledEvent = {
3007
3030
  at: number;
3008
3031
  };
3009
3032
 
3033
+ /** Why a pass or call will not carry guidance (specs/librarian-guidance). */
3034
+ interface GuidanceDiagnostic {
3035
+ code: 'guidance_too_long' | 'guidance_resolver_failed';
3036
+ detail?: {
3037
+ guidanceLength?: number;
3038
+ guidanceSource?: 'per_entity' | 'default';
3039
+ reason?: 'threw' | 'non_string';
3040
+ };
3041
+ }
3042
+
3010
3043
  declare class PromptService {
3011
3044
  private globalOverrides?;
3012
3045
  private grounding;
3013
3046
  constructor(globalOverrides?: PromptOverrides | undefined, grounding?: ResolvedGrounding | null);
3047
+ /**
3048
+ * Specs/librarian-guidance: resolve the effective guidance for one pass
3049
+ * or call — default `config.prompts.guidance`, per-entity
3050
+ * `config.librarian.guidanceForEntity` winning when it returns a
3051
+ * non-empty (trimmed) string. Synchronous: a resolver that throws,
3052
+ * returns a thenable (its rejection is swallowed with a no-op handler;
3053
+ * a throwing `then` counts too), or returns any non-string value is
3054
+ * treated as "no value" and reported in `diagnostic`. Over-cap text
3055
+ * (UTF-16 units, verbatim) is not sent and reported in `diagnostic`.
3056
+ * Emits nothing itself; the caller emits, immediately at resolution.
3057
+ */
3058
+ static resolveGuidance(config: WikiConfig | undefined, entityId: string): {
3059
+ guidance?: string;
3060
+ diagnostic?: GuidanceDiagnostic;
3061
+ };
3014
3062
  /** The resolved grounding config when `writer` is in `grounding.writers`; otherwise null (spec §6.2). */
3015
3063
  groundingFor(writer: GroundingWriter): ResolvedGrounding | null;
3016
3064
  /** Appended after any override and after ontology context, so it is always last. */
3017
3065
  private appendGrounding;
3066
+ /**
3067
+ * Specs/librarian-guidance: append the marked guidance section (with the
3068
+ * general leave-out rule) to the ALREADY-HYDRATED system prompt — after
3069
+ * ontology, immediately before grounding. The guidance text is never
3070
+ * run through hydration, so `{{…}}` inside it cannot change a builder's
3071
+ * template branch or be expanded with data. No-op on empty input.
3072
+ */
3073
+ private appendGuidance;
3018
3074
  private hydrate;
3019
3075
  private hasOntologyPlaceholders;
3020
3076
  /** Removes ontology placeholders until none remain, so a nested form cannot reassemble one (closes CodeQL #11). */
3021
3077
  private stripOntologyPlaceholders;
3022
3078
  private buildSystemPrompt;
3023
3079
  private appendOntology;
3024
- buildIngestPrompt(documentChunk: string, runtimeOverride?: string, ontologyContext?: OntologyPromptContext | null): {
3080
+ buildIngestPrompt(documentChunk: string, runtimeOverride?: string, ontologyContext?: OntologyPromptContext | null, guidance?: string): {
3025
3081
  systemPrompt: string;
3026
3082
  userPrompt: string;
3027
3083
  };
3028
- buildLibrarianPrompt(events: unknown[], currentFacts: unknown[], runtimeOverride?: string, ontologyContext?: OntologyPromptContext | null): {
3084
+ buildLibrarianPrompt(events: unknown[], currentFacts: unknown[], runtimeOverride?: string, ontologyContext?: OntologyPromptContext | null, guidance?: string): {
3029
3085
  systemPrompt: string;
3030
3086
  userPrompt: string;
3031
3087
  groundingCorpus?: string[];
@@ -3065,7 +3121,7 @@ declare class PromptService {
3065
3121
  userPrompt: string;
3066
3122
  };
3067
3123
  /** Ops extract (spec §5.2): events only — no existing facts. */
3068
- buildOpsExtractPrompt(events: LabeledEvent[], ontologyContext?: OntologyPromptContext | null): {
3124
+ buildOpsExtractPrompt(events: LabeledEvent[], ontologyContext?: OntologyPromptContext | null, guidance?: string): {
3069
3125
  systemPrompt: string;
3070
3126
  userPrompt: string;
3071
3127
  groundingCorpus?: string[];
@@ -3092,7 +3148,7 @@ declare class PromptService {
3092
3148
  * placeholders and leaves data placeholders verbatim; heal never receives
3093
3149
  * ontology context, matching `buildHealPrompt`.
3094
3150
  */
3095
- buildInstructionTemplates(ontologyContext: OntologyPromptContext | null, librarianStrategy: 'legacy' | 'ops'): WikiInstructions;
3151
+ buildInstructionTemplates(ontologyContext: OntologyPromptContext | null, librarianStrategy: 'legacy' | 'ops', guidance?: string): WikiInstructions;
3096
3152
  }
3097
3153
 
3098
3154
  declare class IngestionService {
@@ -3435,6 +3491,14 @@ interface LibrarianContext {
3435
3491
  entityId: string;
3436
3492
  trigger: WikiDiagnosticTrigger;
3437
3493
  promptOverride?: string;
3494
+ /**
3495
+ * Specs/librarian-guidance: the effective guidance for this pass, resolved
3496
+ * by `MaintenanceService.runLibrarianPass` (never read as caller input —
3497
+ * that method overwrites whatever a caller supplies here, so "resolved
3498
+ * once per pass" holds for every caller). Strategies pass it to the
3499
+ * prompt builders verbatim.
3500
+ */
3501
+ guidance?: string;
3438
3502
  /** Optional meter (Phase C budgeted maintenance). Legacy honors it:
3439
3503
  * `callLlm` pre-flights the prompt estimate against it, usage is recorded
3440
3504
  * on every call, and the pass returns `budgetStop` when the budget is
@@ -4140,7 +4204,7 @@ declare class WikiMemory {
4140
4204
  /**
4141
4205
  * @param options.promptOverride - Applies only to this manual call. Does NOT affect
4142
4206
  * WriteService-triggered auto-runs. For persistent prompt customization across auto-runs,
4143
- * set `options.config.prompts.librarianSystemPrompt` at WikiMemory construction time.
4207
+ * set `options.config.prompts.guidance` at WikiMemory construction time.
4144
4208
  */
4145
4209
  runLibrarian(entityId: string, options?: {
4146
4210
  promptOverride?: string;
@@ -4494,5 +4558,5 @@ declare class WikiMemory {
4494
4558
  setGeneratedByTask(taskId: string, entityId: string, actor: string): Promise<void>;
4495
4559
  }
4496
4560
 
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 };
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 };
@@ -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 { 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';
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 { 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';
2
2
  import '@equationalapplications/core-okf';
package/dist/testing.js CHANGED
@@ -727,7 +727,9 @@ var SEVERITY = {
727
727
  event_created_at_clamped: "warn",
728
728
  event_created_at_restamped: "info",
729
729
  external_deletion_pending: "warn",
730
- external_deletion_discarded: "warn"
730
+ external_deletion_discarded: "warn",
731
+ guidance_too_long: "warn",
732
+ guidance_resolver_failed: "warn"
731
733
  };
732
734
  var MESSAGE = {
733
735
  ingest_chunk_failed: "One or more document chunks failed to parse or generate.",
@@ -753,7 +755,9 @@ var MESSAGE = {
753
755
  event_created_at_clamped: "Imported events dated in the future were re-dated just after the current time, or after the librarian position if that is later, keeping their order.",
754
756
  event_created_at_restamped: "Imported events that would have sorted behind the librarian position, or had an unusable date, were adjusted: an affected created_at was re-dated just after the current time, or after the librarian position if that is later, keeping their order; an unusable occurred_at was cleared.",
755
757
  external_deletion_pending: "Removals owed to the external vector index are still pending.",
756
- external_deletion_discarded: "Pending external vector removals were discarded because forceDeleteIgnoreRankerHook is set."
758
+ external_deletion_discarded: "Pending external vector removals were discarded because forceDeleteIgnoreRankerHook is set.",
759
+ 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."
757
761
  };
758
762
  var warnedNonFunction = /* @__PURE__ */ new WeakSet();
759
763
  function copyDetail(detail) {
@@ -1886,6 +1890,14 @@ function generateId(prefix = "") {
1886
1890
  }
1887
1891
 
1888
1892
  // src/prompts.ts
1893
+ var LEAVE_OUT_RULE_SENTENCE = "Memory leaves out what a better record already holds, and points to that record.";
1894
+ var GUIDANCE_MAX_CHARS = 2e3;
1895
+ function guidanceSection(guidance) {
1896
+ return `--- Host guidance ---
1897
+ ${guidance}
1898
+ --- End host guidance ---
1899
+ ${LEAVE_OUT_RULE_SENTENCE}`;
1900
+ }
1889
1901
  var LIBRARIAN_SYSTEM_PROMPT = `You are a knowledge extraction agent. Your job is to analyze recent episodic events and extract stable facts and actionable tasks about the user or entity.
1890
1902
  Return ONLY a valid JSON object matching this schema:
1891
1903
  {
@@ -2009,6 +2021,64 @@ var PromptService = class {
2009
2021
  this.globalOverrides = globalOverrides;
2010
2022
  this.grounding = grounding;
2011
2023
  }
2024
+ /**
2025
+ * Specs/librarian-guidance: resolve the effective guidance for one pass
2026
+ * or call — default `config.prompts.guidance`, per-entity
2027
+ * `config.librarian.guidanceForEntity` winning when it returns a
2028
+ * non-empty (trimmed) string. Synchronous: a resolver that throws,
2029
+ * returns a thenable (its rejection is swallowed with a no-op handler;
2030
+ * a throwing `then` counts too), or returns any non-string value is
2031
+ * treated as "no value" and reported in `diagnostic`. Over-cap text
2032
+ * (UTF-16 units, verbatim) is not sent and reported in `diagnostic`.
2033
+ * Emits nothing itself; the caller emits, immediately at resolution.
2034
+ */
2035
+ static resolveGuidance(config, entityId) {
2036
+ let source = null;
2037
+ let effective;
2038
+ let resolverDiagnostic;
2039
+ const defaultValue = config?.prompts?.guidance;
2040
+ const resolver = config?.librarian?.guidanceForEntity;
2041
+ let entityValue;
2042
+ if (resolver) {
2043
+ try {
2044
+ entityValue = resolver(entityId);
2045
+ if (entityValue === void 0) {
2046
+ } else if (typeof entityValue === "string") {
2047
+ if (entityValue.trim() !== "") {
2048
+ source = "per_entity";
2049
+ effective = entityValue;
2050
+ }
2051
+ } else {
2052
+ try {
2053
+ entityValue?.then?.(() => void 0, () => void 0);
2054
+ } catch {
2055
+ }
2056
+ resolverDiagnostic = {
2057
+ code: "guidance_resolver_failed",
2058
+ detail: { reason: "non_string" }
2059
+ };
2060
+ }
2061
+ } catch {
2062
+ resolverDiagnostic = { code: "guidance_resolver_failed", detail: { reason: "threw" } };
2063
+ }
2064
+ }
2065
+ if (source === null && defaultValue !== void 0 && defaultValue.trim() !== "") {
2066
+ source = "default";
2067
+ effective = defaultValue;
2068
+ }
2069
+ if (source === null || effective === void 0) {
2070
+ return resolverDiagnostic ? { diagnostic: resolverDiagnostic } : {};
2071
+ }
2072
+ if (effective.length > GUIDANCE_MAX_CHARS) {
2073
+ return {
2074
+ diagnostic: {
2075
+ code: "guidance_too_long",
2076
+ detail: { guidanceLength: effective.length, guidanceSource: source }
2077
+ }
2078
+ };
2079
+ }
2080
+ return resolverDiagnostic ? { guidance: effective, diagnostic: resolverDiagnostic } : { guidance: effective };
2081
+ }
2012
2082
  /** The resolved grounding config when `writer` is in `grounding.writers`; otherwise null (spec §6.2). */
2013
2083
  groundingFor(writer) {
2014
2084
  return this.grounding?.writers.has(writer) ? this.grounding : null;
@@ -2019,6 +2089,19 @@ var PromptService = class {
2019
2089
  return cfg ? `${systemPrompt}
2020
2090
 
2021
2091
  ${groundingEvidenceBlock(writer, cfg)}` : systemPrompt;
2092
+ }
2093
+ /**
2094
+ * Specs/librarian-guidance: append the marked guidance section (with the
2095
+ * general leave-out rule) to the ALREADY-HYDRATED system prompt — after
2096
+ * ontology, immediately before grounding. The guidance text is never
2097
+ * run through hydration, so `{{…}}` inside it cannot change a builder's
2098
+ * template branch or be expanded with data. No-op on empty input.
2099
+ */
2100
+ appendGuidance(systemPrompt, guidance) {
2101
+ if (!guidance) return systemPrompt;
2102
+ return `${systemPrompt}
2103
+
2104
+ ${guidanceSection(guidance)}`;
2022
2105
  }
2023
2106
  hydrate(template, variables) {
2024
2107
  return template.replace(/\{\{\s*(\w+)\s*\}\}/g, (_match, key) => {
@@ -2055,31 +2138,31 @@ ${groundingEvidenceBlock(writer, cfg)}` : systemPrompt;
2055
2138
 
2056
2139
  ${ctx.ontologyModeInstructions}`;
2057
2140
  }
2058
- buildIngestPrompt(documentChunk, runtimeOverride, ontologyContext) {
2141
+ buildIngestPrompt(documentChunk, runtimeOverride, ontologyContext, guidance) {
2059
2142
  const template = runtimeOverride ?? this.globalOverrides?.ingestSystemPrompt ?? INGEST_SYSTEM_PROMPT;
2060
2143
  const hasDocumentChunk = /\{\{\s*documentChunk\s*\}\}/.test(template);
2061
2144
  if (hasDocumentChunk || this.hasOntologyPlaceholders(template)) {
2062
2145
  return {
2063
- systemPrompt: this.appendGrounding(this.buildSystemPrompt(template, { documentChunk }, ontologyContext), "ingest"),
2146
+ systemPrompt: this.appendGrounding(this.appendGuidance(this.buildSystemPrompt(template, { documentChunk }, ontologyContext), guidance), "ingest"),
2064
2147
  userPrompt: hasDocumentChunk ? "Please extract the facts." : `Document Chunk:
2065
2148
  ${documentChunk}`
2066
2149
  };
2067
2150
  }
2068
2151
  return {
2069
- systemPrompt: this.appendGrounding(this.appendOntology(template, ontologyContext), "ingest"),
2152
+ systemPrompt: this.appendGrounding(this.appendGuidance(this.appendOntology(template, ontologyContext), guidance), "ingest"),
2070
2153
  userPrompt: `Document Chunk:
2071
2154
  ${documentChunk}`
2072
2155
  };
2073
2156
  }
2074
- buildLibrarianPrompt(events, currentFacts, runtimeOverride, ontologyContext) {
2075
- const template = runtimeOverride ?? this.globalOverrides?.librarianSystemPrompt ?? LIBRARIAN_SYSTEM_PROMPT;
2157
+ buildLibrarianPrompt(events, currentFacts, runtimeOverride, ontologyContext, guidance) {
2158
+ const template = runtimeOverride ?? LIBRARIAN_SYSTEM_PROMPT;
2076
2159
  const hasEvents = /\{\{\s*events\s*\}\}/.test(template);
2077
2160
  const hasCurrentFacts = /\{\{\s*currentFacts\s*\}\}/.test(template);
2078
2161
  const eventsShown = hasEvents || !hasCurrentFacts;
2079
2162
  const corpusField = this.groundingFor("librarian") ? { groundingCorpus: buildGroundingCorpus(eventsShown ? events.map(summaryOf) : []) } : {};
2080
2163
  if (hasEvents || hasCurrentFacts || this.hasOntologyPlaceholders(template)) {
2081
2164
  return {
2082
- systemPrompt: this.appendGrounding(this.buildSystemPrompt(template, { events, currentFacts }, ontologyContext), "librarian"),
2165
+ systemPrompt: this.appendGrounding(this.appendGuidance(this.buildSystemPrompt(template, { events, currentFacts }, ontologyContext), guidance), "librarian"),
2083
2166
  userPrompt: hasEvents || hasCurrentFacts ? "Please synthesize the context." : `Events:
2084
2167
  ${JSON.stringify(events, null, 2)}
2085
2168
 
@@ -2089,7 +2172,7 @@ ${JSON.stringify(currentFacts, null, 2)}`,
2089
2172
  };
2090
2173
  }
2091
2174
  return {
2092
- systemPrompt: this.appendGrounding(this.appendOntology(template, ontologyContext), "librarian"),
2175
+ systemPrompt: this.appendGrounding(this.appendGuidance(this.appendOntology(template, ontologyContext), guidance), "librarian"),
2093
2176
  userPrompt: `Events:
2094
2177
  ${JSON.stringify(events, null, 2)}
2095
2178
 
@@ -2192,11 +2275,11 @@ ${JSON.stringify(facts, null, 2)}`
2192
2275
  };
2193
2276
  }
2194
2277
  /** Ops extract (spec §5.2): events only — no existing facts. */
2195
- buildOpsExtractPrompt(events, ontologyContext) {
2278
+ buildOpsExtractPrompt(events, ontologyContext, guidance) {
2196
2279
  const lines = events.map((l) => `${l.label} [${new Date(l.at).toISOString()}] (${l.event.event_type}) ${l.event.summary}`);
2197
2280
  const grounding = this.groundingFor("librarian");
2198
2281
  return {
2199
- systemPrompt: this.appendGrounding(this.appendOntology(OPS_EXTRACT_SYSTEM_PROMPT, ontologyContext), "librarian"),
2282
+ systemPrompt: this.appendGrounding(this.appendGuidance(this.appendOntology(OPS_EXTRACT_SYSTEM_PROMPT, ontologyContext), guidance), "librarian"),
2200
2283
  userPrompt: `Events:
2201
2284
  ${lines.join("\n")}`,
2202
2285
  ...grounding ? { groundingCorpus: buildGroundingCorpus(events.map((l) => l.event.summary)) } : {}
@@ -2213,11 +2296,11 @@ ${JSON.stringify({ items })}` };
2213
2296
  * placeholders and leaves data placeholders verbatim; heal never receives
2214
2297
  * ontology context, matching `buildHealPrompt`.
2215
2298
  */
2216
- buildInstructionTemplates(ontologyContext, librarianStrategy) {
2299
+ buildInstructionTemplates(ontologyContext, librarianStrategy, guidance) {
2217
2300
  const o = this.globalOverrides;
2218
2301
  return {
2219
- ingest: this.appendGrounding(this.buildSystemPrompt(o?.ingestSystemPrompt ?? INGEST_SYSTEM_PROMPT, {}, ontologyContext), "ingest"),
2220
- librarian: librarianStrategy === "ops" ? this.appendGrounding(this.appendOntology(OPS_EXTRACT_SYSTEM_PROMPT, ontologyContext), "librarian") : this.appendGrounding(this.buildSystemPrompt(o?.librarianSystemPrompt ?? LIBRARIAN_SYSTEM_PROMPT, {}, ontologyContext), "librarian"),
2302
+ ingest: this.appendGrounding(this.appendGuidance(this.buildSystemPrompt(o?.ingestSystemPrompt ?? INGEST_SYSTEM_PROMPT, {}, ontologyContext), guidance), "ingest"),
2303
+ librarian: librarianStrategy === "ops" ? this.appendGrounding(this.appendGuidance(this.appendOntology(OPS_EXTRACT_SYSTEM_PROMPT, ontologyContext), guidance), "librarian") : this.appendGrounding(this.appendGuidance(this.buildSystemPrompt(LIBRARIAN_SYSTEM_PROMPT, {}, ontologyContext), guidance), "librarian"),
2221
2304
  heal: this.appendGrounding(o?.healSystemPrompt ?? HEAL_SYSTEM_PROMPT, "heal"),
2222
2305
  ontologyBackfill: this.buildSystemPrompt(o?.ontologyBackfillSystemPrompt ?? ONTOLOGY_BACKFILL_SYSTEM_PROMPT, {}, ontologyContext)
2223
2306
  };
@@ -2392,13 +2475,24 @@ var IngestionService = class {
2392
2475
  const { chunks: chunks2, truncated } = chunkText(params.documentChunk, maxChunkLength, chunkOverlap);
2393
2476
  if (chunks2.length === 0) return zeroChunkResult();
2394
2477
  const ontologyContext = await this.ontologyService?.buildPromptContext(entityId) ?? null;
2478
+ const { guidance, diagnostic } = PromptService.resolveGuidance(this.options.config, entityId);
2479
+ if (diagnostic) {
2480
+ emitDiagnostic(this.options, {
2481
+ code: diagnostic.code,
2482
+ operation: "ingest",
2483
+ trigger: "call",
2484
+ entityId,
2485
+ detail: diagnostic.detail
2486
+ });
2487
+ }
2395
2488
  const ingestGrounding = this.promptService.groundingFor("ingest");
2396
2489
  const chunkResults = await withConcurrency(
2397
2490
  chunks2.map((chunk, chunkIndex) => async () => {
2398
2491
  const { systemPrompt, userPrompt } = this.promptService.buildIngestPrompt(
2399
2492
  chunk,
2400
2493
  params.promptOverride,
2401
- ontologyContext
2494
+ ontologyContext,
2495
+ guidance
2402
2496
  );
2403
2497
  try {
2404
2498
  const responseText = await callLlm(this.options, { operation: "ingest", entityId, trigger: "call" }, { systemPrompt, userPrompt });
@@ -3803,7 +3897,8 @@ var runLegacyLibrarianPass = async (deps, ctx) => {
3803
3897
  promptEvents,
3804
3898
  currentFacts,
3805
3899
  promptOverride,
3806
- ontologyContext
3900
+ ontologyContext,
3901
+ ctx.guidance
3807
3902
  );
3808
3903
  let responseText;
3809
3904
  try {
@@ -3975,7 +4070,7 @@ var OPS_MAX_EVENTS_PER_PASS = 50;
3975
4070
  var OPS_MAX_EXTRACT_CHARS = 24e3;
3976
4071
  var RESOLVE_RESERVE_FACTOR = 2;
3977
4072
  var estimatePrompt = (p) => estimateTokens(p.systemPrompt) + estimateTokens(p.userPrompt);
3978
- async function selectBatch(deps, entityId, wm, meter) {
4073
+ async function selectBatch(deps, entityId, wm, meter, guidance) {
3979
4074
  const events = await deps.eventRepo.getAfter(entityId, wm, OPS_MAX_EVENTS_PER_PASS);
3980
4075
  if (events.length === 0) return { batch: [] };
3981
4076
  let n = 0;
@@ -3989,7 +4084,7 @@ async function selectBatch(deps, entityId, wm, meter) {
3989
4084
  if (meter && meter.budget !== void 0) {
3990
4085
  const ontologyContext = await deps.ontologyService?.buildPromptContext(entityId) ?? null;
3991
4086
  for (; ; ) {
3992
- const need = RESOLVE_RESERVE_FACTOR * estimatePrompt(deps.promptService.buildOpsExtractPrompt(batch, ontologyContext));
4087
+ const need = RESOLVE_RESERVE_FACTOR * estimatePrompt(deps.promptService.buildOpsExtractPrompt(batch, ontologyContext, guidance));
3993
4088
  if (meter.fits(need)) break;
3994
4089
  if (batch.length === 1) return { budgetStop: { requiredEstimate: need } };
3995
4090
  batch = labelEvents(events.slice(0, Math.max(1, Math.floor(batch.length / 2))));
@@ -4000,7 +4095,7 @@ async function selectBatch(deps, entityId, wm, meter) {
4000
4095
  async function runExtract(deps, ctx, batch) {
4001
4096
  const { entityId, trigger } = ctx;
4002
4097
  const ontologyContext = await deps.ontologyService?.buildPromptContext(entityId) ?? null;
4003
- const prompt = deps.promptService.buildOpsExtractPrompt(batch, ontologyContext);
4098
+ const prompt = deps.promptService.buildOpsExtractPrompt(batch, ontologyContext, ctx.guidance);
4004
4099
  const text = await callLlm(deps.options, { operation: "librarian", entityId, trigger, meter: ctx.meter }, prompt);
4005
4100
  const parsed = parseJsonResponse(text);
4006
4101
  const base = { entityId, operation: "librarian", trigger };
@@ -4471,7 +4566,7 @@ var runOpsLibrarianPass = async (deps, ctx) => {
4471
4566
  const cfg = resolveGateConfig(deps.options.config?.librarian?.gate);
4472
4567
  await deps.seedWatermark(entityId);
4473
4568
  const wm = await deps.getWatermark(entityId);
4474
- const sel = await selectBatch(deps, entityId, wm, ctx.meter);
4569
+ const sel = await selectBatch(deps, entityId, wm, ctx.meter, ctx.guidance);
4475
4570
  if ("budgetStop" in sel) return { processedThrough: null, factsWritten: 0, budgetStop: sel.budgetStop };
4476
4571
  if (sel.batch.length === 0) return { processedThrough: null, factsWritten: 0 };
4477
4572
  if (!deps.searchService.isKeywordAvailable() && await gateNeedsKeyword(deps, entityId)) {
@@ -5109,7 +5204,17 @@ var MaintenanceService = class {
5109
5204
  * A budget-stopped pass wrote nothing and must not move the watermark.
5110
5205
  */
5111
5206
  async runLibrarianPass(ctx) {
5112
- const result = await runLibrarianStrategy(this.librarianDeps(), ctx);
5207
+ const { guidance, diagnostic } = PromptService.resolveGuidance(this.options.config, ctx.entityId);
5208
+ if (diagnostic) {
5209
+ emitDiagnostic(this.options, {
5210
+ code: diagnostic.code,
5211
+ operation: "librarian",
5212
+ trigger: ctx.trigger,
5213
+ entityId: ctx.entityId,
5214
+ detail: diagnostic.detail
5215
+ });
5216
+ }
5217
+ const result = await runLibrarianStrategy(this.librarianDeps(), { ...ctx, guidance });
5113
5218
  if (result.processedThrough && !result.budgetStop) {
5114
5219
  await this.advanceLibrarianWatermark(ctx.entityId, result.processedThrough);
5115
5220
  }