Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins
TypeScript ai-agentcoding-agentdesktop-appelectronglobali18nlocal-firstmcppipi-agentpi-desktoppluginsreactrusttypescript
fix(agent-runtime): harden context calibration bounds
vastsac751254cc7c6
diff --git a/packages/agent-runtime/src/context-calibration.test.ts b/packages/agent-runtime/src/context-calibration.test.tsindex 34abca8e4..49ea50922 100644--- a/packages/agent-runtime/src/context-calibration.test.ts+++ b/packages/agent-runtime/src/context-calibration.test.ts@@ -113,6 +113,32 @@ describe("ContextEstimateCalibration", () => {calibration.recordUnanchored(1_000_000, 1_000_000);expect(calibration.frozen()).toBe(false);});+ it("does not let anomalous reports enter calibration windows", () => {+ const wild = new ContextEstimateCalibration();+ for (let i = 0; i < CONTEXT_CALIBRATION_MIN_SAMPLES; i++) {+ wild.recordUnanchored(1_000_000, 4_000_000);+ }+ expect(wild.unanchoredRatio(1_000_000)).toBeNull();+ expect(wild.overheadTokens()).toBe(0);+ expect(wild.correct(unanchored(1_000_000))).toBe(1_000_000);++ const mixed = new ContextEstimateCalibration();+ mixed.recordUnanchored(1_000_000, 100_000);+ for (let i = 0; i < CONTEXT_CALIBRATION_MIN_SAMPLES - 1; i++) {+ mixed.recordUnanchored(1_000_000, 700_000);+ }+ expect(mixed.unanchoredRatio(1_000_000)).toBeNull();+ expect(mixed.correct(unanchored(1_000_000))).toBe(1_000_000);++ const anchoredCalibration = new ContextEstimateCalibration();+ for (let i = 0; i < CONTEXT_CALIBRATION_MIN_SAMPLES; i++) {+ anchoredCalibration.recordAnchored(1_000_000, 100_000, 3_500_000);+ }+ expect(anchoredCalibration.trailingRatio()).toBe(1);+ expect(anchoredCalibration.correct(anchored(1_000_000, 100_000))).toBe(+ 1_100_000,+ );+ });});// ② Ratio versus fixed offset: the same residual, used where it belongs.@@ -139,9 +165,9 @@ describe("ContextEstimateCalibration", () => {it("caps the fixed part so it stays an overhead", () => {const calibration = new ContextEstimateCalibration();for (let i = 0; i < CONTEXT_CALIBRATION_MIN_SAMPLES; i++) {- // A 40k session with a 300k report is inside the sanity band but its- // absolute residual is far past a system prompt plus schemas.- calibration.recordUnanchored(40_000, 300_000);+ // A 40k session with a 120k report stays at the 3x sanity boundary,+ // but its absolute residual is far past a system prompt plus schemas.+ calibration.recordUnanchored(40_000, 120_000);}expect(calibration.overheadTokens()).toBe(CONTEXT_CALIBRATION_OVERHEAD_CAP,@@ -165,6 +191,22 @@ describe("ContextEstimateCalibration", () => {expect(second).toBe(1_400_000);expect(second).toBeGreaterThan(first);});+ it("keeps the downward step cap normalized when raw scale drops", () => {+ const calibration = new ContextEstimateCalibration();+ for (let i = 0; i < CONTEXT_CALIBRATION_MIN_SAMPLES; i++) {+ calibration.recordUnanchored(1_000_000, 600_000);+ }+ for (let i = 0; i < CONTEXT_CALIBRATION_MIN_SAMPLES; i++) {+ calibration.recordUnanchored(100_000, 60_000);+ }++ expect(calibration.correct(unanchored(1_000_000))).toBe(850_000);+ const compacted = calibration.correct(unanchored(100_000));+ expect(compacted).toBe(85_000);+ expect(compacted).toBeLessThanOrEqual(+ 100_000 * CONTEXT_CALIBRATION_FACTOR_MAX,+ );+ });});// ③ Real CJK text: the chars/4 tail is the error this series exists for.diff --git a/packages/agent-runtime/src/context-calibration.ts b/packages/agent-runtime/src/context-calibration.tsindex d9404c608..95547b0fb 100644--- a/packages/agent-runtime/src/context-calibration.ts+++ b/packages/agent-runtime/src/context-calibration.ts@@ -201,6 +201,8 @@ export class ContextEstimateCalibration {private downwardStreak = 0;/** The last value `correct()` returned, for the per-step cap. */private lastCorrected: number | null = null;+ /** Raw scale paired with `lastCorrected`, so the step cap stays scale-free. */+ private lastRawTokens: number | null = null;/*** Record one request whose estimate was anchored on a known usage.@@ -222,7 +224,8 @@ export class ContextEstimateCalibration {// which is not this series' error to absorb.if (!usableNumber(trueTrailing) || !usableNumber(estimatedTrailing)) return;const predicted = usageTokens + estimatedTrailing * this.trailingRatio();- this.recordResidual(predicted, realTotal);+ const accepted = this.recordResidual(predicted, realTotal);+ if (!accepted) return;this.recordDownwardEvidence(predicted, realTotal);this.push(this.trailingRatios,@@ -242,7 +245,8 @@ export class ContextEstimateCalibration {if (!usableNumber(estimate) || !usableNumber(realTotal)) return;if (realTotal > estimate * CONTEXT_CALIBRATION_REAL_MAX_RATIO) return;const predicted = this.correctUnanchored(estimate);- this.recordResidual(predicted, realTotal);+ const accepted = this.recordResidual(predicted, realTotal);+ if (!accepted) return;this.recordDownwardEvidence(predicted, realTotal);this.push(this.unanchored, { estimate, realTotal });}@@ -264,6 +268,7 @@ export class ContextEstimateCalibration {: this.correctUnanchored(rawTokens);const value = this.clampCorrection(corrected, rawTokens);this.lastCorrected = value;+ this.lastRawTokens = rawTokens;return value;}@@ -361,10 +366,10 @@ export class ContextEstimateCalibration {);}- private recordResidual(predicted: number, realTotal: number): void {- if (!usableNumber(predicted) || !usableNumber(realTotal)) return;+ private recordResidual(predicted: number, realTotal: number): boolean {+ if (!usableNumber(predicted) || !usableNumber(realTotal)) return false;const ratio = realTotal / predicted;- if (!Number.isFinite(ratio)) return;+ if (!Number.isFinite(ratio)) return false;// A report this far from the prediction is a misreport. Counting it keeps// the downward direction frozen until a usable report arrives; discarding// it keeps the series honest. Anomalies never move the value up either:@@ -374,16 +379,17 @@ export class ContextEstimateCalibration {ratio > CONTEXT_CALIBRATION_SAMPLE_MAX_RATIO) {this.anomalies += 1;- return;+ return false;}this.anomalies = 0;if (ratio < CONTEXT_CALIBRATION_RESIDUAL_MIN ||ratio > CONTEXT_CALIBRATION_RESIDUAL_MAX) {- return;+ return false;}this.push(this.residuals, ratio);+ return true;}/** Does this sample say the estimate reads high enough to justify a step down? */@@ -412,12 +418,24 @@ export class ContextEstimateCalibration {rawTokens * CONTEXT_CALIBRATION_FACTOR_MAX,);if (value >= rawTokens) return Math.round(value);- // A downward move needs corroboration and may not jump.+ // A downward move needs corroboration and may not jump. Keep the cap in+ // normalized factor space: context compaction can make the next raw+ // estimate much smaller than the previous request.if (!this.downwardAllowed()) return rawTokens;+ const previousFactor =+ this.lastCorrected !== null &&+ this.lastRawTokens !== null &&+ this.lastRawTokens > 0+ ? this.lastCorrected / this.lastRawTokens+ : null;const stepFloor =- this.lastCorrected === null+ previousFactor === null? value- : this.lastCorrected * (1 - CONTEXT_CALIBRATION_DOWNWARD_STEP_MAX);+ : rawTokens *+ Math.min(+ CONTEXT_CALIBRATION_FACTOR_MAX,+ previousFactor * (1 - CONTEXT_CALIBRATION_DOWNWARD_STEP_MAX),+ );return Math.round(Math.max(value, stepFloor));}