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.
Files changed (262) hide show
  1. package/.antigravity-plugin/plugin.json +36 -0
  2. package/.claude-plugin/plugin.json +18 -0
  3. package/CHECKSUMS.sha256 +166 -0
  4. package/LICENSE +27 -0
  5. package/README.md +350 -2
  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 +175 -0
  16. package/bin/cli.mjs +3 -0
  17. package/bin/ctxtop.mjs +1799 -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 +133 -0
  25. package/config/modelCatalog.json +785 -0
  26. package/config/platformQuirks.json +19 -0
  27. package/hooks/handlers/compact-lifecycle.mjs +577 -0
  28. package/hooks/handlers/config-change.mjs +402 -0
  29. package/hooks/handlers/hookIo.mjs +311 -0
  30. package/hooks/handlers/hookIpcClient.mjs +83 -0
  31. package/hooks/handlers/post-model-switch.mjs +111 -0
  32. package/hooks/handlers/post-tool-use.mjs +366 -0
  33. package/hooks/handlers/pre-model-switch.mjs +1048 -0
  34. package/hooks/handlers/pre-tool-use.mjs +632 -0
  35. package/hooks/handlers/stop-gate.mjs +526 -0
  36. package/hooks/handlers/user-prompt-submit.mjs +367 -0
  37. package/hooks/hooks.json +131 -0
  38. package/hooks/post_invocation.mjs +13 -0
  39. package/hooks/post_tool_use.mjs +25 -0
  40. package/hooks/pre_invocation.mjs +14 -0
  41. package/hooks/pre_tool_use.mjs +97 -0
  42. package/hooks/register.js +726 -0
  43. package/hooks/session_start.mjs +24 -0
  44. package/hooks/stop.mjs +23 -0
  45. package/hooks.json +56 -0
  46. package/package.json +110 -4
  47. package/packages/antigravity/package.json +14 -0
  48. package/packages/antigravity/src/index.mjs +1 -0
  49. package/packages/claude-code/package.json +14 -0
  50. package/packages/claude-code/src/index.mjs +2 -0
  51. package/packages/core/package.json +14 -0
  52. package/packages/core/src/index.mjs +1 -0
  53. package/packages/engine-node/package.json +14 -0
  54. package/packages/engine-node/src/index.mjs +1 -0
  55. package/packages/mcp/package.json +17 -0
  56. package/packages/mcp/src/server.mjs +396 -0
  57. package/packages/pro/LICENSE-COMMERCIAL.md +19 -0
  58. package/packages/pro/README-SIGNING.md +30 -0
  59. package/packages/pro/package.json +16 -0
  60. package/packages/pro/src/index.mjs +3 -0
  61. package/packages/pro/src/team_finops_pack.mjs +241 -0
  62. package/packages/pro/workers/polar_webhook_worker.mjs +215 -0
  63. package/plugin.json +36 -0
  64. package/rules/AGENTS.md +10 -0
  65. package/sidecars/horizon-daemon/ipcServer.mjs +24 -0
  66. package/sidecars/horizon-daemon/server.mjs +2038 -0
  67. package/sidecars/horizon-daemon/sidecar.json +19 -0
  68. package/skills/cost-radar/SKILL.md +21 -0
  69. package/skills/evolve/SKILL.md +21 -0
  70. package/skills/handoff/SKILL.md +50 -0
  71. package/skills/horizon/SKILL.md +17 -0
  72. package/skills/inspect/SKILL.md +18 -0
  73. package/skills/precheck/SKILL.md +44 -0
  74. package/src/adapters/antigravity/index.mjs +109 -0
  75. package/src/adapters/claude-code/index.mjs +194 -0
  76. package/src/cli/cost_radar.mjs +70 -0
  77. package/src/cli/doctor.mjs +351 -0
  78. package/src/cli/horizon_hud.mjs +888 -0
  79. package/src/cli/init.mjs +425 -0
  80. package/src/cli/postmortem.mjs +515 -0
  81. package/src/coach/cacheGravityRouter.mjs +12 -0
  82. package/src/config/modelCatalog.json +704 -0
  83. package/src/config/platformQuirks.json +19 -0
  84. package/src/core/action_queue.mjs +264 -0
  85. package/src/core/ag_bridge.mjs +346 -0
  86. package/src/core/atomic_io.mjs +124 -0
  87. package/src/core/baseline.mjs +607 -0
  88. package/src/core/blindspot_sensors.mjs +399 -0
  89. package/src/core/bucket_b_runtime.mjs +1200 -0
  90. package/src/core/classifier.mjs +1757 -0
  91. package/src/core/coach/circuit_breakers.mjs +650 -0
  92. package/src/core/coach/contradiction_auditor.mjs +239 -0
  93. package/src/core/coach/effort_advisor.mjs +143 -0
  94. package/src/core/coach/handoff_hydrator.mjs +483 -0
  95. package/src/core/coach/progressive_checkpointer.mjs +551 -0
  96. package/src/core/coach/prompt_decomposer_coach.mjs +141 -0
  97. package/src/core/coach/reflector_queue.mjs +505 -0
  98. package/src/core/coach/saved_quota_ledger.mjs +615 -0
  99. package/src/core/coach/subagent_ipi_sanitizer.mjs +200 -0
  100. package/src/core/coach/subagent_phantom_auditor.mjs +261 -0
  101. package/src/core/coach/task_quota_router.mjs +955 -0
  102. package/src/core/coach/turn_zero_gate.mjs +574 -0
  103. package/src/core/compaction_coach.mjs +1126 -0
  104. package/src/core/config.mjs +214 -0
  105. package/src/core/constants.mjs +1987 -0
  106. package/src/core/detectors_det01_to_16.mjs +1523 -0
  107. package/src/core/doc_indexer.mjs +338 -0
  108. package/src/core/episodic_memory.mjs +135 -0
  109. package/src/core/fts5_output_compressor.mjs +359 -0
  110. package/src/core/git_ledger.mjs +189 -0
  111. package/src/core/handoff_audit.mjs +558 -0
  112. package/src/core/history.mjs +221 -0
  113. package/src/core/hook_diagnostics.mjs +158 -0
  114. package/src/core/horizon_classifier.mjs +326 -0
  115. package/src/core/horizon_config.mjs +802 -0
  116. package/src/core/host_watchdog.mjs +200 -0
  117. package/src/core/layer5_hygiene.mjs +1084 -0
  118. package/src/core/log_resolver.mjs +231 -0
  119. package/src/core/mcp_auditor.mjs +138 -0
  120. package/src/core/micro_skills_store.mjs +91 -0
  121. package/src/core/offenders.mjs +161 -0
  122. package/src/core/parser.mjs +1997 -0
  123. package/src/core/path_canonicalizer.mjs +73 -0
  124. package/src/core/paths.mjs +311 -0
  125. package/src/core/prefix_cache_shield.mjs +386 -0
  126. package/src/core/pro_license.mjs +385 -0
  127. package/src/core/prompt_rubric.mjs +518 -0
  128. package/src/core/pruner.mjs +433 -0
  129. package/src/core/quota.mjs +1860 -0
  130. package/src/core/rsi_instinct_engine.mjs +1197 -0
  131. package/src/core/rsl_clash_auditor.mjs +423 -0
  132. package/src/core/rsl_distiller.mjs +372 -0
  133. package/src/core/rsl_ledger.mjs +969 -0
  134. package/src/core/rsl_triage.mjs +909 -0
  135. package/src/core/sanitizer.mjs +121 -0
  136. package/src/core/session_auditor.mjs +658 -0
  137. package/src/core/session_forensics.mjs +303 -0
  138. package/src/core/session_timeline.mjs +358 -0
  139. package/src/core/settings.mjs +99 -0
  140. package/src/core/shared/detectors.mjs +1342 -0
  141. package/src/core/shared/fnv1a64.mjs +85 -0
  142. package/src/core/shared/handoff_schema.mjs +123 -0
  143. package/src/core/shared/index.mjs +5 -0
  144. package/src/core/shared/ipi_sanitizer.mjs +165 -0
  145. package/src/core/shared/micro_skills.mjs +1 -0
  146. package/src/core/shared/plugin_validator.mjs +202 -0
  147. package/src/core/shared/prompt_hygiene_governor.mjs +1 -0
  148. package/src/core/shield_manager.mjs +1417 -0
  149. package/src/core/sidecar_store.mjs +302 -0
  150. package/src/core/sprint_metrics.mjs +366 -0
  151. package/src/core/sqlite_client.mjs +283 -0
  152. package/src/core/storage_doctor.mjs +358 -0
  153. package/src/core/subagents.mjs +609 -0
  154. package/src/core/swarm_topology.mjs +360 -0
  155. package/src/core/task_quota_router.mjs +1656 -0
  156. package/src/core/telemetry/cache_ttl_watchdog.mjs +284 -0
  157. package/src/core/telemetry/scope_lock_registry.mjs +578 -0
  158. package/src/core/telemetry/shadow_file_detector.mjs +291 -0
  159. package/src/core/telemetry/trajectory_watcher.mjs +259 -0
  160. package/src/core/timeline_svg.mjs +236 -0
  161. package/src/core/tool_surgeon.mjs +305 -0
  162. package/src/core/trajectory_stitcher.mjs +645 -0
  163. package/src/core/u_shaped_optimizer.mjs +789 -0
  164. package/src/core/wal_hygiene.mjs +233 -0
  165. package/src/core-isomorphic/catalog/detectorCatalog.mjs +558 -0
  166. package/src/core-isomorphic/catalog/index.mjs +1 -0
  167. package/src/core-isomorphic/coach/cacheGravityRouter.mjs +1547 -0
  168. package/src/core-isomorphic/coach/microSkills.mjs +1 -0
  169. package/src/core-isomorphic/coach/promptHygieneGovernor.mjs +1 -0
  170. package/src/core-isomorphic/coach/repoCalibration.mjs +254 -0
  171. package/src/core-isomorphic/coach/resumeToolsetAuditor.mjs +321 -0
  172. package/src/core-isomorphic/coach/savedQuotaLedger.mjs +527 -0
  173. package/src/core-isomorphic/coach/smartCompactAdvisor.mjs +305 -0
  174. package/src/core-isomorphic/coach/stateBatonHydrator.mjs +810 -0
  175. package/src/core-isomorphic/coach/ttlWatchdog.mjs +464 -0
  176. package/src/core-isomorphic/config/anthropicModelCatalog.json +606 -0
  177. package/src/core-isomorphic/config/catalogLoader.mjs +1268 -0
  178. package/src/core-isomorphic/config/horizonConfig.mjs +1055 -0
  179. package/src/core-isomorphic/control/callTree.mjs +338 -0
  180. package/src/core-isomorphic/control/coachLatches.mjs +126 -0
  181. package/src/core-isomorphic/control/controlStateMachine.mjs +205 -0
  182. package/src/core-isomorphic/control/index.mjs +49 -0
  183. package/src/core-isomorphic/control/swarmWorktree.mjs +109 -0
  184. package/src/core-isomorphic/control/toolSuspension.mjs +197 -0
  185. package/src/core-isomorphic/diagnostics/drift_guard.mjs +382 -0
  186. package/src/core-isomorphic/diagnostics/index.mjs +9 -0
  187. package/src/core-isomorphic/diagnostics/micro_skills.mjs +471 -0
  188. package/src/core-isomorphic/diagnostics/prompt_hygiene_governor.mjs +888 -0
  189. package/src/core-isomorphic/economics/billingBlocks.mjs +251 -0
  190. package/src/core-isomorphic/economics/cacheGravity.mjs +369 -0
  191. package/src/core-isomorphic/economics/cliffBreaker.mjs +256 -0
  192. package/src/core-isomorphic/economics/driftLatency.mjs +433 -0
  193. package/src/core-isomorphic/economics/dualTtl.mjs +198 -0
  194. package/src/core-isomorphic/economics/index.mjs +47 -0
  195. package/src/core-isomorphic/economics/retentionRadar.mjs +348 -0
  196. package/src/core-isomorphic/guards/bucketBAlphaBeta.mjs +860 -0
  197. package/src/core-isomorphic/guards/bucketBGamma.mjs +442 -0
  198. package/src/core-isomorphic/guards/bucketBHeuristics.mjs +37 -0
  199. package/src/core-isomorphic/guards/circuitBreakers.mjs +1202 -0
  200. package/src/core-isomorphic/guards/det01_03_shell_secret.mjs +1184 -0
  201. package/src/core-isomorphic/guards/det04_12_thrash_rot.mjs +572 -0
  202. package/src/core-isomorphic/guards/det13_20_mcp_scope.mjs +913 -0
  203. package/src/core-isomorphic/guards/docIndexCore.mjs +446 -0
  204. package/src/core-isomorphic/guards/losslessPostSanitizer.mjs +317 -0
  205. package/src/core-isomorphic/guards/slopsquatGate.mjs +551 -0
  206. package/src/core-isomorphic/index.js +27 -0
  207. package/src/core-isomorphic/telemetry/otelExporter.mjs +187 -0
  208. package/src/core-isomorphic/telemetry/scopeLockRegistry.mjs +522 -0
  209. package/src/core-isomorphic/telemetry/sprintMetrics.mjs +327 -0
  210. package/src/core-isomorphic/telemetry/swarmTopology.mjs +152 -0
  211. package/src/core-isomorphic/telemetry/telemetryBridge.mjs +1156 -0
  212. package/src/core-isomorphic/ui/brailleSparkline.mjs +142 -0
  213. package/src/core-isomorphic/ui/costRadarSvg.mjs +276 -0
  214. package/src/core-isomorphic/ui/horizonGrid.mjs +475 -0
  215. package/src/core-isomorphic/ui/horizonPanelHtml.mjs +1237 -0
  216. package/src/core-isomorphic/ui/modViews.mjs +1504 -0
  217. package/src/core-isomorphic/ui/pdfReceiptGenerator.mjs +329 -0
  218. package/src/core-isomorphic/ustf/index.mjs +7 -0
  219. package/src/core-isomorphic/ustf/normalizer.mjs +512 -0
  220. package/src/core-isomorphic/ustf/schema.mjs +186 -0
  221. package/src/core-isomorphic/utils/runtime.mjs +962 -0
  222. package/src/demo/synthetic_states.mjs +661 -0
  223. package/src/diagnostics/bugReportGenerator.mjs +253 -0
  224. package/src/diagnostics/claudeHookCapabilities.mjs +396 -0
  225. package/src/diagnostics/doctorEngine.mjs +295 -0
  226. package/src/engine-node/db/index.mjs +58 -0
  227. package/src/engine-node/db/jsonl_fallback.mjs +184 -0
  228. package/src/engine-node/db/probe.mjs +342 -0
  229. package/src/engine-node/db/sqlite_wrapper.mjs +122 -0
  230. package/src/engine-node/index.mjs +12 -0
  231. package/src/engine-node/ipc/client.mjs +447 -0
  232. package/src/engine-node/ipc/index.mjs +22 -0
  233. package/src/engine-node/ipc/protocol.mjs +177 -0
  234. package/src/engine-node/ipc/server.mjs +445 -0
  235. package/src/engine-node/offloader/index.mjs +6 -0
  236. package/src/engine-node/offloader/tool_offloader.mjs +241 -0
  237. package/src/engine-node/sensors/blindspots.mjs +376 -0
  238. package/src/engine-node/sensors/git_merge_tree.mjs +223 -0
  239. package/src/engine-node/sensors/index.mjs +7 -0
  240. package/src/hooks/antigravity_rsl_hook.mjs +250 -0
  241. package/src/hooks/claude_rsl_hook.mjs +288 -0
  242. package/src/hooks/portfolio_runtime.mjs +858 -0
  243. package/src/hooks/post_invocation.mjs +611 -0
  244. package/src/hooks/pre_invocation.mjs +1725 -0
  245. package/src/hooks/session_start.mjs +199 -0
  246. package/src/shims/agy_cli_compressor.mjs +705 -0
  247. package/src/shims/agy_git_guard.mjs +749 -0
  248. package/src/shims/ah_log_query.mjs +39 -0
  249. package/src/ui/costRadarSvg.mjs +6 -0
  250. package/src/ui/horizonGrid.mjs +1 -0
  251. package/src/ui/horizonPanelHtml.mjs +1 -0
  252. package/src/ui/horizon_panel.css +167 -0
  253. package/src/ui/horizon_panel.js +212 -0
  254. package/src/ui/modViews.mjs +1 -0
  255. package/src/utils/modelSwitchTelemetry.mjs +308 -0
  256. package/src/utils/nodeIo.mjs +59 -0
  257. package/src/utils/runtime.mjs +1 -0
  258. package/src/utils/sessionCalibration.mjs +657 -0
  259. package/src/webview/advanced_view.html +1808 -0
  260. package/src/webview/horizon_panel.html +12397 -0
  261. package/src/webview/registry.mjs +80 -0
  262. package/src/webview/simple_view.html +1370 -0
