@equationalapplications/core-llm-wiki 9.5.1 → 9.5.3

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, R as ReadOptions, S as SQLiteAdapter, W as WikiOptions, c as WikiMemory } from './testing-BZyrIoJp.mjs';
2
- export { C as CheckpointIncompleteError, d as ChunkFailure, e as ClassifierAnswer, f as ClassifierQuestion, g as ClassifyRequest, h as ClassifyResponse, D as DegradedRecord, i as DraftPage, E as EmbedFactResult, j as EmbedFailureKind, k as EmbeddingMarkerKind, l as EntityMaintenanceReport, m as EntityStatus, n as EraseReport, o as EraseStepError, p as ExtractedFact, q as ExtractedFactEdge, r as ExtractedFactWithOntology, s as ExtractedTask, t as ForgetParams, u as ForgetResult, v as GraphTraversalOptions, w as GroundingConfig, H as HEAL_BATCH_SIZE, x as HEAL_RECHECK_MS, y as HOOK_TIMEOUT_MARKER, z as HealResult, I as ImportDumpResult, A as IngestDocumentResult, L as LLMProvider, B as LibrarianConfig, J as LibrarianGateConfig, K as LockedMaintenanceJob, N as MaintenanceJob, P as MaintenanceStopReason, Q as MemoryDumpEntity, T as MigrationPolicy, U as ONTOLOGY_BACKFILL_BATCH_SIZE, V as ONTOLOGY_BACKFILL_MAX_PROMPT_CHARS, X as ONTOLOGY_BACKFILL_RECHECK_MS, Y as OntologyBackfillResult, Z as OntologyConfig, _ as OntologyEdgeType, $ as OntologyManifest, a0 as OntologyNodeType, a1 as OntologyPromptContext, a2 as OntologyUpdates, a3 as PendingMaintenance, a4 as PendingMigrationWork, a5 as PendingSourceStatus, a6 as PromptOverrides, a7 as PromptService, a8 as PrunePartialFailureError, a9 as ReembedResult, aa as RememberInput, ab as RunPendingMaintenanceOptions, ac as RunPendingMaintenanceResult, ad as SourcePassage, ae as StoreSourceResult, af as StoredSource, ag as StoredSourceDump, ah as StoredSourceSummary, ai as SupersedeReplacement, aj as VectorRanker, ak as VectorRankerFallback, al as VectorRankerRankArgs, am as VectorRankerSemanticResult, an as WikiBusyError, ao as WikiBusyOperation, ap as WikiCheckpoint, aq as WikiConfig, ar as WikiDiagnostic, as as WikiDiagnosticCode, at as WikiDiagnosticDetail, au as WikiDiagnosticOperation, av as WikiDiagnosticSeverity, aw as WikiDiagnosticTrigger, ax as WikiDraftNotFound, ay as WikiDuplicateHashError, az as WikiEdge, aA as WikiEvent, aB as WikiExternalDeletionError, aC as WikiFact, aD as WikiGraphNodeOwnershipConflict, aE as WikiIngestEmptyError, aF as WikiInstructions, aG as WikiInvalidReadOptions, aH as WikiLintReport, aI as WikiMemoryTestAccess, aJ as WikiMigrationRequiredError, aK as WikiOutboxEvent, aL as WikiParseError, aM as WikiSearchUnavailableError, aN as WikiSourcePointer, aO as WikiSourceRefHashCollision, aP as WikiStrictOntologyViolation, aQ as WikiSupersedeError, aR as WikiSupersedeReason, aS as WikiTask, aT as WikiTransactionError, aU as isWikiSearchUnavailableError, aV as validateManifest } from './testing-BZyrIoJp.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-BA6CedgZ.mjs';
2
+ export { C as CheckpointIncompleteError, d as ChunkFailure, e as ClassifierAnswer, f as ClassifierQuestion, g as ClassifyRequest, h as ClassifyResponse, D as DegradedRecord, i as DraftPage, E as EmbedFactResult, j as EmbedFailureKind, k as EmbeddingMarkerKind, l as EntityMaintenanceReport, m as EntityStatus, n as EraseReport, o as EraseStepError, p as ExtractedFact, q as ExtractedFactEdge, r as ExtractedFactWithOntology, s as ExtractedTask, t as ForgetParams, u as ForgetResult, v as GraphTraversalOptions, w as GroundingConfig, H as HEAL_BATCH_SIZE, x as HEAL_RECHECK_MS, y as HOOK_TIMEOUT_MARKER, z as HealResult, I as ImportDumpResult, A as IngestDocumentResult, L as LLMProvider, B as LibrarianConfig, J as LibrarianGateConfig, K as LockedMaintenanceJob, N as MaintenanceJob, P as MaintenanceStopReason, Q as MemoryDumpEntity, T as MigrationPolicy, U as ONTOLOGY_BACKFILL_BATCH_SIZE, V as ONTOLOGY_BACKFILL_MAX_PROMPT_CHARS, X as ONTOLOGY_BACKFILL_RECHECK_MS, Y as OntologyBackfillResult, Z as OntologyConfig, _ as OntologyEdgeType, $ as OntologyManifest, a0 as OntologyNodeType, a1 as OntologyPromptContext, a2 as OntologyUpdates, a3 as PendingMaintenance, a4 as PendingMigrationWork, a5 as PendingSourceStatus, a6 as PromptOverrides, a7 as PromptService, a8 as PrunePartialFailureError, a9 as ReembedResult, aa as RememberInput, ab as RunPendingMaintenanceOptions, ac as RunPendingMaintenanceResult, ad as SourcePassage, ae as StoreSourceResult, af as StoredSource, ag as StoredSourceDump, ah as StoredSourceSummary, ai as SupersedeReplacement, aj as VectorRanker, ak as VectorRankerFallback, al as VectorRankerRankArgs, am as VectorRankerSemanticResult, an as WikiBusyError, ao as WikiBusyOperation, ap as WikiCheckpoint, aq as WikiConfig, ar as WikiDiagnostic, as as WikiDiagnosticCode, at as WikiDiagnosticDetail, au as WikiDiagnosticOperation, av as WikiDiagnosticSeverity, aw as WikiDiagnosticTrigger, ax as WikiDraftNotFound, ay as WikiDuplicateHashError, az as WikiEdge, aA as WikiEvent, aB as WikiExternalDeletionError, aC as WikiFact, aD as WikiGraphNodeOwnershipConflict, aE as WikiIngestEmptyError, aF as WikiInstructions, aG as WikiInvalidReadOptions, aH as WikiLintReport, aI as WikiMemoryTestAccess, aJ as WikiMigrationRequiredError, aK as WikiOutboxEvent, aL as WikiParseError, aM as WikiSearchUnavailableError, aN as WikiSourcePointer, aO as WikiSourceRefHashCollision, aP as WikiStrictOntologyViolation, aQ as WikiSupersedeError, aR as WikiSupersedeReason, aS as WikiTask, aT as WikiTransactionError, aU as isWikiSearchUnavailableError, aV as validateManifest } from './testing-BA6CedgZ.mjs';
3
3
  import { OkfFile } from '@equationalapplications/core-okf';
