@equationalapplications/core-llm-wiki 9.9.0 → 9.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.mts CHANGED
@@ -1,5 +1,5 @@
1
- import { M as MemoryBundle, F as FormatContextOptions, G as GraphNeighborhood, a as MemoryDump, b as FormattedMemoryDump, O as OntologyMode, W as WikiConfig, R as ReadOptions, c as OntologyConfig, S as SQLiteAdapter, d as WikiOptions, e as WikiMemory } from './testing-CDSfjx8j.mjs';
2
- export { C as CLASSIFIER_MAX_CHOICES, f as CheckpointIncompleteError, g as ChunkFailure, h as ClassifierAnswer, i as ClassifierQuestion, j as ClassifyRequest, k as ClassifyResponse, D as DegradedRecord, l as DraftPage, E as EmbedFactResult, m as EmbedFailureKind, n as EmbeddingMarkerKind, o as EntityMaintenanceReport, p as EntityStatus, q as EraseReport, r as EraseStepError, s as ExtractedFact, t as ExtractedFactEdge, u as ExtractedFactWithOntology, v as ExtractedTask, w as ForgetParams, x as ForgetResult, y as GraphTraversalOptions, z as GroundingConfig, H as HEAL_BATCH_SIZE, A as HEAL_RECHECK_MS, B as HOOK_TIMEOUT_MARKER, I as HealResult, J as ImportDumpResult, K as IngestDocumentResult, L as LLMProvider, N as LibrarianConfig, P as LibrarianGateConfig, Q as LockedMaintenanceJob, T as MaintenanceJob, U as MaintenanceStopReason, V as MemoryDumpEntity, X as MigrationPolicy, Y as ONTOLOGY_ABSTAIN_SENTINEL, Z as ONTOLOGY_BACKFILL_BATCH_SIZE, _ as ONTOLOGY_BACKFILL_MAX_PROMPT_CHARS, $ as ONTOLOGY_BACKFILL_RECHECK_MS, a0 as OntologyBackfillResult, a1 as OntologyEdgeType, a2 as OntologyManifest, a3 as OntologyNodeType, a4 as OntologyPromptContext, a5 as OntologyUpdates, a6 as PendingMaintenance, a7 as PendingMigrationWork, a8 as PendingSourceStatus, a9 as PromptOverrides, aa as PromptService, ab as PrunePartialFailureError, ac as ReembedResult, ad as RememberInput, ae as RunPendingMaintenanceOptions, af as RunPendingMaintenanceResult, ag as SourcePassage, ah as StoreSourceResult, ai as StoredSource, aj as StoredSourceDump, ak as StoredSourceSummary, al as SupersedeReplacement, am as SystemOneConfig, an as SystemOneThresholdSite, ao as VectorRanker, ap as VectorRankerFallback, aq as VectorRankerRankArgs, ar as VectorRankerSemanticResult, as as WikiBusyError, at as WikiBusyOperation, au as WikiCheckpoint, av as WikiDiagnostic, aw as WikiDiagnosticCode, ax as WikiDiagnosticDetail, ay as WikiDiagnosticOperation, az as WikiDiagnosticSeverity, aA as WikiDiagnosticTrigger, aB as WikiDraftNotFound, aC as WikiDuplicateHashError, aD as WikiEdge, aE as WikiEvent, aF as WikiExternalDeletionError, aG as WikiFact, aH as WikiGraphNodeOwnershipConflict, aI as WikiIngestEmptyError, aJ as WikiInstructions, aK as WikiInvalidReadOptions, aL as WikiLintReport, aM as WikiMemoryTestAccess, aN as WikiMigrationRequiredError, aO as WikiOutboxEvent, aP as WikiParseError, aQ as WikiSearchUnavailableError, aR as WikiSourcePointer, aS as WikiSourceRefHashCollision, aT as WikiStrictOntologyViolation, aU as WikiSupersedeError, aV as WikiSupersedeReason, aW as WikiTask, aX as WikiTransactionError, aY as isReservedAbstainSlug, aZ as isWikiSearchUnavailableError, a_ as validateManifest } from './testing-CDSfjx8j.mjs';
1
+ import { M as MemoryBundle, F as FormatContextOptions, G as GraphNeighborhood, a as MemoryDump, b as FormattedMemoryDump, O as OntologyMode, W as WikiConfig, R as ReadOptions, c as OntologyConfig, S as SQLiteAdapter, d as WikiOptions, e as WikiMemory } from './testing-DFyghdSG.mjs';
2
+ export { C as CLASSIFIER_MAX_CHOICES, f as CheckpointIncompleteError, g as ChunkFailure, h as ClassifierAnswer, i as ClassifierQuestion, j as ClassifyRequest, k as ClassifyResponse, D as DegradedRecord, l as DraftPage, E as EmbedFactResult, m as EmbedFailureKind, n as EmbeddingMarkerKind, o as EntityMaintenanceReport, p as EntityStatus, q as EraseReport, r as EraseStepError, s as ExtractedFact, t as ExtractedFactEdge, u as ExtractedFactWithOntology, v as ExtractedTask, w as ForgetParams, x as ForgetResult, y as GraphTraversalOptions, z as GroundingConfig, H as HEAL_BATCH_SIZE, A as HEAL_RECHECK_MS, B as HOOK_TIMEOUT_MARKER, I as HealResult, J as ImportDumpResult, K as IngestDocumentResult, L as LLMProvider, N as LibrarianConfig, P as LibrarianGateConfig, Q as LockedMaintenanceJob, T as MaintenanceJob, U as MaintenanceStopReason, V as MemoryDumpEntity, X as MigrationPolicy, Y as ONTOLOGY_ABSTAIN_SENTINEL, Z as ONTOLOGY_BACKFILL_BATCH_SIZE, _ as ONTOLOGY_BACKFILL_RECHECK_MS, $ as OntologyBackfillResult, a0 as OntologyEdgeType, a1 as OntologyManifest, a2 as OntologyNodeType, a3 as OntologyPromptContext, a4 as OntologyUpdates, a5 as PendingMaintenance, a6 as PendingMigrationWork, a7 as PendingSourceStatus, a8 as PromptOverrides, a9 as PromptService, aa as PrunePartialFailureError, ab as ReembedResult, ac as RememberInput, ad as RunPendingMaintenanceOptions, ae as RunPendingMaintenanceResult, af as SourcePassage, ag as StoreSourceResult, ah as StoredSource, ai as StoredSourceDump, aj as StoredSourceSummary, ak as SupersedeReplacement, al as SystemOneConfig, am as SystemOneThresholdSite, an as VectorRanker, ao as VectorRankerFallback, ap as VectorRankerRankArgs, aq as VectorRankerSemanticResult, ar as WikiBusyError, as as WikiBusyOperation, at as WikiCheckpoint, au as WikiDiagnostic, av as WikiDiagnosticCode, aw as WikiDiagnosticDetail, ax as WikiDiagnosticOperation, ay as WikiDiagnosticSeverity, az as WikiDiagnosticTrigger, aA as WikiDraftNotFound, aB as WikiDuplicateHashError, aC as WikiEdge, aD as WikiEvent, aE as WikiExternalDeletionError, aF as WikiFact, aG as WikiGraphNodeOwnershipConflict, aH as WikiIngestEmptyError, aI as WikiInstructions, aJ as WikiInvalidReadOptions, aK as WikiLintReport, aL as WikiMemoryTestAccess, aM as WikiMigrationRequiredError, aN as WikiOutboxEvent, aO as WikiParseError, aP as WikiSearchUnavailableError, aQ as WikiSourcePointer, aR as WikiSourceRefHashCollision, aS as WikiStrictOntologyViolation, aT as WikiSupersedeError, aU as WikiSupersedeReason, aV as WikiTask, aW as WikiTransactionError, aX as isReservedAbstainSlug, aY as isWikiSearchUnavailableError, aZ as validateManifest } from './testing-DFyghdSG.mjs';
3
3
  import { OkfFile } from '@equationalapplications/core-okf';
