@equationalapplications/core-llm-wiki 9.10.0 → 9.12.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-DnYjL2QD.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-DnYjL2QD.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-imNjsm-X.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-imNjsm-X.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). */
@@ -231,6 +234,12 @@ declare function warnOnce(message: string): void;
231
234
  * `??` throughout — falsy config values never participate by accident.
232
235
  */
233
236
  declare function resolveSystemOneTyping(config: WikiConfig | undefined, classifierCallOption?: 'auto' | 'llm'): 'auto' | 'llm';
237
+ /**
238
+ * Edge-mode resolution (specs/edge-suggestions-system-one §2): `systemOne.edges`
239
+ * → `'llm'`. A present non-`'auto'`/non-`'llm'` value warns once and is treated
240
+ * as unset. No legacy chain and no call option.
241
+ */
242
+ declare function resolveSystemOneEdges(config: WikiConfig | undefined): 'auto' | 'llm';
234
243
  /** Engine default confidence floor for classifier typing. */
235
244
  declare const DEFAULT_TYPING_MIN_CONFIDENCE: 0.5;
236
245
  /**
@@ -240,10 +249,18 @@ declare const DEFAULT_TYPING_MIN_CONFIDENCE: 0.5;
240
249
  * typing path reads this; call it there, never on the generative path.
241
250
  */
242
251
  declare function resolveTypingMinConfidence(config: WikiConfig | undefined): number;
252
+ /**
253
+ * Edge-screen floor (specs/edge-suggestions-system-one §3): returns the
254
+ * `systemOne.minConfidence.edges` floor only when the edge mode resolves
255
+ * `'auto'` and the floor is a finite number in [0.5, 1]. There is no default
256
+ * floor: a missing or out-of-domain value warns once and returns `undefined`
257
+ * (the site then resolves `'llm'`). Under `'llm'` or unset it reads nothing.
258
+ */
259
+ declare function resolveEdgesMinConfidence(config: WikiConfig | undefined): number | undefined;
243
260
 
244
261
  declare const ONTOLOGY_BACKFILL_SYSTEM_PROMPT = "You are a knowledge classification agent. You will receive existing memory facts that currently have no ontology type. For each input fact { \"id\", \"title\", \"body\", \"tags\" }, assign the best matching okf_type from the ontology manifest and optionally propose edges to related facts by title.\nReturn ONLY a valid JSON object matching this schema:\n{\n \"classifications\": [\n { \"id\": \"string (input fact id, copied verbatim)\", \"okf_type\": \"string (manifest node type slug)\", \"edges\": [{ \"edge_type\": \"string\", \"target_title\": \"string\" }] }\n ]\n}\nIf 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).\nWhen 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.";
245
262
 
246
263
  declare function createWiki(db: SQLiteAdapter, options: WikiOptions): WikiMemory;
247
264
 
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 };
265
+ 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, resolveEdgesMinConfidence, resolveMaxPromptChars, resolveOntologyJobDefaults, resolveSystemOneEdges, resolveSystemOneTyping, resolveTypingMinConfidence, safeSlice, validUsage, validateLibrarianPromptTemplate, warnOnce };
249
266
  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-DnYjL2QD.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-DnYjL2QD.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-imNjsm-X.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-imNjsm-X.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). */
@@ -231,6 +234,12 @@ declare function warnOnce(message: string): void;
231
234
  * `??` throughout — falsy config values never participate by accident.
232
235
  */
233
236
  declare function resolveSystemOneTyping(config: WikiConfig | undefined, classifierCallOption?: 'auto' | 'llm'): 'auto' | 'llm';
237
+ /**
238
+ * Edge-mode resolution (specs/edge-suggestions-system-one §2): `systemOne.edges`
239
+ * → `'llm'`. A present non-`'auto'`/non-`'llm'` value warns once and is treated
240
+ * as unset. No legacy chain and no call option.
241
+ */
242
+ declare function resolveSystemOneEdges(config: WikiConfig | undefined): 'auto' | 'llm';
234
243
  /** Engine default confidence floor for classifier typing. */
235
244
  declare const DEFAULT_TYPING_MIN_CONFIDENCE: 0.5;
