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.
Files changed (240) hide show
  1. package/.antigravity-plugin/plugin.json +36 -0
  2. package/.claude-plugin/plugin.json +18 -0
  3. package/CHECKSUMS.sha256 +149 -0
  4. package/LICENSE +27 -0
  5. package/README.md +330 -3
  6. package/SECURITY.md +22 -0
  7. package/agents/ah-flash-scout.md +25 -0
  8. package/assets/advanced_view_loaded_420px.png +0 -0
  9. package/assets/hero-demo.svg +188 -0
  10. package/assets/logo.svg +19 -0
  11. package/assets/simple_view_lean_420px.png +0 -0
  12. package/assets/simple_view_loaded_420px.png +0 -0
  13. package/assets/social-preview.svg +72 -0
  14. package/assets/zone_c_step3_shield_full.png +0 -0
  15. package/bin/ah-statusline.mjs +145 -0
  16. package/bin/cli.mjs +3 -0
  17. package/bin/ctxtop.mjs +1474 -0
  18. package/commands/cost-radar.md +11 -0
  19. package/commands/evolve.md +10 -0
  20. package/commands/handoff.md +10 -0
  21. package/commands/horizon.md +10 -0
  22. package/commands/inspect.md +10 -0
  23. package/commands/precheck.md +10 -0
  24. package/config/default_flightcheck.json +114 -0
  25. package/config/modelCatalog.json +620 -0
  26. package/config/platformQuirks.json +19 -0
  27. package/hooks/handlers/compact-lifecycle.mjs +262 -0
  28. package/hooks/handlers/hookIo.mjs +255 -0
  29. package/hooks/handlers/hookIpcClient.mjs +83 -0
  30. package/hooks/handlers/post-tool-use.mjs +265 -0
  31. package/hooks/handlers/pre-model-switch.mjs +249 -0
  32. package/hooks/handlers/pre-tool-use.mjs +365 -0
  33. package/hooks/handlers/stop-gate.mjs +240 -0
  34. package/hooks/handlers/user-prompt-submit.mjs +143 -0
  35. package/hooks/hooks.json +81 -0
  36. package/hooks/post_invocation.mjs +13 -0
  37. package/hooks/post_tool_use.mjs +17 -0
  38. package/hooks/pre_invocation.mjs +14 -0
  39. package/hooks/pre_tool_use.mjs +97 -0
  40. package/hooks/register.js +687 -0
  41. package/hooks/session_start.mjs +14 -0
  42. package/hooks/stop.mjs +13 -0
  43. package/hooks.json +56 -0
  44. package/package.json +103 -4
  45. package/packages/antigravity/package.json +14 -0
  46. package/packages/antigravity/src/index.mjs +1 -0
  47. package/packages/claude-code/package.json +14 -0
  48. package/packages/claude-code/src/index.mjs +2 -0
  49. package/packages/core/package.json +14 -0
  50. package/packages/core/src/index.mjs +1 -0
  51. package/packages/engine-node/package.json +14 -0
  52. package/packages/engine-node/src/index.mjs +1 -0
  53. package/packages/mcp/package.json +17 -0
  54. package/packages/mcp/src/server.mjs +396 -0
  55. package/packages/pro/LICENSE-COMMERCIAL.md +19 -0
  56. package/packages/pro/README-SIGNING.md +30 -0
  57. package/packages/pro/package.json +16 -0
  58. package/packages/pro/src/index.mjs +3 -0
  59. package/packages/pro/src/team_finops_pack.mjs +241 -0
  60. package/packages/pro/workers/polar_webhook_worker.mjs +215 -0
  61. package/plugin.json +36 -0
  62. package/rules/AGENTS.md +10 -0
  63. package/sidecars/horizon-daemon/ipcServer.mjs +24 -0
  64. package/sidecars/horizon-daemon/server.mjs +2002 -0
  65. package/sidecars/horizon-daemon/sidecar.json +19 -0
  66. package/skills/cost-radar/SKILL.md +21 -0
  67. package/skills/evolve/SKILL.md +21 -0
  68. package/skills/handoff/SKILL.md +42 -0
  69. package/skills/horizon/SKILL.md +17 -0
  70. package/skills/inspect/SKILL.md +18 -0
  71. package/skills/precheck/SKILL.md +44 -0
  72. package/src/adapters/antigravity/index.mjs +79 -0
  73. package/src/adapters/claude-code/index.mjs +155 -0
  74. package/src/cli/cost_radar.mjs +70 -0
  75. package/src/cli/doctor.mjs +351 -0
  76. package/src/cli/horizon_hud.mjs +686 -0
  77. package/src/cli/init.mjs +425 -0
  78. package/src/cli/postmortem.mjs +515 -0
  79. package/src/coach/cacheGravityRouter.mjs +12 -0
  80. package/src/config/modelCatalog.json +620 -0
  81. package/src/config/platformQuirks.json +19 -0
  82. package/src/core/action_queue.mjs +264 -0
  83. package/src/core/ag_bridge.mjs +346 -0
  84. package/src/core/atomic_io.mjs +124 -0
  85. package/src/core/baseline.mjs +607 -0
  86. package/src/core/blindspot_sensors.mjs +399 -0
  87. package/src/core/classifier.mjs +1757 -0
  88. package/src/core/coach/circuit_breakers.mjs +650 -0
  89. package/src/core/coach/contradiction_auditor.mjs +239 -0
  90. package/src/core/coach/effort_advisor.mjs +143 -0
  91. package/src/core/coach/handoff_hydrator.mjs +483 -0
  92. package/src/core/coach/progressive_checkpointer.mjs +551 -0
  93. package/src/core/coach/prompt_decomposer_coach.mjs +141 -0
  94. package/src/core/coach/reflector_queue.mjs +505 -0
  95. package/src/core/coach/saved_quota_ledger.mjs +615 -0
  96. package/src/core/coach/subagent_ipi_sanitizer.mjs +200 -0
  97. package/src/core/coach/subagent_phantom_auditor.mjs +261 -0
  98. package/src/core/coach/task_quota_router.mjs +955 -0
  99. package/src/core/coach/turn_zero_gate.mjs +574 -0
  100. package/src/core/compaction_coach.mjs +1126 -0
  101. package/src/core/config.mjs +214 -0
  102. package/src/core/constants.mjs +1800 -0
  103. package/src/core/detectors_det01_to_16.mjs +1474 -0
  104. package/src/core/episodic_memory.mjs +135 -0
  105. package/src/core/fts5_output_compressor.mjs +359 -0
  106. package/src/core/git_ledger.mjs +189 -0
  107. package/src/core/handoff_audit.mjs +558 -0
  108. package/src/core/history.mjs +221 -0
  109. package/src/core/hook_diagnostics.mjs +158 -0
  110. package/src/core/horizon_classifier.mjs +326 -0
  111. package/src/core/horizon_config.mjs +802 -0
  112. package/src/core/host_watchdog.mjs +200 -0
  113. package/src/core/layer5_hygiene.mjs +966 -0
  114. package/src/core/log_resolver.mjs +231 -0
  115. package/src/core/mcp_auditor.mjs +138 -0
  116. package/src/core/micro_skills_store.mjs +91 -0
  117. package/src/core/offenders.mjs +161 -0
  118. package/src/core/parser.mjs +1996 -0
  119. package/src/core/path_canonicalizer.mjs +73 -0
  120. package/src/core/paths.mjs +310 -0
  121. package/src/core/prefix_cache_shield.mjs +386 -0
  122. package/src/core/pro_license.mjs +385 -0
  123. package/src/core/prompt_rubric.mjs +518 -0
  124. package/src/core/pruner.mjs +433 -0
  125. package/src/core/quota.mjs +1860 -0
  126. package/src/core/rsi_instinct_engine.mjs +1197 -0
  127. package/src/core/sanitizer.mjs +121 -0
  128. package/src/core/session_forensics.mjs +303 -0
  129. package/src/core/session_timeline.mjs +358 -0
  130. package/src/core/settings.mjs +99 -0
  131. package/src/core/shared/detectors.mjs +1342 -0
  132. package/src/core/shared/fnv1a64.mjs +85 -0
  133. package/src/core/shared/handoff_schema.mjs +123 -0
  134. package/src/core/shared/index.mjs +5 -0
  135. package/src/core/shared/ipi_sanitizer.mjs +165 -0
  136. package/src/core/shared/micro_skills.mjs +1 -0
  137. package/src/core/shared/plugin_validator.mjs +202 -0
  138. package/src/core/shared/prompt_hygiene_governor.mjs +1 -0
  139. package/src/core/sidecar_store.mjs +302 -0
  140. package/src/core/sprint_metrics.mjs +366 -0
  141. package/src/core/sqlite_client.mjs +283 -0
  142. package/src/core/storage_doctor.mjs +358 -0
  143. package/src/core/subagents.mjs +609 -0
  144. package/src/core/swarm_topology.mjs +360 -0
  145. package/src/core/task_quota_router.mjs +1656 -0
  146. package/src/core/telemetry/cache_ttl_watchdog.mjs +284 -0
  147. package/src/core/telemetry/scope_lock_registry.mjs +578 -0
  148. package/src/core/telemetry/shadow_file_detector.mjs +291 -0
  149. package/src/core/telemetry/trajectory_watcher.mjs +259 -0
  150. package/src/core/timeline_svg.mjs +236 -0
  151. package/src/core/tool_surgeon.mjs +305 -0
  152. package/src/core/trajectory_stitcher.mjs +645 -0
  153. package/src/core/u_shaped_optimizer.mjs +789 -0
  154. package/src/core/wal_hygiene.mjs +233 -0
  155. package/src/core-isomorphic/catalog/detectorCatalog.mjs +558 -0
  156. package/src/core-isomorphic/catalog/index.mjs +1 -0
  157. package/src/core-isomorphic/coach/cacheGravityRouter.mjs +720 -0
  158. package/src/core-isomorphic/coach/microSkills.mjs +1 -0
  159. package/src/core-isomorphic/coach/promptHygieneGovernor.mjs +1 -0
  160. package/src/core-isomorphic/coach/repoCalibration.mjs +254 -0
  161. package/src/core-isomorphic/coach/savedQuotaLedger.mjs +527 -0
  162. package/src/core-isomorphic/coach/stateBatonHydrator.mjs +810 -0
  163. package/src/core-isomorphic/coach/ttlWatchdog.mjs +457 -0
  164. package/src/core-isomorphic/config/anthropicModelCatalog.json +203 -0
  165. package/src/core-isomorphic/config/catalogLoader.mjs +768 -0
  166. package/src/core-isomorphic/config/horizonConfig.mjs +1009 -0
  167. package/src/core-isomorphic/control/callTree.mjs +338 -0
  168. package/src/core-isomorphic/control/coachLatches.mjs +126 -0
  169. package/src/core-isomorphic/control/controlStateMachine.mjs +205 -0
  170. package/src/core-isomorphic/control/index.mjs +49 -0
  171. package/src/core-isomorphic/control/swarmWorktree.mjs +109 -0
  172. package/src/core-isomorphic/control/toolSuspension.mjs +197 -0
  173. package/src/core-isomorphic/diagnostics/drift_guard.mjs +382 -0
  174. package/src/core-isomorphic/diagnostics/index.mjs +9 -0
  175. package/src/core-isomorphic/diagnostics/micro_skills.mjs +471 -0
  176. package/src/core-isomorphic/diagnostics/prompt_hygiene_governor.mjs +622 -0
  177. package/src/core-isomorphic/economics/billingBlocks.mjs +251 -0
  178. package/src/core-isomorphic/economics/cacheGravity.mjs +351 -0
  179. package/src/core-isomorphic/economics/cliffBreaker.mjs +170 -0
  180. package/src/core-isomorphic/economics/driftLatency.mjs +319 -0
  181. package/src/core-isomorphic/economics/dualTtl.mjs +198 -0
  182. package/src/core-isomorphic/economics/index.mjs +47 -0
  183. package/src/core-isomorphic/economics/retentionRadar.mjs +348 -0
  184. package/src/core-isomorphic/guards/circuitBreakers.mjs +1202 -0
  185. package/src/core-isomorphic/guards/det01_03_shell_secret.mjs +1035 -0
  186. package/src/core-isomorphic/guards/det04_12_thrash_rot.mjs +480 -0
  187. package/src/core-isomorphic/guards/det13_20_mcp_scope.mjs +603 -0
  188. package/src/core-isomorphic/guards/losslessPostSanitizer.mjs +301 -0
  189. package/src/core-isomorphic/index.js +26 -0
  190. package/src/core-isomorphic/telemetry/otelExporter.mjs +187 -0
  191. package/src/core-isomorphic/telemetry/scopeLockRegistry.mjs +522 -0
  192. package/src/core-isomorphic/telemetry/sprintMetrics.mjs +327 -0
  193. package/src/core-isomorphic/telemetry/swarmTopology.mjs +152 -0
  194. package/src/core-isomorphic/telemetry/telemetryBridge.mjs +1132 -0
  195. package/src/core-isomorphic/ui/brailleSparkline.mjs +142 -0
  196. package/src/core-isomorphic/ui/costRadarSvg.mjs +276 -0
  197. package/src/core-isomorphic/ui/horizonGrid.mjs +475 -0
  198. package/src/core-isomorphic/ui/horizonPanelHtml.mjs +1181 -0
  199. package/src/core-isomorphic/ui/modViews.mjs +1478 -0
  200. package/src/core-isomorphic/ui/pdfReceiptGenerator.mjs +329 -0
  201. package/src/core-isomorphic/ustf/index.mjs +7 -0
  202. package/src/core-isomorphic/ustf/normalizer.mjs +512 -0
  203. package/src/core-isomorphic/ustf/schema.mjs +186 -0
  204. package/src/core-isomorphic/utils/runtime.mjs +962 -0
  205. package/src/demo/synthetic_states.mjs +661 -0
  206. package/src/diagnostics/bugReportGenerator.mjs +253 -0
  207. package/src/diagnostics/doctorEngine.mjs +203 -0
  208. package/src/engine-node/db/index.mjs +58 -0
  209. package/src/engine-node/db/jsonl_fallback.mjs +184 -0
  210. package/src/engine-node/db/probe.mjs +110 -0
  211. package/src/engine-node/db/sqlite_wrapper.mjs +122 -0
  212. package/src/engine-node/index.mjs +9 -0
  213. package/src/engine-node/ipc/client.mjs +447 -0
  214. package/src/engine-node/ipc/index.mjs +22 -0
  215. package/src/engine-node/ipc/protocol.mjs +177 -0
  216. package/src/engine-node/ipc/server.mjs +445 -0
  217. package/src/engine-node/offloader/index.mjs +6 -0
  218. package/src/engine-node/offloader/tool_offloader.mjs +241 -0
  219. package/src/engine-node/sensors/blindspots.mjs +369 -0
  220. package/src/engine-node/sensors/git_merge_tree.mjs +223 -0
  221. package/src/engine-node/sensors/index.mjs +7 -0
  222. package/src/hooks/portfolio_runtime.mjs +858 -0
  223. package/src/hooks/post_invocation.mjs +419 -0
  224. package/src/hooks/pre_invocation.mjs +1015 -0
  225. package/src/hooks/session_start.mjs +161 -0
  226. package/src/shims/agy_cli_compressor.mjs +705 -0
  227. package/src/shims/agy_git_guard.mjs +749 -0
  228. package/src/shims/ah_log_query.mjs +39 -0
  229. package/src/ui/costRadarSvg.mjs +6 -0
  230. package/src/ui/horizonGrid.mjs +1 -0
  231. package/src/ui/horizonPanelHtml.mjs +1 -0
  232. package/src/ui/horizon_panel.css +167 -0
  233. package/src/ui/horizon_panel.js +212 -0
  234. package/src/ui/modViews.mjs +1 -0
  235. package/src/utils/nodeIo.mjs +59 -0
  236. package/src/utils/runtime.mjs +1 -0
  237. package/src/webview/advanced_view.html +1808 -0
  238. package/src/webview/horizon_panel.html +11389 -0
  239. package/src/webview/registry.mjs +80 -0
  240. package/src/webview/simple_view.html +1370 -0