4
4
 
5
5
  /**
@@ -47,21 +47,6 @@ declare function chunkText(input: string, maxChunkLength: number, overlap: numbe
47
47
  truncated: boolean;
48
48
  };
49
49
 
50
- /** Per-candidate anchor ratio used at L0: `min(HEAL_MAX_ANCHORS, batch.length * HEAL_ANCHORS_PER_CANDIDATE)`. */
51
- declare const HEAL_ANCHORS_PER_CANDIDATE = 4;
52
- /**
53
- * Default body truncation cap applied at L3 only. A fact whose body is at or
54
- * below this cap passes through unchanged; a fact above it is sliced to this
55
- * length with a `...[truncated at N chars, original was M]` marker.
56
- */
57
- declare const HEAL_MAX_FACT_BODY_CHARS_L3 = 4000;
58
- /**
59
- * Hard ceiling on the `allTasks` slice fed to the heal prompt at L0. Tasks
60
- * are entity-global (not batch-local), so this is a constant rather than a
61
- * function of batch length.
62
- */
63
- declare const HEAL_MAX_TASKS = 50;
64
-
65
50
  /**
66
51
  * Default maximum characters per chunk that `ingestDocument` uses when a
67
52
  * caller doesn't override `maxChunkLength` (directly or via
@@ -78,6 +63,24 @@ declare const DEFAULT_MAX_CHUNK_LENGTH = 12000;
78
63
  */
79
64
  declare const DEFAULT_CHUNK_OVERLAP = 400;
80
65
 
66
+ /** Input bound for the ontology-backfill generative prompt (was `MaintenanceService.ts`). */
67
+ declare const ONTOLOGY_BACKFILL_MAX_PROMPT_CHARS = 40000;
68
+
69
+ /** Per-candidate anchor ratio used at L0: `min(HEAL_MAX_ANCHORS, batch.length * HEAL_ANCHORS_PER_CANDIDATE)`. */
70
+ declare const HEAL_ANCHORS_PER_CANDIDATE = 4;
71
+ /**
72
+ * Default body truncation cap applied at L3 only. A fact whose body is at or
73
+ * below this cap passes through unchanged; a fact above it is sliced to this
74
+ * length with a `...[truncated at N chars, original was M]` marker.
75
+ */
76
+ declare const HEAL_MAX_FACT_BODY_CHARS_L3 = 4000;
77
+ /**
78
+ * Hard ceiling on the `allTasks` slice fed to the heal prompt at L0. Tasks
79
+ * are entity-global (not batch-local), so this is a constant rather than a
80
+ * function of batch length.
81
+ */
82
+ declare const HEAL_MAX_TASKS = 50;
83
+
81
84
  declare function formatContext(bundle: MemoryBundle, options?: FormatContextOptions): string;
82
85
 
83
86
  /**
@@ -148,7 +151,7 @@ interface ContextBudget {
148
151
  }
149
152
  declare function estimateTokensWith(budget: ContextBudget, text: string): number;
150
153
 
151
- type ContextBudgetOp = 'resolve' | 'heal' | 'extract';
154
+ type ContextBudgetOp = 'resolve' | 'heal' | 'extract' | 'backfill';
152
155
  declare function resolveContextBudget(config: WikiConfig | undefined): ContextBudget;
153
156
  declare function resolveMaxPromptChars(budget: ContextBudget, op: ContextBudgetOp): number;
154
157
  /** The ingest chunk default stays 12000 in both modes (ruling R2). */
@@ -245,5 +248,5 @@ declare const ONTOLOGY_BACKFILL_SYSTEM_PROMPT = "You are a knowledge classificat
245
248
 
246
249
  declare function createWiki(db: SQLiteAdapter, options: WikiOptions): WikiMemory;
247
250
 