236
245
  /**
@@ -240,10 +249,18 @@ declare const DEFAULT_TYPING_MIN_CONFIDENCE: 0.5;
240
249
  * typing path reads this; call it there, never on the generative path.
241
250
  */
242
251
  declare function resolveTypingMinConfidence(config: WikiConfig | undefined): number;
252
+ /**
253
+ * Edge-screen floor (specs/edge-suggestions-system-one §3): returns the
254
+ * `systemOne.minConfidence.edges` floor only when the edge mode resolves
255
+ * `'auto'` and the floor is a finite number in [0.5, 1]. There is no default
256
+ * floor: a missing or out-of-domain value warns once and returns `undefined`
257
+ * (the site then resolves `'llm'`). Under `'llm'` or unset it reads nothing.
258
+ */
259
+ declare function resolveEdgesMinConfidence(config: WikiConfig | undefined): number | undefined;
243
260
 
244
261
  declare const ONTOLOGY_BACKFILL_SYSTEM_PROMPT = "You are a knowledge classification agent. You will receive existing memory facts that currently have no ontology type. For each input fact { \"id\", \"title\", \"body\", \"tags\" }, assign the best matching okf_type from the ontology manifest and optionally propose edges to related facts by title.\nReturn ONLY a valid JSON object matching this schema:\n{\n \"classifications\": [\n { \"id\": \"string (input fact id, copied verbatim)\", \"okf_type\": \"string (manifest node type slug)\", \"edges\": [{ \"edge_type\": \"string\", \"target_title\": \"string\" }] }\n ]\n}\nIf 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).\nWhen 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.";
245
262
 
246
263
  declare function createWiki(db: SQLiteAdapter, options: WikiOptions): WikiMemory;
247
264
 
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 };
265
+ 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, resolveEdgesMinConfidence, resolveMaxPromptChars, resolveOntologyJobDefaults, resolveSystemOneEdges, resolveSystemOneTyping, resolveTypingMinConfidence, safeSlice, validUsage, validateLibrarianPromptTemplate, warnOnce };
249
266
  export type { ContextBudget, FormatOkfBundleOptions, LibrarianOptions, LibrarianPromptVariables, OkfFormatProfile, OkfImportOptions };
package/dist/index.js CHANGED
@@ -7974,6 +7974,7 @@ var DEFAULT_CHUNK_OVERLAP = 400;
7974
7974
 
7975
7975
  // src/utils/contextCaps.ts
7976
7976
  var OPS_RESOLVE_MAX_PROMPT_CHARS = 4e4;
7977
+ var ONTOLOGY_BACKFILL_MAX_PROMPT_CHARS = 4e4;
7977
7978
  var HEAL_MAX_PROMPT_CHARS = 4e4;
7978
7979
  var OPS_MAX_EXTRACT_CHARS = 24e3;
7979
7980
 
@@ -7984,7 +7985,8 @@ var DEFAULT_OUTPUT_RESERVE_TOKENS = 4e3;
7984
7985
  var OP_FLOOR = {
7985
7986
  resolve: OPS_RESOLVE_MAX_PROMPT_CHARS,
7986
7987
  heal: HEAL_MAX_PROMPT_CHARS,
7987
- extract: OPS_MAX_EXTRACT_CHARS
7988
+ extract: OPS_MAX_EXTRACT_CHARS,
7989
+ backfill: ONTOLOGY_BACKFILL_MAX_PROMPT_CHARS
7988
7990
  };
