ctxtop 0.0.0-stage → 4.1.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 +166 -0
- package/LICENSE +27 -0
- package/README.md +350 -2
- 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 +175 -0
- package/bin/cli.mjs +3 -0
- package/bin/ctxtop.mjs +1799 -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 +133 -0
- package/config/modelCatalog.json +785 -0
- package/config/platformQuirks.json +19 -0
- package/hooks/handlers/compact-lifecycle.mjs +577 -0
- package/hooks/handlers/config-change.mjs +402 -0
- package/hooks/handlers/hookIo.mjs +311 -0
- package/hooks/handlers/hookIpcClient.mjs +83 -0
- package/hooks/handlers/post-model-switch.mjs +111 -0
- package/hooks/handlers/post-tool-use.mjs +366 -0
- package/hooks/handlers/pre-model-switch.mjs +1048 -0
- package/hooks/handlers/pre-tool-use.mjs +632 -0
- package/hooks/handlers/stop-gate.mjs +526 -0
- package/hooks/handlers/user-prompt-submit.mjs +367 -0
- package/hooks/hooks.json +131 -0
- package/hooks/post_invocation.mjs +13 -0
- package/hooks/post_tool_use.mjs +25 -0
- package/hooks/pre_invocation.mjs +14 -0
- package/hooks/pre_tool_use.mjs +97 -0
- package/hooks/register.js +726 -0
- package/hooks/session_start.mjs +24 -0
- package/hooks/stop.mjs +23 -0
- package/hooks.json +56 -0
- package/package.json +110 -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 +2038 -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 +50 -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 +109 -0
- package/src/adapters/claude-code/index.mjs +194 -0
- package/src/cli/cost_radar.mjs +70 -0
- package/src/cli/doctor.mjs +351 -0
- package/src/cli/horizon_hud.mjs +888 -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 +704 -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/bucket_b_runtime.mjs +1200 -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 +1987 -0
- package/src/core/detectors_det01_to_16.mjs +1523 -0
- package/src/core/doc_indexer.mjs +338 -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 +1084 -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 +1997 -0
- package/src/core/path_canonicalizer.mjs +73 -0
- package/src/core/paths.mjs +311 -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/rsl_clash_auditor.mjs +423 -0
- package/src/core/rsl_distiller.mjs +372 -0
- package/src/core/rsl_ledger.mjs +969 -0
- package/src/core/rsl_triage.mjs +909 -0
- package/src/core/sanitizer.mjs +121 -0
- package/src/core/session_auditor.mjs +658 -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/shield_manager.mjs +1417 -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 +1547 -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/resumeToolsetAuditor.mjs +321 -0
- package/src/core-isomorphic/coach/savedQuotaLedger.mjs +527 -0
- package/src/core-isomorphic/coach/smartCompactAdvisor.mjs +305 -0
- package/src/core-isomorphic/coach/stateBatonHydrator.mjs +810 -0
- package/src/core-isomorphic/coach/ttlWatchdog.mjs +464 -0
- package/src/core-isomorphic/config/anthropicModelCatalog.json +606 -0
- package/src/core-isomorphic/config/catalogLoader.mjs +1268 -0
- package/src/core-isomorphic/config/horizonConfig.mjs +1055 -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 +888 -0
- package/src/core-isomorphic/economics/billingBlocks.mjs +251 -0
- package/src/core-isomorphic/economics/cacheGravity.mjs +369 -0
- package/src/core-isomorphic/economics/cliffBreaker.mjs +256 -0
- package/src/core-isomorphic/economics/driftLatency.mjs +433 -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/bucketBAlphaBeta.mjs +860 -0
- package/src/core-isomorphic/guards/bucketBGamma.mjs +442 -0
- package/src/core-isomorphic/guards/bucketBHeuristics.mjs +37 -0
- package/src/core-isomorphic/guards/circuitBreakers.mjs +1202 -0
- package/src/core-isomorphic/guards/det01_03_shell_secret.mjs +1184 -0
- package/src/core-isomorphic/guards/det04_12_thrash_rot.mjs +572 -0
- package/src/core-isomorphic/guards/det13_20_mcp_scope.mjs +913 -0
- package/src/core-isomorphic/guards/docIndexCore.mjs +446 -0
- package/src/core-isomorphic/guards/losslessPostSanitizer.mjs +317 -0
- package/src/core-isomorphic/guards/slopsquatGate.mjs +551 -0
- package/src/core-isomorphic/index.js +27 -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 +1156 -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 +1237 -0
- package/src/core-isomorphic/ui/modViews.mjs +1504 -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/claudeHookCapabilities.mjs +396 -0
- package/src/diagnostics/doctorEngine.mjs +295 -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 +342 -0
- package/src/engine-node/db/sqlite_wrapper.mjs +122 -0
- package/src/engine-node/index.mjs +12 -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 +376 -0
- package/src/engine-node/sensors/git_merge_tree.mjs +223 -0
- package/src/engine-node/sensors/index.mjs +7 -0
- package/src/hooks/antigravity_rsl_hook.mjs +250 -0
- package/src/hooks/claude_rsl_hook.mjs +288 -0
- package/src/hooks/portfolio_runtime.mjs +858 -0
- package/src/hooks/post_invocation.mjs +611 -0
- package/src/hooks/pre_invocation.mjs +1725 -0
- package/src/hooks/session_start.mjs +199 -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/modelSwitchTelemetry.mjs +308 -0
- package/src/utils/nodeIo.mjs +59 -0
- package/src/utils/runtime.mjs +1 -0
- package/src/utils/sessionCalibration.mjs +657 -0
- package/src/webview/advanced_view.html +1808 -0
- package/src/webview/horizon_panel.html +12397 -0
- package/src/webview/registry.mjs +80 -0
- package/src/webview/simple_view.html +1370 -0
|
@@ -0,0 +1,518 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Prompt Sufficiency Rubric (adapted from analyze-project.md Step 4).
|
|
3
|
+
* Evaluates prompt quality deterministically across 6 dimensions (0-2 each, total 12).
|
|
4
|
+
*
|
|
5
|
+
* Ground Rule: "Short prompts are not bad by default" - concise scoped instructions
|
|
6
|
+
* targeting existing active-set files should not be penalised.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
export const RUBRIC_DIMENSIONS = [
|
|
10
|
+
'clarity',
|
|
11
|
+
'boundedness',
|
|
12
|
+
'testability',
|
|
13
|
+
'architecturalSpecificity',
|
|
14
|
+
'constraintAwareness',
|
|
15
|
+
'dependencyAwareness'
|
|
16
|
+
];
|
|
17
|
+
|
|
18
|
+
export const SUFFICIENCY_BANDS = {
|
|
19
|
+
HIGH: 'High',
|
|
20
|
+
MEDIUM: 'Medium',
|
|
21
|
+
LOW: 'Low'
|
|
22
|
+
};
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* Deterministically scores a user prompt against the 6 sufficiency dimensions.
|
|
26
|
+
* @param {string} promptText
|
|
27
|
+
* @param {Object} context
|
|
28
|
+
* @param {string[]} [context.activeSetPaths=[]]
|
|
29
|
+
* @returns {Object} { score: number, band: string, dims: Object, missing: string[], shortPrompt: boolean }
|
|
30
|
+
*/
|
|
31
|
+
export function scorePromptSufficiency(promptText = '', { activeSetPaths = [] } = {}) {
|
|
32
|
+
const text = String(promptText || '').trim();
|
|
33
|
+
const lower = text.toLowerCase();
|
|
34
|
+
|
|
35
|
+
const tokenCountEst = Math.max(1, Math.ceil(text.length / 4));
|
|
36
|
+
|
|
37
|
+
// Detect explicit file/symbol targets
|
|
38
|
+
const hasFilePath = /(@[\w./\\-]+|\b[\w-]+\.(mjs|js|ts|json|md|py|go|rs|html|css)\b|[/\\][\w.-]+)/i.test(text);
|
|
39
|
+
const hasSymbol = /\b[a-zA-Z_]\w+\([^)]*\)|\b[A-Z][a-zA-Z0-9]+\b/.test(text);
|
|
40
|
+
const matchesActiveSet = (activeSetPaths || []).some(p => {
|
|
41
|
+
const base = p.split(/[/\\]/).pop();
|
|
42
|
+
return base && (lower.includes(base.toLowerCase()) || text.includes(p));
|
|
43
|
+
});
|
|
44
|
+
|
|
45
|
+
const isShort = tokenCountEst <= 18;
|
|
46
|
+
const shortPrompt = isShort && (hasFilePath || matchesActiveSet || /^(fix|yes|no|proceed|continue|run|test|compact)\b/i.test(text));
|
|
47
|
+
|
|
48
|
+
const dims = {
|
|
49
|
+
clarity: 0,
|
|
50
|
+
boundedness: 0,
|
|
51
|
+
testability: 0,
|
|
52
|
+
architecturalSpecificity: 0,
|
|
53
|
+
constraintAwareness: 0,
|
|
54
|
+
dependencyAwareness: 0
|
|
55
|
+
};
|
|
56
|
+
|
|
57
|
+
const missing = [];
|
|
58
|
+
|
|
59
|
+
// 1. Clarity (0-2): Action verb + clear object, penalise floating vague pronouns
|
|
60
|
+
const hasActionVerb = /\b(add|create|update|modify|refactor|fix|remove|delete|implement|wire|extract|replace|audit|check)\b/i.test(text);
|
|
61
|
+
const vagueCatchAll = /\b(everything|all|stuff|things|broken|make it work|fix this|do it)\b/i.test(lower);
|
|
62
|
+
if (hasActionVerb && !vagueCatchAll) {
|
|
63
|
+
dims.clarity = 2;
|
|
64
|
+
} else if (hasActionVerb || (text.length > 10 && !vagueCatchAll)) {
|
|
65
|
+
dims.clarity = 1;
|
|
66
|
+
} else {
|
|
67
|
+
dims.clarity = 0;
|
|
68
|
+
missing.push('clear action verb & concrete scope');
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
// 2. Boundedness (0-2): explicit scope boundaries
|
|
72
|
+
const hasNegativeBoundary = /\b(do not|don't|only|leave alone|without touching|out of scope|non-goal|avoid|preserve)\b/i.test(lower);
|
|
73
|
+
const hasSingleTarget = (hasFilePath && !/\b(all files|entire codebase|everywhere)\b/i.test(lower));
|
|
74
|
+
if (hasNegativeBoundary) {
|
|
75
|
+
dims.boundedness = 2;
|
|
76
|
+
} else if (hasSingleTarget || shortPrompt) {
|
|
77
|
+
dims.boundedness = 1;
|
|
78
|
+
} else {
|
|
79
|
+
dims.boundedness = 0;
|
|
80
|
+
missing.push('scope boundaries (what NOT to touch)');
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
// 3. Testability (0-2): explicit verification criteria
|
|
84
|
+
const hasVerificationSpec = /\b(test|tests|verify|verification|acceptance criteria|should pass|assert|exit code|exit 0|spec|benchmark)\b/i.test(lower);
|
|
85
|
+
const hasExpectedOutput = /\b(expect|expected|result should be|returns|outputs)\b/i.test(lower);
|
|
86
|
+
if (hasVerificationSpec && hasExpectedOutput) {
|
|
87
|
+
dims.testability = 2;
|
|
88
|
+
} else if (hasVerificationSpec || hasExpectedOutput) {
|
|
89
|
+
dims.testability = 1;
|
|
90
|
+
} else {
|
|
91
|
+
dims.testability = 0;
|
|
92
|
+
missing.push('testability & expected outcome');
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
// 4. Architectural Specificity (0-2): target files or code symbols
|
|
96
|
+
if (hasFilePath && hasSymbol) {
|
|
97
|
+
dims.architecturalSpecificity = 2;
|
|
98
|
+
} else if (hasFilePath || matchesActiveSet || hasSymbol) {
|
|
99
|
+
dims.architecturalSpecificity = 1;
|
|
100
|
+
} else {
|
|
101
|
+
dims.architecturalSpecificity = 0;
|
|
102
|
+
missing.push('file/symbol target (@file or function)');
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
// 5. Constraint Awareness (0-2): explicit operational invariants
|
|
106
|
+
const hasHardConstraints = /\b(must|must not|cannot|without adding|zero[- ]dep|strict|<15ms|backward compatible|parity|invariant)\b/i.test(lower);
|
|
107
|
+
const hasSoftConstraints = /\b(keep|ensure|make sure|prefer|clean|minimal)\b/i.test(lower);
|
|
108
|
+
if (hasHardConstraints) {
|
|
109
|
+
dims.constraintAwareness = 2;
|
|
110
|
+
} else if (hasSoftConstraints) {
|
|
111
|
+
dims.constraintAwareness = 1;
|
|
112
|
+
} else {
|
|
113
|
+
dims.constraintAwareness = 0;
|
|
114
|
+
missing.push('invariants or operational constraints');
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
// 6. Dependency Awareness (0-2): downstream callers, imports, mirrors
|
|
118
|
+
const hasDepTerms = /\b(caller|callers|import|imports|importer|importers|dependent|downstream|consumer|mirror|mirrors|sidecar|sync)\b/i.test(lower);
|
|
119
|
+
const hasCrossFileMention = (text.match(/[\w-]+\.(mjs|js|ts|json|md)/g) || []).length >= 2;
|
|
120
|
+
if (hasDepTerms && hasCrossFileMention) {
|
|
121
|
+
dims.dependencyAwareness = 2;
|
|
122
|
+
} else if (hasDepTerms || hasCrossFileMention) {
|
|
123
|
+
dims.dependencyAwareness = 1;
|
|
124
|
+
} else {
|
|
125
|
+
dims.dependencyAwareness = 0;
|
|
126
|
+
missing.push('dependency / caller considerations');
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
// Total Score (0-12)
|
|
130
|
+
const score = Object.values(dims).reduce((sum, v) => sum + v, 0);
|
|
131
|
+
|
|
132
|
+
let band = SUFFICIENCY_BANDS.LOW;
|
|
133
|
+
if (score >= 9) {
|
|
134
|
+
band = SUFFICIENCY_BANDS.HIGH;
|
|
135
|
+
} else if (score >= 5) {
|
|
136
|
+
band = SUFFICIENCY_BANDS.MEDIUM;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
return {
|
|
140
|
+
score,
|
|
141
|
+
band,
|
|
142
|
+
dims,
|
|
143
|
+
missing,
|
|
144
|
+
shortPrompt
|
|
145
|
+
};
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
export const COMPACTION_ADVISORY_MESSAGES = Object.freeze({
|
|
149
|
+
DEFER_WARM:
|
|
150
|
+
'Cache is currently warm (95% token cost discount). Defer compaction until work pause to avoid 70s execution stall and complete KV cache invalidation.',
|
|
151
|
+
COMPACT_NOW:
|
|
152
|
+
'Cache expired. Run parameterized compaction now before firing next turn.',
|
|
153
|
+
LEAN_NO_COMPACT:
|
|
154
|
+
'Session is lean \u2014 no compaction needed until >50k tokens'
|
|
155
|
+
});
|
|
156
|
+
|
|
157
|
+
export const LEAN_SESSION_MIN_TOKENS = 50000;
|
|
158
|
+
export const LEAN_SESSION_MIN_SLUDGE = 25000;
|
|
159
|
+
|
|
160
|
+
/** True when compaction is worth its ~70s stall: >=50k active, >=25k reclaimable, or past the safe horizon. */
|
|
161
|
+
export function isCompactionRelevant({ totalActiveTokens = 0, sludgeTokens = 0, safeHorizonTokens = 179000 } = {}) {
|
|
162
|
+
return Number(totalActiveTokens) > Number(safeHorizonTokens || 179000) ||
|
|
163
|
+
Number(totalActiveTokens) >= LEAN_SESSION_MIN_TOKENS ||
|
|
164
|
+
Number(sludgeTokens) >= LEAN_SESSION_MIN_SLUDGE;
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/**
|
|
168
|
+
* Returns true if a file path is an internal Antigravity telemetry/hydration log
|
|
169
|
+
* or brain artifact path that must be excluded from active workspace AST lists.
|
|
170
|
+
*/
|
|
171
|
+
export function isInternalTelemetryPath(p) {
|
|
172
|
+
if (!p) return true;
|
|
173
|
+
const s = String(p).trim().replace(/\\/g, '/');
|
|
174
|
+
if (!s || s.includes('Older chat history')) return true;
|
|
175
|
+
if (/\.system_generated(\/|$)/i.test(s)) return true;
|
|
176
|
+
if (/(^|\/)\.gemini\/antigravity[^/]*\/brain(\/|$)/i.test(s)) return true;
|
|
177
|
+
if (/(^|\/)steps\/\d+\/output\.txt$/i.test(s)) return true;
|
|
178
|
+
if (/^\d+\/output\.txt$/i.test(s)) return true;
|
|
179
|
+
return false;
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
const WORKSPACE_TOP_LEVEL_DIRS = new Set([
|
|
183
|
+
'src', 'tests', 'test', 'scripts', 'docs', 'lib', 'app', 'packages', 'config',
|
|
184
|
+
'sidecars', 'skills', 'rules', 'public', 'assets', 'bin', 'tools', 'examples'
|
|
185
|
+
]);
|
|
186
|
+
|
|
187
|
+
/**
|
|
188
|
+
* formats a file path as a clean workspace-relative path (no `.../` prefixes).
|
|
189
|
+
* Prefers stripping `workspaceRoot`; otherwise anchors on a well-known top-level directory
|
|
190
|
+
* (src/, tests/, scripts/, ...); otherwise falls back to the last two path segments.
|
|
191
|
+
*/
|
|
192
|
+
export function toWorkspaceRelativePath(p, workspaceRoot = '') {
|
|
193
|
+
if (!p) return '';
|
|
194
|
+
let s = String(p).trim().replace(/\\/g, '/').replace(/^file:\/\/\/?/i, '');
|
|
195
|
+
s = s.replace(/^(\.\.\.\/)+/, '').replace(/^\.\//, '');
|
|
196
|
+
const root = String(workspaceRoot || '').trim().replace(/\\/g, '/').replace(/\/+$/, '');
|
|
197
|
+
if (root && s.toLowerCase().startsWith(root.toLowerCase() + '/')) {
|
|
198
|
+
return s.slice(root.length + 1);
|
|
199
|
+
}
|
|
200
|
+
const segs = s.split('/').filter(Boolean);
|
|
201
|
+
if (segs.length <= 1) return segs.join('/');
|
|
202
|
+
const isAbsolute = /^([a-zA-Z]:|\/)/.test(s);
|
|
203
|
+
if (!isAbsolute) return segs.join('/');
|
|
204
|
+
for (let i = segs.length - 2; i >= 0; i--) {
|
|
205
|
+
if (WORKSPACE_TOP_LEVEL_DIRS.has(segs[i].toLowerCase())) {
|
|
206
|
+
// Use the outermost matching anchor (e.g. src/webview/x.html, not webview/x.html)
|
|
207
|
+
let j = i;
|
|
208
|
+
for (let k = i - 1; k >= 0; k--) {
|
|
209
|
+
if (WORKSPACE_TOP_LEVEL_DIRS.has(segs[k].toLowerCase())) j = k;
|
|
210
|
+
}
|
|
211
|
+
return segs.slice(j).join('/');
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
return segs.slice(-2).join('/');
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
/**
|
|
218
|
+
* sanitizes a raw user message into a concise constraint clause.
|
|
219
|
+
* Strips `/plan` (and other slash-command) headers, artifact/file URIs, XML-ish wrapper tags and
|
|
220
|
+
* markdown headers, then truncates cleanly at a word boundary within `maxLen` characters.
|
|
221
|
+
* Returns '' when nothing meaningful remains.
|
|
222
|
+
*/
|
|
223
|
+
export function sanitizeUserConstraintText(raw, maxLen = 90) {
|
|
224
|
+
if (typeof raw !== 'string') return '';
|
|
225
|
+
let txt = raw
|
|
226
|
+
.replace(/<ADDITIONAL_METADATA>[\s\S]*?<\/ADDITIONAL_METADATA>/gi, ' ')
|
|
227
|
+
.replace(/<USER_SETTINGS_CHANGE>[\s\S]*?<\/USER_SETTINGS_CHANGE>/gi, ' ')
|
|
228
|
+
.replace(/<\/?[A-Za-z_][\w-]*[^>]*>/g, ' ')
|
|
229
|
+
.split(/\r?\n/)
|
|
230
|
+
.map(line => line.trim())
|
|
231
|
+
.filter(line => line && !/^\/[a-z][\w-]*\b/i.test(line) && !/^#{1,6}\s/.test(line))
|
|
232
|
+
.join(' ')
|
|
233
|
+
.replace(/\b[a-z][a-z0-9+.-]*:\/\/\S+/gi, ' ')
|
|
234
|
+
.replace(/\[([^\]]*)\]\(\s*\)/g, '$1')
|
|
235
|
+
.replace(/\s+/g, ' ')
|
|
236
|
+
.trim();
|
|
237
|
+
if (!txt || !/[a-z]{2,}/i.test(txt)) return '';
|
|
238
|
+
if (txt.length > maxLen) {
|
|
239
|
+
const cut = txt.slice(0, maxLen - 1);
|
|
240
|
+
const lastSpace = cut.lastIndexOf(' ');
|
|
241
|
+
txt = (lastSpace > maxLen * 0.5 ? cut.slice(0, lastSpace) : cut).replace(/[\s,;:.\-]+$/, '') + '\u2026';
|
|
242
|
+
}
|
|
243
|
+
return txt;
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
/**
|
|
247
|
+
* Synthesizes a parameterized, context-preserving /compact command
|
|
248
|
+
* pulling in active file paths and extracted in-chat user corrections.
|
|
249
|
+
*/
|
|
250
|
+
export function synthesizeParameterizedCompact({
|
|
251
|
+
activeFiles = [],
|
|
252
|
+
userCorrections = [],
|
|
253
|
+
steps = [],
|
|
254
|
+
workspaceRoot = ''
|
|
255
|
+
} = {}) {
|
|
256
|
+
const fileSet = new Set();
|
|
257
|
+
for (const f of activeFiles || []) {
|
|
258
|
+
if (!f) continue;
|
|
259
|
+
const raw = typeof f === 'string' ? f : (f.path || f.target || '');
|
|
260
|
+
if (isInternalTelemetryPath(raw)) continue;
|
|
261
|
+
const clean = toWorkspaceRelativePath(raw, workspaceRoot);
|
|
262
|
+
if (clean && !isInternalTelemetryPath(clean)) fileSet.add(clean);
|
|
263
|
+
}
|
|
264
|
+
if (fileSet.size === 0 && Array.isArray(steps)) {
|
|
265
|
+
for (let i = steps.length - 1; i >= 0 && fileSet.size < 4; i--) {
|
|
266
|
+
const calls = steps[i]?.toolCalls || [];
|
|
267
|
+
for (const c of calls) {
|
|
268
|
+
const p = c?.args?.Path || c?.args?.path || c?.args?.TargetFile;
|
|
269
|
+
if (p && typeof p === 'string' && !isInternalTelemetryPath(p)) {
|
|
270
|
+
const clean = toWorkspaceRelativePath(p, workspaceRoot);
|
|
271
|
+
if (clean && !isInternalTelemetryPath(clean)) fileSet.add(clean);
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
const filesList = fileSet.size > 0
|
|
277
|
+
? Array.from(fileSet).slice(0, 4).join(', ')
|
|
278
|
+
: 'active workspace files';
|
|
279
|
+
|
|
280
|
+
const constraintsSet = new Set();
|
|
281
|
+
if (Array.isArray(userCorrections)) {
|
|
282
|
+
for (const corr of userCorrections) {
|
|
283
|
+
const clean = sanitizeUserConstraintText(corr, 90);
|
|
284
|
+
if (clean) constraintsSet.add(clean);
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
if (constraintsSet.size === 0 && Array.isArray(steps)) {
|
|
288
|
+
for (const s of steps) {
|
|
289
|
+
if (s?.source === 'USER_EXPLICIT' || s?.type === 'USER_INPUT') {
|
|
290
|
+
const txt = String(s.content || '').trim();
|
|
291
|
+
if (/\b(no[, ]|don't|do not|instead|wrong|must|never|strictly|preserve)\b/i.test(txt)) {
|
|
292
|
+
const clean = sanitizeUserConstraintText(txt, 90);
|
|
293
|
+
if (clean) constraintsSet.add(clean);
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
const base = `/compact Focus on preserving: 1) Exported symbol signatures and state scales for [${filesList}], 2) Current checklist state in task.md`;
|
|
300
|
+
if (constraintsSet.size === 0) {
|
|
301
|
+
// No valid user constraint text: omit clause 3 entirely rather than emitting a placeholder.
|
|
302
|
+
return `${base}.`;
|
|
303
|
+
}
|
|
304
|
+
const constraintsList = Array.from(constraintsSet).slice(0, 3).join('; ');
|
|
305
|
+
return `${base}, 3) Explicit user constraints: [${constraintsList}].`;
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
/**
|
|
309
|
+
* Evaluates Cache-Aware Compaction Advisory.
|
|
310
|
+
* - If Cache TTL > 0s and totalActiveTokens <= 179k: Defer compaction until work pause.
|
|
311
|
+
* - If Cache TTL == 0s OR totalActiveTokens > 179k: Run parameterized compaction now.
|
|
312
|
+
* - when `isCacheTrulyWarm === false` (0 cache reads / 0% hit / prefix bust), never DEFER_WARM.
|
|
313
|
+
*/
|
|
314
|
+
export function evaluateCompactionCacheAdvisory({
|
|
315
|
+
cacheTtlRemainingSec = 300,
|
|
316
|
+
totalActiveTokens = 0,
|
|
317
|
+
safeHorizonTokens = 179000,
|
|
318
|
+
isCacheTrulyWarm,
|
|
319
|
+
nextTurnLikelyWarm,
|
|
320
|
+
sludgeTokens = 0
|
|
321
|
+
} = {}) {
|
|
322
|
+
if (!isCompactionRelevant({ totalActiveTokens, sludgeTokens, safeHorizonTokens })) {
|
|
323
|
+
return {
|
|
324
|
+
state: 'LEAN_NO_COMPACT',
|
|
325
|
+
domState: 'lean-no-compact',
|
|
326
|
+
message: COMPACTION_ADVISORY_MESSAGES.LEAN_NO_COMPACT
|
|
327
|
+
};
|
|
328
|
+
}
|
|
329
|
+
// a turn that missed the cache wrote a fresh prefix, so the *next* turn is likely warm.
|
|
330
|
+
// When `nextTurnLikelyWarm` is supplied it supersedes the strict badge predicate for this advisory.
|
|
331
|
+
const warmEvidence = typeof nextTurnLikelyWarm === 'boolean' ? nextTurnLikelyWarm : isCacheTrulyWarm;
|
|
332
|
+
const isExpiredOrOverHorizon = warmEvidence === false ||
|
|
333
|
+
Number(cacheTtlRemainingSec) <= 0 || Number(totalActiveTokens) > Number(safeHorizonTokens || 179000);
|
|
334
|
+
if (isExpiredOrOverHorizon) {
|
|
335
|
+
return {
|
|
336
|
+
state: 'COMPACT_NOW',
|
|
337
|
+
domState: 'cold-compact-now',
|
|
338
|
+
message: COMPACTION_ADVISORY_MESSAGES.COMPACT_NOW
|
|
339
|
+
};
|
|
340
|
+
}
|
|
341
|
+
return {
|
|
342
|
+
state: 'DEFER_WARM',
|
|
343
|
+
domState: 'warm-defer',
|
|
344
|
+
message: COMPACTION_ADVISORY_MESSAGES.DEFER_WARM
|
|
345
|
+
};
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
/**
|
|
349
|
+
* Synthesizes The Baton Pass (/handoff) workflow command and target path.
|
|
350
|
+
*/
|
|
351
|
+
export function synthesizeBatonPassHandoffCommand({
|
|
352
|
+
timestamp = null,
|
|
353
|
+
activeFiles = [],
|
|
354
|
+
pendingTasks = []
|
|
355
|
+
} = {}) {
|
|
356
|
+
const ts = timestamp || new Date().toISOString().replace(/[:.]/g, '-').slice(0, 19);
|
|
357
|
+
const handoffFile = `docs/HANDOFF_${ts}.md`;
|
|
358
|
+
const cleanActive = (activeFiles || [])
|
|
359
|
+
.map(f => typeof f === 'string' ? f : (f?.path || f?.target || ''))
|
|
360
|
+
.filter(p => p && !isInternalTelemetryPath(p));
|
|
361
|
+
const filesSummary = cleanActive.length > 0
|
|
362
|
+
? cleanActive.slice(0, 5).join(', ')
|
|
363
|
+
: 'active workspace modules';
|
|
364
|
+
const tasksSummary = (pendingTasks && pendingTasks.length > 0)
|
|
365
|
+
? pendingTasks.slice(0, 3).join('; ')
|
|
366
|
+
: 'remaining checklist items in task.md';
|
|
367
|
+
|
|
368
|
+
const command = `/handoff Summarize active AST contracts (${filesSummary}), latest test verification states, and pending task.md items (${tasksSummary}) into ${handoffFile} so a fresh chat can pick up from a written summary.`;
|
|
369
|
+
return {
|
|
370
|
+
timestamp: ts,
|
|
371
|
+
handoffFile,
|
|
372
|
+
command
|
|
373
|
+
};
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
function fmtKShort(tokens) {
|
|
377
|
+
const n = Math.max(0, Number(tokens) || 0);
|
|
378
|
+
if (n <= 0) return '0k';
|
|
379
|
+
return (n / 1000).toFixed(1).replace(/\.0$/, '') + 'k';
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
function fmtMmSs(seconds) {
|
|
383
|
+
const s = Math.max(0, Math.floor(Number(seconds) || 0));
|
|
384
|
+
const m = Math.floor(s / 60);
|
|
385
|
+
const rem = s % 60;
|
|
386
|
+
return m > 0 ? `${m}m ${String(rem).padStart(2, '0')}s` : `${rem}s`;
|
|
387
|
+
}
|
|
388
|
+
|
|
389
|
+
/**
|
|
390
|
+
* Computes a single deterministic top-level Tufte verdict line resolving
|
|
391
|
+
* the trade-off between KV-cache warmth (300s TTL), Effort-Adaptive Safe Limit (e.g. 147k High),
|
|
392
|
+
* and active DET-* circuit breakers.
|
|
393
|
+
*/
|
|
394
|
+
export function computeUnifiedVerdict({
|
|
395
|
+
totalActiveTokens = 0,
|
|
396
|
+
safeLimitTokens = 147000,
|
|
397
|
+
maxTokens = 256000,
|
|
398
|
+
effortShortLabel = 'High',
|
|
399
|
+
cacheTtlRemainingSec = 0,
|
|
400
|
+
isCacheWarm = false,
|
|
401
|
+
reclaimableTokens = 0,
|
|
402
|
+
activeCircuitBreaker = null,
|
|
403
|
+
routerNudgeLabel = ''
|
|
404
|
+
} = {}) {
|
|
405
|
+
const total = Math.max(0, Number(totalActiveTokens) || 0);
|
|
406
|
+
const safe = Math.max(20000, Number(safeLimitTokens) || 147000);
|
|
407
|
+
const ceiling = Math.max(safe, Number(maxTokens) || 256000);
|
|
408
|
+
const ttl = Math.max(0, Number(cacheTtlRemainingSec) || 0);
|
|
409
|
+
const warm = Boolean(isCacheWarm && ttl > 0);
|
|
410
|
+
const reclaim = Math.max(0, Number(reclaimableTokens) || 0);
|
|
411
|
+
const label = effortShortLabel || 'Auto';
|
|
412
|
+
|
|
413
|
+
// Precedence 1: Active DET-* Circuit Breaker or Imminent Hard Ceiling (>90% of maxTokens)
|
|
414
|
+
if (activeCircuitBreaker || total >= Math.round(ceiling * 0.90)) {
|
|
415
|
+
const reason = activeCircuitBreaker || `At ${fmtKShort(total)} / ${fmtKShort(ceiling)} ceiling`;
|
|
416
|
+
return {
|
|
417
|
+
state: 'CRITICAL_STOP',
|
|
418
|
+
severity: 'danger',
|
|
419
|
+
headline: `STOP & HANDOFF · ${reason} · Overrides warm cache`,
|
|
420
|
+
routerHoldNote: ''
|
|
421
|
+
};
|
|
422
|
+
}
|
|
423
|
+
|
|
424
|
+
// Precedence 2: Over Effort-Adaptive Safe Limit while Cache is Warm -> HOLD COMPACT
|
|
425
|
+
if (total > safe && warm) {
|
|
426
|
+
const overStr = fmtKShort(total - safe);
|
|
427
|
+
return {
|
|
428
|
+
state: 'HOLD_COMPACT',
|
|
429
|
+
severity: 'warn',
|
|
430
|
+
headline: `HOLD COMPACT · Cache warm ${fmtMmSs(ttl)} · +${overStr} over ${label}`,
|
|
431
|
+
routerHoldNote: routerNudgeLabel ? `${routerNudgeLabel} (held while cache warm)` : ''
|
|
432
|
+
};
|
|
433
|
+
}
|
|
434
|
+
|
|
435
|
+
// Precedence 3: Over Safe Limit or High Reclaimable Sludge (>=25k on >=50k session) with Cold Cache -> COMPACT NOW
|
|
436
|
+
if (total > safe || (total >= LEAN_SESSION_MIN_TOKENS && reclaim >= LEAN_SESSION_MIN_SLUDGE)) {
|
|
437
|
+
if (!warm) {
|
|
438
|
+
const recStr = fmtKShort(reclaim > 0 ? reclaim : Math.max(1000, total - safe));
|
|
439
|
+
return {
|
|
440
|
+
state: 'COMPACT_NOW',
|
|
441
|
+
severity: 'amber',
|
|
442
|
+
headline: `COMPACT NOW · Cache cold · Reclaim ${recStr}`,
|
|
443
|
+
routerHoldNote: routerNudgeLabel || ''
|
|
444
|
+
};
|
|
445
|
+
}
|
|
446
|
+
return {
|
|
447
|
+
state: 'HOLD_COMPACT',
|
|
448
|
+
severity: 'warn',
|
|
449
|
+
headline: `HOLD COMPACT · Cache warm ${fmtMmSs(ttl)} · ${fmtKShort(reclaim)} staged`,
|
|
450
|
+
routerHoldNote: routerNudgeLabel ? `${routerNudgeLabel} (held while cache warm)` : ''
|
|
451
|
+
};
|
|
452
|
+
}
|
|
453
|
+
|
|
454
|
+
// Precedence 4: Nominal
|
|
455
|
+
const headroomStr = fmtKShort(Math.max(0, safe - total));
|
|
456
|
+
const cachePart = warm ? `Cache warm ${fmtMmSs(ttl)}` : 'Cache cold';
|
|
457
|
+
return {
|
|
458
|
+
state: 'NOMINAL',
|
|
459
|
+
severity: 'ok',
|
|
460
|
+
headline: `NOMINAL · ${cachePart} · ${headroomStr} to ${label} cap`,
|
|
461
|
+
routerHoldNote: routerNudgeLabel
|
|
462
|
+
? (warm ? `${routerNudgeLabel} (locked ${fmtMmSs(ttl)})` : routerNudgeLabel)
|
|
463
|
+
: ''
|
|
464
|
+
};
|
|
465
|
+
}
|
|
466
|
+
|
|
467
|
+
const SPARK_GLYPHS = ['\u2581', '\u2582', '\u2583', '\u2584', '\u2585', '\u2586', '\u2587', '\u2588'];
|
|
468
|
+
|
|
469
|
+
/**
|
|
470
|
+
* Renders a 16-turn inline Unicode sparkline of per-turn token growth.
|
|
471
|
+
*/
|
|
472
|
+
export function buildTurnVelocitySparkline(turnDeltas = [], maxTurns = 16) {
|
|
473
|
+
const arr = Array.isArray(turnDeltas)
|
|
474
|
+
? turnDeltas.map(n => Math.max(0, Number(n) || 0)).slice(-maxTurns)
|
|
475
|
+
: [];
|
|
476
|
+
if (arr.length === 0) return '';
|
|
477
|
+
const peak = Math.max(...arr, 1000);
|
|
478
|
+
return arr.map(val => {
|
|
479
|
+
if (val <= 0) return SPARK_GLYPHS[0];
|
|
480
|
+
const idx = Math.min(SPARK_GLYPHS.length - 1, Math.max(0, Math.floor((val / peak) * (SPARK_GLYPHS.length - 1))));
|
|
481
|
+
return SPARK_GLYPHS[idx];
|
|
482
|
+
}).join('');
|
|
483
|
+
}
|
|
484
|
+
|
|
485
|
+
/**
|
|
486
|
+
* Accounts for 100% of a single turn's token delta (e.g. "write 5.5k + 4 tool steps 46.6k")
|
|
487
|
+
* so there is never an unexplained gap between the total delta and the single largest step.
|
|
488
|
+
*/
|
|
489
|
+
export function formatFullTurnDeltaAccounting(delta = {}) {
|
|
490
|
+
const total = Math.max(0, Number(delta?.tokens) || 0);
|
|
491
|
+
if (total < 100) return '';
|
|
492
|
+
if (typeof delta?.accountingSummary === 'string' && delta.accountingSummary.trim()) {
|
|
493
|
+
return delta.accountingSummary.trim();
|
|
494
|
+
}
|
|
495
|
+
const writeTok = Number(delta?.writeTokens ?? delta?.promptAndResponseTokens ?? 0);
|
|
496
|
+
const toolTok = Number(delta?.toolTokens ?? 0);
|
|
497
|
+
const toolCount = Number(delta?.toolStepCount ?? delta?.toolCallsCount ?? 0);
|
|
498
|
+
if (writeTok > 0 && toolTok > 0) {
|
|
499
|
+
const stepLabel = toolCount > 0 ? `${toolCount} tool step${toolCount === 1 ? '' : 's'}` : 'tools';
|
|
500
|
+
return `write ${fmtKShort(writeTok)} + ${stepLabel} ${fmtKShort(toolTok)}`;
|
|
501
|
+
}
|
|
502
|
+
const topTok = Math.min(total, Math.max(0, Number(delta?.topSource?.tokens) || 0));
|
|
503
|
+
const topLabel = String(delta?.topSource?.label || '').trim();
|
|
504
|
+
if (topTok > 0 && topTok < total * 0.88) {
|
|
505
|
+
const restTok = Math.max(0, total - topTok);
|
|
506
|
+
const stepCount = Math.max(1, Number(delta?.stepCount || toolCount || 2) - 1);
|
|
507
|
+
const cleanTop = /^(planner response|model response|agent response)$/i.test(topLabel)
|
|
508
|
+
? 'write'
|
|
509
|
+
: (topLabel ? topLabel.split(/[\\/]/).pop().slice(0, 18) : 'top step');
|
|
510
|
+
return `${cleanTop} ${fmtKShort(topTok)} + ${stepCount} step${stepCount === 1 ? '' : 's'} ${fmtKShort(restTok)}`;
|
|
511
|
+
}
|
|
512
|
+
if (topLabel) {
|
|
513
|
+
const cleanTop = /^(planner response|model response)$/i.test(topLabel) ? 'agent response' : topLabel.split(/[\\/]/).pop();
|
|
514
|
+
return `${cleanTop} (${fmtKShort(topTok || total)})`;
|
|
515
|
+
}
|
|
516
|
+
return `${fmtKShort(total)} across turn`;
|
|
517
|
+
}
|
|
518
|
+
|