4
4
 
5
5
  /**
@@ -105,6 +105,11 @@ type GetRandomValues = (bytes: Uint8Array) => void;
105
105
  */
106
106
  declare function configureRandomSource(fn: GetRandomValues | null): void;
107
107
 
108
+ declare function validUsage(u: unknown): u is {
109
+ inputTokens: number;
110
+ outputTokens: number;
111
+ };
112
+
108
113
  /**
109
114
  * Default maximum characters per chunk that `ingestDocument` uses when a
110
115
  * caller doesn't override `maxChunkLength` (directly or via
@@ -166,5 +171,5 @@ declare const ONTOLOGY_BACKFILL_SYSTEM_PROMPT = "You are a knowledge classificat
166
171
 
167
172
  declare function createWiki(db: SQLiteAdapter, options: WikiOptions): WikiMemory;
168
173
 
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 };
174
+ 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, validUsage, validateLibrarianPromptTemplate };
170
175
  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, O as OntologyMode, R as ReadOptions, S as SQLiteAdapter, W as WikiOptions, c as WikiMemory } from './testing-BZyrIoJp.js';
2
- export { C as CheckpointIncompleteError, d as ChunkFailure, e as ClassifierAnswer, f as ClassifierQuestion, g as ClassifyRequest, h as ClassifyResponse, D as DegradedRecord, i as DraftPage, E as EmbedFactResult, j as EmbedFailureKind, k as EmbeddingMarkerKind, l as EntityMaintenanceReport, m as EntityStatus, n as EraseReport, o as EraseStepError, p as ExtractedFact, q as ExtractedFactEdge, r as ExtractedFactWithOntology, s as ExtractedTask, t as ForgetParams, u as ForgetResult, v as GraphTraversalOptions, w as GroundingConfig, H as HEAL_BATCH_SIZE, x as HEAL_RECHECK_MS, y as HOOK_TIMEOUT_MARKER, z as HealResult, I as ImportDumpResult, A as IngestDocumentResult, L as LLMProvider, B as LibrarianConfig, J as LibrarianGateConfig, K as LockedMaintenanceJob, N as MaintenanceJob, P as MaintenanceStopReason, Q as MemoryDumpEntity, T as MigrationPolicy, U as ONTOLOGY_BACKFILL_BATCH_SIZE, V as ONTOLOGY_BACKFILL_MAX_PROMPT_CHARS, X as ONTOLOGY_BACKFILL_RECHECK_MS, Y as OntologyBackfillResult, Z as OntologyConfig, _ as OntologyEdgeType, $ as OntologyManifest, a0 as OntologyNodeType, a1 as OntologyPromptContext, a2 as OntologyUpdates, a3 as PendingMaintenance, a4 as PendingMigrationWork, a5 as PendingSourceStatus, a6 as PromptOverrides, a7 as PromptService, a8 as PrunePartialFailureError, a9 as ReembedResult, aa as RememberInput, ab as RunPendingMaintenanceOptions, ac as RunPendingMaintenanceResult, ad as SourcePassage, ae as StoreSourceResult, af as StoredSource, ag as StoredSourceDump, ah as StoredSourceSummary, ai as SupersedeReplacement, aj as VectorRanker, ak as VectorRankerFallback, al as VectorRankerRankArgs, am as VectorRankerSemanticResult, an as WikiBusyError, ao as WikiBusyOperation, ap as WikiCheckpoint, aq as WikiConfig, ar as WikiDiagnostic, as as WikiDiagnosticCode, at as WikiDiagnosticDetail, au as WikiDiagnosticOperation, av as WikiDiagnosticSeverity, aw as WikiDiagnosticTrigger, ax as WikiDraftNotFound, ay as WikiDuplicateHashError, az as WikiEdge, aA as WikiEvent, aB as WikiExternalDeletionError, aC as WikiFact, aD as WikiGraphNodeOwnershipConflict, aE as WikiIngestEmptyError, aF as WikiInstructions, aG as WikiInvalidReadOptions, aH as WikiLintReport, aI as WikiMemoryTestAccess, aJ as WikiMigrationRequiredError, aK as WikiOutboxEvent, aL as WikiParseError, aM as WikiSearchUnavailableError, aN as WikiSourcePointer, aO as WikiSourceRefHashCollision, aP as WikiStrictOntologyViolation, aQ as WikiSupersedeError, aR as WikiSupersedeReason, aS as WikiTask, aT as WikiTransactionError, aU as isWikiSearchUnavailableError, aV as validateManifest } from './testing-BZyrIoJp.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-BA6CedgZ.js';
2
+ export { C as CheckpointIncompleteError, d as ChunkFailure, e as ClassifierAnswer, f as ClassifierQuestion, g as ClassifyRequest, h as ClassifyResponse, D as DegradedRecord, i as DraftPage, E as EmbedFactResult, j as EmbedFailureKind, k as EmbeddingMarkerKind, l as EntityMaintenanceReport, m as EntityStatus, n as EraseReport, o as EraseStepError, p as ExtractedFact, q as ExtractedFactEdge, r as ExtractedFactWithOntology, s as ExtractedTask, t as ForgetParams, u as ForgetResult, v as GraphTraversalOptions, w as GroundingConfig, H as HEAL_BATCH_SIZE, x as HEAL_RECHECK_MS, y as HOOK_TIMEOUT_MARKER, z as HealResult, I as ImportDumpResult, A as IngestDocumentResult, L as LLMProvider, B as LibrarianConfig, J as LibrarianGateConfig, K as LockedMaintenanceJob, N as MaintenanceJob, P as MaintenanceStopReason, Q as MemoryDumpEntity, T as MigrationPolicy, U as ONTOLOGY_BACKFILL_BATCH_SIZE, V as ONTOLOGY_BACKFILL_MAX_PROMPT_CHARS, X as ONTOLOGY_BACKFILL_RECHECK_MS, Y as OntologyBackfillResult, Z as OntologyConfig, _ as OntologyEdgeType, $ as OntologyManifest, a0 as OntologyNodeType, a1 as OntologyPromptContext, a2 as OntologyUpdates, a3 as PendingMaintenance, a4 as PendingMigrationWork, a5 as PendingSourceStatus, a6 as PromptOverrides, a7 as PromptService, a8 as PrunePartialFailureError, a9 as ReembedResult, aa as RememberInput, ab as RunPendingMaintenanceOptions, ac as RunPendingMaintenanceResult, ad as SourcePassage, ae as StoreSourceResult, af as StoredSource, ag as StoredSourceDump, ah as StoredSourceSummary, ai as SupersedeReplacement, aj as VectorRanker, ak as VectorRankerFallback, al as VectorRankerRankArgs, am as VectorRankerSemanticResult, an as WikiBusyError, ao as WikiBusyOperation, ap as WikiCheckpoint, aq as WikiConfig, ar as WikiDiagnostic, as as WikiDiagnosticCode, at as WikiDiagnosticDetail, au as WikiDiagnosticOperation, av as WikiDiagnosticSeverity, aw as WikiDiagnosticTrigger, ax as WikiDraftNotFound, ay as WikiDuplicateHashError, az as WikiEdge, aA as WikiEvent, aB as WikiExternalDeletionError, aC as WikiFact, aD as WikiGraphNodeOwnershipConflict, aE as WikiIngestEmptyError, aF as WikiInstructions, aG as WikiInvalidReadOptions, aH as WikiLintReport, aI as WikiMemoryTestAccess, aJ as WikiMigrationRequiredError, aK as WikiOutboxEvent, aL as WikiParseError, aM as WikiSearchUnavailableError, aN as WikiSourcePointer, aO as WikiSourceRefHashCollision, aP as WikiStrictOntologyViolation, aQ as WikiSupersedeError, aR as WikiSupersedeReason, aS as WikiTask, aT as WikiTransactionError, aU as isWikiSearchUnavailableError, aV as validateManifest } from './testing-BA6CedgZ.js';
3
3
  import { OkfFile } from '@equationalapplications/core-okf';
4
4
 
5
5
  /**
@@ -105,6 +105,11 @@ type GetRandomValues = (bytes: Uint8Array) => void;
105
105
  */