7989
7991
  function bad(key, value, why) {
7990
7992
  return new Error(`[core-llm-wiki] config.context.${key} must be ${why}; received ${JSON.stringify(value)}`);
@@ -8022,12 +8024,11 @@ function declaredPromptCap(budget, op) {
8022
8024
  const derived = Math.floor(
8023
8025
  (budget.contextWindowTokens - budget.outputReserveTokens) * budget.safetyFraction * budget.charsPerToken
8024
8026
  );
8025
- if (op === "resolve") return Math.max(OP_FLOOR.resolve, derived);
8026
- return Math.max(OP_FLOOR.heal, derived);
8027
+ return Math.max(OP_FLOOR[op], derived);
8027
8028
  }
8028
8029
  function resolveMaxPromptChars(budget, op) {
8029
8030
  if (budget.mode !== "declared") {
8030
- return op === "resolve" ? OP_FLOOR.resolve : op === "heal" ? OP_FLOOR.heal : OP_FLOOR.extract;
8031
+ return OP_FLOOR[op];
8031
8032
  }
8032
8033
  if (op === "extract") {
8033
8034
  const resolveDerived = declaredPromptCap(budget, "resolve");
@@ -9162,6 +9163,16 @@ function resolveSystemOneTyping(config, classifierCallOption) {
9162
9163
  }
9163
9164
  return classifierCallOption ?? (systemOneValid ? systemOne.typing : void 0) ?? (legacyValid ? legacy : void 0) ?? "llm";
9164
9165
  }
9166
+ function resolveSystemOneEdges(config) {
9167
+ const edges = config?.systemOne?.edges;
9168
+ if (edges !== void 0 && !isTypingMode(edges)) {
9169
+ warnOnce(
9170
+ `[core-llm-wiki] systemOne: \`systemOne.edges\` is ${formatConfigValue(edges)}, which is not 'auto' or 'llm'. The key is treated as unset; the default ('llm') applies.`
9171
+ );
9172
+ return "llm";
9173
+ }
9174
+ return edges ?? "llm";
9175
+ }
9165
9176
  var DEFAULT_SHORTLIST_K = 10;
9166
9177
  function resolveShortlistK(config) {
9167
9178
  const k = config?.ontology?.shortlistK;
@@ -9191,6 +9202,16 @@ function resolveTypingMinConfidence(config) {
9191
9202
  }
9192
9203
  return (systemOneValid ? systemOneFloor : void 0) ?? (legacyValid ? legacyFloor : void 0) ?? DEFAULT_TYPING_MIN_CONFIDENCE;
9193
9204
  }
9205
+ var isEdgesFloor = (v) => typeof v === "number" && Number.isFinite(v) && v >= 0.5 && v <= 1;
9206
+ function resolveEdgesMinConfidence(config) {
9207
+ if (resolveSystemOneEdges(config) !== "auto") return void 0;
9208
+ const floor = config?.systemOne?.minConfidence?.edges;
9209
+ if (isEdgesFloor(floor)) return floor;
9210
+ warnOnce(
9211
+ floor === void 0 ? "[core-llm-wiki] systemOne: `systemOne.minConfidence.edges` is required when `systemOne.edges` is 'auto'. The edge screen is off for this site; edges stay on the generative path." : `[core-llm-wiki] systemOne: \`systemOne.minConfidence.edges\` is ${formatConfigValue(floor)}, which is not a finite number in [0.5, 1]. The edge screen is off for this site; edges stay on the generative path.`
9212
+ );
9213
+ return void 0;
9214
+ }
9194
9215
 
9195
9216
  // src/repositories/VectorRemovalRepository.ts
9196
9217
  var CHUNK2 = 500;
@@ -10837,7 +10858,6 @@ async function runLibrarianStrategy(deps, ctx) {
10837
10858
  // src/services/MaintenanceService.ts
10838
10859
  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.`;
10839
10860
  var ONTOLOGY_BACKFILL_BATCH_SIZE = 25;
10840
- var ONTOLOGY_BACKFILL_MAX_PROMPT_CHARS = 4e4;
10841
10861
  var ONTOLOGY_BACKFILL_RECHECK_MS = 7 * 24 * 60 * 60 * 1e3;
10842
10862
  var CLASSIFIER_MAX_CHOICES = 255;
10843
10863
  var HEAL_ANCHOR_SEARCH_OVERFETCH = 4;
@@ -12314,6 +12334,7 @@ DROP TRIGGER IF EXISTS ${ad};`);
12314
12334
  throw new TypeError(`Invalid classifier option: ${JSON.stringify(options.classifier)} \u2014 must be 'auto' or 'llm'`);
12315
12335
  }
12316
12336
  const shortlistK = resolveShortlistK(this.options.config);
12337
+ const maxPromptChars = resolveMaxPromptChars(resolveContextBudget(this.options.config), "backfill");
12317
12338
  const trigger = options?.trigger ?? "call";
12318
12339
  const now = Date.now();
12319
12340
  const recheckCutoff = options?.recheckCheckedBefore ?? now - ONTOLOGY_BACKFILL_RECHECK_MS;
@@ -12333,7 +12354,10 @@ DROP TRIGGER IF EXISTS ${ad};`);
12333
12354
  return { ...zeroed, remaining: counts.eligible, deferred: counts.deferred };
12334
12355
  }
12335
12356
  const classifierMode = resolveSystemOneTyping(this.options.config, options?.classifier);
12357
+ const edgeMode = resolveSystemOneEdges(this.options.config);
12336
12358
  const classify = this.options.llmProvider.classify;
12359
+ const edgeMinConfidence = edgeMode === "auto" && classifierMode === "auto" && typeof classify === "function" ? resolveEdgesMinConfidence(this.options.config) : void 0;
12360
+ const edgeSiteMode = edgeMode === "auto" && typeof edgeMinConfidence === "number" ? "auto" : "llm";
12337
12361
  if (classifierMode === "auto" && typeof classify === "function") {
12338
12362
  const slugs = effectiveManifest.node_types.map((n) => n.type);
12339
12363
  if (slugs.length > 0 && slugs.length + 1 <= CLASSIFIER_MAX_CHOICES && !slugs.some((s) => isReservedAbstainSlug(s))) {
@@ -12344,16 +12368,29 @@ DROP TRIGGER IF EXISTS ${ad};`);
12344
12368
  now,