248
- export { DEFAULT_CHUNK_OVERLAP, DEFAULT_LIBRARIAN_SYNTHESIS_PROMPT, DEFAULT_MAX_CHUNK_LENGTH, DEFAULT_MAX_EMBED_CHARS, DEFAULT_ONTOLOGY_JOB_BATCH_SIZE, DEFAULT_SETUP_BUDGET_MS, DEFAULT_TYPING_MIN_CONFIDENCE, 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, OntologyConfig, OntologyMode, ReadOptions, SQLiteAdapter, WikiConfig, WikiMemory, WikiOptions, buildOntologyPromptAppendix, chunkText, configureRandomSource, createWiki, estimateTokensWith, formatContext, formatGraphContext, formatMemoryDump, formatOkfBundle, hydrateLibrarianPrompt, mapLibrarianOptionsToReadOptions, parseEmbedding, parseOkfBundle, resolveContextBudget, resolveDefaultChunkLength, resolveMaxPromptChars, resolveOntologyJobDefaults, resolveSystemOneTyping, resolveTypingMinConfidence, safeSlice, validUsage, validateLibrarianPromptTemplate, warnOnce };
251
+ export { DEFAULT_CHUNK_OVERLAP, DEFAULT_LIBRARIAN_SYNTHESIS_PROMPT, DEFAULT_MAX_CHUNK_LENGTH, DEFAULT_MAX_EMBED_CHARS, DEFAULT_ONTOLOGY_JOB_BATCH_SIZE, DEFAULT_SETUP_BUDGET_MS, DEFAULT_TYPING_MIN_CONFIDENCE, EMBED_CHARS_CEILING, FormatContextOptions, FormattedMemoryDump, GraphNeighborhood, HEAL_ANCHORS_PER_CANDIDATE, HEAL_MAX_FACT_BODY_CHARS_L3, HEAL_MAX_TASKS, MemoryBundle, MemoryDump, ONTOLOGY_BACKFILL_MAX_PROMPT_CHARS, ONTOLOGY_BACKFILL_SYSTEM_PROMPT, OntologyConfig, OntologyMode, ReadOptions, SQLiteAdapter, WikiConfig, WikiMemory, WikiOptions, buildOntologyPromptAppendix, chunkText, configureRandomSource, createWiki, estimateTokensWith, formatContext, formatGraphContext, formatMemoryDump, formatOkfBundle, hydrateLibrarianPrompt, mapLibrarianOptionsToReadOptions, parseEmbedding, parseOkfBundle, resolveContextBudget, resolveDefaultChunkLength, resolveMaxPromptChars, resolveOntologyJobDefaults, resolveSystemOneTyping, resolveTypingMinConfidence, safeSlice, validUsage, validateLibrarianPromptTemplate, warnOnce };
249
252
  export type { ContextBudget, 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, O as OntologyMode, W as WikiConfig, R as ReadOptions, c as OntologyConfig, S as SQLiteAdapter, d as WikiOptions, e as WikiMemory } from './testing-CDSfjx8j.js';