@@ -0,0 +1,121 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { getHomeDir } from './paths.mjs';
4
+
5
+ /**
6
+ * Zero-PII Sanitized Forensic Snapshot Exporter.
7
+ *
8
+ * Scrubs API keys (`sk-ant-*`, `sk-proj-*`, `AIza*`), GitHub PATs (`ghp_*`, `github_pat_*`),
9
+ * Bearer tokens, AWS keys (`AKIA*`), `.env` assignments, and user home directory paths (`C:\Users\<user>` -> `~`)
10
+ * before exporting a shareable JSON or self-contained HTML forensic bundle.
11
+ */
12
+
13
+ const SECRET_PATTERNS = [
14
+ { name: 'anthropic_key', hint: 'sk-ant-', re: /\bsk-ant-[A-Za-z0-9_-]{8,}\b/g, replacement: '[REDACTED:ANTHROPIC_KEY]' },
15
+ { name: 'openai_key', hint: 'sk-', re: /\bsk-(?:proj-|live-)?[A-Za-z0-9_-]{16,}\b/g, replacement: '[REDACTED:OPENAI_KEY]' },
16
+ { name: 'google_api_key', hint: 'AIza', re: /\bAIza[0-9A-Za-z_-]{20,}\b/g, replacement: '[REDACTED:GOOGLE_API_KEY]' },
17
+ { name: 'github_pat', hint: 'gh', re: /\b(?:ghp|gho|ghu|ghs|ghr)_[A-Za-z0-9]{16,}\b/g, replacement: '[REDACTED:GITHUB_PAT]' },
18
+ { name: 'github_fine_pat', hint: 'github_pat_', re: /\bgithub_pat_[A-Za-z0-9_]{16,}\b/g, replacement: '[REDACTED:GITHUB_PAT]' },
19
+ { name: 'aws_access_key', hint: 'AKIA', re: /\bAKIA[0-9A-Z]{16}\b/g, replacement: '[REDACTED:AWS_KEY]' },
20
+ { name: 'bearer_token', hint: 'earer', re: /\bBearer\s+[A-Za-z0-9._~+/-]{16,}\b/gi, replacement: 'Bearer [REDACTED:TOKEN]' },
21
+ { name: 'env_secret', hint: '=', re: /\b([A-Z0-9_]*(?:SECRET|TOKEN|PASSWORD|API_KEY|PRIVATE_KEY)[A-Z0-9_]*)\s*=\s*(['"]?)[^\s'"]+\2/g, replacement: '$1=[REDACTED:ENV]' }
22
+ ];
23
+
24
+ export function sanitizeForensicPayload(input, { homeDir = getHomeDir() } = {}) {
25
+ let redactedSecretCount = 0;
26
+ let redactedPathCount = 0;
27
+
28
+ const cleanHome = String(homeDir || '').replace(/\\/g, '/').replace(/\/$/, '');
29
+ const winHome = cleanHome.replace(/\//g, '\\');
30
+
31
+ const scrubString = (str) => {
32
+ let out = String(str);
33
+ for (const pat of SECRET_PATTERNS) {
34
+ if (pat.hint) {
35
+ if (pat.name === 'bearer_token') {
36
+ if (!out.includes('earer') && !out.includes('EARER')) continue;
37
+ } else if (!out.includes(pat.hint)) {
38
+ continue;
39
+ }
40
+ }
41
+ out = out.replace(pat.re, (...args) => {
42
+ redactedSecretCount += 1;
43
+ if (pat.name === 'env_secret') {
44
+ return `${args[1]}=[REDACTED:ENV]`;
45
+ }
46
+ return pat.replacement;
47
+ });
48
+ }
49
+
50
+ if (cleanHome && cleanHome.length > 3) {
51
+ if (out.includes(cleanHome)) {
52
+ redactedPathCount += 1;
53
+ out = out.split(cleanHome).join('~');
54
+ }
55
+ if (winHome && out.includes(winHome)) {
56
+ redactedPathCount += 1;
57
+ out = out.split(winHome).join('~');
58
+ }
59
+ }
60
+
61
+ // Also scrub generic OS user paths like C:\Users\<username> or /Users/<username>
62
+ if (out.includes('Users') || out.includes('users') || out.includes('/home/')) {
63
+ out = out.replace(/(?:[A-Za-z]:[\\/]Users[\\/]|\/Users\/|\/home\/)([A-Za-z0-9._-]+)(?=[\\/])/g, () => {
64
+ redactedPathCount += 1;
65
+ return '~';
66
+ });
67
+ }
68
+
69
+ return out;
70
+ };
71
+
72
+ const walk = (val) => {
73
+ if (typeof val === 'string') return scrubString(val);
74
+ if (Array.isArray(val)) return val.map(walk);
75
+ if (val && typeof val === 'object') {
76
+ const next = {};
77
+ for (const [k, v] of Object.entries(val)) {
78
+ next[k] = walk(v);
79
+ }
80
+ return next;
81
+ }
82
+ return val;
83
+ };
84
+
85
+ const sanitized = walk(input);
86
+ return {
87
+ sanitized,
88
+ redactedSecretCount,
89
+ redactedPathCount
90
+ };
91
+ }
92
+
93
+ export function exportSanitizedSnapshot(state = {}, { format = 'json', homeDir = getHomeDir(), outputPath = null } = {}) {
94
+ const { sanitized, redactedSecretCount, redactedPathCount } = sanitizeForensicPayload(state, { homeDir });
95
+ const payload = {
96
+ exportedAt: new Date().toISOString(),
97
+ zeroPiiVerified: true,
98
+ redactedSecretCount,
99
+ redactedPathCount,
100
+ state: sanitized
101
+ };
102
+
103
+ const content = format === 'html'
104
+ ? `<!doctype html><html><head><meta charset="utf-8"><title>Sanitized Horizon Snapshot</title></head><body><pre id="snapshotData">${JSON.stringify(payload, null, 2).replace(/</g, '&lt;')}</pre></body></html>`
105
+ : JSON.stringify(payload, null, 2);
106
+
107
+ if (outputPath) {
108
+ fs.mkdirSync(path.dirname(outputPath), { recursive: true });
109
+ fs.writeFileSync(outputPath, content, 'utf8');
110
+ }
111
+
112
+ return {
113
+ success: true,
114
+ format,
115
+ outputPath,
116
+ redactedSecretCount,
117
+ redactedPathCount,
118
+ content,
119
+ payload
120
+ };
121
+ }
@@ -0,0 +1,303 @@
1
+ /**
2
+ * Session Forensics & Deterministic Quality Diagnostics.
3
+ * Adapted from antigravity-postmortem-workflows (analyze-project, verify, recover, pause).
4
+ * Zero external dependencies, pure functions with bounded runtime.
5
+ */
6
+
7
+ /**
8
+ * Normalizes an error string to create a durable fingerprint across turns.
9
+ * Strips line numbers, timestamps, hex addresses, and file paths.
10
+ */
11
+ export function normalizeErrorSignature(cmd = '', errorOutput = '') {
12
+ const baseCmd = String(cmd || '').trim().split(/\s+/)[0].split(/[\\/]/).pop() || 'command';
13
+ const firstLine = String(errorOutput || '')
14
+ .split(/\r?\n/)
15
+ .map(l => l.trim())
16
+ .find(l => l.length > 0 && !l.startsWith('Created At:') && !l.startsWith('Completed At:')) || '';
17
+
18
+ const clean = firstLine
19
+ .replace(/[A-Za-z]:\\[^:\s]+/g, '<path>')
20
+ .replace(/\/[^:\s]+/g, '<path>')
21
+ .replace(/\b0x[0-9a-fA-F]+\b/g, '<hex>')
22
+ .replace(/\b\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\b/g, '<date>')
23
+ .replace(/:\d+:\d+/g, ':<line>')
24
+ .replace(/\d+/g, '<n>')
25
+ .trim()
26
+ .slice(0, 100);
27
+
28
+ return `${baseCmd}::${clean}`;
29
+ }
30
+
31
+ /**
32
+ * Detects plan and task churn across session steps.
33
+ * Revisions >= 3 indicate plan thrashing (severity warning in postmortem repo).
34
+ */
35
+ export function computePlanChurn(steps = [], config = {}) {
36
+ const planWarnThreshold = config.plan_revision_warn ?? 3;
37
+ let planRevisions = 0;
38
+ let taskRevisions = 0;
39
+ const taskWriteIndices = [];
40
+
41
+ for (let i = 0; i < steps.length; i++) {
42
+ const s = steps[i];
43
+ const calls = s?.toolCalls || s?.tool_calls || [];
44
+ for (const call of calls) {
45
+ const name = call.name || call.tool || '';
46
+ const args = call.args || {};
47
+ const targetPath = String(args.Path || args.path || args.TargetFile || args.AbsolutePath || '');
48
+ const isWrite = /write|edit|replace|create|append/i.test(name);
49
+
50
+ if (isWrite) {
51
+ if (/implementation_plan\.md/i.test(targetPath)) {
52
+ planRevisions++;
53
+ } else if (/task\.md/i.test(targetPath)) {
54
+ taskRevisions++;
55
+ taskWriteIndices.push(i);
56
+ }
57
+ }
58
+ }
59
+ }
60
+
61
+ // Late-stage task churn: multiple task rewrites in the last 30% of turns
62
+ const lateCutoff = Math.floor(steps.length * 0.7);
63
+ const lateTaskWrites = taskWriteIndices.filter(idx => idx >= lateCutoff).length;
64
+ const lateStageTaskChurn = lateTaskWrites >= 2 && steps.length >= 10;
65
+
66
+ return {
67
+ planRevisions,
68
+ taskRevisions,
69
+ lateStageTaskChurn,
70
+ warn: planRevisions >= planWarnThreshold
71
+ };
72
+ }
73
+
74
+ /**
75
+ * Grades proof quality when completion is claimed.
76
+ * Strong = actual test/build/lint output with exitCode 0, or visual screenshots.
77
+ * Medium = generic successful command execution.
78
+ * Weak = only file edits without execution.
79
+ * None = verbal claim with zero tool output.
80
+ */
81
+ export function gradeProofQuality(steps = []) {
82
+ if (!Array.isArray(steps) || steps.length === 0) {
83
+ return { grade: 'None', reason: 'No steps in session', claimStepIndex: -1 };
84
+ }
85
+
86
+ // Find the most recent step claiming completion
87
+ let claimStepIndex = -1;
88
+ for (let i = steps.length - 1; i >= 0; i--) {
89
+ const s = steps[i];
90
+ const content = String(s.content || '');
91
+ const calls = s.toolCalls || s.tool_calls || [];
92
+ const isWalkthrough = calls.some(c => /walkthrough\.md/i.test(JSON.stringify(c.args || {})));
93
+
94
+ if (isWalkthrough || /\b(completed the task|task is complete|all steps (are )?verified|fixes verified|everything is working)\b/i.test(content)) {
95
+ claimStepIndex = i;
96
+ break;
97
+ }
98
+ }
99
+
100
+ const explicitClaimFound = claimStepIndex !== -1;
101
+ // If no explicit completion claim was found, check the final turn
102
+ if (claimStepIndex === -1) {
103
+ claimStepIndex = steps.length - 1;
104
+ }
105
+
106
+ // Inspect tool executions in the 5 turns leading up to or including the claim
107
+ const windowStart = Math.max(0, claimStepIndex - 5);
108
+ const relevantSteps = steps.slice(windowStart, claimStepIndex + 1);
109
+
110
+ let hasTestPass = false;
111
+ let hasBuildPass = false;
112
+ let hasGenericPass = false;
113
+ let hasFileEdits = false;
114
+ let toolCount = 0;
115
+
116
+ for (const s of relevantSteps) {
117
+ const calls = s.toolCalls || s.tool_calls || [];
118
+ toolCount += calls.length;
119
+
120
+ for (const call of calls) {
121
+ const name = call.name || call.tool || '';
122
+ const args = call.args || {};
123
+ const cmd = String(args.CommandLine || args.command || '');
124
+ const exitCode = s.exitCode ?? (s.status === 'ERROR' ? 1 : 0);
125
+
126
+ if (/write|edit|replace/i.test(name)) {
127
+ hasFileEdits = true;
128
+ }
129
+
130
+ if (/run_command/i.test(name) || cmd) {
131
+ if (exitCode === 0) {
132
+ if (/(test|vitest|jest|pytest|cargo test|go test|npm test)/i.test(cmd)) {
133
+ hasTestPass = true;
134
+ } else if (/(node --check|build|tsc|lint|verify)/i.test(cmd)) {
135
+ hasBuildPass = true;
136
+ } else {
137
+ hasGenericPass = true;
138
+ }
139
+ }
140
+ }
141
+ }
142
+ }
143
+
144
+ if (hasTestPass || hasBuildPass) {
145
+ return {
146
+ grade: 'Strong',
147
+ reason: hasTestPass ? 'Verified via passing automated test suite' : 'Verified via syntax check / build run',
148
+ claimStepIndex
149
+ };
150
+ }
151
+
152
+ if (hasGenericPass) {
153
+ return {
154
+ grade: 'Medium',
155
+ reason: 'Executed commands exited 0, but no dedicated test/build suite run',
156
+ claimStepIndex
157
+ };
158
+ }
159
+
160
+ if (hasFileEdits) {
161
+ return {
162
+ grade: 'Weak',
163
+ reason: 'Files were edited but no automated execution or verification test was run',
164
+ claimStepIndex
165
+ };
166
+ }
167
+
168
+ if (!explicitClaimFound) {
169
+ return {
170
+ grade: 'Pending',
171
+ reason: 'Session in progress or read-only (no completion claim or file edits yet)',
172
+ claimStepIndex: -1
173
+ };
174
+ }
175
+
176
+ return {
177
+ grade: 'None',
178
+ reason: 'Completion stated verbally without tool execution proof',
179
+ claimStepIndex
180
+ };
181
+ }
182
+
183
+ /**
184
+ * Detects context rot and recommends splitting long, degrading sessions.
185
+ * Ground rule: Duration alone never triggers split; requires evidence of performance decay.
186
+ */
187
+ export function detectContextRot(steps = [], state = {}, config = {}) {
188
+ const splitMinutesThreshold = config.split_recommend_minutes ?? 45;
189
+
190
+ if (!Array.isArray(steps) || steps.length < 6) {
191
+ return { elapsedMinutes: 0, splitRecommended: false, reason: 'Session too young to assess rot' };
192
+ }
193
+
194
+ // Estimate session duration from ISO timestamps
195
+ let firstTs = null;
196
+ let lastTs = null;
197
+ for (const s of steps) {
198
+ const rawTs = s?.createdAt || s?.created_at || s?.timestamp;
199
+ if (rawTs) {
200
+ const t = new Date(rawTs).getTime();
201
+ if (!isNaN(t)) {
202
+ if (!firstTs || t < firstTs) firstTs = t;
203
+ if (!lastTs || t > lastTs) lastTs = t;
204
+ }
205
+ }
206
+ }
207
+
208
+ const hasRealTimestamps = Boolean(firstTs && lastTs && lastTs >= firstTs);
209
+ const elapsedMinutes = (firstTs && lastTs && lastTs > firstTs)
210
+ ? Math.round((lastTs - firstTs) / (1000 * 60))
211
+ : (hasRealTimestamps ? 0 : Math.round(steps.length * 1.5));
212
+
213
+ // Compare error rate: first third vs last third
214
+ const third = Math.max(2, Math.floor(steps.length / 3));
215
+ const initialSteps = steps.slice(0, third);
216
+ const finalSteps = steps.slice(-third);
217
+
218
+ const isErr = s => s.status === 'ERROR' || (typeof s.exitCode === 'number' && s.exitCode !== 0);
219
+ const errInitial = initialSteps.filter(isErr).length / initialSteps.length;
220
+ const errFinal = finalSteps.filter(isErr).length / finalSteps.length;
221
+
222
+ const errorRateDeteriorated = errFinal > 0.25 && errFinal > (errInitial * 1.5);
223
+ const userCorrections = state.correctionCount || 0;
224
+ const lateTaskChurn = Boolean(state.lateStageTaskChurn);
225
+ const lowPurity = (state.totalActiveTokens > 100000) && ((state.signalPurityPct ?? 100) < 45);
226
+
227
+ const hasDegradation = errorRateDeteriorated || userCorrections >= 3 || lateTaskChurn || lowPurity;
228
+ const splitRecommended = elapsedMinutes >= splitMinutesThreshold && hasDegradation;
229
+
230
+ let reason = 'Context health stable';
231
+ if (splitRecommended) {
232
+ reason = `Session elapsed ${elapsedMinutes}m (>=${splitMinutesThreshold}m) with degrading error rate or late churn; checkpoint and /clear recommended`;
233
+ }
234
+
235
+ return {
236
+ elapsedMinutes,
237
+ errorRateInitial: Number(errInitial.toFixed(2)),
238
+ errorRateFinal: Number(errFinal.toFixed(2)),
239
+ splitRecommended,
240
+ reason
241
+ };
242
+ }
243
+
244
+ /**
245
+ * Fingerprints command failures to detect loops across non-consecutive steps.
246
+ * Categorizes failure into config | logic | integration | tooling.
247
+ */
248
+ export function fingerprintErrorLoop(steps = []) {
249
+ const occurrences = new Map();
250
+
251
+ for (let i = 0; i < steps.length; i++) {
252
+ const s = steps[i];
253
+ const isError = s.status === 'ERROR' || (typeof s.exitCode === 'number' && s.exitCode !== 0);
254
+ if (!isError) continue;
255
+
256
+ const calls = s.toolCalls || s.tool_calls || [];
257
+ for (const call of calls) {
258
+ const cmd = call.args?.CommandLine || call.args?.command || call.name || 'tool';
259
+ const out = s.content || s.output || '';
260
+ const fp = normalizeErrorSignature(cmd, out);
261
+
262
+ if (!occurrences.has(fp)) {
263
+ occurrences.set(fp, []);
264
+ }
265
+ occurrences.get(fp).push({
266
+ stepIndex: i,
267
+ command: cmd,
268
+ firstErrorLine: String(out).split(/\r?\n/)[0]?.slice(0, 120) || ''
269
+ });
270
+ }
271
+ }
272
+
273
+ for (const [fp, attempts] of occurrences.entries()) {
274
+ if (attempts.length >= 3) {
275
+ const sampleText = attempts.map(a => a.firstErrorLine).join(' ').toLowerCase();
276
+
277
+ let category = 'logic';
278
+ if (/enoent|not found|cannot find module|cannot import/i.test(sampleText)) {
279
+ category = 'config';
280
+ } else if (/econnrefused|etimedout|socket|network|fetch/i.test(sampleText)) {
281
+ category = 'integration';
282
+ } else if (/command failed|syntaxerror|unexpected/i.test(sampleText)) {
283
+ category = 'tooling';
284
+ }
285
+
286
+ return {
287
+ loop: true,
288
+ fingerprint: fp,
289
+ occurrences: attempts.length,
290
+ attempts,
291
+ category
292
+ };
293
+ }
294
+ }
295
+
296
+ return {
297
+ loop: false,
298
+ fingerprint: null,
299
+ occurrences: 0,
300
+ attempts: [],
301
+ category: null
302
+ };
303
+ }