106
106
  declare function configureRandomSource(fn: GetRandomValues | null): void;
107
107
 
108
+ declare function validUsage(u: unknown): u is {
109
+ inputTokens: number;
110
+ outputTokens: number;
111
+ };
112
+
108
113
  /**
109
114
  * Default maximum characters per chunk that `ingestDocument` uses when a
110
115
  * caller doesn't override `maxChunkLength` (directly or via
@@ -166,5 +171,5 @@ declare const ONTOLOGY_BACKFILL_SYSTEM_PROMPT = "You are a knowledge classificat
166
171
 
167
172
  declare function createWiki(db: SQLiteAdapter, options: WikiOptions): WikiMemory;
168
173
 
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 };
174
+ 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, validUsage, validateLibrarianPromptTemplate };
170
175
  export type { FormatOkfBundleOptions, LibrarianOptions, LibrarianPromptVariables, OkfFormatProfile, OkfImportOptions };
package/dist/index.js CHANGED
@@ -30,6 +30,7 @@ var SEVERITY = {
30
30
  grounding_failed: "warn",
31
31
  classification_low_confidence: "info",
32
32
  classification_invalid: "warn",
33
+ context_overflow_skipped: "warn",
33
34
  llm_usage: "info",
34
35
  librarian_gate: "info",
35
36
  librarian_op_rejected: "warn",
@@ -75,6 +76,7 @@ var MESSAGE = {
75
76
  grounding_failed: "A fact carried evidence not found in its source and was stored as a draft.",
76
77
  classification_low_confidence: "A classifier answer was below the confidence threshold and was not applied.",
77
78
  classification_invalid: "A classifier answer was invalid and was not applied.",
79
+ context_overflow_skipped: "An item (fact or event) was skipped because the model input exceeded its context window.",
78
80
  llm_usage: "An LLM call completed; token usage attached.",
79
81
  librarian_gate: "Librarian gate outcome counts for one pass.",
80
82
  librarian_op_rejected: "A librarian reconciliation op was invalid and the candidate was added instead.",
@@ -7949,6 +7951,31 @@ async function callLlm(options, ctx, prompts) {
7949
7951
  }
7950
7952
  return text;
7951
7953
  }
7954
+ async function callClassify(options, ctx, request) {
7955
+ const inputEstimate = estimateTokens(request.state) + estimateTokens(JSON.stringify(request.questions));
7956
+ if (ctx.meter && !ctx.meter.fits(inputEstimate)) {
7957
+ throw new WikiBudgetExhausted(inputEstimate, ctx.meter.remaining);
7958
+ }
7959
+ const provider = options.llmProvider;
7960
+ if (typeof provider.classify !== "function") {
7961
+ throw new TypeError("callClassify requires a provider with classify()");
7962
+ }
7963
+ const response = await provider.classify(request);
7964
+ const reported = validUsage(response?.usage) ? response.usage : void 0;
7965
+ const outputEstimate = estimateTokens(JSON.stringify(response?.answers ?? {}));
7966
+ const record = reported ? { inputTokens: reported.inputTokens, outputTokens: reported.outputTokens, estimated: false } : { inputTokens: inputEstimate, outputTokens: outputEstimate, estimated: true };
7967
+ ctx.meter?.record(record);
7968
+ if (options.config?.reportLlmUsage === true) {
7969
+ emitDiagnostic(options, {
7970
+ code: "llm_usage",
7971
+ operation: ctx.operation,
7972
+ trigger: ctx.trigger,
7973
+ entityId: ctx.entityId,
7974
+ detail: { inputTokens: record.inputTokens, outputTokens: record.outputTokens, estimated: record.estimated }
7975
+ });
7976
+ }
7977
+ return response;
7978
+ }
7952
7979
 
7953
7980
  // src/services/IngestionService.ts
7954
7981
  var LLM_PASS_DIAGNOSTIC_CODES = ["ingest_chunk_failed", "fact_rejected", "fact_deduplicated"];
@@ -9379,6 +9406,29 @@ var TRUNCATION_PATTERNS = [
9379
9406
  /finish[_ ]?reason/i
9380
9407
  ];
9381
9408
  var EXCEEDS_LIMIT_PATTERN = /exceed[a-z]*[^.]{0,40}\b(model|context)?[ _-]?limit/i;
9409
+ var RATE_LIMIT_PATTERN = /\b(?:status|http|code|error)[^\d]{0,10}429\b|\b429[ _-]?too[ _-]?many[ _-]?requests\b|\b(rate[ _-]?limit|too many requests|(tokens?|requests?)[ _-]?per[ _-]?(minute|min)\b|retry[ _-]?after|quota exceeded)\b/i;
9410
+ var CONTEXT_OVERFLOW_PATTERNS = [
9411
+ /maximum context length/i,
9412
+ /context[_ ]?length[_ ]?exceeded/i,
9413
+ /prompt is too long/i,
9414
+ /input (token count|is too long)/i,
9415
+ /exceeds? the (available )?context( size)?/i,
9416
+ // Tail requires a context-window clause (context|maximum), NOT bare `token`:
9417
+ // a 429 body like "input exceeds the tokens-per-minute limit" must NOT
9418
+ // classify as input overflow (it would split the batch and stamp a cooldown).
9419
+ /(input|prompt).{0,40}exceed(s|ed)? .{0,30}(context|maximum)/i,
9420
+ /context limit/i,
9421
+ /too long for (the )?requested model/i,
9422
+ // vLLM dual-match wording (errata E2 ruling): the regex ENFORCES the dual-match —
9423
+ // "max_tokens ... too large" PLUS a context clause; a bare message is NOT overflow
9424
+ /max[_ ]?tokens?.{0,40}too large.{0,80}context/i
9425
+ ];
9426
+ function isContextOverflowError(err) {
9427
+ const message = getErrorMessage(err);
9428
+ if (message === void 0) return false;
9429
+ if (RATE_LIMIT_PATTERN.test(message)) return false;
9430
+ return CONTEXT_OVERFLOW_PATTERNS.some((p) => p.test(message));
9431
+ }
9382
9432
  function getErrorMessage(err) {
9383
9433
  try {
9384
9434
  return err instanceof Error ? err.message : String(err ?? "");
@@ -9389,12 +9439,14 @@ function getErrorMessage(err) {
9389
9439
  function isTruncationError(err) {
9390
9440
  const message = getErrorMessage(err);
9391
9441
  if (message === void 0) return false;
9442
+ if (RATE_LIMIT_PATTERN.test(message)) return false;
9392
9443
  if (EXCEEDS_LIMIT_PATTERN.test(message)) return false;
9393
9444
  return TRUNCATION_PATTERNS.some((pattern) => pattern.test(message));
9394
9445
  }
9395
9446
  function isConfigError(err) {
9396
9447
  const message = getErrorMessage(err);
9397
9448
  if (message === void 0) return false;
9449
+ if (RATE_LIMIT_PATTERN.test(message)) return false;
9398
9450
  return EXCEEDS_LIMIT_PATTERN.test(message);
9399
9451
  }
9400
9452
  function initialBatchSize(maxOutputTokens) {
@@ -9408,7 +9460,7 @@ function initialBatchSize(maxOutputTokens) {
9408
9460
  }
9409
9461
  var promptLength = (prompts) => prompts.systemPrompt.length + prompts.userPrompt.length;
9410
9462
  async function runBatched(args) {
9411
- const { items, buildPrompt, call, parse, maxPromptChars, maxOutputTokens, onSkip } = args;
9463
+ const { items, buildPrompt, call, parse, maxPromptChars, maxOutputTokens, onSkip, supportsEscalation } = args;
9412
9464
  const results = [];
9413
9465
  const skipped = [];
9414
9466
  let batches = 0;
@@ -9442,17 +9494,17 @@ async function runBatched(args) {
9442
9494
  };
9443
9495
  const onFailure = async (batch, err, attemptLevel, fromCall) => {
9444
9496
  if (batch.length === 1) {
9445
- if (fromCall && isTruncationError(err) && attemptLevel < 3) {
9497
+ if (fromCall && (isContextOverflowError(err) ? supportsEscalation : isTruncationError(err)) && attemptLevel < 3) {
9446
9498
  await attempt(batch, void 0, attemptLevel + 1);
9447
9499
  } else {
9448
- const reason = fromCall && !isTruncationError(err) && !isConfigError(err) ? "call_error" : "non_convergent";
9500
+ const reason = fromCall && !isTruncationError(err) && !isConfigError(err) && !isContextOverflowError(err) ? "call_error" : "non_convergent";
9449
9501
  skipped.push({ item: batch[0], reason });
9450
9502
  settled.add(batch[0]);
9451
9503
  onSkip?.(batch[0], err);
9452
9504
  }
9453
9505
  return;
9454
9506
  }
9455
- if (fromCall && !isTruncationError(err)) throw err;
9507
+ if (fromCall && !isTruncationError(err) && !isContextOverflowError(err)) throw err;
9456
9508
  const mid = Math.ceil(batch.length / 2);
9457
9509
  if (mid < batchSize) batchSize = mid;
9458
9510
  let i = 0;
@@ -9706,6 +9758,8 @@ function parseValidFrom(v) {
9706
9758
  var OPS_MAX_EVENTS_PER_PASS = 50;
9707
9759
  var OPS_MAX_EXTRACT_CHARS = 24e3;
9708
9760
  var RESOLVE_RESERVE_FACTOR = 2;
9761
+ var MIN_SEGMENT_CHARS = 500;
9762
+ var MAX_SEGMENT_CALLS = 8;
9709
9763
  var estimatePrompt = (p) => estimateTokens(p.systemPrompt) + estimateTokens(p.userPrompt);
9710
9764
  async function selectBatch(deps, entityId, wm, meter, guidance) {
9711
9765
  const events = await deps.eventRepo.getAfter(entityId, wm, OPS_MAX_EVENTS_PER_PASS);
@@ -9729,9 +9783,158 @@ async function selectBatch(deps, entityId, wm, meter, guidance) {
9729
9783
  }
9730
9784
  return { batch };
9731
9785
  }
9786
+ function splitSummary(summary) {
9787
+ const mid = Math.floor(summary.length / 2);
9788
+ let cut = -1;
9789
+ for (let d = 0; d <= mid; d++) {
9790
+ if (/\s/.test(summary[mid - d] ?? "")) {
9791
+ cut = mid - d;
9792
+ break;
9793
+ }
9794
+ if (/\s/.test(summary[mid + d] ?? "")) {
9795
+ cut = mid + d;
9796
+ break;
9797
+ }
9798
+ }
9799
+ if (cut <= 0 || cut >= summary.length - 1) cut = mid;
9800
+ return [summary.slice(0, cut), summary.slice(cut)];
9801
+ }
9802
+ function dedupeByType(xs) {
9803
+ const seen = /* @__PURE__ */ new Set();
9804
+ return xs.filter((x) => seen.has(x.type) ? false : (seen.add(x.type), true));
9805
+ }
9806
+ function normalizeOntologyUpdates(raw) {
9807
+ if (typeof raw !== "object" || raw === null) return void 0;
9808
+ const r = raw;
9809
+ const pick = (v) => (Array.isArray(v) ? v : []).filter(
9810
+ (x) => !!x && typeof x === "object" && typeof x.type === "string" && x.type.length > 0
9811
+ );
9812
+ const node_types = pick(r.node_types);
9813
+ const edge_types = pick(r.edge_types);
9814
+ return {
9815
+ ...node_types.length ? { node_types } : {},
9816
+ ...edge_types.length ? { edge_types } : {}
9817
+ };
9818
+ }
9819
+ function mergeOutcomes(a, b) {
9820
+ if (a.groundingCorpus === null !== (b.groundingCorpus === null)) {
9821
+ throw new Error("ops extract: merge corpus invariant violated (only one half has a grounding corpus)");
9822
+ }
9823
+ const partOffset = a.groundingCorpus?.length ?? a.batch.length;
9824
+ const indexOffset = a.factItems;
9825
+ const candidates = [
9826
+ ...a.candidates,
9827
+ ...b.candidates.map((c) => ({
9828
+ ...c,
9829
+ index: c.index + indexOffset,
9830
+ sourcePartIndex: c.sourcePartIndex === null ? null : c.sourcePartIndex + partOffset
9831
+ }))
9832
+ ];
9833
+ let ontologyUpdates;
9834
+ if (a.ontologyUpdates || b.ontologyUpdates) {
9835
+ const nodes = dedupeByType([...a.ontologyUpdates?.node_types ?? [], ...b.ontologyUpdates?.node_types ?? []]);
9836
+ const edges = dedupeByType([...a.ontologyUpdates?.edge_types ?? [], ...b.ontologyUpdates?.edge_types ?? []]);
9837
+ ontologyUpdates = {
9838
+ ...nodes.length ? { node_types: nodes } : {},
9839
+ ...edges.length ? { edge_types: edges } : {}
9840
+ };
9841
+ }
9842
+ const shiftedDiags = b.diagnostics.map((d) => {
9843
+ const detail = d.detail;
9844
+ if (typeof detail?.itemIndex !== "number") return d;
9845
+ const off = d.code === "fact_rejected" ? a.factItems : d.code === "task_rejected" ? a.taskItems : 0;
9846
+ return off ? { ...d, detail: { ...detail, itemIndex: detail.itemIndex + off } } : d;
9847
+ });
9848
+ return {
9849
+ batch: [...a.batch, ...b.batch],
9850
+ candidates,
9851
+ tasks: [...a.tasks, ...b.tasks],
9852
+ ...ontologyUpdates ? { ontologyUpdates } : {},
9853
+ groundingCorpus: a.groundingCorpus || b.groundingCorpus ? [...a.groundingCorpus ?? [], ...b.groundingCorpus ?? []] : null,
9854
+ diagnostics: [...a.diagnostics, ...shiftedDiags],
9855
+ skippedEvents: a.skippedEvents + b.skippedEvents,
9856
+ factItems: a.factItems + b.factItems,
9857
+ taskItems: a.taskItems + b.taskItems
9858
+ };
9859
+ }
9860
+ async function extractWithOverflowRetry(deps, ctx, ontologyContext, batch, probe) {
9861
+ try {
9862
+ return await extractOnce(deps, ctx, ontologyContext, batch);
9863
+ } catch (err) {
9864
+ if (!isContextOverflowError(err)) throw err;
9865
+ if (!probe.checked) {
9866
+ probe.checked = true;
9867
+ const probePrompt = deps.promptService.buildOpsExtractPrompt(
9868
+ [{ ...batch[0], event: { ...batch[0].event, summary: "x" } }],
9869
+ ontologyContext,
9870
+ ctx.guidance
9871
+ );
9872
+ try {
9873
+ await callLlm(deps.options, { operation: "librarian", entityId: ctx.entityId, trigger: ctx.trigger, meter: ctx.meter }, probePrompt);
9874
+ } catch (e) {
9875
+ if (!isContextOverflowError(e)) throw e;
9876
+ throw new Error("ops extract: minimal-prompt probe also overflowed (fixed prompt part exceeds the model window?)");
9877
+ }
9878
+ }
9879
+ if (batch.length > 1) {
9880
+ const mid = Math.ceil(batch.length / 2);
9881
+ const a = await extractWithOverflowRetry(deps, ctx, ontologyContext, batch.slice(0, mid), probe);
9882
+ const b = await extractWithOverflowRetry(deps, ctx, ontologyContext, batch.slice(mid), probe);
9883
+ return mergeOutcomes(a, b);
9884
+ }
9885
+ const lone = batch[0];
9886
+ const skipDiag = () => ({
9887
+ entityId: ctx.entityId,
9888
+ operation: "librarian",
9889
+ trigger: ctx.trigger,
9890
+ code: "context_overflow_skipped",
9891
+ detail: { sourceRef: lone.event.id }
9892
+ });
9893
+ const segLabel = (label, n) => label.includes("#") ? `${label}.${n}` : `${label}#${n}`;
9894
+ let segCalls = 0;
9895
+ const extractSegment = async (label, text, alreadyOverflowed) => {
9896
+ if (!alreadyOverflowed) {
9897
+ if (segCalls >= MAX_SEGMENT_CALLS) return null;
9898
+ segCalls++;
9899
+ try {
9900
+ return await extractOnce(deps, ctx, ontologyContext, [{ label, at: lone.at, event: { ...lone.event, summary: text } }]);
9901
+ } catch (e) {
9902
+ if (!isContextOverflowError(e)) throw e;
9903
+ }
9904
+ }
9905
+ if (text.length < 2 * MIN_SEGMENT_CHARS) return null;
9906
+ const [h1, h2] = splitSummary(text);
9907
+ if (h1.length < MIN_SEGMENT_CHARS || h2.length < MIN_SEGMENT_CHARS) return null;
9908
+ const a = await extractSegment(segLabel(label, 1), h1, false);
9909
+ const b = await extractSegment(segLabel(label, 2), h2, false);
9910
+ if (a === "partial" || b === "partial") return "partial";
9911
+ if (!a && !b) return null;
9912
+ if (!a || !b) return "partial";
9913
+ return mergeOutcomes(a, b);
9914
+ };
9915
+ const merged = await extractSegment(lone.label, lone.event.summary, true);
9916
+ if (!merged || merged === "partial") {
9917
+ const corpus = deps.promptService.buildOpsExtractPrompt([lone], ontologyContext, ctx.guidance).groundingCorpus ?? null;
9918
+ return {
9919
+ batch: [lone],
9920
+ candidates: [],
9921
+ tasks: [],
9922
+ groundingCorpus: corpus,
9923
+ diagnostics: [skipDiag()],
9924
+ skippedEvents: 1,
9925
+ factItems: 0,
9926
+ taskItems: 0
9927
+ };
9928
+ }
9929
+ return { ...merged, batch: [lone] };
9930
+ }
9931
+ }
9732
9932
  async function runExtract(deps, ctx, batch) {
9933
+ const ontologyContext = await deps.ontologyService?.buildPromptContext(ctx.entityId) ?? null;
9934
+ return extractWithOverflowRetry(deps, ctx, ontologyContext, batch, { checked: false });
9935
+ }
9936
+ async function extractOnce(deps, ctx, ontologyContext, batch) {
9733
9937
  const { entityId, trigger } = ctx;
9734
- const ontologyContext = await deps.ontologyService?.buildPromptContext(entityId) ?? null;
9735
9938
  const prompt = deps.promptService.buildOpsExtractPrompt(batch, ontologyContext, ctx.guidance);
9736
9939
  const text = await callLlm(deps.options, { operation: "librarian", entityId, trigger, meter: ctx.meter }, prompt);
9737
9940
  const parsed = parseJsonResponse(text);
@@ -9773,13 +9976,17 @@ async function runExtract(deps, ctx, batch) {
9773
9976
  if (task) tasks.push(task);
9774
9977
  else diagnostics.push({ ...base, code: "task_rejected", detail: { itemIndex: index, reason: taskRejectionReason(raw) } });
9775
9978
  });