12345
12369
  recheckCutoff,
12346
12370
  options?.meter,
12347
- trigger
12371
+ trigger,
12372
+ shortlistK,
12373
+ edgeSiteMode,
12374
+ edgeMinConfidence
12348
12375
  );
12349
12376
  if (classifierRun.abortedOntologyOff || classifierRun.result.budgetStop) {
12350
12377
  return classifierRun.result;
12351
12378
  }
12352
- if (classifierRun.escalated.length > 0 && this.resolveSystemOneOnLowConfidence() === "llm") {
12379
+ if (classifierRun.escalated.length > 0) {
12353
12380
  const { mode: liveMode } = await ontologyService.getEffectiveState(entityId);
12354
12381
  if (liveMode === "off") {
12355
12382
  const counts = await this.entryRepo.countUntypedByEntityId(entityId, recheckCutoff);
12356
- return { ...zeroed, remaining: 0, deferred: counts.deferred };
12383
+ const committed = classifierRun.result;
12384
+ return {
12385
+ scanned: committed.scanned,
12386
+ typed: committed.typed,
12387
+ failedValidation: committed.failedValidation,
12388
+ edgesAdded: committed.edgesAdded,
12389
+ abstained: committed.abstained,
12390
+ skipped: committed.skipped,
12391
+ remaining: 0,
12392
+ deferred: counts.deferred
12393
+ };
12357
12394
  }
12358
12395
  const escalated = classifierRun.escalated;
12359
12396
  const generative = await this._runGenerativeBackfill(entityId, escalated, {
@@ -12362,7 +12399,10 @@ DROP TRIGGER IF EXISTS ${ad};`);
12362
12399
  trigger,
12363
12400
  batchSize: escalated.length,
12364
12401
  recheckCutoff,
12365
- shortlistK
12402
+ shortlistK,
12403
+ maxPromptChars,
12404
+ edgeSiteMode,
12405
+ edgeMinConfidence
12366
12406
  });
12367
12407
  return {
12368
12408
  scanned: classifierRun.result.scanned,
@@ -12384,7 +12424,10 @@ DROP TRIGGER IF EXISTS ${ad};`);
12384
12424
  meter: options?.meter,
12385
12425
  trigger,
12386
12426
  recheckCutoff,
12387
- shortlistK
12427
+ shortlistK,
12428
+ maxPromptChars,
12429
+ edgeSiteMode,
12430
+ edgeMinConfidence
12388
12431
  });
12389
12432
  }
