@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.
package/dist/index.d.mts CHANGED
@@ -1,5 +1,5 @@
1
- import { M as MemoryBundle, F as FormatContextOptions, G as GraphNeighborhood, a as MemoryDump, b as FormattedMemoryDump, R as ReadOptions, S as SQLiteAdapter, W as WikiOptions, c as WikiMemory } from './testing-Og5x9rFu.mjs';
2
- export { C as ChunkFailure, d as ClassifierAnswer, e as ClassifierQuestion, f as ClassifyRequest, g as ClassifyResponse, D as DegradedRecord, h as DraftPage, E as EmbedFactResult, i as EmbedFailureKind, j as EmbeddingMarkerKind, k as EntityMaintenanceReport, l as EntityStatus, m as ExtractedFact, n as ExtractedFactEdge, o as ExtractedFactWithOntology, p as ExtractedTask, q as ForgetParams, r as ForgetResult, s as GraphTraversalOptions, t as GroundingConfig, H as HEAL_BATCH_SIZE, u as HEAL_RECHECK_MS, v as HOOK_TIMEOUT_MARKER, w as HealResult, I as IngestDocumentResult, L as LLMProvider, x as LibrarianConfig, y as LibrarianGateConfig, z as LockedMaintenanceJob, A as MaintenanceJob, B as MaintenanceStopReason, J as MigrationPolicy, O as ONTOLOGY_BACKFILL_BATCH_SIZE, K as ONTOLOGY_BACKFILL_MAX_PROMPT_CHARS, N as ONTOLOGY_BACKFILL_RECHECK_MS, P as OntologyBackfillResult, Q as OntologyConfig, T as OntologyEdgeType, U as OntologyManifest, V as OntologyMode, X as OntologyNodeType, Y as OntologyPromptContext, Z as OntologyUpdates, _ as PendingMaintenance, $ as PendingMigrationWork, a0 as PendingSourceStatus, a1 as PromptOverrides, a2 as PromptService, a3 as PrunePartialFailureError, a4 as ReembedResult, a5 as RememberInput, a6 as RunPendingMaintenanceOptions, a7 as RunPendingMaintenanceResult, a8 as SupersedeReplacement, a9 as VectorRanker, aa as VectorRankerFallback, ab as VectorRankerRankArgs, ac as VectorRankerSemanticResult, ad as WikiBusyError, ae as WikiBusyOperation, af as WikiCheckpoint, ag as WikiConfig, ah as WikiDiagnostic, ai as WikiDiagnosticCode, aj as WikiDiagnosticDetail, ak as WikiDiagnosticOperation, al as WikiDiagnosticSeverity, am as WikiDiagnosticTrigger, an as WikiDraftNotFound, ao as WikiDuplicateHashError, ap as WikiEdge, aq as WikiEvent, ar as WikiExternalDeletionError, as as WikiFact, at as WikiGraphNodeOwnershipConflict, au as WikiIngestEmptyError, av as WikiInstructions, aw as WikiInvalidReadOptions, ax as WikiLintReport, ay as WikiMemoryTestAccess, az as WikiMigrationRequiredError, aA as WikiOutboxEvent, aB as WikiParseError, aC as WikiSearchUnavailableError, aD as WikiSourceRefHashCollision, aE as WikiStrictOntologyViolation, aF as WikiSupersedeError, aG as WikiSupersedeReason, aH as WikiTask, aI as WikiTransactionError, aJ as isWikiSearchUnavailableError, aK as validateManifest } from './testing-Og5x9rFu.mjs';
1
+ import { M as MemoryBundle, F as FormatContextOptions, G as GraphNeighborhood, a as MemoryDump, b as FormattedMemoryDump, O as OntologyMode, R as ReadOptions, S as SQLiteAdapter, W as WikiOptions, c as WikiMemory } from './testing-s6DBqXxQ.mjs';
2
+ export { C as ChunkFailure, d as ClassifierAnswer, e as ClassifierQuestion, f as ClassifyRequest, g as ClassifyResponse, D as DegradedRecord, h as DraftPage, E as EmbedFactResult, i as EmbedFailureKind, j as EmbeddingMarkerKind, k as EntityMaintenanceReport, l as EntityStatus, m as ExtractedFact, n as ExtractedFactEdge, o as ExtractedFactWithOntology, p as ExtractedTask, q as ForgetParams, r as ForgetResult, s as GraphTraversalOptions, t as GroundingConfig, H as HEAL_BATCH_SIZE, u as HEAL_RECHECK_MS, v as HOOK_TIMEOUT_MARKER, w as HealResult, I as IngestDocumentResult, L as LLMProvider, x as LibrarianConfig, y as LibrarianGateConfig, z as LockedMaintenanceJob, A as MaintenanceJob, B as MaintenanceStopReason, J as MigrationPolicy, K as ONTOLOGY_BACKFILL_BATCH_SIZE, N as ONTOLOGY_BACKFILL_MAX_PROMPT_CHARS, P as ONTOLOGY_BACKFILL_RECHECK_MS, Q as OntologyBackfillResult, T as OntologyConfig, U as OntologyEdgeType, V as OntologyManifest, X as OntologyNodeType, Y as OntologyPromptContext, Z as OntologyUpdates, _ as PendingMaintenance, $ as PendingMigrationWork, a0 as PendingSourceStatus, a1 as PromptOverrides, a2 as PromptService, a3 as PrunePartialFailureError, a4 as ReembedResult, a5 as RememberInput, a6 as RunPendingMaintenanceOptions, a7 as RunPendingMaintenanceResult, a8 as SupersedeReplacement, a9 as VectorRanker, aa as VectorRankerFallback, ab as VectorRankerRankArgs, ac as VectorRankerSemanticResult, ad as WikiBusyError, ae as WikiBusyOperation, af as WikiCheckpoint, ag as WikiConfig, ah as WikiDiagnostic, ai as WikiDiagnosticCode, aj as WikiDiagnosticDetail, ak as WikiDiagnosticOperation, al as WikiDiagnosticSeverity, am as WikiDiagnosticTrigger, an as WikiDraftNotFound, ao as WikiDuplicateHashError, ap as WikiEdge, aq as WikiEvent, ar as WikiExternalDeletionError, as as WikiFact, at as WikiGraphNodeOwnershipConflict, au as WikiIngestEmptyError, av as WikiInstructions, aw as WikiInvalidReadOptions, ax as WikiLintReport, ay as WikiMemoryTestAccess, az as WikiMigrationRequiredError, aA as WikiOutboxEvent, aB as WikiParseError, aC as WikiSearchUnavailableError, aD as WikiSourceRefHashCollision, aE as WikiStrictOntologyViolation, aF as WikiSupersedeError, aG as WikiSupersedeReason, aH as WikiTask, aI as WikiTransactionError, aJ as isWikiSearchUnavailableError, aK as validateManifest } from './testing-s6DBqXxQ.mjs';
3
3
  import { OkfFile } from '@equationalapplications/core-okf';