9979
+ const ontologyUpdates = normalizeOntologyUpdates(parsed.ontology_updates);
9776
9980
  return {
9777
9981
  batch,
9778
9982
  candidates,
9779
9983
  tasks,
9780
- ...parsed.ontology_updates ? { ontologyUpdates: parsed.ontology_updates } : {},
9984
+ ...ontologyUpdates ? { ontologyUpdates } : {},
9781
9985
  groundingCorpus: prompt.groundingCorpus ?? null,
9782
- diagnostics
9986
+ diagnostics,
9987
+ skippedEvents: 0,
9988
+ factItems: Array.isArray(parsed.facts) ? parsed.facts.length : 0,
9989
+ taskItems: Array.isArray(parsed.tasks) ? parsed.tasks.length : 0
9783
9990
  };
9784
9991
  }
9785
9992
 
@@ -9906,7 +10113,7 @@ function validateOp(raw, aliases) {
9906
10113
  }
9907
10114
  var aliasMapOf = (g) => new Map(g.neighbours.map((n) => [n.ref, n.id]));
9908
10115
  async function runResolve(deps, ctx, ambiguous) {
9909
- const out = { ops: /* @__PURE__ */ new Map(), rejected: [], failed: [] };
10116
+ const out = { ops: /* @__PURE__ */ new Map(), rejected: [], failed: [], overflowSkipped: [] };
9910
10117
  if (ambiguous.length === 0) return out;
9911
10118
  const { entityId, trigger } = ctx;
9912
10119
  const outcome = await runBatched({
@@ -9928,6 +10135,9 @@ async function runResolve(deps, ctx, ambiguous) {
9928
10135
  if (!Array.isArray(parsed.ops)) throw new Error("resolve: ops missing");
9929
10136
  return { batch, ops: parsed.ops };
9930
10137
  },
10138
+ onSkip: (g, err) => {
10139
+ if (isContextOverflowError(err)) out.overflowSkipped.push(g.candidate.index);
10140
+ },
9931
10141
  maxPromptChars: OPS_RESOLVE_MAX_PROMPT_CHARS,
9932
10142
  maxOutputTokens: deps.options.llmProvider.maxOutputTokens
9933
10143
  });
@@ -10166,6 +10376,16 @@ var runOpsLibrarianPass = async (deps, ctx) => {
10166
10376
  }
10167
10377
  diagnostics.push(gateDiagnostic);
10168
10378
  const res = await runResolve(deps, ctx, gated.filter((g) => g.decision.kind === "ambiguous"));
10379
+ for (const itemIndex of res.overflowSkipped) {
10380
+ diagnostics.push({
10381
+ entityId,
10382
+ operation: "librarian",
10383
+ trigger,
10384
+ code: "context_overflow_skipped",
10385
+ detail: { itemIndex }
10386
+ // (index into the merged extract batch)
10387
+ });
10388
+ }
10169
10389
  if (res.budgetStop) {
10170
10390
  diagnostics.discard();
10171
10391
  return { processedThrough: null, factsWritten: 0, budgetStop: res.budgetStop };
@@ -10196,7 +10416,7 @@ var runOpsLibrarianPass = async (deps, ctx) => {
10196
10416
  }
10197
10417
  }
10198
10418
  deps.searchService.evictCache(entityId);
10199
- const last = sel.batch[sel.batch.length - 1].event;
10419
+ const last = ex.batch[ex.batch.length - 1].event;
10200
10420
  return {
10201
10421
  processedThrough: { at: last.created_at, id: last.id },
10202
10422
  factsWritten: written.length + updatedIds.length
@@ -10907,7 +11127,10 @@ DROP TRIGGER IF EXISTS ${ad};`);
10907
11127
  async runOntologyBackfill(entityId, options) {
10908
11128
  this.jobManager.acquireLock("ontologyBackfill", entityId);
10909
11129
  try {
10910
- return await this.doRunOntologyBackfill(entityId, options);
11130
+ return await this.doRunOntologyBackfill(entityId, {
11131
+ ...options,
11132
+ meter: new UsageMeter(options?.tokenBudget)
11133
+ });
10911
11134
  } finally {
10912
11135
  this.jobManager.releaseLock("ontologyBackfill", entityId);
10913
11136
  }
@@ -11496,7 +11719,19 @@ DROP TRIGGER IF EXISTS ${ad};`);
11496
11719
  },
