open-multi-agent-kit 0.90.4 → 0.90.5
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/CHANGELOG.md +22 -0
- package/README.md +8 -8
- package/dist/core/adaptorch-bridge.d.ts +14 -21
- package/dist/core/adaptorch-bridge.d.ts.map +1 -1
- package/dist/core/adaptorch-bridge.js +11 -18
- package/dist/core/adaptorch-bridge.js.map +1 -1
- package/dist/core/agent-session.d.ts +6 -39
- package/dist/core/agent-session.d.ts.map +1 -1
- package/dist/core/agent-session.js +7 -99
- package/dist/core/agent-session.js.map +1 -1
- package/dist/core/context-budget-v2-planner.d.ts.map +1 -1
- package/dist/core/context-budget-v2-planner.js +10 -2
- package/dist/core/context-budget-v2-planner.js.map +1 -1
- package/dist/core/context-budget-v2-types.d.ts +7 -1
- package/dist/core/context-budget-v2-types.d.ts.map +1 -1
- package/dist/core/context-budget-v2-types.js.map +1 -1
- package/dist/core/reasoning-router-bias.d.ts +11 -23
- package/dist/core/reasoning-router-bias.d.ts.map +1 -1
- package/dist/core/reasoning-router-bias.js +9 -18
- package/dist/core/reasoning-router-bias.js.map +1 -1
- package/dist/core/reasoning-router-resolver.d.ts +44 -0
- package/dist/core/reasoning-router-resolver.d.ts.map +1 -0
- package/dist/core/reasoning-router-resolver.js +79 -0
- package/dist/core/reasoning-router-resolver.js.map +1 -0
- package/dist/core/reasoning-router-v4-weights.d.ts +28 -72
- package/dist/core/reasoning-router-v4-weights.d.ts.map +1 -1
- package/dist/core/reasoning-router-v4-weights.js +16 -60
- package/dist/core/reasoning-router-v4-weights.js.map +1 -1
- package/dist/core/reasoning-router-v4.d.ts +25 -70
- package/dist/core/reasoning-router-v4.d.ts.map +1 -1
- package/dist/core/reasoning-router-v4.js +46 -144
- package/dist/core/reasoning-router-v4.js.map +1 -1
- package/dist/core/router-feedback-collector.d.ts +13 -16
- package/dist/core/router-feedback-collector.d.ts.map +1 -1
- package/dist/core/router-feedback-collector.js +5 -8
- package/dist/core/router-feedback-collector.js.map +1 -1
- package/dist/core/slash-commands.d.ts.map +1 -1
- package/dist/core/slash-commands.js +1 -1
- package/dist/core/slash-commands.js.map +1 -1
- package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-mode.js +16 -98
- package/dist/modes/interactive/interactive-mode.js.map +1 -1
- package/docs/usage.md +11 -12
- package/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
- package/examples/extensions/custom-provider-anthropic/package.json +1 -1
- package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
- package/examples/extensions/gondolin/package-lock.json +2 -2
- package/examples/extensions/gondolin/package.json +1 -1
- package/examples/extensions/sandbox/package-lock.json +2 -2
- package/examples/extensions/sandbox/package.json +1 -1
- package/examples/extensions/subagent/agent-capability-router.test.ts +123 -0
- package/examples/extensions/subagent/agent-capability-router.ts +274 -0
- package/examples/extensions/subagent/agents/planner.md +3 -0
- package/examples/extensions/subagent/agents/reviewer.md +3 -0
- package/examples/extensions/subagent/agents/scout.md +3 -0
- package/examples/extensions/subagent/agents/worker.md +2 -0
- package/examples/extensions/subagent/agents.ts +14 -0
- package/examples/extensions/subagent/capabilities.ts +368 -0
- package/examples/extensions/subagent/domain-profiles.ts +1089 -0
- package/examples/extensions/subagent/index.ts +71 -3
- package/examples/extensions/with-deps/package-lock.json +2 -2
- package/examples/extensions/with-deps/package.json +1 -1
- package/examples/sdk/12-full-control.ts +1 -1
- package/npm-shrinkwrap.json +12 -12
- package/package.json +4 -4
- package/dist/core/compactor.d.ts +0 -42
- package/dist/core/compactor.d.ts.map +0 -1
- package/dist/core/compactor.js +0 -128
- package/dist/core/compactor.js.map +0 -1
- package/dist/core/reasoning-router-v2.d.ts +0 -94
- package/dist/core/reasoning-router-v2.d.ts.map +0 -1
- package/dist/core/reasoning-router-v2.js +0 -288
- package/dist/core/reasoning-router-v2.js.map +0 -1
- package/dist/core/reasoning-router-v3.d.ts +0 -15
- package/dist/core/reasoning-router-v3.d.ts.map +0 -1
- package/dist/core/reasoning-router-v3.js +0 -193
- package/dist/core/reasoning-router-v3.js.map +0 -1
- package/dist/core/reasoning-router-weights.d.ts +0 -155
- package/dist/core/reasoning-router-weights.d.ts.map +0 -1
- package/dist/core/reasoning-router-weights.js +0 -204
- package/dist/core/reasoning-router-weights.js.map +0 -1
- package/dist/core/reasoning-router.d.ts +0 -44
- package/dist/core/reasoning-router.d.ts.map +0 -1
- package/dist/core/reasoning-router.js +0 -138
- package/dist/core/reasoning-router.js.map +0 -1
- package/dist/core/token-optimizer.d.ts +0 -58
- package/dist/core/token-optimizer.d.ts.map +0 -1
- package/dist/core/token-optimizer.js +0 -179
- package/dist/core/token-optimizer.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"context-budget-v2-planner.d.ts","sourceRoot":"","sources":["../../src/core/context-budget-v2-planner.ts"],"names":[],"mappings":"AA2BA,OAAO,EAGN,KAAK,0BAA0B,EAE/B,KAAK,yBAAyB,
|
|
1
|
+
{"version":3,"file":"context-budget-v2-planner.d.ts","sourceRoot":"","sources":["../../src/core/context-budget-v2-planner.ts"],"names":[],"mappings":"AA2BA,OAAO,EAGN,KAAK,0BAA0B,EAE/B,KAAK,yBAAyB,EAK9B,MAAM,8BAA8B,CAAC;AAYtC,wBAAgB,yBAAyB,CAAC,KAAK,EAAE,0BAA0B,GAAG,yBAAyB,CAuKtG","sourcesContent":["import {\n\ttype ContextBudgetItemV2,\n\ttype ContextBudgetTierV2,\n\ttype ContextSourceRefV2,\n\tDEFAULT_HEADROOM_QUALITY_POLICY,\n} from \"./context-budget-headroom.ts\";\nimport {\n\tbuildContextBudgetPlanCacheKeyV2,\n\tcreateContextBudgetCacheKeyBaseV2,\n\tcreateContextBudgetSelectionCacheV2,\n\tfinalizeContextBudgetCacheTelemetryV2,\n\treadValidPlanCacheV2,\n\twritePlanCacheV2,\n} from \"./context-budget-v2-cache.ts\";\nimport { computePlanHash } from \"./context-budget-v2-plan-hash.ts\";\nimport { compareOptionalForSelection } from \"./context-budget-v2-scoring.ts\";\nimport {\n\tapplyPlannerRedundancyPenalties,\n\tbuildTierAllocations,\n\tcreatePlannedItems,\n\tcreateTierUsage,\n\temitCoverageDiagnostics,\n\temitOmissionDiagnostics,\n\tselectHardItem,\n\tselectOptionalItem,\n} from \"./context-budget-v2-selection.ts\";\nimport { allocateTiers, computeTierDemand } from \"./context-budget-v2-tiers.ts\";\nimport {\n\tCONTEXT_BUDGET_POLICY_VERSION_V2,\n\tDEFAULT_TIER_POLICY_V2,\n\ttype PromptContextBudgetInputV2,\n\ttype PromptContextBudgetObservabilityV2,\n\ttype PromptContextBudgetPlanV2,\n\ttype QualityDiagnosticV2,\n\ttype SelectedRepresentationV2,\n\ttype TierBudgetPolicyV2,\n\ttype TokenOptimizerRuntimeStatus,\n} from \"./context-budget-v2-types.ts\";\n\n// Inlined constant replacing the deleted legacy token-optimizer.ts module's\n// getTokenOptimizerRuntimeStatus(): a fixed, hardcoded compatibility status.\nconst TOKEN_OPTIMIZER_RUNTIME_STATUS: TokenOptimizerRuntimeStatus = {\n\toptimizerId: \"legacy-token-optimizer\",\n\tstatus: \"quarantined_compatibility\",\n\tactive: false,\n\tactiveContextBudgetOptimizer: \"context-budget-v2\",\n\tcompatibilityOnly: true,\n};\n\nexport function planPromptContextBudgetV2(input: PromptContextBudgetInputV2): PromptContextBudgetPlanV2 {\n\tconst modelId = input.modelId ?? \"unknown\";\n\tconst qualityPolicy = input.qualityPolicy ?? DEFAULT_HEADROOM_QUALITY_POLICY;\n\tconst policyVersion = input.policyVersion ?? CONTEXT_BUDGET_POLICY_VERSION_V2;\n\tconst diagnostics: QualityDiagnosticV2[] = [];\n\n\tconst maxTokens = normalizeBudgetTokens(\"maxTokens\", input.maxTokens, diagnostics);\n\tconst responseReserve = normalizeBudgetTokens(\n\t\t\"responseReserveTokens\",\n\t\tinput.responseReserveTokens ?? 0,\n\t\tdiagnostics,\n\t);\n\tconst safetyMargin = normalizeBudgetTokens(\n\t\t\"safetyMarginTokens\",\n\t\tinput.safetyMarginTokens ?? Math.ceil(maxTokens * 0.05),\n\t\tdiagnostics,\n\t);\n\tconst available = Math.max(0, maxTokens - responseReserve - safetyMargin);\n\n\tconst tierPolicy: Readonly<Record<ContextBudgetTierV2, TierBudgetPolicyV2>> = {\n\t\t...DEFAULT_TIER_POLICY_V2,\n\t\t...(input.tierPolicy ?? {}),\n\t};\n\tconst basePlanned = createPlannedItems(input.items, input.tokenCounter, modelId);\n\tapplyPlannerRedundancyPenalties(basePlanned);\n\tconst rawTokens = basePlanned.reduce((sum, planned) => sum + planned.fullTokens, 0);\n\n\tconst demand = computeTierDemand(basePlanned);\n\tconst allocation = allocateTiers(available, tierPolicy, demand);\n\tconst cacheKeyBase = createContextBudgetCacheKeyBaseV2({\n\t\tbudgetBucket: input.cacheBudgetBucket ?? String(available),\n\t\tmodelId,\n\t\tnamespace: input.cacheNamespace,\n\t\tpolicyVersion,\n\t\tquery: input.query,\n\t\tqueryIntentHash: input.queryIntentHash,\n\t\tredactionPolicyHash: input.redactionPolicyHash,\n\t\tsafetyProfileHash: input.safetyProfileHash,\n\t\ttokenizerId: input.tokenizerId,\n\t});\n\tconst planCacheKey = buildContextBudgetPlanCacheKeyV2({\n\t\tavailableTokens: available,\n\t\tkeyBase: cacheKeyBase,\n\t\tmaxTokens,\n\t\tplanned: basePlanned,\n\t\tpromptHash: input.promptHash,\n\t\tqualityPolicy,\n\t\tresponseReserveTokens: responseReserve,\n\t\tsafetyMarginTokens: safetyMargin,\n\t\ttierPolicy,\n\t});\n\tconst cache = createContextBudgetSelectionCacheV2({\n\t\tkeyBase: cacheKeyBase,\n\t\tnowEpochMs: input.cacheNowEpochMs,\n\t\tplanCacheKey,\n\t\tprovider: input.cacheProvider,\n\t\tttlMs: input.cacheTtlMs,\n\t});\n\tconst cachedPlan = readValidPlanCacheV2({\n\t\tavailableTokens: available,\n\t\tcache,\n\t\tkey: planCacheKey,\n\t\tplanned: basePlanned,\n\t});\n\tif (cachedPlan) {\n\t\treturn cachedPlan;\n\t}\n\tconst selection = new Map<string, SelectedRepresentationV2>();\n\tconst tierUsed = createTierUsage();\n\tconst omitted: ContextBudgetItemV2[] = [];\n\tconst retrievalFallbacks: ContextSourceRefV2[] = [];\n\tlet usedTokens = 0;\n\n\tfor (const planned of basePlanned) {\n\t\tif (!planned.isHard) continue;\n\t\tusedTokens += selectHardItem(planned, selection, tierUsed);\n\t}\n\tif (usedTokens > available) {\n\t\tdiagnostics.push({\n\t\t\treason: \"hard_pin_over_capacity\",\n\t\t\tdetail: `hard-pinned context uses ${usedTokens} tokens against ${available} available tokens`,\n\t\t});\n\t}\n\n\tconst optionalPlanned = basePlanned.filter((planned) => !planned.isHard).sort(compareOptionalForSelection);\n\tfor (const planned of optionalPlanned) {\n\t\tusedTokens = selectOptionalItem(planned, {\n\t\t\tallocation,\n\t\t\tavailable,\n\t\t\tcache,\n\t\t\tdiagnostics,\n\t\t\tomitted,\n\t\t\tqualityPolicy,\n\t\t\tretrievalFallbacks,\n\t\t\tselection,\n\t\t\ttierUsed,\n\t\t\tusedTokens,\n\t\t});\n\t}\n\n\tconst omittedHighPriority = omitted.some((item) => item.priority === \"high\" || item.required === true);\n\temitOmissionDiagnostics(omitted, diagnostics, retrievalFallbacks);\n\temitCoverageDiagnostics(input.query, selection, diagnostics);\n\n\tconst tierAllocations = buildTierAllocations(allocation, demand, tierUsed);\n\tconst omittedTokens = omitted.reduce(\n\t\t(sum, item) => sum + (basePlanned.find((planned) => planned.item.id === item.id)?.fullTokens ?? 0),\n\t\t0,\n\t);\n\tconst omittedItemIds = omitted.map((item) => item.id);\n\tconst planHash = computePlanHash({\n\t\tpolicyVersion,\n\t\tpromptHash: input.promptHash,\n\t\tplanned: basePlanned,\n\t\tselection,\n\t\tallocations: tierAllocations,\n\t\tomittedItemIds,\n\t});\n\tconst observability = buildObservability({\n\t\tavailable,\n\t\tdiagnostics,\n\t\tomittedItemIds,\n\t\tomittedTokens,\n\t\tplanHash,\n\t\trawTokens,\n\t\tretrievalFallbacks,\n\t\tselection,\n\t\tusedTokens,\n\t\tcacheTelemetry: finalizeContextBudgetCacheTelemetryV2(cache.telemetry, {\n\t\t\tomittedTokens,\n\t\t\trawTokens,\n\t\t\tusedTokens,\n\t\t}),\n\t});\n\n\tconst plan: PromptContextBudgetPlanV2 = {\n\t\tpolicyVersion,\n\t\tpromptHash: input.promptHash,\n\t\tplanHash,\n\t\tmaxTokens,\n\t\tresponseReserveTokens: responseReserve,\n\t\tsafetyMarginTokens: safetyMargin,\n\t\tavailableTokens: available,\n\t\tusedTokens,\n\t\tomittedTokens,\n\t\trawTokens,\n\t\ttokenSavingsRatio: rawTokens > 0 ? Math.max(0, 1 - usedTokens / rawTokens) : 0,\n\t\temergency: usedTokens > available || diagnostics.some((diagnostic) => diagnostic.reason === \"invalid_budget\"),\n\t\tomittedHighPriority,\n\t\ttierAllocations,\n\t\tselectedRepresentations: [...selection.values()].sort((a, b) => a.itemId.localeCompare(b.itemId)),\n\t\tincludedItemIds: basePlanned\n\t\t\t.map((planned) => planned.item.id)\n\t\t\t.filter((id) => selection.has(id))\n\t\t\t.sort(),\n\t\tomittedItemIds,\n\t\tdiagnostics,\n\t\tretrievalFallbacks,\n\t\tobservability,\n\t};\n\twritePlanCacheV2({\n\t\tcache,\n\t\tkey: planCacheKey,\n\t\tplan,\n\t\tplanned: basePlanned,\n\t});\n\treturn plan;\n}\n\nfunction normalizeBudgetTokens(field: string, value: number, diagnostics: QualityDiagnosticV2[]): number {\n\tif (!Number.isFinite(value) || value < 0) {\n\t\tdiagnostics.push({\n\t\t\treason: \"invalid_budget\",\n\t\t\tdetail: `${field} must be a non-negative finite number, got ${value}`,\n\t\t});\n\t\treturn 0;\n\t}\n\treturn Math.floor(value);\n}\n\nfunction buildObservability(input: {\n\treadonly available: number;\n\treadonly diagnostics: readonly QualityDiagnosticV2[];\n\treadonly omittedItemIds: readonly string[];\n\treadonly omittedTokens: number;\n\treadonly planHash: string;\n\treadonly rawTokens: number;\n\treadonly retrievalFallbacks: readonly ContextSourceRefV2[];\n\treadonly selection: ReadonlyMap<string, SelectedRepresentationV2>;\n\treadonly usedTokens: number;\n\treadonly cacheTelemetry: PromptContextBudgetObservabilityV2[\"cache\"];\n}): PromptContextBudgetObservabilityV2 {\n\tconst selected = [...input.selection.values()];\n\treturn {\n\t\tcounts: {\n\t\t\tselected: selected.length,\n\t\t\tomitted: input.omittedItemIds.length,\n\t\t\tpointer: selected.filter((representation) => representation.kind === \"pointer\").length,\n\t\t\tcompressed: selected.filter((representation) => representation.kind === \"headroom-compressed\").length,\n\t\t\tfull: selected.filter((representation) => representation.kind === \"full\").length,\n\t\t\tretrievalFallback: countUniqueRetrievalFallbacks(input.retrievalFallbacks),\n\t\t},\n\t\tdiagnosticReasons: [...new Set(input.diagnostics.map((diagnostic) => diagnostic.reason))].sort(),\n\t\ttokens: {\n\t\t\tavailable: input.available,\n\t\t\tused: input.usedTokens,\n\t\t\traw: input.rawTokens,\n\t\t\tomitted: input.omittedTokens,\n\t\t\ttokenSavings: Math.max(0, input.rawTokens - input.usedTokens),\n\t\t},\n\t\tplanHash: input.planHash,\n\t\tcache: input.cacheTelemetry,\n\t\ttokenOptimizer: TOKEN_OPTIMIZER_RUNTIME_STATUS,\n\t};\n}\n\nfunction countUniqueRetrievalFallbacks(retrievalFallbacks: readonly ContextSourceRefV2[]): number {\n\treturn new Set(\n\t\tretrievalFallbacks.map((ref) =>\n\t\t\t[ref.uri, ref.contentHash, ref.symbol ?? \"\", ref.range?.startLine ?? \"\", ref.range?.endLine ?? \"\"].join(\"\\0\"),\n\t\t),\n\t).size;\n}\n"]}
|
|
@@ -5,7 +5,15 @@ import { compareOptionalForSelection } from "./context-budget-v2-scoring.js";
|
|
|
5
5
|
import { applyPlannerRedundancyPenalties, buildTierAllocations, createPlannedItems, createTierUsage, emitCoverageDiagnostics, emitOmissionDiagnostics, selectHardItem, selectOptionalItem, } from "./context-budget-v2-selection.js";
|
|
6
6
|
import { allocateTiers, computeTierDemand } from "./context-budget-v2-tiers.js";
|
|
7
7
|
import { CONTEXT_BUDGET_POLICY_VERSION_V2, DEFAULT_TIER_POLICY_V2, } from "./context-budget-v2-types.js";
|
|
8
|
-
|
|
8
|
+
// Inlined constant replacing the deleted legacy token-optimizer.ts module's
|
|
9
|
+
// getTokenOptimizerRuntimeStatus(): a fixed, hardcoded compatibility status.
|
|
10
|
+
const TOKEN_OPTIMIZER_RUNTIME_STATUS = {
|
|
11
|
+
optimizerId: "legacy-token-optimizer",
|
|
12
|
+
status: "quarantined_compatibility",
|
|
13
|
+
active: false,
|
|
14
|
+
activeContextBudgetOptimizer: "context-budget-v2",
|
|
15
|
+
compatibilityOnly: true,
|
|
16
|
+
};
|
|
9
17
|
export function planPromptContextBudgetV2(input) {
|
|
10
18
|
const modelId = input.modelId ?? "unknown";
|
|
11
19
|
const qualityPolicy = input.qualityPolicy ?? DEFAULT_HEADROOM_QUALITY_POLICY;
|
|
@@ -187,7 +195,7 @@ function buildObservability(input) {
|
|
|
187
195
|
},
|
|
188
196
|
planHash: input.planHash,
|
|
189
197
|
cache: input.cacheTelemetry,
|
|
190
|
-
tokenOptimizer:
|
|
198
|
+
tokenOptimizer: TOKEN_OPTIMIZER_RUNTIME_STATUS,
|
|
191
199
|
};
|
|
192
200
|
}
|
|
193
201
|
function countUniqueRetrievalFallbacks(retrievalFallbacks) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"context-budget-v2-planner.js","sourceRoot":"","sources":["../../src/core/context-budget-v2-planner.ts"],"names":[],"mappings":"AAAA,OAAO,EAIN,+BAA+B,GAC/B,MAAM,8BAA8B,CAAC;AACtC,OAAO,EACN,gCAAgC,EAChC,iCAAiC,EACjC,mCAAmC,EACnC,qCAAqC,EACrC,oBAAoB,EACpB,gBAAgB,GAChB,MAAM,8BAA8B,CAAC;AACtC,OAAO,EAAE,eAAe,EAAE,MAAM,kCAAkC,CAAC;AACnE,O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GAAG,CAAC,CAAC,EAAE,KAAK,CAAC,SAAS,GAAG,KAAK,CAAC,UAAU,CAAC;SAC7D;QACD,QAAQ,EAAE,KAAK,CAAC,QAAQ;QACxB,KAAK,EAAE,KAAK,CAAC,cAAc;QAC3B,cAAc,EAAE,8BAA8B,EAAE;KAChD,CAAC;AAAA,CACF;AAED,SAAS,6BAA6B,CAAC,kBAAiD,EAAU;IACjG,OAAO,IAAI,GAAG,CACb,kBAAkB,CAAC,GAAG,CAAC,CAAC,GAAG,EAAE,EAAE,CAC9B,CAAC,GAAG,CAAC,GAAG,EAAE,GAAG,CAAC,WAAW,EAAE,GAAG,CAAC,MAAM,IAAI,EAAE,EAAE,GAAG,CAAC,KAAK,EAAE,SAAS,IAAI,EAAE,EAAE,GAAG,CAAC,KAAK,EAAE,OAAO,IAAI,EAAE,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,CAC7G,CACD,CAAC,IAAI,CAAC;AAAA,CACP","sourcesContent":["import {\n\ttype ContextBudgetItemV2,\n\ttype ContextBudgetTierV2,\n\ttype ContextSourceRefV2,\n\tDEFAULT_HEADROOM_QUALITY_POLICY,\n} from \"./context-budget-headroom.ts\";\nimport {\n\tbuildContextBudgetPlanCacheKeyV2,\n\tcreateContextBudgetCacheKeyBaseV2,\n\tcreateContextBudgetSelectionCacheV2,\n\tfinalizeContextBudgetCacheTelemetryV2,\n\treadValidPlanCacheV2,\n\twritePlanCacheV2,\n} from \"./context-budget-v2-cache.ts\";\nimport { computePlanHash } from \"./context-budget-v2-plan-hash.ts\";\nimport { compareOptionalForSelection } from \"./context-budget-v2-scoring.ts\";\nimport {\n\tapplyPlannerRedundancyPenalties,\n\tbuildTierAllocations,\n\tcreatePlannedItems,\n\tcreateTierUsage,\n\temitCoverageDiagnostics,\n\temitOmissionDiagnostics,\n\tselectHardItem,\n\tselectOptionalItem,\n} from \"./context-budget-v2-selection.ts\";\nimport { allocateTiers, computeTierDemand } from \"./context-budget-v2-tiers.ts\";\nimport {\n\tCONTEXT_BUDGET_POLICY_VERSION_V2,\n\tDEFAULT_TIER_POLICY_V2,\n\ttype PromptContextBudgetInputV2,\n\ttype PromptContextBudgetObservabilityV2,\n\ttype PromptContextBudgetPlanV2,\n\ttype QualityDiagnosticV2,\n\ttype SelectedRepresentationV2,\n\ttype TierBudgetPolicyV2,\n} from \"./context-budget-v2-types.ts\";\nimport { getTokenOptimizerRuntimeStatus } from \"./token-optimizer.ts\";\n\nexport function planPromptContextBudgetV2(input: PromptContextBudgetInputV2): PromptContextBudgetPlanV2 {\n\tconst modelId = input.modelId ?? \"unknown\";\n\tconst qualityPolicy = input.qualityPolicy ?? DEFAULT_HEADROOM_QUALITY_POLICY;\n\tconst policyVersion = input.policyVersion ?? CONTEXT_BUDGET_POLICY_VERSION_V2;\n\tconst diagnostics: QualityDiagnosticV2[] = [];\n\n\tconst maxTokens = normalizeBudgetTokens(\"maxTokens\", input.maxTokens, diagnostics);\n\tconst responseReserve = normalizeBudgetTokens(\n\t\t\"responseReserveTokens\",\n\t\tinput.responseReserveTokens ?? 0,\n\t\tdiagnostics,\n\t);\n\tconst safetyMargin = normalizeBudgetTokens(\n\t\t\"safetyMarginTokens\",\n\t\tinput.safetyMarginTokens ?? Math.ceil(maxTokens * 0.05),\n\t\tdiagnostics,\n\t);\n\tconst available = Math.max(0, maxTokens - responseReserve - safetyMargin);\n\n\tconst tierPolicy: Readonly<Record<ContextBudgetTierV2, TierBudgetPolicyV2>> = {\n\t\t...DEFAULT_TIER_POLICY_V2,\n\t\t...(input.tierPolicy ?? {}),\n\t};\n\tconst basePlanned = createPlannedItems(input.items, input.tokenCounter, modelId);\n\tapplyPlannerRedundancyPenalties(basePlanned);\n\tconst rawTokens = basePlanned.reduce((sum, planned) => sum + planned.fullTokens, 0);\n\n\tconst demand = computeTierDemand(basePlanned);\n\tconst allocation = allocateTiers(available, tierPolicy, demand);\n\tconst cacheKeyBase = createContextBudgetCacheKeyBaseV2({\n\t\tbudgetBucket: input.cacheBudgetBucket ?? String(available),\n\t\tmodelId,\n\t\tnamespace: input.cacheNamespace,\n\t\tpolicyVersion,\n\t\tquery: input.query,\n\t\tqueryIntentHash: input.queryIntentHash,\n\t\tredactionPolicyHash: input.redactionPolicyHash,\n\t\tsafetyProfileHash: input.safetyProfileHash,\n\t\ttokenizerId: input.tokenizerId,\n\t});\n\tconst planCacheKey = buildContextBudgetPlanCacheKeyV2({\n\t\tavailableTokens: available,\n\t\tkeyBase: cacheKeyBase,\n\t\tmaxTokens,\n\t\tplanned: basePlanned,\n\t\tpromptHash: input.promptHash,\n\t\tqualityPolicy,\n\t\tresponseReserveTokens: responseReserve,\n\t\tsafetyMarginTokens: safetyMargin,\n\t\ttierPolicy,\n\t});\n\tconst cache = createContextBudgetSelectionCacheV2({\n\t\tkeyBase: cacheKeyBase,\n\t\tnowEpochMs: input.cacheNowEpochMs,\n\t\tplanCacheKey,\n\t\tprovider: input.cacheProvider,\n\t\tttlMs: input.cacheTtlMs,\n\t});\n\tconst cachedPlan = readValidPlanCacheV2({\n\t\tavailableTokens: available,\n\t\tcache,\n\t\tkey: planCacheKey,\n\t\tplanned: basePlanned,\n\t});\n\tif (cachedPlan) {\n\t\treturn cachedPlan;\n\t}\n\tconst selection = new Map<string, SelectedRepresentationV2>();\n\tconst tierUsed = createTierUsage();\n\tconst omitted: ContextBudgetItemV2[] = [];\n\tconst retrievalFallbacks: ContextSourceRefV2[] = [];\n\tlet usedTokens = 0;\n\n\tfor (const planned of basePlanned) {\n\t\tif (!planned.isHard) continue;\n\t\tusedTokens += selectHardItem(planned, selection, tierUsed);\n\t}\n\tif (usedTokens > available) {\n\t\tdiagnostics.push({\n\t\t\treason: \"hard_pin_over_capacity\",\n\t\t\tdetail: `hard-pinned context uses ${usedTokens} tokens against ${available} available tokens`,\n\t\t});\n\t}\n\n\tconst optionalPlanned = basePlanned.filter((planned) => !planned.isHard).sort(compareOptionalForSelection);\n\tfor (const planned of optionalPlanned) {\n\t\tusedTokens = selectOptionalItem(planned, {\n\t\t\tallocation,\n\t\t\tavailable,\n\t\t\tcache,\n\t\t\tdiagnostics,\n\t\t\tomitted,\n\t\t\tqualityPolicy,\n\t\t\tretrievalFallbacks,\n\t\t\tselection,\n\t\t\ttierUsed,\n\t\t\tusedTokens,\n\t\t});\n\t}\n\n\tconst omittedHighPriority = omitted.some((item) => item.priority === \"high\" || item.required === true);\n\temitOmissionDiagnostics(omitted, diagnostics, retrievalFallbacks);\n\temitCoverageDiagnostics(input.query, selection, diagnostics);\n\n\tconst tierAllocations = buildTierAllocations(allocation, demand, tierUsed);\n\tconst omittedTokens = omitted.reduce(\n\t\t(sum, item) => sum + (basePlanned.find((planned) => planned.item.id === item.id)?.fullTokens ?? 0),\n\t\t0,\n\t);\n\tconst omittedItemIds = omitted.map((item) => item.id);\n\tconst planHash = computePlanHash({\n\t\tpolicyVersion,\n\t\tpromptHash: input.promptHash,\n\t\tplanned: basePlanned,\n\t\tselection,\n\t\tallocations: tierAllocations,\n\t\tomittedItemIds,\n\t});\n\tconst observability = buildObservability({\n\t\tavailable,\n\t\tdiagnostics,\n\t\tomittedItemIds,\n\t\tomittedTokens,\n\t\tplanHash,\n\t\trawTokens,\n\t\tretrievalFallbacks,\n\t\tselection,\n\t\tusedTokens,\n\t\tcacheTelemetry: finalizeContextBudgetCacheTelemetryV2(cache.telemetry, {\n\t\t\tomittedTokens,\n\t\t\trawTokens,\n\t\t\tusedTokens,\n\t\t}),\n\t});\n\n\tconst plan: PromptContextBudgetPlanV2 = {\n\t\tpolicyVersion,\n\t\tpromptHash: input.promptHash,\n\t\tplanHash,\n\t\tmaxTokens,\n\t\tresponseReserveTokens: responseReserve,\n\t\tsafetyMarginTokens: safetyMargin,\n\t\tavailableTokens: available,\n\t\tusedTokens,\n\t\tomittedTokens,\n\t\trawTokens,\n\t\ttokenSavingsRatio: rawTokens > 0 ? Math.max(0, 1 - usedTokens / rawTokens) : 0,\n\t\temergency: usedTokens > available || diagnostics.some((diagnostic) => diagnostic.reason === \"invalid_budget\"),\n\t\tomittedHighPriority,\n\t\ttierAllocations,\n\t\tselectedRepresentations: [...selection.values()].sort((a, b) => a.itemId.localeCompare(b.itemId)),\n\t\tincludedItemIds: basePlanned\n\t\t\t.map((planned) => planned.item.id)\n\t\t\t.filter((id) => selection.has(id))\n\t\t\t.sort(),\n\t\tomittedItemIds,\n\t\tdiagnostics,\n\t\tretrievalFallbacks,\n\t\tobservability,\n\t};\n\twritePlanCacheV2({\n\t\tcache,\n\t\tkey: planCacheKey,\n\t\tplan,\n\t\tplanned: basePlanned,\n\t});\n\treturn plan;\n}\n\nfunction normalizeBudgetTokens(field: string, value: number, diagnostics: QualityDiagnosticV2[]): number {\n\tif (!Number.isFinite(value) || value < 0) {\n\t\tdiagnostics.push({\n\t\t\treason: \"invalid_budget\",\n\t\t\tdetail: `${field} must be a non-negative finite number, got ${value}`,\n\t\t});\n\t\treturn 0;\n\t}\n\treturn Math.floor(value);\n}\n\nfunction buildObservability(input: {\n\treadonly available: number;\n\treadonly diagnostics: readonly QualityDiagnosticV2[];\n\treadonly omittedItemIds: readonly string[];\n\treadonly omittedTokens: number;\n\treadonly planHash: string;\n\treadonly rawTokens: number;\n\treadonly retrievalFallbacks: readonly ContextSourceRefV2[];\n\treadonly selection: ReadonlyMap<string, SelectedRepresentationV2>;\n\treadonly usedTokens: number;\n\treadonly cacheTelemetry: PromptContextBudgetObservabilityV2[\"cache\"];\n}): PromptContextBudgetObservabilityV2 {\n\tconst selected = [...input.selection.values()];\n\treturn {\n\t\tcounts: {\n\t\t\tselected: selected.length,\n\t\t\tomitted: input.omittedItemIds.length,\n\t\t\tpointer: selected.filter((representation) => representation.kind === \"pointer\").length,\n\t\t\tcompressed: selected.filter((representation) => representation.kind === \"headroom-compressed\").length,\n\t\t\tfull: selected.filter((representation) => representation.kind === \"full\").length,\n\t\t\tretrievalFallback: countUniqueRetrievalFallbacks(input.retrievalFallbacks),\n\t\t},\n\t\tdiagnosticReasons: [...new Set(input.diagnostics.map((diagnostic) => diagnostic.reason))].sort(),\n\t\ttokens: {\n\t\t\tavailable: input.available,\n\t\t\tused: input.usedTokens,\n\t\t\traw: input.rawTokens,\n\t\t\tomitted: input.omittedTokens,\n\t\t\ttokenSavings: Math.max(0, input.rawTokens - input.usedTokens),\n\t\t},\n\t\tplanHash: input.planHash,\n\t\tcache: input.cacheTelemetry,\n\t\ttokenOptimizer: getTokenOptimizerRuntimeStatus(),\n\t};\n}\n\nfunction countUniqueRetrievalFallbacks(retrievalFallbacks: readonly ContextSourceRefV2[]): number {\n\treturn new Set(\n\t\tretrievalFallbacks.map((ref) =>\n\t\t\t[ref.uri, ref.contentHash, ref.symbol ?? \"\", ref.range?.startLine ?? \"\", ref.range?.endLine ?? \"\"].join(\"\\0\"),\n\t\t),\n\t).size;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"context-budget-v2-planner.js","sourceRoot":"","sources":["../../src/core/context-budget-v2-planner.ts"],"names":[],"mappings":"AAAA,OAAO,EAIN,+BAA+B,GAC/B,MAAM,8BAA8B,CAAC;AACtC,OAAO,EACN,gCAAgC,EAChC,iCAAiC,EACjC,mCAAmC,EACnC,qCAAqC,EACrC,oBAAoB,EACpB,gBAAgB,GAChB,MAAM,8BAA8B,CAAC;AACtC,OAAO,EAAE,eAAe,EAAE,MAAM,kCAAkC,CAAC;AACnE,OAAO,EAAE,2BAA2B,EAAE,MAAM,gCAAgC,CAAC;AAC7E,OAAO,EACN,+BAA+B,EAC/B,oBAAoB,EACpB,kBAAkB,EAClB,eAAe,EACf,uBAAuB,EACvB,uBAAuB,EACvB,cAAc,EACd,kBAAkB,GAClB,MAAM,kCAAkC,CAAC;AAC1C,OAAO,EAAE,aAAa,EAAE,iBAAiB,EAAE,MAAM,8BAA8B,CAAC;AAChF,OAAO,EACN,gCAAgC,EAChC,sBAAsB,GAQtB,MAAM,8BAA8B,CAAC;AAEtC,4EAA4E;AAC5E,6EAA6E;AAC7E,MAAM,8BAA8B,GAAgC;IACnE,WAAW,EAAE,wBAA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,GAAG,CACb,kBAAkB,CAAC,GAAG,CAAC,CAAC,GAAG,EAAE,EAAE,CAC9B,CAAC,GAAG,CAAC,GAAG,EAAE,GAAG,CAAC,WAAW,EAAE,GAAG,CAAC,MAAM,IAAI,EAAE,EAAE,GAAG,CAAC,KAAK,EAAE,SAAS,IAAI,EAAE,EAAE,GAAG,CAAC,KAAK,EAAE,OAAO,IAAI,EAAE,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,CAC7G,CACD,CAAC,IAAI,CAAC;AAAA,CACP","sourcesContent":["import {\n\ttype ContextBudgetItemV2,\n\ttype ContextBudgetTierV2,\n\ttype ContextSourceRefV2,\n\tDEFAULT_HEADROOM_QUALITY_POLICY,\n} from \"./context-budget-headroom.ts\";\nimport {\n\tbuildContextBudgetPlanCacheKeyV2,\n\tcreateContextBudgetCacheKeyBaseV2,\n\tcreateContextBudgetSelectionCacheV2,\n\tfinalizeContextBudgetCacheTelemetryV2,\n\treadValidPlanCacheV2,\n\twritePlanCacheV2,\n} from \"./context-budget-v2-cache.ts\";\nimport { computePlanHash } from \"./context-budget-v2-plan-hash.ts\";\nimport { compareOptionalForSelection } from \"./context-budget-v2-scoring.ts\";\nimport {\n\tapplyPlannerRedundancyPenalties,\n\tbuildTierAllocations,\n\tcreatePlannedItems,\n\tcreateTierUsage,\n\temitCoverageDiagnostics,\n\temitOmissionDiagnostics,\n\tselectHardItem,\n\tselectOptionalItem,\n} from \"./context-budget-v2-selection.ts\";\nimport { allocateTiers, computeTierDemand } from \"./context-budget-v2-tiers.ts\";\nimport {\n\tCONTEXT_BUDGET_POLICY_VERSION_V2,\n\tDEFAULT_TIER_POLICY_V2,\n\ttype PromptContextBudgetInputV2,\n\ttype PromptContextBudgetObservabilityV2,\n\ttype PromptContextBudgetPlanV2,\n\ttype QualityDiagnosticV2,\n\ttype SelectedRepresentationV2,\n\ttype TierBudgetPolicyV2,\n\ttype TokenOptimizerRuntimeStatus,\n} from \"./context-budget-v2-types.ts\";\n\n// Inlined constant replacing the deleted legacy token-optimizer.ts module's\n// getTokenOptimizerRuntimeStatus(): a fixed, hardcoded compatibility status.\nconst TOKEN_OPTIMIZER_RUNTIME_STATUS: TokenOptimizerRuntimeStatus = {\n\toptimizerId: \"legacy-token-optimizer\",\n\tstatus: \"quarantined_compatibility\",\n\tactive: false,\n\tactiveContextBudgetOptimizer: \"context-budget-v2\",\n\tcompatibilityOnly: true,\n};\n\nexport function planPromptContextBudgetV2(input: PromptContextBudgetInputV2): PromptContextBudgetPlanV2 {\n\tconst modelId = input.modelId ?? \"unknown\";\n\tconst qualityPolicy = input.qualityPolicy ?? DEFAULT_HEADROOM_QUALITY_POLICY;\n\tconst policyVersion = input.policyVersion ?? CONTEXT_BUDGET_POLICY_VERSION_V2;\n\tconst diagnostics: QualityDiagnosticV2[] = [];\n\n\tconst maxTokens = normalizeBudgetTokens(\"maxTokens\", input.maxTokens, diagnostics);\n\tconst responseReserve = normalizeBudgetTokens(\n\t\t\"responseReserveTokens\",\n\t\tinput.responseReserveTokens ?? 0,\n\t\tdiagnostics,\n\t);\n\tconst safetyMargin = normalizeBudgetTokens(\n\t\t\"safetyMarginTokens\",\n\t\tinput.safetyMarginTokens ?? Math.ceil(maxTokens * 0.05),\n\t\tdiagnostics,\n\t);\n\tconst available = Math.max(0, maxTokens - responseReserve - safetyMargin);\n\n\tconst tierPolicy: Readonly<Record<ContextBudgetTierV2, TierBudgetPolicyV2>> = {\n\t\t...DEFAULT_TIER_POLICY_V2,\n\t\t...(input.tierPolicy ?? {}),\n\t};\n\tconst basePlanned = createPlannedItems(input.items, input.tokenCounter, modelId);\n\tapplyPlannerRedundancyPenalties(basePlanned);\n\tconst rawTokens = basePlanned.reduce((sum, planned) => sum + planned.fullTokens, 0);\n\n\tconst demand = computeTierDemand(basePlanned);\n\tconst allocation = allocateTiers(available, tierPolicy, demand);\n\tconst cacheKeyBase = createContextBudgetCacheKeyBaseV2({\n\t\tbudgetBucket: input.cacheBudgetBucket ?? String(available),\n\t\tmodelId,\n\t\tnamespace: input.cacheNamespace,\n\t\tpolicyVersion,\n\t\tquery: input.query,\n\t\tqueryIntentHash: input.queryIntentHash,\n\t\tredactionPolicyHash: input.redactionPolicyHash,\n\t\tsafetyProfileHash: input.safetyProfileHash,\n\t\ttokenizerId: input.tokenizerId,\n\t});\n\tconst planCacheKey = buildContextBudgetPlanCacheKeyV2({\n\t\tavailableTokens: available,\n\t\tkeyBase: cacheKeyBase,\n\t\tmaxTokens,\n\t\tplanned: basePlanned,\n\t\tpromptHash: input.promptHash,\n\t\tqualityPolicy,\n\t\tresponseReserveTokens: responseReserve,\n\t\tsafetyMarginTokens: safetyMargin,\n\t\ttierPolicy,\n\t});\n\tconst cache = createContextBudgetSelectionCacheV2({\n\t\tkeyBase: cacheKeyBase,\n\t\tnowEpochMs: input.cacheNowEpochMs,\n\t\tplanCacheKey,\n\t\tprovider: input.cacheProvider,\n\t\tttlMs: input.cacheTtlMs,\n\t});\n\tconst cachedPlan = readValidPlanCacheV2({\n\t\tavailableTokens: available,\n\t\tcache,\n\t\tkey: planCacheKey,\n\t\tplanned: basePlanned,\n\t});\n\tif (cachedPlan) {\n\t\treturn cachedPlan;\n\t}\n\tconst selection = new Map<string, SelectedRepresentationV2>();\n\tconst tierUsed = createTierUsage();\n\tconst omitted: ContextBudgetItemV2[] = [];\n\tconst retrievalFallbacks: ContextSourceRefV2[] = [];\n\tlet usedTokens = 0;\n\n\tfor (const planned of basePlanned) {\n\t\tif (!planned.isHard) continue;\n\t\tusedTokens += selectHardItem(planned, selection, tierUsed);\n\t}\n\tif (usedTokens > available) {\n\t\tdiagnostics.push({\n\t\t\treason: \"hard_pin_over_capacity\",\n\t\t\tdetail: `hard-pinned context uses ${usedTokens} tokens against ${available} available tokens`,\n\t\t});\n\t}\n\n\tconst optionalPlanned = basePlanned.filter((planned) => !planned.isHard).sort(compareOptionalForSelection);\n\tfor (const planned of optionalPlanned) {\n\t\tusedTokens = selectOptionalItem(planned, {\n\t\t\tallocation,\n\t\t\tavailable,\n\t\t\tcache,\n\t\t\tdiagnostics,\n\t\t\tomitted,\n\t\t\tqualityPolicy,\n\t\t\tretrievalFallbacks,\n\t\t\tselection,\n\t\t\ttierUsed,\n\t\t\tusedTokens,\n\t\t});\n\t}\n\n\tconst omittedHighPriority = omitted.some((item) => item.priority === \"high\" || item.required === true);\n\temitOmissionDiagnostics(omitted, diagnostics, retrievalFallbacks);\n\temitCoverageDiagnostics(input.query, selection, diagnostics);\n\n\tconst tierAllocations = buildTierAllocations(allocation, demand, tierUsed);\n\tconst omittedTokens = omitted.reduce(\n\t\t(sum, item) => sum + (basePlanned.find((planned) => planned.item.id === item.id)?.fullTokens ?? 0),\n\t\t0,\n\t);\n\tconst omittedItemIds = omitted.map((item) => item.id);\n\tconst planHash = computePlanHash({\n\t\tpolicyVersion,\n\t\tpromptHash: input.promptHash,\n\t\tplanned: basePlanned,\n\t\tselection,\n\t\tallocations: tierAllocations,\n\t\tomittedItemIds,\n\t});\n\tconst observability = buildObservability({\n\t\tavailable,\n\t\tdiagnostics,\n\t\tomittedItemIds,\n\t\tomittedTokens,\n\t\tplanHash,\n\t\trawTokens,\n\t\tretrievalFallbacks,\n\t\tselection,\n\t\tusedTokens,\n\t\tcacheTelemetry: finalizeContextBudgetCacheTelemetryV2(cache.telemetry, {\n\t\t\tomittedTokens,\n\t\t\trawTokens,\n\t\t\tusedTokens,\n\t\t}),\n\t});\n\n\tconst plan: PromptContextBudgetPlanV2 = {\n\t\tpolicyVersion,\n\t\tpromptHash: input.promptHash,\n\t\tplanHash,\n\t\tmaxTokens,\n\t\tresponseReserveTokens: responseReserve,\n\t\tsafetyMarginTokens: safetyMargin,\n\t\tavailableTokens: available,\n\t\tusedTokens,\n\t\tomittedTokens,\n\t\trawTokens,\n\t\ttokenSavingsRatio: rawTokens > 0 ? Math.max(0, 1 - usedTokens / rawTokens) : 0,\n\t\temergency: usedTokens > available || diagnostics.some((diagnostic) => diagnostic.reason === \"invalid_budget\"),\n\t\tomittedHighPriority,\n\t\ttierAllocations,\n\t\tselectedRepresentations: [...selection.values()].sort((a, b) => a.itemId.localeCompare(b.itemId)),\n\t\tincludedItemIds: basePlanned\n\t\t\t.map((planned) => planned.item.id)\n\t\t\t.filter((id) => selection.has(id))\n\t\t\t.sort(),\n\t\tomittedItemIds,\n\t\tdiagnostics,\n\t\tretrievalFallbacks,\n\t\tobservability,\n\t};\n\twritePlanCacheV2({\n\t\tcache,\n\t\tkey: planCacheKey,\n\t\tplan,\n\t\tplanned: basePlanned,\n\t});\n\treturn plan;\n}\n\nfunction normalizeBudgetTokens(field: string, value: number, diagnostics: QualityDiagnosticV2[]): number {\n\tif (!Number.isFinite(value) || value < 0) {\n\t\tdiagnostics.push({\n\t\t\treason: \"invalid_budget\",\n\t\t\tdetail: `${field} must be a non-negative finite number, got ${value}`,\n\t\t});\n\t\treturn 0;\n\t}\n\treturn Math.floor(value);\n}\n\nfunction buildObservability(input: {\n\treadonly available: number;\n\treadonly diagnostics: readonly QualityDiagnosticV2[];\n\treadonly omittedItemIds: readonly string[];\n\treadonly omittedTokens: number;\n\treadonly planHash: string;\n\treadonly rawTokens: number;\n\treadonly retrievalFallbacks: readonly ContextSourceRefV2[];\n\treadonly selection: ReadonlyMap<string, SelectedRepresentationV2>;\n\treadonly usedTokens: number;\n\treadonly cacheTelemetry: PromptContextBudgetObservabilityV2[\"cache\"];\n}): PromptContextBudgetObservabilityV2 {\n\tconst selected = [...input.selection.values()];\n\treturn {\n\t\tcounts: {\n\t\t\tselected: selected.length,\n\t\t\tomitted: input.omittedItemIds.length,\n\t\t\tpointer: selected.filter((representation) => representation.kind === \"pointer\").length,\n\t\t\tcompressed: selected.filter((representation) => representation.kind === \"headroom-compressed\").length,\n\t\t\tfull: selected.filter((representation) => representation.kind === \"full\").length,\n\t\t\tretrievalFallback: countUniqueRetrievalFallbacks(input.retrievalFallbacks),\n\t\t},\n\t\tdiagnosticReasons: [...new Set(input.diagnostics.map((diagnostic) => diagnostic.reason))].sort(),\n\t\ttokens: {\n\t\t\tavailable: input.available,\n\t\t\tused: input.usedTokens,\n\t\t\traw: input.rawTokens,\n\t\t\tomitted: input.omittedTokens,\n\t\t\ttokenSavings: Math.max(0, input.rawTokens - input.usedTokens),\n\t\t},\n\t\tplanHash: input.planHash,\n\t\tcache: input.cacheTelemetry,\n\t\ttokenOptimizer: TOKEN_OPTIMIZER_RUNTIME_STATUS,\n\t};\n}\n\nfunction countUniqueRetrievalFallbacks(retrievalFallbacks: readonly ContextSourceRefV2[]): number {\n\treturn new Set(\n\t\tretrievalFallbacks.map((ref) =>\n\t\t\t[ref.uri, ref.contentHash, ref.symbol ?? \"\", ref.range?.startLine ?? \"\", ref.range?.endLine ?? \"\"].join(\"\\0\"),\n\t\t),\n\t).size;\n}\n"]}
|
|
@@ -1,7 +1,13 @@
|
|
|
1
1
|
import type { ContextBudgetItemV2, ContextBudgetTierV2, ContextRepresentationCacheMetadataV2, ContextRepresentationCandidateV2, ContextRepresentationKindV2, ContextSourceRefV2, HeadroomQualityPolicyV2 } from "./context-budget-headroom.ts";
|
|
2
2
|
import type { TokenCounterAdapter } from "./context-budget-token-counter.ts";
|
|
3
|
-
import type { TokenOptimizerRuntimeStatus } from "./token-optimizer.ts";
|
|
4
3
|
export declare const CONTEXT_BUDGET_POLICY_VERSION_V2 = "context-budget-v2";
|
|
4
|
+
export interface TokenOptimizerRuntimeStatus {
|
|
5
|
+
readonly optimizerId: "legacy-token-optimizer";
|
|
6
|
+
readonly status: "quarantined_compatibility";
|
|
7
|
+
readonly active: false;
|
|
8
|
+
readonly activeContextBudgetOptimizer: "context-budget-v2";
|
|
9
|
+
readonly compatibilityOnly: true;
|
|
10
|
+
}
|
|
5
11
|
export interface TierBudgetPolicyV2 {
|
|
6
12
|
readonly floorPct: number;
|
|
7
13
|
readonly ceilingPct: number;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"context-budget-v2-types.d.ts","sourceRoot":"","sources":["../../src/core/context-budget-v2-types.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kCAAkC,CAAC;CAC3D","sourcesContent":["import type {\n\tContextBudgetItemV2,\n\tContextBudgetTierV2,\n\tContextRepresentationCacheMetadataV2,\n\tContextRepresentationCandidateV2,\n\tContextRepresentationKindV2,\n\tContextSourceRefV2,\n\tHeadroomQualityPolicyV2,\n} from \"./context-budget-headroom.ts\";\nimport type { TokenCounterAdapter } from \"./context-budget-token-counter.ts\";\nimport type { TokenOptimizerRuntimeStatus } from \"./token-optimizer.ts\";\n\nexport const CONTEXT_BUDGET_POLICY_VERSION_V2 = \"context-budget-v2\";\n\nexport interface TierBudgetPolicyV2 {\n\treadonly floorPct: number;\n\treadonly ceilingPct: number;\n}\n\nexport const DEFAULT_TIER_POLICY_V2: Readonly<Record<ContextBudgetTierV2, TierBudgetPolicyV2>> = {\n\tsystem: { floorPct: 0.25, ceilingPct: 0.45 },\n\t\"active-goal\": { floorPct: 0.1, ceilingPct: 0.25 },\n\t\"current-files\": { floorPct: 0.08, ceilingPct: 0.2 },\n\ttools: { floorPct: 0.04, ceilingPct: 0.12 },\n\tskills: { floorPct: 0.03, ceilingPct: 0.12 },\n\tmcp: { floorPct: 0.02, ceilingPct: 0.08 },\n\thistory: { floorPct: 0.1, ceilingPct: 0.3 },\n\tevidence: { floorPct: 0.08, ceilingPct: 0.25 },\n\tscratch: { floorPct: 0, ceilingPct: 0.05 },\n};\n\nexport const ALL_TIERS_V2: readonly ContextBudgetTierV2[] = [\n\t\"system\",\n\t\"active-goal\",\n\t\"current-files\",\n\t\"tools\",\n\t\"skills\",\n\t\"mcp\",\n\t\"history\",\n\t\"evidence\",\n\t\"scratch\",\n];\n\nexport interface PromptContextBudgetInputV2 {\n\treadonly maxTokens: number;\n\treadonly responseReserveTokens?: number;\n\treadonly safetyMarginTokens?: number;\n\treadonly modelId?: string;\n\treadonly tokenizerId?: string;\n\treadonly policyVersion?: string;\n\treadonly promptHash?: string;\n\treadonly query?: string;\n\treadonly items: readonly ContextBudgetItemV2[];\n\treadonly tokenCounter?: TokenCounterAdapter;\n\treadonly tierPolicy?: Partial<Record<ContextBudgetTierV2, TierBudgetPolicyV2>>;\n\treadonly qualityPolicy?: HeadroomQualityPolicyV2;\n\treadonly cacheProvider?: ContextBudgetCacheProviderV2;\n\treadonly cacheNamespace?: string;\n\treadonly queryIntentHash?: string;\n\treadonly cacheBudgetBucket?: string;\n\treadonly redactionPolicyHash?: string;\n\treadonly safetyProfileHash?: string;\n\treadonly cacheNowEpochMs?: number;\n\treadonly cacheTtlMs?: number;\n}\n\nexport interface SelectedRepresentationV2 {\n\treadonly itemId: string;\n\treadonly kind: ContextRepresentationKindV2;\n\treadonly text: string;\n\treadonly estimatedTokens: number;\n\treadonly fidelity: ContextRepresentationCandidateV2[\"fidelity\"];\n\treadonly sourceRef?: ContextSourceRefV2;\n\treadonly summaryHash?: string;\n\treadonly compressorId?: string;\n\treadonly cache?: ContextRepresentationCacheMetadataV2;\n}\n\nexport interface TierBudgetAllocationV2 {\n\treadonly tier: ContextBudgetTierV2;\n\treadonly floorTokens: number;\n\treadonly ceilingTokens: number;\n\treadonly allocatedTokens: number;\n\treadonly usedTokens: number;\n\treadonly hardTokens: number;\n}\n\nexport type QualityDiagnosticReasonV2 =\n\t| \"omitted_high_priority\"\n\t| \"retrieval_miss_risk\"\n\t| \"restore_on_demand_hint\"\n\t| \"hard_pin_over_capacity\"\n\t| \"coverage_gap\"\n\t| \"tier_ceiling_exceeded\"\n\t| \"invalid_budget\";\n\nexport interface QualityDiagnosticV2 {\n\treadonly reason: QualityDiagnosticReasonV2;\n\treadonly itemId?: string;\n\treadonly detail: string;\n}\n\nexport interface ContextBudgetObservabilityCountsV2 {\n\treadonly selected: number;\n\treadonly omitted: number;\n\treadonly pointer: number;\n\treadonly compressed: number;\n\treadonly full: number;\n\treadonly retrievalFallback: number;\n}\n\nexport interface ContextBudgetObservabilityTokensV2 {\n\treadonly available: number;\n\treadonly used: number;\n\treadonly raw: number;\n\treadonly omitted: number;\n\treadonly tokenSavings: number;\n}\n\nexport type ContextBudgetCacheLayerV2 = \"turn\" | \"session\" | \"workspace\" | \"shared\";\n\nexport type ContextBudgetRepresentationCacheRejectReasonV2 =\n\t| \"fingerprint_mismatch\"\n\t| \"kind_mismatch\"\n\t| \"model_mismatch\"\n\t| \"negative\"\n\t| \"policy_mismatch\"\n\t| \"poisoned\"\n\t| \"source_hash_mismatch\"\n\t| \"stale\"\n\t| \"token_invalid\"\n\t| \"tokenizer_mismatch\";\n\nexport type ContextBudgetRepresentationCacheKeyKindV2 = \"exact\" | \"materialized\";\n\nexport interface ContextBudgetMaterializedVerificationV2 {\n\treadonly queryCoverage?: number;\n\treadonly sourceCoverage?: number;\n\treadonly secretLeakScore?: number;\n\treadonly poisonScore?: number;\n\treadonly validatorVersion?: string;\n}\n\nexport interface ContextBudgetRepresentationCacheEntryV2 {\n\treadonly kind: ContextRepresentationKindV2;\n\treadonly text: string;\n\treadonly estimatedTokens: number;\n\treadonly fidelity: ContextRepresentationCandidateV2[\"fidelity\"];\n\treadonly sourceHash: string;\n\treadonly representationFingerprint: string;\n\treadonly keyKind?: ContextBudgetRepresentationCacheKeyKindV2;\n\treadonly modelId: string;\n\treadonly tokenizerId: string;\n\treadonly policyVersion: string;\n\treadonly sourceRef?: ContextSourceRefV2;\n\treadonly summaryHash?: string;\n\treadonly compressorId?: string;\n\treadonly compressorPolicyHash?: string;\n\treadonly qualityPolicyHash?: string;\n\treadonly queryIntentCluster?: string;\n\treadonly outputTextHash?: string;\n\treadonly targetTokenBucket?: number;\n\treadonly verification?: ContextBudgetMaterializedVerificationV2;\n\treadonly createdAtEpochMs?: number;\n}\n\nexport interface ContextBudgetRepresentationCacheReadV2 {\n\treadonly entry: ContextBudgetRepresentationCacheEntryV2;\n\treadonly layer?: ContextBudgetCacheLayerV2;\n}\n\nexport interface ContextBudgetNegativeCacheEntryV2 {\n\treadonly reason: string;\n\treadonly createdAtEpochMs?: number;\n\treadonly layer?: ContextBudgetCacheLayerV2;\n}\n\nexport interface ContextBudgetPlanCacheEntryV2 {\n\treadonly plan: PromptContextBudgetPlanV2;\n\treadonly sourceHashes: Readonly<Record<string, string>>;\n\treadonly createdAtEpochMs?: number;\n}\n\nexport interface ContextBudgetPlanCacheReadV2 {\n\treadonly entry: ContextBudgetPlanCacheEntryV2;\n\treadonly layer?: ContextBudgetCacheLayerV2;\n}\n\nexport interface ContextBudgetCacheProviderV2 {\n\treadRepresentation(key: string): ContextBudgetRepresentationCacheReadV2 | undefined;\n\twriteRepresentation(input: { readonly key: string; readonly entry: ContextBudgetRepresentationCacheEntryV2 }): void;\n\treadNegativeRepresentation(key: string): ContextBudgetNegativeCacheEntryV2 | undefined;\n\twriteNegativeRepresentation(input: { readonly key: string; readonly reason: string }): void;\n\treadPlan(key: string): ContextBudgetPlanCacheReadV2 | undefined;\n\twritePlan(input: { readonly key: string; readonly entry: ContextBudgetPlanCacheEntryV2 }): void;\n}\n\nexport interface ContextBudgetPlanCacheTelemetryV2 {\n\treadonly hit: boolean;\n\treadonly key: string;\n\treadonly layer?: ContextBudgetCacheLayerV2;\n\treadonly rejectedReason?: string;\n}\n\nexport interface ContextBudgetRepresentationCacheTelemetryV2 {\n\treadonly exactHits: number;\n\treadonly semanticHits: number;\n\treadonly pointerHits: number;\n\treadonly misses: number;\n\treadonly staleRejects: number;\n\treadonly poisonRejects: number;\n\treadonly negativeHits: number;\n\treadonly writes: number;\n}\n\nexport interface ContextBudgetCacheTokenTelemetryV2 {\n\treadonly raw: number;\n\treadonly rendered: number;\n\treadonly savedByCache: number;\n\treadonly savedByCompression: number;\n\treadonly savedByOmission: number;\n}\n\nexport interface TokenCacheTelemetryV2 {\n\treadonly planCache: ContextBudgetPlanCacheTelemetryV2;\n\treadonly representationCache: ContextBudgetRepresentationCacheTelemetryV2;\n\treadonly tokens: ContextBudgetCacheTokenTelemetryV2;\n}\n\nexport interface PromptContextBudgetObservabilityV2 {\n\treadonly counts: ContextBudgetObservabilityCountsV2;\n\treadonly diagnosticReasons: readonly QualityDiagnosticReasonV2[];\n\treadonly tokens: ContextBudgetObservabilityTokensV2;\n\treadonly planHash: string;\n\treadonly cache: TokenCacheTelemetryV2;\n\treadonly tokenOptimizer: TokenOptimizerRuntimeStatus;\n}\n\nexport interface PromptContextBudgetPlanV2 {\n\treadonly policyVersion: string;\n\treadonly promptHash?: string;\n\treadonly planHash: string;\n\treadonly maxTokens: number;\n\treadonly responseReserveTokens: number;\n\treadonly safetyMarginTokens: number;\n\treadonly availableTokens: number;\n\treadonly usedTokens: number;\n\treadonly omittedTokens: number;\n\treadonly rawTokens: number;\n\treadonly tokenSavingsRatio: number;\n\treadonly emergency: boolean;\n\treadonly omittedHighPriority: boolean;\n\treadonly tierAllocations: readonly TierBudgetAllocationV2[];\n\treadonly selectedRepresentations: readonly SelectedRepresentationV2[];\n\treadonly includedItemIds: readonly string[];\n\treadonly omittedItemIds: readonly string[];\n\treadonly diagnostics: readonly QualityDiagnosticV2[];\n\treadonly retrievalFallbacks: readonly ContextSourceRefV2[];\n\treadonly observability: PromptContextBudgetObservabilityV2;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"context-budget-v2-types.d.ts","sourceRoot":"","sources":["../../src/core/context-budget-v2-types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACX,mBAAmB,EACnB,mBAAmB,EACnB,oCAAoC,EACpC,gCAAgC,EAChC,2BAA2B,EAC3B,kBAAkB,EAClB,uBAAuB,EACvB,MAAM,8BAA8B,CAAC;AACtC,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,mCAAmC,CAAC;AAE7E,eAAO,MAAM,gCAAgC,sBAAsB,CAAC;AAIpE,MAAM,WAAW,2BAA2B;IAC3C,QAAQ,CAAC,WAAW,EAAE,wBAAwB,CAAC;IAC/C,QAAQ,CAAC,MAAM,EAAE,2BAA2B,CAAC;IAC7C,QAAQ,CAAC,MAAM,EAAE,KAAK,CAAC;IACvB,QAAQ,CAAC,4BAA4B,EAAE,mBAAmB,CAAC;IAC3D,QAAQ,CAAC,iBAA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CAAC;IAC/B,QAAQ,CAAC,UAAU,CAAC,EAAE,MAAM,CAAC;IAC7B,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;IAC1B,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC;IAC3B,QAAQ,CAAC,qBAAqB,EAAE,MAAM,CAAC;IACvC,QAAQ,CAAC,kBAAkB,EAAE,MAAM,CAAC;IACpC,QAAQ,CAAC,eAAe,EAAE,MAAM,CAAC;IACjC,QAAQ,CAAC,UAAU,EAAE,MAAM,CAAC;IAC5B,QAAQ,CAAC,aAAa,EAAE,MAAM,CAAC;IAC/B,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC;IAC3B,QAAQ,CAAC,iBAAiB,EAAE,MAAM,CAAC;IACnC,QAAQ,CAAC,SAAS,EAAE,OAAO,CAAC;IAC5B,QAAQ,CAAC,mBAAmB,EAAE,OAAO,CAAC;IACtC,QAAQ,CAAC,eAAe,EAAE,SAAS,sBAAsB,EAAE,CAAC;IAC5D,QAAQ,CAAC,uBAAuB,EAAE,SAAS,wBAAwB,EAAE,CAAC;IACtE,QAAQ,CAAC,eAAe,EAAE,SAAS,MAAM,EAAE,CAAC;IAC5C,QAAQ,CAAC,cAAc,EAAE,SAAS,MAAM,EAAE,CAAC;IAC3C,QAAQ,CAAC,WAAW,EAAE,SAAS,mBAAmB,EAAE,CAAC;IACrD,QAAQ,CAAC,kBAAkB,EAAE,SAAS,kBAAkB,EAAE,CAAC;IAC3D,QAAQ,CAAC,aAAa,EAAE,kCAAkC,CAAC;CAC3D","sourcesContent":["import type {\n\tContextBudgetItemV2,\n\tContextBudgetTierV2,\n\tContextRepresentationCacheMetadataV2,\n\tContextRepresentationCandidateV2,\n\tContextRepresentationKindV2,\n\tContextSourceRefV2,\n\tHeadroomQualityPolicyV2,\n} from \"./context-budget-headroom.ts\";\nimport type { TokenCounterAdapter } from \"./context-budget-token-counter.ts\";\n\nexport const CONTEXT_BUDGET_POLICY_VERSION_V2 = \"context-budget-v2\";\n\n// Inlined from the deleted token-optimizer.ts (legacy quarantine-compatibility\n// status; legacy-token-optimizer itself no longer exists as a module).\nexport interface TokenOptimizerRuntimeStatus {\n\treadonly optimizerId: \"legacy-token-optimizer\";\n\treadonly status: \"quarantined_compatibility\";\n\treadonly active: false;\n\treadonly activeContextBudgetOptimizer: \"context-budget-v2\";\n\treadonly compatibilityOnly: true;\n}\n\nexport interface TierBudgetPolicyV2 {\n\treadonly floorPct: number;\n\treadonly ceilingPct: number;\n}\n\nexport const DEFAULT_TIER_POLICY_V2: Readonly<Record<ContextBudgetTierV2, TierBudgetPolicyV2>> = {\n\tsystem: { floorPct: 0.25, ceilingPct: 0.45 },\n\t\"active-goal\": { floorPct: 0.1, ceilingPct: 0.25 },\n\t\"current-files\": { floorPct: 0.08, ceilingPct: 0.2 },\n\ttools: { floorPct: 0.04, ceilingPct: 0.12 },\n\tskills: { floorPct: 0.03, ceilingPct: 0.12 },\n\tmcp: { floorPct: 0.02, ceilingPct: 0.08 },\n\thistory: { floorPct: 0.1, ceilingPct: 0.3 },\n\tevidence: { floorPct: 0.08, ceilingPct: 0.25 },\n\tscratch: { floorPct: 0, ceilingPct: 0.05 },\n};\n\nexport const ALL_TIERS_V2: readonly ContextBudgetTierV2[] = [\n\t\"system\",\n\t\"active-goal\",\n\t\"current-files\",\n\t\"tools\",\n\t\"skills\",\n\t\"mcp\",\n\t\"history\",\n\t\"evidence\",\n\t\"scratch\",\n];\n\nexport interface PromptContextBudgetInputV2 {\n\treadonly maxTokens: number;\n\treadonly responseReserveTokens?: number;\n\treadonly safetyMarginTokens?: number;\n\treadonly modelId?: string;\n\treadonly tokenizerId?: string;\n\treadonly policyVersion?: string;\n\treadonly promptHash?: string;\n\treadonly query?: string;\n\treadonly items: readonly ContextBudgetItemV2[];\n\treadonly tokenCounter?: TokenCounterAdapter;\n\treadonly tierPolicy?: Partial<Record<ContextBudgetTierV2, TierBudgetPolicyV2>>;\n\treadonly qualityPolicy?: HeadroomQualityPolicyV2;\n\treadonly cacheProvider?: ContextBudgetCacheProviderV2;\n\treadonly cacheNamespace?: string;\n\treadonly queryIntentHash?: string;\n\treadonly cacheBudgetBucket?: string;\n\treadonly redactionPolicyHash?: string;\n\treadonly safetyProfileHash?: string;\n\treadonly cacheNowEpochMs?: number;\n\treadonly cacheTtlMs?: number;\n}\n\nexport interface SelectedRepresentationV2 {\n\treadonly itemId: string;\n\treadonly kind: ContextRepresentationKindV2;\n\treadonly text: string;\n\treadonly estimatedTokens: number;\n\treadonly fidelity: ContextRepresentationCandidateV2[\"fidelity\"];\n\treadonly sourceRef?: ContextSourceRefV2;\n\treadonly summaryHash?: string;\n\treadonly compressorId?: string;\n\treadonly cache?: ContextRepresentationCacheMetadataV2;\n}\n\nexport interface TierBudgetAllocationV2 {\n\treadonly tier: ContextBudgetTierV2;\n\treadonly floorTokens: number;\n\treadonly ceilingTokens: number;\n\treadonly allocatedTokens: number;\n\treadonly usedTokens: number;\n\treadonly hardTokens: number;\n}\n\nexport type QualityDiagnosticReasonV2 =\n\t| \"omitted_high_priority\"\n\t| \"retrieval_miss_risk\"\n\t| \"restore_on_demand_hint\"\n\t| \"hard_pin_over_capacity\"\n\t| \"coverage_gap\"\n\t| \"tier_ceiling_exceeded\"\n\t| \"invalid_budget\";\n\nexport interface QualityDiagnosticV2 {\n\treadonly reason: QualityDiagnosticReasonV2;\n\treadonly itemId?: string;\n\treadonly detail: string;\n}\n\nexport interface ContextBudgetObservabilityCountsV2 {\n\treadonly selected: number;\n\treadonly omitted: number;\n\treadonly pointer: number;\n\treadonly compressed: number;\n\treadonly full: number;\n\treadonly retrievalFallback: number;\n}\n\nexport interface ContextBudgetObservabilityTokensV2 {\n\treadonly available: number;\n\treadonly used: number;\n\treadonly raw: number;\n\treadonly omitted: number;\n\treadonly tokenSavings: number;\n}\n\nexport type ContextBudgetCacheLayerV2 = \"turn\" | \"session\" | \"workspace\" | \"shared\";\n\nexport type ContextBudgetRepresentationCacheRejectReasonV2 =\n\t| \"fingerprint_mismatch\"\n\t| \"kind_mismatch\"\n\t| \"model_mismatch\"\n\t| \"negative\"\n\t| \"policy_mismatch\"\n\t| \"poisoned\"\n\t| \"source_hash_mismatch\"\n\t| \"stale\"\n\t| \"token_invalid\"\n\t| \"tokenizer_mismatch\";\n\nexport type ContextBudgetRepresentationCacheKeyKindV2 = \"exact\" | \"materialized\";\n\nexport interface ContextBudgetMaterializedVerificationV2 {\n\treadonly queryCoverage?: number;\n\treadonly sourceCoverage?: number;\n\treadonly secretLeakScore?: number;\n\treadonly poisonScore?: number;\n\treadonly validatorVersion?: string;\n}\n\nexport interface ContextBudgetRepresentationCacheEntryV2 {\n\treadonly kind: ContextRepresentationKindV2;\n\treadonly text: string;\n\treadonly estimatedTokens: number;\n\treadonly fidelity: ContextRepresentationCandidateV2[\"fidelity\"];\n\treadonly sourceHash: string;\n\treadonly representationFingerprint: string;\n\treadonly keyKind?: ContextBudgetRepresentationCacheKeyKindV2;\n\treadonly modelId: string;\n\treadonly tokenizerId: string;\n\treadonly policyVersion: string;\n\treadonly sourceRef?: ContextSourceRefV2;\n\treadonly summaryHash?: string;\n\treadonly compressorId?: string;\n\treadonly compressorPolicyHash?: string;\n\treadonly qualityPolicyHash?: string;\n\treadonly queryIntentCluster?: string;\n\treadonly outputTextHash?: string;\n\treadonly targetTokenBucket?: number;\n\treadonly verification?: ContextBudgetMaterializedVerificationV2;\n\treadonly createdAtEpochMs?: number;\n}\n\nexport interface ContextBudgetRepresentationCacheReadV2 {\n\treadonly entry: ContextBudgetRepresentationCacheEntryV2;\n\treadonly layer?: ContextBudgetCacheLayerV2;\n}\n\nexport interface ContextBudgetNegativeCacheEntryV2 {\n\treadonly reason: string;\n\treadonly createdAtEpochMs?: number;\n\treadonly layer?: ContextBudgetCacheLayerV2;\n}\n\nexport interface ContextBudgetPlanCacheEntryV2 {\n\treadonly plan: PromptContextBudgetPlanV2;\n\treadonly sourceHashes: Readonly<Record<string, string>>;\n\treadonly createdAtEpochMs?: number;\n}\n\nexport interface ContextBudgetPlanCacheReadV2 {\n\treadonly entry: ContextBudgetPlanCacheEntryV2;\n\treadonly layer?: ContextBudgetCacheLayerV2;\n}\n\nexport interface ContextBudgetCacheProviderV2 {\n\treadRepresentation(key: string): ContextBudgetRepresentationCacheReadV2 | undefined;\n\twriteRepresentation(input: { readonly key: string; readonly entry: ContextBudgetRepresentationCacheEntryV2 }): void;\n\treadNegativeRepresentation(key: string): ContextBudgetNegativeCacheEntryV2 | undefined;\n\twriteNegativeRepresentation(input: { readonly key: string; readonly reason: string }): void;\n\treadPlan(key: string): ContextBudgetPlanCacheReadV2 | undefined;\n\twritePlan(input: { readonly key: string; readonly entry: ContextBudgetPlanCacheEntryV2 }): void;\n}\n\nexport interface ContextBudgetPlanCacheTelemetryV2 {\n\treadonly hit: boolean;\n\treadonly key: string;\n\treadonly layer?: ContextBudgetCacheLayerV2;\n\treadonly rejectedReason?: string;\n}\n\nexport interface ContextBudgetRepresentationCacheTelemetryV2 {\n\treadonly exactHits: number;\n\treadonly semanticHits: number;\n\treadonly pointerHits: number;\n\treadonly misses: number;\n\treadonly staleRejects: number;\n\treadonly poisonRejects: number;\n\treadonly negativeHits: number;\n\treadonly writes: number;\n}\n\nexport interface ContextBudgetCacheTokenTelemetryV2 {\n\treadonly raw: number;\n\treadonly rendered: number;\n\treadonly savedByCache: number;\n\treadonly savedByCompression: number;\n\treadonly savedByOmission: number;\n}\n\nexport interface TokenCacheTelemetryV2 {\n\treadonly planCache: ContextBudgetPlanCacheTelemetryV2;\n\treadonly representationCache: ContextBudgetRepresentationCacheTelemetryV2;\n\treadonly tokens: ContextBudgetCacheTokenTelemetryV2;\n}\n\nexport interface PromptContextBudgetObservabilityV2 {\n\treadonly counts: ContextBudgetObservabilityCountsV2;\n\treadonly diagnosticReasons: readonly QualityDiagnosticReasonV2[];\n\treadonly tokens: ContextBudgetObservabilityTokensV2;\n\treadonly planHash: string;\n\treadonly cache: TokenCacheTelemetryV2;\n\treadonly tokenOptimizer: TokenOptimizerRuntimeStatus;\n}\n\nexport interface PromptContextBudgetPlanV2 {\n\treadonly policyVersion: string;\n\treadonly promptHash?: string;\n\treadonly planHash: string;\n\treadonly maxTokens: number;\n\treadonly responseReserveTokens: number;\n\treadonly safetyMarginTokens: number;\n\treadonly availableTokens: number;\n\treadonly usedTokens: number;\n\treadonly omittedTokens: number;\n\treadonly rawTokens: number;\n\treadonly tokenSavingsRatio: number;\n\treadonly emergency: boolean;\n\treadonly omittedHighPriority: boolean;\n\treadonly tierAllocations: readonly TierBudgetAllocationV2[];\n\treadonly selectedRepresentations: readonly SelectedRepresentationV2[];\n\treadonly includedItemIds: readonly string[];\n\treadonly omittedItemIds: readonly string[];\n\treadonly diagnostics: readonly QualityDiagnosticV2[];\n\treadonly retrievalFallbacks: readonly ContextSourceRefV2[];\n\treadonly observability: PromptContextBudgetObservabilityV2;\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"context-budget-v2-types.js","sourceRoot":"","sources":["../../src/core/context-budget-v2-types.ts"],"names":[],"mappings":"AAYA,MAAM,CAAC,MAAM,gCAAgC,GAAG,mBAAmB,CAAC;AAOpE,MAAM,CAAC,MAAM,sBAAsB,GAA8D;IAChG,MAAM,EAAE,EAAE,QAAQ,EAAE,IAAI,EAAE,UAAU,EAAE,IAAI,EAAE;IAC5C,aAAa,EAAE,EAAE,QAAQ,EAAE,GAAG,EAAE,UAAU,EAAE,IAAI,EAAE;IAClD,eAAe,EAAE,EAAE,QAAQ,EAAE,IAAI,EAAE,UAAU,EAAE,GAAG,EAAE;IACpD,KAAK,EAAE,EAAE,QAAQ,EAAE,IAAI,EAAE,UAAU,EAAE,IAAI,EAAE;IAC3C,MAAM,EAAE,EAAE,QAAQ,EAAE,IAAI,EAAE,UAAU,EAAE,IAAI,EAAE;IAC5C,GAAG,EAAE,EAAE,QAAQ,EAAE,IAAI,EAAE,UAAU,EAAE,IAAI,EAAE;IACzC,OAAO,EAAE,EAAE,QAAQ,EAAE,GAAG,EAAE,UAAU,EAAE,GAAG,EAAE;IAC3C,QAAQ,EAAE,EAAE,QAAQ,EAAE,IAAI,EAAE,UAAU,EAAE,IAAI,EAAE;IAC9C,OAAO,EAAE,EAAE,QAAQ,EAAE,CAAC,EAAE,UAAU,EAAE,IAAI,EAAE;CAC1C,CAAC;AAEF,MAAM,CAAC,MAAM,YAAY,GAAmC;IAC3D,QAAQ;IACR,aAAa;IACb,eAAe;IACf,OAAO;IACP,QAAQ;IACR,KAAK;IACL,SAAS;IACT,UAAU;IACV,SAAS;CACT,CAAC","sourcesContent":["import type {\n\tContextBudgetItemV2,\n\tContextBudgetTierV2,\n\tContextRepresentationCacheMetadataV2,\n\tContextRepresentationCandidateV2,\n\tContextRepresentationKindV2,\n\tContextSourceRefV2,\n\tHeadroomQualityPolicyV2,\n} from \"./context-budget-headroom.ts\";\nimport type { TokenCounterAdapter } from \"./context-budget-token-counter.ts\";\nimport type { TokenOptimizerRuntimeStatus } from \"./token-optimizer.ts\";\n\nexport const CONTEXT_BUDGET_POLICY_VERSION_V2 = \"context-budget-v2\";\n\nexport interface TierBudgetPolicyV2 {\n\treadonly floorPct: number;\n\treadonly ceilingPct: number;\n}\n\nexport const DEFAULT_TIER_POLICY_V2: Readonly<Record<ContextBudgetTierV2, TierBudgetPolicyV2>> = {\n\tsystem: { floorPct: 0.25, ceilingPct: 0.45 },\n\t\"active-goal\": { floorPct: 0.1, ceilingPct: 0.25 },\n\t\"current-files\": { floorPct: 0.08, ceilingPct: 0.2 },\n\ttools: { floorPct: 0.04, ceilingPct: 0.12 },\n\tskills: { floorPct: 0.03, ceilingPct: 0.12 },\n\tmcp: { floorPct: 0.02, ceilingPct: 0.08 },\n\thistory: { floorPct: 0.1, ceilingPct: 0.3 },\n\tevidence: { floorPct: 0.08, ceilingPct: 0.25 },\n\tscratch: { floorPct: 0, ceilingPct: 0.05 },\n};\n\nexport const ALL_TIERS_V2: readonly ContextBudgetTierV2[] = [\n\t\"system\",\n\t\"active-goal\",\n\t\"current-files\",\n\t\"tools\",\n\t\"skills\",\n\t\"mcp\",\n\t\"history\",\n\t\"evidence\",\n\t\"scratch\",\n];\n\nexport interface PromptContextBudgetInputV2 {\n\treadonly maxTokens: number;\n\treadonly responseReserveTokens?: number;\n\treadonly safetyMarginTokens?: number;\n\treadonly modelId?: string;\n\treadonly tokenizerId?: string;\n\treadonly policyVersion?: string;\n\treadonly promptHash?: string;\n\treadonly query?: string;\n\treadonly items: readonly ContextBudgetItemV2[];\n\treadonly tokenCounter?: TokenCounterAdapter;\n\treadonly tierPolicy?: Partial<Record<ContextBudgetTierV2, TierBudgetPolicyV2>>;\n\treadonly qualityPolicy?: HeadroomQualityPolicyV2;\n\treadonly cacheProvider?: ContextBudgetCacheProviderV2;\n\treadonly cacheNamespace?: string;\n\treadonly queryIntentHash?: string;\n\treadonly cacheBudgetBucket?: string;\n\treadonly redactionPolicyHash?: string;\n\treadonly safetyProfileHash?: string;\n\treadonly cacheNowEpochMs?: number;\n\treadonly cacheTtlMs?: number;\n}\n\nexport interface SelectedRepresentationV2 {\n\treadonly itemId: string;\n\treadonly kind: ContextRepresentationKindV2;\n\treadonly text: string;\n\treadonly estimatedTokens: number;\n\treadonly fidelity: ContextRepresentationCandidateV2[\"fidelity\"];\n\treadonly sourceRef?: ContextSourceRefV2;\n\treadonly summaryHash?: string;\n\treadonly compressorId?: string;\n\treadonly cache?: ContextRepresentationCacheMetadataV2;\n}\n\nexport interface TierBudgetAllocationV2 {\n\treadonly tier: ContextBudgetTierV2;\n\treadonly floorTokens: number;\n\treadonly ceilingTokens: number;\n\treadonly allocatedTokens: number;\n\treadonly usedTokens: number;\n\treadonly hardTokens: number;\n}\n\nexport type QualityDiagnosticReasonV2 =\n\t| \"omitted_high_priority\"\n\t| \"retrieval_miss_risk\"\n\t| \"restore_on_demand_hint\"\n\t| \"hard_pin_over_capacity\"\n\t| \"coverage_gap\"\n\t| \"tier_ceiling_exceeded\"\n\t| \"invalid_budget\";\n\nexport interface QualityDiagnosticV2 {\n\treadonly reason: QualityDiagnosticReasonV2;\n\treadonly itemId?: string;\n\treadonly detail: string;\n}\n\nexport interface ContextBudgetObservabilityCountsV2 {\n\treadonly selected: number;\n\treadonly omitted: number;\n\treadonly pointer: number;\n\treadonly compressed: number;\n\treadonly full: number;\n\treadonly retrievalFallback: number;\n}\n\nexport interface ContextBudgetObservabilityTokensV2 {\n\treadonly available: number;\n\treadonly used: number;\n\treadonly raw: number;\n\treadonly omitted: number;\n\treadonly tokenSavings: number;\n}\n\nexport type ContextBudgetCacheLayerV2 = \"turn\" | \"session\" | \"workspace\" | \"shared\";\n\nexport type ContextBudgetRepresentationCacheRejectReasonV2 =\n\t| \"fingerprint_mismatch\"\n\t| \"kind_mismatch\"\n\t| \"model_mismatch\"\n\t| \"negative\"\n\t| \"policy_mismatch\"\n\t| \"poisoned\"\n\t| \"source_hash_mismatch\"\n\t| \"stale\"\n\t| \"token_invalid\"\n\t| \"tokenizer_mismatch\";\n\nexport type ContextBudgetRepresentationCacheKeyKindV2 = \"exact\" | \"materialized\";\n\nexport interface ContextBudgetMaterializedVerificationV2 {\n\treadonly queryCoverage?: number;\n\treadonly sourceCoverage?: number;\n\treadonly secretLeakScore?: number;\n\treadonly poisonScore?: number;\n\treadonly validatorVersion?: string;\n}\n\nexport interface ContextBudgetRepresentationCacheEntryV2 {\n\treadonly kind: ContextRepresentationKindV2;\n\treadonly text: string;\n\treadonly estimatedTokens: number;\n\treadonly fidelity: ContextRepresentationCandidateV2[\"fidelity\"];\n\treadonly sourceHash: string;\n\treadonly representationFingerprint: string;\n\treadonly keyKind?: ContextBudgetRepresentationCacheKeyKindV2;\n\treadonly modelId: string;\n\treadonly tokenizerId: string;\n\treadonly policyVersion: string;\n\treadonly sourceRef?: ContextSourceRefV2;\n\treadonly summaryHash?: string;\n\treadonly compressorId?: string;\n\treadonly compressorPolicyHash?: string;\n\treadonly qualityPolicyHash?: string;\n\treadonly queryIntentCluster?: string;\n\treadonly outputTextHash?: string;\n\treadonly targetTokenBucket?: number;\n\treadonly verification?: ContextBudgetMaterializedVerificationV2;\n\treadonly createdAtEpochMs?: number;\n}\n\nexport interface ContextBudgetRepresentationCacheReadV2 {\n\treadonly entry: ContextBudgetRepresentationCacheEntryV2;\n\treadonly layer?: ContextBudgetCacheLayerV2;\n}\n\nexport interface ContextBudgetNegativeCacheEntryV2 {\n\treadonly reason: string;\n\treadonly createdAtEpochMs?: number;\n\treadonly layer?: ContextBudgetCacheLayerV2;\n}\n\nexport interface ContextBudgetPlanCacheEntryV2 {\n\treadonly plan: PromptContextBudgetPlanV2;\n\treadonly sourceHashes: Readonly<Record<string, string>>;\n\treadonly createdAtEpochMs?: number;\n}\n\nexport interface ContextBudgetPlanCacheReadV2 {\n\treadonly entry: ContextBudgetPlanCacheEntryV2;\n\treadonly layer?: ContextBudgetCacheLayerV2;\n}\n\nexport interface ContextBudgetCacheProviderV2 {\n\treadRepresentation(key: string): ContextBudgetRepresentationCacheReadV2 | undefined;\n\twriteRepresentation(input: { readonly key: string; readonly entry: ContextBudgetRepresentationCacheEntryV2 }): void;\n\treadNegativeRepresentation(key: string): ContextBudgetNegativeCacheEntryV2 | undefined;\n\twriteNegativeRepresentation(input: { readonly key: string; readonly reason: string }): void;\n\treadPlan(key: string): ContextBudgetPlanCacheReadV2 | undefined;\n\twritePlan(input: { readonly key: string; readonly entry: ContextBudgetPlanCacheEntryV2 }): void;\n}\n\nexport interface ContextBudgetPlanCacheTelemetryV2 {\n\treadonly hit: boolean;\n\treadonly key: string;\n\treadonly layer?: ContextBudgetCacheLayerV2;\n\treadonly rejectedReason?: string;\n}\n\nexport interface ContextBudgetRepresentationCacheTelemetryV2 {\n\treadonly exactHits: number;\n\treadonly semanticHits: number;\n\treadonly pointerHits: number;\n\treadonly misses: number;\n\treadonly staleRejects: number;\n\treadonly poisonRejects: number;\n\treadonly negativeHits: number;\n\treadonly writes: number;\n}\n\nexport interface ContextBudgetCacheTokenTelemetryV2 {\n\treadonly raw: number;\n\treadonly rendered: number;\n\treadonly savedByCache: number;\n\treadonly savedByCompression: number;\n\treadonly savedByOmission: number;\n}\n\nexport interface TokenCacheTelemetryV2 {\n\treadonly planCache: ContextBudgetPlanCacheTelemetryV2;\n\treadonly representationCache: ContextBudgetRepresentationCacheTelemetryV2;\n\treadonly tokens: ContextBudgetCacheTokenTelemetryV2;\n}\n\nexport interface PromptContextBudgetObservabilityV2 {\n\treadonly counts: ContextBudgetObservabilityCountsV2;\n\treadonly diagnosticReasons: readonly QualityDiagnosticReasonV2[];\n\treadonly tokens: ContextBudgetObservabilityTokensV2;\n\treadonly planHash: string;\n\treadonly cache: TokenCacheTelemetryV2;\n\treadonly tokenOptimizer: TokenOptimizerRuntimeStatus;\n}\n\nexport interface PromptContextBudgetPlanV2 {\n\treadonly policyVersion: string;\n\treadonly promptHash?: string;\n\treadonly planHash: string;\n\treadonly maxTokens: number;\n\treadonly responseReserveTokens: number;\n\treadonly safetyMarginTokens: number;\n\treadonly availableTokens: number;\n\treadonly usedTokens: number;\n\treadonly omittedTokens: number;\n\treadonly rawTokens: number;\n\treadonly tokenSavingsRatio: number;\n\treadonly emergency: boolean;\n\treadonly omittedHighPriority: boolean;\n\treadonly tierAllocations: readonly TierBudgetAllocationV2[];\n\treadonly selectedRepresentations: readonly SelectedRepresentationV2[];\n\treadonly includedItemIds: readonly string[];\n\treadonly omittedItemIds: readonly string[];\n\treadonly diagnostics: readonly QualityDiagnosticV2[];\n\treadonly retrievalFallbacks: readonly ContextSourceRefV2[];\n\treadonly observability: PromptContextBudgetObservabilityV2;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"context-budget-v2-types.js","sourceRoot":"","sources":["../../src/core/context-budget-v2-types.ts"],"names":[],"mappings":"AAWA,MAAM,CAAC,MAAM,gCAAgC,GAAG,mBAAmB,CAAC;AAiBpE,MAAM,CAAC,MAAM,sBAAsB,GAA8D;IAChG,MAAM,EAAE,EAAE,QAAQ,EAAE,IAAI,EAAE,UAAU,EAAE,IAAI,EAAE;IAC5C,aAAa,EAAE,EAAE,QAAQ,EAAE,GAAG,EAAE,UAAU,EAAE,IAAI,EAAE;IAClD,eAAe,EAAE,EAAE,QAAQ,EAAE,IAAI,EAAE,UAAU,EAAE,GAAG,EAAE;IACpD,KAAK,EAAE,EAAE,QAAQ,EAAE,IAAI,EAAE,UAAU,EAAE,IAAI,EAAE;IAC3C,MAAM,EAAE,EAAE,QAAQ,EAAE,IAAI,EAAE,UAAU,EAAE,IAAI,EAAE;IAC5C,GAAG,EAAE,EAAE,QAAQ,EAAE,IAAI,EAAE,UAAU,EAAE,IAAI,EAAE;IACzC,OAAO,EAAE,EAAE,QAAQ,EAAE,GAAG,EAAE,UAAU,EAAE,GAAG,EAAE;IAC3C,QAAQ,EAAE,EAAE,QAAQ,EAAE,IAAI,EAAE,UAAU,EAAE,IAAI,EAAE;IAC9C,OAAO,EAAE,EAAE,QAAQ,EAAE,CAAC,EAAE,UAAU,EAAE,IAAI,EAAE;CAC1C,CAAC;AAEF,MAAM,CAAC,MAAM,YAAY,GAAmC;IAC3D,QAAQ;IACR,aAAa;IACb,eAAe;IACf,OAAO;IACP,QAAQ;IACR,KAAK;IACL,SAAS;IACT,UAAU;IACV,SAAS;CACT,CAAC","sourcesContent":["import type {\n\tContextBudgetItemV2,\n\tContextBudgetTierV2,\n\tContextRepresentationCacheMetadataV2,\n\tContextRepresentationCandidateV2,\n\tContextRepresentationKindV2,\n\tContextSourceRefV2,\n\tHeadroomQualityPolicyV2,\n} from \"./context-budget-headroom.ts\";\nimport type { TokenCounterAdapter } from \"./context-budget-token-counter.ts\";\n\nexport const CONTEXT_BUDGET_POLICY_VERSION_V2 = \"context-budget-v2\";\n\n// Inlined from the deleted token-optimizer.ts (legacy quarantine-compatibility\n// status; legacy-token-optimizer itself no longer exists as a module).\nexport interface TokenOptimizerRuntimeStatus {\n\treadonly optimizerId: \"legacy-token-optimizer\";\n\treadonly status: \"quarantined_compatibility\";\n\treadonly active: false;\n\treadonly activeContextBudgetOptimizer: \"context-budget-v2\";\n\treadonly compatibilityOnly: true;\n}\n\nexport interface TierBudgetPolicyV2 {\n\treadonly floorPct: number;\n\treadonly ceilingPct: number;\n}\n\nexport const DEFAULT_TIER_POLICY_V2: Readonly<Record<ContextBudgetTierV2, TierBudgetPolicyV2>> = {\n\tsystem: { floorPct: 0.25, ceilingPct: 0.45 },\n\t\"active-goal\": { floorPct: 0.1, ceilingPct: 0.25 },\n\t\"current-files\": { floorPct: 0.08, ceilingPct: 0.2 },\n\ttools: { floorPct: 0.04, ceilingPct: 0.12 },\n\tskills: { floorPct: 0.03, ceilingPct: 0.12 },\n\tmcp: { floorPct: 0.02, ceilingPct: 0.08 },\n\thistory: { floorPct: 0.1, ceilingPct: 0.3 },\n\tevidence: { floorPct: 0.08, ceilingPct: 0.25 },\n\tscratch: { floorPct: 0, ceilingPct: 0.05 },\n};\n\nexport const ALL_TIERS_V2: readonly ContextBudgetTierV2[] = [\n\t\"system\",\n\t\"active-goal\",\n\t\"current-files\",\n\t\"tools\",\n\t\"skills\",\n\t\"mcp\",\n\t\"history\",\n\t\"evidence\",\n\t\"scratch\",\n];\n\nexport interface PromptContextBudgetInputV2 {\n\treadonly maxTokens: number;\n\treadonly responseReserveTokens?: number;\n\treadonly safetyMarginTokens?: number;\n\treadonly modelId?: string;\n\treadonly tokenizerId?: string;\n\treadonly policyVersion?: string;\n\treadonly promptHash?: string;\n\treadonly query?: string;\n\treadonly items: readonly ContextBudgetItemV2[];\n\treadonly tokenCounter?: TokenCounterAdapter;\n\treadonly tierPolicy?: Partial<Record<ContextBudgetTierV2, TierBudgetPolicyV2>>;\n\treadonly qualityPolicy?: HeadroomQualityPolicyV2;\n\treadonly cacheProvider?: ContextBudgetCacheProviderV2;\n\treadonly cacheNamespace?: string;\n\treadonly queryIntentHash?: string;\n\treadonly cacheBudgetBucket?: string;\n\treadonly redactionPolicyHash?: string;\n\treadonly safetyProfileHash?: string;\n\treadonly cacheNowEpochMs?: number;\n\treadonly cacheTtlMs?: number;\n}\n\nexport interface SelectedRepresentationV2 {\n\treadonly itemId: string;\n\treadonly kind: ContextRepresentationKindV2;\n\treadonly text: string;\n\treadonly estimatedTokens: number;\n\treadonly fidelity: ContextRepresentationCandidateV2[\"fidelity\"];\n\treadonly sourceRef?: ContextSourceRefV2;\n\treadonly summaryHash?: string;\n\treadonly compressorId?: string;\n\treadonly cache?: ContextRepresentationCacheMetadataV2;\n}\n\nexport interface TierBudgetAllocationV2 {\n\treadonly tier: ContextBudgetTierV2;\n\treadonly floorTokens: number;\n\treadonly ceilingTokens: number;\n\treadonly allocatedTokens: number;\n\treadonly usedTokens: number;\n\treadonly hardTokens: number;\n}\n\nexport type QualityDiagnosticReasonV2 =\n\t| \"omitted_high_priority\"\n\t| \"retrieval_miss_risk\"\n\t| \"restore_on_demand_hint\"\n\t| \"hard_pin_over_capacity\"\n\t| \"coverage_gap\"\n\t| \"tier_ceiling_exceeded\"\n\t| \"invalid_budget\";\n\nexport interface QualityDiagnosticV2 {\n\treadonly reason: QualityDiagnosticReasonV2;\n\treadonly itemId?: string;\n\treadonly detail: string;\n}\n\nexport interface ContextBudgetObservabilityCountsV2 {\n\treadonly selected: number;\n\treadonly omitted: number;\n\treadonly pointer: number;\n\treadonly compressed: number;\n\treadonly full: number;\n\treadonly retrievalFallback: number;\n}\n\nexport interface ContextBudgetObservabilityTokensV2 {\n\treadonly available: number;\n\treadonly used: number;\n\treadonly raw: number;\n\treadonly omitted: number;\n\treadonly tokenSavings: number;\n}\n\nexport type ContextBudgetCacheLayerV2 = \"turn\" | \"session\" | \"workspace\" | \"shared\";\n\nexport type ContextBudgetRepresentationCacheRejectReasonV2 =\n\t| \"fingerprint_mismatch\"\n\t| \"kind_mismatch\"\n\t| \"model_mismatch\"\n\t| \"negative\"\n\t| \"policy_mismatch\"\n\t| \"poisoned\"\n\t| \"source_hash_mismatch\"\n\t| \"stale\"\n\t| \"token_invalid\"\n\t| \"tokenizer_mismatch\";\n\nexport type ContextBudgetRepresentationCacheKeyKindV2 = \"exact\" | \"materialized\";\n\nexport interface ContextBudgetMaterializedVerificationV2 {\n\treadonly queryCoverage?: number;\n\treadonly sourceCoverage?: number;\n\treadonly secretLeakScore?: number;\n\treadonly poisonScore?: number;\n\treadonly validatorVersion?: string;\n}\n\nexport interface ContextBudgetRepresentationCacheEntryV2 {\n\treadonly kind: ContextRepresentationKindV2;\n\treadonly text: string;\n\treadonly estimatedTokens: number;\n\treadonly fidelity: ContextRepresentationCandidateV2[\"fidelity\"];\n\treadonly sourceHash: string;\n\treadonly representationFingerprint: string;\n\treadonly keyKind?: ContextBudgetRepresentationCacheKeyKindV2;\n\treadonly modelId: string;\n\treadonly tokenizerId: string;\n\treadonly policyVersion: string;\n\treadonly sourceRef?: ContextSourceRefV2;\n\treadonly summaryHash?: string;\n\treadonly compressorId?: string;\n\treadonly compressorPolicyHash?: string;\n\treadonly qualityPolicyHash?: string;\n\treadonly queryIntentCluster?: string;\n\treadonly outputTextHash?: string;\n\treadonly targetTokenBucket?: number;\n\treadonly verification?: ContextBudgetMaterializedVerificationV2;\n\treadonly createdAtEpochMs?: number;\n}\n\nexport interface ContextBudgetRepresentationCacheReadV2 {\n\treadonly entry: ContextBudgetRepresentationCacheEntryV2;\n\treadonly layer?: ContextBudgetCacheLayerV2;\n}\n\nexport interface ContextBudgetNegativeCacheEntryV2 {\n\treadonly reason: string;\n\treadonly createdAtEpochMs?: number;\n\treadonly layer?: ContextBudgetCacheLayerV2;\n}\n\nexport interface ContextBudgetPlanCacheEntryV2 {\n\treadonly plan: PromptContextBudgetPlanV2;\n\treadonly sourceHashes: Readonly<Record<string, string>>;\n\treadonly createdAtEpochMs?: number;\n}\n\nexport interface ContextBudgetPlanCacheReadV2 {\n\treadonly entry: ContextBudgetPlanCacheEntryV2;\n\treadonly layer?: ContextBudgetCacheLayerV2;\n}\n\nexport interface ContextBudgetCacheProviderV2 {\n\treadRepresentation(key: string): ContextBudgetRepresentationCacheReadV2 | undefined;\n\twriteRepresentation(input: { readonly key: string; readonly entry: ContextBudgetRepresentationCacheEntryV2 }): void;\n\treadNegativeRepresentation(key: string): ContextBudgetNegativeCacheEntryV2 | undefined;\n\twriteNegativeRepresentation(input: { readonly key: string; readonly reason: string }): void;\n\treadPlan(key: string): ContextBudgetPlanCacheReadV2 | undefined;\n\twritePlan(input: { readonly key: string; readonly entry: ContextBudgetPlanCacheEntryV2 }): void;\n}\n\nexport interface ContextBudgetPlanCacheTelemetryV2 {\n\treadonly hit: boolean;\n\treadonly key: string;\n\treadonly layer?: ContextBudgetCacheLayerV2;\n\treadonly rejectedReason?: string;\n}\n\nexport interface ContextBudgetRepresentationCacheTelemetryV2 {\n\treadonly exactHits: number;\n\treadonly semanticHits: number;\n\treadonly pointerHits: number;\n\treadonly misses: number;\n\treadonly staleRejects: number;\n\treadonly poisonRejects: number;\n\treadonly negativeHits: number;\n\treadonly writes: number;\n}\n\nexport interface ContextBudgetCacheTokenTelemetryV2 {\n\treadonly raw: number;\n\treadonly rendered: number;\n\treadonly savedByCache: number;\n\treadonly savedByCompression: number;\n\treadonly savedByOmission: number;\n}\n\nexport interface TokenCacheTelemetryV2 {\n\treadonly planCache: ContextBudgetPlanCacheTelemetryV2;\n\treadonly representationCache: ContextBudgetRepresentationCacheTelemetryV2;\n\treadonly tokens: ContextBudgetCacheTokenTelemetryV2;\n}\n\nexport interface PromptContextBudgetObservabilityV2 {\n\treadonly counts: ContextBudgetObservabilityCountsV2;\n\treadonly diagnosticReasons: readonly QualityDiagnosticReasonV2[];\n\treadonly tokens: ContextBudgetObservabilityTokensV2;\n\treadonly planHash: string;\n\treadonly cache: TokenCacheTelemetryV2;\n\treadonly tokenOptimizer: TokenOptimizerRuntimeStatus;\n}\n\nexport interface PromptContextBudgetPlanV2 {\n\treadonly policyVersion: string;\n\treadonly promptHash?: string;\n\treadonly planHash: string;\n\treadonly maxTokens: number;\n\treadonly responseReserveTokens: number;\n\treadonly safetyMarginTokens: number;\n\treadonly availableTokens: number;\n\treadonly usedTokens: number;\n\treadonly omittedTokens: number;\n\treadonly rawTokens: number;\n\treadonly tokenSavingsRatio: number;\n\treadonly emergency: boolean;\n\treadonly omittedHighPriority: boolean;\n\treadonly tierAllocations: readonly TierBudgetAllocationV2[];\n\treadonly selectedRepresentations: readonly SelectedRepresentationV2[];\n\treadonly includedItemIds: readonly string[];\n\treadonly omittedItemIds: readonly string[];\n\treadonly diagnostics: readonly QualityDiagnosticV2[];\n\treadonly retrievalFallbacks: readonly ContextSourceRefV2[];\n\treadonly observability: PromptContextBudgetObservabilityV2;\n}\n"]}
|
|
@@ -1,26 +1,17 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* Reasoning-router bias compiler —
|
|
2
|
+
* Reasoning-router bias compiler — privacy-safe learning ledger.
|
|
3
3
|
*
|
|
4
|
-
* Pure, deterministic compiler from
|
|
5
|
-
*
|
|
6
|
-
*
|
|
7
|
-
*
|
|
8
|
-
*
|
|
9
|
-
*
|
|
10
|
-
* agent-session.ts by this lane.
|
|
11
|
-
*
|
|
12
|
-
* Goal 010 Lane I addition: `isRouterBiasCell` / `isRouterBiasSnapshot` /
|
|
13
|
-
* `parseRouterBiasSnapshot` / `getDefaultRouterBiasSnapshotPath` below let a
|
|
14
|
-
* (now opt-in) caller safely load a snapshot this module previously only
|
|
15
|
-
* wrote. `parseRouterBiasSnapshot` performs no filesystem access itself — it
|
|
16
|
-
* only validates already-read text — so this module's zero-I/O determinism
|
|
17
|
-
* guarantee for `compileBiasSnapshot`/`getBiasStepsForCell` is unchanged; the
|
|
18
|
-
* actual disk read lives in agent-session.ts.
|
|
4
|
+
* Pure, deterministic compiler from v4 feedback records (see
|
|
5
|
+
* router-feedback-collector.ts) to a bounded, per-cell reasoning-level bias
|
|
6
|
+
* snapshot. No clock, randomness, network, or model calls: the same input array
|
|
7
|
+
* always produces the same output (`JSON.stringify` byte-identical), regardless
|
|
8
|
+
* of input record order. `parseRouterBiasSnapshot` performs no filesystem
|
|
9
|
+
* access itself; the actual disk read lives in agent-session.ts.
|
|
19
10
|
*/
|
|
20
11
|
import { type RouterFeedbackLaneType, type RouterFeedbackLenBucket, type RouterFeedbackTaskClass, type RouterFeedbackVersion } from "./router-feedback-collector.ts";
|
|
21
12
|
/** Minimum non-neutral ("strong") record count per cell before any bias applies. */
|
|
22
13
|
export declare const BIAS_STRONG_THRESHOLD = 5;
|
|
23
|
-
/** Bias magnitude bound, matching the resolver's
|
|
14
|
+
/** Bias magnitude bound, matching the resolver's bias clamp. */
|
|
24
15
|
export declare const BIAS_MAX_STEPS = 2;
|
|
25
16
|
/** Bounded per-cell bias, in ladder steps. Never outside [-2, 2]. */
|
|
26
17
|
export type RouterBiasSteps = -2 | -1 | 0 | 1 | 2;
|
|
@@ -52,12 +43,9 @@ export interface RouterBiasSnapshot {
|
|
|
52
43
|
}
|
|
53
44
|
export interface CompileBiasSnapshotOptions {
|
|
54
45
|
/**
|
|
55
|
-
* Restrict compilation to one router version
|
|
56
|
-
*
|
|
57
|
-
*
|
|
58
|
-
* counted in `droppedCount`. Defaults to "v3" for API compatibility; the
|
|
59
|
-
* offline CLI now defaults to "v4", matching the only auto-router wired to
|
|
60
|
-
* consume a learning-bias snapshot at runtime.
|
|
46
|
+
* Restrict compilation to one router version. The only supported runtime
|
|
47
|
+
* router version is v4; records tagged with any other value are invalid and
|
|
48
|
+
* counted in `droppedCount`.
|
|
61
49
|
*/
|
|
62
50
|
readonly routerVersion?: RouterFeedbackVersion;
|
|
63
51
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"reasoning-router-bias.d.ts","sourceRoot":"","sources":["../../src/core/reasoning-router-bias.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;GAkBG;AAKH,OAAO,EAKN,KAAK,sBAAsB,EAC3B,KAAK,uBAAuB,EAE5B,KAAK,uBAAuB,EAC5B,KAAK,qBAAqB,EAC1B,MAAM,gCAAgC,CAAC;AAExC,oFAAoF;AACpF,eAAO,MAAM,qBAAqB,IA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AED,6GAA6G;AAC7G,wBAAgB,mBAAmB,CAAC,QAAQ,EAAE,kBAAkB,EAAE,GAAG,EAAE,iBAAiB,GAAG,eAAe,CAMzG;AAwDD;;;;;;;;;GASG;AACH,wBAAgB,gBAAgB,CAAC,KAAK,EAAE,OAAO,GAAG,KAAK,IAAI,cAAc,CAaxE;AAED;;;;;GAKG;AACH,wBAAgB,oBAAoB,CAAC,KAAK,EAAE,OAAO,GAAG,KAAK,IAAI,kBAAkB,CAYhF;AAED;;;;;;GAMG;AACH,wBAAgB,uBAAuB,CAAC,GAAG,EAAE,MAAM,GAAG,kBAAkB,GAAG,IAAI,CAQ9E;AAED;;;;;;;;GAQG;AACH,wBAAgB,gCAAgC,CAAC,OAAO,GAAE,qBAA4B,GAAG,MAAM,CAE9F","sourcesContent":["/**\n * Reasoning-router bias compiler — Goal 009 Wave 1 Lane L (privacy-safe learning ledger).\n *\n * Pure, deterministic compiler from a set of privacy-safe feedback records\n * (see router-feedback-collector.ts) to a bounded, per-cell reasoning-level\n * bias snapshot. No clock, randomness, network, or model calls: the same\n * input array always produces the same output (`JSON.stringify` byte-\n * identical), regardless of input record order. This module is a standalone,\n * pure utility — nothing here is wired into a router resolver or\n * agent-session.ts by this lane.\n *\n * Goal 010 Lane I addition: `isRouterBiasCell` / `isRouterBiasSnapshot` /\n * `parseRouterBiasSnapshot` / `getDefaultRouterBiasSnapshotPath` below let a\n * (now opt-in) caller safely load a snapshot this module previously only\n * wrote. `parseRouterBiasSnapshot` performs no filesystem access itself — it\n * only validates already-read text — so this module's zero-I/O determinism\n * guarantee for `compileBiasSnapshot`/`getBiasStepsForCell` is unchanged; the\n * actual disk read lives in agent-session.ts.\n */\n\nimport { createHash } from \"crypto\";\nimport { join } from \"path\";\nimport { getAgentDir } from \"../config.ts\";\nimport {\n\tisRouterFeedbackRecord,\n\tROUTER_FEEDBACK_LANE_TYPES,\n\tROUTER_FEEDBACK_LEN_BUCKETS,\n\tROUTER_FEEDBACK_TASK_CLASSES,\n\ttype RouterFeedbackLaneType,\n\ttype RouterFeedbackLenBucket,\n\ttype RouterFeedbackRecord,\n\ttype RouterFeedbackTaskClass,\n\ttype RouterFeedbackVersion,\n} from \"./router-feedback-collector.ts\";\n\n/** Minimum non-neutral (\"strong\") record count per cell before any bias applies. */\nexport const BIAS_STRONG_THRESHOLD = 5;\n\n/** Bias magnitude bound, matching the resolver's existing bias clamp (reasoning-router-v2.ts BIAS_MAX). */\nexport const BIAS_MAX_STEPS = 2;\n\n/** Bounded per-cell bias, in ladder steps. Never outside [-2, 2]. */\nexport type RouterBiasSteps = -2 | -1 | 0 | 1 | 2;\n\n/** The feature tuple a bias cell is keyed on — identical dimensions the router already computes locally. */\nexport interface RouterBiasCellKey {\n\treadonly predictedClass: RouterFeedbackTaskClass;\n\treadonly laneType: RouterFeedbackLaneType;\n\treadonly lenBucket: RouterFeedbackLenBucket;\n\treadonly hadFence: boolean;\n\treadonly hadDiff: boolean;\n}\n\nexport interface RouterBiasCell extends RouterBiasCellKey {\n\treadonly biasSteps: RouterBiasSteps;\n\t/** Non-neutral (up/down-signaling) record count for this cell. */\n\treadonly nStrong: number;\n\t/** Total record count for this cell, including neutral (accepted/same/pass) records. */\n\treadonly nTotal: number;\n}\n\nexport interface RouterBiasSnapshot {\n\treadonly schemaVersion: \"router-bias-snapshot/v1\";\n\t/** sha256 hex digest of the canonicalized valid-record set actually compiled; not a prompt hash. */\n\treadonly sourceRecordDigest: string;\n\t/** Count of records that were validated and included in this snapshot. */\n\treadonly consideredCount: number;\n\t/** Count of records excluded from this snapshot (schema-invalid, or router-version mismatch). */\n\treadonly droppedCount: number;\n\t/** Bias cells, sorted deterministically. Empty when there is no ledger data or no cell reaches the threshold. */\n\treadonly biasCells: readonly RouterBiasCell[];\n}\n\nexport interface CompileBiasSnapshotOptions {\n\t/**\n\t * Restrict compilation to one router version — `compileBiasSnapshot` never\n\t * mixes records from different router versions into one snapshot. Records\n\t * tagged with any other `routerVersion` are excluded from this snapshot and\n\t * counted in `droppedCount`. Defaults to \"v3\" for API compatibility; the\n\t * offline CLI now defaults to \"v4\", matching the only auto-router wired to\n\t * consume a learning-bias snapshot at runtime.\n\t */\n\treadonly routerVersion?: RouterFeedbackVersion;\n}\n\nfunction cellKeyString(key: RouterBiasCellKey): string {\n\treturn [key.predictedClass, key.laneType, String(key.lenBucket), String(key.hadFence), String(key.hadDiff)].join(\n\t\t\"|\",\n\t);\n}\n\n/** +1 \"needed more effort\", -1 \"needed less effort\", 0 neutral (no directional bias contribution). */\nfunction outcomeDirection(outcome: RouterFeedbackRecord[\"outcome\"]): -1 | 0 | 1 {\n\tif (outcome === \"up\" || outcome === \"fail\" || outcome === \"debug-follow-up\") return 1;\n\tif (outcome === \"down\") return -1;\n\treturn 0;\n}\n\n/** Fixed-key-order JSON so identical records always canonicalize to identical bytes. */\nfunction canonicalRecordJson(record: RouterFeedbackRecord): string {\n\treturn JSON.stringify({\n\t\trouterVersion: record.routerVersion,\n\t\tlaneType: record.laneType,\n\t\tpredictedClass: record.predictedClass,\n\t\tresolvedLevel: record.resolvedLevel,\n\t\tacceptedLevel: record.acceptedLevel,\n\t\tsignal: record.signal,\n\t\toutcome: record.outcome,\n\t\tlenBucket: record.lenBucket,\n\t\thadFence: record.hadFence,\n\t\thadDiff: record.hadDiff,\n\t});\n}\n\ninterface CellAccumulator extends RouterBiasCellKey {\n\tnTotal: number;\n\tupVotes: number;\n\tdownVotes: number;\n}\n\nfunction computeBiasSteps(upVotes: number, downVotes: number, nStrong: number): RouterBiasSteps {\n\tif (nStrong < BIAS_STRONG_THRESHOLD) return 0;\n\tconst majority = upVotes - downVotes;\n\tif (majority === 0) return 0;\n\n\tconst dominance = Math.abs(majority) / nStrong;\n\tconst magnitude = dominance >= 0.75 ? BIAS_MAX_STEPS : 1;\n\tconst signedMagnitude = majority > 0 ? magnitude : -magnitude;\n\treturn Math.max(-BIAS_MAX_STEPS, Math.min(BIAS_MAX_STEPS, signedMagnitude)) as RouterBiasSteps;\n}\n\n/**\n * Deterministically compile a bounded bias snapshot from raw (possibly\n * malformed) ledger entries. Unknown-shaped entries — including ones with\n * extra keys, missing keys, or out-of-range enum values — are dropped and\n * counted, never thrown. Records tagged with a `routerVersion` other than the\n * target version are also dropped and counted (never merged across router\n * versions into one snapshot). An empty or all-dropped input compiles to an\n * empty-bias snapshot (`biasCells: []`), which is exactly the shipped\n * no-learning behavior — this makes \"empty ledger -> zero bias\" true by\n * construction, not by a special case.\n *\n * Pure: same `records` (any order) -> same `RouterBiasSnapshot` (byte-\n * identical `JSON.stringify` output), because cells are grouped by an\n * order-independent key and the emitted cell/record ordering is always\n * sorted before serialization.\n */\nexport function compileBiasSnapshot(\n\trecords: readonly unknown[],\n\toptions: CompileBiasSnapshotOptions = {},\n): RouterBiasSnapshot {\n\tconst routerVersion = options.routerVersion ?? \"v3\";\n\tconst valid: RouterFeedbackRecord[] = [];\n\tlet droppedCount = 0;\n\n\tfor (const entry of records) {\n\t\tif (isRouterFeedbackRecord(entry) && entry.routerVersion === routerVersion) {\n\t\t\tvalid.push(entry);\n\t\t} else {\n\t\t\tdroppedCount += 1;\n\t\t}\n\t}\n\n\tconst cells = new Map<string, CellAccumulator>();\n\tfor (const record of valid) {\n\t\tconst key: RouterBiasCellKey = {\n\t\t\tpredictedClass: record.predictedClass,\n\t\t\tlaneType: record.laneType,\n\t\t\tlenBucket: record.lenBucket,\n\t\t\thadFence: record.hadFence,\n\t\t\thadDiff: record.hadDiff,\n\t\t};\n\t\tconst mapKey = cellKeyString(key);\n\t\tconst existing = cells.get(mapKey) ?? { ...key, nTotal: 0, upVotes: 0, downVotes: 0 };\n\t\texisting.nTotal += 1;\n\t\tconst direction = outcomeDirection(record.outcome);\n\t\tif (direction === 1) existing.upVotes += 1;\n\t\telse if (direction === -1) existing.downVotes += 1;\n\t\tcells.set(mapKey, existing);\n\t}\n\n\tconst biasCells: RouterBiasCell[] = [];\n\tfor (const mapKey of [...cells.keys()].sort()) {\n\t\tconst acc = cells.get(mapKey);\n\t\tif (!acc) continue;\n\t\tconst nStrong = acc.upVotes + acc.downVotes;\n\t\tbiasCells.push({\n\t\t\tpredictedClass: acc.predictedClass,\n\t\t\tlaneType: acc.laneType,\n\t\t\tlenBucket: acc.lenBucket,\n\t\t\thadFence: acc.hadFence,\n\t\t\thadDiff: acc.hadDiff,\n\t\t\tbiasSteps: computeBiasSteps(acc.upVotes, acc.downVotes, nStrong),\n\t\t\tnStrong,\n\t\t\tnTotal: acc.nTotal,\n\t\t});\n\t}\n\n\tconst canonicalValid = valid.map(canonicalRecordJson).sort();\n\tconst sourceRecordDigest = createHash(\"sha256\").update(canonicalValid.join(\"\\n\")).digest(\"hex\");\n\n\treturn {\n\t\tschemaVersion: \"router-bias-snapshot/v1\",\n\t\tsourceRecordDigest,\n\t\tconsideredCount: valid.length,\n\t\tdroppedCount,\n\t\tbiasCells,\n\t};\n}\n\n/** Look up the compiled bias for one feature cell; 0 (no bias) when the cell is absent from the snapshot. */\nexport function getBiasStepsForCell(snapshot: RouterBiasSnapshot, key: RouterBiasCellKey): RouterBiasSteps {\n\tconst wantKey = cellKeyString(key);\n\tfor (const cell of snapshot.biasCells) {\n\t\tif (cellKeyString(cell) === wantKey) return cell.biasSteps;\n\t}\n\treturn 0;\n}\n\n// ============================================================================\n// Snapshot parser / loader (Goal 010 Lane I)\n// ============================================================================\n//\n// Everything below lets a caller safely turn untrusted on-disk JSON text into\n// a validated RouterBiasSnapshot. Same posture as isRouterFeedbackRecord in\n// router-feedback-collector.ts: an exact positive key-set allowlist (not a\n// denylist), bounded per-field checks reusing the ledger's own closed enums,\n// and \"never throw, return null/false instead\" on any malformed input.\n\n/** Bounded bias-step values a compiled cell may carry; mirrors RouterBiasSteps. */\nconst ROUTER_BIAS_STEPS_VALUES: readonly RouterBiasSteps[] = [-2, -1, 0, 1, 2];\n\n/** Exact allowed key set for one compiled `RouterBiasCell`, sorted for canonical set-equality comparison. */\nconst ROUTER_BIAS_CELL_KEYS: readonly string[] = [\n\t\"predictedClass\",\n\t\"laneType\",\n\t\"lenBucket\",\n\t\"hadFence\",\n\t\"hadDiff\",\n\t\"biasSteps\",\n\t\"nStrong\",\n\t\"nTotal\",\n].sort();\n\n/** Exact allowed key set for a `RouterBiasSnapshot`, sorted for canonical set-equality comparison. */\nconst ROUTER_BIAS_SNAPSHOT_KEYS: readonly string[] = [\n\t\"schemaVersion\",\n\t\"sourceRecordDigest\",\n\t\"consideredCount\",\n\t\"droppedCount\",\n\t\"biasCells\",\n].sort();\n\n/** sha256 hex digest shape check for `sourceRecordDigest` (never trusts the value is actually a real digest of anything, only that it has the right shape). */\nconst SHA256_HEX_PATTERN = /^[0-9a-f]{64}$/;\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction hasExactKeySet(value: Record<string, unknown>, allowedSortedKeys: readonly string[]): boolean {\n\tconst keys = Object.keys(value).sort();\n\tif (keys.length !== allowedSortedKeys.length) return false;\n\tfor (let i = 0; i < keys.length; i++) {\n\t\tif (keys[i] !== allowedSortedKeys[i]) return false;\n\t}\n\treturn true;\n}\n\nfunction isBoundedNonNegativeInteger(value: unknown): value is number {\n\treturn typeof value === \"number\" && Number.isInteger(value) && value >= 0;\n}\n\n/**\n * Strict runtime validator for one compiled bias cell. Exact eight-key\n * allowlist plus bounded per-field checks, reusing the same closed enums as\n * `isRouterFeedbackRecord` (`ROUTER_FEEDBACK_TASK_CLASSES`,\n * `ROUTER_FEEDBACK_LANE_TYPES`, `ROUTER_FEEDBACK_LEN_BUCKETS`) so this\n * validator cannot silently drift from the ledger's own schema. `nStrong` is\n * additionally required to never exceed `nTotal` (true by construction for\n * every cell `compileBiasSnapshot` can produce; a cheap sanity bound against\n * a hand-tampered file).\n */\nexport function isRouterBiasCell(value: unknown): value is RouterBiasCell {\n\tif (!isPlainObject(value)) return false;\n\tif (!hasExactKeySet(value, ROUTER_BIAS_CELL_KEYS)) return false;\n\tif (!ROUTER_FEEDBACK_TASK_CLASSES.includes(value.predictedClass as RouterFeedbackTaskClass)) return false;\n\tif (!ROUTER_FEEDBACK_LANE_TYPES.includes(value.laneType as RouterFeedbackLaneType)) return false;\n\tif (!ROUTER_FEEDBACK_LEN_BUCKETS.includes(value.lenBucket as RouterFeedbackLenBucket)) return false;\n\tif (typeof value.hadFence !== \"boolean\") return false;\n\tif (typeof value.hadDiff !== \"boolean\") return false;\n\tif (!ROUTER_BIAS_STEPS_VALUES.includes(value.biasSteps as RouterBiasSteps)) return false;\n\tif (!isBoundedNonNegativeInteger(value.nStrong)) return false;\n\tif (!isBoundedNonNegativeInteger(value.nTotal)) return false;\n\tif ((value.nStrong as number) > (value.nTotal as number)) return false;\n\treturn true;\n}\n\n/**\n * Strict runtime validator for a compiled bias snapshot. Exact five-key\n * allowlist; `biasCells` must be an array whose every element passes\n * `isRouterBiasCell`. Never trusts on-disk content: any unexpected shape,\n * extra key, or out-of-range value returns `false` rather than throwing.\n */\nexport function isRouterBiasSnapshot(value: unknown): value is RouterBiasSnapshot {\n\tif (!isPlainObject(value)) return false;\n\tif (!hasExactKeySet(value, ROUTER_BIAS_SNAPSHOT_KEYS)) return false;\n\tif (value.schemaVersion !== \"router-bias-snapshot/v1\") return false;\n\tif (typeof value.sourceRecordDigest !== \"string\" || !SHA256_HEX_PATTERN.test(value.sourceRecordDigest)) return false;\n\tif (!isBoundedNonNegativeInteger(value.consideredCount)) return false;\n\tif (!isBoundedNonNegativeInteger(value.droppedCount)) return false;\n\tif (!Array.isArray(value.biasCells)) return false;\n\tfor (const cell of value.biasCells) {\n\t\tif (!isRouterBiasCell(cell)) return false;\n\t}\n\treturn true;\n}\n\n/**\n * Safe parse of raw (untrusted, e.g. on-disk) JSON text into a validated\n * `RouterBiasSnapshot`. Never throws: malformed JSON or any schema violation\n * returns `null`. Performs no filesystem access itself — callers own the\n * actual read — so this module's zero-I/O determinism guarantee for\n * `compileBiasSnapshot`/`getBiasStepsForCell` is unaffected.\n */\nexport function parseRouterBiasSnapshot(raw: string): RouterBiasSnapshot | null {\n\tlet parsed: unknown;\n\ttry {\n\t\tparsed = JSON.parse(raw);\n\t} catch {\n\t\treturn null;\n\t}\n\treturn isRouterBiasSnapshot(parsed) ? parsed : null;\n}\n\n/**\n * Default compiled-bias-snapshot path:\n * `<agentDir>/router-feedback/weights/router-bias-snapshot.<version>.json` —\n * matches `compile-bias-snapshot.ts`'s own default `--out` naming exactly, so\n * a snapshot compiled offline for `version` is found here with no extra\n * configuration. Owner-only agent dir, never repo-local (mirrors\n * `getDefaultRouterFeedbackLedgerPath`). Defaults to \"v4\", the router version\n * this lane wires bias *consumption* for.\n */\nexport function getDefaultRouterBiasSnapshotPath(version: RouterFeedbackVersion = \"v4\"): string {\n\treturn join(getAgentDir(), \"router-feedback\", \"weights\", `router-bias-snapshot.${version}.json`);\n}\n"]}
|
|
1
|
+
{"version":3,"file":"reasoning-router-bias.d.ts","sourceRoot":"","sources":["../../src/core/reasoning-router-bias.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAKH,OAAO,EAKN,KAAK,sBAAsB,EAC3B,KAAK,uBAAuB,EAE5B,KAAK,uBAAuB,EAC5B,KAAK,qBAAqB,EAC1B,MAAM,gCAAgC,CAAC;AAExC,oFAAoF;AACpF,eAAO,MAAM,qBAAqB,IAAI,CAAC;AAEvC,gEAAgE;AAChE,eAAO,MAAM,cAAc,IAAI,CAAC;AAEhC,qEAAqE;AACrE,MAAM,MAAM,eAAe,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;AAElD,8GAA4G;AAC5G,MAAM,WAAW,iBAAiB;IACjC,QAAQ,CAAC,cAAc,EAAE,uBAAuB,CAAC;IACjD,QAAQ,CAAC,QAAQ,EAAE,sBAAsB,CAAC;IAC1C,QAAQ,CAAC,SAAS,EAAE,uBAAuB,CAAC;IAC5C,QAAQ,CAAC,QAAQ,EAAE,OAAO,CAAC;IAC3B,QAAQ,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BAAgB,gCAAgC,CAAC,OAAO,GAAE,qBAA4B,GAAG,MAAM,CAE9F","sourcesContent":["/**\n * Reasoning-router bias compiler — privacy-safe learning ledger.\n *\n * Pure, deterministic compiler from v4 feedback records (see\n * router-feedback-collector.ts) to a bounded, per-cell reasoning-level bias\n * snapshot. No clock, randomness, network, or model calls: the same input array\n * always produces the same output (`JSON.stringify` byte-identical), regardless\n * of input record order. `parseRouterBiasSnapshot` performs no filesystem\n * access itself; the actual disk read lives in agent-session.ts.\n */\n\nimport { createHash } from \"crypto\";\nimport { join } from \"path\";\nimport { getAgentDir } from \"../config.ts\";\nimport {\n\tisRouterFeedbackRecord,\n\tROUTER_FEEDBACK_LANE_TYPES,\n\tROUTER_FEEDBACK_LEN_BUCKETS,\n\tROUTER_FEEDBACK_TASK_CLASSES,\n\ttype RouterFeedbackLaneType,\n\ttype RouterFeedbackLenBucket,\n\ttype RouterFeedbackRecord,\n\ttype RouterFeedbackTaskClass,\n\ttype RouterFeedbackVersion,\n} from \"./router-feedback-collector.ts\";\n\n/** Minimum non-neutral (\"strong\") record count per cell before any bias applies. */\nexport const BIAS_STRONG_THRESHOLD = 5;\n\n/** Bias magnitude bound, matching the resolver's bias clamp. */\nexport const BIAS_MAX_STEPS = 2;\n\n/** Bounded per-cell bias, in ladder steps. Never outside [-2, 2]. */\nexport type RouterBiasSteps = -2 | -1 | 0 | 1 | 2;\n\n/** The feature tuple a bias cell is keyed on — identical dimensions the router already computes locally. */\nexport interface RouterBiasCellKey {\n\treadonly predictedClass: RouterFeedbackTaskClass;\n\treadonly laneType: RouterFeedbackLaneType;\n\treadonly lenBucket: RouterFeedbackLenBucket;\n\treadonly hadFence: boolean;\n\treadonly hadDiff: boolean;\n}\n\nexport interface RouterBiasCell extends RouterBiasCellKey {\n\treadonly biasSteps: RouterBiasSteps;\n\t/** Non-neutral (up/down-signaling) record count for this cell. */\n\treadonly nStrong: number;\n\t/** Total record count for this cell, including neutral (accepted/same/pass) records. */\n\treadonly nTotal: number;\n}\n\nexport interface RouterBiasSnapshot {\n\treadonly schemaVersion: \"router-bias-snapshot/v1\";\n\t/** sha256 hex digest of the canonicalized valid-record set actually compiled; not a prompt hash. */\n\treadonly sourceRecordDigest: string;\n\t/** Count of records that were validated and included in this snapshot. */\n\treadonly consideredCount: number;\n\t/** Count of records excluded from this snapshot (schema-invalid, or router-version mismatch). */\n\treadonly droppedCount: number;\n\t/** Bias cells, sorted deterministically. Empty when there is no ledger data or no cell reaches the threshold. */\n\treadonly biasCells: readonly RouterBiasCell[];\n}\n\nexport interface CompileBiasSnapshotOptions {\n\t/**\n\t * Restrict compilation to one router version. The only supported runtime\n\t * router version is v4; records tagged with any other value are invalid and\n\t * counted in `droppedCount`.\n\t */\n\treadonly routerVersion?: RouterFeedbackVersion;\n}\n\nfunction cellKeyString(key: RouterBiasCellKey): string {\n\treturn [key.predictedClass, key.laneType, String(key.lenBucket), String(key.hadFence), String(key.hadDiff)].join(\n\t\t\"|\",\n\t);\n}\n\n/** +1 \"needed more effort\", -1 \"needed less effort\", 0 neutral (no directional bias contribution). */\nfunction outcomeDirection(outcome: RouterFeedbackRecord[\"outcome\"]): -1 | 0 | 1 {\n\tif (outcome === \"up\" || outcome === \"fail\" || outcome === \"debug-follow-up\") return 1;\n\tif (outcome === \"down\") return -1;\n\treturn 0;\n}\n\n/** Fixed-key-order JSON so identical records always canonicalize to identical bytes. */\nfunction canonicalRecordJson(record: RouterFeedbackRecord): string {\n\treturn JSON.stringify({\n\t\trouterVersion: record.routerVersion,\n\t\tlaneType: record.laneType,\n\t\tpredictedClass: record.predictedClass,\n\t\tresolvedLevel: record.resolvedLevel,\n\t\tacceptedLevel: record.acceptedLevel,\n\t\tsignal: record.signal,\n\t\toutcome: record.outcome,\n\t\tlenBucket: record.lenBucket,\n\t\thadFence: record.hadFence,\n\t\thadDiff: record.hadDiff,\n\t});\n}\n\ninterface CellAccumulator extends RouterBiasCellKey {\n\tnTotal: number;\n\tupVotes: number;\n\tdownVotes: number;\n}\n\nfunction computeBiasSteps(upVotes: number, downVotes: number, nStrong: number): RouterBiasSteps {\n\tif (nStrong < BIAS_STRONG_THRESHOLD) return 0;\n\tconst majority = upVotes - downVotes;\n\tif (majority === 0) return 0;\n\n\tconst dominance = Math.abs(majority) / nStrong;\n\tconst magnitude = dominance >= 0.75 ? BIAS_MAX_STEPS : 1;\n\tconst signedMagnitude = majority > 0 ? magnitude : -magnitude;\n\treturn Math.max(-BIAS_MAX_STEPS, Math.min(BIAS_MAX_STEPS, signedMagnitude)) as RouterBiasSteps;\n}\n\n/**\n * Deterministically compile a bounded bias snapshot from raw (possibly\n * malformed) ledger entries. Unknown-shaped entries — including ones with\n * extra keys, missing keys, or out-of-range enum values — are dropped and\n * counted, never thrown. Records tagged with a `routerVersion` other than the\n * target version are also dropped and counted (never merged across router\n * versions into one snapshot). An empty or all-dropped input compiles to an\n * empty-bias snapshot (`biasCells: []`), which is exactly the shipped\n * no-learning behavior — this makes \"empty ledger -> zero bias\" true by\n * construction, not by a special case.\n *\n * Pure: same `records` (any order) -> same `RouterBiasSnapshot` (byte-\n * identical `JSON.stringify` output), because cells are grouped by an\n * order-independent key and the emitted cell/record ordering is always\n * sorted before serialization.\n */\nexport function compileBiasSnapshot(\n\trecords: readonly unknown[],\n\toptions: CompileBiasSnapshotOptions = {},\n): RouterBiasSnapshot {\n\tconst routerVersion = options.routerVersion ?? \"v4\";\n\tconst valid: RouterFeedbackRecord[] = [];\n\tlet droppedCount = 0;\n\n\tfor (const entry of records) {\n\t\tif (isRouterFeedbackRecord(entry) && entry.routerVersion === routerVersion) {\n\t\t\tvalid.push(entry);\n\t\t} else {\n\t\t\tdroppedCount += 1;\n\t\t}\n\t}\n\n\tconst cells = new Map<string, CellAccumulator>();\n\tfor (const record of valid) {\n\t\tconst key: RouterBiasCellKey = {\n\t\t\tpredictedClass: record.predictedClass,\n\t\t\tlaneType: record.laneType,\n\t\t\tlenBucket: record.lenBucket,\n\t\t\thadFence: record.hadFence,\n\t\t\thadDiff: record.hadDiff,\n\t\t};\n\t\tconst mapKey = cellKeyString(key);\n\t\tconst existing = cells.get(mapKey) ?? { ...key, nTotal: 0, upVotes: 0, downVotes: 0 };\n\t\texisting.nTotal += 1;\n\t\tconst direction = outcomeDirection(record.outcome);\n\t\tif (direction === 1) existing.upVotes += 1;\n\t\telse if (direction === -1) existing.downVotes += 1;\n\t\tcells.set(mapKey, existing);\n\t}\n\n\tconst biasCells: RouterBiasCell[] = [];\n\tfor (const mapKey of [...cells.keys()].sort()) {\n\t\tconst acc = cells.get(mapKey);\n\t\tif (!acc) continue;\n\t\tconst nStrong = acc.upVotes + acc.downVotes;\n\t\tbiasCells.push({\n\t\t\tpredictedClass: acc.predictedClass,\n\t\t\tlaneType: acc.laneType,\n\t\t\tlenBucket: acc.lenBucket,\n\t\t\thadFence: acc.hadFence,\n\t\t\thadDiff: acc.hadDiff,\n\t\t\tbiasSteps: computeBiasSteps(acc.upVotes, acc.downVotes, nStrong),\n\t\t\tnStrong,\n\t\t\tnTotal: acc.nTotal,\n\t\t});\n\t}\n\n\tconst canonicalValid = valid.map(canonicalRecordJson).sort();\n\tconst sourceRecordDigest = createHash(\"sha256\").update(canonicalValid.join(\"\\n\")).digest(\"hex\");\n\n\treturn {\n\t\tschemaVersion: \"router-bias-snapshot/v1\",\n\t\tsourceRecordDigest,\n\t\tconsideredCount: valid.length,\n\t\tdroppedCount,\n\t\tbiasCells,\n\t};\n}\n\n/** Look up the compiled bias for one feature cell; 0 (no bias) when the cell is absent from the snapshot. */\nexport function getBiasStepsForCell(snapshot: RouterBiasSnapshot, key: RouterBiasCellKey): RouterBiasSteps {\n\tconst wantKey = cellKeyString(key);\n\tfor (const cell of snapshot.biasCells) {\n\t\tif (cellKeyString(cell) === wantKey) return cell.biasSteps;\n\t}\n\treturn 0;\n}\n\n// ============================================================================\n// Snapshot parser / loader (Goal 010 Lane I)\n// ============================================================================\n//\n// Everything below lets a caller safely turn untrusted on-disk JSON text into\n// a validated RouterBiasSnapshot. Same posture as isRouterFeedbackRecord in\n// router-feedback-collector.ts: an exact positive key-set allowlist (not a\n// denylist), bounded per-field checks reusing the ledger's own closed enums,\n// and \"never throw, return null/false instead\" on any malformed input.\n\n/** Bounded bias-step values a compiled cell may carry; mirrors RouterBiasSteps. */\nconst ROUTER_BIAS_STEPS_VALUES: readonly RouterBiasSteps[] = [-2, -1, 0, 1, 2];\n\n/** Exact allowed key set for one compiled `RouterBiasCell`, sorted for canonical set-equality comparison. */\nconst ROUTER_BIAS_CELL_KEYS: readonly string[] = [\n\t\"predictedClass\",\n\t\"laneType\",\n\t\"lenBucket\",\n\t\"hadFence\",\n\t\"hadDiff\",\n\t\"biasSteps\",\n\t\"nStrong\",\n\t\"nTotal\",\n].sort();\n\n/** Exact allowed key set for a `RouterBiasSnapshot`, sorted for canonical set-equality comparison. */\nconst ROUTER_BIAS_SNAPSHOT_KEYS: readonly string[] = [\n\t\"schemaVersion\",\n\t\"sourceRecordDigest\",\n\t\"consideredCount\",\n\t\"droppedCount\",\n\t\"biasCells\",\n].sort();\n\n/** sha256 hex digest shape check for `sourceRecordDigest` (never trusts the value is actually a real digest of anything, only that it has the right shape). */\nconst SHA256_HEX_PATTERN = /^[0-9a-f]{64}$/;\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction hasExactKeySet(value: Record<string, unknown>, allowedSortedKeys: readonly string[]): boolean {\n\tconst keys = Object.keys(value).sort();\n\tif (keys.length !== allowedSortedKeys.length) return false;\n\tfor (let i = 0; i < keys.length; i++) {\n\t\tif (keys[i] !== allowedSortedKeys[i]) return false;\n\t}\n\treturn true;\n}\n\nfunction isBoundedNonNegativeInteger(value: unknown): value is number {\n\treturn typeof value === \"number\" && Number.isInteger(value) && value >= 0;\n}\n\n/**\n * Strict runtime validator for one compiled bias cell. Exact eight-key\n * allowlist plus bounded per-field checks, reusing the same closed enums as\n * `isRouterFeedbackRecord` (`ROUTER_FEEDBACK_TASK_CLASSES`,\n * `ROUTER_FEEDBACK_LANE_TYPES`, `ROUTER_FEEDBACK_LEN_BUCKETS`) so this\n * validator cannot silently drift from the ledger's own schema. `nStrong` is\n * additionally required to never exceed `nTotal` (true by construction for\n * every cell `compileBiasSnapshot` can produce; a cheap sanity bound against\n * a hand-tampered file).\n */\nexport function isRouterBiasCell(value: unknown): value is RouterBiasCell {\n\tif (!isPlainObject(value)) return false;\n\tif (!hasExactKeySet(value, ROUTER_BIAS_CELL_KEYS)) return false;\n\tif (!ROUTER_FEEDBACK_TASK_CLASSES.includes(value.predictedClass as RouterFeedbackTaskClass)) return false;\n\tif (!ROUTER_FEEDBACK_LANE_TYPES.includes(value.laneType as RouterFeedbackLaneType)) return false;\n\tif (!ROUTER_FEEDBACK_LEN_BUCKETS.includes(value.lenBucket as RouterFeedbackLenBucket)) return false;\n\tif (typeof value.hadFence !== \"boolean\") return false;\n\tif (typeof value.hadDiff !== \"boolean\") return false;\n\tif (!ROUTER_BIAS_STEPS_VALUES.includes(value.biasSteps as RouterBiasSteps)) return false;\n\tif (!isBoundedNonNegativeInteger(value.nStrong)) return false;\n\tif (!isBoundedNonNegativeInteger(value.nTotal)) return false;\n\tif ((value.nStrong as number) > (value.nTotal as number)) return false;\n\treturn true;\n}\n\n/**\n * Strict runtime validator for a compiled bias snapshot. Exact five-key\n * allowlist; `biasCells` must be an array whose every element passes\n * `isRouterBiasCell`. Never trusts on-disk content: any unexpected shape,\n * extra key, or out-of-range value returns `false` rather than throwing.\n */\nexport function isRouterBiasSnapshot(value: unknown): value is RouterBiasSnapshot {\n\tif (!isPlainObject(value)) return false;\n\tif (!hasExactKeySet(value, ROUTER_BIAS_SNAPSHOT_KEYS)) return false;\n\tif (value.schemaVersion !== \"router-bias-snapshot/v1\") return false;\n\tif (typeof value.sourceRecordDigest !== \"string\" || !SHA256_HEX_PATTERN.test(value.sourceRecordDigest)) return false;\n\tif (!isBoundedNonNegativeInteger(value.consideredCount)) return false;\n\tif (!isBoundedNonNegativeInteger(value.droppedCount)) return false;\n\tif (!Array.isArray(value.biasCells)) return false;\n\tfor (const cell of value.biasCells) {\n\t\tif (!isRouterBiasCell(cell)) return false;\n\t}\n\treturn true;\n}\n\n/**\n * Safe parse of raw (untrusted, e.g. on-disk) JSON text into a validated\n * `RouterBiasSnapshot`. Never throws: malformed JSON or any schema violation\n * returns `null`. Performs no filesystem access itself — callers own the\n * actual read — so this module's zero-I/O determinism guarantee for\n * `compileBiasSnapshot`/`getBiasStepsForCell` is unaffected.\n */\nexport function parseRouterBiasSnapshot(raw: string): RouterBiasSnapshot | null {\n\tlet parsed: unknown;\n\ttry {\n\t\tparsed = JSON.parse(raw);\n\t} catch {\n\t\treturn null;\n\t}\n\treturn isRouterBiasSnapshot(parsed) ? parsed : null;\n}\n\n/**\n * Default compiled-bias-snapshot path:\n * `<agentDir>/router-feedback/weights/router-bias-snapshot.<version>.json` —\n * matches `compile-bias-snapshot.ts`'s own default `--out` naming exactly, so\n * a snapshot compiled offline for `version` is found here with no extra\n * configuration. Owner-only agent dir, never repo-local (mirrors\n * `getDefaultRouterFeedbackLedgerPath`). Defaults to \"v4\", the router version\n * this lane wires bias *consumption* for.\n */\nexport function getDefaultRouterBiasSnapshotPath(version: RouterFeedbackVersion = \"v4\"): string {\n\treturn join(getAgentDir(), \"router-feedback\", \"weights\", `router-bias-snapshot.${version}.json`);\n}\n"]}
|
|
@@ -1,21 +1,12 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* Reasoning-router bias compiler —
|
|
2
|
+
* Reasoning-router bias compiler — privacy-safe learning ledger.
|
|
3
3
|
*
|
|
4
|
-
* Pure, deterministic compiler from
|
|
5
|
-
*
|
|
6
|
-
*
|
|
7
|
-
*
|
|
8
|
-
*
|
|
9
|
-
*
|
|
10
|
-
* agent-session.ts by this lane.
|
|
11
|
-
*
|
|
12
|
-
* Goal 010 Lane I addition: `isRouterBiasCell` / `isRouterBiasSnapshot` /
|
|
13
|
-
* `parseRouterBiasSnapshot` / `getDefaultRouterBiasSnapshotPath` below let a
|
|
14
|
-
* (now opt-in) caller safely load a snapshot this module previously only
|
|
15
|
-
* wrote. `parseRouterBiasSnapshot` performs no filesystem access itself — it
|
|
16
|
-
* only validates already-read text — so this module's zero-I/O determinism
|
|
17
|
-
* guarantee for `compileBiasSnapshot`/`getBiasStepsForCell` is unchanged; the
|
|
18
|
-
* actual disk read lives in agent-session.ts.
|
|
4
|
+
* Pure, deterministic compiler from v4 feedback records (see
|
|
5
|
+
* router-feedback-collector.ts) to a bounded, per-cell reasoning-level bias
|
|
6
|
+
* snapshot. No clock, randomness, network, or model calls: the same input array
|
|
7
|
+
* always produces the same output (`JSON.stringify` byte-identical), regardless
|
|
8
|
+
* of input record order. `parseRouterBiasSnapshot` performs no filesystem
|
|
9
|
+
* access itself; the actual disk read lives in agent-session.ts.
|
|
19
10
|
*/
|
|
20
11
|
import { createHash } from "crypto";
|
|
21
12
|
import { join } from "path";
|
|
@@ -23,7 +14,7 @@ import { getAgentDir } from "../config.js";
|
|
|
23
14
|
import { isRouterFeedbackRecord, ROUTER_FEEDBACK_LANE_TYPES, ROUTER_FEEDBACK_LEN_BUCKETS, ROUTER_FEEDBACK_TASK_CLASSES, } from "./router-feedback-collector.js";
|
|
24
15
|
/** Minimum non-neutral ("strong") record count per cell before any bias applies. */
|
|
25
16
|
export const BIAS_STRONG_THRESHOLD = 5;
|
|
26
|
-
/** Bias magnitude bound, matching the resolver's
|
|
17
|
+
/** Bias magnitude bound, matching the resolver's bias clamp. */
|
|
27
18
|
export const BIAS_MAX_STEPS = 2;
|
|
28
19
|
function cellKeyString(key) {
|
|
29
20
|
return [key.predictedClass, key.laneType, String(key.lenBucket), String(key.hadFence), String(key.hadDiff)].join("|");
|
|
@@ -79,7 +70,7 @@ function computeBiasSteps(upVotes, downVotes, nStrong) {
|
|
|
79
70
|
* sorted before serialization.
|
|
80
71
|
*/
|
|
81
72
|
export function compileBiasSnapshot(records, options = {}) {
|
|
82
|
-
const routerVersion = options.routerVersion ?? "
|
|
73
|
+
const routerVersion = options.routerVersion ?? "v4";
|
|
83
74
|
const valid = [];
|
|
84
75
|
let droppedCount = 0;
|
|
85
76
|
for (const entry of records) {
|