4
4
 
5
5
  /**
@@ -90,6 +90,11 @@ declare function parseOkfBundle(entityId: string, files: OkfFile[], options?: Ok
90
90
 
91
91
  declare function parseEmbedding(blob: Uint8Array | null | undefined, text: string | null | undefined): Float32Array | null;
92
92
 
93
+ declare function buildOntologyPromptAppendix(mode: OntologyMode, manifestJson: string): {
94
+ ontologyManifest: string;
95
+ ontologyModeInstructions: string;
96
+ };
97
+
93
98
  type GetRandomValues = (bytes: Uint8Array) => void;
94
99
  /**
95
100
  * Inject a platform-specific `getRandomValues` implementation.
@@ -161,5 +166,5 @@ declare const ONTOLOGY_BACKFILL_SYSTEM_PROMPT = "You are a knowledge classificat
161
166
 
162
167
  declare function createWiki(db: SQLiteAdapter, options: WikiOptions): WikiMemory;
163
168
 
164
- export { DEFAULT_CHUNK_OVERLAP, DEFAULT_LIBRARIAN_SYNTHESIS_PROMPT, DEFAULT_MAX_CHUNK_LENGTH, DEFAULT_MAX_EMBED_CHARS, DEFAULT_SETUP_BUDGET_MS, EMBED_CHARS_CEILING, FormatContextOptions, FormattedMemoryDump, GraphNeighborhood, HEAL_ANCHORS_PER_CANDIDATE, HEAL_MAX_FACT_BODY_CHARS_L3, HEAL_MAX_TASKS, MemoryBundle, MemoryDump, ONTOLOGY_BACKFILL_SYSTEM_PROMPT, ReadOptions, SQLiteAdapter, WikiMemory, WikiOptions, chunkText, configureRandomSource, createWiki, formatContext, formatGraphContext, formatMemoryDump, formatOkfBundle, hydrateLibrarianPrompt, mapLibrarianOptionsToReadOptions, parseEmbedding, parseOkfBundle, safeSlice, validateLibrarianPromptTemplate };
169
+ export { DEFAULT_CHUNK_OVERLAP, DEFAULT_LIBRARIAN_SYNTHESIS_PROMPT, DEFAULT_MAX_CHUNK_LENGTH, DEFAULT_MAX_EMBED_CHARS, DEFAULT_SETUP_BUDGET_MS, EMBED_CHARS_CEILING, FormatContextOptions, FormattedMemoryDump, GraphNeighborhood, HEAL_ANCHORS_PER_CANDIDATE, HEAL_MAX_FACT_BODY_CHARS_L3, HEAL_MAX_TASKS, MemoryBundle, MemoryDump, ONTOLOGY_BACKFILL_SYSTEM_PROMPT, OntologyMode, ReadOptions, SQLiteAdapter, WikiMemory, WikiOptions, buildOntologyPromptAppendix, chunkText, configureRandomSource, createWiki, formatContext, formatGraphContext, formatMemoryDump, formatOkfBundle, hydrateLibrarianPrompt, mapLibrarianOptionsToReadOptions, parseEmbedding, parseOkfBundle, safeSlice, validateLibrarianPromptTemplate };
165
170
  export type { FormatOkfBundleOptions, LibrarianOptions, LibrarianPromptVariables, OkfFormatProfile, OkfImportOptions };
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { M as MemoryBundle, F as FormatContextOptions, G as GraphNeighborhood, a as MemoryDump, b as FormattedMemoryDump, R as ReadOptions, S as SQLiteAdapter, W as WikiOptions, c as WikiMemory } from './testing-Og5x9rFu.js';
2
- export { C as ChunkFailure, d as ClassifierAnswer, e as ClassifierQuestion, f as ClassifyRequest, g as ClassifyResponse, D as DegradedRecord, h as DraftPage, E as EmbedFactResult, i as EmbedFailureKind, j as EmbeddingMarkerKind, k as EntityMaintenanceReport, l as EntityStatus, m as ExtractedFact, n as ExtractedFactEdge, o as ExtractedFactWithOntology, p as ExtractedTask, q as ForgetParams, r as ForgetResult, s as GraphTraversalOptions, t as GroundingConfig, H as HEAL_BATCH_SIZE, u as HEAL_RECHECK_MS, v as HOOK_TIMEOUT_MARKER, w as HealResult, I as IngestDocumentResult, L as LLMProvider, x as LibrarianConfig, y as LibrarianGateConfig, z as LockedMaintenanceJob, A as MaintenanceJob, B as MaintenanceStopReason, J as MigrationPolicy, O as ONTOLOGY_BACKFILL_BATCH_SIZE, K as ONTOLOGY_BACKFILL_MAX_PROMPT_CHARS, N as ONTOLOGY_BACKFILL_RECHECK_MS, P as OntologyBackfillResult, Q as OntologyConfig, T as OntologyEdgeType, U as OntologyManifest, V as OntologyMode, X as OntologyNodeType, Y as OntologyPromptContext, Z as OntologyUpdates, _ as PendingMaintenance, $ as PendingMigrationWork, a0 as PendingSourceStatus, a1 as PromptOverrides, a2 as PromptService, a3 as PrunePartialFailureError, a4 as ReembedResult, a5 as RememberInput, a6 as RunPendingMaintenanceOptions, a7 as RunPendingMaintenanceResult, a8 as SupersedeReplacement, a9 as VectorRanker, aa as VectorRankerFallback, ab as VectorRankerRankArgs, ac as VectorRankerSemanticResult, ad as WikiBusyError, ae as WikiBusyOperation, af as WikiCheckpoint, ag as WikiConfig, ah as WikiDiagnostic, ai as WikiDiagnosticCode, aj as WikiDiagnosticDetail, ak as WikiDiagnosticOperation, al as WikiDiagnosticSeverity, am as WikiDiagnosticTrigger, an as WikiDraftNotFound, ao as WikiDuplicateHashError, ap as WikiEdge, aq as WikiEvent, ar as WikiExternalDeletionError, as as WikiFact, at as WikiGraphNodeOwnershipConflict, au as WikiIngestEmptyError, av as WikiInstructions, aw as WikiInvalidReadOptions, ax as WikiLintReport, ay as WikiMemoryTestAccess, az as WikiMigrationRequiredError, aA as WikiOutboxEvent, aB as WikiParseError, aC as WikiSearchUnavailableError, aD as WikiSourceRefHashCollision, aE as WikiStrictOntologyViolation, aF as WikiSupersedeError, aG as WikiSupersedeReason, aH as WikiTask, aI as WikiTransactionError, aJ as isWikiSearchUnavailableError, aK as validateManifest } from './testing-Og5x9rFu.js';
1
+ import { M as MemoryBundle, F as FormatContextOptions, G as GraphNeighborhood, a as MemoryDump, b as FormattedMemoryDump, O as OntologyMode, R as ReadOptions, S as SQLiteAdapter, W as WikiOptions, c as WikiMemory } from './testing-s6DBqXxQ.js';
2
+ export { C as ChunkFailure, d as ClassifierAnswer, e as ClassifierQuestion, f as ClassifyRequest, g as ClassifyResponse, D as DegradedRecord, h as DraftPage, E as EmbedFactResult, i as EmbedFailureKind, j as EmbeddingMarkerKind, k as EntityMaintenanceReport, l as EntityStatus, m as ExtractedFact, n as ExtractedFactEdge, o as ExtractedFactWithOntology, p as ExtractedTask, q as ForgetParams, r as ForgetResult, s as GraphTraversalOptions, t as GroundingConfig, H as HEAL_BATCH_SIZE, u as HEAL_RECHECK_MS, v as HOOK_TIMEOUT_MARKER, w as HealResult, I as IngestDocumentResult, L as LLMProvider, x as LibrarianConfig, y as LibrarianGateConfig, z as LockedMaintenanceJob, A as MaintenanceJob, B as MaintenanceStopReason, J as MigrationPolicy, K as ONTOLOGY_BACKFILL_BATCH_SIZE, N as ONTOLOGY_BACKFILL_MAX_PROMPT_CHARS, P as ONTOLOGY_BACKFILL_RECHECK_MS, Q as OntologyBackfillResult, T as OntologyConfig, U as OntologyEdgeType, V as OntologyManifest, X as OntologyNodeType, Y as OntologyPromptContext, Z as OntologyUpdates, _ as PendingMaintenance, $ as PendingMigrationWork, a0 as PendingSourceStatus, a1 as PromptOverrides, a2 as PromptService, a3 as PrunePartialFailureError, a4 as ReembedResult, a5 as RememberInput, a6 as RunPendingMaintenanceOptions, a7 as RunPendingMaintenanceResult, a8 as SupersedeReplacement, a9 as VectorRanker, aa as VectorRankerFallback, ab as VectorRankerRankArgs, ac as VectorRankerSemanticResult, ad as WikiBusyError, ae as WikiBusyOperation, af as WikiCheckpoint, ag as WikiConfig, ah as WikiDiagnostic, ai as WikiDiagnosticCode, aj as WikiDiagnosticDetail, ak as WikiDiagnosticOperation, al as WikiDiagnosticSeverity, am as WikiDiagnosticTrigger, an as WikiDraftNotFound, ao as WikiDuplicateHashError, ap as WikiEdge, aq as WikiEvent, ar as WikiExternalDeletionError, as as WikiFact, at as WikiGraphNodeOwnershipConflict, au as WikiIngestEmptyError, av as WikiInstructions, aw as WikiInvalidReadOptions, ax as WikiLintReport, ay as WikiMemoryTestAccess, az as WikiMigrationRequiredError, aA as WikiOutboxEvent, aB as WikiParseError, aC as WikiSearchUnavailableError, aD as WikiSourceRefHashCollision, aE as WikiStrictOntologyViolation, aF as WikiSupersedeError, aG as WikiSupersedeReason, aH as WikiTask, aI as WikiTransactionError, aJ as isWikiSearchUnavailableError, aK as validateManifest } from './testing-s6DBqXxQ.js';
3
3
  import { OkfFile } from '@equationalapplications/core-okf';
4
4
 
5
5
  /**
@@ -90,6 +90,11 @@ declare function parseOkfBundle(entityId: string, files: OkfFile[], options?: Ok
90
90
 
91
91
  declare function parseEmbedding(blob: Uint8Array | null | undefined, text: string | null | undefined): Float32Array | null;
92
92
 
93
+ declare function buildOntologyPromptAppendix(mode: OntologyMode, manifestJson: string): {
94
+ ontologyManifest: string;
95
+ ontologyModeInstructions: string;
96
+ };
97
+
93
98
  type GetRandomValues = (bytes: Uint8Array) => void;
94
99
  /**
95
100
  * Inject a platform-specific `getRandomValues` implementation.
@@ -161,5 +166,5 @@ declare const ONTOLOGY_BACKFILL_SYSTEM_PROMPT = "You are a knowledge classificat
161
166
 
162
167
  declare function createWiki(db: SQLiteAdapter, options: WikiOptions): WikiMemory;
163
168
 
164
- export { DEFAULT_CHUNK_OVERLAP, DEFAULT_LIBRARIAN_SYNTHESIS_PROMPT, DEFAULT_MAX_CHUNK_LENGTH, DEFAULT_MAX_EMBED_CHARS, DEFAULT_SETUP_BUDGET_MS, EMBED_CHARS_CEILING, FormatContextOptions, FormattedMemoryDump, GraphNeighborhood, HEAL_ANCHORS_PER_CANDIDATE, HEAL_MAX_FACT_BODY_CHARS_L3, HEAL_MAX_TASKS, MemoryBundle, MemoryDump, ONTOLOGY_BACKFILL_SYSTEM_PROMPT, ReadOptions, SQLiteAdapter, WikiMemory, WikiOptions, chunkText, configureRandomSource, createWiki, formatContext, formatGraphContext, formatMemoryDump, formatOkfBundle, hydrateLibrarianPrompt, mapLibrarianOptionsToReadOptions, parseEmbedding, parseOkfBundle, safeSlice, validateLibrarianPromptTemplate };
169
+ export { DEFAULT_CHUNK_OVERLAP, DEFAULT_LIBRARIAN_SYNTHESIS_PROMPT, DEFAULT_MAX_CHUNK_LENGTH, DEFAULT_MAX_EMBED_CHARS, DEFAULT_SETUP_BUDGET_MS, EMBED_CHARS_CEILING, FormatContextOptions, FormattedMemoryDump, GraphNeighborhood, HEAL_ANCHORS_PER_CANDIDATE, HEAL_MAX_FACT_BODY_CHARS_L3, HEAL_MAX_TASKS, MemoryBundle, MemoryDump, ONTOLOGY_BACKFILL_SYSTEM_PROMPT, OntologyMode, ReadOptions, SQLiteAdapter, WikiMemory, WikiOptions, buildOntologyPromptAppendix, chunkText, configureRandomSource, createWiki, formatContext, formatGraphContext, formatMemoryDump, formatOkfBundle, hydrateLibrarianPrompt, mapLibrarianOptionsToReadOptions, parseEmbedding, parseOkfBundle, safeSlice, validateLibrarianPromptTemplate };
165
170
  export type { FormatOkfBundleOptions, LibrarianOptions, LibrarianPromptVariables, OkfFormatProfile, OkfImportOptions };
package/dist/index.js CHANGED
@@ -40,7 +40,9 @@ var SEVERITY = {
40
40
  event_created_at_clamped: "warn",
41
41
  event_created_at_restamped: "info",
42
42
  external_deletion_pending: "warn",
43
- external_deletion_discarded: "warn"
43
+ external_deletion_discarded: "warn",
44
+ guidance_too_long: "warn",
45
+ guidance_resolver_failed: "warn"
44
46
  };
45
47
  var MESSAGE = {
46
48
  ingest_chunk_failed: "One or more document chunks failed to parse or generate.",
@@ -66,7 +68,9 @@ var MESSAGE = {
66
68
  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.",
67
69
  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.",
68
70
  external_deletion_pending: "Removals owed to the external vector index are still pending.",
69
- external_deletion_discarded: "Pending external vector removals were discarded because forceDeleteIgnoreRankerHook is set."
71
+ external_deletion_discarded: "Pending external vector removals were discarded because forceDeleteIgnoreRankerHook is set.",
72
+ guidance_too_long: "The configured guidance exceeded the length cap and was not sent for this pass.",
73
+ guidance_resolver_failed: "The per-entity guidance resolver failed; its value was not used for this pass."
70
74
  };
71
75
  var warnedNonFunction = /* @__PURE__ */ new WeakSet();