11497
11720
  maxOutputTokens: this.options.llmProvider.maxOutputTokens,
11498
11721
  maxPromptChars: HEAL_MAX_PROMPT_CHARS,
11722
+ // heal's buildPrompt sheds anchors per attemptLevel — escalation is real (errata E2)
11723
+ supportsEscalation: true,
11499
11724
  onSkip: (fact, err) => {
11725
+ if (isContextOverflowError(err)) {
11726
+ emitDiagnostic(this.options, {
11727
+ entityId,
11728
+ operation: "heal",
11729
+ trigger,
11730
+ code: "context_overflow_skipped",
11731
+ detail: { factId: fact.id }
11732
+ });
11733
+ return;
11734
+ }
11500
11735
  console.warn(
11501
11736
  `[WikiMemory] heal skipped ${entityId}/${fact.id}: response could not be bounded: ${formatSkipError(err)}`
11502
11737
  );
@@ -11668,7 +11903,7 @@ DROP TRIGGER IF EXISTS ${ad};`);
11668
11903
  if (classifierMode === "auto" && typeof classify === "function") {
11669
11904
  const slugs = effectiveManifest.node_types.map((n) => n.type);
11670
11905
  if (slugs.length > 0 && slugs.length <= 255) {
11671
- return this._runClassifierBackfill(entityId, candidates, effectiveManifest, now, recheckCutoff);
11906
+ return this._runClassifierBackfill(entityId, candidates, effectiveManifest, now, recheckCutoff, options?.meter);
11672
11907
  }
11673
11908
  }
11674
11909
  const ontologyContext = await ontologyService.buildPromptContext(entityId);
@@ -11684,7 +11919,7 @@ DROP TRIGGER IF EXISTS ${ad};`);
11684
11919
  const outcome = await runBatched({
11685
11920
  items: candidates,
11686
11921
  buildPrompt,
11687
- call: (prompts) => callLlm(this.options, { operation: "ontologyBackfill", entityId, trigger: "call" }, prompts),
11922
+ call: (prompts) => callLlm(this.options, { operation: "ontologyBackfill", entityId, trigger: "call", meter: options?.meter }, prompts),
11688
11923
  parse: (responseText, batch) => {
11689
11924
  const parsed = parseJsonResponse(responseText);
11690
11925
  return {
@@ -11696,6 +11931,16 @@ DROP TRIGGER IF EXISTS ${ad};`);
11696
11931
  maxOutputTokens: this.options.llmProvider.maxOutputTokens,
11697
11932
  maxPromptChars: ONTOLOGY_BACKFILL_MAX_PROMPT_CHARS,
11698
11933
  onSkip: (fact, err) => {
11934
+ if (isContextOverflowError(err)) {
11935
+ emitDiagnostic(this.options, {
11936
+ entityId,
11937
+ operation: "ontologyBackfill",
11938
+ trigger: "call",
11939
+ code: "context_overflow_skipped",
11940
+ detail: { factId: fact.id }
11941
+ });
11942
+ return;
11943
+ }
11699
11944
  console.warn(
11700
11945
  `[WikiMemory] ontology backfill skipped ${entityId}/${fact.id}: response could not be bounded: ${formatSkipError(err)}`
11701
11946
  );
@@ -11726,7 +11971,8 @@ DROP TRIGGER IF EXISTS ${ad};`);
11726
11971
  edgesAdded,
11727
11972
  skipped: outcome.skipped.length,
11728
11973
  remaining: 0,
11729
- deferred: counts2.deferred
11974
+ deferred: counts2.deferred,
11975
+ ...outcome.budgetStop ? { budgetStop: outcome.budgetStop } : {}
11730
11976
  };
11731
11977
  }
11732
11978
  if (outcome.skipped.length > 0) {
@@ -11749,7 +11995,8 @@ DROP TRIGGER IF EXISTS ${ad};`);
11749
11995
  edgesAdded,
11750
11996
  skipped: outcome.skipped.length,
11751
11997
  remaining: counts.eligible,
11752
- deferred: counts.deferred
11998
+ deferred: counts.deferred,
11999
+ ...outcome.budgetStop ? { budgetStop: outcome.budgetStop } : {}
11753
12000
  };
11754
12001
  }
11755
12002
  /**
@@ -11758,8 +12005,7 @@ DROP TRIGGER IF EXISTS ${ad};`);
11758
12005
  * through `_applyOntologyBackfillBatch` exactly like LLM classifications.
11759
12006
  * No edges are proposed.
11760
12007
  */
11761
- async _runClassifierBackfill(entityId, candidates, manifest, now, recheckCutoff) {
11762
- const provider = this.options.llmProvider;
12008
+ async _runClassifierBackfill(entityId, candidates, manifest, now, recheckCutoff, meter) {
11763
12009
  const rawMin = this.options.config?.ontology?.classifyMinConfidence;
11764
12010
  const minConfidence = typeof rawMin === "number" && Number.isFinite(rawMin) && rawMin >= 0 && rawMin <= 1 ? rawMin : 0.5;
11765
12011
  const rawConcurrency = this.options.config?.chunkConcurrency ?? 1;
@@ -11769,12 +12015,23 @@ DROP TRIGGER IF EXISTS ${ad};`);
11769
12015
  options: manifest.node_types.map((n) => n.type),
11770
12016
  instructions: "Choose the ontology node type that best describes this fact.\n" + manifest.node_types.map((n) => `- ${n.type}: ${n.description}`).join("\n")
11771
12017
  };
12018
+ let stopped;
11772
12019
  const outcomes = await withConcurrency(
11773
12020
  candidates.map((fact) => async () => {
12021
+ if (stopped) return { fact, kind: "unattempted" };
11774
12022
  let response;
11775
12023
  try {
11776
- response = await provider.classify({ state: classifierStateForFact(fact), questions: { okf_type: question } });
11777
- } catch {
12024
+ response = await callClassify(
12025
+ this.options,
12026
+ { operation: "ontologyBackfill", entityId, trigger: "call", meter },
12027
+ { state: classifierStateForFact(fact), questions: { okf_type: question } }
12028
+ );
12029
+ } catch (err) {
12030
+ if (err instanceof WikiBudgetExhausted) {
12031
+ stopped ?? (stopped = err);
12032
+ return { fact, kind: "unattempted" };
12033
+ }
12034
+ if (isContextOverflowError(err)) return { fact, kind: "overflow_skip" };
11778
12035
  return { fact, kind: "threw" };
11779
12036
  }
11780
12037
  const checked = validateClassifierAnswer(response, "okf_type", question);
@@ -11785,8 +12042,9 @@ DROP TRIGGER IF EXISTS ${ad};`);
11785
12042
  }),