12390
12433
  /**
@@ -12416,6 +12459,13 @@ DROP TRIGGER IF EXISTS ${ad};`);
12416
12459
  if (shortlistK === void 0) {
12417
12460
  throw new Error("_runGenerativeBackfill: runOpts.shortlistK is required (resolved at doRunOntologyBackfill entry)");
12418
12461
  }
12462
+ const maxPromptChars = runOpts.maxPromptChars;
12463
+ if (maxPromptChars === void 0) {
12464
+ throw new Error("_runGenerativeBackfill: runOpts.maxPromptChars is required (resolved at doRunOntologyBackfill entry)");
12465
+ }
12466
+ if (runOpts.edgeSiteMode === void 0) {
12467
+ throw new Error("_runGenerativeBackfill: runOpts.edgeSiteMode is required (resolved at doRunOntologyBackfill entry)");
12468
+ }
12419
12469
  const ontologyService = this.ontologyService;
12420
12470
  const now = Date.now();
12421
12471
  const recheckCutoff = runOpts.recheckCutoff;
@@ -12454,7 +12504,7 @@ DROP TRIGGER IF EXISTS ${ad};`);
12454
12504
  };
12455
12505
  },
12456
12506
  maxOutputTokens: this.options.llmProvider.maxOutputTokens,
12457
- maxPromptChars: ONTOLOGY_BACKFILL_MAX_PROMPT_CHARS,
12507
+ maxPromptChars,
12458
12508
  onSkip: (fact, err) => {
12459
12509
  if (isContextOverflowError(err)) {
12460
12510
  emitDiagnostic(this.options, {
@@ -12543,12 +12593,19 @@ DROP TRIGGER IF EXISTS ${ad};`);
12543
12593
  * untyped fact over the effective manifest's node-type slugs plus the
12544
12594
  * reserved abstain sentinel. Accepted answers go through
12545
12595
  * `_applyOntologyBackfillBatch` exactly like LLM classifications. No edges
12546
- * are proposed. Abstains and low-confidence answers are cooldown-stamped
12596
+ * are proposed unless `systemOne.edges` is `'auto'`; under `'auto'` the
12597
+ * classifier screens per-fact edge questions against
12598
+ * `systemOne.minConfidence.edges` (an explicit floor; missing → warn and
12599
+ * `'llm'`). Confident "yes" answers (`p > 0.5 && p >= floor`) apply,
12600
+ * confident "no" answers (`p < 0.5 && 1 - p >= floor`) are terminal, and
12601
+ * everything else (including exactly `p = 0.5`) plus invalid edge answers
12602
+ * fall through to the generative step. Edge outcomes are evaluated only for
12603
+ * typing-ACCEPTED facts. Abstains and low-confidence answers are cooldown-stamped
12547
12604
  * omissions under `onLowConfidence: 'leave'`; under `'llm'` they are
12548
12605
  * returned un-stamped in `escalated` for the generative step. Always
12549
12606
  * returns the `OntologyBackfillResult` for its step plus escalation state.
12550
12607
  */