2
- export { C as CLASSIFIER_MAX_CHOICES, f as CheckpointIncompleteError, g as ChunkFailure, h as ClassifierAnswer, i as ClassifierQuestion, j as ClassifyRequest, k as ClassifyResponse, D as DegradedRecord, l as DraftPage, E as EmbedFactResult, m as EmbedFailureKind, n as EmbeddingMarkerKind, o as EntityMaintenanceReport, p as EntityStatus, q as EraseReport, r as EraseStepError, s as ExtractedFact, t as ExtractedFactEdge, u as ExtractedFactWithOntology, v as ExtractedTask, w as ForgetParams, x as ForgetResult, y as GraphTraversalOptions, z as GroundingConfig, H as HEAL_BATCH_SIZE, A as HEAL_RECHECK_MS, B as HOOK_TIMEOUT_MARKER, I as HealResult, J as ImportDumpResult, K as IngestDocumentResult, L as LLMProvider, N as LibrarianConfig, P as LibrarianGateConfig, Q as LockedMaintenanceJob, T as MaintenanceJob, U as MaintenanceStopReason, V as MemoryDumpEntity, X as MigrationPolicy, Y as ONTOLOGY_ABSTAIN_SENTINEL, Z as ONTOLOGY_BACKFILL_BATCH_SIZE, _ as ONTOLOGY_BACKFILL_MAX_PROMPT_CHARS, $ as ONTOLOGY_BACKFILL_RECHECK_MS, a0 as OntologyBackfillResult, a1 as OntologyEdgeType, a2 as OntologyManifest, a3 as OntologyNodeType, a4 as OntologyPromptContext, a5 as OntologyUpdates, a6 as PendingMaintenance, a7 as PendingMigrationWork, a8 as PendingSourceStatus, a9 as PromptOverrides, aa as PromptService, ab as PrunePartialFailureError, ac as ReembedResult, ad as RememberInput, ae as RunPendingMaintenanceOptions, af as RunPendingMaintenanceResult, ag as SourcePassage, ah as StoreSourceResult, ai as StoredSource, aj as StoredSourceDump, ak as StoredSourceSummary, al as SupersedeReplacement, am as SystemOneConfig, an as SystemOneThresholdSite, ao as VectorRanker, ap as VectorRankerFallback, aq as VectorRankerRankArgs, ar as VectorRankerSemanticResult, as as WikiBusyError, at as WikiBusyOperation, au as WikiCheckpoint, av as WikiDiagnostic, aw as WikiDiagnosticCode, ax as WikiDiagnosticDetail, ay as WikiDiagnosticOperation, az as WikiDiagnosticSeverity, aA as WikiDiagnosticTrigger, aB as WikiDraftNotFound, aC as WikiDuplicateHashError, aD as WikiEdge, aE as WikiEvent, aF as WikiExternalDeletionError, aG as WikiFact, aH as WikiGraphNodeOwnershipConflict, aI as WikiIngestEmptyError, aJ as WikiInstructions, aK as WikiInvalidReadOptions, aL as WikiLintReport, aM as WikiMemoryTestAccess, aN as WikiMigrationRequiredError, aO as WikiOutboxEvent, aP as WikiParseError, aQ as WikiSearchUnavailableError, aR as WikiSourcePointer, aS as WikiSourceRefHashCollision, aT as WikiStrictOntologyViolation, aU as WikiSupersedeError, aV as WikiSupersedeReason, aW as WikiTask, aX as WikiTransactionError, aY as isReservedAbstainSlug, aZ as isWikiSearchUnavailableError, a_ as validateManifest } from './testing-CDSfjx8j.js';
1
+ import { M as MemoryBundle, F as FormatContextOptions, G as GraphNeighborhood, a as MemoryDump, b as FormattedMemoryDump, O as OntologyMode, W as WikiConfig, R as ReadOptions, c as OntologyConfig, S as SQLiteAdapter, d as WikiOptions, e as WikiMemory } from './testing-DFyghdSG.js';
2
+ export { C as CLASSIFIER_MAX_CHOICES, f as CheckpointIncompleteError, g as ChunkFailure, h as ClassifierAnswer, i as ClassifierQuestion, j as ClassifyRequest, k as ClassifyResponse, D as DegradedRecord, l as DraftPage, E as EmbedFactResult, m as EmbedFailureKind, n as EmbeddingMarkerKind, o as EntityMaintenanceReport, p as EntityStatus, q as EraseReport, r as EraseStepError, s as ExtractedFact, t as ExtractedFactEdge, u as ExtractedFactWithOntology, v as ExtractedTask, w as ForgetParams, x as ForgetResult, y as GraphTraversalOptions, z as GroundingConfig, H as HEAL_BATCH_SIZE, A as HEAL_RECHECK_MS, B as HOOK_TIMEOUT_MARKER, I as HealResult, J as ImportDumpResult, K as IngestDocumentResult, L as LLMProvider, N as LibrarianConfig, P as LibrarianGateConfig, Q as LockedMaintenanceJob, T as MaintenanceJob, U as MaintenanceStopReason, V as MemoryDumpEntity, X as MigrationPolicy, Y as ONTOLOGY_ABSTAIN_SENTINEL, Z as ONTOLOGY_BACKFILL_BATCH_SIZE, _ as ONTOLOGY_BACKFILL_RECHECK_MS, $ as OntologyBackfillResult, a0 as OntologyEdgeType, a1 as OntologyManifest, a2 as OntologyNodeType, a3 as OntologyPromptContext, a4 as OntologyUpdates, a5 as PendingMaintenance, a6 as PendingMigrationWork, a7 as PendingSourceStatus, a8 as PromptOverrides, a9 as PromptService, aa as PrunePartialFailureError, ab as ReembedResult, ac as RememberInput, ad as RunPendingMaintenanceOptions, ae as RunPendingMaintenanceResult, af as SourcePassage, ag as StoreSourceResult, ah as StoredSource, ai as StoredSourceDump, aj as StoredSourceSummary, ak as SupersedeReplacement, al as SystemOneConfig, am as SystemOneThresholdSite, an as VectorRanker, ao as VectorRankerFallback, ap as VectorRankerRankArgs, aq as VectorRankerSemanticResult, ar as WikiBusyError, as as WikiBusyOperation, at as WikiCheckpoint, au as WikiDiagnostic, av as WikiDiagnosticCode, aw as WikiDiagnosticDetail, ax as WikiDiagnosticOperation, ay as WikiDiagnosticSeverity, az as WikiDiagnosticTrigger, aA as WikiDraftNotFound, aB as WikiDuplicateHashError, aC as WikiEdge, aD as WikiEvent, aE as WikiExternalDeletionError, aF as WikiFact, aG as WikiGraphNodeOwnershipConflict, aH as WikiIngestEmptyError, aI as WikiInstructions, aJ as WikiInvalidReadOptions, aK as WikiLintReport, aL as WikiMemoryTestAccess, aM as WikiMigrationRequiredError, aN as WikiOutboxEvent, aO as WikiParseError, aP as WikiSearchUnavailableError, aQ as WikiSourcePointer, aR as WikiSourceRefHashCollision, aS as WikiStrictOntologyViolation, aT as WikiSupersedeError, aU as WikiSupersedeReason, aV as WikiTask, aW as WikiTransactionError, aX as isReservedAbstainSlug, aY as isWikiSearchUnavailableError, aZ as validateManifest } from './testing-DFyghdSG.js';
3
3
  import { OkfFile } from '@equationalapplications/core-okf';
4
4
 
5
5
  /**
@@ -47,21 +47,6 @@ declare function chunkText(input: string, maxChunkLength: number, overlap: numbe
47
47
  truncated: boolean;
48
48
  };
49
49
 
50
- /** Per-candidate anchor ratio used at L0: `min(HEAL_MAX_ANCHORS, batch.length * HEAL_ANCHORS_PER_CANDIDATE)`. */
51
- declare const HEAL_ANCHORS_PER_CANDIDATE = 4;
52
- /**
53
- * Default body truncation cap applied at L3 only. A fact whose body is at or
54
- * below this cap passes through unchanged; a fact above it is sliced to this
55
- * length with a `...[truncated at N chars, original was M]` marker.
56
- */
57
- declare const HEAL_MAX_FACT_BODY_CHARS_L3 = 4000;
58
- /**
59
- * Hard ceiling on the `allTasks` slice fed to the heal prompt at L0. Tasks
60
- * are entity-global (not batch-local), so this is a constant rather than a
61
- * function of batch length.
62
- */
63
- declare const HEAL_MAX_TASKS = 50;
64
-
65
50
  /**
66
51
  * Default maximum characters per chunk that `ingestDocument` uses when a
67
52
  * caller doesn't override `maxChunkLength` (directly or via
@@ -78,6 +63,24 @@ declare const DEFAULT_MAX_CHUNK_LENGTH = 12000;
78
63
  */
79
64
  declare const DEFAULT_CHUNK_OVERLAP = 400;
80
65
 
66
+ /** Input bound for the ontology-backfill generative prompt (was `MaintenanceService.ts`). */
67
+ declare const ONTOLOGY_BACKFILL_MAX_PROMPT_CHARS = 40000;
68
+
69
+ /** Per-candidate anchor ratio used at L0: `min(HEAL_MAX_ANCHORS, batch.length * HEAL_ANCHORS_PER_CANDIDATE)`. */
70
+ declare const HEAL_ANCHORS_PER_CANDIDATE = 4;
71
+ /**
72
+ * Default body truncation cap applied at L3 only. A fact whose body is at or
73
+ * below this cap passes through unchanged; a fact above it is sliced to this
74
+ * length with a `...[truncated at N chars, original was M]` marker.
75
+ */
76
+ declare const HEAL_MAX_FACT_BODY_CHARS_L3 = 4000;
77
+ /**
78
+ * Hard ceiling on the `allTasks` slice fed to the heal prompt at L0. Tasks
79
+ * are entity-global (not batch-local), so this is a constant rather than a
80
+ * function of batch length.
81
+ */
82
+ declare const HEAL_MAX_TASKS = 50;
83
+
81
84
  declare function formatContext(bundle: MemoryBundle, options?: FormatContextOptions): string;