11786
12043
  concurrency
11787
12044
  );
11788
- const attempted = outcomes.filter((o) => o.kind !== "threw").map((o) => o.fact);
11789
- const skipped = outcomes.length - attempted.length;
12045
+ const attempted = outcomes.filter((o) => o.kind !== "threw" && o.kind !== "unattempted").map((o) => o.fact);
12046
+ const unattemptedCount = outcomes.filter((o) => o.kind === "unattempted").length;
12047
+ const skipped = outcomes.filter((o) => o.kind === "threw" || o.kind === "overflow_skip").length;
11790
12048
  const classifications = outcomes.filter((o) => o.kind === "accepted").map((o) => ({ id: o.fact.id, okf_type: o.okfType }));
11791
12049
  const invalidCount = outcomes.filter((o) => o.kind === "invalid").length;
11792
12050
  let typed = 0;
@@ -11815,22 +12073,25 @@ DROP TRIGGER IF EXISTS ${ad};`);
11815
12073
  diagBuffer.push({ ...diagBase, code: "classification_invalid", detail: { factId: o.fact.id, reason: o.reason } });
11816
12074
  } else if (o.kind === "threw") {
11817
12075
  diagBuffer.push({ ...diagBase, code: "classification_invalid", detail: { factId: o.fact.id, reason: "classify_threw" } });
12076
+ } else if (o.kind === "overflow_skip") {
12077
+ diagBuffer.push({ ...diagBase, code: "context_overflow_skipped", detail: { factId: o.fact.id } });
11818
12078
  }
11819
12079
  }
11820
12080
  diagBuffer.flush(this.options);
11821
12081
  const counts = await this.entryRepo.countUntypedByEntityId(entityId, recheckCutoff);
11822
12082
  if (aborted) {
11823
- return { scanned: 0, typed: 0, failedValidation: 0, edgesAdded: 0, skipped, remaining: 0, deferred: counts.deferred };
12083
+ return { scanned: 0, typed: 0, failedValidation: 0, edgesAdded: 0, skipped, remaining: 0, deferred: counts.deferred, ...stopped ? { budgetStop: { requiredEstimate: stopped.requiredEstimate } } : {} };
11824
12084
  }
11825
12085
  this.searchService.evictCache(entityId);
11826
12086
  return {
11827
- scanned: candidates.length,
12087
+ scanned: candidates.length - unattemptedCount,
11828
12088
  typed,
11829
12089
  failedValidation,
11830
12090
  edgesAdded,
11831
12091
  skipped,
11832
12092
  remaining: counts.eligible,
11833
- deferred: counts.deferred
12093
+ deferred: counts.deferred,
12094
+ ...stopped ? { budgetStop: { requiredEstimate: stopped.requiredEstimate } } : {}
11834
12095
  };
11835
12096
  }
11836
12097
  /**
@@ -17235,6 +17496,7 @@ exports.mapLibrarianOptionsToReadOptions = mapLibrarianOptionsToReadOptions;
17235
17496
  exports.parseEmbedding = parseEmbedding;
17236
17497
  exports.parseOkfBundle = parseOkfBundle;
17237
17498
  exports.safeSlice = safeSlice;
17499
+ exports.validUsage = validUsage;
17238
17500
  exports.validateLibrarianPromptTemplate = validateLibrarianPromptTemplate;
17239
17501
  exports.validateManifest = validateManifest;
17240
17502
  //# sourceMappingURL=index.js.map