23f7624596
ADR-166 MCP Bridge Security Lock / Static-source security lock (push) Failing after 0s
ADR-166 MCP Bridge Security Lock / Compose default binds loopback + Mongo has auth (push) Failing after 2s
CodeQL Advanced / Analyze (rust) (push) Failing after 0s
ADR-166 MCP Bridge Security Lock / plugin-agent-federation bindHost default (push) Failing after 1s
ADR-166 MCP Bridge Security Lock / Runtime behavior — 401 + terminal gate + fail-closed (push) Failing after 4s
business-pods-smoke / smoke (push) Failing after 1s
all-plugins-smoke / smoke-all (push) Failing after 2s
CI/CD Pipeline / Security & Code Quality (push) Failing after 1s
CI/CD Pipeline / Test Suite (ubuntu-latest) (push) Failing after 1s
CI/CD Pipeline / Build & Package (macos-latest) (push) Has been skipped
CI/CD Pipeline / Build & Package (ubuntu-latest) (push) Has been skipped
CI/CD Pipeline / Build & Package (windows-latest) (push) Has been skipped
CI/CD Pipeline / Documentation & Examples (push) Failing after 1s
Clone Tracker (14-day rolling) / Snapshot clones for ruflo ecosystem (push) Failing after 1s
CodeQL Advanced / Analyze (actions) (push) Failing after 1s
CodeQL Advanced / Analyze (javascript-typescript) (push) Failing after 1s
federation-peer-rust / stable-noop (push) Failing after 1s
metaharness-ci / score (push) Failing after 1s
metaharness-ci / router-compat (push) Failing after 0s
metaharness-ci / similarity-tests (push) Failing after 0s
no-agentbbs-smoke / smoke-without-agentbbs (push) Failing after 1s
V3 CI/CD Pipeline / Build V3 (windows-latest) (push) Has been skipped
codex-integration-audit / Codex integration audit (push) Failing after 1s
helpers-manifest-guard / guard (push) Failing after 1s
🔗 Cross-Agent Integration Tests / 🤝 Agent Coordination Tests (push) Has been skipped
🔗 Cross-Agent Integration Tests / 🧠 Memory Sharing Integration (push) Has been skipped
🔗 Cross-Agent Integration Tests / 🛡️ Fault Tolerance Tests (push) Has been skipped
🔗 Cross-Agent Integration Tests / ⚡ Performance Integration Tests (push) Has been skipped
metaharness-ci / mcp-scan (push) Failing after 1s
metaharness-ci / eject-dryrun (push) Failing after 1s
metaharness-ci / metaharness-real-data (push) Failing after 0s
no-cli-optdep-bloat-2561 / guard (push) Failing after 1s
no-metaharness-smoke / smoke-without-metaharness (push) Failing after 1s
no-phantom-agentic-flow-subpath / guard (push) Failing after 1s
🔄 Automated Rollback Manager / 🚨 Failure Detection (push) Failing after 1s
V3 CI/CD Pipeline / Plugin hooks smoke / ubuntu-latest / Node 22 (push) Failing after 1s
V3 CI/CD Pipeline / ruflo-graph-intelligence build + test smoke (#2044, ADR-123) (push) Failing after 1s
CVE Audit Gate / Audit root (critical-blocking) (push) Failing after 2s
cost-tracker-smoke / smoke (push) Failing after 3s
oia-audit-weekly / audit (push) Failing after 2s
ruflo-agent-smoke / ruflo-agent structural smoke (push) Failing after 1s
📊 Status Badges Update / 📊 Update Status Badges (push) Failing after 1s
V3 CI/CD Pipeline / Static regression guards (#2267 YAML + (push) Failing after 1s
V3 CI/CD Pipeline / Test V3 Packages (push) Failing after 0s
V3 CI/CD Pipeline / agent_execute provider routing smoke (#2042) (push) Failing after 0s
CVE Audit Gate / Audit v3 (critical-blocking) (push) Failing after 1s
federation-peer-rust / stable-native (push) Failing after 2s
🔗 Cross-Agent Integration Tests / 🚀 Integration Test Setup (push) Failing after 2s
neural-trader-smoke / runtime-smoke (push) Failing after 1s
V3 CI/CD Pipeline / Build V3 (macos-latest) (push) Has been skipped
V3 CI/CD Pipeline / Build V3 (ubuntu-latest) (push) Has been skipped
V3 CI/CD Pipeline / Type Check V3 (push) Failing after 1s
V3 CI/CD Pipeline / Smoke (no better-sqlite3) / ubuntu-latest / Node 24 (push) Failing after 1s
V3 CI/CD Pipeline / Smoke (no better-sqlite3) / ubuntu-latest / Node 22 (push) Failing after 2s
V3 CI/CD Pipeline / browser rvf create flag smoke (#2015) (push) Failing after 0s
V3 CI/CD Pipeline / Dependency review (#2046) (push) Has been skipped
V3 CI/CD Pipeline / Supply-chain audit (#2046) (push) Failing after 0s
V3 CI/CD Pipeline / witness marker drift smoke (#2021) (push) Failing after 1s
V3 CI/CD Pipeline / neural-trader portfolio CG smoke (#2068, ADR-126 Phase 3) (push) Failing after 1s
V3 CI/CD Pipeline / neural-trader backtest signing smoke (#2068, ADR-126 Phase 4) (push) Failing after 1s
V3 CI/CD Pipeline / kg-extract type-import classification smoke (#2049) (push) Failing after 0s
V3 CI/CD Pipeline / witness verify precondition smoke (#1880) (push) Failing after 2s
V3 CI/CD Pipeline / neural-trader pipeline risk-gate smoke (#2068, ADR-126 Phase 5) (push) Failing after 0s
V3 CI/CD Pipeline / neural-trader feature attribution smoke (#2068, ADR-126 Phase 6) (push) Failing after 0s
V3 CI/CD Pipeline / plugin-registry signature verification smoke (#1922, CWE-347) (push) Failing after 4s
V3 CI/CD Pipeline / memory stats legacy-DB smoke (#2120) (push) Failing after 4s
V3 CI/CD Pipeline / github deprecated actions smoke (#2089, ADR-127 Phase 3) (push) Failing after 1s
V3 CI/CD Pipeline / graph query + pathfinder smoke (ADR-130 P2+P5) (push) Has been skipped
V3 CI/CD Pipeline / graph trajectory hooks smoke (ADR-130 P3) (push) Has been skipped
V3 CI/CD Pipeline / graph plugin adapter smoke (ADR-130 P4) (push) Has been skipped
V3 CI/CD Pipeline / graph benchmark (ADR-130 P6) (push) Has been skipped
V3 CI/CD Pipeline / statusline generator delegation smoke (#2195) (push) Failing after 1s
V3 CI/CD Pipeline / wizard init regression guard (#2206 (push) Failing after 1s
V3 CI/CD Pipeline / memory no-stray-db smoke (ADR-125 P7) (push) Failing after 1s
V3 CI/CD Pipeline / github-safe injection smoke (#2089, ADR-127 Phase 1) (push) Failing after 1s
V3 CI/CD Pipeline / github actions pin smoke (#2089, ADR-127 Phase 1) (push) Failing after 1s
V3 CI/CD Pipeline / github attribution opt-in smoke (#2089, ADR-127 Phase 4) (push) Failing after 1s
V3 CI/CD Pipeline / pre-bash hook safety smoke (#2017) (push) Failing after 1s
V3 CI/CD Pipeline / Memory import smoke / ubuntu-latest (push) Failing after 0s
V3 CI/CD Pipeline / MCP protocol smoke / ubuntu-latest (push) Failing after 2s
V3 CI/CD Pipeline / ruvllm WASM auto-init smoke (#2086) (push) Failing after 4s
V3 CI/CD Pipeline / MCP paired-tool round-trip smoke (#1889) (push) Failing after 1s
V3 CI/CD Pipeline / Plugin package install-safety (#1902/#1903/#1904) (push) Failing after 1s
V3 CI/CD Pipeline / Tool description discoverability (ADR-112) (push) Failing after 3s
V3 CI/CD Pipeline / CLI npx-install smoke (#1147 / (22) (push) Failing after 1s
V3 CI/CD Pipeline / CLI npx-install smoke (#1147 / (24) (push) Failing after 1s
V3 CI/CD Pipeline / Windows hook shim smoke (#2132) / ubuntu-latest (push) Failing after 2s
V3 CI/CD Pipeline / Windows hook execution smoke (#2132) / ubuntu-latest (push) Failing after 1s
V3 CI/CD Pipeline / Windows init hooks smoke (#2132) / ubuntu-latest (push) Failing after 1s
V3 CI/CD Pipeline / Vector-index dimension audit (#1947) (push) Failing after 0s
V3 CI/CD Pipeline / Hook-command install safety (#1921) (push) Failing after 1s
V3 CI/CD Pipeline / ToolOutputGuardrail smoke (ADR-131, (push) Failing after 1s
V3 CI/CD Pipeline / init-bundle invariants smoke (#2095, ADR-128 Phase 5) (push) Failing after 1s
V3 CI/CD Pipeline / wasm provider bridge smoke (ADR-129 P1) (push) Failing after 2s
V3 CI/CD Pipeline / wasm gallery CRUD smoke (ADR-129 P3) (push) Failing after 1s
V3 CI/CD Pipeline / wasm plugin bridge smoke (ADR-129 P4) (push) Failing after 0s
V3 CI/CD Pipeline / wasm compose smoke (ADR-129 P2) (push) Failing after 4s
V3 CI/CD Pipeline / graph schema smoke (ADR-130 P1) (push) Failing after 0s
Validate Marketplace / validate (push) Failing after 1s
🔍 Verification Pipeline / 🚀 Setup Verification (push) Failing after 1s
🔍 Verification Pipeline / 🛡️ Security Verification (push) Has been skipped
🔍 Verification Pipeline / 📝 Code Quality (push) Has been skipped
🔍 Verification Pipeline / 🧪 Test Verification (${{ matrix.os }}, Node ${{ matrix.node }}) (push) Has been skipped
🔍 Verification Pipeline / 🏗️ Build Verification (push) Has been skipped
🔍 Verification Pipeline / 📚 Documentation Verification (push) Has been skipped
CVE Audit Gate / High-severity report (warn only) (push) Has been cancelled
🔄 Automated Rollback Manager / 🔄 Execute Rollback (push) Has been cancelled
🔄 Automated Rollback Manager / ✅ Post-Rollback Verification (push) Has been cancelled
🔄 Automated Rollback Manager / 📊 Rollback Monitoring (push) Has been cancelled
V3 CI/CD Pipeline / Windows init hooks smoke (#2132) / windows-latest (push) Has been cancelled
V3 CI/CD Pipeline / Windows hook execution smoke (#2132) / macos-latest (push) Has been cancelled
V3 CI/CD Pipeline / Windows hook execution smoke (#2132) / windows-latest (push) Has been cancelled
🔄 Automated Rollback Manager / ⏳ Manual Rollback Approval (push) Has been cancelled
V3 CI/CD Pipeline / MCP protocol smoke / macos-latest (push) Has been cancelled
V3 CI/CD Pipeline / Memory import smoke / macos-latest (push) Has been cancelled
V3 CI/CD Pipeline / Windows hook shim smoke (#2132) / macos-latest (push) Has been cancelled
V3 CI/CD Pipeline / Windows hook shim smoke (#2132) / windows-latest (push) Has been cancelled
V3 CI/CD Pipeline / Windows init hooks smoke (#2132) / macos-latest (push) Has been cancelled
V3 CI/CD Pipeline / Witness verify (signed manifest) / macos-latest (push) Has been cancelled
V3 CI/CD Pipeline / Witness verify (signed manifest) / ubuntu-latest (push) Has been cancelled
V3 CI/CD Pipeline / Witness verify (signed manifest) / windows-latest (push) Has been cancelled
V3 CI/CD Pipeline / Publish to npm (alpha) (push) Has been cancelled
V3 CI/CD Pipeline / Smoke (no better-sqlite3) / macos-latest / Node 22 (push) Has been cancelled
V3 CI/CD Pipeline / Plugin hooks smoke / macos-latest / Node 22 (push) Has been cancelled
CI/CD Pipeline / Deploy & Release (push) Has been cancelled
CI/CD Pipeline / CI Status (push) Has been cancelled
🔗 Cross-Agent Integration Tests / 📊 Integration Test Report (push) Has been cancelled
🔄 Automated Rollback Manager / 🔍 Pre-Rollback Validation (push) Has been cancelled
🔍 Verification Pipeline / ⚡ Performance Verification (push) Has been cancelled
🔍 Verification Pipeline / 📊 Verification Report (push) Has been cancelled
528 lines
18 KiB
TypeScript
528 lines
18 KiB
TypeScript
import { describe, it, expect, beforeEach, vi } from 'vitest';
|
|
import {
|
|
type ContinueGateConfig,
|
|
type StepContext,
|
|
type ContinueDecision,
|
|
ContinueGate,
|
|
createContinueGate,
|
|
} from '../src/continue-gate.ts';
|
|
|
|
// ============================================================================
|
|
// Helpers
|
|
// ============================================================================
|
|
|
|
function makeContext(overrides: Partial<StepContext> = {}): StepContext {
|
|
return {
|
|
stepNumber: 10,
|
|
totalTokensUsed: 5000,
|
|
totalToolCalls: 20,
|
|
reworkCount: 1,
|
|
coherenceScore: 0.8,
|
|
uncertaintyScore: 0.3,
|
|
elapsedMs: 30000,
|
|
lastCheckpointStep: 0,
|
|
budgetRemaining: {
|
|
tokens: 100000,
|
|
toolCalls: 500,
|
|
timeMs: 600000,
|
|
},
|
|
recentDecisions: [],
|
|
...overrides,
|
|
};
|
|
}
|
|
|
|
// ============================================================================
|
|
// Factory Function
|
|
// ============================================================================
|
|
|
|
describe('createContinueGate()', () => {
|
|
it('should create a ContinueGate with default config', () => {
|
|
const gate = createContinueGate();
|
|
expect(gate).toBeInstanceOf(ContinueGate);
|
|
const config = gate.getConfig();
|
|
expect(config.maxConsecutiveSteps).toBe(100);
|
|
expect(config.maxBudgetSlopePerStep).toBe(0.02);
|
|
expect(config.minCoherenceForContinue).toBe(0.4);
|
|
expect(config.maxUncertaintyForContinue).toBe(0.8);
|
|
expect(config.maxReworkRatio).toBe(0.3);
|
|
expect(config.checkpointIntervalSteps).toBe(25);
|
|
expect(config.cooldownMs).toBe(5000);
|
|
});
|
|
|
|
it('should create a ContinueGate with custom config', () => {
|
|
const gate = createContinueGate({
|
|
maxConsecutiveSteps: 50,
|
|
minCoherenceForContinue: 0.6,
|
|
});
|
|
const config = gate.getConfig();
|
|
expect(config.maxConsecutiveSteps).toBe(50);
|
|
expect(config.minCoherenceForContinue).toBe(0.6);
|
|
// defaults preserved
|
|
expect(config.maxBudgetSlopePerStep).toBe(0.02);
|
|
});
|
|
});
|
|
|
|
// ============================================================================
|
|
// ContinueGate.evaluate() - Decision Logic
|
|
// ============================================================================
|
|
|
|
describe('ContinueGate.evaluate()', () => {
|
|
let gate: ContinueGate;
|
|
|
|
beforeEach(() => {
|
|
gate = new ContinueGate();
|
|
});
|
|
|
|
// --- continue ---
|
|
|
|
it('should return continue when all checks pass', () => {
|
|
const decision = gate.evaluate(makeContext());
|
|
expect(decision.decision).toBe('continue');
|
|
expect(decision.reasons).toContain('All checks passed');
|
|
});
|
|
|
|
// --- stop: coherence ---
|
|
|
|
it('should return stop when coherence is below threshold', () => {
|
|
const decision = gate.evaluate(makeContext({ coherenceScore: 0.2 }));
|
|
expect(decision.decision).toBe('stop');
|
|
expect(decision.reasons[0]).toContain('Coherence below threshold');
|
|
expect(decision.metrics.coherenceLevel).toBe('critical');
|
|
});
|
|
|
|
it('should return stop when coherence is exactly at threshold', () => {
|
|
// 0.4 is minCoherenceForContinue; < 0.4 → stop
|
|
const decision = gate.evaluate(makeContext({ coherenceScore: 0.39 }));
|
|
expect(decision.decision).toBe('stop');
|
|
});
|
|
|
|
it('should continue when coherence equals the threshold', () => {
|
|
const decision = gate.evaluate(makeContext({ coherenceScore: 0.4 }));
|
|
expect(decision.decision).not.toBe('stop');
|
|
});
|
|
|
|
// --- stop: step limit ---
|
|
|
|
it('should return stop when step limit exceeded without recent checkpoint', () => {
|
|
const decision = gate.evaluate(makeContext({
|
|
stepNumber: 100,
|
|
lastCheckpointStep: 50, // 100 - 50 = 50 >= 25
|
|
}));
|
|
expect(decision.decision).toBe('stop');
|
|
expect(decision.reasons[0]).toContain('Step limit exceeded');
|
|
});
|
|
|
|
it('should not stop at step limit if recent checkpoint exists', () => {
|
|
const decision = gate.evaluate(makeContext({
|
|
stepNumber: 100,
|
|
lastCheckpointStep: 90, // 100 - 90 = 10 < 25
|
|
}));
|
|
expect(decision.decision).not.toBe('stop');
|
|
});
|
|
|
|
// --- stop: budget exhausted ---
|
|
|
|
it('should return stop when token budget is exhausted', () => {
|
|
const decision = gate.evaluate(makeContext({
|
|
budgetRemaining: { tokens: 0, toolCalls: 500, timeMs: 600000 },
|
|
}));
|
|
expect(decision.decision).toBe('stop');
|
|
expect(decision.reasons[0]).toContain('Budget exhausted');
|
|
expect(decision.reasons[0]).toContain('tokens');
|
|
});
|
|
|
|
it('should return stop when tool call budget is exhausted', () => {
|
|
const decision = gate.evaluate(makeContext({
|
|
budgetRemaining: { tokens: 100000, toolCalls: 0, timeMs: 600000 },
|
|
}));
|
|
expect(decision.decision).toBe('stop');
|
|
expect(decision.reasons[0]).toContain('tool calls');
|
|
});
|
|
|
|
it('should return stop when time budget is exhausted', () => {
|
|
const decision = gate.evaluate(makeContext({
|
|
budgetRemaining: { tokens: 100000, toolCalls: 500, timeMs: 0 },
|
|
}));
|
|
expect(decision.decision).toBe('stop');
|
|
expect(decision.reasons[0]).toContain('time');
|
|
});
|
|
|
|
it('should list all exhausted budgets', () => {
|
|
const decision = gate.evaluate(makeContext({
|
|
budgetRemaining: { tokens: 0, toolCalls: 0, timeMs: 0 },
|
|
}));
|
|
expect(decision.decision).toBe('stop');
|
|
expect(decision.reasons[0]).toContain('tokens');
|
|
expect(decision.reasons[0]).toContain('tool calls');
|
|
expect(decision.reasons[0]).toContain('time');
|
|
});
|
|
|
|
// --- pause: rework ratio ---
|
|
|
|
it('should return pause when rework ratio exceeds threshold', () => {
|
|
const decision = gate.evaluate(makeContext({
|
|
stepNumber: 10,
|
|
reworkCount: 4, // 4/10 = 0.4 > 0.3
|
|
}));
|
|
expect(decision.decision).toBe('pause');
|
|
expect(decision.reasons[0]).toContain('Rework ratio too high');
|
|
expect(decision.metrics.reworkRatio).toBeCloseTo(0.4);
|
|
});
|
|
|
|
it('should not pause when rework ratio is at threshold', () => {
|
|
const decision = gate.evaluate(makeContext({
|
|
stepNumber: 10,
|
|
reworkCount: 3, // 3/10 = 0.3, not > 0.3
|
|
}));
|
|
expect(decision.decision).not.toBe('pause');
|
|
});
|
|
|
|
// --- pause: uncertainty ---
|
|
|
|
it('should return pause when uncertainty exceeds threshold', () => {
|
|
const decision = gate.evaluate(makeContext({ uncertaintyScore: 0.9 }));
|
|
expect(decision.decision).toBe('pause');
|
|
expect(decision.reasons[0]).toContain('Uncertainty too high');
|
|
expect(decision.metrics.uncertaintyLevel).toBe('extreme');
|
|
});
|
|
|
|
it('should not pause when uncertainty is at threshold', () => {
|
|
const decision = gate.evaluate(makeContext({ uncertaintyScore: 0.8 }));
|
|
expect(decision.decision).not.toBe('pause');
|
|
});
|
|
|
|
// --- throttle: budget acceleration ---
|
|
|
|
it('should return throttle when budget slope is accelerating', () => {
|
|
const gate = new ContinueGate({ maxBudgetSlopePerStep: 0.02 });
|
|
|
|
// Feed increasing token usage to build up slope
|
|
for (let step = 1; step <= 10; step++) {
|
|
gate.evaluate(makeContext({
|
|
stepNumber: step,
|
|
totalTokensUsed: step * step * 1000, // quadratic growth
|
|
}));
|
|
}
|
|
|
|
// The 11th step should detect the high slope
|
|
const decision = gate.evaluate(makeContext({
|
|
stepNumber: 11,
|
|
totalTokensUsed: 11 * 11 * 1000,
|
|
}));
|
|
|
|
// With quadratic growth, the slope should be positive and large
|
|
expect(decision.metrics.budgetSlope).toBeGreaterThan(0);
|
|
});
|
|
|
|
// --- checkpoint ---
|
|
|
|
it('should return checkpoint when interval reached', () => {
|
|
const decision = gate.evaluate(makeContext({
|
|
stepNumber: 25,
|
|
lastCheckpointStep: 0, // 25 - 0 = 25 >= 25
|
|
}));
|
|
expect(decision.decision).toBe('checkpoint');
|
|
expect(decision.reasons[0]).toContain('Checkpoint interval reached');
|
|
});
|
|
|
|
it('should not checkpoint before interval', () => {
|
|
const decision = gate.evaluate(makeContext({
|
|
stepNumber: 24,
|
|
lastCheckpointStep: 0, // 24 - 0 = 24 < 25
|
|
}));
|
|
expect(decision.decision).toBe('continue');
|
|
});
|
|
|
|
// --- priority order ---
|
|
|
|
it('should prioritize stop over pause', () => {
|
|
// Both coherence below threshold (stop) and high rework (pause)
|
|
const decision = gate.evaluate(makeContext({
|
|
coherenceScore: 0.2,
|
|
reworkCount: 5,
|
|
stepNumber: 10,
|
|
}));
|
|
expect(decision.decision).toBe('stop');
|
|
});
|
|
|
|
it('should prioritize pause over throttle', () => {
|
|
// High rework (pause) with some budget acceleration
|
|
const gate = new ContinueGate();
|
|
// Build slope data
|
|
for (let step = 1; step <= 10; step++) {
|
|
gate.evaluate(makeContext({
|
|
stepNumber: step,
|
|
totalTokensUsed: step * step * 1000,
|
|
reworkCount: 0,
|
|
}));
|
|
}
|
|
const decision = gate.evaluate(makeContext({
|
|
stepNumber: 11,
|
|
totalTokensUsed: 11 * 11 * 1000,
|
|
reworkCount: 5, // 5/11 > 0.3
|
|
}));
|
|
expect(decision.decision).toBe('pause');
|
|
});
|
|
|
|
// --- metrics ---
|
|
|
|
it('should compute coherence level correctly', () => {
|
|
expect(gate.evaluate(makeContext({ coherenceScore: 0.8 })).metrics.coherenceLevel).toBe('healthy');
|
|
expect(gate.evaluate(makeContext({ coherenceScore: 0.5 })).metrics.coherenceLevel).toBe('degraded');
|
|
});
|
|
|
|
it('should compute uncertainty level correctly', () => {
|
|
expect(gate.evaluate(makeContext({ uncertaintyScore: 0.2 })).metrics.uncertaintyLevel).toBe('low');
|
|
expect(gate.evaluate(makeContext({ uncertaintyScore: 0.5 })).metrics.uncertaintyLevel).toBe('moderate');
|
|
expect(gate.evaluate(makeContext({ uncertaintyScore: 0.7 })).metrics.uncertaintyLevel).toBe('high');
|
|
});
|
|
|
|
it('should compute rework ratio correctly', () => {
|
|
const decision = gate.evaluate(makeContext({
|
|
stepNumber: 20,
|
|
reworkCount: 4,
|
|
}));
|
|
expect(decision.metrics.reworkRatio).toBeCloseTo(0.2);
|
|
});
|
|
|
|
it('should handle zero step number (division by zero)', () => {
|
|
const decision = gate.evaluate(makeContext({ stepNumber: 0, reworkCount: 0 }));
|
|
expect(decision.metrics.reworkRatio).toBe(0);
|
|
});
|
|
|
|
it('should include recommended action for non-continue decisions', () => {
|
|
const decision = gate.evaluate(makeContext({ coherenceScore: 0.1 }));
|
|
expect(decision.recommendedAction).toBeDefined();
|
|
expect(decision.recommendedAction).toContain('coherence');
|
|
});
|
|
});
|
|
|
|
// ============================================================================
|
|
// ContinueGate.evaluateWithHistory() - History and Cooldown
|
|
// ============================================================================
|
|
|
|
describe('ContinueGate.evaluateWithHistory()', () => {
|
|
it('should record evaluations in history', () => {
|
|
const gate = new ContinueGate({ cooldownMs: 0 });
|
|
gate.evaluateWithHistory(makeContext({ stepNumber: 1 }));
|
|
gate.evaluateWithHistory(makeContext({ stepNumber: 2 }));
|
|
|
|
const history = gate.getHistory();
|
|
expect(history).toHaveLength(2);
|
|
expect(history[0].step).toBe(1);
|
|
expect(history[1].step).toBe(2);
|
|
expect(history[0].timestamp).toBeLessThanOrEqual(history[1].timestamp);
|
|
});
|
|
|
|
it('should return continue with minimal metrics during cooldown', () => {
|
|
const gate = new ContinueGate({ cooldownMs: 60000 });
|
|
|
|
// First call proceeds normally
|
|
const first = gate.evaluateWithHistory(makeContext());
|
|
expect(first.decision).toBe('continue');
|
|
|
|
// Second call within cooldown
|
|
const second = gate.evaluateWithHistory(makeContext());
|
|
expect(second.decision).toBe('continue');
|
|
expect(second.reasons[0]).toContain('Cooldown');
|
|
});
|
|
|
|
it('should still stop during cooldown if coherence collapses', () => {
|
|
const gate = new ContinueGate({ cooldownMs: 60000 });
|
|
|
|
// First call to set cooldown timer
|
|
gate.evaluateWithHistory(makeContext());
|
|
|
|
// Second call during cooldown with coherence collapse
|
|
const decision = gate.evaluateWithHistory(makeContext({
|
|
coherenceScore: 0.1,
|
|
}));
|
|
expect(decision.decision).toBe('stop');
|
|
expect(decision.reasons[0]).toContain('Coherence below threshold');
|
|
});
|
|
|
|
it('should still stop during cooldown if budget exhausted', () => {
|
|
const gate = new ContinueGate({ cooldownMs: 60000 });
|
|
|
|
// First call to set cooldown timer
|
|
gate.evaluateWithHistory(makeContext());
|
|
|
|
// Second call during cooldown with budget exhausted
|
|
const decision = gate.evaluateWithHistory(makeContext({
|
|
budgetRemaining: { tokens: 0, toolCalls: 500, timeMs: 600000 },
|
|
}));
|
|
expect(decision.decision).toBe('stop');
|
|
expect(decision.reasons[0]).toContain('Budget exhausted');
|
|
});
|
|
|
|
it('should evict oldest entries when history exceeds max size', () => {
|
|
const gate = new ContinueGate({ cooldownMs: 0 });
|
|
|
|
// Fill beyond max (10000)
|
|
for (let i = 0; i < 10002; i++) {
|
|
gate.evaluateWithHistory(makeContext({ stepNumber: i }));
|
|
}
|
|
|
|
const history = gate.getHistory();
|
|
expect(history.length).toBeLessThanOrEqual(10000);
|
|
// Oldest entries should be evicted
|
|
expect(history[0].step).toBeGreaterThan(0);
|
|
});
|
|
});
|
|
|
|
// ============================================================================
|
|
// ContinueGate.getStats()
|
|
// ============================================================================
|
|
|
|
describe('ContinueGate.getStats()', () => {
|
|
it('should return zero stats when no evaluations', () => {
|
|
const gate = new ContinueGate();
|
|
const stats = gate.getStats();
|
|
expect(stats.totalEvaluations).toBe(0);
|
|
expect(stats.decisions.continue).toBe(0);
|
|
expect(stats.averageBudgetSlope).toBe(0);
|
|
});
|
|
|
|
it('should count decisions by type', () => {
|
|
const gate = new ContinueGate({ cooldownMs: 0 });
|
|
|
|
// 2 continues (reworkCount: 0 to avoid pause)
|
|
gate.evaluateWithHistory(makeContext({ stepNumber: 1, reworkCount: 0 }));
|
|
gate.evaluateWithHistory(makeContext({ stepNumber: 2, reworkCount: 0 }));
|
|
|
|
// 1 stop (coherence collapse)
|
|
gate.evaluateWithHistory(makeContext({ stepNumber: 3, reworkCount: 0, coherenceScore: 0.1 }));
|
|
|
|
// 1 checkpoint
|
|
gate.evaluateWithHistory(makeContext({
|
|
stepNumber: 25,
|
|
reworkCount: 0,
|
|
lastCheckpointStep: 0,
|
|
}));
|
|
|
|
const stats = gate.getStats();
|
|
expect(stats.totalEvaluations).toBe(4);
|
|
expect(stats.decisions.continue).toBe(2);
|
|
expect(stats.decisions.stop).toBe(1);
|
|
expect(stats.decisions.checkpoint).toBe(1);
|
|
});
|
|
});
|
|
|
|
// ============================================================================
|
|
// ContinueGate.reset()
|
|
// ============================================================================
|
|
|
|
describe('ContinueGate.reset()', () => {
|
|
it('should clear all internal state', () => {
|
|
const gate = new ContinueGate({ cooldownMs: 0 });
|
|
gate.evaluateWithHistory(makeContext({ stepNumber: 1 }));
|
|
gate.evaluateWithHistory(makeContext({ stepNumber: 2 }));
|
|
expect(gate.getHistory()).toHaveLength(2);
|
|
|
|
gate.reset();
|
|
|
|
expect(gate.getHistory()).toHaveLength(0);
|
|
expect(gate.getStats().totalEvaluations).toBe(0);
|
|
});
|
|
});
|
|
|
|
// ============================================================================
|
|
// Budget Slope Detection (Linear Regression)
|
|
// ============================================================================
|
|
|
|
describe('Budget slope detection', () => {
|
|
it('should detect zero slope with constant token usage', () => {
|
|
const gate = new ContinueGate({ cooldownMs: 0 });
|
|
|
|
// Constant token usage: 1000 per step
|
|
for (let step = 1; step <= 10; step++) {
|
|
gate.evaluate(makeContext({
|
|
stepNumber: step,
|
|
totalTokensUsed: 1000, // same every step
|
|
}));
|
|
}
|
|
|
|
const decision = gate.evaluate(makeContext({
|
|
stepNumber: 11,
|
|
totalTokensUsed: 1000,
|
|
}));
|
|
expect(decision.metrics.budgetSlope).toBeCloseTo(0, 1);
|
|
});
|
|
|
|
it('should detect positive slope with increasing token usage', () => {
|
|
const gate = new ContinueGate({ cooldownMs: 0 });
|
|
|
|
for (let step = 1; step <= 10; step++) {
|
|
gate.evaluate(makeContext({
|
|
stepNumber: step,
|
|
totalTokensUsed: step * 500, // linear growth
|
|
}));
|
|
}
|
|
|
|
const decision = gate.evaluate(makeContext({
|
|
stepNumber: 11,
|
|
totalTokensUsed: 5500,
|
|
}));
|
|
expect(decision.metrics.budgetSlope).toBeGreaterThan(0);
|
|
});
|
|
|
|
it('should return zero slope with fewer than 2 data points', () => {
|
|
const gate = new ContinueGate({ cooldownMs: 0 });
|
|
const decision = gate.evaluate(makeContext({ stepNumber: 1, totalTokensUsed: 1000 }));
|
|
expect(decision.metrics.budgetSlope).toBe(0);
|
|
});
|
|
});
|
|
|
|
// ============================================================================
|
|
// ContinueGate.getConfig()
|
|
// ============================================================================
|
|
|
|
describe('ContinueGate.getConfig()', () => {
|
|
it('should return a copy of the config', () => {
|
|
const gate = new ContinueGate({ maxConsecutiveSteps: 50 });
|
|
const config = gate.getConfig();
|
|
expect(config.maxConsecutiveSteps).toBe(50);
|
|
|
|
// Should be a copy, not the internal object
|
|
config.maxConsecutiveSteps = 999;
|
|
expect(gate.getConfig().maxConsecutiveSteps).toBe(50);
|
|
});
|
|
});
|
|
|
|
// ============================================================================
|
|
// Edge Cases
|
|
// ============================================================================
|
|
|
|
describe('Edge cases', () => {
|
|
it('should handle negative budget remaining', () => {
|
|
const gate = new ContinueGate();
|
|
const decision = gate.evaluate(makeContext({
|
|
budgetRemaining: { tokens: -100, toolCalls: 500, timeMs: 600000 },
|
|
}));
|
|
expect(decision.decision).toBe('stop');
|
|
});
|
|
|
|
it('should handle coherence score of exactly 0', () => {
|
|
const gate = new ContinueGate();
|
|
const decision = gate.evaluate(makeContext({ coherenceScore: 0 }));
|
|
expect(decision.decision).toBe('stop');
|
|
});
|
|
|
|
it('should handle uncertainty score of exactly 1', () => {
|
|
const gate = new ContinueGate();
|
|
const decision = gate.evaluate(makeContext({ uncertaintyScore: 1.0 }));
|
|
expect(decision.decision).toBe('pause');
|
|
});
|
|
|
|
it('should handle very large step numbers', () => {
|
|
const gate = new ContinueGate();
|
|
const decision = gate.evaluate(makeContext({
|
|
stepNumber: 1000000,
|
|
lastCheckpointStep: 999990,
|
|
}));
|
|
// Should stop due to step limit, but has recent checkpoint
|
|
// so it depends on checkpoint interval check
|
|
expect(decision.decision).toBeDefined();
|
|
});
|
|
});
|