12551
- async _runClassifierBackfill(entityId, candidates, manifest, now, recheckCutoff, meter, trigger) {
12608
+ async _runClassifierBackfill(entityId, candidates, manifest, now, recheckCutoff, meter, trigger, shortlistK, edgeSiteMode, edgeMinConfidence) {
12552
12609
  const minConfidence = resolveTypingMinConfidence(this.options.config);
12553
12610
  const rawConcurrency = this.options.config?.chunkConcurrency ?? 1;
12554
12611
  const concurrency = Number.isFinite(rawConcurrency) && rawConcurrency >= 1 ? Math.floor(rawConcurrency) : 1;
@@ -12558,17 +12615,65 @@ DROP TRIGGER IF EXISTS ${ad};`);
12558
12615
  instructions: `Choose the ontology node type that best describes this fact, or choose "${ONTOLOGY_ABSTAIN_SENTINEL}" if none of the listed types fits.
12559
12616
  ` + manifest.node_types.map((n) => `- ${n.type}: ${n.description}`).join("\n")
12560
12617
  };
12618
+ const edgeScreen = /* @__PURE__ */ new Map();
12619
+ if (edgeSiteMode === "auto" && (manifest.edge_types ?? []).length > 0) {
12620
+ const pool = await this.entryRepo.findShortlistRowsByEntityId(entityId);
12621
+ const poolTitleCounts = /* @__PURE__ */ new Map();
12622
+ for (const r of pool) {
12623
+ const k = normalizeTitleKey(r.title);
12624
+ poolTitleCounts.set(k, (poolTitleCounts.get(k) ?? 0) + 1);
12625
+ }
12626
+ const batchTitleKeys = new Set(candidates.map((f) => normalizeTitleKey(f.title)));
12627
+ const collides = (title) => {
12628
+ const k = normalizeTitleKey(title);
12629
+ return (poolTitleCounts.get(k) ?? 0) > 1 || batchTitleKeys.has(k);
12630
+ };
12631
+ const scorer = createShortlistScorer(pool);
12632
+ const edgeTypeNames = [...new Set(manifest.edge_types.map((e) => e.type))];
12633
+ for (const fact of candidates) {
12634
+ const ranked = buildShortlist({ title: fact.title, body: fact.body }, pool, shortlistK, scorer).filter((row) => !collides(row.title));
12635
+ const questions = {};
12636
+ const keyMap = /* @__PURE__ */ new Map();
12637
+ for (const row of ranked) {
12638
+ for (const edgeType of edgeTypeNames) {
12639
+ const definitions = manifest.edge_types.filter(
12640
+ (e) => e.type === edgeType && typeSatisfies(e.target_type, row.okf_type, manifest)
12641
+ );
12642
+ if (definitions.length === 0) continue;
12643
+ const key = `edge:${edgeType}:${row.id}`;
12644
+ const descriptions = [...new Set(definitions.map((d) => d.description))].join(" / ");
12645
+ questions[key] = {
12646
+ kind: "binary",
12647
+ instructions: `Does this fact have the "${edgeType}" relationship (${descriptions}) to the existing fact titled "${row.title}"?`
12648
+ };
12649
+ keyMap.set(key, { definitions, candidate: { id: row.id, title: row.title, okf_type: row.okf_type } });
12650
+ }
12651
+ }
12652
+ if (keyMap.size > 0) edgeScreen.set(fact.id, { questions, keyMap });
12653
+ }
12654
+ }
12561
12655
  let stopped;
12656
+ const retriedFacts = /* @__PURE__ */ new Set();
12562
12657
  const outcomes = await withConcurrency(
12563
12658
  candidates.map((fact) => async () => {
12564
12659
  if (stopped) return { fact, kind: "unattempted" };
12660
+ const edgeEntry = edgeScreen.get(fact.id);
12661
+ const ask = (questions) => callClassify(
12662
+ this.options,
12663
+ { operation: "ontologyBackfill", entityId, trigger, meter },
12664
+ { state: classifierStateForFact(fact), questions }
12665
+ );
12565
12666
  let response;
12667
+ let screened = edgeEntry !== void 0;
12566
12668
  try {
12567
- response = await callClassify(
12568
- this.options,
12569
- { operation: "ontologyBackfill", entityId, trigger, meter },
12570
- { state: classifierStateForFact(fact), questions: { okf_type: question } }
12571
- );
12669
+ try {
12670
+ response = await ask({ okf_type: question, ...edgeEntry?.questions ?? {} });
12671
+ } catch (err) {
12672
+ if (!edgeEntry || err instanceof WikiBudgetExhausted || !isContextOverflowError(err)) throw err;
12673
+ response = await ask({ okf_type: question });
12674
+ screened = false;
12675
+ retriedFacts.add(fact.id);
12676
+ }
12572
12677
  } catch (err) {
12573
12678
  if (err instanceof WikiBudgetExhausted) {
12574
12679
  stopped ?? (stopped = err);
@@ -12582,17 +12687,54 @@ DROP TRIGGER IF EXISTS ${ad};`);
12582
12687
  if (checked.answer.kind !== "choice") return { fact, kind: "invalid", reason: "kind_mismatch" };
12583
12688
  if (isReservedAbstainSlug(checked.answer.choice)) return { fact, kind: "abstain" };
12584
12689
  if (checked.answer.confidence < minConfidence) return { fact, kind: "low_confidence" };
12585
- return { fact, kind: "accepted", okfType: checked.answer.choice };
12690
+ const okfType = checked.answer.choice;
12691
+ if (!screened || !edgeEntry || typeof edgeMinConfidence !== "number") return { fact, kind: "accepted", okfType };
12692
+ const floor = edgeMinConfidence;
12693
+ const edges = [];
12694
+ const edgeCandidateIds = /* @__PURE__ */ Object.create(null);
12695
+ let evaluated = 0;
12696
+ let uncertain = 0;
12697
+ let invalid = 0;
12698
+ let missing = 0;
12699
+ for (const [key, { definitions, candidate }] of edgeEntry.keyMap) {
12700
+ if (!definitions.some((d) => typeSatisfies(d.source_type, okfType, manifest))) continue;
12701
+ evaluated++;
12702
+ const answer = validateClassifierAnswer(response, key, edgeEntry.questions[key]);
12703
+ if (!answer.ok) {
12704
+ if (answer.reason === "missing_answer") missing++;
12705
+ else invalid++;
12706
+ continue;
12707
+ }
12708
+ if (answer.answer.kind !== "binary") {
12709
+ invalid++;
12710
+ continue;
12711
+ }
12712
+ const p = answer.answer.probability;
12713
+ if (p > 0.5 && p >= floor) {
12714
+ edges.push({ edge_type: definitions[0].type, target_title: candidate.title });
12715
+ edgeCandidateIds[normalizeTitleKey(candidate.title)] = candidate.id;
12716
+ } else if (p < 0.5 && 1 - p >= floor) continue;
12717
+ else uncertain++;
12718
+ }
12719
+ const edgeStats = { uncertain, invalid, missing, allMissing: evaluated > 0 && missing === evaluated };
12720
+ if (edgeStats.allMissing) return { fact, kind: "accepted", okfType, edgeStats };
12721
+ if (uncertain > 0 || invalid > 0 || missing > 0) return { fact, kind: "accepted", okfType, fallthrough: true, edgeStats };
12722
+ return { fact, kind: "accepted", okfType, ...edges.length > 0 ? { edges, edgeCandidateIds } : {} };
12586
12723
  }),