82
85
 
83
86
  /**
@@ -148,7 +151,7 @@ interface ContextBudget {
148
151
  }
149
152
  declare function estimateTokensWith(budget: ContextBudget, text: string): number;
150
153
 
151
- type ContextBudgetOp = 'resolve' | 'heal' | 'extract';
154
+ type ContextBudgetOp = 'resolve' | 'heal' | 'extract' | 'backfill';
152
155
  declare function resolveContextBudget(config: WikiConfig | undefined): ContextBudget;
153
156
  declare function resolveMaxPromptChars(budget: ContextBudget, op: ContextBudgetOp): number;
154
157
  /** The ingest chunk default stays 12000 in both modes (ruling R2). */
@@ -245,5 +248,5 @@ declare const ONTOLOGY_BACKFILL_SYSTEM_PROMPT = "You are a knowledge classificat
245
248
 
246
249
  declare function createWiki(db: SQLiteAdapter, options: WikiOptions): WikiMemory;
247
250
 
248
- export { DEFAULT_CHUNK_OVERLAP, DEFAULT_LIBRARIAN_SYNTHESIS_PROMPT, DEFAULT_MAX_CHUNK_LENGTH, DEFAULT_MAX_EMBED_CHARS, DEFAULT_ONTOLOGY_JOB_BATCH_SIZE, DEFAULT_SETUP_BUDGET_MS, DEFAULT_TYPING_MIN_CONFIDENCE, 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, OntologyConfig, OntologyMode, ReadOptions, SQLiteAdapter, WikiConfig, WikiMemory, WikiOptions, buildOntologyPromptAppendix, chunkText, configureRandomSource, createWiki, estimateTokensWith, formatContext, formatGraphContext, formatMemoryDump, formatOkfBundle, hydrateLibrarianPrompt, mapLibrarianOptionsToReadOptions, parseEmbedding, parseOkfBundle, resolveContextBudget, resolveDefaultChunkLength, resolveMaxPromptChars, resolveOntologyJobDefaults, resolveSystemOneTyping, resolveTypingMinConfidence, safeSlice, validUsage, validateLibrarianPromptTemplate, warnOnce };
251
+ export { DEFAULT_CHUNK_OVERLAP, DEFAULT_LIBRARIAN_SYNTHESIS_PROMPT, DEFAULT_MAX_CHUNK_LENGTH, DEFAULT_MAX_EMBED_CHARS, DEFAULT_ONTOLOGY_JOB_BATCH_SIZE, DEFAULT_SETUP_BUDGET_MS, DEFAULT_TYPING_MIN_CONFIDENCE, EMBED_CHARS_CEILING, FormatContextOptions, FormattedMemoryDump, GraphNeighborhood, HEAL_ANCHORS_PER_CANDIDATE, HEAL_MAX_FACT_BODY_CHARS_L3, HEAL_MAX_TASKS, MemoryBundle, MemoryDump, ONTOLOGY_BACKFILL_MAX_PROMPT_CHARS, ONTOLOGY_BACKFILL_SYSTEM_PROMPT, OntologyConfig, OntologyMode, ReadOptions, SQLiteAdapter, WikiConfig, WikiMemory, WikiOptions, buildOntologyPromptAppendix, chunkText, configureRandomSource, createWiki, estimateTokensWith, formatContext, formatGraphContext, formatMemoryDump, formatOkfBundle, hydrateLibrarianPrompt, mapLibrarianOptionsToReadOptions, parseEmbedding, parseOkfBundle, resolveContextBudget, resolveDefaultChunkLength, resolveMaxPromptChars, resolveOntologyJobDefaults, resolveSystemOneTyping, resolveTypingMinConfidence, safeSlice, validUsage, validateLibrarianPromptTemplate, warnOnce };
249
252
  export type { ContextBudget, FormatOkfBundleOptions, LibrarianOptions, LibrarianPromptVariables, OkfFormatProfile, OkfImportOptions };
package/dist/index.js CHANGED
@@ -3584,6 +3584,18 @@ var _EntryRepository = class _EntryRepository extends BaseRepository {
3584
3584
  );
3585
3585
  return rows.map((r) => ({ id: r.id, title: r.title, okf_type: r.okf_type ?? null }));
3586
3586
  }
3587
+ /**
3588
+ * Shortlist scoring rows (id, title, okf_type, body) over all live typed
3589
+ * facts. Same filters as findTitleIndexByEntityId; okf_type is never NULL
3590
+ * in results because the query excludes untyped rows.
3591
+ */
3592
+ async findShortlistRowsByEntityId(entityId, tx) {
3593
+ const executor = this.getExecutor(tx);
3594
+ return executor.getAllAsync(
3595
+ `SELECT id, title, okf_type, body FROM ${this.prefix}entries WHERE entity_id = ? AND deleted_at IS NULL AND okf_type IS NOT NULL`,
3596
+ [entityId]
3597
+ );
3598
+ }
3587
3599
  /** Counts live mutable facts: eligible (past cooldown) vs deferred (in cooldown). */
3588
3600
  async countHealCandidatesByEntityId(entityId, recheckCutoff, tx) {
3589
3601
  const executor = this.getExecutor(tx);
@@ -7557,46 +7569,29 @@ Return ONLY a valid JSON object matching this schema:
7557
7569
  }
7558
7570
  If no manifest type fits a fact, assign the closest type the fact is an example of; omit that fact from "classifications" only when no type applies even broadly. Use the manifest slug EXACTLY as spelled (spelling variants are folded to the manifest form).