72
76
  function copyDetail(detail) {
@@ -6211,6 +6215,14 @@ function groundingOutcome(verdict, now) {
6211
6215
  }
6212
6216
 
6213
6217
  // src/prompts.ts
6218
+ var LEAVE_OUT_RULE_SENTENCE = "Memory leaves out what a better record already holds, and points to that record.";
6219
+ var GUIDANCE_MAX_CHARS = 2e3;
6220
+ function guidanceSection(guidance) {
6221
+ return `--- Host guidance ---
6222
+ ${guidance}
6223
+ --- End host guidance ---
6224
+ ${LEAVE_OUT_RULE_SENTENCE}`;
6225
+ }
6214
6226
  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.
6215
6227
  Return ONLY a valid JSON object matching this schema:
6216
6228
  {
@@ -6280,6 +6292,64 @@ var PromptService = class {
6280
6292
  this.globalOverrides = globalOverrides;
6281
6293
  this.grounding = grounding;
6282
6294
  }
6295
+ /**
6296
+ * Specs/librarian-guidance: resolve the effective guidance for one pass
6297
+ * or call — default `config.prompts.guidance`, per-entity
6298
+ * `config.librarian.guidanceForEntity` winning when it returns a
6299
+ * non-empty (trimmed) string. Synchronous: a resolver that throws,
6300
+ * returns a thenable (its rejection is swallowed with a no-op handler;
6301
+ * a throwing `then` counts too), or returns any non-string value is
6302
+ * treated as "no value" and reported in `diagnostic`. Over-cap text
6303
+ * (UTF-16 units, verbatim) is not sent and reported in `diagnostic`.
6304
+ * Emits nothing itself; the caller emits, immediately at resolution.
6305
+ */
6306
+ static resolveGuidance(config, entityId) {
6307
+ let source = null;
6308
+ let effective;
6309
+ let resolverDiagnostic;
6310
+ const defaultValue = config?.prompts?.guidance;
6311
+ const resolver = config?.librarian?.guidanceForEntity;
6312
+ let entityValue;
6313
+ if (resolver) {
6314
+ try {
6315
+ entityValue = resolver(entityId);
6316
+ if (entityValue === void 0) {
6317
+ } else if (typeof entityValue === "string") {
6318
+ if (entityValue.trim() !== "") {
6319
+ source = "per_entity";
6320
+ effective = entityValue;
6321
+ }
6322
+ } else {
6323
+ try {
6324
+ entityValue?.then?.(() => void 0, () => void 0);
6325
+ } catch {
6326
+ }
6327
+ resolverDiagnostic = {
6328
+ code: "guidance_resolver_failed",
6329
+ detail: { reason: "non_string" }
6330
+ };
6331
+ }
6332
+ } catch {
6333
+ resolverDiagnostic = { code: "guidance_resolver_failed", detail: { reason: "threw" } };
6334
+ }
6335
+ }
6336
+ if (source === null && defaultValue !== void 0 && defaultValue.trim() !== "") {
6337
+ source = "default";
6338
+ effective = defaultValue;
6339
+ }
6340
+ if (source === null || effective === void 0) {
6341
+ return resolverDiagnostic ? { diagnostic: resolverDiagnostic } : {};
6342
+ }
6343
+ if (effective.length > GUIDANCE_MAX_CHARS) {
6344
+ return {
6345
+ diagnostic: {
6346
+ code: "guidance_too_long",
6347
+ detail: { guidanceLength: effective.length, guidanceSource: source }
6348
+ }
6349
+ };
6350
+ }
6351
+ return resolverDiagnostic ? { guidance: effective, diagnostic: resolverDiagnostic } : { guidance: effective };
6352
+ }
6283
6353
  /** The resolved grounding config when `writer` is in `grounding.writers`; otherwise null (spec §6.2). */
6284
6354
  groundingFor(writer) {
6285
6355
  return this.grounding?.writers.has(writer) ? this.grounding : null;
@@ -6290,6 +6360,19 @@ var PromptService = class {
6290
6360
  return cfg ? `${systemPrompt}
6291
6361
 
6292
6362
  ${groundingEvidenceBlock(writer, cfg)}` : systemPrompt;
6363
+ }
6364
+ /**
6365
+ * Specs/librarian-guidance: append the marked guidance section (with the
6366
+ * general leave-out rule) to the ALREADY-HYDRATED system prompt — after
6367
+ * ontology, immediately before grounding. The guidance text is never
6368
+ * run through hydration, so `{{…}}` inside it cannot change a builder's
6369
+ * template branch or be expanded with data. No-op on empty input.
6370
+ */
6371
+ appendGuidance(systemPrompt, guidance) {
6372
+ if (!guidance) return systemPrompt;
6373
+ return `${systemPrompt}
6374
+
6375
+ ${guidanceSection(guidance)}`;
6293
6376
  }
6294
6377
  hydrate(template, variables) {
6295
6378
  return template.replace(/\{\{\s*(\w+)\s*\}\}/g, (_match, key) => {
@@ -6326,31 +6409,31 @@ ${groundingEvidenceBlock(writer, cfg)}` : systemPrompt;
6326
6409
 
6327
6410
  ${ctx.ontologyModeInstructions}`;
6328
6411
  }
6329
- buildIngestPrompt(documentChunk, runtimeOverride, ontologyContext) {
6412
+ buildIngestPrompt(documentChunk, runtimeOverride, ontologyContext, guidance) {
6330
6413
  const template = runtimeOverride ?? this.globalOverrides?.ingestSystemPrompt ?? INGEST_SYSTEM_PROMPT;
6331
6414
  const hasDocumentChunk = /\{\{\s*documentChunk\s*\}\}/.test(template);
6332
6415
  if (hasDocumentChunk || this.hasOntologyPlaceholders(template)) {
6333
6416
  return {
6334
- systemPrompt: this.appendGrounding(this.buildSystemPrompt(template, { documentChunk }, ontologyContext), "ingest"),
6417
+ systemPrompt: this.appendGrounding(this.appendGuidance(this.buildSystemPrompt(template, { documentChunk }, ontologyContext), guidance), "ingest"),
6335
6418
  userPrompt: hasDocumentChunk ? "Please extract the facts." : `Document Chunk:
6336
6419
  ${documentChunk}`
6337
6420
  };
6338
6421
  }
6339
6422
  return {
6340
- systemPrompt: this.appendGrounding(this.appendOntology(template, ontologyContext), "ingest"),
6423
+ systemPrompt: this.appendGrounding(this.appendGuidance(this.appendOntology(template, ontologyContext), guidance), "ingest"),
6341
6424
  userPrompt: `Document Chunk:
6342
6425
  ${documentChunk}`
6343
6426
  };
6344
6427
  }
6345
- buildLibrarianPrompt(events, currentFacts, runtimeOverride, ontologyContext) {
6346
- const template = runtimeOverride ?? this.globalOverrides?.librarianSystemPrompt ?? LIBRARIAN_SYSTEM_PROMPT;
6428
+ buildLibrarianPrompt(events, currentFacts, runtimeOverride, ontologyContext, guidance) {
6429
+ const template = runtimeOverride ?? LIBRARIAN_SYSTEM_PROMPT;
6347
6430
  const hasEvents = /\{\{\s*events\s*\}\}/.test(template);
6348
6431
  const hasCurrentFacts = /\{\{\s*currentFacts\s*\}\}/.test(template);
6349
6432
  const eventsShown = hasEvents || !hasCurrentFacts;
6350
6433
  const corpusField = this.groundingFor("librarian") ? { groundingCorpus: buildGroundingCorpus(eventsShown ? events.map(summaryOf) : []) } : {};
6351
6434
  if (hasEvents || hasCurrentFacts || this.hasOntologyPlaceholders(template)) {
6352
6435
  return {
6353
- systemPrompt: this.appendGrounding(this.buildSystemPrompt(template, { events, currentFacts }, ontologyContext), "librarian"),
6436
+ systemPrompt: this.appendGrounding(this.appendGuidance(this.buildSystemPrompt(template, { events, currentFacts }, ontologyContext), guidance), "librarian"),
6354
6437
  userPrompt: hasEvents || hasCurrentFacts ? "Please synthesize the context." : `Events:
6355
6438
  ${JSON.stringify(events, null, 2)}
6356
6439
 
@@ -6360,7 +6443,7 @@ ${JSON.stringify(currentFacts, null, 2)}`,
6360
6443
  };
6361
6444
  }
6362
6445
  return {
6363
- systemPrompt: this.appendGrounding(this.appendOntology(template, ontologyContext), "librarian"),
6446
+ systemPrompt: this.appendGrounding(this.appendGuidance(this.appendOntology(template, ontologyContext), guidance), "librarian"),
6364
6447
  userPrompt: `Events:
6365
6448
  ${JSON.stringify(events, null, 2)}
6366
6449
 
@@ -6463,11 +6546,11 @@ ${JSON.stringify(facts, null, 2)}`
6463
6546
  };
6464
6547
  }
6465
6548
  /** Ops extract (spec §5.2): events only — no existing facts. */
6466
- buildOpsExtractPrompt(events, ontologyContext) {
6549
+ buildOpsExtractPrompt(events, ontologyContext, guidance) {
6467
6550
  const lines = events.map((l) => `${l.label} [${new Date(l.at).toISOString()}] (${l.event.event_type}) ${l.event.summary}`);
6468
6551
  const grounding = this.groundingFor("librarian");
6469
6552
  return {
6470
- systemPrompt: this.appendGrounding(this.appendOntology(OPS_EXTRACT_SYSTEM_PROMPT, ontologyContext), "librarian"),
6553
+ systemPrompt: this.appendGrounding(this.appendGuidance(this.appendOntology(OPS_EXTRACT_SYSTEM_PROMPT, ontologyContext), guidance), "librarian"),
6471
6554
  userPrompt: `Events:
6472
6555
  ${lines.join("\n")}`,
6473
6556
  ...grounding ? { groundingCorpus: buildGroundingCorpus(events.map((l) => l.event.summary)) } : {}
@@ -6484,11 +6567,11 @@ ${JSON.stringify({ items })}` };
6484
6567
  * placeholders and leaves data placeholders verbatim; heal never receives
6485
6568
  * ontology context, matching `buildHealPrompt`.
6486
6569
  */
6487
- buildInstructionTemplates(ontologyContext, librarianStrategy) {
6570
+ buildInstructionTemplates(ontologyContext, librarianStrategy, guidance) {
6488
6571
  const o = this.globalOverrides;
6489
6572
  return {
6490
- ingest: this.appendGrounding(this.buildSystemPrompt(o?.ingestSystemPrompt ?? INGEST_SYSTEM_PROMPT, {}, ontologyContext), "ingest"),
6491
- librarian: librarianStrategy === "ops" ? this.appendGrounding(this.appendOntology(OPS_EXTRACT_SYSTEM_PROMPT, ontologyContext), "librarian") : this.appendGrounding(this.buildSystemPrompt(o?.librarianSystemPrompt ?? LIBRARIAN_SYSTEM_PROMPT, {}, ontologyContext), "librarian"),
6573
+ ingest: this.appendGrounding(this.appendGuidance(this.buildSystemPrompt(o?.ingestSystemPrompt ?? INGEST_SYSTEM_PROMPT, {}, ontologyContext), guidance), "ingest"),
6574
+ 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"),
6492
6575
  heal: this.appendGrounding(o?.healSystemPrompt ?? HEAL_SYSTEM_PROMPT, "heal"),
6493
6576
  ontologyBackfill: this.buildSystemPrompt(o?.ontologyBackfillSystemPrompt ?? ONTOLOGY_BACKFILL_SYSTEM_PROMPT, {}, ontologyContext)
6494
6577
  };
@@ -6683,13 +6766,24 @@ var IngestionService = class {
6683
6766
  const { chunks: chunks2, truncated } = chunkText(params.documentChunk, maxChunkLength, chunkOverlap);
6684
6767
  if (chunks2.length === 0) return zeroChunkResult();
6685
6768
  const ontologyContext = await this.ontologyService?.buildPromptContext(entityId) ?? null;
6769
+ const { guidance, diagnostic } = PromptService.resolveGuidance(this.options.config, entityId);
6770
+ if (diagnostic) {
6771
+ emitDiagnostic(this.options, {
6772
+ code: diagnostic.code,
6773
+ operation: "ingest",
6774
+ trigger: "call",
6775
+ entityId,
6776
+ detail: diagnostic.detail
6777
+ });
6778
+ }
6686
6779
  const ingestGrounding = this.promptService.groundingFor("ingest");
6687
6780
  const chunkResults = await withConcurrency(
6688
6781
  chunks2.map((chunk, chunkIndex) => async () => {
6689
6782
  const { systemPrompt, userPrompt } = this.promptService.buildIngestPrompt(
6690
6783
  chunk,
6691
6784
  params.promptOverride,
6692
- ontologyContext
6785
+ ontologyContext,
6786
+ guidance
6693
6787
  );
6694
6788
  try {
6695
6789
  const responseText = await callLlm(this.options, { operation: "ingest", entityId, trigger: "call" }, { systemPrompt, userPrompt });
@@ -7328,9 +7422,9 @@ function changedDefaultWarnings(config) {
7328
7422
  "[core-llm-wiki] auto-run thresholds are set, but `maintenance` now defaults to 'deferred', so write() will not start the librarian or heal. Set `maintenance: 'auto'` or call runPendingMaintenance()."
7329
7423
  );
7330
7424
  }
7331
- if (config?.prompts?.librarianSystemPrompt !== void 0 && config?.librarian?.strategy === void 0) {
7425
+ if (config?.prompts?.librarianSystemPrompt !== void 0) {
7332
7426
  warnings.push(
7333
- "[core-llm-wiki] `prompts.librarianSystemPrompt` is set, but `librarian.strategy` now defaults to 'ops', which does not use it. Set `librarian: { strategy: 'legacy' }` to keep the override."
7427
+ "[core-llm-wiki] `prompts.librarianSystemPrompt` was removed in 9.0.0 and its value is ignored. Move the domain part of it to `prompts.guidance`, which works under both librarian strategies."
7334
7428
  );
7335
7429
  }
7336
7430
  if (config?.librarian?.strategy === "legacy" && config?.maintenance === void 0 && !hasThreshold) {
@@ -8065,7 +8159,8 @@ var runLegacyLibrarianPass = async (deps, ctx) => {
8065
8159
  promptEvents,
8066
8160
  currentFacts,
8067
8161
  promptOverride,
8068
- ontologyContext
8162
+ ontologyContext,
8163
+ ctx.guidance
8069
8164
  );
8070
8165
  let responseText;
8071
8166
  try {
@@ -8237,7 +8332,7 @@ var OPS_MAX_EVENTS_PER_PASS = 50;
8237
8332
  var OPS_MAX_EXTRACT_CHARS = 24e3;
8238
8333
  var RESOLVE_RESERVE_FACTOR = 2;
8239
8334
  var estimatePrompt = (p) => estimateTokens(p.systemPrompt) + estimateTokens(p.userPrompt);
8240
- async function selectBatch(deps, entityId, wm, meter) {
8335
+ async function selectBatch(deps, entityId, wm, meter, guidance) {
8241
8336
  const events = await deps.eventRepo.getAfter(entityId, wm, OPS_MAX_EVENTS_PER_PASS);
8242
8337
  if (events.length === 0) return { batch: [] };
8243
8338
  let n = 0;
@@ -8251,7 +8346,7 @@ async function selectBatch(deps, entityId, wm, meter) {
8251
8346
  if (meter && meter.budget !== void 0) {
8252
8347
  const ontologyContext = await deps.ontologyService?.buildPromptContext(entityId) ?? null;
8253
8348
  for (; ; ) {
8254
- const need = RESOLVE_RESERVE_FACTOR * estimatePrompt(deps.promptService.buildOpsExtractPrompt(batch, ontologyContext));
8349
+ const need = RESOLVE_RESERVE_FACTOR * estimatePrompt(deps.promptService.buildOpsExtractPrompt(batch, ontologyContext, guidance));
8255
8350
  if (meter.fits(need)) break;
8256
8351
  if (batch.length === 1) return { budgetStop: { requiredEstimate: need } };
8257
8352
  batch = labelEvents(events.slice(0, Math.max(1, Math.floor(batch.length / 2))));
@@ -8262,7 +8357,7 @@ async function selectBatch(deps, entityId, wm, meter) {
8262
8357
  async function runExtract(deps, ctx, batch) {
8263
8358
  const { entityId, trigger } = ctx;
8264
8359
  const ontologyContext = await deps.ontologyService?.buildPromptContext(entityId) ?? null;
8265
- const prompt = deps.promptService.buildOpsExtractPrompt(batch, ontologyContext);
8360
+ const prompt = deps.promptService.buildOpsExtractPrompt(batch, ontologyContext, ctx.guidance);
8266
8361
  const text = await callLlm(deps.options, { operation: "librarian", entityId, trigger, meter: ctx.meter }, prompt);
8267
8362
  const parsed = parseJsonResponse(text);
8268
8363
  const base = { entityId, operation: "librarian", trigger };
@@ -8720,7 +8815,7 @@ var runOpsLibrarianPass = async (deps, ctx) => {
8720
8815
  const cfg = resolveGateConfig(deps.options.config?.librarian?.gate);
8721
8816
  await deps.seedWatermark(entityId);
8722
8817
  const wm = await deps.getWatermark(entityId);
8723
- const sel = await selectBatch(deps, entityId, wm, ctx.meter);
8818
+ const sel = await selectBatch(deps, entityId, wm, ctx.meter, ctx.guidance);
8724
8819
  if ("budgetStop" in sel) return { processedThrough: null, factsWritten: 0, budgetStop: sel.budgetStop };
8725
8820
  if (sel.batch.length === 0) return { processedThrough: null, factsWritten: 0 };
8726
8821
  if (!deps.searchService.isKeywordAvailable() && await gateNeedsKeyword(deps, entityId)) {
@@ -9358,7 +9453,17 @@ var MaintenanceService = class {
9358
9453
  * A budget-stopped pass wrote nothing and must not move the watermark.
9359
9454
  */
9360
9455
  async runLibrarianPass(ctx) {
9361
- const result = await runLibrarianStrategy(this.librarianDeps(), ctx);
9456
+ const { guidance, diagnostic } = PromptService.resolveGuidance(this.options.config, ctx.entityId);
9457
+ if (diagnostic) {
9458
+ emitDiagnostic(this.options, {
9459
+ code: diagnostic.code,
9460
+ operation: "librarian",
9461
+ trigger: ctx.trigger,
9462
+ entityId: ctx.entityId,
9463
+ detail: diagnostic.detail
9464
+ });
9465
+ }
9466
+ const result = await runLibrarianStrategy(this.librarianDeps(), { ...ctx, guidance });
9362
9467
  if (result.processedThrough && !result.budgetStop) {
9363
9468
  await this.advanceLibrarianWatermark(ctx.entityId, result.processedThrough);
9364
9469
  }
@@ -13287,7 +13392,17 @@ var WikiMemory = class {
13287
13392
  async getInstructions(entityId) {
13288
13393
  assertEntityId2(entityId);
13289
13394
  const ontologyContext = await this.ontologyService.buildPromptContext(entityId);
13290
- return this.promptService.buildInstructionTemplates(ontologyContext, resolveLibrarianStrategy(this.options.config));
13395
+ const { guidance, diagnostic } = PromptService.resolveGuidance(this.options.config, entityId);
13396
+ if (diagnostic) {
13397
+ emitDiagnostic(this.options, {
13398
+ code: diagnostic.code,
13399
+ operation: "read",
13400
+ trigger: "call",
13401
+ entityId,
13402
+ detail: diagnostic.detail
13403
+ });
13404
+ }
13405
+ return this.promptService.buildInstructionTemplates(ontologyContext, resolveLibrarianStrategy(this.options.config), guidance);
13291
13406
  }
13292
13407
  /**
13293
13408
  * Returns the live source_refs for an entity, one row per ref, with the most
@@ -13401,7 +13516,7 @@ var WikiMemory = class {
13401
13516
  /**
13402
13517
  * @param options.promptOverride - Applies only to this manual call. Does NOT affect
13403
13518
  * WriteService-triggered auto-runs. For persistent prompt customization across auto-runs,
13404
- * set `options.config.prompts.librarianSystemPrompt` at WikiMemory construction time.
13519
+ * set `options.config.prompts.guidance` at WikiMemory construction time.
13405
13520
  */
13406
13521
  async runLibrarian(entityId, options) {
13407
13522
  return this.maintenanceService.runLibrarian(entityId, options);
@@ -14890,6 +15005,7 @@ exports.WikiSourceRefHashCollision = WikiSourceRefHashCollision;
14890
15005
  exports.WikiStrictOntologyViolation = WikiStrictOntologyViolation;
14891
15006
  exports.WikiSupersedeError = WikiSupersedeError;
14892
15007
  exports.WikiTransactionError = WikiTransactionError;
15008
+ exports.buildOntologyPromptAppendix = buildOntologyPromptAppendix;
14893
15009
  exports.chunkText = chunkText;
14894
15010
  exports.configureRandomSource = configureRandomSource;
14895
15011
  exports.createWiki = createWiki;