12587
12724
  concurrency
12588
12725
  );
12589
12726
  const escalate = this.resolveSystemOneOnLowConfidence() === "llm";
12590
- const escalated = escalate ? outcomes.filter((o) => o.kind === "abstain" || o.kind === "low_confidence").map((o) => o.fact) : [];
12591
- const isEscalated = (o) => escalate && (o.kind === "abstain" || o.kind === "low_confidence");
12727
+ const isEscalated = (o) => o.kind === "accepted" && o.fallthrough === true || escalate && (o.kind === "abstain" || o.kind === "low_confidence");
12728
+ const escalated = outcomes.filter(isEscalated).map((o) => o.fact);
12592
12729
  const attempted = outcomes.filter((o) => o.kind !== "threw" && o.kind !== "unattempted" && !isEscalated(o)).map((o) => o.fact);
12593
12730
  const unattemptedCount = outcomes.filter((o) => o.kind === "unattempted").length;
12594
12731
  const skipped = outcomes.filter((o) => o.kind === "threw" || o.kind === "overflow_skip").length;
12595
- const classifications = outcomes.filter((o) => o.kind === "accepted").map((o) => ({ id: o.fact.id, okf_type: o.okfType }));
12732
+ const classifications = outcomes.filter((o) => o.kind === "accepted" && o.fallthrough !== true).map((o) => ({
12733
+ id: o.fact.id,
12734
+ okf_type: o.okfType,
12735
+ // An outcome carries `edges` only when the site is 'auto'.
12736
+ ...o.edges && o.edges.length > 0 ? { edges: o.edges, edgeCandidateIds: o.edgeCandidateIds } : {}
12737
+ }));
12596
12738
  const invalidCount = outcomes.filter((o) => o.kind === "invalid").length;
12597
12739
  const abstainCount = outcomes.filter((o) => o.kind === "abstain" && !isEscalated(o)).length;
12598
12740
  let typed = 0;