@@ -0,0 +1,558 @@
1
+ /**
2
+ * Handoff Quality Gate & Checkpoint Auditor.
3
+ * Adapted from .agents/skills/handoff-auditor/SKILL.md & state-compressor/SKILL.md.
4
+ * Verifies that task.md / STATE.md is clean, actionable, and ready before compaction or handoff.
5
+ */
6
+
7
+ import fs from 'node:fs';
8
+ import path from 'node:path';
9
+ import { execFileSync } from 'node:child_process';
10
+ import { isInternalTelemetryPath, isCompactionRelevant, synthesizeParameterizedCompact } from './prompt_rubric.mjs';
11
+ import { canonicalizePath } from './paths.mjs';
12
+ import { atomicWriteFileSync } from './atomic_io.mjs';
13
+
14
+ export const HANDOFF_RESULTS = {
15
+ CLEAN: 'CLEAN',
16
+ NEEDS_FIXES: 'NEEDS_FIXES',
17
+ MISSING: 'MISSING'
18
+ };
19
+
20
+ /**
21
+ * Deterministically audits task.md / STATE.md checkpoint for a session.
22
+ * @param {string} brainDirOrPath Directory containing task.md or direct file path
23
+ * @param {Object} [sessionSignals={}] Extracted brainSignals from classifier
24
+ * @returns {Object} { result: 'CLEAN'|'NEEDS_FIXES'|'MISSING', checks: Array, fixes: string[] }
25
+ */
26
+ export function auditHandoff(brainDirOrPath = '', sessionSignals = {}, options = {}) {
27
+ let targetFile = null;
28
+ let resolvedBrainDir = null;
29
+
30
+ if (brainDirOrPath && fs.existsSync(brainDirOrPath)) {
31
+ const stat = fs.statSync(brainDirOrPath);
32
+ if (stat.isFile()) {
33
+ targetFile = brainDirOrPath;
34
+ resolvedBrainDir = path.dirname(brainDirOrPath);
35
+ } else {
36
+ resolvedBrainDir = brainDirOrPath;
37
+ const taskMd = path.join(brainDirOrPath, 'task.md');
38
+ const stateMd = path.join(brainDirOrPath, 'STATE.md');
39
+ const taskHint = sessionSignals?.activeSignal?.taskMdPathHint;
40
+ if (fs.existsSync(taskMd)) targetFile = taskMd;
41
+ else if (taskHint && fs.existsSync(taskHint)) targetFile = taskHint;
42
+ else if (fs.existsSync(stateMd)) targetFile = stateMd;
43
+ }
44
+ }
45
+
46
+ const syncAudit = checkBrainArtifactsAndGitDrift(resolvedBrainDir, options.workspacePath || '', sessionSignals, options);
47
+
48
+ if (!targetFile || !fs.existsSync(targetFile)) {
49
+ return {
50
+ result: HANDOFF_RESULTS.MISSING,
51
+ targetFile: null,
52
+ checks: [
53
+ { id: 'file_exists', name: 'Checkpoint file exists', pass: false, detail: 'No task.md or STATE.md found in session directory' }
54
+ ],
55
+ fixes: ['Create task.md or STATE.md checkpoint with Next Action, Decisions, and Blockers'],
56
+ ...syncAudit
57
+ };
58
+ }
59
+
60
+ let text = '';
61
+ try {
62
+ text = fs.readFileSync(targetFile, 'utf8');
63
+ } catch (err) {
64
+ return {
65
+ result: HANDOFF_RESULTS.MISSING,
66
+ targetFile,
67
+ checks: [
68
+ { id: 'file_readable', name: 'Checkpoint file readable', pass: false, detail: err.message }
69
+ ],
70
+ fixes: ['Ensure task.md is readable']
71
+ };
72
+ }
73
+
74
+ const checks = [];
75
+ const fixes = [];
76
+
77
+ // 1. Next Action Clarity: Must have specific, unblocked next action
78
+ const lines = text.split(/\r?\n/);
79
+ const nextSectionIdx = lines.findIndex(l => /^(#+\s*next action|next steps|up next)/i.test(l.trim()));
80
+ let nextActionText = '';
81
+
82
+ if (nextSectionIdx !== -1) {
83
+ for (let i = nextSectionIdx + 1; i < lines.length; i++) {
84
+ const l = lines[i].trim();
85
+ if (/^#+/.test(l)) break;
86
+ if (l.length > 0) {
87
+ nextActionText = l.replace(/^[-*]\s*(\[[ x/]]\s*)?/, '').trim();
88
+ break;
89
+ }
90
+ }
91
+ } else {
92
+ // Look for first pending checkbox
93
+ const firstPending = lines.find(l => /^[-*]\s*\[ \]/i.test(l.trim()));
94
+ if (firstPending) {
95
+ nextActionText = firstPending.replace(/^[-*]\s*\[ \]\s*/, '').trim();
96
+ }
97
+ }
98
+
99
+ const hasSpecificTarget = /(@[\w./\\-]+|\b[\w-]+\.(mjs|js|ts|json|md|py)\b|[/\\][\w.-]+|\b\w+\([^)]*\))/i.test(nextActionText);
100
+ const isVague = /^(continue|keep going|finish|wip|work in progress|todo|implement|fix code)\.?$/i.test(nextActionText);
101
+
102
+ if (nextActionText && !isVague && (hasSpecificTarget || nextActionText.length >= 18)) {
103
+ checks.push({ id: 'next_action', name: 'Next Action Clarity', pass: true, detail: `Specific next step: "${nextActionText.slice(0, 60)}"` });
104
+ } else {
105
+ const detail = nextActionText ? `Next action is vague: "${nextActionText}"` : 'No Next Action or pending checkbox found';
106
+ checks.push({ id: 'next_action', name: 'Next Action Clarity', pass: false, detail });
107
+ fixes.push('Specify next action with exact file target (@file or function) and concrete verb');
108
+ }
109
+
110
+ // 2. Incomplete Work Coverage: Any in-progress items [-] or [/] must have details
111
+ const inProgressItems = lines
112
+ .filter(l => /^[-*]\s*\[\/\]/i.test(l.trim()))
113
+ .map(l => l.replace(/^[-*]\s*\[\/\]\s*/, '').trim());
114
+
115
+ let incompleteOk = true;
116
+ for (const item of inProgressItems) {
117
+ const hasPathOrDetail = /(@|[\w-]+\.\w+|[/\\]|\b(in|on|at)\b)/i.test(item);
118
+ if (!hasPathOrDetail && item.length < 15) {
119
+ incompleteOk = false;
120
+ checks.push({ id: 'incomplete_coverage', name: 'Incomplete Work Coverage', pass: false, detail: `In-progress item has no files touched: "${item}"` });
121
+ fixes.push(`Specify files touched for in-progress task "${item}"`);
122
+ break;
123
+ }
124
+ }
125
+ if (incompleteOk) {
126
+ checks.push({ id: 'incomplete_coverage', name: 'Incomplete Work Coverage', pass: true, detail: `${inProgressItems.length} in-progress items properly documented` });
127
+ }
128
+
129
+ // 3. Blockers: If active error loop or failures detected, must be captured
130
+ const hasActiveFailure = sessionSignals?.errorLoop?.loop || (sessionSignals?.deadErrors?.isErrorLoop);
131
+ const hasBlockerSection = /#+\s*blockers?/i.test(text) || /\bblocker\b/i.test(text);
132
+
133
+ if (hasActiveFailure && !hasBlockerSection) {
134
+ checks.push({ id: 'blocker_accuracy', name: 'Blocker Accuracy', pass: false, detail: 'Active failure loop detected in session, but not captured in blockers' });
135
+ fixes.push('Add active failure to Blockers section with context and severity');
136
+ } else {
137
+ checks.push({ id: 'blocker_accuracy', name: 'Blocker Accuracy', pass: true, detail: 'Blocker state aligned with transcript evidence' });
138
+ }
139
+
140
+ // 4. Decision Log: If plan underwent revisions, rationale must be noted
141
+ const hasPlanChurn = (sessionSignals?.planChurn?.planRevisions || 0) >= 1;
142
+ const hasDecisionLogged = /#+\s*decisions?|\bdecision|\brationale\b/i.test(text);
143
+
144
+ if (hasPlanChurn && !hasDecisionLogged) {
145
+ checks.push({ id: 'decision_completeness', name: 'Decision Completeness', pass: false, detail: 'Plan was revised, but no decision or rationale was documented' });
146
+ fixes.push('Document plan change in Decisions section with 1-sentence rationale');
147
+ } else {
148
+ checks.push({ id: 'decision_completeness', name: 'Decision Completeness', pass: true, detail: 'Decisions documented or plan stable' });
149
+ }
150
+
151
+ // 5. Freshness: task.md turns behind
152
+ const explicitEditFlag = sessionSignals?.sessionHasWorkspaceEdits ?? sessionSignals?.activeSignal?.sessionHasWorkspaceEdits;
153
+ const sessionEdited = explicitEditFlag !== undefined
154
+ ? Boolean(explicitEditFlag)
155
+ : (Array.isArray(options.sessionWrittenPaths) ? options.sessionWrittenPaths.length > 0 : true);
156
+ const turnsBehind = sessionSignals?.activeSignal?.taskMdTurnsBehind ?? 0;
157
+ if (turnsBehind > 2 && sessionEdited) {
158
+ checks.push({ id: 'state_freshness', name: 'State Freshness', pass: false, detail: `task.md is ${turnsBehind} user turns stale` });
159
+ fixes.push('Update task.md with latest turn accomplishments');
160
+ } else {
161
+ checks.push({ id: 'state_freshness', name: 'State Freshness', pass: true, detail: `task.md freshness optimal (${turnsBehind} turns behind)` });
162
+ }
163
+
164
+ const allPassed = checks.every(c => c.pass);
165
+ return {
166
+ result: allPassed ? HANDOFF_RESULTS.CLEAN : HANDOFF_RESULTS.NEEDS_FIXES,
167
+ targetFile,
168
+ checks,
169
+ fixes,
170
+ ...syncAudit
171
+ };
172
+ }
173
+
174
+ /**
175
+ * Verifies all three brain artifacts (`task.md`, `implementation_plan.md`, `walkthrough.md`)
176
+ * and checks `git status --porcelain` in the workspace. Raises `preCompactionWarning` when uncommitted
177
+ * git modifications exist alongside a stale or missing `task.md`.
178
+ */
179
+ export function checkBrainArtifactsAndGitDrift(brainDir = null, workspacePath = '', sessionSignals = {}, options = {}) {
180
+ const inspectArtifact = (filename) => {
181
+ if (!brainDir) return { exists: false, path: null, mtimeMs: 0 };
182
+ const p = path.join(brainDir, filename);
183
+ try {
184
+ if (fs.existsSync(p)) {
185
+ const st = fs.statSync(p);
186
+ return { exists: true, path: p, mtimeMs: st.mtimeMs };
187
+ }
188
+ const hint = filename === 'task.md' ? sessionSignals?.activeSignal?.taskMdPathHint : null;
189
+ if (hint && fs.existsSync(hint)) {
190
+ return { exists: true, path: hint, mtimeMs: fs.statSync(hint).mtimeMs };
191
+ }
192
+ } catch {}
193
+ return { exists: false, path: p, mtimeMs: 0 };
194
+ };
195
+
196
+ const artifacts = {
197
+ taskMd: inspectArtifact('task.md'),
198
+ implementationPlanMd: inspectArtifact('implementation_plan.md'),
199
+ walkthroughMd: inspectArtifact('walkthrough.md')
200
+ };
201
+
202
+ let dirtyFiles = [];
203
+ let dirtyEntries = [];
204
+ let repoRoot = workspacePath || '';
205
+ if (typeof options.gitPorcelainOutput === 'string') {
206
+ dirtyEntries = parseGitPorcelain(options.gitPorcelainOutput);
207
+ } else if (workspacePath && fs.existsSync(workspacePath)) {
208
+ const snap = readGitStatusCached(workspacePath);
209
+ dirtyEntries = snap.entries;
210
+ repoRoot = snap.repoRoot || workspacePath;
211
+ }
212
+ dirtyFiles = dirtyEntries.map(e => `${e.status} ${e.path}`);
213
+
214
+ // session-scoped drift — only files this session wrote/edited count toward the warning.
215
+ const hasSessionScope = Array.isArray(options.sessionWrittenPaths);
216
+ let sessionDirtyFiles = [];
217
+ if (hasSessionScope) {
218
+ const norm = (p) => canonicalizePath(p).toLowerCase();
219
+ const sessionSet = new Set(options.sessionWrittenPaths.filter(Boolean).map(norm));
220
+ sessionDirtyFiles = dirtyEntries
221
+ .filter(e => {
222
+ const abs = path.isAbsolute(e.path) ? e.path : path.join(repoRoot || '', e.path);
223
+ return sessionSet.has(norm(abs));
224
+ })
225
+ .map(e => e.path);
226
+ }
227
+
228
+ const taskSaved = Boolean(sessionSignals?.activeSignal?.taskMdSaved);
229
+ const taskExists = artifacts.taskMd.exists || taskSaved;
230
+ const turnsBehind = Number(sessionSignals?.activeSignal?.taskMdTurnsBehind ?? 0);
231
+ const isTaskMdStale = !taskExists || turnsBehind >= 1;
232
+ const hasDirtyGit = hasSessionScope ? sessionDirtyFiles.length > 0 : dirtyFiles.length > 0;
233
+ const compactionRelevant = isCompactionRelevant({
234
+ totalActiveTokens: sessionSignals?.totalActiveTokens ?? 0,
235
+ sludgeTokens: sessionSignals?.sludgeTokens ?? 0
236
+ });
237
+ const explicitEditFlag = sessionSignals?.sessionHasWorkspaceEdits ?? sessionSignals?.activeSignal?.sessionHasWorkspaceEdits;
238
+ const sessionEditedWorkspace =
239
+ explicitEditFlag !== undefined
240
+ ? Boolean(explicitEditFlag)
241
+ : (hasSessionScope ? sessionDirtyFiles.length > 0 : true);
242
+ const preCompactionWarning = hasDirtyGit && sessionEditedWorkspace && isTaskMdStale && compactionRelevant;
243
+ const taskMdState = !taskExists ? 'missing' : `${turnsBehind} turn${turnsBehind === 1 ? '' : 's'} stale`;
244
+ let preCompactionWarningMessage = '';
245
+ if (preCompactionWarning) {
246
+ if (hasSessionScope) {
247
+ const n = sessionDirtyFiles.length;
248
+ preCompactionWarningMessage = `\u26A0\uFE0F ${n} file${n === 1 ? '' : 's'} edited in this session ${n === 1 ? 'is' : 'are'} uncommitted (${dirtyFiles.length} repo-wide) while task.md is ${taskMdState}.`;
249
+ } else {
250
+ // Legacy shape (direct unit calls without a session path set).
251
+ preCompactionWarningMessage = `\u26A0\uFE0F Pre-Compaction Drift Warning: ${dirtyFiles.length} uncommitted workspace file(s) detected via git status --porcelain while task.md is ${taskMdState}. Sync task.md before compacting.`;
252
+ }
253
+ }
254
+
255
+ return {
256
+ artifacts,
257
+ gitDrift: {
258
+ hasDirtyFiles: dirtyFiles.length > 0,
259
+ dirtyFileCount: dirtyFiles.length,
260
+ dirtyFiles: dirtyFiles.slice(0, 15),
261
+ sessionScoped: hasSessionScope,
262
+ sessionDirtyFileCount: hasSessionScope ? sessionDirtyFiles.length : null,
263
+ sessionDirtyFiles: hasSessionScope ? sessionDirtyFiles.slice(0, 15) : []
264
+ },
265
+ preCompactionWarning,
266
+ preCompactionWarningMessage
267
+ };
268
+ }
269
+
270
+ /**
271
+ * Parses `git status --porcelain=v1` output. Accepts both `-z` (NUL-separated) and newline output.
272
+ * Status columns are read BEFORE any trimming (a leading space in " M path" is significant).
273
+ * Renames/copies report the NEW path. Returns [{ status, path }] with repo-root-relative paths.
274
+ */
275
+ export function parseGitPorcelain(output = '') {
276
+ const s = String(output || '');
277
+ const entries = [];
278
+ if (s.includes('\0')) {
279
+ const parts = s.split('\0');
280
+ for (let i = 0; i < parts.length; i++) {
281
+ const rec = parts[i];
282
+ if (!rec || rec.length < 4) continue;
283
+ const status = rec.slice(0, 2);
284
+ const p = rec.slice(3);
285
+ // In -z mode a rename/copy record is "XY new\0old": skip the following old-path field.
286
+ if (status[0] === 'R' || status[0] === 'C' || status[1] === 'R' || status[1] === 'C') i++;
287
+ if (p) entries.push({ status, path: p });
288
+ }
289
+ return entries;
290
+ }
291
+ for (const rawLine of s.split(/\r?\n/)) {
292
+ if (!rawLine || !rawLine.trim() || rawLine.length < 4) continue;
293
+ const status = rawLine.slice(0, 2);
294
+ let p = rawLine.slice(3);
295
+ if ((status[0] === 'R' || status[0] === 'C') && p.includes(' -> ')) p = p.split(' -> ').pop();
296
+ p = p.trim().replace(/^"(.*)"$/, '$1');
297
+ if (p) entries.push({ status, path: p });
298
+ }
299
+ return entries;
300
+ }
301
+
302
+ const GIT_STATUS_CACHE_TTL_MS = 4000;
303
+ const gitStatusCache = new Map();
304
+
305
+ /**
306
+ * Runs `git status --porcelain=v1 -z -uall` (no shell) plus `git rev-parse --show-toplevel`,
307
+ * cached for a few seconds per workspace so refreshes don't spawn git every time.
308
+ */
309
+ export function readGitStatusCached(workspacePath, { nowMs = Date.now(), ttlMs = GIT_STATUS_CACHE_TTL_MS } = {}) {
310
+ const key = canonicalizePath(workspacePath).toLowerCase();
311
+ const hit = gitStatusCache.get(key);
312
+ if (hit && (nowMs - hit.atMs) < ttlMs) return hit.value;
313
+ let value = { entries: [], repoRoot: '' };
314
+ try {
315
+ const execOpts = { cwd: workspacePath, encoding: 'utf8', timeout: 1200, windowsHide: true, stdio: ['ignore', 'pipe', 'ignore'], maxBuffer: 8 * 1024 * 1024 };
316
+ const out = execFileSync('git', ['status', '--porcelain=v1', '-z', '-uall'], execOpts);
317
+ let repoRoot = '';
318
+ try {
319
+ repoRoot = String(execFileSync('git', ['rev-parse', '--show-toplevel'], execOpts) || '').trim();
320
+ } catch {}
321
+ value = { entries: parseGitPorcelain(String(out || '')), repoRoot };
322
+ } catch {}
323
+ gitStatusCache.set(key, { atMs: nowMs, value });
324
+ return value;
325
+ }
326
+
327
+ /**
328
+ * Generates the Baton Pass (`/handoff`) Markdown file summarizing
329
+ * active AST contracts, test states, brain artifact status, and pending `task.md` tasks.
330
+ */
331
+ export function generateHandoffMarkdown(state = {}, options = {}) {
332
+ const ts = options.timestamp || new Date().toISOString().replace(/[:.]/g, '-').slice(0, 19);
333
+ const relPath = `docs/HANDOFF_${ts}.md`;
334
+ const wsPath = options.workspacePath || state?.workspace?.canonicalPath || process.cwd();
335
+ const absPath = path.resolve(wsPath, relPath);
336
+
337
+ const sessionId = state?.sessionId || state?.conversationId || 'active-session';
338
+ const sessionTitle = state?.sessionTitle || 'Active Session';
339
+ const modelId = state?.model?.id || 'gemini-3.8-flash';
340
+ const totalTok = state?.window?.totalActiveTokens || 0;
341
+ const maxTok = state?.window?.maxTokens || 256000;
342
+
343
+ const dupFiles = state?.brainSignals?.duplicateReads?.topFiles || [];
344
+ const activeFiles = (options.activeFiles || dupFiles.map(f => f.path)).filter(p => p && !isInternalTelemetryPath(p));
345
+ const proofGrade = state?.brainSignals?.proofQuality?.grade || 'Verified';
346
+ const proofReason = state?.brainSignals?.proofQuality?.reason || 'Automated verification suite';
347
+
348
+ let pendingTasks = options.pendingTasks || [];
349
+ const handoffTarget = state?.brainSignals?.handoff?.targetFile;
350
+ if (pendingTasks.length === 0 && handoffTarget && fs.existsSync(handoffTarget)) {
351
+ try {
352
+ const rawTask = fs.readFileSync(handoffTarget, 'utf8');
353
+ pendingTasks = rawTask
354
+ .split(/\r?\n/)
355
+ .filter(l => /^[-*]\s*\[[ /]\]/.test(l.trim()))
356
+ .map(l => l.trim())
357
+ .slice(0, 10);
358
+ } catch {}
359
+ }
360
+
361
+ const parameterizedCompact = state?.compaction?.parameterizedCommand ||
362
+ synthesizeParameterizedCompact({
363
+ activeFiles,
364
+ userCorrections: state?.brainSignals?.userCorrectionTexts || [],
365
+ workspaceRoot: wsPath
366
+ });
367
+
368
+ const markdown = [
369
+ `# Session Handoff Baton Pass (\`${sessionId}\`)`,
370
+ ``,
371
+ `- **Session Title**: ${sessionTitle}`,
372
+ `- **Generated At**: ${new Date().toISOString()}`,
373
+ `- **Model & Window**: \`${modelId}\` (${Math.round(totalTok / 1000)}k / ${Math.round(maxTok / 1000)}k tokens)`,
374
+ `- **Verification Proof State**: **${proofGrade}** (${proofReason})`,
375
+ ``,
376
+ `## 1. Active AST Contracts & Modified Modules`,
377
+ ...(activeFiles.length > 0
378
+ ? activeFiles.slice(0, 8).map(f => `- \`${f}\``)
379
+ : [`- Active workspace modules in \`${wsPath}\``]),
380
+ ``,
381
+ `## 2. Pending \`task.md\` Checklist Items`,
382
+ ...(pendingTasks.length > 0
383
+ ? pendingTasks
384
+ : [`- [ ] Review \`task.md\` and \`implementation_plan.md\` in session brain directory`]),
385
+ ``,
386
+ `## 3. Brain Artifacts & Git Synchronization`,
387
+ `- \`task.md\`: ${state?.brainSignals?.handoff?.artifacts?.taskMd?.exists ? 'Present' : 'Check brain directory'}`,
388
+ `- \`implementation_plan.md\`: ${state?.brainSignals?.handoff?.artifacts?.implementationPlanMd?.exists ? 'Present' : 'Check brain directory'}`,
389
+ `- \`walkthrough.md\`: ${state?.brainSignals?.handoff?.artifacts?.walkthroughMd?.exists ? 'Present' : 'Not created yet'}`,
390
+ `- **Uncommitted Git Files**: ${state?.brainSignals?.handoff?.gitDrift?.dirtyFileCount ?? 0}`,
391
+ ``,
392
+ `## 4. Guarded Compaction Fallback Command`,
393
+ `\`\`\`text`,
394
+ parameterizedCompact,
395
+ `\`\`\``,
396
+ ``
397
+ ].join('\n');
398
+
399
+ let writtenPath = null;
400
+ if (options.writeToDisk !== false) {
401
+ try {
402
+ atomicWriteFileSync(absPath, markdown, { encoding: 'utf8' });
403
+ writtenPath = absPath;
404
+ } catch {}
405
+ }
406
+
407
+ return {
408
+ success: true,
409
+ timestamp: ts,
410
+ relativePath: relPath,
411
+ filePath: writtenPath || absPath,
412
+ markdown
413
+ };
414
+ }
415
+
416
+ /**
417
+ * Deterministically extracts a rotating `.handoff.md` file at >=80% context saturation
418
+ * (or on explicit 1-click/hook invocation) without LLM calls, containing:
419
+ * (1) Modified and inspected file paths (`toolUseResult.filePath`, `structuredPatch`, `edited_text_file`, `codeBlockDiff`)
420
+ * (2) Active checklist items (`TodoWrite`, `goal_status`, `task.md.resolved`)
421
+ * (3) Last 3 user prompts + unresolved `stderr`/`errorDetails`
422
+ */
423
+ export function distillPreCompactionHandoff(steps = [], state = {}, options = {}) {
424
+ const list = Array.isArray(steps) ? steps : [];
425
+ const totalTok = Number(state?.window?.totalActiveTokens || options.totalActiveTokens || 0);
426
+ const maxTok = Number(state?.window?.maxTokens || options.maxTokens || 256000);
427
+ const saturationPct = maxTok > 0 ? Math.round((totalTok / maxTok) * 100) : 0;
428
+ const shouldTrigger = Boolean(options.force || saturationPct >= 80);
429
+
430
+ const modifiedPaths = new Set();
431
+ const inspectedPaths = new Set();
432
+ const checklistItems = [];
433
+ const userPrompts = [];
434
+ const unresolvedErrors = [];
435
+
436
+ for (let i = 0; i < list.length; i++) {
437
+ const s = list[i] || {};
438
+ const type = String(s.type || s.role || '').toUpperCase();
439
+ const calls = Array.isArray(s.toolCalls)
440
+ ? s.toolCalls
441
+ : (Array.isArray(s.tool_calls) ? s.tool_calls : []);
442
+
443
+ if (type === 'USER_INPUT' || type === 'USER') {
444
+ const promptText = String(s.content || s.text || '').trim();
445
+ if (promptText) userPrompts.push(promptText.slice(0, 240));
446
+ }
447
+
448
+ if (s.toolUseResult?.filePath) {
449
+ const fp = String(s.toolUseResult.filePath);
450
+ if (s.toolUseResult.structuredPatch || s.structuredPatch) modifiedPaths.add(fp);
451
+ else inspectedPaths.add(fp);
452
+ }
453
+ if (s.edited_text_file) modifiedPaths.add(String(s.edited_text_file));
454
+ if (s.codeBlockDiff?.filePath) modifiedPaths.add(String(s.codeBlockDiff.filePath));
455
+
456
+ for (const c of calls) {
457
+ const name = String(c.name || c.tool || '').toLowerCase();
458
+ const args = c.args || c.parameters || c.Arguments || {};
459
+ const fp = args.Path || args.path || args.TargetFile || args.AbsolutePath;
460
+ if (fp && typeof fp === 'string' && !isInternalTelemetryPath(fp)) {
461
+ if (/edit|write|replace/i.test(name)) modifiedPaths.add(fp);
462
+ else if (/read|view/i.test(name)) inspectedPaths.add(fp);
463
+ }
464
+ if (name === 'todowrite' && Array.isArray(args.todos)) {
465
+ for (const td of args.todos) {
466
+ if (td && td.content) {
467
+ const box = td.status === 'completed' ? '[x]' : (td.status === 'in_progress' ? '[/]' : '[ ]');
468
+ checklistItems.push(`- ${box} ${td.content}`);
469
+ }
470
+ }
471
+ }
472
+ }
473
+
474
+ if (s.goal_status && typeof s.goal_status === 'string') {
475
+ checklistItems.push(`- [/] ${s.goal_status.trim()}`);
476
+ }
477
+
478
+ const isErr = Boolean(
479
+ s.status === 'ERROR' ||
480
+ (typeof s.exitCode === 'number' && s.exitCode !== 0) ||
481
+ s.errorDetails ||
482
+ s.stderr
483
+ );
484
+ if (isErr) {
485
+ const errMsg = String(s.errorDetails || s.stderr || s.content || '').trim().split(/\r?\n/).slice(0, 3).join(' | ');
486
+ if (errMsg) unresolvedErrors.push(`Turn #${s.stepIndex ?? i}: ${errMsg.slice(0, 200)}`);
487
+ } else if (calls.some(c => /run_command|bash/i.test(String(c.name || ''))) && s.exitCode === 0) {
488
+ // Later passing test run clears earlier transient command errors
489
+ unresolvedErrors.length = 0;
490
+ }
491
+ }
492
+
493
+ const brainDir = options.brainDir || state?.brainDir || '';
494
+ if (brainDir) {
495
+ for (const fname of ['task.md.resolved', 'task.md']) {
496
+ const p = path.join(brainDir, fname);
497
+ if (fs.existsSync(p)) {
498
+ try {
499
+ const lines = fs.readFileSync(p, 'utf8').split(/\r?\n/).filter(l => /^[-*]\s*\[[ x/]\]/i.test(l.trim()));
500
+ for (const l of lines.slice(0, 12)) checklistItems.push(l.trim());
501
+ break;
502
+ } catch {}
503
+ }
504
+ }
505
+ }
506
+
507
+ const recentUserPrompts = userPrompts.slice(-3);
508
+ const modList = Array.from(modifiedPaths);
509
+ const inspList = Array.from(inspectedPaths).filter(p => !modifiedPaths.has(p));
510
+
511
+ const wsPath = options.workspacePath || state?.workspace?.canonicalPath || process.cwd();
512
+ const handoffPath = options.outputPath || path.join(wsPath, '.handoff.md');
513
+
514
+ const markdown = [
515
+ `# Pre-Compaction Deterministic Handoff (\`.handoff.md\`)`,
516
+ ``,
517
+ `- **Context Saturation**: ${saturationPct}% (${Math.round(totalTok / 1000)}k / ${Math.round(maxTok / 1000)}k tokens)`,
518
+ `- **Distilled At**: ${new Date().toISOString()}`,
519
+ ``,
520
+ `## 1. Modified & Inspected Files`,
521
+ `### Modified (${modList.length})`,
522
+ ...(modList.length > 0 ? modList.map(p => `- \`${p}\``) : ['- None']),
523
+ `### Inspected (${inspList.length})`,
524
+ ...(inspList.length > 0 ? inspList.slice(0, 15).map(p => `- \`${p}\``) : ['- None']),
525
+ ``,
526
+ `## 2. Active Checklist & Goal State`,
527
+ ...(checklistItems.length > 0 ? Array.from(new Set(checklistItems)) : ['- [ ] Continue active implementation task']),
528
+ ``,
529
+ `## 3. Last 3 User Prompts`,
530
+ ...(recentUserPrompts.length > 0 ? recentUserPrompts.map((p, idx) => `${idx + 1}. "${p}"`) : ['1. (No user prompts recorded)']),
531
+ ``,
532
+ `## 4. Unresolved Errors / Stderr`,
533
+ ...(unresolvedErrors.length > 0 ? unresolvedErrors.slice(-5).map(e => `- ${e}`) : ['- Zero unresolved errors']),
534
+ ``
535
+ ].join('\n');
536
+
537
+ let written = false;
538
+ if (shouldTrigger && options.writeToDisk !== false) {
539
+ try {
540
+ atomicWriteFileSync(handoffPath, markdown, { encoding: 'utf8' });
541
+ written = true;
542
+ } catch {}
543
+ }
544
+
545
+ return {
546
+ triggered: shouldTrigger,
547
+ written,
548
+ saturationPct,
549
+ handoffPath,
550
+ modifiedFiles: modList,
551
+ inspectedFiles: inspList,
552
+ checklistItems: Array.from(new Set(checklistItems)),
553
+ lastUserPrompts: recentUserPrompts,
554
+ unresolvedErrors,
555
+ markdown
556
+ };
557
+ }
558
+