7559
7571
  When echoing an existing fact's title verbatim into "target_title", preserve every JSON escape sequence (\\", \\n, \\\\, \\/) exactly as it appeared in the input body \u2014 do not strip backslashes, do not add unescaped quotes. Do not return markdown, just raw JSON.`;
7560
- var TITLE_CATALOG_MAX_ENTRIES = 200;
7561
- function buildTitleCatalogBlock(rows) {
7562
- const byKey = /* @__PURE__ */ new Map();
7563
- for (const r of rows) {
7564
- if (typeof r.title !== "string" || r.title.length === 0) continue;
7565
- if (typeof r.okf_type !== "string" || r.okf_type.length === 0) continue;
7566
- byKey.set(normalizeTitleKey(r.title), { title: r.title, okf_type: r.okf_type });
7567
- }
7568
- const typed = [...byKey.values()].sort((a, b) => a.title < b.title ? -1 : a.title > b.title ? 1 : 0);
7569
- const CHAR_BUDGET = 8e3;
7570
- const listed = [];
7571
- let used = 0;
7572
- for (const r of typed) {
7573
- const line = `- ${JSON.stringify(r.title)} (${r.okf_type})`;
7574
- if (line.length + 1 > CHAR_BUDGET) continue;
7575
- if (listed.length >= TITLE_CATALOG_MAX_ENTRIES) break;
7576
- if (used + line.length + 1 > CHAR_BUDGET) continue;
7577
- listed.push(r);
7578
- used += line.length + 1;
7579
- }
7580
- const truncated = typed.length > listed.length;
7581
- if (typed.length === 0) {
7582
- return [
7583
- "TITLE CATALOG: this memory contains no typed nodes yet.",
7584
- 'A fact classified in this same response is a valid "target_title" once typed. Otherwise omit "edges" rather than invent a target_title.'
7585
- ].join("\n");
7572
+ function formatCatalogLine(r) {
7573
+ return `- ${JSON.stringify(r.title)} (${r.okf_type})`;
7574
+ }
7575
+ function buildCandidateSections(facts, rowsByFact) {
7576
+ const footer = 'A "target_title" may be copied verbatim from the candidates above for its fact, or be another fact classified in this same response. Any other existing typed node in this memory is also a valid "target_title", even if not listed here. If no valid target exists, omit "edges" rather than invent a target_title.';
7577
+ const sections = [];
7578
+ for (const fact of facts) {
7579
+ const rows = rowsByFact.get(fact.id);
7580
+ if (!rows || rows.length === 0) continue;
7581
+ sections.push(
7582
+ [
7583
+ `CANDIDATE TARGETS for fact ${JSON.stringify(fact.id)}: typed nodes in this memory, ranked by title overlap:`,
7584
+ ...rows.map(formatCatalogLine)
7585
+ ].join("\n")
7586
+ );
7586
7587
  }
7587
- if (listed.length === 0) {
7588
+ if (sections.length === 0) {
7588
7589
  return [
7589
- "TITLE CATALOG: existing typed nodes exist in this memory, but none fit the catalog budget.",
7590
+ "CANDIDATE TARGETS: this memory contains no typed nodes yet.",
7590
7591
  'A fact classified in this same response is a valid "target_title" once typed. Otherwise omit "edges" rather than invent a target_title.'
7591
7592
  ].join("\n");
7592
7593
  }
7593
- const catalog = listed.map((r) => `- ${JSON.stringify(r.title)} (${r.okf_type})`).join("\n");
7594
- return [
7595
- "TITLE CATALOG: existing typed nodes in this memory include:",
7596
- catalog,
7597
- ...truncated ? ["(This list is truncated; more typed nodes exist than are shown here.)"] : [],
7598
- 'A "target_title" may be copied verbatim from this catalog, or be another fact classified in this same response. If no valid target exists, omit "edges" rather than invent a target_title.'
7599
- ].join("\n");
7594
+ return [...sections, footer].join("\n\n");
7600
7595
  }
7601
7596
  var GROUNDING_SOURCE = {
7602
7597
  ingest: { key: "facts", source: "the document chunk" },
@@ -7874,7 +7869,7 @@ The following document anchors are provided for contradiction detection only. Do
7874
7869
  ...corpusField
7875
7870
  };
7876
7871
  }
7877
- buildOntologyBackfillPrompt(facts, runtimeOverride, ontologyContext, titleCatalog) {
7872
+ buildOntologyBackfillPrompt(facts, runtimeOverride, ontologyContext, candidateSections) {
7878
7873
  const template = runtimeOverride ?? this.globalOverrides?.ontologyBackfillSystemPrompt ?? ONTOLOGY_BACKFILL_SYSTEM_PROMPT;
7879
7874
  const hasFacts = /\{\{\s*facts\s*\}\}/.test(template);
7880
7875
  if (hasFacts || this.hasOntologyPlaceholders(template)) {
@@ -7884,13 +7879,13 @@ The following document anchors are provided for contradiction detection only. Do
7884
7879
  ${JSON.stringify(facts, null, 2)}`
7885
7880
  };
7886
7881
  }
7887
- const effective = titleCatalog !== void 0 ? `${template}
7888
-
7889
- ${titleCatalog}` : template;
7882
+ const factsBlock = `Facts:
7883
+ ${JSON.stringify(facts, null, 2)}`;
7890
7884
  return {
7891
- systemPrompt: this.appendOntology(effective, ontologyContext),
7892
- userPrompt: `Facts:
7893
- ${JSON.stringify(facts, null, 2)}`
7885
+ systemPrompt: this.appendOntology(template, ontologyContext),
7886
+ userPrompt: candidateSections !== void 0 ? `${factsBlock}
7887
+
7888
+ ${candidateSections}` : factsBlock
7894
7889
  };
7895
7890
  }
7896
7891
  /** Ops extract (spec §5.2): events only — no existing facts. */
@@ -7979,6 +7974,7 @@ var DEFAULT_CHUNK_OVERLAP = 400;
7979
7974
 
7980
7975
  // src/utils/contextCaps.ts
7981
7976
  var OPS_RESOLVE_MAX_PROMPT_CHARS = 4e4;
7977
+ var ONTOLOGY_BACKFILL_MAX_PROMPT_CHARS = 4e4;
7982
7978
  var HEAL_MAX_PROMPT_CHARS = 4e4;
7983
7979
  var OPS_MAX_EXTRACT_CHARS = 24e3;
7984
7980
 
@@ -7989,7 +7985,8 @@ var DEFAULT_OUTPUT_RESERVE_TOKENS = 4e3;
7989
7985
  var OP_FLOOR = {
7990
7986
  resolve: OPS_RESOLVE_MAX_PROMPT_CHARS,
7991
7987
  heal: HEAL_MAX_PROMPT_CHARS,
7992
- extract: OPS_MAX_EXTRACT_CHARS
7988
+ extract: OPS_MAX_EXTRACT_CHARS,
7989
+ backfill: ONTOLOGY_BACKFILL_MAX_PROMPT_CHARS
7993
7990
  };
7994
7991
  function bad(key, value, why) {
7995
7992
  return new Error(`[core-llm-wiki] config.context.${key} must be ${why}; received ${JSON.stringify(value)}`);
@@ -8027,12 +8024,11 @@ function declaredPromptCap(budget, op) {
8027
8024
  const derived = Math.floor(
8028
8025
  (budget.contextWindowTokens - budget.outputReserveTokens) * budget.safetyFraction * budget.charsPerToken
8029
8026
  );
8030
- if (op === "resolve") return Math.max(OP_FLOOR.resolve, derived);
8031
- return Math.max(OP_FLOOR.heal, derived);
8027
+ return Math.max(OP_FLOOR[op], derived);
8032
8028
  }
8033
8029
  function resolveMaxPromptChars(budget, op) {
8034
8030
  if (budget.mode !== "declared") {
8035
- return op === "resolve" ? OP_FLOOR.resolve : op === "heal" ? OP_FLOOR.heal : OP_FLOOR.extract;
8031
+ return OP_FLOOR[op];
8036
8032
  }
8037
8033
  if (op === "extract") {
8038
8034
  const resolveDerived = declaredPromptCap(budget, "resolve");
@@ -8932,6 +8928,52 @@ function classifierStateForFact(fact) {
8932
8928
  return parts.join("\n\n");
8933
8929
  }
8934
8930
 
8931
+ // src/utils/shortlist.ts
8932
+ function shortlistScore(factTitle, factBody, row) {
8933
+ const factTokens = /* @__PURE__ */ new Set([...titleTokens(factTitle), ...titleTokens(factBody)]);
8934
+ const rowTokens = /* @__PURE__ */ new Set([...titleTokens(row.title), ...titleTokens(row.body ?? "")]);
8935
+ return jaccardScore(factTokens, rowTokens);
8936
+ }
8937
+ function createShortlistScorer(rows) {
8938
+ const rowTokens = /* @__PURE__ */ new Map();
8939
+ const tokensOfRow = (row) => {
8940
+ let t = rowTokens.get(row);
8941
+ if (!t) {
8942
+ t = /* @__PURE__ */ new Set([...titleTokens(row.title), ...titleTokens(row.body ?? "")]);
8943
+ rowTokens.set(row, t);
8944
+ }
8945
+ return t;
8946
+ };
8947
+ for (const r of rows) tokensOfRow(r);
8948
+ const factTokens = /* @__PURE__ */ new WeakMap();
8949
+ return (fact, row) => {
8950
+ let ft = factTokens.get(fact);
8951
+ if (!ft) {
8952
+ ft = /* @__PURE__ */ new Set([...titleTokens(fact.title), ...titleTokens(fact.body)]);
8953
+ factTokens.set(fact, ft);
8954
+ }
8955
+ return jaccardScore(ft, tokensOfRow(row));
8956
+ };
8957
+ }
8958
+ function buildShortlist(fact, rows, k, score = (f, r) => shortlistScore(f.title, f.body, r)) {
8959
+ if (typeof k !== "number" || Number.isNaN(k) || !Number.isInteger(k)) {
8960
+ throw new Error(`buildShortlist: k must be a non-negative integer, got ${String(k)}`);
8961
+ }
8962
+ if (k <= 0) return [];
8963
+ const byKey = /* @__PURE__ */ new Map();
8964
+ for (const r of rows) {
8965
+ if (typeof r.title !== "string" || r.title.length === 0) continue;
8966
+ if (typeof r.okf_type !== "string" || r.okf_type.length === 0) continue;
8967
+ byKey.set(normalizeTitleKey(r.title), r);
8968
+ }
8969
+ const scored = [...byKey.values()].map((row) => ({ row, score: score(fact, row) }));
8970
+ scored.sort((a, b) => {
8971
+ if (a.score !== b.score) return b.score - a.score;
8972
+ return a.row.title < b.row.title ? -1 : a.row.title > b.row.title ? 1 : 0;
8973
+ });
8974
+ return scored.slice(0, k).map((s) => s.row);
8975
+ }
8976
+
8935
8977
  // src/services/TemporalService.ts
8936
8978
  var HISTORY_MAX_DEPTH = 100;
8937
8979
  var TemporalService = class {
@@ -9121,6 +9163,17 @@ function resolveSystemOneTyping(config, classifierCallOption) {
9121
9163
  }
9122
9164
  return classifierCallOption ?? (systemOneValid ? systemOne.typing : void 0) ?? (legacyValid ? legacy : void 0) ?? "llm";
9123
9165
  }
9166
+ var DEFAULT_SHORTLIST_K = 10;
9167
+ function resolveShortlistK(config) {
9168
+ const k = config?.ontology?.shortlistK;
9169
+ if (k === void 0) return DEFAULT_SHORTLIST_K;
9170
+ if (typeof k !== "number" || !Number.isInteger(k) || k < 1) {
9171
+ throw new Error(
9172
+ `[core-llm-wiki] \`ontology.shortlistK\` is ${formatConfigValue(k)}, which is not a finite integer >= 1.`
9173
+ );
9174
+ }
9175
+ return k;
9176
+ }
9124
9177
  var DEFAULT_TYPING_MIN_CONFIDENCE = 0.5;
9125
9178
  function resolveTypingMinConfidence(config) {
9126
9179
  const systemOneFloor = config?.systemOne?.minConfidence?.typing;
@@ -10785,7 +10838,6 @@ async function runLibrarianStrategy(deps, ctx) {
10785
10838
  // src/services/MaintenanceService.ts
10786
10839
  var CHAIN_TRUNCATED_NOTICE = `includeChain walk stopped at the depth cap (${HISTORY_MAX_DEPTH} links per direction); the chain is longer than the ids listed. Run forget again on a remaining chain id to continue.`;
10787
10840
  var ONTOLOGY_BACKFILL_BATCH_SIZE = 25;
10788
- var ONTOLOGY_BACKFILL_MAX_PROMPT_CHARS = 4e4;
10789
10841
  var ONTOLOGY_BACKFILL_RECHECK_MS = 7 * 24 * 60 * 60 * 1e3;
10790
10842
  var CLASSIFIER_MAX_CHOICES = 255;
10791
10843
  var HEAL_ANCHOR_SEARCH_OVERFETCH = 4;
@@ -12261,6 +12313,8 @@ DROP TRIGGER IF EXISTS ${ad};`);
12261
12313
  if (options?.classifier !== void 0 && options.classifier !== "auto" && options.classifier !== "llm") {
12262
12314
  throw new TypeError(`Invalid classifier option: ${JSON.stringify(options.classifier)} \u2014 must be 'auto' or 'llm'`);
12263
12315
  }
12316
+ const shortlistK = resolveShortlistK(this.options.config);
12317
+ const maxPromptChars = resolveMaxPromptChars(resolveContextBudget(this.options.config), "backfill");
12264
12318
  const trigger = options?.trigger ?? "call";
12265
12319
  const now = Date.now();
12266
12320
  const recheckCutoff = options?.recheckCheckedBefore ?? now - ONTOLOGY_BACKFILL_RECHECK_MS;
@@ -12308,7 +12362,9 @@ DROP TRIGGER IF EXISTS ${ad};`);
12308
12362
  meter: options?.meter,
12309
12363
  trigger,
12310
12364
  batchSize: escalated.length,
12311
- recheckCutoff
12365
+ recheckCutoff,
12366
+ shortlistK,
12367
+ maxPromptChars
12312
12368
  });
12313
12369
  return {
12314
12370
  scanned: classifierRun.result.scanned,
@@ -12329,7 +12385,9 @@ DROP TRIGGER IF EXISTS ${ad};`);
12329
12385
  promptOverride: options?.promptOverride,
12330
12386
  meter: options?.meter,
12331
12387
  trigger,
12332
- recheckCutoff
12388
+ recheckCutoff,
12389
+ shortlistK,
12390
+ maxPromptChars
12333
12391
  });
12334
12392
  }
12335
12393
  /**
@@ -12357,19 +12415,39 @@ DROP TRIGGER IF EXISTS ${ad};`);
12357
12415
  */
12358
12416
  async _runGenerativeBackfill(entityId, candidates, runOpts) {
12359
12417
  runOpts.batchSize ?? ONTOLOGY_BACKFILL_BATCH_SIZE;
12418
+ const shortlistK = runOpts.shortlistK;
12419
+ if (shortlistK === void 0) {
12420
+ throw new Error("_runGenerativeBackfill: runOpts.shortlistK is required (resolved at doRunOntologyBackfill entry)");
12421
+ }
12422
+ const maxPromptChars = runOpts.maxPromptChars;
12423
+ if (maxPromptChars === void 0) {
12424
+ throw new Error("_runGenerativeBackfill: runOpts.maxPromptChars is required (resolved at doRunOntologyBackfill entry)");
12425
+ }
12360
12426
  const ontologyService = this.ontologyService;
12361
12427
  const now = Date.now();
12362
12428
  const recheckCutoff = runOpts.recheckCutoff;
12363
12429
  const ontologyContext = await ontologyService.buildPromptContext(entityId);
12364
- const titleRows = await this.entryRepo.findTitleIndexByEntityId(entityId);
12365
- const titleCatalog = buildTitleCatalogBlock(titleRows);
12430
+ const shortlistRows = await this.entryRepo.findShortlistRowsByEntityId(entityId);
12366
12431
  const toPromptShape = (f) => ({ id: f.id, title: f.title, body: f.body, tags: f.tags });
12367
- const buildPrompt = (facts) => this.promptService.buildOntologyBackfillPrompt(
12368
- facts.map(toPromptShape),
12369
- runOpts.promptOverride,
12370
- ontologyContext,
12371
- titleCatalog
12372
- );
12432
+ const shortlistScorer = createShortlistScorer(shortlistRows);
12433
+ const shortlistCache = /* @__PURE__ */ new Map();
12434
+ const buildPrompt = (facts) => {
12435
+ const rowsByFact = /* @__PURE__ */ new Map();
12436
+ for (const f of facts) {
12437
+ let rows = shortlistCache.get(f.id);
12438
+ if (!rows) {
12439
+ rows = buildShortlist({ title: f.title, body: f.body }, shortlistRows, shortlistK, shortlistScorer);
12440
+ shortlistCache.set(f.id, rows);
12441
+ }
12442
+ rowsByFact.set(f.id, rows);
12443
+ }
12444
+ return this.promptService.buildOntologyBackfillPrompt(
12445
+ facts.map(toPromptShape),
12446
+ runOpts.promptOverride,
12447
+ ontologyContext,
12448
+ buildCandidateSections(facts, rowsByFact)
12449
+ );
12450
+ };
12373
12451
  const outcome = await runBatched({
12374
12452
  items: candidates,
12375
12453
  buildPrompt,
@@ -12383,7 +12461,7 @@ DROP TRIGGER IF EXISTS ${ad};`);
12383
12461
  };
12384
12462
  },
12385
12463
  maxOutputTokens: this.options.llmProvider.maxOutputTokens,
12386
- maxPromptChars: ONTOLOGY_BACKFILL_MAX_PROMPT_CHARS,
12464
+ maxPromptChars,
12387
12465
  onSkip: (fact, err) => {
12388
12466
  if (isContextOverflowError(err)) {
12389
12467
  emitDiagnostic(this.options, {