@@ -12617,7 +12759,21 @@ DROP TRIGGER IF EXISTS ${ad};`);
12617
12759
  const diagBuffer = new DiagnosticBuffer();
12618
12760
  const diagBase = { entityId, operation: "ontologyBackfill", trigger };
12619
12761
  for (const o of outcomes) {
12620
- if (o.kind === "abstain") {
12762
+ if (retriedFacts.has(o.fact.id)) {
12763
+ diagBuffer.push({ ...diagBase, code: "context_overflow_skipped", detail: { factId: o.fact.id, reason: "edge_screen_overflow_retry" } });
12764
+ }
12765
+ if (o.kind === "accepted" && o.edgeStats) {
12766
+ const { invalid, missing, allMissing } = o.edgeStats;
12767
+ const code = allMissing || invalid > 0 || missing > 0 ? "classification_invalid" : "classification_low_confidence";
12768
+ diagBuffer.push({
12769
+ ...diagBase,
12770
+ code,
12771
+ detail: {
12772
+ factId: o.fact.id,
12773
+ reason: allMissing ? "edge_answers_missing" : code === "classification_invalid" ? "edge_answer_invalid" : "edge_uncertain"
12774
+ }
12775
+ });
12776
+ } else if (o.kind === "abstain") {
12621
12777
  if (isEscalated(o)) continue;
12622
12778
  diagBuffer.push({ ...diagBase, code: "classification_abstained", detail: { factId: o.fact.id, writer: "classifier" } });
12623
12779
  } else if (o.kind === "low_confidence") {
@@ -12752,16 +12908,41 @@ DROP TRIGGER IF EXISTS ${ad};`);
12752
12908
  });
12753
12909
  titleIndex.set(normalizeTitleKey(fact.title), { id: fact.id, okf_type: normalized.okf_type });
12754
12910
  if (normalized.edges.length > 0) {
12755
- pendingEdges.push({ sourceId: fact.id, sourceType: normalized.okf_type, edges: normalized.edges });
12911
+ pendingEdges.push({
12912
+ sourceId: fact.id,
12913
+ sourceType: normalized.okf_type,
12914
+ edges: normalized.edges,
12915
+ candidateIds: classification.edgeCandidateIds
12916
+ });
12756
12917
  }
12757
12918
  }
12758
12919
  for (const item of pendingEdges) {
12759
12920
  const resolveDrops = [];
12921
+ let edgesToResolve = item.edges;
12922
+ const screenedIds = item.candidateIds;
12923
+ if (screenedIds) {
12924
+ edgesToResolve = [];
12925
+ for (const edge of item.edges) {
12926
+ const key = normalizeTitleKey(edge.target_title);
12927
+ const screened = screenedIds[key];
12928
+ if (screened !== void 0 && titleIndex.get(key)?.id !== screened) {
12929
+ resolveDrops.push({
12930
+ reason: "target_not_found",
12931
+ sourceId: item.sourceId,
12932
+ edgeType: edge.edge_type,
12933
+ sourceNodeType: item.sourceType,
12934
+ targetNodeType: null
12935
+ });
12936
+ } else {
12937
+ edgesToResolve.push(edge);
12938
+ }
12939
+ }
12940
+ }
12760
12941
  const added = await ontologyService.resolveAndPersistEdges(
12761
12942
  entityId,
12762
12943
  item.sourceId,
12763
12944
  item.sourceType,
12764
- item.edges,
12945
+ edgesToResolve,
12765
12946
  manifest,
12766
12947
  titleIndex,
12767
12948
  tx,
@@ -18220,8 +18401,10 @@ exports.parseEmbedding = parseEmbedding;
18220
18401
  exports.parseOkfBundle = parseOkfBundle;
18221
18402
  exports.resolveContextBudget = resolveContextBudget;
18222
18403
  exports.resolveDefaultChunkLength = resolveDefaultChunkLength;
18404
+ exports.resolveEdgesMinConfidence = resolveEdgesMinConfidence;
18223
18405
  exports.resolveMaxPromptChars = resolveMaxPromptChars;
18224
18406
  exports.resolveOntologyJobDefaults = resolveOntologyJobDefaults;
18407
+ exports.resolveSystemOneEdges = resolveSystemOneEdges;
18225
18408
  exports.resolveSystemOneTyping = resolveSystemOneTyping;
18226
18409
  exports.resolveTypingMinConfidence = resolveTypingMinConfidence;
18227
18410
  exports.safeSlice = safeSlice;