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,471 @@
1
+ /**
2
+ * @file src/core-isomorphic/diagnostics/micro_skills.mjs
3
+ * RSI-04 ("micro-skills") — Zero-LLM-Cost Deterministic Command-Pair Micro-Skills Engine.
4
+ *
5
+ * Strictly zero `node:*` imports (Claude Code Mod Law 4 compliant).
6
+ * Captures verified shell recovery pairs (`failedCmd` -> `workingCmd` within <= 3 turns),
7
+ * promotes after >= N distinct sessions (default 2), evicts contradicted skills,
8
+ * rejects secret-bearing or Ring-0 unsafe bypass commands, and formats <80-token StateBaton snippets.
9
+ */
10
+
11
+ import { path, getCwd, readJsonSafe, writeJsonAtomic } from '../utils/runtime.mjs';
12
+
13
+ export const MAX_MICRO_SKILL_BATON_TOKENS = 80;
14
+ export const MAX_MICRO_SKILL_BATON_CHARS = 300; // ~75-78 tokens
15
+
16
+ const LIVE_SECRET_PATTERNS = Object.freeze([
17
+ /\bsk-(?:ant-|proj-|live-|test-)?[A-Za-z0-9_-]{16,}\b/,
18
+ /\bgh[pousr]_[A-Za-z0-9]{20,}\b/,
19
+ /\bgithub_pat_[A-Za-z0-9_]{24,}\b/,
20
+ /\bAKIA[0-9A-Z]{16}\b/,
21
+ /\bAIza[0-9A-Za-z_-]{30,}\b/,
22
+ /\bxox[baprs]-[0-9A-Za-z-]{16,}\b/,
23
+ /\bBearer\s+[A-Za-z0-9._-]{16,}\b/i,
24
+ /-----BEGIN\s+[A-Z0-9\s]*PRIVATE\s+KEY-----/,
25
+ /[a-z0-9+.-]+:\/\/[^/\s:@]+:[^/\s@]+@[^\s]+/i,
26
+ /\b(?:API_KEY|SECRET|TOKEN|PASSWORD|PASSWD|PRIVATE_KEY|AUTH_TOKEN|ACCESS_KEY|STRIPE_KEY|OPENAI_API_KEY|ANTHROPIC_API_KEY)\s*=\s*['"]?[^\s'"]{6,}/i,
27
+ /--(?:token|password|api-key|secret|auth)(?:=|\s+)['"]?[^\s'"]+/i
28
+ ]);
29
+
30
+ const UNSAFE_BYPASS_PATTERNS = Object.freeze([
31
+ /--no-verify\b/i,
32
+ /--no-gpg-sign\b/i,
33
+ /\bgit\s+commit\b[^\r\n]*\s-[a-z]*n[a-z]*\b/i,
34
+ /\bgit\s+reset\s+--hard\b/i,
35
+ /\bgit\s+clean\s+-[a-z]*f/i,
36
+ /\bgit\s+push\b[^\r\n]*(?:--force\b|--force-with-lease\b|\s-f\b)/i,
37
+ /\brm\s+-[a-z]*r[a-z]*f\b/i,
38
+ /\brm\s+-[a-z]*f[a-z]*r\b/i,
39
+ /\bRemove-Item\b[^\r\n]*-Recurse[^\r\n]*-Force\b/i,
40
+ /\bdel\s+\/[sqf]/i,
41
+ /\bsudo\s+/i,
42
+ /\bchmod\s+777\b/i,
43
+ /\bNODE_TLS_REJECT_UNAUTHORIZED\s*=\s*['"]?0/i,
44
+ /\b(?:curl|wget)\b[^\r\n]*\|\s*(?:sh|bash|zsh|pwsh|powershell)\b/i
45
+ ]);
46
+
47
+ function shannonEntropy(str = '') {
48
+ if (!str) return 0;
49
+ const freq = new Map();
50
+ for (let i = 0; i < str.length; i++) {
51
+ const ch = str[i];
52
+ freq.set(ch, (freq.get(ch) || 0) + 1);
53
+ }
54
+ let entropy = 0;
55
+ const len = str.length;
56
+ for (const count of freq.values()) {
57
+ const p = count / len;
58
+ entropy -= p * Math.log2(p);
59
+ }
60
+ return entropy;
61
+ }
62
+
63
+ /**
64
+ * Validates that a shell command string is safe to record (contains zero secrets
65
+ * and zero Ring-0 destructive / hook-bypass flags).
66
+ *
67
+ * @param {string} rawCommand
68
+ * @returns {{ safe: boolean, reason: string | null }}
69
+ */
70
+ export function inspectCommandSafetyForMicroSkill(rawCommand = '') {
71
+ const text = String(rawCommand || '').trim();
72
+ if (!text || text.length > 400 || /[\r\n]/.test(text)) {
73
+ return { safe: false, reason: 'INVALID_LENGTH_OR_MULTILINE' };
74
+ }
75
+
76
+ for (const re of LIVE_SECRET_PATTERNS) {
77
+ if (re.test(text)) {
78
+ return { safe: false, reason: 'SECRET_DETECTED' };
79
+ }
80
+ }
81
+
82
+ // Check inline KEY=VALUE env assignments for high-entropy secrets
83
+ const envMatches = text.matchAll(/\b([A-Za-z_][A-Za-z0-9_]{1,})\s*=\s*(['"]?)([^\s'"]{16,})\2/g);
84
+ for (const m of envMatches) {
85
+ const val = m[3] || '';
86
+ if (shannonEntropy(val) >= 3.55) {
87
+ return { safe: false, reason: 'SECRET_DETECTED' };
88
+ }
89
+ }
90
+
91
+ for (const re of UNSAFE_BYPASS_PATTERNS) {
92
+ if (re.test(text)) {
93
+ return { safe: false, reason: 'UNSAFE_BYPASS_COMMAND' };
94
+ }
95
+ }
96
+
97
+ return { safe: true, reason: null };
98
+ }
99
+
100
+ function isFileTargetToken(tok = '') {
101
+ const clean = String(tok || '').replace(/^['"]|['"]$/g, '');
102
+ if (!clean || clean === './...' || clean.startsWith('-')) return false;
103
+ if (clean.includes('::')) return true;
104
+ if (/^(?:\.{1,2}[\\/]|[A-Za-z]:[\\/]|tests?[\\/]|src[\\/]|lib[\\/]|packages[\\/]|app[\\/])/i.test(clean)) {
105
+ return true;
106
+ }
107
+ if (/\.(?:py|js|mjs|cjs|ts|tsx|jsx|rs|go|rb|java|kt|cs|php|json|ya?ml|toml|md)$/i.test(clean)) {
108
+ return true;
109
+ }
110
+ return false;
111
+ }
112
+
113
+ /**
114
+ * Normalizes a shell command down to its canonical reusable runner invocation and detects its `commandFamily`.
115
+ * E.g. `poetry run pytest tests/test_auth.py::test_login` -> `{ canonical: 'poetry run pytest', commandFamily: 'pytest' }`.
116
+ *
117
+ * @param {string} rawCommand
118
+ * @returns {{ valid: boolean, canonical: string, commandFamily: string | null, rejectedReason: string | null }}
119
+ */
120
+ export function canonicalizeMicroSkillCommand(rawCommand = '') {
121
+ const safety = inspectCommandSafetyForMicroSkill(rawCommand);
122
+ if (!safety.safe) {
123
+ return { valid: false, canonical: '', commandFamily: null, rejectedReason: safety.reason };
124
+ }
125
+
126
+ // Reject compound multi-statement shell pipelines (`&&`, `||`, `;`, `|`) to keep micro-skills atomic
127
+ const trimmed = String(rawCommand || '').trim().replace(/\s+/g, ' ');
128
+ if (/(?:\|\||&&|;|\|)/.test(trimmed)) {
129
+ return { valid: false, canonical: '', commandFamily: null, rejectedReason: 'COMPOUND_COMMAND' };
130
+ }
131
+
132
+ const tokens = trimmed.split(' ').filter(Boolean);
133
+ // Strip trailing specific file targets while keeping runner, subcommand, and structural flags like `--workspace` / `run`
134
+ const kept = [];
135
+ for (let i = 0; i < tokens.length; i++) {
136
+ const tok = tokens[i];
137
+ if (i >= 1 && isFileTargetToken(tok)) {
138
+ continue;
139
+ }
140
+ kept.push(tok);
141
+ }
142
+
143
+ const canonical = kept.join(' ').trim();
144
+ const lower = canonical.toLowerCase();
145
+
146
+ let commandFamily = null;
147
+ if (/\bpytest\b/.test(lower)) {
148
+ commandFamily = 'pytest';
149
+ } else if (/\b(?:vitest|jest|mocha|ava)\b/.test(lower) || /\b(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?test\b/.test(lower) || /^node\s+--test\b/.test(lower)) {
150
+ commandFamily = 'js-test';
151
+ } else if (/\bcargo\s+test\b/.test(lower)) {
152
+ commandFamily = 'cargo-test';
153
+ } else if (/\bcargo\s+(?:build|check)\b/.test(lower)) {
154
+ commandFamily = 'cargo-build';
155
+ } else if (/\bgo\s+test\b/.test(lower)) {
156
+ commandFamily = 'go-test';
157
+ } else if (/\btsc\b/.test(lower) || /\b(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?typecheck\b/.test(lower)) {
158
+ commandFamily = 'typecheck';
159
+ } else if (/\b(?:eslint|biome)\b/.test(lower) || /\b(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?lint\b/.test(lower)) {
160
+ commandFamily = 'js-lint';
161
+ } else if (/\b(?:ruff|flake8|black)\b/.test(lower)) {
162
+ commandFamily = 'py-lint';
163
+ } else if (/\bmypy\b|\bpyright\b/.test(lower)) {
164
+ commandFamily = 'py-typecheck';
165
+ } else if (/\b(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?build\b/.test(lower)) {
166
+ commandFamily = 'js-build';
167
+ }
168
+
169
+ if (!commandFamily) {
170
+ return { valid: false, canonical, commandFamily: null, rejectedReason: 'UNSUPPORTED_FAMILY' };
171
+ }
172
+
173
+ return { valid: true, canonical, commandFamily, rejectedReason: null };
174
+ }
175
+
176
+ export function createEmptyMicroSkillsRegistry() {
177
+ return {
178
+ schemaVersion: '1.0.0',
179
+ skills: [],
180
+ pendingFailuresBySession: {}
181
+ };
182
+ }
183
+
184
+ /**
185
+ * Pure state-transition function recording a shell command's exit outcome in the Micro-Skills registry.
186
+ *
187
+ * @param {object} currentRegistry
188
+ * @param {object} event
189
+ * @param {string} event.command
190
+ * @param {number} event.exitCode
191
+ * @param {number} [event.turn=1]
192
+ * @param {string} [event.sessionId='default']
193
+ * @param {number} [event.confirmSessions=2]
194
+ * @param {string} [event.nowIso]
195
+ */
196
+ export function recordShellOutcomeInRegistry(currentRegistry = {}, event = {}) {
197
+ const base = currentRegistry && typeof currentRegistry === 'object'
198
+ ? currentRegistry
199
+ : createEmptyMicroSkillsRegistry();
200
+
201
+ const skills = Array.isArray(base.skills) ? base.skills.map((s) => ({
202
+ ...s,
203
+ confirmedSessionIds: Array.isArray(s.confirmedSessionIds) ? [...s.confirmedSessionIds] : []
204
+ })) : [];
205
+ const pendingMap = base.pendingFailuresBySession && typeof base.pendingFailuresBySession === 'object'
206
+ ? { ...base.pendingFailuresBySession }
207
+ : {};
208
+
209
+ const parsed = canonicalizeMicroSkillCommand(event.command || '');
210
+ if (!parsed.valid) {
211
+ return {
212
+ updated: false,
213
+ rejectedReason: parsed.rejectedReason,
214
+ promotedSkill: null,
215
+ capturedCandidate: null,
216
+ evictedContradictions: [],
217
+ registry: { schemaVersion: '1.0.0', skills, pendingFailuresBySession: pendingMap }
218
+ };
219
+ }
220
+
221
+ const sessionId = String(event.sessionId || 'default');
222
+ const turn = Math.max(1, Number(event.turn ?? 1));
223
+ const exitCode = Number(event.exitCode ?? 0);
224
+ const confirmSessions = Math.max(1, Number(event.confirmSessions ?? 2));
225
+ const nowIso = event.nowIso || new Date().toISOString();
226
+ const sessionFailures = Array.isArray(pendingMap[sessionId]) ? [...pendingMap[sessionId]] : [];
227
+
228
+ if (exitCode !== 0) {
229
+ // Prune stale failures (> 3 turns old) and record this failed command
230
+ const fresh = sessionFailures.filter((f) => turn - Number(f.turn || 0) <= 3 && f.failedCmd !== parsed.canonical);
231
+ fresh.push({
232
+ failedCmd: parsed.canonical,
233
+ commandFamily: parsed.commandFamily,
234
+ turn,
235
+ recordedAt: nowIso
236
+ });
237
+ pendingMap[sessionId] = fresh.slice(-8);
238
+
239
+ // Track if an existing promoted workingCmd just failed in this session
240
+ for (const sk of skills) {
241
+ if (sk.workingCmd === parsed.canonical && sk.commandFamily === parsed.commandFamily) {
242
+ sk.lastWorkingFailedSession = sessionId;
243
+ sk.lastWorkingFailedTurn = turn;
244
+ }
245
+ }
246
+
247
+ return {
248
+ updated: true,
249
+ rejectedReason: null,
250
+ promotedSkill: null,
251
+ capturedCandidate: null,
252
+ evictedContradictions: [],
253
+ registry: { schemaVersion: '1.0.0', skills, pendingFailuresBySession: pendingMap }
254
+ };
255
+ }
256
+
257
+ // exitCode === 0: Check contradiction eviction & candidate capture within <= 3 turns
258
+ const evictedContradictions = [];
259
+ for (let i = skills.length - 1; i >= 0; i--) {
260
+ const sk = skills[i];
261
+ const failedCmdNowWorks =
262
+ sk.failedCmd === parsed.canonical &&
263
+ sk.commandFamily === parsed.commandFamily;
264
+ const workingCmdSuperseded =
265
+ sk.commandFamily === parsed.commandFamily &&
266
+ sk.workingCmd !== parsed.canonical &&
267
+ sk.lastWorkingFailedSession === sessionId &&
268
+ typeof sk.lastWorkingFailedTurn === 'number' &&
269
+ turn - sk.lastWorkingFailedTurn >= 0 &&
270
+ turn - sk.lastWorkingFailedTurn <= 3;
271
+
272
+ if (failedCmdNowWorks || workingCmdSuperseded) {
273
+ evictedContradictions.push({ ...sk });
274
+ skills.splice(i, 1);
275
+ }
276
+ }
277
+
278
+ // Match most recent failure in the same commandFamily within <= 3 turns
279
+ const matchingFailure = [...sessionFailures]
280
+ .reverse()
281
+ .find(
282
+ (f) =>
283
+ f.commandFamily === parsed.commandFamily &&
284
+ f.failedCmd !== parsed.canonical &&
285
+ turn - Number(f.turn || 0) >= 0 &&
286
+ turn - Number(f.turn || 0) <= 3
287
+ );
288
+
289
+ if (!matchingFailure) {
290
+ return {
291
+ updated: evictedContradictions.length > 0,
292
+ rejectedReason: null,
293
+ promotedSkill: null,
294
+ capturedCandidate: null,
295
+ evictedContradictions,
296
+ registry: { schemaVersion: '1.0.0', skills, pendingFailuresBySession: pendingMap }
297
+ };
298
+ }
299
+
300
+ // Clear consumed failure from session pending list
301
+ pendingMap[sessionId] = sessionFailures.filter((f) => f !== matchingFailure);
302
+
303
+ let target = skills.find(
304
+ (s) => s.failedCmd === matchingFailure.failedCmd && s.commandFamily === parsed.commandFamily
305
+ );
306
+
307
+ if (!target) {
308
+ target = {
309
+ failedCmd: matchingFailure.failedCmd,
310
+ workingCmd: parsed.canonical,
311
+ commandFamily: parsed.commandFamily,
312
+ confirmedSessionIds: [sessionId],
313
+ confirmedSessions: 1,
314
+ promoted: 1 >= confirmSessions,
315
+ lastVerifiedAt: nowIso
316
+ };
317
+ skills.push(target);
318
+ } else if (target.workingCmd !== parsed.canonical) {
319
+ // Working command changed for this failedCmd -> reset confirmation to new workingCmd
320
+ target.workingCmd = parsed.canonical;
321
+ target.confirmedSessionIds = [sessionId];
322
+ target.confirmedSessions = 1;
323
+ target.promoted = 1 >= confirmSessions;
324
+ target.lastVerifiedAt = nowIso;
325
+ } else {
326
+ if (!target.confirmedSessionIds.includes(sessionId)) {
327
+ target.confirmedSessionIds.push(sessionId);
328
+ }
329
+ target.confirmedSessions = target.confirmedSessionIds.length;
330
+ target.promoted = target.confirmedSessions >= confirmSessions;
331
+ target.lastVerifiedAt = nowIso;
332
+ }
333
+
334
+ delete target.lastWorkingFailedSession;
335
+ delete target.lastWorkingFailedTurn;
336
+
337
+ return {
338
+ updated: true,
339
+ rejectedReason: null,
340
+ promotedSkill: target.promoted ? { ...target } : null,
341
+ capturedCandidate: { ...target },
342
+ evictedContradictions,
343
+ registry: { schemaVersion: '1.0.0', skills, pendingFailuresBySession: pendingMap }
344
+ };
345
+ }
346
+
347
+ /**
348
+ * Evaluates a `PreToolUse` shell command against promoted Repo Micro-Skills (`RSI-04`).
349
+ *
350
+ * @param {object} registry
351
+ * @param {object} params
352
+ * @param {string} params.command
353
+ * @param {string} [params.flightMode='COACH']
354
+ * @param {string} [params.overrideMode='default']
355
+ */
356
+ export function evaluateMicroSkillIntercept(registry = {}, {
357
+ command = '',
358
+ flightMode = 'COACH',
359
+ overrideMode = 'default'
360
+ } = {}) {
361
+ const normOverride = String(overrideMode || 'default').toLowerCase();
362
+ if (normOverride === 'off') {
363
+ return { triggered: false, detectorId: 'RSI-04', decision: 'allow' };
364
+ }
365
+
366
+ const parsed = canonicalizeMicroSkillCommand(command);
367
+ if (!parsed.valid) {
368
+ return { triggered: false, detectorId: 'RSI-04', decision: 'allow' };
369
+ }
370
+
371
+ const skills = Array.isArray(registry?.skills) ? registry.skills : [];
372
+ const match = skills.find(
373
+ (s) => s && s.promoted === true && s.failedCmd === parsed.canonical && s.workingCmd !== parsed.canonical
374
+ );
375
+
376
+ if (!match) {
377
+ return { triggered: false, detectorId: 'RSI-04', decision: 'allow' };
378
+ }
379
+
380
+ const fMode = String(flightMode || 'COACH').toUpperCase();
381
+ const shouldBlock =
382
+ normOverride === 'block' || (normOverride === 'default' && fMode === 'AUTO_PILOT');
383
+
384
+ const reason = `[RSI-04 Repo Micro-Skill] "${match.failedCmd}" previously failed in this repo; use verified command "${match.workingCmd}" instead.`;
385
+
386
+ return {
387
+ triggered: true,
388
+ detectorId: 'RSI-04',
389
+ slug: 'micro-skills',
390
+ subType: 'KNOWN_BROKEN_REPO_COMMAND',
391
+ failedCmd: match.failedCmd,
392
+ workingCmd: match.workingCmd,
393
+ commandFamily: match.commandFamily,
394
+ decision: shouldBlock ? 'deny' : 'allow',
395
+ reason,
396
+ hudAlert: reason
397
+ };
398
+ }
399
+
400
+ /**
401
+ * Formats promoted repo Micro-Skills into a compact `SessionStart` StateBaton line
402
+ * strictly capped under `<80` tokens (`<= 300` chars).
403
+ *
404
+ * @param {object} registry
405
+ * @returns {{ snippet: string, estimatedTokens: number, count: number }}
406
+ */
407
+ export function formatMicroSkillsBatonSnippet(registry = {}) {
408
+ const skills = Array.isArray(registry?.skills)
409
+ ? registry.skills.filter((s) => s && s.promoted === true && s.failedCmd && s.workingCmd)
410
+ : [];
411
+
412
+ if (skills.length === 0) {
413
+ return { snippet: '', estimatedTokens: 0, count: 0 };
414
+ }
415
+
416
+ const prefix = '[RSI-04 Verified Repo Commands] ';
417
+ const pairs = [];
418
+ let currentLen = prefix.length;
419
+ for (const sk of skills) {
420
+ const item = `"${sk.failedCmd}" -> "${sk.workingCmd}"`;
421
+ const sepLen = pairs.length > 0 ? 2 : 0;
422
+ if (currentLen + sepLen + item.length > MAX_MICRO_SKILL_BATON_CHARS) {
423
+ break;
424
+ }
425
+ pairs.push(item);
426
+ currentLen += sepLen + item.length;
427
+ }
428
+
429
+ if (pairs.length === 0) {
430
+ return { snippet: '', estimatedTokens: 0, count: 0 };
431
+ }
432
+
433
+ const snippet = `${prefix}${pairs.join('; ')}`;
434
+ const estimatedTokens = Math.ceil(snippet.length / 4);
435
+ return {
436
+ snippet,
437
+ estimatedTokens,
438
+ count: pairs.length
439
+ };
440
+ }
441
+
442
+ export function resolveMicroSkillsPath(options = {}) {
443
+ const cwd = getCwd(options);
444
+ return path.join(cwd, '.agents', 'state', 'micro_skills.json');
445
+ }
446
+
447
+ export function loadMicroSkillsRegistry(options = {}) {
448
+ const filePath = resolveMicroSkillsPath(options);
449
+ const parsed = readJsonSafe(filePath, null, options);
450
+ if (!parsed || typeof parsed !== 'object') {
451
+ return createEmptyMicroSkillsRegistry();
452
+ }
453
+ return {
454
+ schemaVersion: '1.0.0',
455
+ skills: Array.isArray(parsed.skills) ? parsed.skills : [],
456
+ pendingFailuresBySession:
457
+ parsed.pendingFailuresBySession && typeof parsed.pendingFailuresBySession === 'object'
458
+ ? parsed.pendingFailuresBySession
459
+ : {}
460
+ };
461
+ }
462
+
463
+ export function recordWorkspaceShellOutcome(event = {}, options = {}) {
464
+ const current = loadMicroSkillsRegistry(options);
465
+ const res = recordShellOutcomeInRegistry(current, event);
466
+ if (res.updated) {
467
+ const filePath = resolveMicroSkillsPath(options);
468
+ writeJsonAtomic(filePath, res.registry, options);
469
+ }
470
+ return res;
471
+ }