ctxtop 0.0.0-stage → 4.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.antigravity-plugin/plugin.json +36 -0
- package/.claude-plugin/plugin.json +18 -0
- package/CHECKSUMS.sha256 +149 -0
- package/LICENSE +27 -0
- package/README.md +330 -3
- package/SECURITY.md +22 -0
- package/agents/ah-flash-scout.md +25 -0
- package/assets/advanced_view_loaded_420px.png +0 -0
- package/assets/hero-demo.svg +188 -0
- package/assets/logo.svg +19 -0
- package/assets/simple_view_lean_420px.png +0 -0
- package/assets/simple_view_loaded_420px.png +0 -0
- package/assets/social-preview.svg +72 -0
- package/assets/zone_c_step3_shield_full.png +0 -0
- package/bin/ah-statusline.mjs +145 -0
- package/bin/cli.mjs +3 -0
- package/bin/ctxtop.mjs +1474 -0
- package/commands/cost-radar.md +11 -0
- package/commands/evolve.md +10 -0
- package/commands/handoff.md +10 -0
- package/commands/horizon.md +10 -0
- package/commands/inspect.md +10 -0
- package/commands/precheck.md +10 -0
- package/config/default_flightcheck.json +114 -0
- package/config/modelCatalog.json +620 -0
- package/config/platformQuirks.json +19 -0
- package/hooks/handlers/compact-lifecycle.mjs +262 -0
- package/hooks/handlers/hookIo.mjs +255 -0
- package/hooks/handlers/hookIpcClient.mjs +83 -0
- package/hooks/handlers/post-tool-use.mjs +265 -0
- package/hooks/handlers/pre-model-switch.mjs +249 -0
- package/hooks/handlers/pre-tool-use.mjs +365 -0
- package/hooks/handlers/stop-gate.mjs +240 -0
- package/hooks/handlers/user-prompt-submit.mjs +143 -0
- package/hooks/hooks.json +81 -0
- package/hooks/post_invocation.mjs +13 -0
- package/hooks/post_tool_use.mjs +17 -0
- package/hooks/pre_invocation.mjs +14 -0
- package/hooks/pre_tool_use.mjs +97 -0
- package/hooks/register.js +687 -0
- package/hooks/session_start.mjs +14 -0
- package/hooks/stop.mjs +13 -0
- package/hooks.json +56 -0
- package/package.json +103 -4
- package/packages/antigravity/package.json +14 -0
- package/packages/antigravity/src/index.mjs +1 -0
- package/packages/claude-code/package.json +14 -0
- package/packages/claude-code/src/index.mjs +2 -0
- package/packages/core/package.json +14 -0
- package/packages/core/src/index.mjs +1 -0
- package/packages/engine-node/package.json +14 -0
- package/packages/engine-node/src/index.mjs +1 -0
- package/packages/mcp/package.json +17 -0
- package/packages/mcp/src/server.mjs +396 -0
- package/packages/pro/LICENSE-COMMERCIAL.md +19 -0
- package/packages/pro/README-SIGNING.md +30 -0
- package/packages/pro/package.json +16 -0
- package/packages/pro/src/index.mjs +3 -0
- package/packages/pro/src/team_finops_pack.mjs +241 -0
- package/packages/pro/workers/polar_webhook_worker.mjs +215 -0
- package/plugin.json +36 -0
- package/rules/AGENTS.md +10 -0
- package/sidecars/horizon-daemon/ipcServer.mjs +24 -0
- package/sidecars/horizon-daemon/server.mjs +2002 -0
- package/sidecars/horizon-daemon/sidecar.json +19 -0
- package/skills/cost-radar/SKILL.md +21 -0
- package/skills/evolve/SKILL.md +21 -0
- package/skills/handoff/SKILL.md +42 -0
- package/skills/horizon/SKILL.md +17 -0
- package/skills/inspect/SKILL.md +18 -0
- package/skills/precheck/SKILL.md +44 -0
- package/src/adapters/antigravity/index.mjs +79 -0
- package/src/adapters/claude-code/index.mjs +155 -0
- package/src/cli/cost_radar.mjs +70 -0
- package/src/cli/doctor.mjs +351 -0
- package/src/cli/horizon_hud.mjs +686 -0
- package/src/cli/init.mjs +425 -0
- package/src/cli/postmortem.mjs +515 -0
- package/src/coach/cacheGravityRouter.mjs +12 -0
- package/src/config/modelCatalog.json +620 -0
- package/src/config/platformQuirks.json +19 -0
- package/src/core/action_queue.mjs +264 -0
- package/src/core/ag_bridge.mjs +346 -0
- package/src/core/atomic_io.mjs +124 -0
- package/src/core/baseline.mjs +607 -0
- package/src/core/blindspot_sensors.mjs +399 -0
- package/src/core/classifier.mjs +1757 -0
- package/src/core/coach/circuit_breakers.mjs +650 -0
- package/src/core/coach/contradiction_auditor.mjs +239 -0
- package/src/core/coach/effort_advisor.mjs +143 -0
- package/src/core/coach/handoff_hydrator.mjs +483 -0
- package/src/core/coach/progressive_checkpointer.mjs +551 -0
- package/src/core/coach/prompt_decomposer_coach.mjs +141 -0
- package/src/core/coach/reflector_queue.mjs +505 -0
- package/src/core/coach/saved_quota_ledger.mjs +615 -0
- package/src/core/coach/subagent_ipi_sanitizer.mjs +200 -0
- package/src/core/coach/subagent_phantom_auditor.mjs +261 -0
- package/src/core/coach/task_quota_router.mjs +955 -0
- package/src/core/coach/turn_zero_gate.mjs +574 -0
- package/src/core/compaction_coach.mjs +1126 -0
- package/src/core/config.mjs +214 -0
- package/src/core/constants.mjs +1800 -0
- package/src/core/detectors_det01_to_16.mjs +1474 -0
- package/src/core/episodic_memory.mjs +135 -0
- package/src/core/fts5_output_compressor.mjs +359 -0
- package/src/core/git_ledger.mjs +189 -0
- package/src/core/handoff_audit.mjs +558 -0
- package/src/core/history.mjs +221 -0
- package/src/core/hook_diagnostics.mjs +158 -0
- package/src/core/horizon_classifier.mjs +326 -0
- package/src/core/horizon_config.mjs +802 -0
- package/src/core/host_watchdog.mjs +200 -0
- package/src/core/layer5_hygiene.mjs +966 -0
- package/src/core/log_resolver.mjs +231 -0
- package/src/core/mcp_auditor.mjs +138 -0
- package/src/core/micro_skills_store.mjs +91 -0
- package/src/core/offenders.mjs +161 -0
- package/src/core/parser.mjs +1996 -0
- package/src/core/path_canonicalizer.mjs +73 -0
- package/src/core/paths.mjs +310 -0
- package/src/core/prefix_cache_shield.mjs +386 -0
- package/src/core/pro_license.mjs +385 -0
- package/src/core/prompt_rubric.mjs +518 -0
- package/src/core/pruner.mjs +433 -0
- package/src/core/quota.mjs +1860 -0
- package/src/core/rsi_instinct_engine.mjs +1197 -0
- package/src/core/sanitizer.mjs +121 -0
- package/src/core/session_forensics.mjs +303 -0
- package/src/core/session_timeline.mjs +358 -0
- package/src/core/settings.mjs +99 -0
- package/src/core/shared/detectors.mjs +1342 -0
- package/src/core/shared/fnv1a64.mjs +85 -0
- package/src/core/shared/handoff_schema.mjs +123 -0
- package/src/core/shared/index.mjs +5 -0
- package/src/core/shared/ipi_sanitizer.mjs +165 -0
- package/src/core/shared/micro_skills.mjs +1 -0
- package/src/core/shared/plugin_validator.mjs +202 -0
- package/src/core/shared/prompt_hygiene_governor.mjs +1 -0
- package/src/core/sidecar_store.mjs +302 -0
- package/src/core/sprint_metrics.mjs +366 -0
- package/src/core/sqlite_client.mjs +283 -0
- package/src/core/storage_doctor.mjs +358 -0
- package/src/core/subagents.mjs +609 -0
- package/src/core/swarm_topology.mjs +360 -0
- package/src/core/task_quota_router.mjs +1656 -0
- package/src/core/telemetry/cache_ttl_watchdog.mjs +284 -0
- package/src/core/telemetry/scope_lock_registry.mjs +578 -0
- package/src/core/telemetry/shadow_file_detector.mjs +291 -0
- package/src/core/telemetry/trajectory_watcher.mjs +259 -0
- package/src/core/timeline_svg.mjs +236 -0
- package/src/core/tool_surgeon.mjs +305 -0
- package/src/core/trajectory_stitcher.mjs +645 -0
- package/src/core/u_shaped_optimizer.mjs +789 -0
- package/src/core/wal_hygiene.mjs +233 -0
- package/src/core-isomorphic/catalog/detectorCatalog.mjs +558 -0
- package/src/core-isomorphic/catalog/index.mjs +1 -0
- package/src/core-isomorphic/coach/cacheGravityRouter.mjs +720 -0
- package/src/core-isomorphic/coach/microSkills.mjs +1 -0
- package/src/core-isomorphic/coach/promptHygieneGovernor.mjs +1 -0
- package/src/core-isomorphic/coach/repoCalibration.mjs +254 -0
- package/src/core-isomorphic/coach/savedQuotaLedger.mjs +527 -0
- package/src/core-isomorphic/coach/stateBatonHydrator.mjs +810 -0
- package/src/core-isomorphic/coach/ttlWatchdog.mjs +457 -0
- package/src/core-isomorphic/config/anthropicModelCatalog.json +203 -0
- package/src/core-isomorphic/config/catalogLoader.mjs +768 -0
- package/src/core-isomorphic/config/horizonConfig.mjs +1009 -0
- package/src/core-isomorphic/control/callTree.mjs +338 -0
- package/src/core-isomorphic/control/coachLatches.mjs +126 -0
- package/src/core-isomorphic/control/controlStateMachine.mjs +205 -0
- package/src/core-isomorphic/control/index.mjs +49 -0
- package/src/core-isomorphic/control/swarmWorktree.mjs +109 -0
- package/src/core-isomorphic/control/toolSuspension.mjs +197 -0
- package/src/core-isomorphic/diagnostics/drift_guard.mjs +382 -0
- package/src/core-isomorphic/diagnostics/index.mjs +9 -0
- package/src/core-isomorphic/diagnostics/micro_skills.mjs +471 -0
- package/src/core-isomorphic/diagnostics/prompt_hygiene_governor.mjs +622 -0
- package/src/core-isomorphic/economics/billingBlocks.mjs +251 -0
- package/src/core-isomorphic/economics/cacheGravity.mjs +351 -0
- package/src/core-isomorphic/economics/cliffBreaker.mjs +170 -0
- package/src/core-isomorphic/economics/driftLatency.mjs +319 -0
- package/src/core-isomorphic/economics/dualTtl.mjs +198 -0
- package/src/core-isomorphic/economics/index.mjs +47 -0
- package/src/core-isomorphic/economics/retentionRadar.mjs +348 -0
- package/src/core-isomorphic/guards/circuitBreakers.mjs +1202 -0
- package/src/core-isomorphic/guards/det01_03_shell_secret.mjs +1035 -0
- package/src/core-isomorphic/guards/det04_12_thrash_rot.mjs +480 -0
- package/src/core-isomorphic/guards/det13_20_mcp_scope.mjs +603 -0
- package/src/core-isomorphic/guards/losslessPostSanitizer.mjs +301 -0
- package/src/core-isomorphic/index.js +26 -0
- package/src/core-isomorphic/telemetry/otelExporter.mjs +187 -0
- package/src/core-isomorphic/telemetry/scopeLockRegistry.mjs +522 -0
- package/src/core-isomorphic/telemetry/sprintMetrics.mjs +327 -0
- package/src/core-isomorphic/telemetry/swarmTopology.mjs +152 -0
- package/src/core-isomorphic/telemetry/telemetryBridge.mjs +1132 -0
- package/src/core-isomorphic/ui/brailleSparkline.mjs +142 -0
- package/src/core-isomorphic/ui/costRadarSvg.mjs +276 -0
- package/src/core-isomorphic/ui/horizonGrid.mjs +475 -0
- package/src/core-isomorphic/ui/horizonPanelHtml.mjs +1181 -0
- package/src/core-isomorphic/ui/modViews.mjs +1478 -0
- package/src/core-isomorphic/ui/pdfReceiptGenerator.mjs +329 -0
- package/src/core-isomorphic/ustf/index.mjs +7 -0
- package/src/core-isomorphic/ustf/normalizer.mjs +512 -0
- package/src/core-isomorphic/ustf/schema.mjs +186 -0
- package/src/core-isomorphic/utils/runtime.mjs +962 -0
- package/src/demo/synthetic_states.mjs +661 -0
- package/src/diagnostics/bugReportGenerator.mjs +253 -0
- package/src/diagnostics/doctorEngine.mjs +203 -0
- package/src/engine-node/db/index.mjs +58 -0
- package/src/engine-node/db/jsonl_fallback.mjs +184 -0
- package/src/engine-node/db/probe.mjs +110 -0
- package/src/engine-node/db/sqlite_wrapper.mjs +122 -0
- package/src/engine-node/index.mjs +9 -0
- package/src/engine-node/ipc/client.mjs +447 -0
- package/src/engine-node/ipc/index.mjs +22 -0
- package/src/engine-node/ipc/protocol.mjs +177 -0
- package/src/engine-node/ipc/server.mjs +445 -0
- package/src/engine-node/offloader/index.mjs +6 -0
- package/src/engine-node/offloader/tool_offloader.mjs +241 -0
- package/src/engine-node/sensors/blindspots.mjs +369 -0
- package/src/engine-node/sensors/git_merge_tree.mjs +223 -0
- package/src/engine-node/sensors/index.mjs +7 -0
- package/src/hooks/portfolio_runtime.mjs +858 -0
- package/src/hooks/post_invocation.mjs +419 -0
- package/src/hooks/pre_invocation.mjs +1015 -0
- package/src/hooks/session_start.mjs +161 -0
- package/src/shims/agy_cli_compressor.mjs +705 -0
- package/src/shims/agy_git_guard.mjs +749 -0
- package/src/shims/ah_log_query.mjs +39 -0
- package/src/ui/costRadarSvg.mjs +6 -0
- package/src/ui/horizonGrid.mjs +1 -0
- package/src/ui/horizonPanelHtml.mjs +1 -0
- package/src/ui/horizon_panel.css +167 -0
- package/src/ui/horizon_panel.js +212 -0
- package/src/ui/modViews.mjs +1 -0
- package/src/utils/nodeIo.mjs +59 -0
- package/src/utils/runtime.mjs +1 -0
- package/src/webview/advanced_view.html +1808 -0
- package/src/webview/horizon_panel.html +11389 -0
- package/src/webview/registry.mjs +80 -0
- package/src/webview/simple_view.html +1370 -0
|
@@ -0,0 +1,1757 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import {
|
|
4
|
+
HORIZON_WINDOW,
|
|
5
|
+
SESSION_RISK_THRESHOLDS,
|
|
6
|
+
PREFIX_LOCK_WARNING_TEXT,
|
|
7
|
+
CORTEX_CLAMPED_CEILING_LABEL,
|
|
8
|
+
WATERMARK_TOOLTIPS,
|
|
9
|
+
STRANDED_SIGNAL_WARNING_TEXT,
|
|
10
|
+
ATTENTION_TROUGH_CONFIG,
|
|
11
|
+
CATEGORIES,
|
|
12
|
+
MODEL_PRICING_PER_MILLION,
|
|
13
|
+
EFFORT_PROFILES,
|
|
14
|
+
resolveEffortProfile,
|
|
15
|
+
resolveModelCeiling,
|
|
16
|
+
resolveModelCeilingDetailed,
|
|
17
|
+
resolvePricePerM,
|
|
18
|
+
resolveSurfaceTag,
|
|
19
|
+
scaleEffortProfileForCeiling,
|
|
20
|
+
computeUnifiedContextPool,
|
|
21
|
+
evaluateCarbonVerbosityGuardrail,
|
|
22
|
+
getDeprecatedModelMigrationNotice
|
|
23
|
+
} from './constants.mjs';
|
|
24
|
+
import { loadFlightcheckConfig } from './config.mjs';
|
|
25
|
+
import { loadCliSurfaceSettings } from './settings.mjs';
|
|
26
|
+
import { canonicalizePath, isIgnorablePath } from './paths.mjs';
|
|
27
|
+
import { extractEffortTimeline } from './parser.mjs';
|
|
28
|
+
import { computeQuotaAndCacheTelemetry, humanizeModelLabel } from './quota.mjs';
|
|
29
|
+
import { inspectSubagentTree } from './subagents.mjs';
|
|
30
|
+
import { computeSwarmTopology } from './swarm_topology.mjs';
|
|
31
|
+
import { loadRegistry as loadSwarmScopeRegistry } from './telemetry/scope_lock_registry.mjs';
|
|
32
|
+
import { computePlanChurn, gradeProofQuality, detectContextRot, fingerprintErrorLoop } from './session_forensics.mjs';
|
|
33
|
+
import { auditHandoff } from './handoff_audit.mjs';
|
|
34
|
+
import {
|
|
35
|
+
synthesizeParameterizedCompact,
|
|
36
|
+
evaluateCompactionCacheAdvisory,
|
|
37
|
+
synthesizeBatonPassHandoffCommand,
|
|
38
|
+
isInternalTelemetryPath,
|
|
39
|
+
isCompactionRelevant
|
|
40
|
+
} from './prompt_rubric.mjs';
|
|
41
|
+
import { auditMcpPrefixBloat } from './baseline.mjs';
|
|
42
|
+
import { buildActionQueue, formatActionQueueAnsi } from './action_queue.mjs';
|
|
43
|
+
import { buildSessionTimeline } from './session_timeline.mjs';
|
|
44
|
+
import {
|
|
45
|
+
CORTEX_STEP_TYPE_CHECKPOINT,
|
|
46
|
+
MEMORY_MD_TRUNCATION_THRESHOLD_LINES,
|
|
47
|
+
isCompactionCheckpointStep,
|
|
48
|
+
evaluateSmartFileReReads,
|
|
49
|
+
wrapNoisyCommandWithDampener,
|
|
50
|
+
registerCliDampeningHook,
|
|
51
|
+
computeAttentionZoneInsertionIndex,
|
|
52
|
+
auditRuleFileAttentionAndLineLimit,
|
|
53
|
+
promoteRuleWithAttentionZone
|
|
54
|
+
} from './layer5_hygiene.mjs';
|
|
55
|
+
|
|
56
|
+
export {
|
|
57
|
+
CORTEX_STEP_TYPE_CHECKPOINT,
|
|
58
|
+
MEMORY_MD_TRUNCATION_THRESHOLD_LINES,
|
|
59
|
+
STRANDED_SIGNAL_WARNING_TEXT,
|
|
60
|
+
ATTENTION_TROUGH_CONFIG,
|
|
61
|
+
isCompactionCheckpointStep,
|
|
62
|
+
evaluateSmartFileReReads,
|
|
63
|
+
wrapNoisyCommandWithDampener,
|
|
64
|
+
registerCliDampeningHook,
|
|
65
|
+
computeAttentionZoneInsertionIndex,
|
|
66
|
+
auditRuleFileAttentionAndLineLimit,
|
|
67
|
+
promoteRuleWithAttentionZone,
|
|
68
|
+
auditMcpPrefixBloat,
|
|
69
|
+
buildActionQueue,
|
|
70
|
+
formatActionQueueAnsi
|
|
71
|
+
};
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* Parabolic U-Shaped Attention Curve & Low-Attention Trough Model.
|
|
75
|
+
*
|
|
76
|
+
* Models positional recall decay across N populated cells (gamma = 0.6):
|
|
77
|
+
* - U-shaped recall weight (1.0 at Primacy/Recency edges, minimum 1.0 - gamma at midpoint 0.5):
|
|
78
|
+
* A_u(i) = (1.0 - gamma) + 4.0 * gamma * ((i / N) - 0.5)^2
|
|
79
|
+
* - Shades the middle 30% to 70% band (or Cells 7..15) as the Low-Attention Trough.
|
|
80
|
+
*/
|
|
81
|
+
export function calculateParabolicAttentionCurve(cellIndex, activeCellCount, gamma = ATTENTION_TROUGH_CONFIG.GAMMA) {
|
|
82
|
+
if (activeCellCount <= 1) {
|
|
83
|
+
return {
|
|
84
|
+
cellIndex,
|
|
85
|
+
activeCellCount,
|
|
86
|
+
gamma,
|
|
87
|
+
normalizedPosition: 0,
|
|
88
|
+
uShapedWeight: 1.0,
|
|
89
|
+
specFormulaValue: 1.0,
|
|
90
|
+
inTrough: false,
|
|
91
|
+
zone: 'PRIMACY'
|
|
92
|
+
};
|
|
93
|
+
}
|
|
94
|
+
const N = Math.max(1, activeCellCount - 1);
|
|
95
|
+
const clampedIdx = Math.max(0, Math.min(N, cellIndex));
|
|
96
|
+
const ratio = clampedIdx / N;
|
|
97
|
+
const distFromCenterSq = Math.pow(ratio - 0.5, 2);
|
|
98
|
+
const specFormulaValue = parseFloat((1.0 - 4.0 * gamma * distFromCenterSq).toFixed(3));
|
|
99
|
+
const uShapedWeight = parseFloat(Math.min(1.0, Math.max(0.20, (1.0 - gamma) + 4.0 * gamma * distFromCenterSq)).toFixed(2));
|
|
100
|
+
|
|
101
|
+
const inRatioTrough = activeCellCount >= 7 &&
|
|
102
|
+
ratio >= ATTENTION_TROUGH_CONFIG.TROUGH_START_RATIO &&
|
|
103
|
+
ratio <= ATTENTION_TROUGH_CONFIG.TROUGH_END_RATIO;
|
|
104
|
+
const inCanonicalCellTrough = activeCellCount >= 23 &&
|
|
105
|
+
cellIndex >= ATTENTION_TROUGH_CONFIG.CANONICAL_TROUGH_START_CELL &&
|
|
106
|
+
cellIndex <= ATTENTION_TROUGH_CONFIG.CANONICAL_TROUGH_END_CELL &&
|
|
107
|
+
ratio <= ATTENTION_TROUGH_CONFIG.TROUGH_END_RATIO;
|
|
108
|
+
const inTrough = inRatioTrough || inCanonicalCellTrough;
|
|
109
|
+
|
|
110
|
+
let zone = 'LOW_ATTENTION_TROUGH';
|
|
111
|
+
if (!inTrough) {
|
|
112
|
+
zone = ratio < 0.5 ? 'PRIMACY' : 'RECENCY';
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
return {
|
|
116
|
+
cellIndex,
|
|
117
|
+
activeCellCount,
|
|
118
|
+
gamma,
|
|
119
|
+
normalizedPosition: parseFloat(ratio.toFixed(3)),
|
|
120
|
+
uShapedWeight,
|
|
121
|
+
specFormulaValue,
|
|
122
|
+
inTrough,
|
|
123
|
+
zone
|
|
124
|
+
};
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/**
|
|
128
|
+
* Calculates U-Shaped Attention Recall Curve weight A(i) for cell i in [0..activeCellCount-1]
|
|
129
|
+
*/
|
|
130
|
+
export function calculateAttentionWeight(cellIndex, activeCellCount, gamma = ATTENTION_TROUGH_CONFIG.GAMMA) {
|
|
131
|
+
return calculateParabolicAttentionCurve(cellIndex, activeCellCount, gamma).uShapedWeight;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/**
|
|
135
|
+
* Locked v2.0 UI Law 3: Zero-Click Passive Workload Tag.
|
|
136
|
+
* Passively classifies session state from tool-call ratios without manual dropdowns or buttons,
|
|
137
|
+
* and adjusts warning thresholds automatically.
|
|
138
|
+
*/
|
|
139
|
+
export function classifyWorkloadMode(steps = []) {
|
|
140
|
+
let readCalls = 0;
|
|
141
|
+
let editCalls = 0;
|
|
142
|
+
let subagentCalls = 0;
|
|
143
|
+
let totalCalls = 0;
|
|
144
|
+
let subagentSteps = 0;
|
|
145
|
+
const editedFiles = new Set();
|
|
146
|
+
|
|
147
|
+
for (const s of (Array.isArray(steps) ? steps : [])) {
|
|
148
|
+
if (!s || typeof s !== 'object') continue;
|
|
149
|
+
if (s.isSidechain || (s.agentId && s.agentId !== 'parent') || s.hasSubtrajectory) {
|
|
150
|
+
subagentSteps++;
|
|
151
|
+
}
|
|
152
|
+
const calls = Array.isArray(s.toolCalls) ? s.toolCalls : (Array.isArray(s.tool_calls) ? s.tool_calls : []);
|
|
153
|
+
if (calls.length === 0 && s.toolName) {
|
|
154
|
+
calls.push({ name: s.toolName, args: s.targetPath ? { Path: s.targetPath } : {} });
|
|
155
|
+
}
|
|
156
|
+
for (const c of calls) {
|
|
157
|
+
const name = String(c?.name || c?.tool || '').toLowerCase();
|
|
158
|
+
if (!name) continue;
|
|
159
|
+
totalCalls++;
|
|
160
|
+
if (name.includes('subagent') || name === 'agent' || name === 'task') {
|
|
161
|
+
subagentCalls++;
|
|
162
|
+
} else if (/write|edit|replace|create|patch/i.test(name)) {
|
|
163
|
+
editCalls++;
|
|
164
|
+
const f = c?.args?.Path || c?.args?.path || c?.args?.TargetFile || c?.args?.AbsolutePath || s.targetPath;
|
|
165
|
+
if (f) editedFiles.add(String(f).toLowerCase());
|
|
166
|
+
} else if (/read|view|grep|find|search|glob|list/i.test(name)) {
|
|
167
|
+
readCalls++;
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
const readRatio = totalCalls > 0 ? parseFloat((readCalls / totalCalls).toFixed(2)) : 1.0;
|
|
173
|
+
const editRatio = totalCalls > 0 ? parseFloat((editCalls / totalCalls).toFixed(2)) : 0.0;
|
|
174
|
+
const subagentStepRatio = steps.length > 0 ? subagentSteps / steps.length : 0;
|
|
175
|
+
|
|
176
|
+
if (subagentCalls >= 2 || (subagentCalls >= 1 && subagentSteps >= 2) || subagentStepRatio >= 0.20) {
|
|
177
|
+
return {
|
|
178
|
+
modeId: 'SUBAGENT_SWARM',
|
|
179
|
+
tag: '[Mode: Subagent Swarm]',
|
|
180
|
+
readRatio,
|
|
181
|
+
editRatio,
|
|
182
|
+
subagentCount: Math.max(subagentCalls, subagentSteps > 0 ? 1 : 0),
|
|
183
|
+
safeLimitMultiplier: 1.05,
|
|
184
|
+
reReadTolerance: 2,
|
|
185
|
+
thresholds: { safeLimitDeltaTokens: 10000, duplicateReadTolerance: 2 }
|
|
186
|
+
};
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
if (editCalls >= 2 && (editRatio >= 0.25 || editedFiles.size >= 3)) {
|
|
190
|
+
return {
|
|
191
|
+
modeId: 'MULTI_FILE_REFACTOR',
|
|
192
|
+
tag: '[Mode: Multi-File Refactor]',
|
|
193
|
+
readRatio,
|
|
194
|
+
editRatio,
|
|
195
|
+
subagentCount: subagentCalls,
|
|
196
|
+
safeLimitMultiplier: 0.95,
|
|
197
|
+
reReadTolerance: 3,
|
|
198
|
+
thresholds: { safeLimitDeltaTokens: -10000, duplicateReadTolerance: 3 }
|
|
199
|
+
};
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
return {
|
|
203
|
+
modeId: 'READ_HEAVY_AUDIT',
|
|
204
|
+
tag: '[Mode: Read-Heavy Audit]',
|
|
205
|
+
readRatio,
|
|
206
|
+
editRatio,
|
|
207
|
+
subagentCount: subagentCalls,
|
|
208
|
+
safeLimitMultiplier: 1.0,
|
|
209
|
+
reReadTolerance: 2,
|
|
210
|
+
thresholds: { safeLimitDeltaTokens: 0, duplicateReadTolerance: 2 }
|
|
211
|
+
};
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
/**
|
|
215
|
+
* Locked v2.0 UI Law 2: Hero 40-Cell Flamegraph + Top 3-5 Riskiest Cells.
|
|
216
|
+
* Ranks the top 3-5 riskiest cells with exact file paths, token weights, attention recall %,
|
|
217
|
+
* and a 1-click `[Re-Anchor / Prune]` action when critical specs (`task.md`) drift into the trough.
|
|
218
|
+
*/
|
|
219
|
+
export function rankRiskiestCells(cells = [], { totalActiveTokens = 0, safeLimit = 140000, cellSizeTokens = 6400 } = {}) {
|
|
220
|
+
if (!Array.isArray(cells) || cells.length === 0) return [];
|
|
221
|
+
const scored = [];
|
|
222
|
+
|
|
223
|
+
for (const c of cells) {
|
|
224
|
+
if (!c || c.dominantCategory === CATEGORIES.FREE_HEADROOM) continue;
|
|
225
|
+
const catMap = c.tokensByCategory || {};
|
|
226
|
+
const cellTokens = Object.values(catMap).reduce((s, v) => s + Number(v || 0), 0) || Number(c.totalTokens) || cellSizeTokens;
|
|
227
|
+
if (cellTokens <= 0) continue;
|
|
228
|
+
|
|
229
|
+
const target = String(c.topTarget || c.primaryPath || `Cell #${(c.index ?? 0) + 1}`);
|
|
230
|
+
const isCriticalSpec = /task\.md|implementation_plan\.md|agents\.md|context\.md|state\.md/i.test(target);
|
|
231
|
+
const inTrough = typeof c.inAttentionTrough === 'boolean'
|
|
232
|
+
? c.inAttentionTrough
|
|
233
|
+
: Boolean(totalActiveTokens >= 44800 && (cells?.length || 0) >= 23 && c.index >= 6 && c.index <= 15);
|
|
234
|
+
const isStrandedSpec = (Boolean(c.isStrandedSignal) || inTrough) && (isCriticalSpec || c.dominantCategory === CATEGORIES.ANCHOR || c.dominantCategory === CATEGORIES.ACTIVE_WORKING_SET);
|
|
235
|
+
const wasteTokens = (catMap[CATEGORIES.STALE_DUPLICATE] || 0) + (catMap[CATEGORIES.DEAD_ERROR] || 0) + (catMap[CATEGORIES.FOREIGN_BLEED] || 0);
|
|
236
|
+
const isAmputation = Boolean(c.isAmputationZone || (totalActiveTokens > safeLimit && c.index < 8));
|
|
237
|
+
const recallPct = Math.round((Number(c.attentionWeight) || 0.4) * 100);
|
|
238
|
+
|
|
239
|
+
let riskScore = 0;
|
|
240
|
+
let riskReason = 'HIGH_SLUDGE_DENSITY';
|
|
241
|
+
let actionType = 'PRUNE';
|
|
242
|
+
|
|
243
|
+
if (isStrandedSpec && isCriticalSpec) {
|
|
244
|
+
riskScore = 100000 + cellTokens + (100 - recallPct) * 500;
|
|
245
|
+
riskReason = 'TROUGH_STRANDED_SPEC';
|
|
246
|
+
actionType = 'REANCHOR';
|
|
247
|
+
} else if (isStrandedSpec) {
|
|
248
|
+
riskScore = 70000 + cellTokens + (100 - recallPct) * 300;
|
|
249
|
+
riskReason = 'TROUGH_STRANDED_SPEC';
|
|
250
|
+
actionType = 'REANCHOR';
|
|
251
|
+
} else if (isAmputation) {
|
|
252
|
+
riskScore = 50000 + cellTokens;
|
|
253
|
+
riskReason = 'AMPUTATION_ZONE';
|
|
254
|
+
actionType = isCriticalSpec ? 'REANCHOR' : 'PRUNE';
|
|
255
|
+
} else if (wasteTokens > 0 || String(c.dominantCategory).includes('STALE') || String(c.dominantCategory).includes('ERROR')) {
|
|
256
|
+
riskScore = 20000 + (wasteTokens || cellTokens);
|
|
257
|
+
riskReason = 'HIGH_SLUDGE_DENSITY';
|
|
258
|
+
actionType = 'PRUNE';
|
|
259
|
+
} else if (inTrough && recallPct < 60) {
|
|
260
|
+
riskScore = 10000 + cellTokens * (1 - (Number(c.attentionWeight) || 0.5));
|
|
261
|
+
riskReason = 'LOW_ATTENTION_TROUGH';
|
|
262
|
+
actionType = 'REANCHOR';
|
|
263
|
+
} else {
|
|
264
|
+
// Cell is clean with 0 waste tokens and healthy recall; do not flag as risky
|
|
265
|
+
continue;
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
scored.push({
|
|
269
|
+
cellIndex: c.index ?? 0,
|
|
270
|
+
cellNumber: (c.index ?? 0) + 1,
|
|
271
|
+
filePath: target,
|
|
272
|
+
tokenWeight: cellTokens,
|
|
273
|
+
wasteTokens,
|
|
274
|
+
attentionRecallPct: recallPct,
|
|
275
|
+
inTrough,
|
|
276
|
+
riskScore,
|
|
277
|
+
riskReason,
|
|
278
|
+
actionType,
|
|
279
|
+
actionLabel: '[Re-Anchor / Prune]',
|
|
280
|
+
specificActionLabel: actionType === 'REANCHOR' ? '[Re-Anchor Cell to Handoff]' : '[Prune Stale Tool Outputs]'
|
|
281
|
+
});
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
return scored
|
|
285
|
+
.sort((a, b) => b.riskScore - a.riskScore)
|
|
286
|
+
.slice(0, 5)
|
|
287
|
+
.map(({ riskScore, ...rest }) => rest);
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
/**
|
|
291
|
+
* Evaluates Composite Operational Session Risk & Prefix-Lock Protection.
|
|
292
|
+
*
|
|
293
|
+
* Rules:
|
|
294
|
+
* - RED: Context >= 179k (safe horizon breached) OR 7d lockout risk active without AI Credit overages enabled.
|
|
295
|
+
* - AMBER: Cache TTL == 0s (cold cache window expired) OR context > 50k with pending checklist item OR task.md is >= 1 turn stale.
|
|
296
|
+
* - GREEN: Total tokens < 179k AND Cache TTL > 0s AND task.md is in sync (0 turns behind).
|
|
297
|
+
* - Prefix-Lock Protection Warning: Active when a session holds > 50k cached tokens with TTL > 0s.
|
|
298
|
+
*/
|
|
299
|
+
export function evaluateCompositeSessionRisk({
|
|
300
|
+
totalActiveTokens = 0,
|
|
301
|
+
safeHorizonTokens = undefined,
|
|
302
|
+
safeLimit = undefined,
|
|
303
|
+
cacheTtlRemainingSec = 300,
|
|
304
|
+
cacheReadTokens = 0,
|
|
305
|
+
cacheHitRatePct = 0,
|
|
306
|
+
taskMdTurnsBehind = 0,
|
|
307
|
+
taskMdExists = true,
|
|
308
|
+
sessionHasWorkspaceEdits = true,
|
|
309
|
+
hasPendingTaskItems = false,
|
|
310
|
+
weekly7dUsedPct = 0,
|
|
311
|
+
weekly7dLockoutRisk = false,
|
|
312
|
+
weekly7dSource = undefined,
|
|
313
|
+
aiCreditOveragesEnabled = false,
|
|
314
|
+
prefixBustDetected = false
|
|
315
|
+
} = {}) {
|
|
316
|
+
const resolvedHorizon = safeHorizonTokens ?? safeLimit;
|
|
317
|
+
const safeHorizon = Number(resolvedHorizon) > 0
|
|
318
|
+
? Number(resolvedHorizon)
|
|
319
|
+
: SESSION_RISK_THRESHOLDS.SAFE_HORIZON_TOKENS;
|
|
320
|
+
|
|
321
|
+
const isSafeHorizonBreached = totalActiveTokens >= safeHorizon;
|
|
322
|
+
// Local quota estimates never escalate to RED; only host-sourced (or legacy unsourced) 7d values do.
|
|
323
|
+
const is7dLockoutWithoutOverages = weekly7dSource !== 'estimate' &&
|
|
324
|
+
(weekly7dUsedPct >= 100 || Boolean(weekly7dLockoutRisk)) && !aiCreditOveragesEnabled;
|
|
325
|
+
const isCacheExpired = Number(cacheTtlRemainingSec) <= 0 &&
|
|
326
|
+
totalActiveTokens >= SESSION_RISK_THRESHOLDS.LEAN_SESSION_TOKENS;
|
|
327
|
+
const isCascadeArmedWithPendingTask = totalActiveTokens > SESSION_RISK_THRESHOLDS.CASCADE_SYNC_WATERMARK_TOKENS && Boolean(hasPendingTaskItems);
|
|
328
|
+
const isTaskMdStale = Boolean(taskMdExists) && Boolean(sessionHasWorkspaceEdits) && Number(taskMdTurnsBehind) >= 1;
|
|
329
|
+
|
|
330
|
+
const effectiveCachedTokens = Math.max(
|
|
331
|
+
Number(cacheReadTokens || 0),
|
|
332
|
+
cacheHitRatePct > 0 ? Math.round(totalActiveTokens * (cacheHitRatePct / 100)) : 0,
|
|
333
|
+
!isCacheExpired ? totalActiveTokens : 0
|
|
334
|
+
);
|
|
335
|
+
// the Warm badge requires real cache-read evidence, not merely TTL > 0s.
|
|
336
|
+
const isCacheTrulyWarm = computeIsCacheTrulyWarm({
|
|
337
|
+
ttlRemainingSec: cacheTtlRemainingSec,
|
|
338
|
+
cacheReadTokens,
|
|
339
|
+
hitRatePct: cacheHitRatePct,
|
|
340
|
+
prefixBustDetected
|
|
341
|
+
});
|
|
342
|
+
const prefixLockWarning = isCacheTrulyWarm && effectiveCachedTokens > SESSION_RISK_THRESHOLDS.WARM_CACHE_LOCK_TOKENS;
|
|
343
|
+
|
|
344
|
+
const safeHorizonK = Math.round(safeHorizon / 1000);
|
|
345
|
+
const reasons = [];
|
|
346
|
+
let band = 'GREEN';
|
|
347
|
+
|
|
348
|
+
if (isSafeHorizonBreached || is7dLockoutWithoutOverages) {
|
|
349
|
+
band = 'RED';
|
|
350
|
+
if (isSafeHorizonBreached) {
|
|
351
|
+
reasons.push(`Safe horizon breached (${Math.round(totalActiveTokens / 1000)}k >= ${safeHorizonK}k tokens)`);
|
|
352
|
+
}
|
|
353
|
+
if (is7dLockoutWithoutOverages) {
|
|
354
|
+
reasons.push('7d quota lockout risk active without AI Credit overages enabled');
|
|
355
|
+
}
|
|
356
|
+
} else if (isCacheExpired || isCascadeArmedWithPendingTask || isTaskMdStale) {
|
|
357
|
+
band = 'AMBER';
|
|
358
|
+
if (isCacheExpired) {
|
|
359
|
+
reasons.push('Cache TTL == 0s (cold cache window expired)');
|
|
360
|
+
}
|
|
361
|
+
if (isCascadeArmedWithPendingTask) {
|
|
362
|
+
reasons.push('Context > 50k with pending task.md checklist item (Cascade sync armed)');
|
|
363
|
+
}
|
|
364
|
+
if (isTaskMdStale) {
|
|
365
|
+
reasons.push(`task.md is ${taskMdTurnsBehind} turn${taskMdTurnsBehind === 1 ? '' : 's'} stale`);
|
|
366
|
+
}
|
|
367
|
+
} else {
|
|
368
|
+
band = 'GREEN';
|
|
369
|
+
const cacheStatusLabel = isCacheTrulyWarm
|
|
370
|
+
? 'warm KV cache TTL > 0s'
|
|
371
|
+
: (Number(cacheTtlRemainingSec) > 0 ? 'cache window open (0 cached reads yet)' : 'lean session');
|
|
372
|
+
reasons.push(`Healthy (<${safeHorizonK}k tokens, ${cacheStatusLabel}, task.md in sync)`);
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
return {
|
|
376
|
+
band,
|
|
377
|
+
isCacheTrulyWarm,
|
|
378
|
+
dotClass: band === 'RED' ? 'dot danger' : (band === 'AMBER' ? 'dot warn' : 'dot'),
|
|
379
|
+
reasons,
|
|
380
|
+
summary: reasons.join(' · '),
|
|
381
|
+
prefixLockWarning,
|
|
382
|
+
prefixLockCachedTokens: prefixLockWarning ? effectiveCachedTokens : 0,
|
|
383
|
+
prefixLockTooltip: prefixLockWarning ? PREFIX_LOCK_WARNING_TEXT : ''
|
|
384
|
+
};
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
/**
|
|
388
|
+
* strict cache warmth predicate. TTL > 0s alone is NOT proof of a warm cache —
|
|
389
|
+
* a session with 0 cache-read tokens or a 0% hit rate is cold regardless of the TTL clock.
|
|
390
|
+
*/
|
|
391
|
+
export function computeIsCacheTrulyWarm(cache = {}) {
|
|
392
|
+
if (!cache || cache.isCacheCold || cache.prefixBustDetected) return false;
|
|
393
|
+
const readTok = Number(cache.cacheReadTokens ?? cache.cachedTokens ?? 0);
|
|
394
|
+
const hasHitPct = cache.hitRatePct !== undefined && cache.hitRatePct !== null;
|
|
395
|
+
const hitOk = hasHitPct ? Number(cache.hitRatePct) > 0 : readTok > 0;
|
|
396
|
+
return Boolean(Number(cache.ttlRemainingSec) > 0 && readTok > 0 && hitOk);
|
|
397
|
+
}
|
|
398
|
+
|
|
399
|
+
/**
|
|
400
|
+
* Tenth-of-a-Kilotoken Mathematical Parity.
|
|
401
|
+
* Derives the reclaimable display value from the rounded total and active values so that
|
|
402
|
+
* Active Signal + Reclaimable always equals the headline total to exactly 0.1k.
|
|
403
|
+
* If `anchorReclaimTenths` is supplied (sum of rounded reclaim rows), Reclaimable is pinned to it
|
|
404
|
+
* and Active absorbs the rounding remainder so rows, badge and card stay identical.
|
|
405
|
+
*/
|
|
406
|
+
export function computeDisplayTenthsParity(totalTokens = 0, activeSignalTokens = 0, anchorReclaimTenths = null) {
|
|
407
|
+
const displayTotalTenths = Math.round(Math.max(0, Number(totalTokens) || 0) / 100);
|
|
408
|
+
const hasAnchor = anchorReclaimTenths !== null && Number.isFinite(Number(anchorReclaimTenths)) && Number(anchorReclaimTenths) >= 0;
|
|
409
|
+
const displayActiveTenths = hasAnchor
|
|
410
|
+
? displayTotalTenths - Math.min(displayTotalTenths, Math.round(Number(anchorReclaimTenths)))
|
|
411
|
+
: Math.min(displayTotalTenths, Math.round(Math.max(0, Number(activeSignalTokens) || 0) / 100));
|
|
412
|
+
const displayReclaimableTenths = Math.max(0, displayTotalTenths - displayActiveTenths);
|
|
413
|
+
return {
|
|
414
|
+
displayTotalTenths,
|
|
415
|
+
displayActiveTenths,
|
|
416
|
+
displayReclaimableTenths,
|
|
417
|
+
totalK: displayTotalTenths / 10,
|
|
418
|
+
activeK: displayActiveTenths / 10,
|
|
419
|
+
reclaimableK: displayReclaimableTenths / 10
|
|
420
|
+
};
|
|
421
|
+
}
|
|
422
|
+
|
|
423
|
+
/**
|
|
424
|
+
* Evaluates State-Conditional Bar Coloring for the older history segment.
|
|
425
|
+
* - Muted Slate/Teal ('Cached History — 95% Discounted') while TTL > 0s and totalActiveTokens <= 179k.
|
|
426
|
+
* - Amber ('Reclaimable Cold Bloat') ONLY when TTL == 0s OR totalActiveTokens > 179k.
|
|
427
|
+
*/
|
|
428
|
+
export function evaluateHistoryBarState({
|
|
429
|
+
totalActiveTokens = 0,
|
|
430
|
+
safeHorizonTokens = SESSION_RISK_THRESHOLDS.SAFE_HORIZON_TOKENS,
|
|
431
|
+
cacheTtlRemainingSec = 300,
|
|
432
|
+
isCacheTrulyWarm,
|
|
433
|
+
nextTurnLikelyWarm
|
|
434
|
+
} = {}) {
|
|
435
|
+
const safeHorizon = Number(safeHorizonTokens) > 0
|
|
436
|
+
? Number(safeHorizonTokens)
|
|
437
|
+
: SESSION_RISK_THRESHOLDS.SAFE_HORIZON_TOKENS;
|
|
438
|
+
// When strict warmth evidence is supplied, a 0% hit / 0 cache-read session is COLD_BLOAT even if TTL > 0s.
|
|
439
|
+
const warmEvidence = typeof isCacheTrulyWarm === 'boolean' ? isCacheTrulyWarm : nextTurnLikelyWarm;
|
|
440
|
+
const isNotTrulyWarm = warmEvidence === false;
|
|
441
|
+
const isColdOrOverHorizon = isNotTrulyWarm || Number(cacheTtlRemainingSec) <= 0 || Number(totalActiveTokens) > safeHorizon;
|
|
442
|
+
|
|
443
|
+
if (isColdOrOverHorizon) {
|
|
444
|
+
return {
|
|
445
|
+
state: 'COLD_BLOAT',
|
|
446
|
+
domState: 'cold-bloat',
|
|
447
|
+
label: 'Reclaimable Cold Bloat',
|
|
448
|
+
colorHex: '#f59e0b'
|
|
449
|
+
};
|
|
450
|
+
}
|
|
451
|
+
|
|
452
|
+
return {
|
|
453
|
+
state: 'CACHED_WARM',
|
|
454
|
+
domState: 'cached-warm',
|
|
455
|
+
label: 'Cached History \u2014 95% Discounted',
|
|
456
|
+
colorHex: '#8b5cf6'
|
|
457
|
+
};
|
|
458
|
+
}
|
|
459
|
+
|
|
460
|
+
/**
|
|
461
|
+
* Computes Dual-Watermark + Hard Ceiling visual markers for the context bar.
|
|
462
|
+
*/
|
|
463
|
+
export function computeWatermarks(maxTokens = null, safeLimit = 179000, modelId = 'default') {
|
|
464
|
+
const dynamicDefault = resolveModelCeiling(modelId, null, { useLegacyDefault: false });
|
|
465
|
+
const denom = Math.max(1, Number(maxTokens) || dynamicDefault);
|
|
466
|
+
const cascadeTokens = SESSION_RISK_THRESHOLDS.CASCADE_SYNC_WATERMARK_TOKENS;
|
|
467
|
+
const attentionHorizonTokens = Math.round(denom * 0.70);
|
|
468
|
+
return {
|
|
469
|
+
cascadeSync: {
|
|
470
|
+
tokens: cascadeTokens,
|
|
471
|
+
pct: parseFloat(Math.min(100, (cascadeTokens / denom) * 100).toFixed(1)),
|
|
472
|
+
label: 'Cascade Sync Armed',
|
|
473
|
+
tooltip: WATERMARK_TOOLTIPS.CASCADE_SYNC_ARMED
|
|
474
|
+
},
|
|
475
|
+
attentionHorizon: {
|
|
476
|
+
tokens: attentionHorizonTokens,
|
|
477
|
+
safeLimitTokens: safeLimit,
|
|
478
|
+
pct: parseFloat(Math.min(100, (attentionHorizonTokens / denom) * 100).toFixed(1)),
|
|
479
|
+
label: 'Attention Horizon (Safe Limit)',
|
|
480
|
+
tooltip: WATERMARK_TOOLTIPS.ATTENTION_HORIZON
|
|
481
|
+
},
|
|
482
|
+
hardCeiling: {
|
|
483
|
+
tokens: denom,
|
|
484
|
+
pct: 100,
|
|
485
|
+
label: `${Math.round(denom / 1000)}k Hard Assembly Limit`,
|
|
486
|
+
source: 'cortex/utils.GetCheckpointConfig',
|
|
487
|
+
tooltip: WATERMARK_TOOLTIPS.CORTEX_HARD_CLAMP
|
|
488
|
+
}
|
|
489
|
+
};
|
|
490
|
+
}
|
|
491
|
+
|
|
492
|
+
const ANCHOR_FILE_TARGET_RE = /(^|[\\/])(rules[\\/]|task\.md$|implementation_plan\.md$|agents\.md$|gemini\.md$)/i;
|
|
493
|
+
|
|
494
|
+
function isPairedToolResultStep(step = {}, prev = null) {
|
|
495
|
+
if (!step || !prev) return false;
|
|
496
|
+
const prevCalls = Array.isArray(prev.toolCalls)
|
|
497
|
+
? prev.toolCalls
|
|
498
|
+
: (Array.isArray(prev.tool_calls) ? prev.tool_calls : []);
|
|
499
|
+
if (prevCalls.length === 0) return false;
|
|
500
|
+
const curCalls = Array.isArray(step.toolCalls)
|
|
501
|
+
? step.toolCalls
|
|
502
|
+
: (Array.isArray(step.tool_calls) ? step.tool_calls : []);
|
|
503
|
+
if (curCalls.length > 0) return false;
|
|
504
|
+
const curType = String(step.type || '').toUpperCase();
|
|
505
|
+
const curSource = String(step.source || '').toUpperCase();
|
|
506
|
+
if (
|
|
507
|
+
curType === 'USER_INPUT' ||
|
|
508
|
+
curSource === 'USER_EXPLICIT' ||
|
|
509
|
+
curType === 'SYSTEM_PROMPT' ||
|
|
510
|
+
isCompactionCheckpointStep(step)
|
|
511
|
+
) {
|
|
512
|
+
return false;
|
|
513
|
+
}
|
|
514
|
+
const prevType = String(prev.type || '').toUpperCase();
|
|
515
|
+
if (
|
|
516
|
+
prevType === 'PLANNER_RESPONSE' &&
|
|
517
|
+
(curType === 'GENERIC' || curType === 'TOOL_RESULT' || curSource === 'TOOL' || curSource === 'MODEL')
|
|
518
|
+
) {
|
|
519
|
+
return true;
|
|
520
|
+
}
|
|
521
|
+
if (curType === 'TOOL_RESULT' || curSource === 'TOOL') return true;
|
|
522
|
+
return false;
|
|
523
|
+
}
|
|
524
|
+
|
|
525
|
+
function getEffectiveStepCalls(steps = [], idx = 0) {
|
|
526
|
+
const step = steps[idx] || {};
|
|
527
|
+
const ownCalls = Array.isArray(step.toolCalls)
|
|
528
|
+
? step.toolCalls
|
|
529
|
+
: (Array.isArray(step.tool_calls) ? step.tool_calls : []);
|
|
530
|
+
if (ownCalls.length > 0) return { calls: ownCalls, isPairedResult: false };
|
|
531
|
+
if (idx > 0 && isPairedToolResultStep(step, steps[idx - 1])) {
|
|
532
|
+
const prevCalls = Array.isArray(steps[idx - 1].toolCalls)
|
|
533
|
+
? steps[idx - 1].toolCalls
|
|
534
|
+
: (Array.isArray(steps[idx - 1].tool_calls) ? steps[idx - 1].tool_calls : []);
|
|
535
|
+
return { calls: prevCalls, isPairedResult: true };
|
|
536
|
+
}
|
|
537
|
+
return { calls: [], isPairedResult: false };
|
|
538
|
+
}
|
|
539
|
+
|
|
540
|
+
/**
|
|
541
|
+
* Classifies an array of parsed steps into a full 40-cell HorizonStatePayload
|
|
542
|
+
*/
|
|
543
|
+
export function classifyHorizon(rawSteps, options = {}) {
|
|
544
|
+
const {
|
|
545
|
+
sessionId = 'unknown',
|
|
546
|
+
storeSource = 'antigravity',
|
|
547
|
+
logTierUsed = 1,
|
|
548
|
+
logFilePath = '',
|
|
549
|
+
canonicalWorkspace = '',
|
|
550
|
+
projectId = '',
|
|
551
|
+
kiBleedMap = new Map(),
|
|
552
|
+
modelId = 'gemini-3.8-flash',
|
|
553
|
+
stdinContextWindow = null,
|
|
554
|
+
stdinQuota = null,
|
|
555
|
+
maxTokensOverride = null,
|
|
556
|
+
useNativeCeiling = false,
|
|
557
|
+
cacheDir = null,
|
|
558
|
+
safeLimitTokens = undefined,
|
|
559
|
+
reminderAtPct = 85
|
|
560
|
+
} = options;
|
|
561
|
+
|
|
562
|
+
let lastCheckpointIdx = -1;
|
|
563
|
+
for (let i = rawSteps.length - 1; i >= 0; i--) {
|
|
564
|
+
if (rawSteps[i] && isCompactionCheckpointStep(rawSteps[i])) {
|
|
565
|
+
lastCheckpointIdx = i;
|
|
566
|
+
break;
|
|
567
|
+
}
|
|
568
|
+
}
|
|
569
|
+
const steps = lastCheckpointIdx >= 0 ? rawSteps.slice(lastCheckpointIdx) : rawSteps;
|
|
570
|
+
const fullReReadEval = evaluateSmartFileReReads(rawSteps);
|
|
571
|
+
const smartReReads = lastCheckpointIdx >= 0 ? evaluateSmartFileReReads(steps) : fullReReadEval;
|
|
572
|
+
|
|
573
|
+
const activeConfig = options.config || loadFlightcheckConfig();
|
|
574
|
+
const cliSettings = options.cliSettings || (
|
|
575
|
+
options.cliSettingsPath || storeSource === 'antigravity-cli' || String(logFilePath).includes('antigravity-cli')
|
|
576
|
+
? loadCliSurfaceSettings(options.cliSettingsPath)
|
|
577
|
+
: null
|
|
578
|
+
);
|
|
579
|
+
const ceilingDetails = resolveModelCeilingDetailed(modelId, stdinContextWindow, {
|
|
580
|
+
useLegacyDefault: !useNativeCeiling,
|
|
581
|
+
config: activeConfig,
|
|
582
|
+
cliSettings
|
|
583
|
+
});
|
|
584
|
+
const resolvedMaxTokens = Number(maxTokensOverride) >= 20000
|
|
585
|
+
? Number(maxTokensOverride)
|
|
586
|
+
: ceilingDetails.ceilingTokens;
|
|
587
|
+
|
|
588
|
+
const parsedEffort = extractEffortTimeline(steps, { maxTokens: resolvedMaxTokens });
|
|
589
|
+
const rawEffortProfile = options.activeEffortProfile
|
|
590
|
+
? { ...options.activeEffortProfile }
|
|
591
|
+
: (options.turnMetadata ? resolveEffortProfile(options.turnMetadata) : parsedEffort.activeEffortProfile);
|
|
592
|
+
const activeEffortProfile = scaleEffortProfileForCeiling(rawEffortProfile, resolvedMaxTokens);
|
|
593
|
+
const rawTransitions = Array.isArray(options.effortTransitions)
|
|
594
|
+
? options.effortTransitions
|
|
595
|
+
: parsedEffort.effortHistory;
|
|
596
|
+
|
|
597
|
+
const defaultSafeLimit = activeEffortProfile?.safeLimit || HORIZON_WINDOW.AMPUTATION_THRESHOLD_TOKENS;
|
|
598
|
+
const safeLimit = Number(safeLimitTokens) > 0 ? Number(safeLimitTokens) : defaultSafeLimit;
|
|
599
|
+
if (activeEffortProfile && activeEffortProfile.safeLimit !== safeLimit) {
|
|
600
|
+
activeEffortProfile.safeLimit = safeLimit;
|
|
601
|
+
if (activeEffortProfile.tier === 'STANDARD') {
|
|
602
|
+
activeEffortProfile.limitReason = `${Math.round(safeLimit / 1000)}k recall ceiling`;
|
|
603
|
+
}
|
|
604
|
+
}
|
|
605
|
+
const reminderAt = Math.round(safeLimit * (Number(reminderAtPct) > 0 ? Number(reminderAtPct) : 85) / 100);
|
|
606
|
+
|
|
607
|
+
// Track file operations for stale duplicate detection & semantic reference pinning
|
|
608
|
+
const latestFileTouchStep = new Map();
|
|
609
|
+
const fileTouchCounts = new Map();
|
|
610
|
+
const activeBackgroundDaemons = [];
|
|
611
|
+
const activeWindowStart = Math.max(0, steps.length - HORIZON_WINDOW.ACTIVE_SET_STEP_WINDOW);
|
|
612
|
+
const activeReferenceTokens = new Set();
|
|
613
|
+
|
|
614
|
+
for (let idx = 0; idx < steps.length; idx++) {
|
|
615
|
+
const step = steps[idx];
|
|
616
|
+
const calls = step.toolCalls || [];
|
|
617
|
+
if (idx >= activeWindowStart) {
|
|
618
|
+
const recentText = `${step.content || ''} ${JSON.stringify(calls)}`.toLowerCase();
|
|
619
|
+
const identMatches = recentText.match(/[a-z0-9_.-]{4,64}/g) || [];
|
|
620
|
+
for (const tok of identMatches) activeReferenceTokens.add(tok);
|
|
621
|
+
}
|
|
622
|
+
for (const call of calls) {
|
|
623
|
+
const name = (call.name || '').toLowerCase();
|
|
624
|
+
const args = call.args || {};
|
|
625
|
+
const targetFile = args.Path || args.path || args.Target || args.target;
|
|
626
|
+
if (targetFile && typeof targetFile === 'string' && !isInternalTelemetryPath(targetFile)) {
|
|
627
|
+
const canon = canonicalizePath(targetFile);
|
|
628
|
+
latestFileTouchStep.set(canon, idx);
|
|
629
|
+
fileTouchCounts.set(canon, (fileTouchCounts.get(canon) || 0) + 1);
|
|
630
|
+
}
|
|
631
|
+
|
|
632
|
+
if (name === 'run_command') {
|
|
633
|
+
if (args.IsDaemon === true) {
|
|
634
|
+
activeBackgroundDaemons.push({
|
|
635
|
+
taskId: args.TaskId || `step-${idx}`,
|
|
636
|
+
command: args.CommandLine || '',
|
|
637
|
+
stepIndex: idx
|
|
638
|
+
});
|
|
639
|
+
}
|
|
640
|
+
} else if (name === 'manage_task') {
|
|
641
|
+
if (args.Action === 'kill' && args.TaskId) {
|
|
642
|
+
const dIdx = activeBackgroundDaemons.findIndex(d => d.taskId === args.TaskId);
|
|
643
|
+
if (dIdx !== -1) activeBackgroundDaemons.splice(dIdx, 1);
|
|
644
|
+
}
|
|
645
|
+
}
|
|
646
|
+
}
|
|
647
|
+
}
|
|
648
|
+
|
|
649
|
+
// Classify each step into categories & tokens
|
|
650
|
+
const totalTurns = steps.length;
|
|
651
|
+
const userTurns = steps.filter(x => x && (x.source === 'USER_EXPLICIT' || x.type === 'USER_INPUT' || x.role === 'user'));
|
|
652
|
+
const userTurnCount = userTurns.length > 0 ? userTurns.length : (options.sidecar?.sessionMeta?.turnCount || totalTurns);
|
|
653
|
+
let lastUserTurnStepIdx = -1;
|
|
654
|
+
for (let k = steps.length - 1; k >= 0; k--) {
|
|
655
|
+
const sx = steps[k];
|
|
656
|
+
if (sx && (sx.source === 'USER_EXPLICIT' || sx.type === 'USER_INPUT' || sx.role === 'user')) {
|
|
657
|
+
lastUserTurnStepIdx = k;
|
|
658
|
+
break;
|
|
659
|
+
}
|
|
660
|
+
}
|
|
661
|
+
const totalSteps = steps.length;
|
|
662
|
+
let totalActiveTokens = 0;
|
|
663
|
+
const classifiedSteps = [];
|
|
664
|
+
|
|
665
|
+
const categoryTotals = {
|
|
666
|
+
[CATEGORIES.ANCHOR]: 0,
|
|
667
|
+
[CATEGORIES.MEMORY_KI]: 0,
|
|
668
|
+
[CATEGORIES.FOREIGN_BLEED]: 0,
|
|
669
|
+
[CATEGORIES.STALE_DUPLICATE]: 0,
|
|
670
|
+
[CATEGORIES.DEAD_ERROR]: 0,
|
|
671
|
+
[CATEGORIES.ACTIVE_WORKING_SET]: 0,
|
|
672
|
+
[CATEGORIES.FREE_HEADROOM]: 0
|
|
673
|
+
};
|
|
674
|
+
|
|
675
|
+
const offenderMap = new Map();
|
|
676
|
+
let rawLiveTokens = 0;
|
|
677
|
+
|
|
678
|
+
for (let idx = 0; idx < steps.length; idx++) {
|
|
679
|
+
const step = steps[idx];
|
|
680
|
+
const estFromLength = Number(step.untruncatedLength) > 0 ? Math.round(step.untruncatedLength / 4) : 0;
|
|
681
|
+
let tokens = step.inputTokens > 0 && step.outputTokens > 0
|
|
682
|
+
? Math.max(step.outputTokens, estFromLength)
|
|
683
|
+
: (step.outputTokens || estFromLength || 1000);
|
|
684
|
+
|
|
685
|
+
if (step.stepIndex === 0 && step.inputTokens > 0) {
|
|
686
|
+
tokens = step.inputTokens;
|
|
687
|
+
}
|
|
688
|
+
|
|
689
|
+
let category = CATEGORIES.ACTIVE_WORKING_SET;
|
|
690
|
+
let target = '';
|
|
691
|
+
|
|
692
|
+
const contentStr = String(step.content || '');
|
|
693
|
+
const { calls, isPairedResult } = getEffectiveStepCalls(steps, idx);
|
|
694
|
+
const isReadOnlyFileCall = calls.length > 0 && calls.every(c => /^(view_file|read_file|view_file_outline|view_code_item)$/i.test(String(c.name || c.tool || '')));
|
|
695
|
+
const callFileTargets = calls
|
|
696
|
+
.map(c => {
|
|
697
|
+
const a = c?.args || c?.parameters || c?.Arguments || {};
|
|
698
|
+
return a.Path || a.path || a.TargetFile || a.Target || a.target || a.AbsolutePath || '';
|
|
699
|
+
})
|
|
700
|
+
.filter(Boolean);
|
|
701
|
+
const hasExplicitNonAnchorTarget = callFileTargets.length > 0 &&
|
|
702
|
+
callFileTargets.every(t => !ANCHOR_FILE_TARGET_RE.test(String(t)));
|
|
703
|
+
const isError = step.status === 'ERROR' ||
|
|
704
|
+
(typeof step.exitCode === 'number' && step.exitCode !== 0) ||
|
|
705
|
+
(!isReadOnlyFileCall && contentStr.includes('Traceback (most recent call last)'));
|
|
706
|
+
|
|
707
|
+
const isBackgroundTaskEvent = Boolean(
|
|
708
|
+
(step.type === 'SYSTEM_MESSAGE' || String(step.type).toLowerCase() === 'system_message') &&
|
|
709
|
+
/Task id ["'][^"']+["'] finished/i.test(contentStr)
|
|
710
|
+
);
|
|
711
|
+
|
|
712
|
+
// 1. Anchor detection
|
|
713
|
+
if (
|
|
714
|
+
!isBackgroundTaskEvent && (
|
|
715
|
+
step.stepIndex === 0 ||
|
|
716
|
+
isCompactionCheckpointStep(step) ||
|
|
717
|
+
step.type === 'SYSTEM_PROMPT' ||
|
|
718
|
+
(!hasExplicitNonAnchorTarget && (
|
|
719
|
+
contentStr.includes('rules/') ||
|
|
720
|
+
contentStr.includes('task.md') ||
|
|
721
|
+
contentStr.includes('implementation_plan.md')
|
|
722
|
+
))
|
|
723
|
+
)
|
|
724
|
+
) {
|
|
725
|
+
category = CATEGORIES.ANCHOR;
|
|
726
|
+
target = 'System & Project Anchors';
|
|
727
|
+
}
|
|
728
|
+
// 2. Knowledge Memory & Bleed detection
|
|
729
|
+
else if (
|
|
730
|
+
contentStr.includes('knowledge://') ||
|
|
731
|
+
calls.some(c => (c.name || c.tool || '').includes('knowledge') || (c.args?.Uri || '').includes('knowledge'))
|
|
732
|
+
) {
|
|
733
|
+
let isBleed = false;
|
|
734
|
+
for (const [kiName, info] of kiBleedMap.entries()) {
|
|
735
|
+
if (contentStr.includes(kiName) || calls.some(c => JSON.stringify(c).includes(kiName))) {
|
|
736
|
+
if (info.isBleed) isBleed = true;
|
|
737
|
+
}
|
|
738
|
+
}
|
|
739
|
+
category = isBleed ? CATEGORIES.FOREIGN_BLEED : CATEGORIES.MEMORY_KI;
|
|
740
|
+
target = isBleed ? 'Foreign Bleed Knowledge' : 'Project Knowledge Item';
|
|
741
|
+
}
|
|
742
|
+
// 3. Dead Error detection
|
|
743
|
+
else if (isError) {
|
|
744
|
+
category = CATEGORIES.DEAD_ERROR;
|
|
745
|
+
const cmdCall = calls.find(c => (c.name || c.tool || '').toLowerCase() === 'run_command');
|
|
746
|
+
target = cmdCall?.args?.CommandLine ? `Command: ${cmdCall.args.CommandLine}` : 'Resolved Stack Trace';
|
|
747
|
+
const off = offenderMap.get(target) || { category, target, occurrences: 0, wastedTokens: 0, stepIndices: [] };
|
|
748
|
+
off.occurrences += 1;
|
|
749
|
+
off.wastedTokens += tokens;
|
|
750
|
+
off.stepIndices.push(idx);
|
|
751
|
+
offenderMap.set(target, off);
|
|
752
|
+
}
|
|
753
|
+
// 4. Smart File Re-Read Classifier & Semantic Reference Pinning
|
|
754
|
+
else {
|
|
755
|
+
let isStale = false;
|
|
756
|
+
let isPairedWasteResult = false;
|
|
757
|
+
let stepFileBasename = '';
|
|
758
|
+
for (const call of calls) {
|
|
759
|
+
const args = call.args || call.parameters || call.Arguments || {};
|
|
760
|
+
const targetFile = args.Path || args.path || args.Target || args.target || args.TargetFile || args.AbsolutePath;
|
|
761
|
+
if (targetFile && !isInternalTelemetryPath(targetFile)) {
|
|
762
|
+
stepFileBasename = path.basename(String(targetFile)).toLowerCase();
|
|
763
|
+
break;
|
|
764
|
+
}
|
|
765
|
+
}
|
|
766
|
+
if (smartReReads.wasteTargetByStep.has(idx)) {
|
|
767
|
+
isStale = true;
|
|
768
|
+
target = smartReReads.wasteTargetByStep.get(idx);
|
|
769
|
+
} else if (isPairedResult && smartReReads.wasteTargetByStep.has(idx - 1)) {
|
|
770
|
+
isStale = true;
|
|
771
|
+
isPairedWasteResult = true;
|
|
772
|
+
target = smartReReads.wasteTargetByStep.get(idx - 1);
|
|
773
|
+
}
|
|
774
|
+
|
|
775
|
+
let semanticallyPinned = false;
|
|
776
|
+
const isFromEarlierUserTurn = userTurns.length === 0 ? true : idx < lastUserTurnStepIdx;
|
|
777
|
+
if (!isStale && isFromEarlierUserTurn && idx < totalTurns - HORIZON_WINDOW.STALE_STEP_THRESHOLD) {
|
|
778
|
+
// Check if this older turn defines a file or schema/type symbol still referenced in the active window
|
|
779
|
+
const declMatch = contentStr.match(/\b(?:interface|type|class|struct|CREATE\s+TABLE|schema)\s+([A-Za-z0-9_]{4,64})/i);
|
|
780
|
+
const declaredSymbol = declMatch ? declMatch[1].toLowerCase() : '';
|
|
781
|
+
if (
|
|
782
|
+
(stepFileBasename && activeReferenceTokens.has(stepFileBasename)) ||
|
|
783
|
+
(declaredSymbol && activeReferenceTokens.has(declaredSymbol))
|
|
784
|
+
) {
|
|
785
|
+
semanticallyPinned = true;
|
|
786
|
+
isStale = false;
|
|
787
|
+
target = stepFileBasename ? `Pinned Reference (${stepFileBasename})` : `Pinned Schema (${declaredSymbol})`;
|
|
788
|
+
} else {
|
|
789
|
+
isStale = true;
|
|
790
|
+
target = 'Older chat history (>25 turns ago)';
|
|
791
|
+
}
|
|
792
|
+
}
|
|
793
|
+
|
|
794
|
+
if (isStale) {
|
|
795
|
+
category = CATEGORIES.STALE_DUPLICATE;
|
|
796
|
+
const off = offenderMap.get(target || 'Stale Read') || { category, target: target || 'Stale Read', occurrences: 0, wastedTokens: 0, stepIndices: [] };
|
|
797
|
+
if (!isPairedWasteResult) {
|
|
798
|
+
off.occurrences += 1;
|
|
799
|
+
} else if (off.occurrences === 0) {
|
|
800
|
+
off.occurrences = 1;
|
|
801
|
+
}
|
|
802
|
+
off.wastedTokens += tokens;
|
|
803
|
+
off.stepIndices.push(idx);
|
|
804
|
+
offenderMap.set(target || 'Stale Read', off);
|
|
805
|
+
} else {
|
|
806
|
+
category = CATEGORIES.ACTIVE_WORKING_SET;
|
|
807
|
+
if (!semanticallyPinned) target = 'Active Coding & Context';
|
|
808
|
+
}
|
|
809
|
+
}
|
|
810
|
+
|
|
811
|
+
categoryTotals[category] += tokens;
|
|
812
|
+
totalActiveTokens += tokens;
|
|
813
|
+
// Live session work = pinned task/plan state + recent active turns; the rest of the useful set is workspace baseline
|
|
814
|
+
const isRuleAnchor = step.stepIndex === 0 || step.type === 'SYSTEM_PROMPT' || contentStr.includes('rules/');
|
|
815
|
+
if (category === CATEGORIES.ACTIVE_WORKING_SET || (category === CATEGORIES.ANCHOR && !isRuleAnchor)) rawLiveTokens += tokens;
|
|
816
|
+
|
|
817
|
+
classifiedSteps.push({
|
|
818
|
+
stepIndex: idx,
|
|
819
|
+
category,
|
|
820
|
+
tokens,
|
|
821
|
+
target,
|
|
822
|
+
semanticallyPinned: target.startsWith('Pinned '),
|
|
823
|
+
rawContent: contentStr
|
|
824
|
+
});
|
|
825
|
+
}
|
|
826
|
+
|
|
827
|
+
const rawTotalTokens = Math.max(1, totalActiveTokens);
|
|
828
|
+
// Reconcile total active tokens with stdin context window if provided
|
|
829
|
+
if (stdinContextWindow && stdinContextWindow.total_input_tokens > 0) {
|
|
830
|
+
const scale = stdinContextWindow.total_input_tokens / Math.max(1, totalActiveTokens);
|
|
831
|
+
totalActiveTokens = stdinContextWindow.total_input_tokens;
|
|
832
|
+
for (const cat of Object.keys(categoryTotals)) {
|
|
833
|
+
categoryTotals[cat] = 0;
|
|
834
|
+
}
|
|
835
|
+
for (const s of classifiedSteps) {
|
|
836
|
+
s.tokens = Math.round(s.tokens * scale);
|
|
837
|
+
categoryTotals[s.category] = (categoryTotals[s.category] || 0) + s.tokens;
|
|
838
|
+
}
|
|
839
|
+
const scaledSum = Object.values(categoryTotals).reduce((acc, v) => acc + v, 0);
|
|
840
|
+
const residual = totalActiveTokens - scaledSum;
|
|
841
|
+
if (residual !== 0) {
|
|
842
|
+
if (classifiedSteps.length > 0) {
|
|
843
|
+
let maxStep = classifiedSteps[0];
|
|
844
|
+
for (const s of classifiedSteps) {
|
|
845
|
+
if (s.tokens > maxStep.tokens) maxStep = s;
|
|
846
|
+
}
|
|
847
|
+
maxStep.tokens = Math.max(0, maxStep.tokens + residual);
|
|
848
|
+
categoryTotals[maxStep.category] = Math.max(0, (categoryTotals[maxStep.category] || 0) + residual);
|
|
849
|
+
} else {
|
|
850
|
+
categoryTotals[CATEGORIES.ANCHOR] = Math.max(0, (categoryTotals[CATEGORIES.ANCHOR] || 0) + residual);
|
|
851
|
+
}
|
|
852
|
+
}
|
|
853
|
+
for (const off of offenderMap.values()) {
|
|
854
|
+
off.wastedTokens = off.stepIndices.reduce((sum, sIdx) => sum + (classifiedSteps[sIdx]?.tokens || 0), 0);
|
|
855
|
+
}
|
|
856
|
+
}
|
|
857
|
+
|
|
858
|
+
// If session crosses legacy default ceiling, dynamically promote ceiling to native model ceiling (256k / 1M / 1.048M) so 40 cells never overflow
|
|
859
|
+
const nativeModelCeiling = resolveModelCeiling(modelId, null, {
|
|
860
|
+
useLegacyDefault: false,
|
|
861
|
+
config: activeConfig,
|
|
862
|
+
cliSettings
|
|
863
|
+
});
|
|
864
|
+
const effectiveMaxTokens = (totalActiveTokens > resolvedMaxTokens && resolvedMaxTokens === 200000)
|
|
865
|
+
? (totalActiveTokens > 256000 ? Math.max(1000000, nativeModelCeiling) : 256000)
|
|
866
|
+
: (totalActiveTokens > resolvedMaxTokens ? Math.max(resolvedMaxTokens, nativeModelCeiling) : resolvedMaxTokens);
|
|
867
|
+
const effectiveCellSize = Math.max(
|
|
868
|
+
Math.round(effectiveMaxTokens / HORIZON_WINDOW.TOTAL_CELLS),
|
|
869
|
+
Math.ceil(totalActiveTokens / HORIZON_WINDOW.TOTAL_CELLS) || HORIZON_WINDOW.CELL_SIZE_TOKENS
|
|
870
|
+
);
|
|
871
|
+
|
|
872
|
+
const freeHeadroom = Math.max(0, effectiveMaxTokens - totalActiveTokens);
|
|
873
|
+
categoryTotals[CATEGORIES.FREE_HEADROOM] = freeHeadroom;
|
|
874
|
+
|
|
875
|
+
// Build the 40 cells chronologically (Turn 0 on left -> Current Turn on right)
|
|
876
|
+
const cells = [];
|
|
877
|
+
const activeCellsCount = Math.min(HORIZON_WINDOW.TOTAL_CELLS, Math.ceil(totalActiveTokens / effectiveCellSize));
|
|
878
|
+
|
|
879
|
+
let currentStepIdx = 0;
|
|
880
|
+
let stepTokenOffset = 0;
|
|
881
|
+
|
|
882
|
+
for (let cellIdx = 0; cellIdx < HORIZON_WINDOW.TOTAL_CELLS; cellIdx++) {
|
|
883
|
+
const cellStartToken = cellIdx * effectiveCellSize;
|
|
884
|
+
const cellEndToken = (cellIdx + 1) * effectiveCellSize;
|
|
885
|
+
|
|
886
|
+
if (cellStartToken >= totalActiveTokens) {
|
|
887
|
+
cells.push({
|
|
888
|
+
index: cellIdx,
|
|
889
|
+
tokenRange: [cellStartToken, cellEndToken],
|
|
890
|
+
turnRange: [-1, -1],
|
|
891
|
+
dominantCategory: CATEGORIES.FREE_HEADROOM,
|
|
892
|
+
isAmputationZone: false,
|
|
893
|
+
isCrisisCell: false,
|
|
894
|
+
attentionWeight: 0.20,
|
|
895
|
+
attentionZone: 'FREE_HEADROOM',
|
|
896
|
+
inAttentionTrough: false,
|
|
897
|
+
isStrandedSignal: false,
|
|
898
|
+
strandedWarning: '',
|
|
899
|
+
turnsDetail: [],
|
|
900
|
+
fractures: [],
|
|
901
|
+
hasFracture: false,
|
|
902
|
+
tokensByCategory: { [CATEGORIES.FREE_HEADROOM]: effectiveCellSize },
|
|
903
|
+
topTarget: 'Free Token Headroom'
|
|
904
|
+
});
|
|
905
|
+
continue;
|
|
906
|
+
}
|
|
907
|
+
|
|
908
|
+
const bucketCategories = {};
|
|
909
|
+
let bucketTokensRemaining = Math.min(effectiveCellSize, totalActiveTokens - cellStartToken);
|
|
910
|
+
let cellTurns = [];
|
|
911
|
+
const cellTurnsDetailMap = new Map();
|
|
912
|
+
let dominantCat = CATEGORIES.ACTIVE_WORKING_SET;
|
|
913
|
+
let maxCatTokens = -1;
|
|
914
|
+
let topTarget = '';
|
|
915
|
+
|
|
916
|
+
while (bucketTokensRemaining > 0 && currentStepIdx < classifiedSteps.length) {
|
|
917
|
+
const step = classifiedSteps[currentStepIdx];
|
|
918
|
+
const rawStep = steps[step.stepIndex] || {};
|
|
919
|
+
const stepRemainingTokens = step.tokens - stepTokenOffset;
|
|
920
|
+
const consume = Math.min(bucketTokensRemaining, stepRemainingTokens);
|
|
921
|
+
|
|
922
|
+
bucketCategories[step.category] = (bucketCategories[step.category] || 0) + consume;
|
|
923
|
+
if (bucketCategories[step.category] > maxCatTokens) {
|
|
924
|
+
maxCatTokens = bucketCategories[step.category];
|
|
925
|
+
dominantCat = step.category;
|
|
926
|
+
topTarget = step.target;
|
|
927
|
+
}
|
|
928
|
+
|
|
929
|
+
cellTurns.push(step.stepIndex);
|
|
930
|
+
if (!cellTurnsDetailMap.has(step.stepIndex)) {
|
|
931
|
+
const { calls: rawCalls } = getEffectiveStepCalls(steps, step.stepIndex);
|
|
932
|
+
const toolCallLabels = rawCalls.map(c => {
|
|
933
|
+
const nm = c.name || c.tool || 'tool';
|
|
934
|
+
const a = c.args || c.parameters || c.Arguments || {};
|
|
935
|
+
const arg = a.Path || a.path || a.CommandLine || a.ServerName || '';
|
|
936
|
+
return arg ? `${nm}(${String(arg).slice(0, 60)})` : nm;
|
|
937
|
+
});
|
|
938
|
+
cellTurnsDetailMap.set(step.stepIndex, {
|
|
939
|
+
stepIndex: step.stepIndex,
|
|
940
|
+
category: step.category,
|
|
941
|
+
tokens: consume,
|
|
942
|
+
target: step.target || 'Turn',
|
|
943
|
+
toolCalls: toolCallLabels
|
|
944
|
+
});
|
|
945
|
+
} else {
|
|
946
|
+
cellTurnsDetailMap.get(step.stepIndex).tokens += consume;
|
|
947
|
+
}
|
|
948
|
+
|
|
949
|
+
bucketTokensRemaining -= consume;
|
|
950
|
+
stepTokenOffset += consume;
|
|
951
|
+
|
|
952
|
+
if (stepTokenOffset >= step.tokens) {
|
|
953
|
+
currentStepIdx++;
|
|
954
|
+
stepTokenOffset = 0;
|
|
955
|
+
}
|
|
956
|
+
}
|
|
957
|
+
|
|
958
|
+
const cellUsedTokens = Object.values(bucketCategories).reduce((s, v) => s + v, 0);
|
|
959
|
+
if (cellUsedTokens < effectiveCellSize) {
|
|
960
|
+
bucketCategories[CATEGORIES.FREE_HEADROOM] = (bucketCategories[CATEGORIES.FREE_HEADROOM] || 0) + (effectiveCellSize - cellUsedTokens);
|
|
961
|
+
}
|
|
962
|
+
|
|
963
|
+
const isAmputationZone = totalActiveTokens > safeLimit && cellIdx < HORIZON_WINDOW.AMPUTATION_CELL_COUNT;
|
|
964
|
+
const parabolic = calculateParabolicAttentionCurve(cellIdx, Math.max(1, activeCellsCount));
|
|
965
|
+
const attentionWeight = parabolic.uShapedWeight;
|
|
966
|
+
const meetsTokenFloor = totalActiveTokens >= 44800 && activeCellsCount >= 7;
|
|
967
|
+
const inTrough = meetsTokenFloor && parabolic.inTrough;
|
|
968
|
+
const hasActiveOrRuleBuffer =
|
|
969
|
+
dominantCat === CATEGORIES.ACTIVE_WORKING_SET ||
|
|
970
|
+
dominantCat === CATEGORIES.ANCHOR ||
|
|
971
|
+
(bucketCategories[CATEGORIES.ACTIVE_WORKING_SET] || 0) > 0 ||
|
|
972
|
+
(bucketCategories[CATEGORIES.ANCHOR] || 0) > 0;
|
|
973
|
+
const isStrandedSignal = inTrough && hasActiveOrRuleBuffer;
|
|
974
|
+
|
|
975
|
+
cells.push({
|
|
976
|
+
index: cellIdx,
|
|
977
|
+
tokenRange: [cellStartToken, cellEndToken],
|
|
978
|
+
turnRange: [cellTurns[0] ?? 0, cellTurns[cellTurns.length - 1] ?? 0],
|
|
979
|
+
dominantCategory: dominantCat,
|
|
980
|
+
isAmputationZone,
|
|
981
|
+
isCrisisCell: false,
|
|
982
|
+
attentionWeight,
|
|
983
|
+
attentionZone: parabolic.zone,
|
|
984
|
+
inAttentionTrough: inTrough,
|
|
985
|
+
parabolicAttention: parabolic,
|
|
986
|
+
isStrandedSignal,
|
|
987
|
+
strandedWarning: isStrandedSignal ? STRANDED_SIGNAL_WARNING_TEXT : '',
|
|
988
|
+
turnsDetail: Array.from(cellTurnsDetailMap.values()),
|
|
989
|
+
fractures: [],
|
|
990
|
+
hasFracture: false,
|
|
991
|
+
tokensByCategory: bucketCategories,
|
|
992
|
+
topTarget
|
|
993
|
+
});
|
|
994
|
+
}
|
|
995
|
+
|
|
996
|
+
// Map effort transitions to their corresponding block indices (0..39)
|
|
997
|
+
const tokensPerCell = Math.max(1, Math.round(effectiveMaxTokens / HORIZON_WINDOW.TOTAL_CELLS));
|
|
998
|
+
const filledCellCount = Math.max(1, Math.min(HORIZON_WINDOW.TOTAL_CELLS, Math.ceil(totalActiveTokens / tokensPerCell)));
|
|
999
|
+
const effortTransitions = rawTransitions.map(tr => {
|
|
1000
|
+
const tIdx = tr.turnIndex ?? tr.stepNumber ?? 0;
|
|
1001
|
+
const stepNum = tr.stepNumber ?? tr.turnIndex ?? 0;
|
|
1002
|
+
let matchedBlock = -1;
|
|
1003
|
+
for (const c of cells) {
|
|
1004
|
+
if (c.turnRange && c.turnRange[0] >= 0 && tIdx >= c.turnRange[0] && tIdx <= c.turnRange[1]) {
|
|
1005
|
+
matchedBlock = c.index;
|
|
1006
|
+
break;
|
|
1007
|
+
}
|
|
1008
|
+
}
|
|
1009
|
+
if (matchedBlock < 0 && typeof tr.blockIndex === 'number' && tr.blockIndex >= 0) {
|
|
1010
|
+
matchedBlock = Math.min(39, tr.blockIndex);
|
|
1011
|
+
}
|
|
1012
|
+
if (matchedBlock < 0) {
|
|
1013
|
+
matchedBlock = Math.min(39, Math.max(0, Math.floor((tIdx / Math.max(1, totalTurns)) * Math.max(1, activeCellsCount))));
|
|
1014
|
+
}
|
|
1015
|
+
if (matchedBlock >= filledCellCount) {
|
|
1016
|
+
matchedBlock = Math.min(39, Math.max(0, filledCellCount - 1));
|
|
1017
|
+
}
|
|
1018
|
+
const enriched = {
|
|
1019
|
+
...tr,
|
|
1020
|
+
turnIndex: tIdx,
|
|
1021
|
+
stepNumber: stepNum,
|
|
1022
|
+
blockIndex: matchedBlock
|
|
1023
|
+
};
|
|
1024
|
+
if (cells[matchedBlock]) {
|
|
1025
|
+
cells[matchedBlock].effortTransitions = cells[matchedBlock].effortTransitions || [];
|
|
1026
|
+
cells[matchedBlock].effortTransitions.push(enriched);
|
|
1027
|
+
}
|
|
1028
|
+
return enriched;
|
|
1029
|
+
});
|
|
1030
|
+
|
|
1031
|
+
// Prefix Amputation Bracket & Crisis evaluation
|
|
1032
|
+
// Truncation Zone is Cells 0..7 (earliest 40k tokens) when total tokens > safe limit (default 140k)
|
|
1033
|
+
const inAmputationZone = totalActiveTokens > safeLimit;
|
|
1034
|
+
|
|
1035
|
+
// Crisis condition specifically requires:
|
|
1036
|
+
// 1. Total tokens nearing 200k limit (> 180,000) OR
|
|
1037
|
+
// 2. Active background daemon in cells 0..7 OR
|
|
1038
|
+
// 3. Uncompleted task/plan checkpoint in cells 0..7
|
|
1039
|
+
const earlySteps = classifiedSteps.filter(s => s.stepIndex <= 7);
|
|
1040
|
+
const uncompletedPlanInZone = earlySteps.some(s => s.rawContent.includes('- [ ]'));
|
|
1041
|
+
const daemonsAtRisk = activeBackgroundDaemons.filter(d => d.stepIndex <= 7);
|
|
1042
|
+
const extremeTokenLimit = totalActiveTokens >= 180000;
|
|
1043
|
+
|
|
1044
|
+
const amputationCrisis = inAmputationZone && (daemonsAtRisk.length > 0 || uncompletedPlanInZone || extremeTokenLimit);
|
|
1045
|
+
|
|
1046
|
+
if (amputationCrisis) {
|
|
1047
|
+
for (let c = 0; c < Math.min(HORIZON_WINDOW.AMPUTATION_CELL_COUNT, cells.length); c++) {
|
|
1048
|
+
cells[c].isCrisisCell = true;
|
|
1049
|
+
}
|
|
1050
|
+
}
|
|
1051
|
+
|
|
1052
|
+
// Metrics computation
|
|
1053
|
+
const signalTokens = categoryTotals[CATEGORIES.ANCHOR] + categoryTotals[CATEGORIES.ACTIVE_WORKING_SET] + (categoryTotals[CATEGORIES.MEMORY_KI] || 0);
|
|
1054
|
+
const signalPurityPct = Math.round((signalTokens / Math.max(1, totalActiveTokens)) * 100);
|
|
1055
|
+
|
|
1056
|
+
const pricePerM = resolvePricePerM(modelId, activeConfig);
|
|
1057
|
+
const sludgeTokens = categoryTotals[CATEGORIES.STALE_DUPLICATE] + categoryTotals[CATEGORIES.DEAD_ERROR] + categoryTotals[CATEGORIES.FOREIGN_BLEED];
|
|
1058
|
+
const sludgeTaxPerTurnUsd = parseFloat(((sludgeTokens / 1000000) * pricePerM).toFixed(4));
|
|
1059
|
+
const totalTurnCostUsd = parseFloat(((totalActiveTokens / 1000000) * pricePerM).toFixed(4));
|
|
1060
|
+
|
|
1061
|
+
// Health band (gated on compaction relevance so lean <50k sessions do not false-alarm)
|
|
1062
|
+
const compactionRelevant = isCompactionRelevant({
|
|
1063
|
+
totalActiveTokens,
|
|
1064
|
+
sludgeTokens,
|
|
1065
|
+
safeHorizonTokens: safeLimit
|
|
1066
|
+
});
|
|
1067
|
+
let healthBand = 'OPTIMAL_FOCUS';
|
|
1068
|
+
if (amputationCrisis) healthBand = 'AMPUTATION_CRISIS';
|
|
1069
|
+
else if (compactionRelevant && signalPurityPct < 40) healthBand = 'CRITICAL_SLUDGE';
|
|
1070
|
+
else if (compactionRelevant && signalPurityPct < 75) healthBand = 'VISIBLE_CLUTTER';
|
|
1071
|
+
|
|
1072
|
+
// Format Top Offenders Ledger
|
|
1073
|
+
const offenders = Array.from(offenderMap.values())
|
|
1074
|
+
.sort((a, b) => b.wastedTokens - a.wastedTokens)
|
|
1075
|
+
.slice(0, 5)
|
|
1076
|
+
.map((off, rank) => {
|
|
1077
|
+
const avgStep = off.stepIndices.reduce((acc, v) => acc + v, 0) / (off.stepIndices.length || 1);
|
|
1078
|
+
const estCell = Math.min(39, Math.floor((avgStep / Math.max(1, totalTurns)) * activeCellsCount));
|
|
1079
|
+
const recallPct = Math.round(calculateAttentionWeight(estCell, activeCellsCount) * 100);
|
|
1080
|
+
const costUsd = parseFloat(((off.wastedTokens / 1000000) * pricePerM).toFixed(4));
|
|
1081
|
+
|
|
1082
|
+
const wastedK = Math.max(0.1, parseFloat((off.wastedTokens / 1000).toFixed(1)));
|
|
1083
|
+
const supersededSteps = off.stepIndices.length > 1 ? off.stepIndices.slice(0, -1) : off.stepIndices;
|
|
1084
|
+
const stepListStr = supersededSteps.slice(0, 5).join(', ') + (supersededSteps.length > 5 ? '...' : '');
|
|
1085
|
+
let remediation = `Deduplicate file reads via /compact`;
|
|
1086
|
+
if (off.category === CATEGORIES.DEAD_ERROR) {
|
|
1087
|
+
remediation = `Collapse ${off.occurrences} resolved error trace(s) at step(s) [${off.stepIndices.slice(0, 5).join(', ')}] (~${wastedK}k tok) via Surgical Pruner or /compact`;
|
|
1088
|
+
} else if (off.target === 'Older chat history (>25 turns ago)') {
|
|
1089
|
+
remediation = `Compress ${off.occurrences} stale turns at steps [${stepListStr}] (~${wastedK}k tok) via /compact`;
|
|
1090
|
+
} else if (isIgnorablePath(off.target)) {
|
|
1091
|
+
remediation = `echo "${off.target}" >> .antigravityignore && prune ${ Math.max(1, off.occurrences - 1)} read(s) at step(s) [${stepListStr}] (~${wastedK}k tok)`;
|
|
1092
|
+
} else {
|
|
1093
|
+
remediation = `Fold ${Math.max(1, off.occurrences - 1)} superseded read(s) of ${off.target} at step(s) [${stepListStr}] (~${wastedK}k tok) via Surgical Pruner or use read_file { Path: "${off.target}", StartLine: 1, EndLine: 200 }`;
|
|
1094
|
+
}
|
|
1095
|
+
|
|
1096
|
+
return {
|
|
1097
|
+
rank: rank + 1,
|
|
1098
|
+
target: off.target,
|
|
1099
|
+
category: off.category,
|
|
1100
|
+
occurrences: off.occurrences,
|
|
1101
|
+
stepIndices: off.stepIndices,
|
|
1102
|
+
wastedTokens: off.wastedTokens,
|
|
1103
|
+
sludgeCostPerTurnUsd: costUsd,
|
|
1104
|
+
attentionRecallPct: recallPct,
|
|
1105
|
+
remediation
|
|
1106
|
+
};
|
|
1107
|
+
});
|
|
1108
|
+
|
|
1109
|
+
// Plain-Language Token-Based Diagnostics (Zero $ references)
|
|
1110
|
+
const reclaimK = Math.round(sludgeTokens / 1000);
|
|
1111
|
+
let whatsHappening = '';
|
|
1112
|
+
let theSludgeTax = '';
|
|
1113
|
+
let actionPlan = '';
|
|
1114
|
+
let recommendedCommand = 'Ready';
|
|
1115
|
+
|
|
1116
|
+
if (amputationCrisis) {
|
|
1117
|
+
whatsHappening = `Prefix truncation alert! Total memory (> ${Math.round(reminderAt / 1000)}k tokens) or early task checkpoints are inside the ${Math.round(safeLimit / 1000)}k+ truncation zone.`;
|
|
1118
|
+
theSludgeTax = `${reclaimK}k reclaimable noise tokens (${100 - signalPurityPct}% of active context) are pushing your earliest rules toward truncation.`;
|
|
1119
|
+
actionPlan = `Save progress to task.md and start a fresh chat or run /clear now.`;
|
|
1120
|
+
recommendedCommand = '/clear';
|
|
1121
|
+
} else if (inAmputationZone || (compactionRelevant && signalPurityPct < 40)) {
|
|
1122
|
+
whatsHappening = `High context dilution: ${(100 - signalPurityPct)}% of active memory (${reclaimK}k tokens) consists of outdated turns and repeated file reads.`;
|
|
1123
|
+
theSludgeTax = `${reclaimK}k tokens can be reclaimed immediately via /compact. Middle-window recall has dropped to ~24%.`;
|
|
1124
|
+
actionPlan = `Run /compact to compress older history and drop duplicate file snapshots while keeping active rules intact.`;
|
|
1125
|
+
recommendedCommand = '/compact';
|
|
1126
|
+
} else if (compactionRelevant && (signalPurityPct < 75 || sludgeTokens >= 25000)) {
|
|
1127
|
+
whatsHappening = `Moderate context clutter (${reclaimK}k reclaimable tokens). Working set is healthy, but duplicate file reads are accumulating.`;
|
|
1128
|
+
theSludgeTax = `${reclaimK}k tokens of outdated history can be freed.`;
|
|
1129
|
+
actionPlan = `Run /compact when you finish the current step to reclaim ${reclaimK}k tokens.`;
|
|
1130
|
+
recommendedCommand = '/compact';
|
|
1131
|
+
} else {
|
|
1132
|
+
whatsHappening = `High-efficiency session. Memory is clean and focused on active workspace files with plenty of safe headroom.`;
|
|
1133
|
+
theSludgeTax = `Minimal noise (${reclaimK}k tokens). Signal purity is optimal at ${signalPurityPct}%.`;
|
|
1134
|
+
actionPlan = `Memory is clean. Continue working normally.`;
|
|
1135
|
+
recommendedCommand = 'Ready';
|
|
1136
|
+
}
|
|
1137
|
+
|
|
1138
|
+
// Compute actionable Brain Signals from transcript forensics
|
|
1139
|
+
const allOffenders = Array.from(offenderMap.values());
|
|
1140
|
+
const dupFileOffenders = allOffenders
|
|
1141
|
+
.filter(o => o.category === CATEGORIES.STALE_DUPLICATE && o.target !== 'Older chat history (>25 turns ago)')
|
|
1142
|
+
.sort((a, b) => b.wastedTokens - a.wastedTokens);
|
|
1143
|
+
const oldHistOffender = allOffenders.find(o => o.target === 'Older chat history (>25 turns ago)');
|
|
1144
|
+
const errorOffenders = allOffenders.filter(o => o.category === CATEGORIES.DEAD_ERROR);
|
|
1145
|
+
|
|
1146
|
+
const blowupSteps = classifiedSteps
|
|
1147
|
+
.filter(s => s.tokens >= 8000 && s.stepIndex > 0 && s.category !== CATEGORIES.ANCHOR && s.target !== 'System & Project Anchors')
|
|
1148
|
+
.sort((a, b) => b.tokens - a.tokens)
|
|
1149
|
+
.slice(0, 3)
|
|
1150
|
+
.map(s => {
|
|
1151
|
+
const rawStep = steps[s.stepIndex] || {};
|
|
1152
|
+
const { calls: effCalls } = getEffectiveStepCalls(steps, s.stepIndex);
|
|
1153
|
+
const call = effCalls[0];
|
|
1154
|
+
const args = call?.args || call?.parameters || call?.Arguments || {};
|
|
1155
|
+
const toolName = String(call?.name || call?.tool || rawStep.toolName || '').toLowerCase();
|
|
1156
|
+
const filePath = args.Path || args.path || args.TargetFile || args.Target || args.target || args.AbsolutePath || args.file_path || rawStep.targetPath || null;
|
|
1157
|
+
const command = args.CommandLine || args.command || null;
|
|
1158
|
+
const isFileTool = Boolean(filePath) || /^(view_file|read_file|view_file_outline|view_code_item|replace_file_content|multi_replace_file_content|write_to_file|write_file|edit_file)$/.test(toolName);
|
|
1159
|
+
const isCmdTool = Boolean(command) || /^(run_command|bash|execute_command)$/.test(toolName);
|
|
1160
|
+
const userTurnNumber = Math.max(
|
|
1161
|
+
1,
|
|
1162
|
+
steps.slice(0, s.stepIndex + 1).filter(x => x && (x.source === 'USER_EXPLICIT' || x.type === 'USER_INPUT' || x.role === 'user')).length
|
|
1163
|
+
);
|
|
1164
|
+
return {
|
|
1165
|
+
stepIndex: s.stepIndex,
|
|
1166
|
+
userTurnNumber,
|
|
1167
|
+
tokens: s.tokens,
|
|
1168
|
+
category: s.category,
|
|
1169
|
+
target: s.target || `Step ${s.stepIndex}`,
|
|
1170
|
+
payload: {
|
|
1171
|
+
kind: isCmdTool ? 'command' : (isFileTool ? 'file' : 'other'),
|
|
1172
|
+
tool: call?.name || null,
|
|
1173
|
+
detail: String(command || filePath || call?.name || 'Model/tool output').slice(0, 300),
|
|
1174
|
+
path: filePath
|
|
1175
|
+
}
|
|
1176
|
+
};
|
|
1177
|
+
});
|
|
1178
|
+
|
|
1179
|
+
const recentSteps = steps.slice(-10);
|
|
1180
|
+
const recentErrors = recentSteps.filter(s => s.status === 'ERROR' || (typeof s.exitCode === 'number' && s.exitCode !== 0)).length;
|
|
1181
|
+
|
|
1182
|
+
let correctionCount = 0;
|
|
1183
|
+
const userCorrectionTexts = [];
|
|
1184
|
+
const CORRECTION_RE = /\b(no[, ]|don't|do not|instead|wrong|looks the same|shouldn't|broken|still not)\b/i;
|
|
1185
|
+
for (const s of steps) {
|
|
1186
|
+
if (s.source === 'USER_EXPLICIT' || s.type === 'USER_INPUT') {
|
|
1187
|
+
const rawTxt = String(s.content || '').trim();
|
|
1188
|
+
const strippedHostTxt = rawTxt
|
|
1189
|
+
.replace(/<ADDITIONAL_METADATA>[\s\S]*?<\/ADDITIONAL_METADATA>/gi, '')
|
|
1190
|
+
.replace(/<USER_SETTINGS_CHANGE>[\s\S]*?<\/USER_SETTINGS_CHANGE>/gi, '')
|
|
1191
|
+
.replace(/<CONTEXT_SUMMARY>[\s\S]*?<\/CONTEXT_SUMMARY>/gi, '')
|
|
1192
|
+
.replace(/<SYSTEM_MESSAGE>[\s\S]*?<\/SYSTEM_MESSAGE>/gi, '')
|
|
1193
|
+
.replace(/<system_context_prefix>[\s\S]*?<\/system_context_prefix>/gi, '')
|
|
1194
|
+
.replace(/<\/?(?:USER_REQUEST|system_context_prefix)[^>]*>/gi, '')
|
|
1195
|
+
.trim();
|
|
1196
|
+
const cleanTxt = strippedHostTxt;
|
|
1197
|
+
// Ignore long multi-section specification/persona prompts so role preambles are never mistaken for corrections
|
|
1198
|
+
if (!cleanTxt || cleanTxt.length > 500 || /^(?:#+\s*role\b|you are (?:the|a|evaluating)\b)/im.test(cleanTxt)) {
|
|
1199
|
+
continue;
|
|
1200
|
+
}
|
|
1201
|
+
if (CORRECTION_RE.test(cleanTxt)) {
|
|
1202
|
+
const candidateLines = cleanTxt
|
|
1203
|
+
.split(/\r?\n/)
|
|
1204
|
+
.map(l => l.replace(/^[-*>\s#]+/, '').trim())
|
|
1205
|
+
.filter(l => l.length >= 6 && !/^you are\b/i.test(l));
|
|
1206
|
+
const matchedLine = candidateLines.find(l => CORRECTION_RE.test(l)) || candidateLines[0] || '';
|
|
1207
|
+
if (matchedLine) {
|
|
1208
|
+
correctionCount++;
|
|
1209
|
+
const bounded = matchedLine.length <= 140
|
|
1210
|
+
? matchedLine
|
|
1211
|
+
: matchedLine.slice(0, 140).replace(/\s+\S*$/, '') + '...';
|
|
1212
|
+
userCorrectionTexts.push(bounded);
|
|
1213
|
+
}
|
|
1214
|
+
}
|
|
1215
|
+
}
|
|
1216
|
+
}
|
|
1217
|
+
|
|
1218
|
+
// task.md freshness: user turns since the last tool call that wrote task.md
|
|
1219
|
+
const isUserTurn = x => x.source === 'USER_EXPLICIT' || x.type === 'USER_INPUT';
|
|
1220
|
+
const isTaskWrite = x => (x.toolCalls || []).some(c =>
|
|
1221
|
+
/write|edit|replace|create/i.test(c.name || '') &&
|
|
1222
|
+
/task\.md/i.test(String(c.args?.Path || c.args?.path || c.args?.TargetFile || c.args?.AbsolutePath || '')));
|
|
1223
|
+
let lastTaskWrite = -1;
|
|
1224
|
+
let lastTaskWritePath = null;
|
|
1225
|
+
steps.forEach((x, i) => {
|
|
1226
|
+
if (!isTaskWrite(x)) return;
|
|
1227
|
+
lastTaskWrite = i;
|
|
1228
|
+
for (const c of (x.toolCalls || [])) {
|
|
1229
|
+
const p = String(c.args?.Path || c.args?.path || c.args?.TargetFile || c.args?.AbsolutePath || '');
|
|
1230
|
+
if (/task\.md/i.test(p)) lastTaskWritePath = p;
|
|
1231
|
+
}
|
|
1232
|
+
});
|
|
1233
|
+
const isWorkspaceFileWrite = x => (x.toolCalls || []).some(c => {
|
|
1234
|
+
if (!/write|edit|replace|create/i.test(c.name || '')) return false;
|
|
1235
|
+
const p = String(c.args?.Path || c.args?.path || c.args?.TargetFile || c.args?.AbsolutePath || '');
|
|
1236
|
+
return Boolean(p) && !isInternalTelemetryPath(p);
|
|
1237
|
+
});
|
|
1238
|
+
const sessionHasWorkspaceEdits = steps.some(isWorkspaceFileWrite);
|
|
1239
|
+
const rawTaskTurnsBehind = steps.slice(lastTaskWrite + 1).filter(isUserTurn).length;
|
|
1240
|
+
const taskTurnsBehind = (lastTaskWrite >= 0 || sessionHasWorkspaceEdits)
|
|
1241
|
+
? rawTaskTurnsBehind
|
|
1242
|
+
: 0;
|
|
1243
|
+
// the set of workspace files this session wrote/edited (for session-scoped git drift).
|
|
1244
|
+
const sessionWrittenPaths = new Set();
|
|
1245
|
+
for (const x of steps) {
|
|
1246
|
+
for (const c of (x.toolCalls || [])) {
|
|
1247
|
+
if (!/write|edit|replace|create/i.test(c?.name || '')) continue;
|
|
1248
|
+
const p = String(c?.args?.Path || c?.args?.path || c?.args?.TargetFile || c?.args?.AbsolutePath || '');
|
|
1249
|
+
if (p && !isInternalTelemetryPath(p)) sessionWrittenPaths.add(p);
|
|
1250
|
+
}
|
|
1251
|
+
}
|
|
1252
|
+
|
|
1253
|
+
const pinnedStepsCount = classifiedSteps.filter(s => s.semanticallyPinned).length;
|
|
1254
|
+
|
|
1255
|
+
// Session Forensics (plan churn, proof quality, context rot, error loop)
|
|
1256
|
+
const planChurn = computePlanChurn(steps, options.config || {});
|
|
1257
|
+
const proofQuality = gradeProofQuality(steps);
|
|
1258
|
+
const contextRot = detectContextRot(steps, {
|
|
1259
|
+
totalActiveTokens,
|
|
1260
|
+
correctionCount,
|
|
1261
|
+
lateStageTaskChurn: planChurn.lateStageTaskChurn,
|
|
1262
|
+
signalPurityPct
|
|
1263
|
+
}, options.config || {});
|
|
1264
|
+
const errorLoop = fingerprintErrorLoop(steps);
|
|
1265
|
+
|
|
1266
|
+
let brainDir = options.brainDir || null;
|
|
1267
|
+
if (!brainDir && logFilePath) {
|
|
1268
|
+
try {
|
|
1269
|
+
const parent2 = path.resolve(path.dirname(logFilePath), '..', '..');
|
|
1270
|
+
if (path.basename(path.dirname(parent2)) === 'brain' || path.basename(parent2).length > 20) {
|
|
1271
|
+
brainDir = parent2;
|
|
1272
|
+
}
|
|
1273
|
+
} catch (err) {
|
|
1274
|
+
if (process.env.HORIZON_DEBUG) console.error('[classifier] brainDir resolve failed:', err?.message || err);
|
|
1275
|
+
}
|
|
1276
|
+
}
|
|
1277
|
+
const handoff = auditHandoff(brainDir || canonicalWorkspace, {
|
|
1278
|
+
planChurn,
|
|
1279
|
+
errorLoop,
|
|
1280
|
+
deadErrors: { isErrorLoop: recentErrors >= 3 || errorLoop.loop },
|
|
1281
|
+
totalActiveTokens,
|
|
1282
|
+
sludgeTokens,
|
|
1283
|
+
sessionHasWorkspaceEdits,
|
|
1284
|
+
activeSignal: {
|
|
1285
|
+
taskMdTurnsBehind: taskTurnsBehind,
|
|
1286
|
+
taskMdPathHint: lastTaskWritePath,
|
|
1287
|
+
sessionHasWorkspaceEdits
|
|
1288
|
+
}
|
|
1289
|
+
}, {
|
|
1290
|
+
workspacePath: canonicalWorkspace,
|
|
1291
|
+
gitPorcelainOutput: options.gitPorcelainOutput,
|
|
1292
|
+
sessionWrittenPaths: Array.from(sessionWrittenPaths)
|
|
1293
|
+
});
|
|
1294
|
+
|
|
1295
|
+
const mcpAudit = auditMcpPrefixBloat({
|
|
1296
|
+
workspaceDir: canonicalWorkspace,
|
|
1297
|
+
homeDir: options.homeDir,
|
|
1298
|
+
steps
|
|
1299
|
+
});
|
|
1300
|
+
const rulePromotion = auditRuleFileAttentionAndLineLimit(canonicalWorkspace);
|
|
1301
|
+
|
|
1302
|
+
const brainSignals = {
|
|
1303
|
+
activeSignal: {
|
|
1304
|
+
liveSessionTokens: Math.round((rawLiveTokens / rawTotalTokens) * totalActiveTokens),
|
|
1305
|
+
taskMdSaved: lastTaskWrite >= 0,
|
|
1306
|
+
taskMdTurnsBehind: taskTurnsBehind,
|
|
1307
|
+
sessionHasWorkspaceEdits,
|
|
1308
|
+
semanticallyPinnedTurns: pinnedStepsCount
|
|
1309
|
+
},
|
|
1310
|
+
duplicateReads: {
|
|
1311
|
+
fileCount: dupFileOffenders.length,
|
|
1312
|
+
reclaimableTokens: dupFileOffenders.reduce((sum, o) => sum + o.wastedTokens, 0),
|
|
1313
|
+
topFiles: dupFileOffenders.slice(0, 5).map(o => ({
|
|
1314
|
+
path: o.target,
|
|
1315
|
+
occurrences: o.occurrences,
|
|
1316
|
+
wastedTokens: o.wastedTokens
|
|
1317
|
+
})),
|
|
1318
|
+
exemptedReReads: fullReReadEval.exemptedReReads
|
|
1319
|
+
},
|
|
1320
|
+
oldHistory: {
|
|
1321
|
+
turnCount: oldHistOffender ? oldHistOffender.occurrences : 0,
|
|
1322
|
+
reclaimableTokens: oldHistOffender ? oldHistOffender.wastedTokens : 0
|
|
1323
|
+
},
|
|
1324
|
+
deadErrors: {
|
|
1325
|
+
errorCount: errorOffenders.reduce((sum, o) => sum + o.occurrences, 0),
|
|
1326
|
+
reclaimableTokens: categoryTotals[CATEGORIES.DEAD_ERROR] || 0,
|
|
1327
|
+
isErrorLoop: recentErrors >= 3 || errorLoop.loop,
|
|
1328
|
+
topErrors: errorOffenders.slice(0, 3).map(o => ({
|
|
1329
|
+
target: o.target,
|
|
1330
|
+
occurrences: o.occurrences,
|
|
1331
|
+
wastedTokens: o.wastedTokens
|
|
1332
|
+
}))
|
|
1333
|
+
},
|
|
1334
|
+
foreignBleed: {
|
|
1335
|
+
reclaimableTokens: categoryTotals[CATEGORIES.FOREIGN_BLEED] || 0
|
|
1336
|
+
},
|
|
1337
|
+
blowupSteps,
|
|
1338
|
+
userCorrections: correctionCount,
|
|
1339
|
+
userCorrectionTexts,
|
|
1340
|
+
activeDaemons: activeBackgroundDaemons,
|
|
1341
|
+
planChurn,
|
|
1342
|
+
proofQuality,
|
|
1343
|
+
contextRot,
|
|
1344
|
+
errorLoop,
|
|
1345
|
+
handoff,
|
|
1346
|
+
mcpAudit,
|
|
1347
|
+
rulePromotion
|
|
1348
|
+
};
|
|
1349
|
+
|
|
1350
|
+
const aiCreditOveragesEnabled = Boolean(
|
|
1351
|
+
options.aiCreditOveragesEnabled ??
|
|
1352
|
+
stdinQuota?.enable_ai_credit_overages ??
|
|
1353
|
+
stdinQuota?.aiCreditOveragesEnabled ??
|
|
1354
|
+
false
|
|
1355
|
+
);
|
|
1356
|
+
|
|
1357
|
+
// Compute Dual-Pool Quota & Cache-Read Telemetry
|
|
1358
|
+
const quota = computeQuotaAndCacheTelemetry(steps, {
|
|
1359
|
+
sessionId,
|
|
1360
|
+
modelId,
|
|
1361
|
+
totalActiveTokens,
|
|
1362
|
+
activeEffortProfile,
|
|
1363
|
+
stdinQuota,
|
|
1364
|
+
genMetadata: options.genMetadata || null,
|
|
1365
|
+
aiCreditOveragesEnabled,
|
|
1366
|
+
cacheDir,
|
|
1367
|
+
reclaimableTokens: sludgeTokens || 0,
|
|
1368
|
+
sludgeTokens: sludgeTokens || 0,
|
|
1369
|
+
isAutoMode: Boolean(activeEffortProfile?.tier === 'STANDARD' || activeEffortProfile?.shortLabel === 'Auto')
|
|
1370
|
+
});
|
|
1371
|
+
|
|
1372
|
+
// Detect pending checklist items in task.md (or recent task writes) for Cascade >50k checkpointer arming
|
|
1373
|
+
let hasPendingTaskItems = false;
|
|
1374
|
+
if (options.hasPendingTaskItems !== undefined) {
|
|
1375
|
+
hasPendingTaskItems = Boolean(options.hasPendingTaskItems);
|
|
1376
|
+
} else if (handoff?.targetFile && fs.existsSync(handoff.targetFile)) {
|
|
1377
|
+
try {
|
|
1378
|
+
const taskText = fs.readFileSync(handoff.targetFile, 'utf8');
|
|
1379
|
+
hasPendingTaskItems = /^[-*]\s*\[ \]/m.test(taskText);
|
|
1380
|
+
} catch (err) {
|
|
1381
|
+
if (err?.code !== 'ENOENT' && process.env.HORIZON_DEBUG) console.error('[classifier] task.md read failed:', err?.message || err);
|
|
1382
|
+
}
|
|
1383
|
+
} else if (lastTaskWrite >= 0) {
|
|
1384
|
+
hasPendingTaskItems = steps.slice(lastTaskWrite).some(s => String(s.content || '').includes('- [ ]'));
|
|
1385
|
+
}
|
|
1386
|
+
brainSignals.activeSignal.hasPendingTaskItems = hasPendingTaskItems;
|
|
1387
|
+
|
|
1388
|
+
const effectiveSafeHorizon = effectiveMaxTokens > 256000
|
|
1389
|
+
? safeLimit
|
|
1390
|
+
: Math.min(safeLimit, SESSION_RISK_THRESHOLDS.SAFE_HORIZON_TOKENS);
|
|
1391
|
+
const sessionRisk = evaluateCompositeSessionRisk({
|
|
1392
|
+
totalActiveTokens,
|
|
1393
|
+
safeHorizonTokens: effectiveSafeHorizon,
|
|
1394
|
+
cacheTtlRemainingSec: quota.cache?.ttlRemainingSec ?? 300,
|
|
1395
|
+
cacheReadTokens: quota.cache?.cacheReadTokens ?? 0,
|
|
1396
|
+
cacheHitRatePct: quota.cache?.hitRatePct ?? 0,
|
|
1397
|
+
taskMdTurnsBehind: taskTurnsBehind,
|
|
1398
|
+
taskMdExists: Boolean(lastTaskWrite >= 0 || handoff?.artifacts?.taskMd?.exists),
|
|
1399
|
+
sessionHasWorkspaceEdits,
|
|
1400
|
+
hasPendingTaskItems,
|
|
1401
|
+
weekly7dUsedPct: quota.weekly7d?.usedPct ?? 0,
|
|
1402
|
+
weekly7dLockoutRisk: Boolean(quota.weekly7d?.lockoutRisk),
|
|
1403
|
+
weekly7dSource: quota.weekly7d?.source,
|
|
1404
|
+
aiCreditOveragesEnabled,
|
|
1405
|
+
prefixBustDetected: Boolean(quota.cache?.prefixBustDetected)
|
|
1406
|
+
});
|
|
1407
|
+
const surfaceTag = resolveSurfaceTag(storeSource || logFilePath);
|
|
1408
|
+
const watermarks = computeWatermarks(effectiveMaxTokens, safeLimit);
|
|
1409
|
+
const historyBarState = evaluateHistoryBarState({
|
|
1410
|
+
totalActiveTokens,
|
|
1411
|
+
safeHorizonTokens: SESSION_RISK_THRESHOLDS.SAFE_HORIZON_TOKENS,
|
|
1412
|
+
cacheTtlRemainingSec: quota.cache?.ttlRemainingSec ?? 300,
|
|
1413
|
+
isCacheTrulyWarm: sessionRisk.isCacheTrulyWarm,
|
|
1414
|
+
nextTurnLikelyWarm: typeof quota.cache?.nextTurnLikelyWarm === 'boolean' ? quota.cache.nextTurnLikelyWarm : undefined
|
|
1415
|
+
});
|
|
1416
|
+
|
|
1417
|
+
// Parameterized /compact synthesizer, Cache-Aware Advisory & Baton Pass (/handoff)
|
|
1418
|
+
const activeFileCandidates = Array.from(latestFileTouchStep.keys()).filter(p => !isInternalTelemetryPath(p));
|
|
1419
|
+
const fallbackDupFiles = dupFileOffenders.map(o => o.target).filter(p => !isInternalTelemetryPath(p));
|
|
1420
|
+
const cleanActiveFiles = activeFileCandidates.length > 0 ? activeFileCandidates : fallbackDupFiles;
|
|
1421
|
+
const parameterizedCommand = synthesizeParameterizedCompact({
|
|
1422
|
+
activeFiles: cleanActiveFiles,
|
|
1423
|
+
userCorrections: userCorrectionTexts,
|
|
1424
|
+
steps,
|
|
1425
|
+
workspaceRoot: canonicalWorkspace
|
|
1426
|
+
});
|
|
1427
|
+
const cacheAdvisory = evaluateCompactionCacheAdvisory({
|
|
1428
|
+
cacheTtlRemainingSec: quota.cache?.ttlRemainingSec ?? 300,
|
|
1429
|
+
totalActiveTokens,
|
|
1430
|
+
safeHorizonTokens: SESSION_RISK_THRESHOLDS.SAFE_HORIZON_TOKENS,
|
|
1431
|
+
isCacheTrulyWarm: sessionRisk.isCacheTrulyWarm,
|
|
1432
|
+
nextTurnLikelyWarm: typeof quota.cache?.nextTurnLikelyWarm === 'boolean' ? quota.cache.nextTurnLikelyWarm : undefined,
|
|
1433
|
+
sludgeTokens
|
|
1434
|
+
});
|
|
1435
|
+
const batonPass = synthesizeBatonPassHandoffCommand({
|
|
1436
|
+
activeFiles: cleanActiveFiles
|
|
1437
|
+
});
|
|
1438
|
+
const compaction = {
|
|
1439
|
+
parameterizedCommand,
|
|
1440
|
+
cacheAdvisory,
|
|
1441
|
+
batonPass,
|
|
1442
|
+
preCompactionWarning: Boolean(handoff?.preCompactionWarning),
|
|
1443
|
+
preCompactionWarningMessage: handoff?.preCompactionWarningMessage || ''
|
|
1444
|
+
};
|
|
1445
|
+
|
|
1446
|
+
// Compute Multi-Agent (invoke_subagent) Context Tree & Handoff Compression
|
|
1447
|
+
const subagents = inspectSubagentTree(steps, { cacheDir });
|
|
1448
|
+
for (const inv of subagents.invocations) {
|
|
1449
|
+
for (const c of cells) {
|
|
1450
|
+
if (c.turnRange && c.turnRange[0] >= 0 && inv.stepIndex >= c.turnRange[0] && inv.stepIndex <= c.turnRange[1]) {
|
|
1451
|
+
c.subagents = c.subagents || [];
|
|
1452
|
+
c.subagents.push(inv);
|
|
1453
|
+
break;
|
|
1454
|
+
}
|
|
1455
|
+
}
|
|
1456
|
+
}
|
|
1457
|
+
|
|
1458
|
+
// Sprint 2.1: Subagent /swarm roster + git worktree topology + scope-lock overlaps
|
|
1459
|
+
let swarmTopology = null;
|
|
1460
|
+
try {
|
|
1461
|
+
let swarmLeases = [];
|
|
1462
|
+
if (canonicalWorkspace && options.probeSwarmLeases !== false) {
|
|
1463
|
+
try {
|
|
1464
|
+
const reg = loadSwarmScopeRegistry(canonicalWorkspace);
|
|
1465
|
+
swarmLeases = Array.isArray(reg?.leases) ? reg.leases : [];
|
|
1466
|
+
} catch (err) {
|
|
1467
|
+
if (process.env.HORIZON_DEBUG) console.error('[classifier] swarm lease load failed:', err?.message || err);
|
|
1468
|
+
}
|
|
1469
|
+
}
|
|
1470
|
+
swarmTopology = computeSwarmTopology(steps, {
|
|
1471
|
+
nowMs: typeof options.nowMs === 'number' ? options.nowMs : Date.now(),
|
|
1472
|
+
workspaceDir: canonicalWorkspace || null,
|
|
1473
|
+
worktrees: Array.isArray(options.worktrees) ? options.worktrees : null,
|
|
1474
|
+
leases: swarmLeases,
|
|
1475
|
+
probeGit: options.probeGit !== false
|
|
1476
|
+
});
|
|
1477
|
+
} catch (err) {
|
|
1478
|
+
if (process.env.HORIZON_DEBUG) console.error('[classifier] swarm topology failed:', err?.message || err);
|
|
1479
|
+
swarmTopology = null;
|
|
1480
|
+
}
|
|
1481
|
+
|
|
1482
|
+
// Session Fracture Markers (⚡) & Stranded Signal Summary
|
|
1483
|
+
const fractures = [];
|
|
1484
|
+
const mapStepToCellIndex = (stepIdx) => {
|
|
1485
|
+
for (const c of cells) {
|
|
1486
|
+
if (c.turnRange && c.turnRange[0] >= 0 && stepIdx >= c.turnRange[0] && stepIdx <= c.turnRange[1]) {
|
|
1487
|
+
return c.index;
|
|
1488
|
+
}
|
|
1489
|
+
}
|
|
1490
|
+
return Math.min(39, Math.max(0, Math.floor((stepIdx / Math.max(1, totalTurns)) * Math.max(1, activeCellsCount))));
|
|
1491
|
+
};
|
|
1492
|
+
|
|
1493
|
+
if (lastCheckpointIdx >= 0) {
|
|
1494
|
+
fractures.push({
|
|
1495
|
+
type: 'COMPACTION',
|
|
1496
|
+
glyph: '\u26A1',
|
|
1497
|
+
stepIndex: 0,
|
|
1498
|
+
rawStepIndex: lastCheckpointIdx,
|
|
1499
|
+
cellIndex: 0,
|
|
1500
|
+
label: `Compaction Checkpoint (step_type == ${CORTEX_STEP_TYPE_CHECKPOINT}) at Turn #${lastCheckpointIdx}`
|
|
1501
|
+
});
|
|
1502
|
+
}
|
|
1503
|
+
for (let i = 0; i < steps.length; i++) {
|
|
1504
|
+
const st = steps[i];
|
|
1505
|
+
if (i > 0 && isCompactionCheckpointStep(st)) {
|
|
1506
|
+
const cIdx = mapStepToCellIndex(i);
|
|
1507
|
+
fractures.push({
|
|
1508
|
+
type: 'COMPACTION',
|
|
1509
|
+
glyph: '\u26A1',
|
|
1510
|
+
stepIndex: i,
|
|
1511
|
+
cellIndex: cIdx,
|
|
1512
|
+
label: `Compaction Checkpoint (step_type == ${CORTEX_STEP_TYPE_CHECKPOINT}) at Turn #${i}`
|
|
1513
|
+
});
|
|
1514
|
+
}
|
|
1515
|
+
if (i > 0) {
|
|
1516
|
+
const prev = steps[i - 1];
|
|
1517
|
+
const currCache = Number(st?.cacheReadTokens || 0);
|
|
1518
|
+
const prevCache = Number(prev?.cacheReadTokens || 0);
|
|
1519
|
+
const currInput = Number(st?.inputTokens || st?.outputTokens || 0);
|
|
1520
|
+
let deltaSec = null;
|
|
1521
|
+
if (st?.createdAt && prev?.createdAt) {
|
|
1522
|
+
const dMs = Date.parse(st.createdAt) - Date.parse(prev.createdAt);
|
|
1523
|
+
if (Number.isFinite(dMs) && dMs >= 0) deltaSec = dMs / 1000;
|
|
1524
|
+
}
|
|
1525
|
+
if (currCache === 0 && prevCache > 0 && currInput > 0 && deltaSec !== null && deltaSec < 300) {
|
|
1526
|
+
const cIdx = mapStepToCellIndex(i);
|
|
1527
|
+
fractures.push({
|
|
1528
|
+
type: 'PREFIX_BUST',
|
|
1529
|
+
glyph: '\u26A1',
|
|
1530
|
+
stepIndex: i,
|
|
1531
|
+
cellIndex: cIdx,
|
|
1532
|
+
deltaSec: Math.round(deltaSec),
|
|
1533
|
+
label: `Mid-run Prefix Bust (cache_read_tokens == 0 at \u0394t = ${Math.round(deltaSec)}s < 300s) at Turn #${i}`
|
|
1534
|
+
});
|
|
1535
|
+
}
|
|
1536
|
+
}
|
|
1537
|
+
}
|
|
1538
|
+
if (quota.cache?.prefixBustDetected && !fractures.some(f => f.type === 'PREFIX_BUST')) {
|
|
1539
|
+
const lastActiveCellIdx = Math.max(0, activeCellsCount - 1);
|
|
1540
|
+
fractures.push({
|
|
1541
|
+
type: 'PREFIX_BUST',
|
|
1542
|
+
glyph: '\u26A1',
|
|
1543
|
+
stepIndex: Math.max(0, totalTurns - 1),
|
|
1544
|
+
cellIndex: lastActiveCellIdx,
|
|
1545
|
+
deltaSec: quota.cache?.prefixBustDeltaSec ?? 0,
|
|
1546
|
+
label: quota.cache?.prefixBustLabel || '\u26A0\uFE0F Prefix Bust (system_message / config drift)'
|
|
1547
|
+
});
|
|
1548
|
+
}
|
|
1549
|
+
|
|
1550
|
+
for (const frac of fractures) {
|
|
1551
|
+
const targetCell = cells[frac.cellIndex];
|
|
1552
|
+
if (targetCell) {
|
|
1553
|
+
targetCell.fractures = targetCell.fractures || [];
|
|
1554
|
+
targetCell.fractures.push(frac);
|
|
1555
|
+
targetCell.hasFracture = true;
|
|
1556
|
+
}
|
|
1557
|
+
}
|
|
1558
|
+
|
|
1559
|
+
const troughCells = cells.filter(c => c.inAttentionTrough);
|
|
1560
|
+
const strandedSignals = cells
|
|
1561
|
+
.filter(c => c.isStrandedSignal)
|
|
1562
|
+
.map(c => ({
|
|
1563
|
+
cellIndex: c.index,
|
|
1564
|
+
cellNumber: c.index + 1,
|
|
1565
|
+
dominantCategory: c.dominantCategory,
|
|
1566
|
+
topTarget: c.topTarget,
|
|
1567
|
+
attentionWeight: c.attentionWeight,
|
|
1568
|
+
turnRange: c.turnRange,
|
|
1569
|
+
warning: STRANDED_SIGNAL_WARNING_TEXT
|
|
1570
|
+
}));
|
|
1571
|
+
|
|
1572
|
+
const attentionHeatmap = {
|
|
1573
|
+
gamma: ATTENTION_TROUGH_CONFIG.GAMMA,
|
|
1574
|
+
activeCellsCount,
|
|
1575
|
+
troughStartRatio: ATTENTION_TROUGH_CONFIG.TROUGH_START_RATIO,
|
|
1576
|
+
troughEndRatio: ATTENTION_TROUGH_CONFIG.TROUGH_END_RATIO,
|
|
1577
|
+
troughCellIndices: troughCells.map(c => c.index),
|
|
1578
|
+
strandedSignalCount: strandedSignals.length,
|
|
1579
|
+
strandedSignals,
|
|
1580
|
+
strandedWarningText: STRANDED_SIGNAL_WARNING_TEXT,
|
|
1581
|
+
fractureCount: fractures.length,
|
|
1582
|
+
fractures
|
|
1583
|
+
};
|
|
1584
|
+
|
|
1585
|
+
const workloadMode = classifyWorkloadMode(steps);
|
|
1586
|
+
const topRiskyCells = rankRiskiestCells(cells, {
|
|
1587
|
+
totalActiveTokens,
|
|
1588
|
+
safeLimit,
|
|
1589
|
+
cellSizeTokens: effectiveCellSize
|
|
1590
|
+
});
|
|
1591
|
+
const actionQueue = buildActionQueue({
|
|
1592
|
+
metrics: { totalInputTokens: totalActiveTokens, totalTurns: userTurnCount, totalSteps },
|
|
1593
|
+
brainSignals,
|
|
1594
|
+
quota,
|
|
1595
|
+
topRiskyCells,
|
|
1596
|
+
window: { totalActiveTokens, stepCount: totalSteps },
|
|
1597
|
+
turns: userTurnCount,
|
|
1598
|
+
stepCount: totalSteps,
|
|
1599
|
+
baseline: { mcpAudit },
|
|
1600
|
+
hostHealth: options.hostHealth || null
|
|
1601
|
+
});
|
|
1602
|
+
|
|
1603
|
+
let lastUserPrompt = '';
|
|
1604
|
+
for (let i = steps.length - 1; i >= 0; i--) {
|
|
1605
|
+
const st = steps[i];
|
|
1606
|
+
if (st && (st.source === 'USER_EXPLICIT' || st.type === 'USER_INPUT')) {
|
|
1607
|
+
const cleaned = String(st.content || '')
|
|
1608
|
+
.replace(/<\/?USER_REQUEST>/gi, '')
|
|
1609
|
+
.trim();
|
|
1610
|
+
if (cleaned) {
|
|
1611
|
+
lastUserPrompt = cleaned.slice(0, 8000);
|
|
1612
|
+
break;
|
|
1613
|
+
}
|
|
1614
|
+
}
|
|
1615
|
+
}
|
|
1616
|
+
|
|
1617
|
+
const exportedSteps = steps.map((st, idx) => {
|
|
1618
|
+
const rawCalls = Array.isArray(st?.toolCalls)
|
|
1619
|
+
? st.toolCalls
|
|
1620
|
+
: (Array.isArray(st?.tool_calls) ? st.tool_calls : []);
|
|
1621
|
+
return {
|
|
1622
|
+
stepIndex: Number.isFinite(st?.stepIndex) ? st.stepIndex : idx,
|
|
1623
|
+
type: st?.type || 'GENERIC',
|
|
1624
|
+
source: st?.source || 'MODEL',
|
|
1625
|
+
status: st?.status || 'DONE',
|
|
1626
|
+
exitCode: typeof st?.exitCode === 'number' ? st.exitCode : undefined,
|
|
1627
|
+
tokens: classifiedSteps[idx]?.tokens || 0,
|
|
1628
|
+
outputTokens: st?.outputTokens || 0,
|
|
1629
|
+
category: classifiedSteps[idx]?.category || CATEGORIES.ACTIVE_WORKING_SET,
|
|
1630
|
+
target: classifiedSteps[idx]?.target || '',
|
|
1631
|
+
toolCalls: rawCalls.map(c => ({
|
|
1632
|
+
name: c?.name || c?.tool || '',
|
|
1633
|
+
args: c?.args || c?.parameters || c?.Arguments || {}
|
|
1634
|
+
}))
|
|
1635
|
+
};
|
|
1636
|
+
});
|
|
1637
|
+
|
|
1638
|
+
return {
|
|
1639
|
+
schemaVersion: '1.1.0',
|
|
1640
|
+
sessionId,
|
|
1641
|
+
storeSource,
|
|
1642
|
+
surfaceTag,
|
|
1643
|
+
workloadMode,
|
|
1644
|
+
lastUserPrompt,
|
|
1645
|
+
steps: exportedSteps,
|
|
1646
|
+
topRiskyCells,
|
|
1647
|
+
actionQueue,
|
|
1648
|
+
brainDir: brainDir || null,
|
|
1649
|
+
logTierUsed,
|
|
1650
|
+
logFilePath,
|
|
1651
|
+
workspace: {
|
|
1652
|
+
canonicalPath: canonicalWorkspace,
|
|
1653
|
+
projectId
|
|
1654
|
+
},
|
|
1655
|
+
model: {
|
|
1656
|
+
id: modelId,
|
|
1657
|
+
displayName: humanizeModelLabel(modelId),
|
|
1658
|
+
source: options.modelSource || null,
|
|
1659
|
+
inputPricePerMillionUsd: pricePerM,
|
|
1660
|
+
nativeCeilingTokens: ceilingDetails.ceilingTokens,
|
|
1661
|
+
ceilingSource: ceilingDetails.source,
|
|
1662
|
+
isClamped1MModel: Boolean(ceilingDetails.isClamped1MModel),
|
|
1663
|
+
clampedLabel: ceilingDetails.clampedLabel || '',
|
|
1664
|
+
patchedTier: ceilingDetails.patchedTier || null
|
|
1665
|
+
},
|
|
1666
|
+
parseHealth: options.parseHealth || rawSteps.health || {
|
|
1667
|
+
totalLines: rawSteps.length,
|
|
1668
|
+
parsedLines: rawSteps.length,
|
|
1669
|
+
malformedLines: 0,
|
|
1670
|
+
unknownShapeLines: 0,
|
|
1671
|
+
confidence: 'HIGH'
|
|
1672
|
+
},
|
|
1673
|
+
confidence: (options.parseHealth || rawSteps.health)?.confidence || 'HIGH',
|
|
1674
|
+
window: {
|
|
1675
|
+
maxTokens: effectiveMaxTokens,
|
|
1676
|
+
cellSizeTokens: effectiveCellSize,
|
|
1677
|
+
totalCells: HORIZON_WINDOW.TOTAL_CELLS,
|
|
1678
|
+
totalActiveTokens,
|
|
1679
|
+
usedPercentage: parseFloat(((totalActiveTokens / effectiveMaxTokens) * 100).toFixed(1)),
|
|
1680
|
+
exceeds200kTokens: totalActiveTokens >= 200000,
|
|
1681
|
+
turnCount: userTurnCount,
|
|
1682
|
+
stepCount: totalSteps,
|
|
1683
|
+
safeLimit,
|
|
1684
|
+
safeHeadroomTokens: Math.max(0, safeLimit - totalActiveTokens),
|
|
1685
|
+
reminderAt,
|
|
1686
|
+
watermarks,
|
|
1687
|
+
historyBarState,
|
|
1688
|
+
unifiedPool: computeUnifiedContextPool(
|
|
1689
|
+
{
|
|
1690
|
+
input_tokens: totalActiveTokens,
|
|
1691
|
+
thinking_tokens: options.thinkingTokens ?? 0,
|
|
1692
|
+
output_tokens: options.outputTokens ?? 0
|
|
1693
|
+
},
|
|
1694
|
+
modelId
|
|
1695
|
+
)
|
|
1696
|
+
},
|
|
1697
|
+
breakdown: categoryTotals,
|
|
1698
|
+
metrics: {
|
|
1699
|
+
signalPurityPct,
|
|
1700
|
+
sludgeTokens,
|
|
1701
|
+
sludgeTaxPerTurnUsd,
|
|
1702
|
+
totalTurnCostUsd,
|
|
1703
|
+
healthBand,
|
|
1704
|
+
totalTurns: userTurnCount,
|
|
1705
|
+
totalSteps,
|
|
1706
|
+
displayParity: computeDisplayTenthsParity(
|
|
1707
|
+
totalActiveTokens,
|
|
1708
|
+
Math.max(0, totalActiveTokens - sludgeTokens),
|
|
1709
|
+
Math.round((brainSignals.duplicateReads.reclaimableTokens || 0) / 100) +
|
|
1710
|
+
Math.round((brainSignals.oldHistory.reclaimableTokens || 0) / 100) +
|
|
1711
|
+
Math.round((brainSignals.deadErrors.reclaimableTokens || 0) / 100) +
|
|
1712
|
+
Math.round(((categoryTotals[CATEGORIES.FOREIGN_BLEED] || 0)) / 100)
|
|
1713
|
+
)
|
|
1714
|
+
},
|
|
1715
|
+
amputation: {
|
|
1716
|
+
inAmputationZone,
|
|
1717
|
+
bracketCells: [0, HORIZON_WINDOW.AMPUTATION_CELL_COUNT - 1],
|
|
1718
|
+
truncationRiskTokens: inAmputationZone ? HORIZON_WINDOW.AMPUTATION_CELL_COUNT * effectiveCellSize : 0,
|
|
1719
|
+
amputationCrisis,
|
|
1720
|
+
anchorsAtRisk: Array.from(new Set(earlySteps.filter(s => s.category === CATEGORIES.ANCHOR).map(s => s.target))),
|
|
1721
|
+
activeDaemonsAtRisk: daemonsAtRisk
|
|
1722
|
+
},
|
|
1723
|
+
cells,
|
|
1724
|
+
attentionHeatmap,
|
|
1725
|
+
offenders,
|
|
1726
|
+
brainSignals,
|
|
1727
|
+
quota,
|
|
1728
|
+
sessionRisk,
|
|
1729
|
+
compaction,
|
|
1730
|
+
subagents,
|
|
1731
|
+
swarmTopology,
|
|
1732
|
+
activeEffortProfile,
|
|
1733
|
+
effortTransitions,
|
|
1734
|
+
effortHistory: effortTransitions,
|
|
1735
|
+
sessionTimeline: buildSessionTimeline({
|
|
1736
|
+
steps,
|
|
1737
|
+
classifiedSteps,
|
|
1738
|
+
effortTransitions,
|
|
1739
|
+
safeLimit,
|
|
1740
|
+
totalActiveTokens,
|
|
1741
|
+
isCompactionStep: isCompactionCheckpointStep
|
|
1742
|
+
}),
|
|
1743
|
+
diagnostics: {
|
|
1744
|
+
whatsHappening,
|
|
1745
|
+
theSludgeTax,
|
|
1746
|
+
actionPlan,
|
|
1747
|
+
recommendedCommand,
|
|
1748
|
+
migrationNotice: getDeprecatedModelMigrationNotice(modelId, options.eventTimestampUtc ?? null),
|
|
1749
|
+
carbonVerbosity: evaluateCarbonVerbosityGuardrail(steps, {
|
|
1750
|
+
modelId,
|
|
1751
|
+
activeEffort: activeEffortProfile?.effort || options.effort || 'high',
|
|
1752
|
+
eventTimestampUtc: options.eventTimestampUtc ?? null
|
|
1753
|
+
})
|
|
1754
|
+
},
|
|
1755
|
+
updatedAt: new Date().toISOString()
|
|
1756
|
+
};
|
|
1757
|
+
}
|