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,1197 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import crypto from 'node:crypto';
4
+ import { execFileSync } from 'node:child_process';
5
+ import { getHomeDir, canonicalizePath } from './paths.mjs';
6
+ import { atomicWriteFileSync } from './atomic_io.mjs';
7
+ import { openLocalHorizonDb } from './sqlite_client.mjs';
8
+ import { PrefixCacheShield } from './prefix_cache_shield.mjs';
9
+ import { auditRuleContradictions } from './coach/contradiction_auditor.mjs';
10
+ import {
11
+ computeProjectScopeHash,
12
+ evaluateGlobalPromotionEligibility
13
+ } from './coach/reflector_queue.mjs';
14
+ import { TurnZeroGate } from './coach/turn_zero_gate.mjs';
15
+ import { evaluateRsi01PrefixDietAndSkillFault } from './shared/detectors.mjs';
16
+
17
+ /**
18
+ * Phase 3: Bounded Atomic Instinct & Correction Learning Loop (RSI Engine)
19
+ *
20
+ * Turns user corrections and execution outcomes into confidence-weighted Atomic Instincts
21
+ * and modular Antigravity Skills (SKILL.md) with strict anti-reward-hacking safeguards
22
+ * and an automatic Git Rollback Tripwire.
23
+ */
24
+
25
+ export const RSI_CONSTANTS = Object.freeze({
26
+ INITIAL_CONFIDENCE: 0.30,
27
+ MAX_CONFIDENCE: 0.95,
28
+ MIN_CONFIDENCE: 0.05,
29
+ HELPFUL_DELTA: 0.12,
30
+ HARMFUL_DELTA: -0.20,
31
+ COACH_INJECTION_MIN_CONFIDENCE: 0.55,
32
+ PROMOTION_MIN_CONFIDENCE: 0.75,
33
+ PROMOTION_MIN_HELPFUL_COUNT: 3,
34
+ EVOLVE_CLUSTER_MIN_COUNT: 5,
35
+ EVOLVE_CLUSTER_MIN_CONFIDENCE: 0.55,
36
+ STALENESS_TTL_MS: 48 * 60 * 60 * 1000, // 48 hours
37
+ TRIPWIRE_WINDOW_MS: 24 * 60 * 60 * 1000, // 24 hours
38
+ TRIPWIRE_PASS_RATE_DROP_THRESHOLD: 0.15, // >15% drop triggers rollback
39
+ TRIPWIRE_HARMFUL_COUNT_THRESHOLD: 2
40
+ });
41
+
42
+ const IMMUTABLE_BOUNDARY_PATTERNS = [
43
+ // Test suites
44
+ /(^|[\\/])(tests?|__tests__|specs?)[\\/]/i,
45
+ /\.(test|spec)\.[a-z0-9]+$/i,
46
+ // CI workflows
47
+ /(^|[\\/])\.github[\\/]workflows[\\/]/i,
48
+ /(^|[\\/])(\.gitlab-ci\.yml|azure-pipelines\.yml|Jenkinsfile)$/i,
49
+ // Linter, formatter & compiler configs
50
+ /(^|[\\/])(\.eslintrc(\.[a-z0-9]+)?|eslint\.config\.[a-z0-9]+|biome\.jsonc?|\.prettierrc(\.[a-z0-9]+)?|tsconfig(\.[a-z0-9]+)?\.json|package\.json|package-lock\.json)$/i,
51
+ // Scoring & telemetry SQLite databases
52
+ /instincts\.db(-wal|-shm)?$/i,
53
+ /\.(db|sqlite|sqlite3)(-wal|-shm)?$/i
54
+ ];
55
+
56
+ /**
57
+ * Enforces the Immutable File Boundary List:
58
+ * The RSI Engine is hard-blocked from writing to test suites, CI workflows,
59
+ * linter/compiler configs, or its own scoring SQLite database.
60
+ */
61
+ export function isImmutableRsiTarget(filePath = '') {
62
+ if (!filePath || typeof filePath !== 'string') return true;
63
+ const normalized = filePath.trim().replace(/\\/g, '/');
64
+ for (const pattern of IMMUTABLE_BOUNDARY_PATTERNS) {
65
+ if (pattern.test(normalized)) {
66
+ return true;
67
+ }
68
+ }
69
+ return false;
70
+ }
71
+
72
+ export function assertMutableRsiTarget(filePath = '') {
73
+ if (isImmutableRsiTarget(filePath)) {
74
+ const err = new Error(
75
+ `RSI Immutable File Boundary violation: RSI Engine is hard-blocked from modifying "${filePath}"`
76
+ );
77
+ err.code = 'IMMUTABLE_FILE_BOUNDARY';
78
+ throw err;
79
+ }
80
+ }
81
+
82
+ export function getDefaultInstinctsDbPath(homeDir = getHomeDir()) {
83
+ return path.join(homeDir, '.gemini', 'antigravity', 'agy-horizon', 'instincts.db');
84
+ }
85
+
86
+ const EXPLICIT_CORRECTION_PATTERNS = [
87
+ {
88
+ name: 'instead_of',
89
+ regex: /\b(?:no[,:\s]+)?use\s+([^.,;!\n]+?)\s+instead\s+of\s+([^.,;!\n]+)/i,
90
+ format: m => ({
91
+ trigger_condition: `When tempted to use ${m[2].trim()}`,
92
+ directive_action: `Always use ${m[1].trim()} instead of ${m[2].trim()}`
93
+ })
94
+ },
95
+ {
96
+ name: 'dont_use',
97
+ regex: /\b(?:don'?t|do\s+not)\s+(?:use|call|import|run|write)\s+([^.,;!\n]+)/i,
98
+ format: m => ({
99
+ trigger_condition: `When considering ${m[1].trim()}`,
100
+ directive_action: `Do not use ${m[1].trim()}`
101
+ })
102
+ },
103
+ {
104
+ name: 'stop_doing',
105
+ regex: /\bstop\s+(?:doing|using|calling|writing|adding)\s+([^.,;!\n]+)/i,
106
+ format: m => ({
107
+ trigger_condition: `During implementation involving ${m[1].trim()}`,
108
+ directive_action: `Stop using or doing ${m[1].trim()}`
109
+ })
110
+ },
111
+ {
112
+ name: 'never',
113
+ regex: /\bnever\s+([^.,;!\n]{4,140})/i,
114
+ format: m => ({
115
+ trigger_condition: `When modifying relevant code`,
116
+ directive_action: `NEVER ${m[1].trim()}`
117
+ })
118
+ },
119
+ {
120
+ name: 'always',
121
+ regex: /\balways\s+([^.,;!\n]{4,140})/i,
122
+ format: m => ({
123
+ trigger_condition: `When executing matching domain tasks`,
124
+ directive_action: `ALWAYS ${m[1].trim()}`
125
+ })
126
+ },
127
+ {
128
+ name: 'remember',
129
+ regex: /\bremember(?:\s+to|:)\s*([^.,;!\n]{4,140})/i,
130
+ format: m => ({
131
+ trigger_condition: `Before completing task steps`,
132
+ directive_action: `Remember: ${m[1].trim()}`
133
+ })
134
+ }
135
+ ];
136
+
137
+ /**
138
+ * Infers an instinct domain from text or file paths when not explicitly provided.
139
+ */
140
+ export function inferInstinctDomain(text = '', filePaths = []) {
141
+ const combined = `${text} ${(filePaths || []).join(' ')}`.toLowerCase();
142
+ if (/\b(test|spec|assert|expect|vitest|jest|node:test|mock)\b/.test(combined)) {
143
+ return 'testing';
144
+ }
145
+ if (/\b(typescript|type|interface|any|ts-ignore|tsconfig|generic)\b/.test(combined)) {
146
+ return 'typescript-types';
147
+ }
148
+ if (/\b(git|commit|branch|rebase|merge|worktree|push|pull)\b/.test(combined)) {
149
+ return 'git-workflow';
150
+ }
151
+ if (/\b(css|html|ui|webview|button|style|contrast|tufte|layout)\b/.test(combined)) {
152
+ return 'ui-styling';
153
+ }
154
+ if (/\b(sqlite|wal|pragma|fts5|database|readonly)\b/.test(combined)) {
155
+ return 'sqlite-telemetry';
156
+ }
157
+ return 'general';
158
+ }
159
+
160
+ /**
161
+ * Extracts explicit user correction patterns and implicit behavioral signals from a turn.
162
+ */
163
+ export function parseCorrectionSignals(turn = {}) {
164
+ const results = [];
165
+ const text = String(turn.userMessage || turn.userText || turn.content || turn.text || '').trim();
166
+ const scope = turn.scope === 'global' ? 'global' : 'project';
167
+ const domain = turn.domain || inferInstinctDomain(text, turn.files || []);
168
+
169
+ if (text) {
170
+ for (const pattern of EXPLICIT_CORRECTION_PATTERNS) {
171
+ const match = text.match(pattern.regex);
172
+ if (match) {
173
+ const extracted = pattern.format(match);
174
+ results.push({
175
+ scope,
176
+ domain,
177
+ patternName: pattern.name,
178
+ trigger_condition: turn.trigger_condition || extracted.trigger_condition,
179
+ directive_action: turn.directive_action || extracted.directive_action,
180
+ source: 'explicit_user_correction'
181
+ });
182
+ break;
183
+ }
184
+ }
185
+ }
186
+
187
+ // Implicit signal 1: User reverted or edited lines written by the agent within 2 turns
188
+ if (turn.userRevertedAgentEdit || turn.userEditedAgentLines) {
189
+ const fileLabel = turn.revertedFile ? path.basename(turn.revertedFile) : 'modified file';
190
+ results.push({
191
+ scope,
192
+ domain,
193
+ patternName: 'implicit_user_revert',
194
+ trigger_condition: turn.trigger_condition || `When editing ${fileLabel}`,
195
+ directive_action:
196
+ turn.directive_action ||
197
+ `Preserve user-preferred pattern in ${fileLabel}: ${turn.revertSummary || 'avoid reverted construct'}`,
198
+ source: 'implicit_user_revert'
199
+ });
200
+ }
201
+
202
+ // Implicit signal 2: Deterministic detector DET-01..16 fired
203
+ if (turn.detectorViolation && turn.detectorViolation.id) {
204
+ const det = turn.detectorViolation;
205
+ results.push({
206
+ scope,
207
+ domain,
208
+ patternName: `detector_${det.id}`,
209
+ trigger_condition: turn.trigger_condition || `When executing tool actions monitored by ${det.id}`,
210
+ directive_action:
211
+ turn.directive_action || `Avoid ${det.id} (${det.name || 'anti-pattern'}): ${det.remediation || det.summary || ''}`.trim(),
212
+ source: 'detector_violation'
213
+ });
214
+ }
215
+
216
+ return results;
217
+ }
218
+
219
+ function tryGetGitHeadSha(cwd) {
220
+ if (!cwd || !fs.existsSync(cwd)) return null;
221
+ try {
222
+ return execFileSync('git', ['rev-parse', 'HEAD'], {
223
+ cwd,
224
+ encoding: 'utf8',
225
+ stdio: ['ignore', 'pipe', 'ignore'],
226
+ timeout: 3000
227
+ }).trim();
228
+ } catch {
229
+ return null;
230
+ }
231
+ }
232
+
233
+ export class RsiInstinctEngine {
234
+ constructor(options = {}) {
235
+ this.homeDir = options.homeDir || getHomeDir();
236
+ this.workspaceDir = options.workspaceDir || process.cwd();
237
+ this.projectHash =
238
+ options.projectHash ||
239
+ computeProjectScopeHash(this.workspaceDir, { gitRemoteUrl: options.gitRemoteUrl });
240
+ this.dbPath = options.dbPath || getDefaultInstinctsDbPath(this.homeDir);
241
+ this.prefixShield =
242
+ options.prefixShield ||
243
+ options.prefixCacheShield ||
244
+ new PrefixCacheShield({
245
+ homeDir: this.homeDir,
246
+ queuePath: options.queuePath
247
+ });
248
+ this.turnZeroGate =
249
+ options.turnZeroGate ||
250
+ new TurnZeroGate({
251
+ workspaceDir: this.workspaceDir
252
+ });
253
+ this.nowFn = typeof options.nowFn === 'function' ? options.nowFn : () => Date.now();
254
+ this.db = null;
255
+ this._rollingTestHistory = [];
256
+ this._initDb();
257
+ }
258
+
259
+ _initDb() {
260
+ fs.mkdirSync(path.dirname(this.dbPath), { recursive: true });
261
+ this.db = openLocalHorizonDb(this.dbPath, { readOnly: false });
262
+ this.db.exec(`
263
+ CREATE TABLE IF NOT EXISTS instincts (
264
+ id TEXT PRIMARY KEY,
265
+ scope TEXT NOT NULL DEFAULT 'project',
266
+ project_hash TEXT NOT NULL DEFAULT 'local',
267
+ domain TEXT NOT NULL DEFAULT 'general',
268
+ trigger_condition TEXT NOT NULL,
269
+ directive_action TEXT NOT NULL,
270
+ confidence REAL NOT NULL DEFAULT 0.30,
271
+ helpful_count INTEGER NOT NULL DEFAULT 0,
272
+ harmful_count INTEGER NOT NULL DEFAULT 0,
273
+ status TEXT NOT NULL DEFAULT 'active',
274
+ created_at TEXT NOT NULL,
275
+ last_verified_at TEXT NOT NULL,
276
+ ttl_expires_at TEXT NOT NULL
277
+ );
278
+
279
+ CREATE INDEX IF NOT EXISTS idx_instincts_domain_status
280
+ ON instincts(domain, status, confidence);
281
+
282
+ CREATE TABLE IF NOT EXISTS mutation_snapshots (
283
+ mutation_id TEXT PRIMARY KEY,
284
+ instinct_id TEXT,
285
+ domain TEXT,
286
+ target_path TEXT NOT NULL,
287
+ existed_before INTEGER NOT NULL DEFAULT 0,
288
+ previous_content TEXT,
289
+ git_commit_sha TEXT,
290
+ baseline_pass_rate REAL NOT NULL DEFAULT 1.0,
291
+ created_at_ms INTEGER NOT NULL,
292
+ rolled_back INTEGER NOT NULL DEFAULT 0,
293
+ rollback_reason TEXT
294
+ );
295
+ `);
296
+
297
+ // Ensure project_hash column exists on pre-existing instincts databases
298
+ try {
299
+ const cols = this.db.prepare(`PRAGMA table_info(instincts)`).all();
300
+ const hasProjectHash = cols.some((c) => c.name === 'project_hash');
301
+ if (!hasProjectHash) {
302
+ this.db.exec(`ALTER TABLE instincts ADD COLUMN project_hash TEXT NOT NULL DEFAULT 'local';`);
303
+ }
304
+ } catch {}
305
+ }
306
+
307
+ close() {
308
+ if (this.db) {
309
+ try {
310
+ this.db.close();
311
+ } catch {}
312
+ this.db = null;
313
+ }
314
+ }
315
+
316
+ /**
317
+ * Observes a user turn or correction signal and inserts or reinforces an Atomic Instinct.
318
+ */
319
+ observeTurn(turn = {}) {
320
+ const signals = parseCorrectionSignals(turn);
321
+ const createdOrUpdated = [];
322
+ const projHash = String(turn.project_hash || turn.projectHash || this.projectHash);
323
+
324
+ for (const sig of signals) {
325
+ const existing = this.db
326
+ .prepare(
327
+ `SELECT * FROM instincts
328
+ WHERE domain = ? AND directive_action = ? AND scope = ? AND project_hash = ?
329
+ LIMIT 1`
330
+ )
331
+ .get(sig.domain, sig.directive_action, sig.scope, projHash);
332
+
333
+ const nowMs = this.nowFn();
334
+ const nowIso = new Date(nowMs).toISOString();
335
+ const ttlIso = new Date(nowMs + RSI_CONSTANTS.STALENESS_TTL_MS).toISOString();
336
+
337
+ if (existing) {
338
+ // Reinforce existing instinct when user explicitly repeats or confirms it
339
+ const updated = this.recordOutcome(existing.id, {
340
+ helpful: true,
341
+ session: turn.session,
342
+ targetRulePath: turn.targetRulePath
343
+ });
344
+ createdOrUpdated.push(updated);
345
+ } else {
346
+ const id = turn.id || `inst-${crypto.randomBytes(6).toString('hex')}`;
347
+ const initialConf = Number.isFinite(turn.initialConfidence)
348
+ ? Number(turn.initialConfidence)
349
+ : RSI_CONSTANTS.INITIAL_CONFIDENCE;
350
+ this.db
351
+ .prepare(
352
+ `INSERT INTO instincts (
353
+ id, scope, project_hash, domain, trigger_condition, directive_action,
354
+ confidence, helpful_count, harmful_count, status,
355
+ created_at, last_verified_at, ttl_expires_at
356
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, 0, 0, 'active', ?, ?, ?)`
357
+ )
358
+ .run(
359
+ id,
360
+ sig.scope,
361
+ projHash,
362
+ sig.domain,
363
+ sig.trigger_condition,
364
+ sig.directive_action,
365
+ initialConf,
366
+ nowIso,
367
+ nowIso,
368
+ ttlIso
369
+ );
370
+ createdOrUpdated.push(this.getInstinctById(id));
371
+ }
372
+ }
373
+
374
+ return createdOrUpdated;
375
+ }
376
+
377
+ getInstinctById(id) {
378
+ if (!id) return null;
379
+ return this.db.prepare(`SELECT * FROM instincts WHERE id = ?`).get(id) || null;
380
+ }
381
+
382
+ listInstincts(filter = {}) {
383
+ const clauses = [];
384
+ const params = [];
385
+ if (filter.domain) {
386
+ clauses.push('domain = ?');
387
+ params.push(filter.domain);
388
+ }
389
+ if (filter.status) {
390
+ clauses.push('status = ?');
391
+ params.push(filter.status);
392
+ }
393
+ if (filter.projectHash) {
394
+ clauses.push('project_hash = ?');
395
+ params.push(filter.projectHash);
396
+ }
397
+ if (Number.isFinite(filter.minConfidence)) {
398
+ clauses.push('confidence >= ?');
399
+ params.push(Number(filter.minConfidence));
400
+ }
401
+ const whereSql = clauses.length > 0 ? `WHERE ${clauses.join(' AND ')}` : '';
402
+ return this.db
403
+ .prepare(`SELECT * FROM instincts ${whereSql} ORDER BY confidence DESC, helpful_count DESC`)
404
+ .all(...params);
405
+ }
406
+
407
+ /**
408
+ * Evaluates cross-project instincts eligible for global promotion (`confidence >= 0.80` across `>= 2` repos).
409
+ */
410
+ getGlobalPromotionCandidates(options = {}) {
411
+ const allActive = this.db
412
+ .prepare(`SELECT * FROM instincts WHERE status IN ('active', 'promoted')`)
413
+ .all();
414
+ return evaluateGlobalPromotionEligibility(allActive, options);
415
+ }
416
+
417
+ /**
418
+ * Deterministically updates confidence:
419
+ * - +0.12 when applied and subsequent turn passes tests with zero user reverts (`helpful_count++`)
420
+ * - -0.20 if a DET-01..16 violation or user revert occurs within 2 turns (`harmful_count++`)
421
+ *
422
+ * Automatically stages/applies a rule delta via PrefixCacheShield when
423
+ * `confidence >= 0.75 && helpful_count >= 3`.
424
+ */
425
+ recordOutcome(instinctId, outcome = {}) {
426
+ const inst = this.getInstinctById(instinctId);
427
+ if (!inst) {
428
+ throw new Error(`Instinct not found: ${instinctId}`);
429
+ }
430
+
431
+ const isHarmful =
432
+ outcome.harmful === true ||
433
+ outcome.userReverted === true ||
434
+ outcome.detViolation === true ||
435
+ Boolean(outcome.detectorViolation);
436
+
437
+ const isHelpful = !isHarmful && (outcome.helpful !== false && outcome.passedTests !== false);
438
+
439
+ let nextConfidence = Number(inst.confidence);
440
+ let nextHelpful = Number(inst.helpful_count);
441
+ let nextHarmful = Number(inst.harmful_count);
442
+ let nextStatus = inst.status;
443
+
444
+ if (isHarmful) {
445
+ nextConfidence = Math.max(
446
+ RSI_CONSTANTS.MIN_CONFIDENCE,
447
+ Number((nextConfidence + RSI_CONSTANTS.HARMFUL_DELTA).toFixed(4))
448
+ );
449
+ nextHarmful += 1;
450
+ } else if (isHelpful) {
451
+ nextConfidence = Math.min(
452
+ RSI_CONSTANTS.MAX_CONFIDENCE,
453
+ Number((nextConfidence + RSI_CONSTANTS.HELPFUL_DELTA).toFixed(4))
454
+ );
455
+ nextHelpful += 1;
456
+ }
457
+
458
+ const nowMs = this.nowFn();
459
+ const nowIso = new Date(nowMs).toISOString();
460
+ const ttlIso = new Date(nowMs + RSI_CONSTANTS.STALENESS_TTL_MS).toISOString();
461
+
462
+ let promotionResult = null;
463
+ if (
464
+ nextStatus !== 'quarantined' &&
465
+ nextConfidence >= RSI_CONSTANTS.PROMOTION_MIN_CONFIDENCE &&
466
+ nextHelpful >= RSI_CONSTANTS.PROMOTION_MIN_HELPFUL_COUNT
467
+ ) {
468
+ nextStatus = 'promoted';
469
+ const targetRulePath =
470
+ outcome.targetRulePath || this._resolveDefaultWorkspaceRulePath();
471
+ if (targetRulePath) {
472
+ promotionResult = this.promoteInstinctToRule(
473
+ {
474
+ ...inst,
475
+ confidence: nextConfidence,
476
+ helpful_count: nextHelpful,
477
+ harmful_count: nextHarmful,
478
+ status: nextStatus
479
+ },
480
+ {
481
+ targetPath: targetRulePath,
482
+ operation: outcome.operation || 'ADD',
483
+ session: outcome.session || {}
484
+ }
485
+ );
486
+ }
487
+ }
488
+
489
+ this.db
490
+ .prepare(
491
+ `UPDATE instincts
492
+ SET confidence = ?,
493
+ helpful_count = ?,
494
+ harmful_count = ?,
495
+ status = ?,
496
+ last_verified_at = ?,
497
+ ttl_expires_at = ?
498
+ WHERE id = ?`
499
+ )
500
+ .run(nextConfidence, nextHelpful, nextHarmful, nextStatus, nowIso, ttlIso, instinctId);
501
+
502
+ // Check if harmful_count >= 2 within 24h of a mutation triggers rollback tripwire
503
+ let rollbackResult = null;
504
+ if (isHarmful && nextHarmful >= RSI_CONSTANTS.TRIPWIRE_HARMFUL_COUNT_THRESHOLD) {
505
+ rollbackResult = this.evaluateRollbackTripwire({
506
+ instinctId,
507
+ reason: `harmful_count=${nextHarmful} reached threshold (${RSI_CONSTANTS.TRIPWIRE_HARMFUL_COUNT_THRESHOLD})`
508
+ });
509
+ }
510
+
511
+ return {
512
+ ...this.getInstinctById(instinctId),
513
+ promotionResult,
514
+ rollbackResult
515
+ };
516
+ }
517
+
518
+ _resolveDefaultWorkspaceRulePath() {
519
+ const contextMd = path.join(this.workspaceDir, '.agents', 'CONTEXT.md');
520
+ if (fs.existsSync(contextMd)) return contextMd;
521
+ return path.join(this.workspaceDir, 'GEMINI.md');
522
+ }
523
+
524
+ /**
525
+ * Stages or applies a deterministic rule delta via PrefixCacheShield and writes to
526
+ * Antigravity's native Knowledge Items store while recording a Rollback Tripwire snapshot.
527
+ */
528
+ promoteInstinctToRule(instinct, options = {}) {
529
+ const targetPath = path.resolve(options.targetPath || this._resolveDefaultWorkspaceRulePath());
530
+ assertMutableRsiTarget(targetPath);
531
+
532
+ const existingRulesContent =
533
+ options.existingRulesContent !== undefined
534
+ ? String(options.existingRulesContent)
535
+ : fs.existsSync(targetPath)
536
+ ? fs.readFileSync(targetPath, 'utf8')
537
+ : '';
538
+
539
+ if (existingRulesContent) {
540
+ const contradictionAudit = auditRuleContradictions(
541
+ instinct.directive_action || '',
542
+ existingRulesContent
543
+ );
544
+ if (contradictionAudit.hasContradiction) {
545
+ if (instinct.id && this.db) {
546
+ this.db
547
+ .prepare(`UPDATE instincts SET status = 'quarantined' WHERE id = ?`)
548
+ .run(instinct.id);
549
+ }
550
+ return {
551
+ contradictionBlocked: true,
552
+ contradictionAudit,
553
+ targetPath,
554
+ ruleLine: null,
555
+ shieldResult: null
556
+ };
557
+ }
558
+ }
559
+
560
+ const ruleLine = `- **[RSI:${instinct.domain}]** ${instinct.directive_action} *(trigger: ${instinct.trigger_condition}; confidence: ${Number(instinct.confidence).toFixed(2)})*`;
561
+
562
+ // Record pre-mutation snapshot before flushing or staging
563
+ const snapshotId = this._recordMutationSnapshot({
564
+ instinctId: instinct.id,
565
+ domain: instinct.domain,
566
+ targetPath
567
+ });
568
+
569
+ const resolvedSession = options.session || {
570
+ cacheState: options.cacheState,
571
+ cacheWarm: options.cacheWarm,
572
+ cachedTokens: options.cachedTokens,
573
+ cacheTtlSeconds: options.cacheTtlSeconds,
574
+ forceColdBust: options.forceColdBust,
575
+ postCompact: options.postCompact
576
+ };
577
+
578
+ const shieldResult = this.prefixShield.stageOrApplyDelta(
579
+ {
580
+ targetPath,
581
+ operation: options.operation || 'ADD',
582
+ ruleText: ruleLine,
583
+ source: 'rsi-instinct-engine',
584
+ metadata: {
585
+ instinctId: instinct.id,
586
+ domain: instinct.domain,
587
+ confidence: instinct.confidence,
588
+ snapshotId
589
+ }
590
+ },
591
+ resolvedSession
592
+ );
593
+
594
+ // Also update local Knowledge Items index
595
+ this._syncKnowledgeItem(instinct, ruleLine);
596
+
597
+ return {
598
+ snapshotId,
599
+ targetPath,
600
+ ruleLine,
601
+ staged: Boolean(shieldResult.staged),
602
+ deferred: Boolean(shieldResult.deferred),
603
+ shieldResult
604
+ };
605
+ }
606
+
607
+ _syncKnowledgeItem(instinct, ruleLine) {
608
+ try {
609
+ const kiDir = path.join(this.homeDir, '.gemini', 'antigravity', 'agy-horizon', 'knowledge_items');
610
+ fs.mkdirSync(kiDir, { recursive: true });
611
+ const kiPath = path.join(kiDir, `${instinct.domain}.json`);
612
+ const existing = fs.existsSync(kiPath)
613
+ ? JSON.parse(fs.readFileSync(kiPath, 'utf8'))
614
+ : { domain: instinct.domain, items: [] };
615
+ const filtered = (existing.items || []).filter(item => item.id !== instinct.id);
616
+ filtered.push({
617
+ id: instinct.id,
618
+ trigger_condition: instinct.trigger_condition,
619
+ directive_action: instinct.directive_action,
620
+ confidence: instinct.confidence,
621
+ helpful_count: instinct.helpful_count,
622
+ ruleLine,
623
+ updated_at: new Date(this.nowFn()).toISOString()
624
+ });
625
+ existing.items = filtered;
626
+ atomicWriteFileSync(kiPath, JSON.stringify(existing, null, 2) + '\n', { encoding: 'utf8' });
627
+ } catch {}
628
+ }
629
+
630
+ /**
631
+ * Injects active instincts with `confidence >= 0.55` and valid 48h TTL into
632
+ * `brain/<GUID>/task.md` as a compact `<coach_instincts>` block for mid-session coaching.
633
+ */
634
+ injectCoachInstinctsIntoTaskMd(taskMdPath) {
635
+ if (!taskMdPath) {
636
+ throw new Error('taskMdPath is required for injectCoachInstinctsIntoTaskMd');
637
+ }
638
+ assertMutableRsiTarget(taskMdPath);
639
+
640
+ const nowIso = new Date(this.nowFn()).toISOString();
641
+ const eligible = this.db
642
+ .prepare(
643
+ `SELECT * FROM instincts
644
+ WHERE status IN ('active', 'promoted')
645
+ AND confidence >= ?
646
+ AND ttl_expires_at > ?
647
+ ORDER BY confidence DESC, helpful_count DESC
648
+ LIMIT 10`
649
+ )
650
+ .all(RSI_CONSTANTS.COACH_INJECTION_MIN_CONFIDENCE, nowIso);
651
+
652
+ const existingContent = fs.existsSync(taskMdPath) ? fs.readFileSync(taskMdPath, 'utf8') : '';
653
+ const stripped = existingContent.replace(/\n*<coach_instincts>[\s\S]*?<\/coach_instincts>\n*/g, '\n');
654
+
655
+ if (eligible.length === 0) {
656
+ if (stripped !== existingContent) {
657
+ atomicWriteFileSync(taskMdPath, stripped.trimEnd() + '\n', { encoding: 'utf8' });
658
+ }
659
+ return { injectedCount: 0, instincts: [] };
660
+ }
661
+
662
+ const lines = [
663
+ '<coach_instincts>',
664
+ '<!-- Active Mid-Session Atomic Instincts (48h TTL) -->',
665
+ ...eligible.map(
666
+ inst =>
667
+ `- [${inst.domain} | conf=${Number(inst.confidence).toFixed(2)}] ${inst.directive_action} (when: ${inst.trigger_condition})`
668
+ ),
669
+ '</coach_instincts>'
670
+ ];
671
+
672
+ const updatedContent = `${stripped.trimEnd()}\n\n${lines.join('\n')}\n`;
673
+ atomicWriteFileSync(taskMdPath, updatedContent, { encoding: 'utf8' });
674
+
675
+ return {
676
+ injectedCount: eligible.length,
677
+ instincts: eligible,
678
+ block: lines.join('\n')
679
+ };
680
+ }
681
+
682
+ /**
683
+ * Detects domain clusters where >= 5 high-confidence instincts are ready to evolve into a SKILL.md.
684
+ */
685
+ getDomainClusters(options = {}) {
686
+ const minCount = Number.isFinite(options.minCount)
687
+ ? options.minCount
688
+ : RSI_CONSTANTS.EVOLVE_CLUSTER_MIN_COUNT;
689
+ const minConfidence = Number.isFinite(options.minConfidence)
690
+ ? options.minConfidence
691
+ : RSI_CONSTANTS.EVOLVE_CLUSTER_MIN_CONFIDENCE;
692
+
693
+ const rows = this.db
694
+ .prepare(
695
+ `SELECT domain, COUNT(*) AS count, AVG(confidence) AS avg_confidence
696
+ FROM instincts
697
+ WHERE status != 'quarantined'
698
+ AND confidence >= ?
699
+ GROUP BY domain
700
+ HAVING COUNT(*) >= ?
701
+ ORDER BY count DESC, avg_confidence DESC`
702
+ )
703
+ .all(minConfidence, minCount);
704
+
705
+ return rows.map(r => ({
706
+ domain: r.domain,
707
+ count: Number(r.count),
708
+ avgConfidence: Number(Number(r.avg_confidence).toFixed(2)),
709
+ badge: `🧬 ${r.count} Instincts Ready to Evolve (/evolve)`,
710
+ command: `/evolve ${r.domain}`
711
+ }));
712
+ }
713
+
714
+ /**
715
+ * Executes `/evolve` for a clustered domain, synthesizing a valid Antigravity SKILL.md
716
+ * with YAML frontmatter (`name`, `description`) and structured instructions.
717
+ */
718
+ evolveDomainToSkill(domain, options = {}) {
719
+ if (!domain || typeof domain !== 'string') {
720
+ throw new Error('domain is required for evolveDomainToSkill');
721
+ }
722
+ const minConfidence = Number.isFinite(options.minConfidence)
723
+ ? options.minConfidence
724
+ : RSI_CONSTANTS.EVOLVE_CLUSTER_MIN_CONFIDENCE;
725
+
726
+ const instincts = this.db
727
+ .prepare(
728
+ `SELECT * FROM instincts
729
+ WHERE domain = ?
730
+ AND status != 'quarantined'
731
+ AND confidence >= ?
732
+ ORDER BY confidence DESC, helpful_count DESC`
733
+ )
734
+ .all(domain, minConfidence);
735
+
736
+ const minCount = Number.isFinite(options.minCount)
737
+ ? options.minCount
738
+ : RSI_CONSTANTS.EVOLVE_CLUSTER_MIN_COUNT;
739
+
740
+ if (instincts.length < minCount) {
741
+ throw new Error(
742
+ `Domain "${domain}" has ${instincts.length} eligible instincts; at least ${minCount} required to /evolve`
743
+ );
744
+ }
745
+
746
+ const skillSlug = options.skillSlug || `${domain.toLowerCase().replace(/[^a-z0-9-]+/g, '-')}-instincts`;
747
+ const skillPath =
748
+ options.skillPath ||
749
+ path.join(this.homeDir, '.gemini', 'antigravity', 'skills', skillSlug, 'SKILL.md');
750
+
751
+ assertMutableRsiTarget(skillPath);
752
+
753
+ const snapshotId = this._recordMutationSnapshot({
754
+ instinctId: instincts[0].id,
755
+ domain,
756
+ targetPath: skillPath
757
+ });
758
+
759
+ const yamlFrontmatter = [
760
+ '---',
761
+ `name: ${skillSlug}`,
762
+ `description: Evolved Atomic Instincts for the ${domain} domain (${instincts.length} verified rules synthesized by Highbeam RSI Engine).`,
763
+ '---'
764
+ ].join('\n');
765
+
766
+ const bodyLines = [
767
+ yamlFrontmatter,
768
+ '',
769
+ `# ${skillSlug} — Evolved Domain Skill (\`${domain}\`)`,
770
+ '',
771
+ 'This skill was automatically synthesized from high-confidence Atomic Instincts verified across recent coding sessions.',
772
+ '',
773
+ '## Mandatory Domain Directives',
774
+ '',
775
+ ...instincts.map(
776
+ (inst, idx) =>
777
+ `${idx + 1}. **${inst.directive_action}**\n - *Trigger*: ${inst.trigger_condition}\n - *Confidence*: \`${Number(inst.confidence).toFixed(2)}\` (\`helpful=${inst.helpful_count}\`, \`harmful=${inst.harmful_count}\`)`
778
+ ),
779
+ ''
780
+ ];
781
+
782
+ const skillContent = bodyLines.join('\n');
783
+
784
+ const resolvedSession = options.session || {
785
+ cacheState: options.cacheState,
786
+ cacheWarm: options.cacheWarm,
787
+ cachedTokens: options.cachedTokens,
788
+ cacheTtlSeconds: options.cacheTtlSeconds,
789
+ forceColdBust: options.forceColdBust,
790
+ postCompact: options.postCompact
791
+ };
792
+
793
+ const shieldResult = this.prefixShield.stageOrApplyDelta(
794
+ {
795
+ targetPath: skillPath,
796
+ operation: 'REPLACE',
797
+ newContent: skillContent,
798
+ source: 'rsi-evolve',
799
+ metadata: {
800
+ domain,
801
+ skillSlug,
802
+ instinctIds: instincts.map(i => i.id),
803
+ snapshotId
804
+ }
805
+ },
806
+ resolvedSession
807
+ );
808
+
809
+ return {
810
+ domain,
811
+ skillSlug,
812
+ skillPath,
813
+ instinctCount: instincts.length,
814
+ snapshotId,
815
+ skillContent,
816
+ staged: Boolean(shieldResult.staged),
817
+ deferred: Boolean(shieldResult.deferred),
818
+ shieldResult
819
+ };
820
+ }
821
+
822
+ _recordMutationSnapshot({ instinctId = null, domain = null, targetPath }) {
823
+ const resolved = path.resolve(targetPath);
824
+ const existedBefore = fs.existsSync(resolved) ? 1 : 0;
825
+ const previousContent = existedBefore ? fs.readFileSync(resolved, 'utf8') : null;
826
+ const gitCommitSha = tryGetGitHeadSha(this.workspaceDir);
827
+ const baselinePassRate = this._computeRollingPassRate();
828
+ const mutationId = `mut-${crypto.randomBytes(6).toString('hex')}`;
829
+
830
+ this.db
831
+ .prepare(
832
+ `INSERT INTO mutation_snapshots (
833
+ mutation_id, instinct_id, domain, target_path,
834
+ existed_before, previous_content, git_commit_sha,
835
+ baseline_pass_rate, created_at_ms, rolled_back
836
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 0)`
837
+ )
838
+ .run(
839
+ mutationId,
840
+ instinctId,
841
+ domain,
842
+ resolved,
843
+ existedBefore,
844
+ previousContent,
845
+ gitCommitSha,
846
+ baselinePassRate,
847
+ this.nowFn()
848
+ );
849
+
850
+ return mutationId;
851
+ }
852
+
853
+ _computeRollingPassRate() {
854
+ if (this._rollingTestHistory.length === 0) return 1.0;
855
+ const recent = this._rollingTestHistory.slice(-5);
856
+ const sum = recent.reduce((acc, item) => acc + Number(item.passRate ?? (item.passed ? 1.0 : 0.0)), 0);
857
+ return sum / recent.length;
858
+ }
859
+
860
+ /**
861
+ * Records a turn's test suite execution result into the rolling 5-turn window.
862
+ * Automatically triggers the Git Rollback Tripwire if the rolling 5-turn test
863
+ * pass rate drops by > 15% within 24 hours of a rule/skill mutation.
864
+ */
865
+ recordTestTurnResult(testResult = {}) {
866
+ const passRate = Number.isFinite(testResult.passRate)
867
+ ? Number(testResult.passRate)
868
+ : testResult.passed === false
869
+ ? 0.0
870
+ : 1.0;
871
+
872
+ this._rollingTestHistory.push({
873
+ passRate,
874
+ timestampMs: this.nowFn()
875
+ });
876
+ if (this._rollingTestHistory.length > 5) {
877
+ this._rollingTestHistory.shift();
878
+ }
879
+
880
+ const currentRollingRate = this._computeRollingPassRate();
881
+ const activeSnapshots = this.db
882
+ .prepare(
883
+ `SELECT * FROM mutation_snapshots
884
+ WHERE rolled_back = 0
885
+ AND created_at_ms >= ?
886
+ ORDER BY created_at_ms DESC`
887
+ )
888
+ .all(this.nowFn() - RSI_CONSTANTS.TRIPWIRE_WINDOW_MS);
889
+
890
+ for (const snap of activeSnapshots) {
891
+ const drop = Number(snap.baseline_pass_rate) - currentRollingRate;
892
+ if (drop > RSI_CONSTANTS.TRIPWIRE_PASS_RATE_DROP_THRESHOLD) {
893
+ return this.evaluateRollbackTripwire({
894
+ mutationId: snap.mutation_id,
895
+ instinctId: snap.instinct_id,
896
+ domain: snap.domain,
897
+ reason: `Rolling 5-turn test pass rate dropped by ${(drop * 100).toFixed(1)}% (baseline ${(snap.baseline_pass_rate * 100).toFixed(1)}% -> ${(currentRollingRate * 100).toFixed(1)}%)`
898
+ });
899
+ }
900
+ }
901
+
902
+ return {
903
+ rolledBack: false,
904
+ rollingPassRate: currentRollingRate
905
+ };
906
+ }
907
+
908
+ /**
909
+ * Executes the Git Rollback Tripwire:
910
+ * - Reverts the mutated GEMINI.md / SKILL.md delta on disk (via git checkout or snapshot restore)
911
+ * - Purges any staged PrefixCacheShield deltas for the offending instinct/file
912
+ * - Quarantines the offending instinct in instincts.db
913
+ */
914
+ evaluateRollbackTripwire(trigger = {}) {
915
+ const cutoffMs = this.nowFn() - RSI_CONSTANTS.TRIPWIRE_WINDOW_MS;
916
+ let snapshots = [];
917
+
918
+ if (trigger.mutationId) {
919
+ const snap = this.db
920
+ .prepare(`SELECT * FROM mutation_snapshots WHERE mutation_id = ? AND rolled_back = 0`)
921
+ .get(trigger.mutationId);
922
+ if (snap) snapshots = [snap];
923
+ } else if (trigger.instinctId) {
924
+ snapshots = this.db
925
+ .prepare(
926
+ `SELECT * FROM mutation_snapshots
927
+ WHERE instinct_id = ? AND rolled_back = 0 AND created_at_ms >= ?
928
+ ORDER BY created_at_ms DESC`
929
+ )
930
+ .all(trigger.instinctId, cutoffMs);
931
+ } else {
932
+ snapshots = this.db
933
+ .prepare(
934
+ `SELECT * FROM mutation_snapshots
935
+ WHERE rolled_back = 0 AND created_at_ms >= ?
936
+ ORDER BY created_at_ms DESC`
937
+ )
938
+ .all(cutoffMs);
939
+ }
940
+
941
+ const revertedFiles = [];
942
+ const quarantinedInstinctIds = new Set();
943
+
944
+ for (const snap of snapshots) {
945
+ const targetPath = snap.target_path;
946
+ let restoredViaGit = false;
947
+
948
+ if (snap.git_commit_sha && fs.existsSync(this.workspaceDir)) {
949
+ try {
950
+ const relPath = path.relative(this.workspaceDir, targetPath);
951
+ if (!relPath.startsWith('..') && !path.isAbsolute(relPath)) {
952
+ execFileSync('git', ['checkout', snap.git_commit_sha, '--', relPath], {
953
+ cwd: this.workspaceDir,
954
+ stdio: ['ignore', 'pipe', 'ignore'],
955
+ timeout: 3000
956
+ });
957
+ restoredViaGit = true;
958
+ }
959
+ } catch {
960
+ restoredViaGit = false;
961
+ }
962
+ }
963
+
964
+ // Ensure exact pre-mutation working-tree state is restored even if working tree had uncommitted baseline edits
965
+ if (Number(snap.existed_before) === 1 && snap.previous_content !== null) {
966
+ atomicWriteFileSync(targetPath, snap.previous_content, { encoding: 'utf8' });
967
+ } else if (Number(snap.existed_before) === 0 && fs.existsSync(targetPath)) {
968
+ try {
969
+ fs.unlinkSync(targetPath);
970
+ } catch {}
971
+ }
972
+
973
+ this.db
974
+ .prepare(
975
+ `UPDATE mutation_snapshots
976
+ SET rolled_back = 1, rollback_reason = ?
977
+ WHERE mutation_id = ?`
978
+ )
979
+ .run(trigger.reason || 'TRIPWIRE_REGRESSION', snap.mutation_id);
980
+
981
+ revertedFiles.push({
982
+ targetPath,
983
+ mutationId: snap.mutation_id,
984
+ gitCommitSha: snap.git_commit_sha,
985
+ restoredViaGit
986
+ });
987
+
988
+ if (snap.instinct_id) {
989
+ quarantinedInstinctIds.add(snap.instinct_id);
990
+ }
991
+ }
992
+
993
+ if (trigger.instinctId) {
994
+ quarantinedInstinctIds.add(trigger.instinctId);
995
+ }
996
+
997
+ for (const instId of quarantinedInstinctIds) {
998
+ this.db
999
+ .prepare(`UPDATE instincts SET status = 'quarantined' WHERE id = ?`)
1000
+ .run(instId);
1001
+ }
1002
+
1003
+ return {
1004
+ rolledBack: revertedFiles.length > 0 || quarantinedInstinctIds.size > 0,
1005
+ reason: trigger.reason || 'TRIPWIRE_REGRESSION',
1006
+ revertedFiles,
1007
+ quarantinedInstincts: Array.from(quarantinedInstinctIds)
1008
+ };
1009
+ }
1010
+
1011
+ /**
1012
+ * Rank 9 (`RSI-01`): Prefix Diet (`> 8,000` static rule tokens), Skill Fault Delta Router,
1013
+ * `>= 5` validated domain instincts floor, zero recursive LLM self-critique subagents,
1014
+ * and mandatory 1-click user diff approval gated by `TurnZeroGate`.
1015
+ */
1016
+ auditPrefixDietAndRouteSkillFault(input = {}) {
1017
+ return auditPrefixDietAndRouteSkillFault(input, {
1018
+ workspaceDir: this.workspaceDir,
1019
+ turnZeroGate: this.turnZeroGate,
1020
+ db: this.db
1021
+ });
1022
+ }
1023
+ }
1024
+
1025
+ export function extractMarkdownDomainSections(markdown = '') {
1026
+ const lines = String(markdown || '').split(/\r?\n/);
1027
+ const sections = [];
1028
+ let currentHeading = null;
1029
+ let currentChars = 0;
1030
+
1031
+ const flush = () => {
1032
+ if (!currentHeading) return;
1033
+ const slug = currentHeading
1034
+ .toLowerCase()
1035
+ .replace(/[^a-z0-9]+/g, () => '-')
1036
+ .replace(/^-+|-+$/g, () => '');
1037
+ if (slug && !/^(ground-rules|invariants|core|overview)$/.test(slug)) {
1038
+ sections.push({
1039
+ domain: slug,
1040
+ heading: currentHeading,
1041
+ tokens: Math.max(1, Math.ceil(currentChars / 4))
1042
+ });
1043
+ }
1044
+ };
1045
+
1046
+ for (const line of lines) {
1047
+ const m = line.match(/^##\s+(.+)$/);
1048
+ if (m) {
1049
+ flush();
1050
+ currentHeading = m[1].trim();
1051
+ currentChars = line.length;
1052
+ } else if (currentHeading) {
1053
+ currentChars += line.length + 1;
1054
+ }
1055
+ }
1056
+ flush();
1057
+ return sections;
1058
+ }
1059
+
1060
+ export function auditPrefixDietAndRouteSkillFault(input = {}, options = {}) {
1061
+ const workspaceDir = options.workspaceDir || input.workspaceDir || process.cwd();
1062
+ const gate = options.turnZeroGate || input.turnZeroGate || new TurnZeroGate({ workspaceDir });
1063
+ const db = options.db || null;
1064
+
1065
+ // Hard outlaw recursive LLM self-critique subagents
1066
+ const attemptedRecursiveCritique = Boolean(
1067
+ input.recursiveSubagentCritique || input.spawnCritiqueSubagent
1068
+ );
1069
+
1070
+ // Measure static AGENTS.md / .agents/rules/*.md token overhead if not explicitly supplied
1071
+ let staticRulesTokens = Number(input.staticRulesTokens ?? -1);
1072
+ let domainSections = Array.isArray(input.domainSections) ? input.domainSections : null;
1073
+ if (staticRulesTokens < 0 || !domainSections) {
1074
+ let combinedText = '';
1075
+ const agentsPath = path.join(workspaceDir, 'AGENTS.md');
1076
+ if (fs.existsSync(agentsPath)) {
1077
+ try {
1078
+ combinedText += fs.readFileSync(agentsPath, 'utf8') + '\n';
1079
+ } catch {}
1080
+ }
1081
+ const rulesDir = path.join(workspaceDir, '.agents', 'rules');
1082
+ if (fs.existsSync(rulesDir)) {
1083
+ try {
1084
+ for (const f of fs.readdirSync(rulesDir)) {
1085
+ if (f.endsWith('.md')) {
1086
+ combinedText += fs.readFileSync(path.join(rulesDir, f), 'utf8') + '\n';
1087
+ }
1088
+ }
1089
+ } catch {}
1090
+ }
1091
+ if (staticRulesTokens < 0) {
1092
+ staticRulesTokens = Math.ceil(combinedText.length / 4);
1093
+ }
1094
+ if (!domainSections) {
1095
+ domainSections = extractMarkdownDomainSections(combinedText);
1096
+ }
1097
+ }
1098
+
1099
+ // Count validated domain instincts from input or instincts.db
1100
+ const domain = String(input.domain || inferInstinctDomain(input.userCorrectionText || '', input.files || []));
1101
+ let validatedInstincts = Array.isArray(input.validatedInstincts) ? input.validatedInstincts : null;
1102
+ if (!validatedInstincts && db) {
1103
+ try {
1104
+ validatedInstincts = db
1105
+ .prepare(
1106
+ `SELECT * FROM instincts
1107
+ WHERE domain = ? AND status = 'active' AND confidence >= ? AND harmful_count = 0
1108
+ ORDER BY confidence DESC`
1109
+ )
1110
+ .all(domain, RSI_CONSTANTS.EVOLVE_CLUSTER_MIN_CONFIDENCE);
1111
+ } catch {
1112
+ validatedInstincts = [];
1113
+ }
1114
+ }
1115
+ const validatedList = Array.isArray(validatedInstincts) ? validatedInstincts : [];
1116
+ const validatedCount = Number.isFinite(input.validatedDomainInstinctsCount)
1117
+ ? Number(input.validatedDomainInstinctsCount)
1118
+ : validatedList.length;
1119
+
1120
+ const rsi01 = evaluateRsi01PrefixDietAndSkillFault({
1121
+ staticRulesTokens,
1122
+ staticRulesOverheadCeiling: Number(input.staticRulesOverheadCeiling || 8000),
1123
+ domainSections,
1124
+ lastExecutedSkill: input.lastExecutedSkill || null,
1125
+ userCorrectionText: input.userCorrectionText || '',
1126
+ validatedDomainInstinctsCount: validatedCount
1127
+ });
1128
+
1129
+ // Build proposed SKILL.md draft & unified diff when either routing a skill fault OR synthesizing >= 5 instincts
1130
+ let proposedSkillPath = null;
1131
+ let proposedSkillContent = null;
1132
+ let unifiedDiff = null;
1133
+
1134
+ if (rsi01.routedDeltaTarget && rsi01.routedDeltaTarget.endsWith('/SKILL.md')) {
1135
+ proposedSkillPath = path.join(workspaceDir, rsi01.routedDeltaTarget);
1136
+ const skillSlug = path.basename(path.dirname(proposedSkillPath));
1137
+ const existing = fs.existsSync(proposedSkillPath) ? fs.readFileSync(proposedSkillPath, 'utf8') : '';
1138
+ const deltaBullet = `- ${String(input.userCorrectionText).trim()}`;
1139
+ proposedSkillContent = existing
1140
+ ? `${existing.trimEnd()}\n${deltaBullet}\n`
1141
+ : `---\nname: ${skillSlug}\ndescription: Domain skill directives maintained by Highbeam.\n---\n\n# ${skillSlug}\n\n## Directives\n${deltaBullet}\n`;
1142
+ unifiedDiff = `--- a/${rsi01.routedDeltaTarget}\n+++ b/${rsi01.routedDeltaTarget}\n@@\n+${deltaBullet}`;
1143
+ } else if (rsi01.canSynthesizeNewSkillDraft) {
1144
+ const cleanSlug = domain.toLowerCase().replace(/[^a-z0-9-]+/g, () => '-');
1145
+ const relTarget = `.agents/skills/${cleanSlug}/SKILL.md`;
1146
+ proposedSkillPath = path.join(workspaceDir, relTarget);
1147
+ const bulletLines = (validatedList.length > 0
1148
+ ? validatedList.map((inst) => `- ${inst.directive_action || inst}`)
1149
+ : Array.from({ length: validatedCount }, (_, idx) => `- Validated ${cleanSlug} directive #${idx + 1}`)
1150
+ ).join('\n');
1151
+ proposedSkillContent = `---\nname: ${cleanSlug}\ndescription: Synthesized from ${validatedCount} validated ${cleanSlug} instincts.\n---\n\n# ${cleanSlug}\n\n## Mandatory Directives\n${bulletLines}\n`;
1152
+ unifiedDiff = `--- /dev/null\n+++ b/${relTarget}\n@@\n+${bulletLines.replace(/\n/g, () => '\n+')}`;
1153
+ }
1154
+
1155
+ // Enforce mandatory 1-click user diff approval AND TurnZeroGate cold-cache lock
1156
+ const userApprovedDiff = input.userApprovedDiff === true;
1157
+ let mutation = {
1158
+ applied: false,
1159
+ queued: false,
1160
+ awaitingUserDiffApproval: Boolean(proposedSkillPath && !userApprovedDiff)
1161
+ };
1162
+
1163
+ if (!attemptedRecursiveCritique && proposedSkillPath && proposedSkillContent && userApprovedDiff) {
1164
+ assertMutableRsiTarget(proposedSkillPath);
1165
+ const session = input.session || {
1166
+ turnCount: Number(input.turnCount ?? 0),
1167
+ cachedTokens: Number(input.cachedTokens ?? 0),
1168
+ ttlRemainingSeconds: Number(input.ttlRemainingSeconds ?? 0)
1169
+ };
1170
+ const gateRes = gate.queueOrApplyHygieneMutation(
1171
+ {
1172
+ type: 'RSI01_SKILL_DIFF_APPLY',
1173
+ targetPath: proposedSkillPath,
1174
+ newContent: proposedSkillContent
1175
+ },
1176
+ session
1177
+ );
1178
+ mutation = {
1179
+ ...gateRes,
1180
+ awaitingUserDiffApproval: false
1181
+ };
1182
+ }
1183
+
1184
+ return {
1185
+ ...rsi01,
1186
+ staticRulesTokens,
1187
+ domain,
1188
+ validatedDomainInstinctsCount: validatedCount,
1189
+ recursiveSubagentRejected: attemptedRecursiveCritique,
1190
+ proposedSkillPath,
1191
+ proposedSkillContent,
1192
+ unifiedDiff,
1193
+ mutation
1194
+ };
1195
+ }
1196
+
1197
+ export default RsiInstinctEngine;