@aria_asi/cli 0.2.40 → 0.2.41

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 (802) hide show
  1. package/bin/aria.js +236 -34
  2. package/dist/aria-connector/src/action-ledger-core.d.ts +387 -0
  3. package/dist/aria-connector/src/action-ledger-core.d.ts.map +1 -0
  4. package/dist/aria-connector/src/action-ledger-core.js +638 -0
  5. package/dist/aria-connector/src/action-ledger-core.js.map +1 -0
  6. package/dist/aria-connector/src/chat.d.ts.map +1 -1
  7. package/dist/aria-connector/src/chat.js +5 -6
  8. package/dist/aria-connector/src/chat.js.map +1 -1
  9. package/dist/aria-connector/src/codebase-scanner.d.ts +1 -1
  10. package/dist/aria-connector/src/codebase-scanner.d.ts.map +1 -1
  11. package/dist/aria-connector/src/connectors/claude-code.d.ts +1 -0
  12. package/dist/aria-connector/src/connectors/claude-code.d.ts.map +1 -1
  13. package/dist/aria-connector/src/connectors/claude-code.js +152 -14
  14. package/dist/aria-connector/src/connectors/claude-code.js.map +1 -1
  15. package/dist/aria-connector/src/connectors/codebase-awareness.d.ts +10 -0
  16. package/dist/aria-connector/src/connectors/codebase-awareness.d.ts.map +1 -1
  17. package/dist/aria-connector/src/connectors/codebase-awareness.js +276 -27
  18. package/dist/aria-connector/src/connectors/codebase-awareness.js.map +1 -1
  19. package/dist/aria-connector/src/connectors/codex.d.ts +3 -1
  20. package/dist/aria-connector/src/connectors/codex.d.ts.map +1 -1
  21. package/dist/aria-connector/src/connectors/codex.js +1223 -41
  22. package/dist/aria-connector/src/connectors/codex.js.map +1 -1
  23. package/dist/aria-connector/src/connectors/cursor.d.ts.map +1 -1
  24. package/dist/aria-connector/src/connectors/cursor.js +7 -0
  25. package/dist/aria-connector/src/connectors/cursor.js.map +1 -1
  26. package/dist/aria-connector/src/connectors/governed-adapter.d.ts +30 -0
  27. package/dist/aria-connector/src/connectors/governed-adapter.d.ts.map +1 -0
  28. package/dist/aria-connector/src/connectors/governed-adapter.js +132 -0
  29. package/dist/aria-connector/src/connectors/governed-adapter.js.map +1 -0
  30. package/dist/aria-connector/src/connectors/opencode.d.ts +3 -1
  31. package/dist/aria-connector/src/connectors/opencode.d.ts.map +1 -1
  32. package/dist/aria-connector/src/connectors/opencode.js +18 -2
  33. package/dist/aria-connector/src/connectors/opencode.js.map +1 -1
  34. package/dist/aria-connector/src/connectors/repo-guard.d.ts.map +1 -1
  35. package/dist/aria-connector/src/connectors/repo-guard.js +25 -14
  36. package/dist/aria-connector/src/connectors/repo-guard.js.map +1 -1
  37. package/dist/aria-connector/src/connectors/runtime.d.ts.map +1 -1
  38. package/dist/aria-connector/src/connectors/runtime.js +92 -2
  39. package/dist/aria-connector/src/connectors/runtime.js.map +1 -1
  40. package/dist/aria-connector/src/connectors/shell.d.ts.map +1 -1
  41. package/dist/aria-connector/src/connectors/shell.js +123 -7
  42. package/dist/aria-connector/src/connectors/shell.js.map +1 -1
  43. package/dist/aria-connector/src/cross-cli-hive-binding.d.ts +63 -0
  44. package/dist/aria-connector/src/cross-cli-hive-binding.d.ts.map +1 -0
  45. package/dist/aria-connector/src/cross-cli-hive-binding.js +205 -0
  46. package/dist/aria-connector/src/cross-cli-hive-binding.js.map +1 -0
  47. package/dist/aria-connector/src/garden-control-plane.d.ts +6 -1
  48. package/dist/aria-connector/src/garden-control-plane.d.ts.map +1 -1
  49. package/dist/aria-connector/src/garden-control-plane.js +8 -2
  50. package/dist/aria-connector/src/garden-control-plane.js.map +1 -1
  51. package/dist/aria-connector/src/governed-surface-runner.d.ts +189 -0
  52. package/dist/aria-connector/src/governed-surface-runner.d.ts.map +1 -0
  53. package/dist/aria-connector/src/governed-surface-runner.js +1022 -0
  54. package/dist/aria-connector/src/governed-surface-runner.js.map +1 -0
  55. package/dist/aria-connector/src/index.d.ts +10 -1
  56. package/dist/aria-connector/src/index.d.ts.map +1 -1
  57. package/dist/aria-connector/src/index.js +5 -0
  58. package/dist/aria-connector/src/index.js.map +1 -1
  59. package/dist/aria-connector/src/task-runner.d.ts +3 -0
  60. package/dist/aria-connector/src/task-runner.d.ts.map +1 -0
  61. package/dist/aria-connector/src/task-runner.js +3526 -0
  62. package/dist/aria-connector/src/task-runner.js.map +1 -0
  63. package/dist/aria-web/src/lib/codebase-scanner.d.ts +21 -2
  64. package/dist/aria-web/src/lib/codebase-scanner.d.ts.map +1 -1
  65. package/dist/aria-web/src/lib/codebase-scanner.js +59 -14
  66. package/dist/aria-web/src/lib/codebase-scanner.js.map +1 -1
  67. package/dist/assets/hooks/README.md +58 -0
  68. package/dist/assets/hooks/aria-agent-handoff.mjs +147 -2
  69. package/dist/assets/hooks/aria-agent-ledger-merge.mjs +31 -7
  70. package/dist/assets/hooks/aria-architect-fallback.mjs +10 -2
  71. package/dist/assets/hooks/aria-claim-evidence-stop-gate.mjs +240 -0
  72. package/dist/assets/hooks/aria-cognition-substrate-binding.mjs +84 -10
  73. package/dist/assets/hooks/aria-first-class-coach.mjs +305 -10
  74. package/dist/assets/hooks/aria-harness-via-sdk.mjs +93 -16
  75. package/dist/assets/hooks/aria-import-resolution-gate.mjs +106 -20
  76. package/dist/assets/hooks/aria-outcome-record.mjs +56 -20
  77. package/dist/assets/hooks/aria-pre-emit-autoload.mjs +1809 -0
  78. package/dist/assets/hooks/aria-pre-emit-autoload.mjs.before-orchestration-redesign +1400 -0
  79. package/dist/assets/hooks/aria-pre-emit-dryrun.mjs +22 -3
  80. package/dist/assets/hooks/aria-pre-text-gate.mjs +11 -2
  81. package/dist/assets/hooks/aria-pre-tool-gate.mjs +477 -81
  82. package/dist/assets/hooks/aria-pre-tool-use.mjs +70 -6
  83. package/dist/assets/hooks/aria-preprompt-consult.mjs +23 -4
  84. package/dist/assets/hooks/aria-repo-doctrine-gate.mjs +29 -3
  85. package/dist/assets/hooks/aria-stop-gate.mjs +585 -76
  86. package/dist/assets/hooks/aria-trigger-autolearn.mjs +17 -3
  87. package/dist/assets/hooks/aria-universal-turn-packet.mjs +1165 -0
  88. package/dist/assets/hooks/aria-userprompt-abandon-detect.mjs +9 -1
  89. package/dist/assets/hooks/canonical-settings-block.json +172 -0
  90. package/dist/assets/hooks/codex-native/aria-harness-ticker-sidecar.mjs +92 -0
  91. package/dist/assets/hooks/codex-native/aria-hive-wal-consumer.mjs +86 -0
  92. package/dist/assets/hooks/codex-native/aria-live-ticker.mjs +38 -0
  93. package/dist/assets/hooks/codex-native/aria-post-tool-use.mjs +236 -0
  94. package/dist/assets/hooks/codex-native/aria-pre-tool-use.mjs +362 -0
  95. package/dist/assets/hooks/codex-native/aria-stop.mjs +691 -0
  96. package/dist/assets/hooks/codex-native/aria-userprompt-submit.mjs +623 -0
  97. package/dist/assets/hooks/codex-native/atlas-session-context.mjs +121 -0
  98. package/dist/assets/hooks/codex-native/lib/evaluate-with-kernel.mjs +257 -0
  99. package/dist/assets/hooks/codex-native/lib/hive-wal-consumer.mjs +452 -0
  100. package/dist/assets/hooks/codex-native/lib/kernel/deterministic-cognitive-kernel.mjs +914 -0
  101. package/dist/assets/hooks/codex-native/lib/project-boundary-cognition.mjs +143 -0
  102. package/dist/assets/hooks/codex-native/lib/runtime-client.mjs +3567 -0
  103. package/dist/assets/hooks/codex-native/lib/task-project-ledger.mjs +294 -0
  104. package/dist/assets/hooks/doctrine_trigger_map.json +236 -25
  105. package/dist/assets/hooks/doctrine_trigger_map.schema.json +46 -0
  106. package/dist/assets/hooks/install.sh +84 -0
  107. package/dist/assets/hooks/lib/action-ledger-core.mjs +269 -0
  108. package/dist/assets/hooks/lib/aria-gate-ledger.mjs +143 -0
  109. package/dist/assets/hooks/lib/ast-stub-shape-detector.mjs +107 -0
  110. package/dist/assets/hooks/lib/atlas-dossier-client.mjs +151 -0
  111. package/dist/assets/hooks/lib/atlas-orchestrator-postwire.mjs +221 -0
  112. package/dist/assets/hooks/lib/canonical-lenses.mjs +83 -6
  113. package/dist/assets/hooks/lib/coach-intent-classifier.mjs +248 -0
  114. package/dist/assets/hooks/lib/cognitive-block-parser.mjs +111 -0
  115. package/dist/assets/hooks/lib/doctrine-trigger-map-loader.mjs +137 -0
  116. package/dist/assets/hooks/lib/domain-output-quality.mjs +132 -3
  117. package/dist/assets/hooks/lib/empty-catch-scanner.mjs +91 -0
  118. package/dist/assets/hooks/lib/end-phase-qa-autofire.mjs +426 -0
  119. package/dist/assets/hooks/lib/evaluate-with-kernel.mjs +133 -0
  120. package/dist/assets/hooks/lib/first-class-coach.mjs +454 -19
  121. package/dist/assets/hooks/lib/gate-audit.mjs +12 -2
  122. package/dist/assets/hooks/lib/gate-loop-state.mjs +11 -2
  123. package/dist/assets/hooks/lib/goal-contract-quality.mjs +302 -0
  124. package/dist/assets/hooks/lib/hook-message-window.mjs +101 -9
  125. package/dist/assets/hooks/lib/invocation-required-verifier.mjs +184 -0
  126. package/dist/assets/hooks/lib/kernel/deterministic-cognitive-kernel.mjs +906 -0
  127. package/dist/assets/hooks/lib/obligation-ledger.mjs +147 -0
  128. package/dist/assets/hooks/lib/orchestration-manifest-extract.mjs +217 -0
  129. package/dist/assets/hooks/lib/owner-authorizations.mjs +269 -0
  130. package/dist/assets/hooks/lib/probe-discipline-scanner.mjs +142 -0
  131. package/dist/assets/hooks/lib/project-boundary-cognition.mjs +143 -0
  132. package/dist/assets/hooks/lib/recovery-context.mjs +151 -0
  133. package/dist/assets/hooks/lib/recovery-template-loader.mjs +154 -0
  134. package/dist/assets/hooks/lib/self-doctrine-check.mjs +321 -0
  135. package/dist/assets/hooks/lib/sensitive-shape-detector.mjs +64 -0
  136. package/dist/assets/hooks/lib/skill-autoload-gate-impl.mjs +226 -1
  137. package/dist/assets/hooks/lib/stop-hook-protocol.mjs +166 -0
  138. package/dist/assets/hooks/lib/surface-caught.mjs +94 -0
  139. package/dist/assets/hooks/recovery-templates/force-reauthor.md +67 -0
  140. package/dist/assets/hooks/recovery-templates/handoff-recovery.md +25 -0
  141. package/dist/assets/hooks/scripts/check-hard-risk-prefix.mjs +99 -0
  142. package/dist/assets/hooks/skills/aria-conversational-doctrine-discipline/SKILL.md +101 -0
  143. package/dist/assets/hooks/test-aria-preturn-memory-gate.mjs +2 -2
  144. package/dist/assets/hooks/test-tier-lens-labeling.mjs +14 -3
  145. package/dist/assets/opencode-plugins/harness-context/index.js +39 -6
  146. package/dist/assets/opencode-plugins/harness-context/task-project-ledger.mjs +5 -1
  147. package/dist/assets/opencode-plugins/harness-gate/index.js +36 -0
  148. package/dist/assets/opencode-plugins/harness-gate/lib/atlas-dossier-client.js +1 -0
  149. package/dist/assets/opencode-plugins/harness-gate/lib/recovery-grants.js +79 -0
  150. package/dist/assets/opencode-plugins/harness-outcome/index.js +12 -0
  151. package/dist/assets/opencode-plugins/harness-stop/index.js +97 -2
  152. package/dist/assets/opencode-plugins/harness-stop/lib/atlas-dossier-client.js +1 -0
  153. package/dist/assets/opencode-plugins/harness-stop/lib/domain-output-quality.js +15 -2
  154. package/dist/assets/opencode-plugins/lib/coach.js +148 -0
  155. package/dist/runtime/coach-kernel.mjs +144 -7
  156. package/dist/runtime/codex-bridge.mjs +254 -8
  157. package/dist/runtime/discipline/doctrine_trigger_map.json +236 -25
  158. package/dist/runtime/discipline/skills/aria-cognition/34-frameworks-unified/SKILL.md +42 -0
  159. package/dist/runtime/discipline/skills/aria-cognition/aria-aristotle-cognitives/SKILL.md +128 -0
  160. package/dist/runtime/discipline/skills/aria-cognition/aria-aristotle-intra-phase/SKILL.md +99 -0
  161. package/dist/runtime/discipline/skills/aria-cognition/aria-aristotle-post-phase/SKILL.md +118 -0
  162. package/dist/runtime/discipline/skills/aria-cognition/aria-aristotle-pre-phase/SKILL.md +117 -0
  163. package/dist/runtime/discipline/skills/aria-cognition/aria-axioms-first-principles/SKILL.md +202 -0
  164. package/dist/runtime/discipline/skills/aria-cognition/aria-axioms-first-principles/agents/openai.yaml +4 -0
  165. package/dist/runtime/discipline/skills/aria-cognition/aria-axioms-first-principles/references/source-map.md +130 -0
  166. package/dist/runtime/discipline/skills/aria-cognition/aria-backend-architect/SKILL.md +124 -0
  167. package/dist/runtime/discipline/skills/aria-cognition/aria-backend-architect/references/backend-cookbook.md +417 -0
  168. package/dist/runtime/discipline/skills/aria-cognition/aria-business-audit/SKILL.md +133 -0
  169. package/dist/runtime/discipline/skills/aria-cognition/aria-business-audit/references/audit-cookbook.md +247 -0
  170. package/dist/runtime/discipline/skills/aria-cognition/aria-business-frame/SKILL.md +138 -0
  171. package/dist/runtime/discipline/skills/aria-cognition/aria-business-frame/references/business-cookbook.md +154 -0
  172. package/dist/runtime/discipline/skills/aria-cognition/aria-chat/SKILL.md +84 -0
  173. package/dist/runtime/discipline/skills/aria-cognition/aria-chat/scripts/aria-chat.sh +57 -0
  174. package/dist/runtime/discipline/skills/aria-cognition/aria-cognition-autofire/SKILL.md +137 -0
  175. package/dist/runtime/discipline/skills/aria-cognition/aria-cognition-batch/SKILL.md +264 -0
  176. package/dist/runtime/discipline/skills/aria-cognition/aria-decision-mizan/SKILL.md +136 -0
  177. package/dist/runtime/discipline/skills/aria-cognition/aria-decision-mizan/references/decision-frameworks.md +287 -0
  178. package/dist/runtime/discipline/skills/aria-cognition/aria-first-class-operating-contract/SKILL.md +104 -0
  179. package/dist/runtime/discipline/skills/aria-cognition/aria-frontend-architect/SKILL.md +123 -0
  180. package/dist/runtime/discipline/skills/aria-cognition/aria-frontend-architect/references/frontend-cookbook.md +358 -0
  181. package/dist/runtime/discipline/skills/aria-cognition/aria-fullstack-orchestrator/SKILL.md +127 -0
  182. package/dist/runtime/discipline/skills/aria-cognition/aria-fullstack-orchestrator/references/fullstack-cookbook.md +383 -0
  183. package/dist/runtime/discipline/skills/aria-cognition/aria-gtm-architect/SKILL.md +126 -0
  184. package/dist/runtime/discipline/skills/aria-cognition/aria-gtm-architect/references/gtm-cookbook.md +235 -0
  185. package/dist/runtime/discipline/skills/aria-cognition/aria-harness-deploy/SKILL.md +145 -0
  186. package/dist/runtime/discipline/skills/aria-cognition/aria-harness-no-stripping/SKILL.md +135 -0
  187. package/dist/runtime/discipline/skills/aria-cognition/aria-harness-onboarding/SKILL.md +130 -0
  188. package/dist/runtime/discipline/skills/aria-cognition/aria-harness-output-discipline/SKILL.md +120 -0
  189. package/dist/runtime/discipline/skills/aria-cognition/aria-harness-substrate-binding/SKILL.md +139 -0
  190. package/dist/runtime/discipline/skills/aria-cognition/aria-http-harness-client/SKILL.md +85 -0
  191. package/dist/runtime/discipline/skills/aria-cognition/aria-http-harness-client/scripts/smoke.mjs +47 -0
  192. package/dist/runtime/discipline/skills/aria-cognition/aria-k8s-deploy/SKILL.md +174 -0
  193. package/dist/runtime/discipline/skills/aria-cognition/aria-k8s-deploy/agents/openai.yaml +3 -0
  194. package/dist/runtime/discipline/skills/aria-cognition/aria-ladduniframe/SKILL.md +60 -0
  195. package/dist/runtime/discipline/skills/aria-cognition/aria-ledger-fleet-execution/SKILL.md +126 -0
  196. package/dist/runtime/discipline/skills/aria-cognition/aria-live-ops/SKILL.md +54 -0
  197. package/dist/runtime/discipline/skills/aria-cognition/aria-mac-ssh-ops/SKILL.md +100 -0
  198. package/dist/runtime/discipline/skills/aria-cognition/aria-memory-index/SKILL.md +42 -0
  199. package/dist/runtime/discipline/skills/aria-cognition/aria-noor-cognitives/SKILL.md +120 -0
  200. package/dist/runtime/discipline/skills/aria-cognition/aria-ops/SKILL.md +60 -0
  201. package/dist/runtime/discipline/skills/aria-cognition/aria-ops/references/live-endpoints.md +59 -0
  202. package/dist/runtime/discipline/skills/aria-cognition/aria-quality-audit/SKILL.md +133 -0
  203. package/dist/runtime/discipline/skills/aria-cognition/aria-readable-output/SKILL.md +239 -0
  204. package/dist/runtime/discipline/skills/aria-cognition/aria-readable-output/references/layout-cookbook.md +366 -0
  205. package/dist/runtime/discipline/skills/aria-cognition/aria-reasoning/SKILL.md +67 -0
  206. package/dist/runtime/discipline/skills/aria-cognition/aria-reasoning/references/core-principles.md +42 -0
  207. package/dist/runtime/discipline/skills/aria-cognition/aria-repo-audit/SKILL.md +135 -0
  208. package/dist/runtime/discipline/skills/aria-cognition/aria-repo-audit/references/repo-audit-cookbook.md +375 -0
  209. package/dist/runtime/discipline/skills/aria-cognition/aria-research-orchestrator/SKILL.md +138 -0
  210. package/dist/runtime/discipline/skills/aria-cognition/aria-research-orchestrator/references/research-patterns.md +270 -0
  211. package/dist/runtime/discipline/skills/aria-cognition/aria-retention-engine/SKILL.md +120 -0
  212. package/dist/runtime/discipline/skills/aria-cognition/aria-retention-engine/references/retention-cookbook.md +271 -0
  213. package/dist/runtime/discipline/skills/aria-cognition/aria-revenue-engine/SKILL.md +128 -0
  214. package/dist/runtime/discipline/skills/aria-cognition/aria-revenue-engine/references/revenue-cookbook.md +227 -0
  215. package/dist/runtime/discipline/skills/aria-cognition/aria-senior-code-audit/SKILL.md +233 -0
  216. package/dist/runtime/discipline/skills/aria-cognition/aria-senior-code-audit/references/audit-checklist.md +369 -0
  217. package/dist/runtime/discipline/skills/aria-cognition/aria-senior-code-cookbook/SKILL.md +288 -0
  218. package/dist/runtime/discipline/skills/aria-cognition/aria-senior-code-cookbook/references/engineering-cookbook.md +489 -0
  219. package/dist/runtime/discipline/skills/aria-cognition/aria-soul-principles/SKILL.md +42 -0
  220. package/dist/runtime/discipline/skills/aria-cognition/aria-task-codex-executor/SKILL.md +86 -0
  221. package/dist/runtime/discipline/skills/aria-cognition/aristotle-engine/SKILL.md +42 -0
  222. package/dist/runtime/discipline/skills/aria-cognition/cross-domain-24/SKILL.md +42 -0
  223. package/dist/runtime/discipline/skills/aria-cognition/deepsoul-emotional/SKILL.md +42 -0
  224. package/dist/runtime/discipline/skills/aria-cognition/fitrah-guard/SKILL.md +78 -0
  225. package/dist/runtime/discipline/skills/aria-cognition/ghazali-8lens/SKILL.md +227 -29
  226. package/dist/runtime/discipline/skills/aria-cognition/ghazali-8lens/references/ghazali-8lens-cookbook.md +797 -0
  227. package/dist/runtime/discipline/skills/aria-cognition/ijtihad-novel/SKILL.md +42 -0
  228. package/dist/runtime/discipline/skills/aria-cognition/ilham-intuition/SKILL.md +42 -0
  229. package/dist/runtime/discipline/skills/aria-cognition/never-guess/SKILL.md +77 -0
  230. package/dist/runtime/discipline/skills/aria-cognition/noor-recognition/SKILL.md +45 -0
  231. package/dist/runtime/discipline/skills/aria-cognition/qiyas-analogy/SKILL.md +174 -14
  232. package/dist/runtime/discipline/skills/aria-cognition/ruh-basis/SKILL.md +42 -0
  233. package/dist/runtime/discipline/skills/aria-cognition/tadabbur/SKILL.md +506 -0
  234. package/dist/runtime/discipline/skills/aria-cognition/tadabbur/references/tadabbur-cookbook.md +921 -0
  235. package/dist/runtime/discipline/skills/aria-cognition/tadabbur-ops/SKILL.md +42 -0
  236. package/dist/runtime/discipline/skills/aria-cognition/tafakkur/SKILL.md +104 -0
  237. package/dist/runtime/doctrine_trigger_map.json +236 -25
  238. package/dist/runtime/embedded-public-key.mjs +27 -0
  239. package/dist/runtime/gated-ledger.mjs +41 -14
  240. package/dist/runtime/harness-daemon.mjs +85 -10
  241. package/dist/runtime/hive-wal-publisher.mjs +292 -0
  242. package/dist/runtime/hooks/README.md +58 -0
  243. package/dist/runtime/hooks/aria-agent-handoff.mjs +147 -2
  244. package/dist/runtime/hooks/aria-agent-ledger-merge.mjs +31 -7
  245. package/dist/runtime/hooks/aria-architect-fallback.mjs +10 -2
  246. package/dist/runtime/hooks/aria-claim-evidence-stop-gate.mjs +240 -0
  247. package/dist/runtime/hooks/aria-cognition-substrate-binding.mjs +84 -10
  248. package/dist/runtime/hooks/aria-first-class-coach.mjs +305 -10
  249. package/dist/runtime/hooks/aria-harness-via-sdk.mjs +93 -16
  250. package/dist/runtime/hooks/aria-import-resolution-gate.mjs +106 -20
  251. package/dist/runtime/hooks/aria-outcome-record.mjs +56 -20
  252. package/dist/runtime/hooks/aria-pre-emit-autoload.mjs +1809 -0
  253. package/dist/runtime/hooks/aria-pre-emit-autoload.mjs.before-orchestration-redesign +1400 -0
  254. package/dist/runtime/hooks/aria-pre-emit-dryrun.mjs +22 -3
  255. package/dist/runtime/hooks/aria-pre-text-gate.mjs +11 -2
  256. package/dist/runtime/hooks/aria-pre-tool-gate.mjs +477 -81
  257. package/dist/runtime/hooks/aria-pre-tool-use.mjs +70 -6
  258. package/dist/runtime/hooks/aria-preprompt-consult.mjs +23 -4
  259. package/dist/runtime/hooks/aria-repo-doctrine-gate.mjs +29 -3
  260. package/dist/runtime/hooks/aria-stop-gate.mjs +585 -76
  261. package/dist/runtime/hooks/aria-trigger-autolearn.mjs +17 -3
  262. package/dist/runtime/hooks/aria-universal-turn-packet.mjs +1165 -0
  263. package/dist/runtime/hooks/aria-userprompt-abandon-detect.mjs +9 -1
  264. package/dist/runtime/hooks/canonical-settings-block.json +172 -0
  265. package/dist/runtime/hooks/codex-native/aria-harness-ticker-sidecar.mjs +92 -0
  266. package/dist/runtime/hooks/codex-native/aria-hive-wal-consumer.mjs +86 -0
  267. package/dist/runtime/hooks/codex-native/aria-live-ticker.mjs +38 -0
  268. package/dist/runtime/hooks/codex-native/aria-post-tool-use.mjs +236 -0
  269. package/dist/runtime/hooks/codex-native/aria-pre-tool-use.mjs +362 -0
  270. package/dist/runtime/hooks/codex-native/aria-stop.mjs +691 -0
  271. package/dist/runtime/hooks/codex-native/aria-userprompt-submit.mjs +623 -0
  272. package/dist/runtime/hooks/codex-native/atlas-session-context.mjs +121 -0
  273. package/dist/runtime/hooks/codex-native/lib/evaluate-with-kernel.mjs +257 -0
  274. package/dist/runtime/hooks/codex-native/lib/hive-wal-consumer.mjs +452 -0
  275. package/dist/runtime/hooks/codex-native/lib/kernel/deterministic-cognitive-kernel.mjs +914 -0
  276. package/dist/runtime/hooks/codex-native/lib/project-boundary-cognition.mjs +143 -0
  277. package/dist/runtime/hooks/codex-native/lib/runtime-client.mjs +3567 -0
  278. package/dist/runtime/hooks/codex-native/lib/task-project-ledger.mjs +294 -0
  279. package/dist/runtime/hooks/doctrine_trigger_map.json +236 -25
  280. package/dist/runtime/hooks/doctrine_trigger_map.schema.json +46 -0
  281. package/dist/runtime/hooks/install.sh +84 -0
  282. package/dist/runtime/hooks/lib/action-ledger-core.mjs +269 -0
  283. package/dist/runtime/hooks/lib/aria-gate-ledger.mjs +143 -0
  284. package/dist/runtime/hooks/lib/ast-stub-shape-detector.mjs +107 -0
  285. package/dist/runtime/hooks/lib/atlas-dossier-client.mjs +151 -0
  286. package/dist/runtime/hooks/lib/atlas-orchestrator-postwire.mjs +221 -0
  287. package/dist/runtime/hooks/lib/canonical-lenses.mjs +83 -6
  288. package/dist/runtime/hooks/lib/coach-intent-classifier.mjs +248 -0
  289. package/dist/runtime/hooks/lib/cognitive-block-parser.mjs +111 -0
  290. package/dist/runtime/hooks/lib/doctrine-trigger-map-loader.mjs +137 -0
  291. package/dist/runtime/hooks/lib/domain-output-quality.mjs +132 -3
  292. package/dist/runtime/hooks/lib/empty-catch-scanner.mjs +91 -0
  293. package/dist/runtime/hooks/lib/end-phase-qa-autofire.mjs +426 -0
  294. package/dist/runtime/hooks/lib/evaluate-with-kernel.mjs +133 -0
  295. package/dist/runtime/hooks/lib/first-class-coach.mjs +454 -19
  296. package/dist/runtime/hooks/lib/gate-audit.mjs +12 -2
  297. package/dist/runtime/hooks/lib/gate-loop-state.mjs +11 -2
  298. package/dist/runtime/hooks/lib/goal-contract-quality.mjs +302 -0
  299. package/dist/runtime/hooks/lib/hook-message-window.mjs +101 -9
  300. package/dist/runtime/hooks/lib/invocation-required-verifier.mjs +184 -0
  301. package/dist/runtime/hooks/lib/kernel/deterministic-cognitive-kernel.mjs +906 -0
  302. package/dist/runtime/hooks/lib/obligation-ledger.mjs +147 -0
  303. package/dist/runtime/hooks/lib/orchestration-manifest-extract.mjs +217 -0
  304. package/dist/runtime/hooks/lib/owner-authorizations.mjs +269 -0
  305. package/dist/runtime/hooks/lib/probe-discipline-scanner.mjs +142 -0
  306. package/dist/runtime/hooks/lib/project-boundary-cognition.mjs +143 -0
  307. package/dist/runtime/hooks/lib/recovery-context.mjs +151 -0
  308. package/dist/runtime/hooks/lib/recovery-template-loader.mjs +154 -0
  309. package/dist/runtime/hooks/lib/self-doctrine-check.mjs +321 -0
  310. package/dist/runtime/hooks/lib/sensitive-shape-detector.mjs +64 -0
  311. package/dist/runtime/hooks/lib/skill-autoload-gate-impl.mjs +226 -1
  312. package/dist/runtime/hooks/lib/stop-hook-protocol.mjs +166 -0
  313. package/dist/runtime/hooks/lib/surface-caught.mjs +94 -0
  314. package/dist/runtime/hooks/recovery-templates/force-reauthor.md +67 -0
  315. package/dist/runtime/hooks/recovery-templates/handoff-recovery.md +25 -0
  316. package/dist/runtime/hooks/scripts/check-hard-risk-prefix.mjs +99 -0
  317. package/dist/runtime/hooks/skills/aria-conversational-doctrine-discipline/SKILL.md +101 -0
  318. package/dist/runtime/hooks/test-aria-preturn-memory-gate.mjs +2 -2
  319. package/dist/runtime/hooks/test-tier-lens-labeling.mjs +14 -3
  320. package/dist/runtime/lib/evaluate-with-kernel.mjs +133 -0
  321. package/dist/runtime/lib/kernel/deterministic-cognitive-kernel.mjs +906 -0
  322. package/dist/runtime/local-phase.mjs +10 -5
  323. package/dist/runtime/manifest.json +8 -8
  324. package/dist/runtime/packet-verifier.mjs +166 -0
  325. package/dist/runtime/provider-proxy.mjs +13 -0
  326. package/dist/runtime/quality-enforcer.mjs +40 -23
  327. package/dist/runtime/runtime-rails/registry.mjs +252 -0
  328. package/dist/runtime/sdk/BUNDLED.json +2 -2
  329. package/dist/runtime/sdk/index.d.ts +119 -4
  330. package/dist/runtime/sdk/index.js +138 -12
  331. package/dist/runtime/sdk/index.js.map +1 -1
  332. package/dist/runtime/service.mjs +8036 -764
  333. package/dist/runtime/sub-agent-enforcer.mjs +201 -0
  334. package/dist/runtime/task-project-ledger.mjs +5 -1
  335. package/dist/sdk/BUNDLED.json +2 -2
  336. package/dist/sdk/index.d.ts +119 -4
  337. package/dist/sdk/index.js +138 -12
  338. package/dist/sdk/index.js.map +1 -1
  339. package/hooks/README.md +58 -0
  340. package/hooks/aria-agent-handoff.mjs +147 -2
  341. package/hooks/aria-agent-ledger-merge.mjs +31 -7
  342. package/hooks/aria-architect-fallback.mjs +10 -2
  343. package/hooks/aria-claim-evidence-stop-gate.mjs +240 -0
  344. package/hooks/aria-cognition-substrate-binding.mjs +84 -10
  345. package/hooks/aria-first-class-coach.mjs +305 -10
  346. package/hooks/aria-harness-via-sdk.mjs +93 -16
  347. package/hooks/aria-import-resolution-gate.mjs +106 -20
  348. package/hooks/aria-outcome-record.mjs +56 -20
  349. package/hooks/aria-pre-emit-autoload.mjs +1809 -0
  350. package/hooks/aria-pre-emit-autoload.mjs.before-orchestration-redesign +1400 -0
  351. package/hooks/aria-pre-emit-dryrun.mjs +22 -3
  352. package/hooks/aria-pre-text-gate.mjs +11 -2
  353. package/hooks/aria-pre-tool-gate.mjs +477 -81
  354. package/hooks/aria-pre-tool-use.mjs +70 -6
  355. package/hooks/aria-preprompt-consult.mjs +23 -4
  356. package/hooks/aria-repo-doctrine-gate.mjs +29 -3
  357. package/hooks/aria-stop-gate.mjs +585 -76
  358. package/hooks/aria-trigger-autolearn.mjs +17 -3
  359. package/hooks/aria-universal-turn-packet.mjs +1165 -0
  360. package/hooks/aria-userprompt-abandon-detect.mjs +9 -1
  361. package/hooks/canonical-settings-block.json +172 -0
  362. package/hooks/codex-native/aria-harness-ticker-sidecar.mjs +92 -0
  363. package/hooks/codex-native/aria-hive-wal-consumer.mjs +86 -0
  364. package/hooks/codex-native/aria-live-ticker.mjs +38 -0
  365. package/hooks/codex-native/aria-post-tool-use.mjs +236 -0
  366. package/hooks/codex-native/aria-pre-tool-use.mjs +362 -0
  367. package/hooks/codex-native/aria-stop.mjs +691 -0
  368. package/hooks/codex-native/aria-userprompt-submit.mjs +623 -0
  369. package/hooks/codex-native/atlas-session-context.mjs +121 -0
  370. package/hooks/codex-native/lib/evaluate-with-kernel.mjs +257 -0
  371. package/hooks/codex-native/lib/hive-wal-consumer.mjs +452 -0
  372. package/hooks/codex-native/lib/kernel/deterministic-cognitive-kernel.mjs +914 -0
  373. package/hooks/codex-native/lib/project-boundary-cognition.mjs +143 -0
  374. package/hooks/codex-native/lib/runtime-client.mjs +3567 -0
  375. package/hooks/codex-native/lib/task-project-ledger.mjs +294 -0
  376. package/hooks/doctrine_trigger_map.json +236 -25
  377. package/hooks/doctrine_trigger_map.schema.json +46 -0
  378. package/hooks/install.sh +84 -0
  379. package/hooks/lib/action-ledger-core.mjs +269 -0
  380. package/hooks/lib/aria-gate-ledger.mjs +143 -0
  381. package/hooks/lib/ast-stub-shape-detector.mjs +107 -0
  382. package/hooks/lib/atlas-dossier-client.mjs +151 -0
  383. package/hooks/lib/atlas-orchestrator-postwire.mjs +221 -0
  384. package/hooks/lib/canonical-lenses.mjs +83 -6
  385. package/hooks/lib/coach-intent-classifier.mjs +248 -0
  386. package/hooks/lib/cognitive-block-parser.mjs +111 -0
  387. package/hooks/lib/doctrine-trigger-map-loader.mjs +137 -0
  388. package/hooks/lib/domain-output-quality.mjs +132 -3
  389. package/hooks/lib/empty-catch-scanner.mjs +91 -0
  390. package/hooks/lib/end-phase-qa-autofire.mjs +426 -0
  391. package/hooks/lib/evaluate-with-kernel.mjs +133 -0
  392. package/hooks/lib/first-class-coach.mjs +454 -19
  393. package/hooks/lib/gate-audit.mjs +12 -2
  394. package/hooks/lib/gate-loop-state.mjs +11 -2
  395. package/hooks/lib/goal-contract-quality.mjs +302 -0
  396. package/hooks/lib/hook-message-window.mjs +101 -9
  397. package/hooks/lib/invocation-required-verifier.mjs +184 -0
  398. package/hooks/lib/kernel/deterministic-cognitive-kernel.mjs +906 -0
  399. package/hooks/lib/obligation-ledger.mjs +147 -0
  400. package/hooks/lib/orchestration-manifest-extract.mjs +217 -0
  401. package/hooks/lib/owner-authorizations.mjs +269 -0
  402. package/hooks/lib/probe-discipline-scanner.mjs +142 -0
  403. package/hooks/lib/project-boundary-cognition.mjs +143 -0
  404. package/hooks/lib/recovery-context.mjs +151 -0
  405. package/hooks/lib/recovery-template-loader.mjs +154 -0
  406. package/hooks/lib/self-doctrine-check.mjs +321 -0
  407. package/hooks/lib/sensitive-shape-detector.mjs +64 -0
  408. package/hooks/lib/skill-autoload-gate-impl.mjs +226 -1
  409. package/hooks/lib/stop-hook-protocol.mjs +166 -0
  410. package/hooks/lib/surface-caught.mjs +94 -0
  411. package/hooks/recovery-templates/force-reauthor.md +67 -0
  412. package/hooks/recovery-templates/handoff-recovery.md +25 -0
  413. package/hooks/scripts/check-hard-risk-prefix.mjs +99 -0
  414. package/hooks/skills/aria-conversational-doctrine-discipline/SKILL.md +101 -0
  415. package/hooks/test-aria-preturn-memory-gate.mjs +2 -2
  416. package/hooks/test-tier-lens-labeling.mjs +14 -3
  417. package/opencode-plugins/harness-context/index.js +39 -6
  418. package/opencode-plugins/harness-context/task-project-ledger.mjs +5 -1
  419. package/opencode-plugins/harness-gate/index.js +36 -0
  420. package/opencode-plugins/harness-gate/lib/atlas-dossier-client.js +1 -0
  421. package/opencode-plugins/harness-gate/lib/recovery-grants.js +79 -0
  422. package/opencode-plugins/harness-outcome/index.js +12 -0
  423. package/opencode-plugins/harness-stop/index.js +97 -2
  424. package/opencode-plugins/harness-stop/lib/atlas-dossier-client.js +1 -0
  425. package/opencode-plugins/harness-stop/lib/domain-output-quality.js +15 -2
  426. package/opencode-plugins/lib/coach.js +148 -0
  427. package/package.json +71 -5
  428. package/runtime-src/coach-kernel.mjs +144 -7
  429. package/runtime-src/codex-bridge.mjs +254 -8
  430. package/runtime-src/embedded-public-key.mjs +27 -0
  431. package/runtime-src/gated-ledger.mjs +41 -14
  432. package/runtime-src/harness-daemon.mjs +85 -10
  433. package/runtime-src/hive-wal-publisher.mjs +292 -0
  434. package/runtime-src/lib/evaluate-with-kernel.mjs +133 -0
  435. package/runtime-src/lib/kernel/deterministic-cognitive-kernel.mjs +906 -0
  436. package/runtime-src/local-phase.mjs +10 -5
  437. package/runtime-src/packet-verifier.mjs +166 -0
  438. package/runtime-src/provider-proxy.mjs +13 -0
  439. package/runtime-src/quality-enforcer.mjs +40 -23
  440. package/runtime-src/runtime-rails/registry.mjs +252 -0
  441. package/runtime-src/service.mjs +8036 -764
  442. package/runtime-src/sub-agent-enforcer.mjs +201 -0
  443. package/scripts/aria-ledger-append.mjs +337 -0
  444. package/scripts/aria-task-cheap-worker-dispatch.mjs +234 -0
  445. package/scripts/audit-of-audit-prior-tasks.mjs +194 -0
  446. package/scripts/audit-of-audit-this-turn.mjs +116 -0
  447. package/scripts/bundle-sdk.mjs +31 -5
  448. package/scripts/check-cli-wrapper-provider-contract.mjs +160 -0
  449. package/scripts/check-client-compatibility.mjs +15 -5
  450. package/scripts/check-client-smoke.mjs +297 -0
  451. package/scripts/check-codex-orchestrator-adoption.mjs +150 -0
  452. package/scripts/check-glm-env-wired.mjs +131 -0
  453. package/scripts/check-hive-local-storage-contract.mjs +91 -0
  454. package/scripts/check-hook-mirror.mjs +150 -0
  455. package/scripts/check-install-sh-drift.mjs +152 -0
  456. package/scripts/check-kernel-sync.mjs +101 -0
  457. package/scripts/check-package-artifact.mjs +152 -0
  458. package/scripts/check-registry-mirror.mjs +71 -0
  459. package/scripts/drain-owner-airtable-sync-queue.mjs +287 -0
  460. package/scripts/export-owner-status-sheets.mjs +589 -0
  461. package/scripts/live-sidecar-receipt-canary.mjs +347 -0
  462. package/scripts/qiyas-tadabbur-model-matrix.mjs +970 -0
  463. package/scripts/quality-ab-live-provider.mjs +913 -0
  464. package/scripts/self-test-action-ledger-core.mjs +190 -0
  465. package/scripts/self-test-approval-receipt-binding.mjs +122 -0
  466. package/scripts/self-test-autofire-quality-output.mjs +110 -0
  467. package/scripts/self-test-claude-code-action-ledger.mjs +132 -0
  468. package/scripts/self-test-claude-code-mechanical-autofire-hive.mjs +138 -0
  469. package/scripts/self-test-claude-code-mechanical-autofire.mjs +234 -0
  470. package/scripts/self-test-codebase-awareness-atlas-delta.mjs +159 -0
  471. package/scripts/self-test-codebase-awareness-delta-ingest.mjs +179 -0
  472. package/scripts/self-test-codex-live-hook-parity.mjs +84 -0
  473. package/scripts/self-test-codex-native-action-ledger.mjs +167 -0
  474. package/scripts/self-test-codex-native-hook-json-contract.mjs +74 -0
  475. package/scripts/self-test-codex-orchestrator-continuity.mjs +113 -0
  476. package/scripts/self-test-codex-readable-recovery.mjs +94 -0
  477. package/scripts/self-test-codex-self-harness.mjs +538 -0
  478. package/scripts/self-test-compiled-workunit.mjs +214 -0
  479. package/scripts/self-test-continuation-output-smoke.mjs +101 -0
  480. package/scripts/self-test-cross-cli-fleet-ticker.mjs +85 -0
  481. package/scripts/self-test-cross-cli-hive-adoption.mjs +125 -0
  482. package/scripts/self-test-cross-cli-hive-learning.mjs +146 -0
  483. package/scripts/self-test-cross-phase-tool-failure.mjs +110 -0
  484. package/scripts/self-test-cross-surface-action-ledger.mjs +149 -0
  485. package/scripts/self-test-end-of-phase-qa-court.mjs +616 -0
  486. package/scripts/self-test-evaluate-with-kernel.mjs +111 -0
  487. package/scripts/self-test-first-class-output-delta-proof.mjs +307 -0
  488. package/scripts/self-test-goal-contract-output-qa.mjs +73 -0
  489. package/scripts/self-test-goal-contract.mjs +35 -0
  490. package/scripts/self-test-governed-adapters.mjs +105 -0
  491. package/scripts/self-test-governed-surface-runner.mjs +198 -0
  492. package/scripts/self-test-harness-gates.mjs +15 -12
  493. package/scripts/self-test-harness-ticker-sidecar.mjs +153 -0
  494. package/scripts/self-test-hive-org-kernel.mjs +233 -0
  495. package/scripts/self-test-hive-session-coordination.mjs +156 -0
  496. package/scripts/self-test-hive-wal-consumer.mjs +111 -0
  497. package/scripts/self-test-kernel-a3-a4-selection.mjs +179 -0
  498. package/scripts/self-test-ledger-append.mjs +175 -0
  499. package/scripts/self-test-live-codex-posttool-packet-smoke.mjs +111 -0
  500. package/scripts/self-test-live-codex-pretool-packet-smoke.mjs +101 -0
  501. package/scripts/self-test-live-codex-stop-qa-kernel-smoke.mjs +43 -0
  502. package/scripts/self-test-live-wrapper-substrate-inventory.mjs +149 -0
  503. package/scripts/self-test-local-main-sync-script.mjs +47 -0
  504. package/scripts/self-test-mechanical-autofire-resolver.mjs +296 -0
  505. package/scripts/self-test-no-consult-cognitive-skills-output.mjs +135 -0
  506. package/scripts/self-test-owner-airtable-sync-queue.mjs +196 -0
  507. package/scripts/self-test-owner-airtable-sync.mjs +181 -0
  508. package/scripts/self-test-owner-sheets-action-ledger.mjs +100 -0
  509. package/scripts/self-test-production-preflight.mjs +78 -0
  510. package/scripts/self-test-project-boundary-cognition.mjs +79 -0
  511. package/scripts/self-test-qa-exec-kernel.mjs +34 -0
  512. package/scripts/self-test-qa-recovery-learning-loop.mjs +113 -0
  513. package/scripts/self-test-qiyas-label-alignment.mjs +94 -0
  514. package/scripts/self-test-recovery-context.mjs +110 -0
  515. package/scripts/self-test-repo-guard.mjs +10 -0
  516. package/scripts/self-test-runtime-health-self-heal.mjs +161 -0
  517. package/scripts/self-test-runtime-postcondition.mjs +70 -0
  518. package/scripts/self-test-soul-precommit-hook.mjs +39 -0
  519. package/scripts/self-test-stop-gate-kernel-guards.mjs +185 -0
  520. package/scripts/self-test-stop-gate.mjs +128 -0
  521. package/scripts/self-test-substrate-kernel-execution-receipt.mjs +130 -0
  522. package/scripts/self-test-substrate-open-skill-floor.mjs +87 -0
  523. package/scripts/self-test-substrate-output-quality-eval.mjs +171 -0
  524. package/scripts/self-test-task-closeout-drift.mjs +97 -0
  525. package/scripts/self-test-task-project-ledger-readiness.mjs +43 -0
  526. package/scripts/self-test-task-runner-phase-consumer.mjs +134 -0
  527. package/scripts/self-test-task-worker-lane.mjs +256 -0
  528. package/scripts/self-test-turn-substrate-qa-kernel.mjs +188 -0
  529. package/scripts/self-test-universal-action-capture.mjs +153 -0
  530. package/scripts/self-test-universal-turn-packet-entrypoints.mjs +252 -0
  531. package/scripts/self-test-universal-turn-packet.mjs +320 -0
  532. package/scripts/session-quality-backfill.mjs +253 -0
  533. package/scripts/smoke-autofire-100-prompts.mjs +481 -0
  534. package/scripts/sync-local-main-on-task-complete.mjs +278 -0
  535. package/scripts/sync-owner-status-airtable.mjs +1158 -0
  536. package/scripts/validate-skill-prompts.mjs +12 -1
  537. package/scripts/verify-codex-native-mirror.mjs +262 -0
  538. package/skills/34-frameworks-unified/SKILL.md +42 -0
  539. package/skills/api-design/SKILL.md +123 -0
  540. package/skills/architecture-decision/SKILL.md +105 -0
  541. package/skills/aria-aristotle-cognitives/SKILL.md +128 -0
  542. package/skills/aria-aristotle-intra-phase/SKILL.md +99 -0
  543. package/skills/aria-aristotle-post-phase/SKILL.md +116 -0
  544. package/skills/aria-aristotle-pre-phase/SKILL.md +117 -0
  545. package/skills/aria-axioms-first-principles/SKILL.md +202 -0
  546. package/skills/aria-axioms-first-principles/agents/openai.yaml +4 -0
  547. package/skills/aria-axioms-first-principles/references/source-map.md +130 -0
  548. package/skills/aria-chat/SKILL.md +84 -0
  549. package/skills/aria-chat/scripts/aria-chat.sh +57 -0
  550. package/skills/aria-cognition/34-frameworks-unified/SKILL.md +42 -0
  551. package/skills/aria-cognition/aria-aristotle-cognitives/SKILL.md +128 -0
  552. package/skills/aria-cognition/aria-aristotle-intra-phase/SKILL.md +99 -0
  553. package/skills/aria-cognition/aria-aristotle-post-phase/SKILL.md +118 -0
  554. package/skills/aria-cognition/aria-aristotle-pre-phase/SKILL.md +117 -0
  555. package/skills/aria-cognition/aria-axioms-first-principles/SKILL.md +202 -0
  556. package/skills/aria-cognition/aria-axioms-first-principles/agents/openai.yaml +4 -0
  557. package/skills/aria-cognition/aria-axioms-first-principles/references/source-map.md +130 -0
  558. package/skills/aria-cognition/aria-backend-architect/SKILL.md +124 -0
  559. package/skills/aria-cognition/aria-backend-architect/references/backend-cookbook.md +417 -0
  560. package/skills/aria-cognition/aria-business-audit/SKILL.md +133 -0
  561. package/skills/aria-cognition/aria-business-audit/references/audit-cookbook.md +247 -0
  562. package/skills/aria-cognition/aria-business-frame/SKILL.md +138 -0
  563. package/skills/aria-cognition/aria-business-frame/references/business-cookbook.md +154 -0
  564. package/skills/aria-cognition/aria-chat/SKILL.md +84 -0
  565. package/skills/aria-cognition/aria-chat/scripts/aria-chat.sh +57 -0
  566. package/skills/aria-cognition/aria-cognition-autofire/SKILL.md +137 -0
  567. package/skills/aria-cognition/aria-cognition-batch/SKILL.md +264 -0
  568. package/skills/aria-cognition/aria-decision-mizan/SKILL.md +136 -0
  569. package/skills/aria-cognition/aria-decision-mizan/references/decision-frameworks.md +287 -0
  570. package/skills/aria-cognition/aria-first-class-operating-contract/SKILL.md +104 -0
  571. package/skills/aria-cognition/aria-frontend-architect/SKILL.md +123 -0
  572. package/skills/aria-cognition/aria-frontend-architect/references/frontend-cookbook.md +358 -0
  573. package/skills/aria-cognition/aria-fullstack-orchestrator/SKILL.md +127 -0
  574. package/skills/aria-cognition/aria-fullstack-orchestrator/references/fullstack-cookbook.md +383 -0
  575. package/skills/aria-cognition/aria-gtm-architect/SKILL.md +126 -0
  576. package/skills/aria-cognition/aria-gtm-architect/references/gtm-cookbook.md +235 -0
  577. package/skills/aria-cognition/aria-harness-deploy/SKILL.md +145 -0
  578. package/skills/aria-cognition/aria-harness-no-stripping/SKILL.md +135 -0
  579. package/skills/aria-cognition/aria-harness-onboarding/SKILL.md +130 -0
  580. package/skills/aria-cognition/aria-harness-output-discipline/SKILL.md +120 -0
  581. package/skills/aria-cognition/aria-harness-substrate-binding/SKILL.md +139 -0
  582. package/skills/aria-cognition/aria-http-harness-client/SKILL.md +85 -0
  583. package/skills/aria-cognition/aria-http-harness-client/scripts/smoke.mjs +47 -0
  584. package/skills/aria-cognition/aria-k8s-deploy/SKILL.md +174 -0
  585. package/skills/aria-cognition/aria-k8s-deploy/agents/openai.yaml +3 -0
  586. package/skills/aria-cognition/aria-ladduniframe/SKILL.md +60 -0
  587. package/skills/aria-cognition/aria-ledger-fleet-execution/SKILL.md +126 -0
  588. package/skills/aria-cognition/aria-live-ops/SKILL.md +54 -0
  589. package/skills/aria-cognition/aria-mac-ssh-ops/SKILL.md +100 -0
  590. package/skills/aria-cognition/aria-memory-index/SKILL.md +42 -0
  591. package/skills/aria-cognition/aria-noor-cognitives/SKILL.md +120 -0
  592. package/skills/aria-cognition/aria-ops/SKILL.md +60 -0
  593. package/skills/aria-cognition/aria-ops/references/live-endpoints.md +59 -0
  594. package/skills/aria-cognition/aria-quality-audit/SKILL.md +133 -0
  595. package/skills/aria-cognition/aria-readable-output/SKILL.md +239 -0
  596. package/skills/aria-cognition/aria-readable-output/references/layout-cookbook.md +366 -0
  597. package/skills/aria-cognition/aria-reasoning/SKILL.md +67 -0
  598. package/skills/aria-cognition/aria-reasoning/references/core-principles.md +42 -0
  599. package/skills/aria-cognition/aria-repo-audit/SKILL.md +135 -0
  600. package/skills/aria-cognition/aria-repo-audit/references/repo-audit-cookbook.md +375 -0
  601. package/skills/aria-cognition/aria-research-orchestrator/SKILL.md +138 -0
  602. package/skills/aria-cognition/aria-research-orchestrator/references/research-patterns.md +270 -0
  603. package/skills/aria-cognition/aria-retention-engine/SKILL.md +120 -0
  604. package/skills/aria-cognition/aria-retention-engine/references/retention-cookbook.md +271 -0
  605. package/skills/aria-cognition/aria-revenue-engine/SKILL.md +128 -0
  606. package/skills/aria-cognition/aria-revenue-engine/references/revenue-cookbook.md +227 -0
  607. package/skills/aria-cognition/aria-senior-code-audit/SKILL.md +233 -0
  608. package/skills/aria-cognition/aria-senior-code-audit/references/audit-checklist.md +369 -0
  609. package/skills/aria-cognition/aria-senior-code-cookbook/SKILL.md +288 -0
  610. package/skills/aria-cognition/aria-senior-code-cookbook/references/engineering-cookbook.md +489 -0
  611. package/skills/aria-cognition/aria-soul-principles/SKILL.md +42 -0
  612. package/skills/aria-cognition/aria-task-codex-executor/SKILL.md +86 -0
  613. package/skills/aria-cognition/aristotle-engine/SKILL.md +42 -0
  614. package/skills/aria-cognition/cross-domain-24/SKILL.md +42 -0
  615. package/skills/aria-cognition/deepsoul-emotional/SKILL.md +42 -0
  616. package/skills/aria-cognition/fitrah-guard/SKILL.md +78 -0
  617. package/skills/aria-cognition/ghazali-8lens/SKILL.md +227 -29
  618. package/skills/aria-cognition/ghazali-8lens/references/ghazali-8lens-cookbook.md +797 -0
  619. package/skills/aria-cognition/ijtihad-novel/SKILL.md +42 -0
  620. package/skills/aria-cognition/ilham-intuition/SKILL.md +42 -0
  621. package/skills/aria-cognition/never-guess/SKILL.md +77 -0
  622. package/skills/aria-cognition/noor-recognition/SKILL.md +45 -0
  623. package/skills/aria-cognition/qiyas-analogy/SKILL.md +174 -14
  624. package/skills/aria-cognition/ruh-basis/SKILL.md +42 -0
  625. package/skills/aria-cognition/tadabbur/SKILL.md +506 -0
  626. package/skills/aria-cognition/tadabbur/references/tadabbur-cookbook.md +921 -0
  627. package/skills/aria-cognition/tadabbur-ops/SKILL.md +42 -0
  628. package/skills/aria-cognition/tafakkur/SKILL.md +104 -0
  629. package/skills/aria-cognition-autofire/SKILL.md +109 -0
  630. package/skills/aria-cognition-batch/SKILL.md +264 -0
  631. package/skills/aria-conversational-doctrine-discipline/SKILL.md +125 -0
  632. package/skills/aria-essence/SKILL.md +81 -0
  633. package/skills/aria-essence/references/domain-matrix.md +80 -0
  634. package/skills/aria-essence/references/evolution-loop.md +30 -0
  635. package/skills/aria-essence/references/readable-cognition.md +27 -0
  636. package/skills/aria-first-class-operating-contract/SKILL.md +104 -0
  637. package/skills/aria-forge-guardrails/SKILL.md +53 -0
  638. package/skills/aria-forge-guardrails/references/checklist.md +31 -0
  639. package/skills/aria-harness-deploy/SKILL.md +145 -0
  640. package/skills/aria-harness-no-stripping/SKILL.md +135 -0
  641. package/skills/aria-harness-onboarding/SKILL.md +130 -0
  642. package/skills/aria-harness-output-discipline/SKILL.md +120 -0
  643. package/skills/aria-harness-substrate-binding/SKILL.md +139 -0
  644. package/skills/aria-http-harness-client/SKILL.md +85 -0
  645. package/skills/aria-http-harness-client/scripts/smoke.mjs +47 -0
  646. package/skills/aria-k8s-deploy/SKILL.md +174 -0
  647. package/skills/aria-k8s-deploy/agents/openai.yaml +3 -0
  648. package/skills/aria-ladduniframe/SKILL.md +60 -0
  649. package/skills/aria-ledger-fleet-execution/SKILL.md +126 -0
  650. package/skills/aria-live-ops/SKILL.md +54 -0
  651. package/skills/aria-mac-ssh-ops/SKILL.md +100 -0
  652. package/skills/aria-memory-index/SKILL.md +42 -0
  653. package/skills/aria-noor-cognitives/SKILL.md +120 -0
  654. package/skills/aria-ops/SKILL.md +60 -0
  655. package/skills/aria-ops/references/live-endpoints.md +59 -0
  656. package/skills/aria-quality-audit/SKILL.md +133 -0
  657. package/skills/aria-reasoning/SKILL.md +67 -0
  658. package/skills/aria-reasoning/references/core-principles.md +42 -0
  659. package/skills/aria-repo-doctrine/SKILL.md +57 -0
  660. package/skills/aria-soul-principles/SKILL.md +42 -0
  661. package/skills/aria-task-codex-executor/SKILL.md +86 -0
  662. package/skills/aristotle-engine/SKILL.md +42 -0
  663. package/skills/ci-cd-pipeline/SKILL.md +116 -0
  664. package/skills/code-review/SKILL.md +131 -0
  665. package/skills/cross-domain-24/SKILL.md +42 -0
  666. package/skills/database-design/SKILL.md +124 -0
  667. package/skills/deepsoul-emotional/SKILL.md +42 -0
  668. package/skills/deno-kv-raft-pubsub/SKILL.md +561 -0
  669. package/skills/deno-kv-raft-pubsub/reference/maelstrom-integration.md +393 -0
  670. package/skills/deno-kv-raft-pubsub/reference/pubsub-api.md +376 -0
  671. package/skills/deno-kv-raft-pubsub/reference/raft-spec.md +402 -0
  672. package/skills/deno-kv-raft-pubsub/reference/state-machine.md +182 -0
  673. package/skills/error-handling/SKILL.md +159 -0
  674. package/skills/firecrawl/SKILL.md +165 -0
  675. package/skills/firecrawl/rules/install.md +82 -0
  676. package/skills/firecrawl/rules/security.md +26 -0
  677. package/skills/firecrawl-agent/SKILL.md +86 -0
  678. package/skills/firecrawl-build-interact/SKILL.md +96 -0
  679. package/skills/firecrawl-build-onboarding/SKILL.md +131 -0
  680. package/skills/firecrawl-build-onboarding/references/auth-flow.md +39 -0
  681. package/skills/firecrawl-build-onboarding/references/project-setup.md +20 -0
  682. package/skills/firecrawl-build-onboarding/references/sdk-installation.md +17 -0
  683. package/skills/firecrawl-build-scrape/SKILL.md +97 -0
  684. package/skills/firecrawl-build-search/SKILL.md +97 -0
  685. package/skills/firecrawl-clone/SKILL.md +419 -0
  686. package/skills/firecrawl-crawl/SKILL.md +87 -0
  687. package/skills/firecrawl-download/SKILL.md +98 -0
  688. package/skills/firecrawl-interact/SKILL.md +112 -0
  689. package/skills/firecrawl-map/SKILL.md +79 -0
  690. package/skills/firecrawl-scrape/SKILL.md +97 -0
  691. package/skills/firecrawl-search/SKILL.md +88 -0
  692. package/skills/fitrah-guard/SKILL.md +78 -0
  693. package/skills/forge-quality-rules/SKILL.md +61 -0
  694. package/skills/ghazali-8lens/SKILL.md +56 -0
  695. package/skills/ijtihad-novel/SKILL.md +42 -0
  696. package/skills/ilham-intuition/SKILL.md +42 -0
  697. package/skills/imagegen/LICENSE.txt +201 -0
  698. package/skills/imagegen/SKILL.md +374 -0
  699. package/skills/imagegen/agents/openai.yaml +6 -0
  700. package/skills/imagegen/assets/imagegen-small.svg +5 -0
  701. package/skills/imagegen/assets/imagegen.png +0 -0
  702. package/skills/imagegen/references/cli.md +242 -0
  703. package/skills/imagegen/references/codex-network.md +33 -0
  704. package/skills/imagegen/references/image-api.md +90 -0
  705. package/skills/imagegen/references/prompting.md +118 -0
  706. package/skills/imagegen/references/sample-prompts.md +433 -0
  707. package/skills/imagegen/scripts/image_gen.py +995 -0
  708. package/skills/imagegen/scripts/remove_chroma_key.py +440 -0
  709. package/skills/istiqra-induction/SKILL.md +44 -0
  710. package/skills/ladunni-22/SKILL.md +53 -0
  711. package/skills/mizan/SKILL.md +90 -0
  712. package/skills/nadia/SKILL.md +56 -0
  713. package/skills/nadia-psi/SKILL.md +56 -0
  714. package/skills/never-guess/SKILL.md +75 -0
  715. package/skills/noor-recognition/SKILL.md +45 -0
  716. package/skills/observability/SKILL.md +133 -0
  717. package/skills/openai-docs/LICENSE.txt +201 -0
  718. package/skills/openai-docs/SKILL.md +100 -0
  719. package/skills/openai-docs/agents/openai.yaml +14 -0
  720. package/skills/openai-docs/assets/openai-small.svg +3 -0
  721. package/skills/openai-docs/assets/openai.png +0 -0
  722. package/skills/openai-docs/references/latest-model.md +37 -0
  723. package/skills/openai-docs/references/prompting-guide.md +244 -0
  724. package/skills/openai-docs/references/upgrade-guide.md +181 -0
  725. package/skills/openai-docs/scripts/resolve-latest-model-info.js +147 -0
  726. package/skills/pdf/LICENSE.txt +201 -0
  727. package/skills/pdf/SKILL.md +85 -0
  728. package/skills/pdf/agents/openai.yaml +5 -0
  729. package/skills/pdf/assets/pdf.png +0 -0
  730. package/skills/playwright/LICENSE.txt +201 -0
  731. package/skills/playwright/NOTICE.txt +14 -0
  732. package/skills/playwright/SKILL.md +165 -0
  733. package/skills/playwright/agents/openai.yaml +6 -0
  734. package/skills/playwright/assets/playwright-small.svg +3 -0
  735. package/skills/playwright/assets/playwright.png +0 -0
  736. package/skills/playwright/references/cli.md +116 -0
  737. package/skills/playwright/references/workflows.md +95 -0
  738. package/skills/playwright/scripts/playwright_cli.sh +25 -0
  739. package/skills/plugin-creator/SKILL.md +178 -0
  740. package/skills/plugin-creator/agents/openai.yaml +6 -0
  741. package/skills/plugin-creator/assets/plugin-creator-small.svg +3 -0
  742. package/skills/plugin-creator/assets/plugin-creator.png +0 -0
  743. package/skills/plugin-creator/references/plugin-json-spec.md +170 -0
  744. package/skills/plugin-creator/scripts/create_basic_plugin.py +301 -0
  745. package/skills/predictor/SKILL.md +43 -0
  746. package/skills/qiyas-analogy/SKILL.md +204 -0
  747. package/skills/refactoring/SKILL.md +137 -0
  748. package/skills/ruh-basis/SKILL.md +42 -0
  749. package/skills/security-review/SKILL.md +129 -0
  750. package/skills/skill-creator/SKILL.md +434 -0
  751. package/skills/skill-creator/agents/openai.yaml +5 -0
  752. package/skills/skill-creator/assets/skill-creator-small.svg +3 -0
  753. package/skills/skill-creator/assets/skill-creator.png +0 -0
  754. package/skills/skill-creator/license.txt +202 -0
  755. package/skills/skill-creator/references/openai_yaml.md +49 -0
  756. package/skills/skill-creator/scripts/generate_openai_yaml.py +226 -0
  757. package/skills/skill-creator/scripts/init_skill.py +400 -0
  758. package/skills/skill-creator/scripts/quick_validate.py +101 -0
  759. package/skills/skill-installer/LICENSE.txt +202 -0
  760. package/skills/skill-installer/SKILL.md +76 -0
  761. package/skills/skill-installer/agents/openai.yaml +5 -0
  762. package/skills/skill-installer/assets/skill-installer-small.svg +3 -0
  763. package/skills/skill-installer/assets/skill-installer.png +0 -0
  764. package/skills/skill-installer/scripts/github_utils.py +21 -0
  765. package/skills/skill-installer/scripts/install-skill-from-github.py +308 -0
  766. package/skills/skill-installer/scripts/list-skills.py +107 -0
  767. package/skills/skills-and-hooks-reference/SKILL.md +196 -0
  768. package/skills/soul-domains/SKILL.md +43 -0
  769. package/skills/tadabbur/SKILL.md +232 -0
  770. package/skills/tadabbur-ops/SKILL.md +42 -0
  771. package/skills/tafakkur/SKILL.md +104 -0
  772. package/skills/testing-strategy/SKILL.md +122 -0
  773. package/src/action-ledger-core.ts +1054 -0
  774. package/src/chat.ts +5 -6
  775. package/src/codebase-scanner.ts +2 -0
  776. package/src/connectors/claude-code.ts +149 -12
  777. package/src/connectors/codebase-awareness.ts +325 -25
  778. package/src/connectors/codex.ts +1225 -41
  779. package/src/connectors/cursor.ts +8 -0
  780. package/src/connectors/governed-adapter.ts +174 -0
  781. package/src/connectors/opencode.ts +18 -2
  782. package/src/connectors/repo-guard.ts +24 -12
  783. package/src/connectors/runtime.ts +99 -2
  784. package/src/connectors/shell.ts +125 -7
  785. package/src/cross-cli-hive-binding.ts +290 -0
  786. package/src/garden-control-plane.ts +24 -1
  787. package/src/governed-surface-runner.ts +1227 -0
  788. package/src/index.ts +104 -1
  789. package/src/task-runner.ts +3794 -0
  790. package/dist/aria-connector/src/install-hooks.d.ts +0 -18
  791. package/dist/aria-connector/src/install-hooks.d.ts.map +0 -1
  792. package/dist/aria-connector/src/install-hooks.js +0 -224
  793. package/dist/aria-connector/src/install-hooks.js.map +0 -1
  794. package/dist/aria-connector/src/onboarding-wizard.d.ts +0 -5
  795. package/dist/aria-connector/src/onboarding-wizard.d.ts.map +0 -1
  796. package/dist/aria-connector/src/onboarding-wizard.js +0 -188
  797. package/dist/aria-connector/src/onboarding-wizard.js.map +0 -1
  798. package/dist/cli-0.2.38.tgz +0 -0
  799. package/dist/install.sh +0 -13
  800. package/src/__tests__/anthropic-oauth.test.ts +0 -186
  801. package/src/__tests__/auth-commands.test.ts +0 -132
  802. package/src/__tests__/owner-login.test.ts +0 -311
@@ -0,0 +1,1400 @@
1
+ #!/usr/bin/env node
2
+ // aria-pre-emit-autoload.mjs — UserPromptSubmit hook
3
+ //
4
+ // Redesigned 2026-05-09 per Hamza directive: cognition must FRAME the work
5
+ // pre-flight, not be written as ceremony at end-of-turn. Hooks cannot invoke
6
+ // tools, but they CAN inject content as additionalContext. This hook is the
7
+ // pre-flight cognition delivery mechanism: it reads each required skill's
8
+ // BODY (operative rules, workflow, triggers — not just the description) and
9
+ // injects it into the assistant's UserPromptSubmit context BEFORE drafting.
10
+ //
11
+ // Decoupled from the gates-off marker. The gates-off marker disables BLOCKING
12
+ // gates (coach, recovery-executor); it must NOT disable content enrichment,
13
+ // because the very thing that makes the agent's work first-class is having
14
+ // the doctrine content present in context. Use ARIA_AUTOLOAD_DISABLE=1 only
15
+ // for genuine debugging of this hook itself.
16
+ //
17
+ // Triplet honored:
18
+ // - Thinking: classifier picks required skills based on prompt + carry-forward
19
+ // - Implementation: this file reads bodies + injects them
20
+ // - Accountability: sidecar records body excerpts; gate-ledger records byte counts
21
+ //
22
+ // What this hook does on every UserPromptSubmit:
23
+ // 1. Read user prompt from hook event
24
+ // 2. Classify intent → required skills via classifyRequiredSkills
25
+ // 3. For each required skill, read SKILL.md body (frontmatter stripped,
26
+ // redundant trailing boilerplate stripped, capped at 4KB per skill)
27
+ // 4. Build structured additionalContext: FRAME (skill bodies) +
28
+ // DRIVING-RULES (operative summary) + POST-QA (predicate template) +
29
+ // cognition vocabulary
30
+ // 5. Persist sidecar at ~/.claude/.aria-current-turn-context.json with
31
+ // body excerpts for post-phase QA reference
32
+ // 6. Append gate-ledger entry with byte counts injected
33
+ //
34
+ // What this hook does NOT do:
35
+ // - Does not invoke the Skill tool itself (Claude Code hooks cannot mutate
36
+ // the assistant's tool-call list). Body content arrives as context.
37
+ // - Does not block. Pre-emit is enrichment; pre-tool-gate enforces.
38
+
39
+ import { readFileSync, writeFileSync, existsSync, mkdirSync, statSync, lstatSync, readdirSync } from 'node:fs';
40
+ import { dirname } from 'node:path';
41
+ import { homedir } from 'node:os';
42
+ import { createHash } from 'node:crypto';
43
+ import { classifyRequiredSkills, parseLoadFirstSection } from './lib/skill-autoload-gate-impl.mjs';
44
+ import { appendGateLedger } from './lib/aria-gate-ledger.mjs';
45
+ import { loadDoctrineTriggerMap } from './lib/doctrine-trigger-map-loader.mjs';
46
+
47
+ const HOME = homedir();
48
+ const SIDECAR_PATH = `${HOME}/.claude/.aria-current-turn-context.json`;
49
+ const SKILLS_DIR = `${HOME}/.claude/skills`;
50
+ const HOOK_EVENT_NAME = 'UserPromptSubmit';
51
+ const HEADER_PREFIX = '[ARIA_PRE_EMIT_AUTOLOAD]';
52
+
53
+ // Budget caps. Per-skill 4KB keeps each skill's operative section in scope
54
+ // without bloating context. Total 25KB stays well within additionalContext
55
+ // tolerance observed in this surface. Hard file-size cap 50KB rejects
56
+ // abnormally large or attacker-planted SKILL.md files.
57
+ const MAX_BYTES_PER_SKILL = 4096;
58
+ const MAX_BYTES_TOTAL = 25 * 1024;
59
+ const MAX_SKILL_FILE_BYTES = 50 * 1024;
60
+
61
+ // AI-11803-LOOP1 (2026-05-12): cascade-depth cap. Each loaded skill body is
62
+ // scanned for Load First / Mode Selection / Load Order / Ta'aqqul Autofire
63
+ // sections; named skills cascade onto the load set. Depth 3 covers
64
+ // autofire → quality-audit → first-principles cascades without unbounded
65
+ // recursion through skills that load each other.
66
+ const MAX_CASCADE_DEPTH = 3;
67
+
68
+ // AI-11803-LOOP2 (2026-05-12): doctrine-trigger map pre-emit pass caps.
69
+ // The trigger map has 79 entries; scanning the user prompt against each
70
+ // regex is O(79 * promptLen). The cap on matched triggers prevents a
71
+ // pathological prompt from producing a giant alert block. The per-trigger
72
+ // byte budget keeps each alert compact (teaching + counter_action + memory
73
+ // file name + trigger). Total budget fits inside additionalContext alongside
74
+ // skill bodies without competing for the 25KB skill-body cap.
75
+ const DOCTRINE_TRIGGER_MAP_PATH = `${HOME}/.claude/hooks/doctrine_trigger_map.json`;
76
+ const MEMORY_DIR = `${HOME}/.claude/projects/-home-hamzaibrahim1/memory`;
77
+ const MAX_DOCTRINE_TRIGGER_MATCHES = 8;
78
+ const MAX_BYTES_PER_TRIGGER_ALERT = 480;
79
+ // AI-11803-QA-GAP3 (2026-05-12): per-memory body injection cap.
80
+ // QA-FIX (2026-05-12 same turn): raised to 4KB so the must-satisfy Recovery
81
+ // Contract section (Pre-Conditions + Classification A/B/C/D + Loop Safety +
82
+ // Turn-End Checklist) fits. Same-memory dedup keeps total bounded to
83
+ // ~12KB worst-case (3 distinct memories × 4KB) but typically 4-8KB.
84
+ const MAX_BYTES_PER_MEMORY_BODY = 4096;
85
+ // File-size ceiling raised to 32KB so strengthened doctrine memories
86
+ // (Recovery Contracts + qiyas + tadabbur + 8-lens substrate) don't get
87
+ // silently rejected. Per-body cap above still bounds what gets injected;
88
+ // the ceiling only rejects abnormally-large or attacker-planted files.
89
+ const MAX_MEMORY_FILE_CEILING = 32 * 1024;
90
+ // QA-FIX-SECTION-AWARE: when a memory body has a "# Recovery Contract"
91
+ // section, prefer to extract from that section forward. This makes the
92
+ // must-satisfy operative content load-bearing in autoload context even
93
+ // when the memory is 12-18KB. Falls back to top-of-body truncation when
94
+ // the header isn't present. Header pattern matches "# Recovery Contract"
95
+ // or "# Recovery contract" (case-insensitive) anchored on a heading line.
96
+ const RECOVERY_CONTRACT_HEADER_RX = /^#{1,3}\s+Recovery\s+Contract\b/im;
97
+
98
+ // AI-11803-STEP5 (2026-05-12) — cookbook auto-pull on trigger match.
99
+ // Skill bodies reference `references/<name>.md` cookbooks (1KB-79KB). The
100
+ // cascade primitive loads SKILL.md but NOT the referenced cookbooks. This
101
+ // primitive scans loaded skill bodies for the reference pattern, parses
102
+ // each cookbook's section headers, scores sections by prompt-keyword
103
+ // overlap, and injects the top-1 section per cookbook into context.
104
+ //
105
+ // Deterministic selection (no LLM call, no faux-fallback):
106
+ // 1. Extract keywords from prompt: lowercase tokens length ≥ 4, deduped.
107
+ // 2. Score each `## ` or `### ` section by count of distinct prompt
108
+ // keywords appearing in section text (header to next header of
109
+ // same/higher level).
110
+ // 3. Min threshold: section must score ≥ 2 distinct keywords. Below
111
+ // threshold → skip the cookbook entirely. NO faux-fallback to "first
112
+ // section if no match" — that would be polluting context with
113
+ // arbitrary content (cf. tadabbur INVERSION + forge-guardrails).
114
+ // 4. Tie-break: later position in file wins.
115
+ // 5. Per-cookbook injection capped at MAX_BYTES_PER_COOKBOOK_SECTION (2KB).
116
+ // 6. Total cookbook injection capped at MAX_BYTES_COOKBOOK_TOTAL (4KB).
117
+ //
118
+ // Loop safety: depth cap = 1 (no transitive cookbook→cookbook expansion);
119
+ // each cookbook path injected at most once per turn (Set dedup).
120
+ //
121
+ // Kill switch: ARIA_AUTOLOAD_COOKBOOK_OFF=1.
122
+ // Captures both same-skill (`references/x.md`) and cross-skill
123
+ // (`../<other-skill>/references/x.md`) reference patterns. Group 1 (if
124
+ // present) is the cross-skill name; group 2 is the cookbook filename.
125
+ // QA-FIX (2026-05-12 same turn): cross-skill references were previously
126
+ // silently mis-resolved to the wrong skill dir → invisible to autoload.
127
+ const COOKBOOK_REF_RX = /(?:\.\.\/([a-z0-9_-]+)\/)?references\/([a-z0-9_-]+\.md)/gi;
128
+
129
+ // AI-11803-F3 (2026-05-12) — sub-agent parent-handoff inheritance.
130
+ // When this autoload fires inside a sub-agent session, the parent
131
+ // orchestrator's aria-agent-handoff.mjs wrote a handoff JSON containing
132
+ // the parent's autoload pins (skill names, memory filenames, cookbook
133
+ // section selections). Read those FIRST, layer them into the load set,
134
+ // then let the sub-agent's own classifier add task-specific skills on
135
+ // top. Augment, not override.
136
+ //
137
+ // Loop safety: handoff JSON includes chainDepth=1 marker; downstream
138
+ // hops (sub-sub-agent) DROP propagation when constructing their own
139
+ // handoff (write-side check in aria-agent-handoff.mjs).
140
+ //
141
+ // TTL: handoff carries ttlMs (5min); if expired vs writtenAt, ignore.
142
+ // Stale handoffs aren't an error — they're from a finished parent turn
143
+ // whose context is no longer load-bearing.
144
+ //
145
+ // Kill switch: ARIA_AUTOLOAD_PARENT_HANDOFF_OFF=1
146
+ const PARENT_HANDOFF_PATH = `${HOME}/.claude/aria-agent-harness-handoff.json`;
147
+ const COOKBOOK_HEADER_RX = /^(#{2,3})\s+(.+)$/gm;
148
+ const MAX_BYTES_PER_COOKBOOK_SECTION = 2048;
149
+ const MAX_BYTES_COOKBOOK_TOTAL = 4096;
150
+ const COOKBOOK_MIN_SCORE = 2;
151
+ const COOKBOOK_KEYWORD_MIN_LEN = 4;
152
+ const COOKBOOK_FILE_CEILING = 200 * 1024; // 200KB hard ceiling on cookbook files (largest seen is 79KB)
153
+
154
+ // AI-11803-STEP4 (2026-05-12) — MEMORY.md auto-load + top-N body injection.
155
+ // MEMORY.md is the master index of every Aria doctrine memory written across
156
+ // sessions. Without this primitive, the model only sees memory bodies when a
157
+ // doctrine-trigger regex fires (lib/doctrine-trigger-map-loader.mjs path) —
158
+ // which means ~80% of accumulated doctrine is invisible per turn. Hamza
159
+ // directive 2026-05-12: "memory.md should def auto load."
160
+ //
161
+ // Budget split (hard cap 8KB total so this doesn't crowd the 25KB skill-body
162
+ // budget):
163
+ // - 4KB MEMORY.md index (one-line entries from the file verbatim,
164
+ // gracefully truncated with a tail marker naming how many entries fell
165
+ // off the cap so the agent knows to consult the file directly)
166
+ // - 4KB for top-N memory bodies (default N=3, ~1.3KB each)
167
+ //
168
+ // Priority signal for top-N selection (deterministic, no faux-priority):
169
+ // 1. Frontmatter `priority: <number>` field if present (explicit owner
170
+ // signal — honest first-tier). Higher number = higher priority.
171
+ // 2. mtime descending (recency fallback when no explicit priority — the
172
+ // most-recently authored or edited memory is the most likely to be
173
+ // currently relevant; this matches Hamza's authoring cadence).
174
+ //
175
+ // Dedup contract: top-N body injection MUST skip memories already injected
176
+ // by buildDoctrineTriggerInjection() this turn (trigger-map regex matched
177
+ // → memory body inlined already). Without dedup, the same memory body could
178
+ // land twice on the same turn. Implemented via a Set<string> of memory
179
+ // filenames passed from main() after doctrineScan.matches is computed.
180
+ const MAX_BYTES_MEMORY_INDEX = 4096;
181
+ const MAX_BYTES_MEMORY_BODIES = 4096;
182
+ const TOP_N_MEMORY_BODIES = 3;
183
+ const MEMORY_INDEX_PATH = `${MEMORY_DIR}/MEMORY.md`;
184
+
185
+ // Trailing boilerplate sections that are identical across skills and add
186
+ // only noise when injected. Stripping these gives 1-1.5KB of headroom per
187
+ // skill back to the operative content (Trigger, Rules, Workflow). This is
188
+ // trimming redundant duplication, NOT contract-stripping per the
189
+ // no-stripping-as-workaround doctrine.
190
+ const REDUNDANT_TRAILING_SECTIONS = [
191
+ /## First-Class Production Contract[\s\S]*?(?=\n## |\n# |$)/i,
192
+ /## Self-Executing Recovery Contract[\s\S]*?(?=\n## |\n# |$)/i,
193
+ /## Required Workflow[\s\S]*?(?=\n## |\n# |$)/i, // generic 5-step list also identical across skills
194
+ ];
195
+
196
+ function readEvent() {
197
+ try {
198
+ const raw = readFileSync(0, 'utf8');
199
+ return raw.trim() ? JSON.parse(raw) : {};
200
+ } catch {
201
+ return {};
202
+ }
203
+ }
204
+
205
+ function emit(envelope) {
206
+ process.stdout.write(`${JSON.stringify(envelope)}\n`);
207
+ }
208
+
209
+ function emitNoop(reason) {
210
+ emit({
211
+ hookSpecificOutput: {
212
+ hookEventName: HOOK_EVENT_NAME,
213
+ additionalContext: `${HEADER_PREFIX} skipped: ${reason}`,
214
+ },
215
+ });
216
+ process.exit(0);
217
+ }
218
+
219
+ function writeSidecar(payload) {
220
+ try {
221
+ mkdirSync(dirname(SIDECAR_PATH), { recursive: true, mode: 0o700 });
222
+ writeFileSync(SIDECAR_PATH, `${JSON.stringify(payload, null, 2)}\n`, { mode: 0o600 });
223
+ } catch (err) {
224
+ process.stderr.write(`[aria-pre-emit-autoload:sidecar-write] ${err instanceof Error ? err.message : String(err)}\n`);
225
+ }
226
+ }
227
+
228
+ // Read and prepare a skill body for injection. Returns { body, bytes,
229
+ // fullBytes, redacted, reason } so caller can record what was injected and
230
+ // why. Hardens against:
231
+ // - non-regular files (symlinks, fifos, devices) → reject
232
+ // - oversize SKILL.md (> MAX_SKILL_FILE_BYTES) → reject
233
+ // - missing files → empty body, no crash
234
+ function readSkillBody(skillName) {
235
+ const path = `${SKILLS_DIR}/${skillName}/SKILL.md`;
236
+ if (!existsSync(path)) {
237
+ return { body: '', bytes: 0, fullBytes: 0, redacted: false, reason: 'missing' };
238
+ }
239
+ let lst;
240
+ try {
241
+ lst = lstatSync(path);
242
+ } catch (err) {
243
+ return { body: '', bytes: 0, fullBytes: 0, redacted: false, reason: `lstat-failed: ${err?.message || err}` };
244
+ }
245
+ if (!lst.isFile()) {
246
+ return { body: '', bytes: 0, fullBytes: 0, redacted: true, reason: 'not-regular-file' };
247
+ }
248
+ if (lst.size > MAX_SKILL_FILE_BYTES) {
249
+ return { body: '', bytes: 0, fullBytes: lst.size, redacted: true, reason: `oversize: ${lst.size}B > ${MAX_SKILL_FILE_BYTES}B` };
250
+ }
251
+ let raw;
252
+ try {
253
+ raw = readFileSync(path, 'utf8');
254
+ } catch (err) {
255
+ return { body: '', bytes: 0, fullBytes: lst.size, redacted: false, reason: `read-failed: ${err?.message || err}` };
256
+ }
257
+ const fullBytes = Buffer.byteLength(raw, 'utf8');
258
+ // Strip YAML frontmatter (--- ... --- at top of file)
259
+ let trimmed = raw.replace(/^---[\s\S]*?---\s*/, '');
260
+ // Strip redundant trailing boilerplate sections that are identical
261
+ // across all skills (per pre-phase analysis). This is duplication
262
+ // trimming, not contract stripping.
263
+ for (const rx of REDUNDANT_TRAILING_SECTIONS) {
264
+ trimmed = trimmed.replace(rx, '');
265
+ }
266
+ trimmed = trimmed.trimEnd();
267
+ // Apply per-skill byte cap. If we have to truncate, leave a marker so
268
+ // the agent knows there's more content available via Skill tool.
269
+ let body = trimmed;
270
+ let truncated = false;
271
+ if (Buffer.byteLength(body, 'utf8') > MAX_BYTES_PER_SKILL) {
272
+ // Truncate at a paragraph boundary near the cap when possible.
273
+ const buf = Buffer.from(body, 'utf8').slice(0, MAX_BYTES_PER_SKILL);
274
+ body = buf.toString('utf8');
275
+ const lastBreak = Math.max(body.lastIndexOf('\n\n'), body.lastIndexOf('\n## '));
276
+ if (lastBreak > MAX_BYTES_PER_SKILL * 0.6) {
277
+ body = body.slice(0, lastBreak);
278
+ }
279
+ truncated = true;
280
+ body += `\n\n[…body truncated at ${MAX_BYTES_PER_SKILL}B; full SKILL.md available via /skills/${skillName}/SKILL.md…]`;
281
+ }
282
+ const bytes = Buffer.byteLength(body, 'utf8');
283
+ return {
284
+ body,
285
+ bytes,
286
+ fullBytes,
287
+ redacted: false,
288
+ truncated,
289
+ reason: 'ok',
290
+ };
291
+ }
292
+
293
+ // AI-11803-LOOP2 (2026-05-12) — doctrine-trigger pre-emit scan.
294
+ // Runs the 79-trigger doctrine map against the user's prompt text at
295
+ // UserPromptSubmit so prose-pattern matches (e.g., "graceful degradation",
296
+ // "out of scope", "want me to") surface their bound doctrine memory +
297
+ // teaching + counter_action BEFORE the model drafts. Prior architecture
298
+ // only ran the trigger map post-emit (after the answer was drafted), which
299
+ // caught drift after the fact instead of preventing it.
300
+ //
301
+ // Output shape: a separate "[ARIA_DOCTRINE_TRIGGERS_MATCHED]" section in
302
+ // additionalContext, formatted as compact one-line-per-trigger alerts.
303
+ // Does NOT inject the bound memory file content (separate from skill-body
304
+ // injection); the memory filename surfaces so the model can read it via
305
+ // the existing memory-consumption gate at PreToolUse.
306
+ //
307
+ // Fail-allow: any error in trigger map load returns empty matches list and
308
+ // LOUD telemetry — never blocks the autoload's emission.
309
+ //
310
+ // Kill switch: ARIA_AUTOLOAD_TRIGGER_MAP_OFF=1.
311
+ function scanDoctrineTriggers(promptText) {
312
+ if (/^(?:1|true|yes|on)$/i.test(String(process.env.ARIA_AUTOLOAD_TRIGGER_MAP_OFF || ''))) {
313
+ return { matches: [], errors: [], skipped: 'env-disabled' };
314
+ }
315
+ if (!promptText || typeof promptText !== 'string') {
316
+ return { matches: [], errors: [], skipped: 'empty-prompt' };
317
+ }
318
+ let loaded;
319
+ try {
320
+ loaded = loadDoctrineTriggerMap(DOCTRINE_TRIGGER_MAP_PATH);
321
+ } catch (err) {
322
+ const msg = err instanceof Error ? err.message : String(err);
323
+ process.stderr.write(`[aria-pre-emit-autoload:trigger-map-load-error] ${msg}\n`);
324
+ return { matches: [], errors: [msg], skipped: 'load-error' };
325
+ }
326
+ const matches = [];
327
+ const seen = new Set();
328
+ for (const entry of loaded.triggers) {
329
+ if (matches.length >= MAX_DOCTRINE_TRIGGER_MATCHES) break;
330
+ // Each entry's compiled regex carries the `gi` flags; reset lastIndex
331
+ // so re-use across multiple scans doesn't skip from prior call state.
332
+ entry.regex.lastIndex = 0;
333
+ if (!entry.regex.test(promptText)) continue;
334
+ // De-dup by memory file (multiple triggers may bind the same memory).
335
+ if (seen.has(entry.memory)) continue;
336
+ seen.add(entry.memory);
337
+ matches.push({
338
+ trigger: entry.trigger,
339
+ memory: entry.memory,
340
+ teaching: entry.teaching,
341
+ counter_action: entry.counter_action,
342
+ });
343
+ }
344
+ return { matches, errors: loaded.errors || [], skipped: null };
345
+ }
346
+
347
+ // AI-11803-QA-GAP3 (2026-05-12): read memory body for injection.
348
+ // Returns frontmatter-stripped, cap-truncated body or empty string on any
349
+ // failure. Per parallel-session safety, never throws.
350
+ function readMemoryBody(memoryFilename) {
351
+ if (!memoryFilename || typeof memoryFilename !== 'string') return '';
352
+ const path = `${MEMORY_DIR}/${memoryFilename}`;
353
+ if (!existsSync(path)) return '';
354
+ let lst;
355
+ try { lst = lstatSync(path); } catch { return ''; }
356
+ if (!lst.isFile()) return '';
357
+ if (lst.size > MAX_MEMORY_FILE_CEILING) return ''; // hard ceiling on file size
358
+ let raw;
359
+ try { raw = readFileSync(path, 'utf8'); } catch { return ''; }
360
+ // Strip YAML frontmatter; if absent, raw passes through.
361
+ let body = raw.replace(/^---[\s\S]*?---\s*/, '').trimStart();
362
+ // QA-FIX-SECTION-AWARE: if the body has a "# Recovery Contract" section,
363
+ // extract from that section forward. The must-satisfy contract becomes
364
+ // the operative content; preceding rationale (qiyas / tadabbur / 8-lens
365
+ // pre-amble) stays in the file for read-on-demand but doesn't crowd the
366
+ // pre-emit context.
367
+ const recoveryMatch = body.match(RECOVERY_CONTRACT_HEADER_RX);
368
+ let extractionMode = 'top-of-body';
369
+ if (recoveryMatch) {
370
+ const headerStart = body.indexOf(recoveryMatch[0]);
371
+ const before = body.slice(0, headerStart);
372
+ const beforeBytes = Buffer.byteLength(before, 'utf8');
373
+ body = `[…body preamble omitted, ${beforeBytes}B; recovery contract follows…]\n\n${body.slice(headerStart)}`;
374
+ extractionMode = 'recovery-contract-section';
375
+ }
376
+ if (Buffer.byteLength(body, 'utf8') > MAX_BYTES_PER_MEMORY_BODY) {
377
+ const buf = Buffer.from(body, 'utf8').slice(0, MAX_BYTES_PER_MEMORY_BODY);
378
+ body = buf.toString('utf8');
379
+ const lastBreak = Math.max(body.lastIndexOf('\n\n'), body.lastIndexOf('\n'));
380
+ if (lastBreak > MAX_BYTES_PER_MEMORY_BODY * 0.6) body = body.slice(0, lastBreak);
381
+ body += `\n[…memory body truncated at ${MAX_BYTES_PER_MEMORY_BODY}B; mode=${extractionMode}; full file at ${path}…]`;
382
+ }
383
+ return body;
384
+ }
385
+
386
+ function buildDoctrineTriggerInjection(matches) {
387
+ if (!matches || matches.length === 0) return '';
388
+ const lines = [];
389
+ lines.push('═══ ARIA DOCTRINE TRIGGERS MATCHED (prose patterns in your prompt bind to these memories) ═══');
390
+ for (const m of matches) {
391
+ let teaching = m.teaching;
392
+ let counter = m.counter_action;
393
+ // Per-alert byte cap — truncate teaching+counter if combined exceed budget.
394
+ const baseLen = ` • [${m.trigger}] → ${m.memory}: `.length;
395
+ const budget = MAX_BYTES_PER_TRIGGER_ALERT - baseLen;
396
+ const combined = `${teaching} || ${counter}`;
397
+ const slice = combined.length > budget ? `${combined.slice(0, budget - 3)}...` : combined;
398
+ lines.push(` • [${m.trigger}] → ${m.memory}: ${slice}`);
399
+ // AI-11803-QA-GAP3: inject memory body (capped) so the model sees the
400
+ // operative rule + Why + How-to-apply lines directly, not just a pointer.
401
+ const memBody = readMemoryBody(m.memory);
402
+ if (memBody) {
403
+ lines.push(` ┌─ memory body (${m.memory}):`);
404
+ for (const ln of memBody.split('\n')) lines.push(` │ ${ln}`);
405
+ lines.push(` └─`);
406
+ }
407
+ }
408
+ lines.push('Apply each: the trigger phrase in the prompt names a doctrine the agent must honor THIS turn.');
409
+ return lines.join('\n');
410
+ }
411
+
412
+ // AI-11803-LOOP1 (2026-05-12) — cascade autoload.
413
+ // Expand the initial skill set by reading each skill body and parsing its
414
+ // Load First / Mode Selection / Load Order / Ta'aqqul Autofire Pattern
415
+ // sections. Recursive BFS bounded by MAX_CASCADE_DEPTH and MAX_BYTES_TOTAL.
416
+ // Returns the load order, body map, total bytes, and observed depth so the
417
+ // caller can build skillBodies + sidecar + ledger telemetry from one pass.
418
+ //
419
+ // Cycle-safe: each skill is read at most once (Set<string> seen tracker).
420
+ // Budget-safe: once total bytes would exceed MAX_BYTES_TOTAL, subsequent
421
+ // skills are recorded with reason="budget-exhausted (cascade-depth=N)"
422
+ // instead of being dropped silently — the agent still sees that the skill
423
+ // was wanted but unavailable in context.
424
+ // Existence-filtered: cascade candidates are only enqueued if the SKILL.md
425
+ // actually exists on disk, so mode-label noise (`qa`, `light`, `batch`)
426
+ // and stale skill names from older bodies don't pollute the queue.
427
+ function expandSkillCascade(initialSkills) {
428
+ const loadedBodies = new Map(); // skill -> readSkillBody result
429
+ const order = []; // load order in BFS-by-depth
430
+ const seen = new Set();
431
+ let totalBytes = 0;
432
+ let queue = [...new Set(initialSkills)];
433
+ let depth = 0;
434
+ let maxObservedDepth = 0;
435
+ let maxAttemptedDepth = 0;
436
+ while (queue.length > 0 && depth <= MAX_CASCADE_DEPTH) {
437
+ const nextQueue = [];
438
+ for (const skill of queue) {
439
+ if (seen.has(skill)) continue;
440
+ seen.add(skill);
441
+ const result = readSkillBody(skill);
442
+ // Skip skills that don't exist on disk — keeps cascade quiet on mode
443
+ // labels and stale references.
444
+ if (result.reason === 'missing') continue;
445
+ // AI-11803-QA-GAP1 (2026-05-12): track attempted-depth separately from
446
+ // injected-depth. A candidate enqueued at depth N counts toward
447
+ // maxAttemptedDepth even if its body is budget-exhausted and bytes=0.
448
+ // Prior telemetry conflated "no body injected" with "no depth observed",
449
+ // under-reporting cascade reach when the 25KB cap saturated early.
450
+ maxAttemptedDepth = Math.max(maxAttemptedDepth, depth);
451
+ if (loadedBodies.size > 0 && totalBytes + result.bytes > MAX_BYTES_TOTAL) {
452
+ loadedBodies.set(skill, {
453
+ ...result,
454
+ body: '',
455
+ bytes: 0,
456
+ truncated: false,
457
+ redacted: false,
458
+ reason: `budget-exhausted (cascade-depth=${depth})`,
459
+ });
460
+ order.push(skill);
461
+ // Even when body is budget-exhausted, we still scan for downstream
462
+ // cascade candidates — but only if we have the body (we don't here),
463
+ // so this branch terminates the cascade for this skill's children.
464
+ continue;
465
+ }
466
+ loadedBodies.set(skill, result);
467
+ order.push(skill);
468
+ totalBytes += result.bytes;
469
+ maxObservedDepth = depth;
470
+ if (result.body) {
471
+ for (const c of parseLoadFirstSection(result.body)) {
472
+ if (seen.has(c)) continue;
473
+ if (!existsSync(`${SKILLS_DIR}/${c}/SKILL.md`)) continue;
474
+ nextQueue.push(c);
475
+ }
476
+ }
477
+ }
478
+ queue = nextQueue;
479
+ depth++;
480
+ }
481
+ return {
482
+ loadedBodies,
483
+ order,
484
+ totalBytes,
485
+ cascadeDepth: maxObservedDepth, // depth at which a body was injected (legacy alias for telemetry compat)
486
+ depthInjected: maxObservedDepth,
487
+ depthAttempted: maxAttemptedDepth,
488
+ };
489
+ }
490
+
491
+ // AI-11803-STEP4 (2026-05-12) — read MEMORY.md as an index, capped at
492
+ // MAX_BYTES_MEMORY_INDEX.
493
+ //
494
+ // QA-FIX-1 (2026-05-12, qiyas Owner-Hamza-tomorrow + scale + tadabbur
495
+ // INVERSION): tail-bias the truncation. MEMORY.md is append-only — Hamza
496
+ // writes new memories as entries at the BOTTOM. A head-bias truncation
497
+ // (drop from end) would drop the NEWEST doctrine first, recreating the
498
+ // exact gap this step was meant to close. Tail-bias keeps recent doctrine
499
+ // visible and drops older entries with a head-marker.
500
+ //
501
+ // Algorithm: walk lines from END to START, accumulate while under cap,
502
+ // reverse the kept set, prepend a head-marker naming how many earlier
503
+ // entries were dropped.
504
+ function readMemoryIndex() {
505
+ if (!existsSync(MEMORY_INDEX_PATH)) {
506
+ return { body: '', bytes: 0, totalLines: 0, droppedLines: 0, reason: 'missing' };
507
+ }
508
+ let lst;
509
+ try { lst = lstatSync(MEMORY_INDEX_PATH); } catch (err) {
510
+ return { body: '', bytes: 0, totalLines: 0, droppedLines: 0, reason: `lstat-failed: ${err?.message || err}` };
511
+ }
512
+ if (!lst.isFile()) {
513
+ return { body: '', bytes: 0, totalLines: 0, droppedLines: 0, reason: 'not-regular-file' };
514
+ }
515
+ let raw;
516
+ try { raw = readFileSync(MEMORY_INDEX_PATH, 'utf8'); } catch (err) {
517
+ return { body: '', bytes: 0, totalLines: 0, droppedLines: 0, reason: `read-failed: ${err?.message || err}` };
518
+ }
519
+ const lines = raw.split('\n');
520
+ const totalLines = lines.length;
521
+ if (Buffer.byteLength(raw, 'utf8') <= MAX_BYTES_MEMORY_INDEX) {
522
+ return { body: raw.trimEnd(), bytes: Buffer.byteLength(raw, 'utf8'), totalLines, droppedLines: 0, reason: 'ok' };
523
+ }
524
+ // Tail-bias: walk from end, accumulate newest lines first.
525
+ const keptReversed = [];
526
+ let accBytes = 0;
527
+ const reserveForMarker = 140;
528
+ for (let i = lines.length - 1; i >= 0; i--) {
529
+ const line = lines[i];
530
+ const lineBytes = Buffer.byteLength(line, 'utf8') + 1; // +1 for newline
531
+ if (accBytes + lineBytes > MAX_BYTES_MEMORY_INDEX - reserveForMarker) break;
532
+ keptReversed.push(line);
533
+ accBytes += lineBytes;
534
+ }
535
+ const kept = keptReversed.reverse();
536
+ const droppedLines = Math.max(0, totalLines - kept.length);
537
+ const headMarker = `[…MEMORY.md tail-biased: ${droppedLines} older entries dropped; full file at ${MEMORY_INDEX_PATH}. Showing latest ${kept.length} entries below…]`;
538
+ const body = `${headMarker}\n\n${kept.join('\n').trimEnd()}`;
539
+ return { body, bytes: Buffer.byteLength(body, 'utf8'), totalLines, droppedLines, reason: 'tail-biased' };
540
+ }
541
+
542
+ // AI-11803-STEP4 (2026-05-12) — score every memory file in MEMORY_DIR by
543
+ // (a) frontmatter `priority: <number>` if present (explicit), or
544
+ // (b) mtime descending (recency fallback).
545
+ // Returns sorted array of { filename, score, source } where higher score is
546
+ // more important. `source` is either "frontmatter:<n>" or "mtime:<ms>" so
547
+ // telemetry can audit which signal won.
548
+ //
549
+ // Filters: MEMORY.md itself is excluded (we inject it separately as the
550
+ // index). Non-.md files excluded. Files unreadable or non-regular are
551
+ // skipped silently — never throws.
552
+ function scoreMemoriesForPriority() {
553
+ let entries;
554
+ try { entries = readdirSync(MEMORY_DIR); } catch (err) {
555
+ return { scored: [], errors: [err?.message || String(err)] };
556
+ }
557
+ const scored = [];
558
+ const errors = [];
559
+ for (const filename of entries) {
560
+ if (filename === 'MEMORY.md') continue;
561
+ if (!filename.endsWith('.md')) continue;
562
+ const fullPath = `${MEMORY_DIR}/${filename}`;
563
+ let lst;
564
+ try { lst = lstatSync(fullPath); } catch (err) {
565
+ errors.push(`lstat ${filename}: ${err?.message || err}`);
566
+ continue;
567
+ }
568
+ if (!lst.isFile()) continue;
569
+ // Read just the frontmatter region — first ~1KB is plenty for YAML.
570
+ let head;
571
+ try {
572
+ const fd = readFileSync(fullPath, 'utf8');
573
+ head = fd.slice(0, 2048);
574
+ } catch (err) {
575
+ errors.push(`read ${filename}: ${err?.message || err}`);
576
+ continue;
577
+ }
578
+ const fmMatch = head.match(/^---\s*\n([\s\S]*?)\n---/);
579
+ let priority = null;
580
+ if (fmMatch) {
581
+ const fm = fmMatch[1];
582
+ const pMatch = fm.match(/^priority:\s*(-?\d+(?:\.\d+)?)\s*$/m);
583
+ if (pMatch) {
584
+ const parsed = Number(pMatch[1]);
585
+ if (Number.isFinite(parsed)) priority = parsed;
586
+ }
587
+ }
588
+ if (priority !== null) {
589
+ scored.push({ filename, score: priority, source: `frontmatter:${priority}`, tier: 'explicit' });
590
+ } else {
591
+ const mtimeMs = lst.mtimeMs || 0;
592
+ scored.push({ filename, score: mtimeMs, source: `mtime:${Math.floor(mtimeMs)}`, tier: 'recency' });
593
+ }
594
+ }
595
+ // Explicit-tier always outranks recency-tier. Within tier, score desc.
596
+ scored.sort((a, b) => {
597
+ if (a.tier !== b.tier) return a.tier === 'explicit' ? -1 : 1;
598
+ return b.score - a.score;
599
+ });
600
+ return { scored, errors };
601
+ }
602
+
603
+ // AI-11803-STEP4 (2026-05-12) — select top-N memory files for body injection,
604
+ // excluding those already injected by trigger-map. Reads each body via the
605
+ // existing readMemoryBody primitive (so the same per-memory cap +
606
+ // frontmatter-strip + size-ceiling applies). Stops once
607
+ // MAX_BYTES_MEMORY_BODIES is exhausted to enforce the hard 8KB total.
608
+ //
609
+ // Returns { injected: [{ filename, body, bytes, tier, score }], totalBytes,
610
+ // dedupedFilenames, scoredCount } so telemetry can audit selection + dedup.
611
+ function selectTopNMemoryBodies(alreadyInjectedFilenames) {
612
+ const { scored, errors } = scoreMemoriesForPriority();
613
+ const dedupedFilenames = [];
614
+ const injected = [];
615
+ let totalBytes = 0;
616
+ for (const entry of scored) {
617
+ if (injected.length >= TOP_N_MEMORY_BODIES) break;
618
+ if (alreadyInjectedFilenames && alreadyInjectedFilenames.has(entry.filename)) {
619
+ dedupedFilenames.push(entry.filename);
620
+ continue;
621
+ }
622
+ const body = readMemoryBody(entry.filename);
623
+ if (!body) continue;
624
+ const bodyBytes = Buffer.byteLength(body, 'utf8');
625
+ if (totalBytes + bodyBytes > MAX_BYTES_MEMORY_BODIES) {
626
+ // Don't take a body that would bust the cap; try the next-priority
627
+ // entry (which may be smaller). This avoids a single oversized
628
+ // memory starving subsequent smaller-but-still-important entries.
629
+ continue;
630
+ }
631
+ injected.push({ filename: entry.filename, body, bytes: bodyBytes, tier: entry.tier, score: entry.score });
632
+ totalBytes += bodyBytes;
633
+ }
634
+ return { injected, totalBytes, dedupedFilenames, scoredCount: scored.length, errors };
635
+ }
636
+
637
+ function buildMemoryAutoloadInjection({ indexResult, bodyResult }) {
638
+ // Kill-switch and pure-missing cases: emit nothing rather than a stub
639
+ // that crowds context with a "[unavailable]" placeholder.
640
+ if (indexResult.reason === 'env-disabled' && bodyResult.injected.length === 0) {
641
+ return '';
642
+ }
643
+ const lines = [];
644
+ lines.push('═══ MEMORY.md INDEX (auto-loaded — every doctrine memory available this session) ═══');
645
+ if (indexResult.bytes === 0) {
646
+ lines.push(`[MEMORY.md unavailable: ${indexResult.reason}]`);
647
+ } else {
648
+ lines.push(indexResult.body);
649
+ }
650
+ if (bodyResult.injected.length > 0) {
651
+ lines.push('');
652
+ lines.push(`═══ TOP-${bodyResult.injected.length} MEMORY BODIES (priority-selected, dedup'd against trigger-map matches) ═══`);
653
+ for (const entry of bodyResult.injected) {
654
+ lines.push('');
655
+ lines.push(`──── ${entry.filename} [${entry.tier === 'explicit' ? `priority=${entry.score}` : `mtime-rank`}] ────`);
656
+ lines.push(entry.body);
657
+ }
658
+ }
659
+ if (bodyResult.dedupedFilenames.length > 0) {
660
+ lines.push('');
661
+ lines.push(`[dedup: ${bodyResult.dedupedFilenames.length} top-N candidate(s) already injected by doctrine-trigger match: ${bodyResult.dedupedFilenames.join(', ')}]`);
662
+ }
663
+ return lines.join('\n');
664
+ }
665
+
666
+ // AI-11803-STEP5 — extract keywords from prompt for cookbook scoring.
667
+ // Lowercase, tokenize on non-word characters, filter to length ≥ 4, dedup.
668
+ // Returns Set<string> for O(1) membership check in section scoring.
669
+ function extractPromptKeywords(promptText) {
670
+ if (!promptText || typeof promptText !== 'string') return new Set();
671
+ const tokens = promptText.toLowerCase().split(/[^a-z0-9_-]+/);
672
+ const keywords = new Set();
673
+ for (const t of tokens) {
674
+ if (t.length >= COOKBOOK_KEYWORD_MIN_LEN) keywords.add(t);
675
+ }
676
+ return keywords;
677
+ }
678
+
679
+ // AI-11803-STEP5 — scan a loaded skill body for `references/<name>.md`
680
+ // patterns and resolve to absolute paths under the skill's references/
681
+ // directory. Returns array of { skill, cookbookName, absPath }, dedup by
682
+ // absPath so two skills referencing the same cookbook only enqueue it once.
683
+ function discoverCookbookReferences(skillBodies) {
684
+ const found = [];
685
+ const seenPaths = new Set();
686
+ for (const entry of skillBodies) {
687
+ if (!entry.body || typeof entry.body !== 'string') continue;
688
+ COOKBOOK_REF_RX.lastIndex = 0;
689
+ let m;
690
+ while ((m = COOKBOOK_REF_RX.exec(entry.body)) !== null) {
691
+ const crossSkillName = m[1]; // may be undefined for same-skill refs
692
+ const cookbookName = m[2];
693
+ // Resolve to the correct skill directory: cross-skill targets the
694
+ // named other skill; otherwise stays in the source skill's own dir.
695
+ const resolvedSkill = crossSkillName || entry.skill;
696
+ const absPath = `${SKILLS_DIR}/${resolvedSkill}/references/${cookbookName}`;
697
+ if (seenPaths.has(absPath)) continue;
698
+ if (!existsSync(absPath)) continue;
699
+ seenPaths.add(absPath);
700
+ found.push({
701
+ skill: entry.skill,
702
+ referencedSkill: resolvedSkill,
703
+ cookbookName,
704
+ absPath,
705
+ crossSkill: !!crossSkillName,
706
+ });
707
+ }
708
+ }
709
+ return found;
710
+ }
711
+
712
+ // AI-11803-STEP5 — parse a cookbook into sections by `## ` and `### `
713
+ // headers. Each section = { level, title, headerLine, bodyStart, bodyEnd }
714
+ // where bodyEnd is the byte-offset of the next header (or end of file).
715
+ // Returns sections array in document order.
716
+ function parseCookbookSections(cookbookText) {
717
+ const sections = [];
718
+ const lines = cookbookText.split('\n');
719
+ // Build line offsets so we can map header line index → byte offset.
720
+ const lineOffsets = [0];
721
+ for (let i = 0; i < lines.length - 1; i++) {
722
+ lineOffsets.push(lineOffsets[i] + Buffer.byteLength(lines[i], 'utf8') + 1); // +1 for \n
723
+ }
724
+ const totalBytes = Buffer.byteLength(cookbookText, 'utf8');
725
+ // First pass: collect header positions.
726
+ const headerPositions = [];
727
+ for (let i = 0; i < lines.length; i++) {
728
+ const headerMatch = lines[i].match(/^(#{2,3})\s+(.+?)\s*$/);
729
+ if (headerMatch) {
730
+ headerPositions.push({
731
+ level: headerMatch[1].length,
732
+ title: headerMatch[2],
733
+ lineIdx: i,
734
+ byteOffset: lineOffsets[i],
735
+ });
736
+ }
737
+ }
738
+ // Second pass: build sections with bodyEnd = next header byteOffset.
739
+ for (let i = 0; i < headerPositions.length; i++) {
740
+ const h = headerPositions[i];
741
+ const next = headerPositions[i + 1];
742
+ sections.push({
743
+ level: h.level,
744
+ title: h.title,
745
+ headerByteOffset: h.byteOffset,
746
+ bodyEnd: next ? next.byteOffset : totalBytes,
747
+ });
748
+ }
749
+ return sections;
750
+ }
751
+
752
+ // AI-11803-STEP5 — score a section by counting distinct prompt keywords
753
+ // in its body text. Deterministic, observable. Returns integer.
754
+ function scoreSectionByKeywords(cookbookText, section, promptKeywords) {
755
+ if (promptKeywords.size === 0) return 0;
756
+ const sectionText = cookbookText
757
+ .slice(section.headerByteOffset, section.bodyEnd)
758
+ .toLowerCase();
759
+ let score = 0;
760
+ for (const kw of promptKeywords) {
761
+ if (sectionText.includes(kw)) score++;
762
+ }
763
+ return score;
764
+ }
765
+
766
+ // AI-11803-STEP5 — pick the top-1 section for a cookbook by keyword score.
767
+ // Returns { section, score, extracted } or null if no section meets the
768
+ // min-score threshold. extracted is the section text capped at
769
+ // MAX_BYTES_PER_COOKBOOK_SECTION with a truncation marker if needed.
770
+ function selectTopSectionForCookbook(cookbookText, sections, promptKeywords) {
771
+ let best = null;
772
+ for (const sec of sections) {
773
+ const score = scoreSectionByKeywords(cookbookText, sec, promptKeywords);
774
+ if (score < COOKBOOK_MIN_SCORE) continue;
775
+ // Tie-break: later position wins (later sections often more refined).
776
+ if (best === null || score > best.score || (score === best.score && sec.headerByteOffset > best.section.headerByteOffset)) {
777
+ best = { section: sec, score };
778
+ }
779
+ }
780
+ if (!best) return null;
781
+ let extracted = cookbookText.slice(best.section.headerByteOffset, best.section.bodyEnd).trimEnd();
782
+ if (Buffer.byteLength(extracted, 'utf8') > MAX_BYTES_PER_COOKBOOK_SECTION) {
783
+ const buf = Buffer.from(extracted, 'utf8').slice(0, MAX_BYTES_PER_COOKBOOK_SECTION);
784
+ extracted = buf.toString('utf8');
785
+ const lastBreak = Math.max(extracted.lastIndexOf('\n\n'), extracted.lastIndexOf('\n'));
786
+ if (lastBreak > MAX_BYTES_PER_COOKBOOK_SECTION * 0.6) extracted = extracted.slice(0, lastBreak);
787
+ extracted += `\n[…section truncated at ${MAX_BYTES_PER_COOKBOOK_SECTION}B; full section available in source file…]`;
788
+ }
789
+ return { section: best.section, score: best.score, extracted };
790
+ }
791
+
792
+ // AI-11803-STEP5 — orchestrate cookbook discovery + selection + injection.
793
+ // Returns { injected: [{ skill, cookbookName, absPath, sectionTitle,
794
+ // score, bytes }], totalBytes, scannedCount, skippedBelowThreshold,
795
+ // errors }. Never throws; on any file-read error, the cookbook is
796
+ // recorded as skipped with the error reason.
797
+ function autoloadCookbookSections(skillBodies, promptKeywords) {
798
+ if (/^(?:1|true|yes|on)$/i.test(String(process.env.ARIA_AUTOLOAD_COOKBOOK_OFF || ''))) {
799
+ return { injected: [], totalBytes: 0, scannedCount: 0, skippedBelowThreshold: [], errors: [], skipped: 'env-disabled' };
800
+ }
801
+ const refs = discoverCookbookReferences(skillBodies);
802
+ const injected = [];
803
+ const skippedBelowThreshold = [];
804
+ const errors = [];
805
+ let totalBytes = 0;
806
+ for (const ref of refs) {
807
+ if (totalBytes >= MAX_BYTES_COOKBOOK_TOTAL) {
808
+ skippedBelowThreshold.push({ ...ref, reason: 'total-budget-exhausted' });
809
+ continue;
810
+ }
811
+ let lst;
812
+ try { lst = lstatSync(ref.absPath); } catch (err) {
813
+ errors.push(`lstat ${ref.cookbookName}: ${err?.message || err}`);
814
+ continue;
815
+ }
816
+ if (!lst.isFile()) continue;
817
+ if (lst.size > COOKBOOK_FILE_CEILING) {
818
+ errors.push(`oversize ${ref.cookbookName}: ${lst.size}B > ${COOKBOOK_FILE_CEILING}B`);
819
+ continue;
820
+ }
821
+ let raw;
822
+ try { raw = readFileSync(ref.absPath, 'utf8'); } catch (err) {
823
+ errors.push(`read ${ref.cookbookName}: ${err?.message || err}`);
824
+ continue;
825
+ }
826
+ const sections = parseCookbookSections(raw);
827
+ if (sections.length === 0) {
828
+ skippedBelowThreshold.push({ ...ref, reason: 'no-sections-parsed' });
829
+ continue;
830
+ }
831
+ const result = selectTopSectionForCookbook(raw, sections, promptKeywords);
832
+ if (!result) {
833
+ skippedBelowThreshold.push({ ...ref, reason: `no-section-met-min-score-${COOKBOOK_MIN_SCORE}` });
834
+ continue;
835
+ }
836
+ const remainingBudget = MAX_BYTES_COOKBOOK_TOTAL - totalBytes;
837
+ const extractedBytes = Buffer.byteLength(result.extracted, 'utf8');
838
+ if (extractedBytes > remainingBudget) {
839
+ skippedBelowThreshold.push({ ...ref, reason: `total-budget-would-overflow (${extractedBytes}B > ${remainingBudget}B remaining)` });
840
+ continue;
841
+ }
842
+ injected.push({
843
+ skill: ref.skill,
844
+ cookbookName: ref.cookbookName,
845
+ absPath: ref.absPath,
846
+ sectionTitle: result.section.title,
847
+ score: result.score,
848
+ bytes: extractedBytes,
849
+ extracted: result.extracted,
850
+ });
851
+ totalBytes += extractedBytes;
852
+ }
853
+ return { injected, totalBytes, scannedCount: refs.length, skippedBelowThreshold, errors, skipped: null };
854
+ }
855
+
856
+ function buildCookbookInjection({ result, promptKeywords }) {
857
+ if (result.skipped === 'env-disabled') return '';
858
+ if (result.injected.length === 0) {
859
+ // Emit a low-information stub only when at least 1 cookbook was scanned
860
+ // but none scored above threshold — surfaces signal that scoring fired
861
+ // but selected nothing, so the agent knows cookbook context is empty
862
+ // by design, not by error.
863
+ if (result.scannedCount > 0) {
864
+ return `═══ COOKBOOK AUTOLOAD (scanned ${result.scannedCount} cookbook(s); 0 section(s) met min-score=${COOKBOOK_MIN_SCORE}; ${promptKeywords.size} prompt keywords) ═══`;
865
+ }
866
+ return '';
867
+ }
868
+ const lines = [];
869
+ lines.push(`═══ COOKBOOK AUTOLOAD (top-1 sections from ${result.injected.length} cookbook(s); deterministic keyword-overlap scoring) ═══`);
870
+ for (const entry of result.injected) {
871
+ lines.push('');
872
+ lines.push(`──── ${entry.cookbookName} [section: "${entry.sectionTitle}" — score=${entry.score}] ────`);
873
+ lines.push(entry.extracted);
874
+ }
875
+ return lines.join('\n');
876
+ }
877
+
878
+ // AI-11803-F3 (2026-05-12) — read the parent handoff JSON if present
879
+ // and within TTL. Returns the `parentAutoload` field (skill names,
880
+ // memory filenames, cookbook section pointers) or null if absent / stale
881
+ // / kill-switched / malformed.
882
+ function readParentHandoffAutoload() {
883
+ if (/^(?:1|true|yes|on)$/i.test(String(process.env.ARIA_AUTOLOAD_PARENT_HANDOFF_OFF || ''))) {
884
+ return { result: null, skipped: 'env-disabled' };
885
+ }
886
+ if (!existsSync(PARENT_HANDOFF_PATH)) {
887
+ return { result: null, skipped: 'no-handoff-file' };
888
+ }
889
+ let raw;
890
+ try { raw = readFileSync(PARENT_HANDOFF_PATH, 'utf-8'); } catch (err) {
891
+ process.stderr.write(`[aria-pre-emit-autoload:parent-handoff-read-error] ${err?.message || err}\n`);
892
+ return { result: null, skipped: `read-error:${err?.message || err}` };
893
+ }
894
+ let parsed;
895
+ try { parsed = JSON.parse(raw); } catch (err) {
896
+ process.stderr.write(`[aria-pre-emit-autoload:parent-handoff-parse-error] ${err?.message || err}\n`);
897
+ return { result: null, skipped: `parse-error:${err?.message || err}` };
898
+ }
899
+ // TTL check — if handoff older than ttlMs vs writtenAt, ignore.
900
+ const ttlMs = Number(parsed.ttlMs) || (5 * 60 * 1000);
901
+ const writtenAtMs = new Date(parsed.writtenAt || 0).getTime();
902
+ if (Number.isFinite(writtenAtMs) && writtenAtMs > 0) {
903
+ const ageMs = Date.now() - writtenAtMs;
904
+ if (ageMs > ttlMs) {
905
+ return { result: null, skipped: `stale:age=${Math.round(ageMs/1000)}s>ttl=${Math.round(ttlMs/1000)}s` };
906
+ }
907
+ }
908
+ const parentAutoload = parsed.parentAutoload;
909
+ if (!parentAutoload || typeof parentAutoload !== 'object') {
910
+ return { result: null, skipped: 'no-parentAutoload-field' };
911
+ }
912
+ return { result: parentAutoload, skipped: null, ageMs: Date.now() - writtenAtMs };
913
+ }
914
+
915
+ // Default cognition vocabulary anchors the named-lens labels the
916
+ // substrate-binding gate parses. Agents in the same session converge on
917
+ // one vocabulary so emissions stay coherent across a turn.
918
+ function chooseCognitionVocabulary() {
919
+ return ['nur', 'mizan', 'hikma', 'tafakkur', 'tadabbur', 'ilham', 'wahi', 'firasah'];
920
+ }
921
+
922
+ // Stage 5 — cross-turn substrate feedback: read recent gate-block events
923
+ // from the gate-ledger and surface them as next-turn FRAME content. This
924
+ // turns past gate-blocks into structural pressure on the next turn so the
925
+ // agent literally cannot drift the same way twice without seeing it.
926
+ function readRecentGateBlocks({ maxAgeMinutes = 30, maxEntries = 8, sessionId = null } = {}) {
927
+ const ledgerPath = `${HOME}/.claude/.aria-gate-ledger.jsonl`;
928
+ if (!existsSync(ledgerPath)) return [];
929
+ let raw;
930
+ try {
931
+ raw = readFileSync(ledgerPath, 'utf8');
932
+ } catch {
933
+ return [];
934
+ }
935
+ const lines = raw.split('\n').filter(Boolean);
936
+ const recent = lines.slice(-300); // bound the parse cost
937
+ const cutoff = Date.now() - maxAgeMinutes * 60 * 1000;
938
+ const blocks = [];
939
+ for (let i = recent.length - 1; i >= 0 && blocks.length < maxEntries; i--) {
940
+ let entry;
941
+ try { entry = JSON.parse(recent[i]); } catch { continue; }
942
+ if (!entry || typeof entry !== 'object') continue;
943
+ if (entry.decision !== 'block') continue;
944
+ const t = Date.parse(entry.ts || '');
945
+ if (!Number.isFinite(t) || t < cutoff) continue;
946
+ if (sessionId && entry.sessionId && entry.sessionId !== sessionId) continue;
947
+ blocks.push({
948
+ ts: entry.ts,
949
+ hook: entry.hook,
950
+ source: entry.source,
951
+ reason: entry.reasonShort || '(no reason)',
952
+ });
953
+ }
954
+ return blocks;
955
+ }
956
+
957
+ function buildFrameInjection({ requiredSkills, reasons, redirectOnly, cognitionVocab, skillBodies, totalBytes, recentBlocks = [] }) {
958
+ if (!requiredSkills || requiredSkills.length === 0) {
959
+ const lines = [`${HEADER_PREFIX} no doctrine-bound skills required for this prompt; standard cognition expected.`];
960
+ if (recentBlocks && recentBlocks.length > 0) {
961
+ lines.push('');
962
+ lines.push('═══ STAGE 5 — RECENT GATE BLOCKS (cross-turn substrate feedback) ═══');
963
+ lines.push(`Past ${recentBlocks.length} block(s) within last 30 minutes for this session — adjust this turn to NOT recur:`);
964
+ for (const b of recentBlocks) {
965
+ lines.push(` - [${b.hook}] ${b.source}: ${b.reason}`);
966
+ }
967
+ lines.push('Apply the lesson: same block reason in this turn means same drift pattern; address the root, not the surface.');
968
+ }
969
+ return lines.join('\n');
970
+ }
971
+ const lines = [];
972
+ lines.push(`${HEADER_PREFIX} FRAME — required skills loaded for this turn (content below should shape your work BEFORE you draft).`);
973
+ lines.push('');
974
+ lines.push(`Required skills (${requiredSkills.length}): ${requiredSkills.join(', ')}`);
975
+ if (reasons.length > 0) {
976
+ lines.push('Why these skills:');
977
+ for (const reason of reasons) lines.push(` - ${reason}`);
978
+ }
979
+ lines.push('');
980
+ lines.push(`Total injected: ${totalBytes}B across ${skillBodies.filter(s => s.bytes > 0).length} skill(s).`);
981
+ lines.push('');
982
+ lines.push('═══ SKILL BODIES (operative content — apply, do not narrate) ═══');
983
+ lines.push('');
984
+ for (const entry of skillBodies) {
985
+ if (entry.bytes === 0) {
986
+ if (entry.reason !== 'missing' && entry.reason !== 'ok') {
987
+ lines.push(`──── ${entry.skill} ──── [SKIPPED: ${entry.reason}]`);
988
+ lines.push('');
989
+ }
990
+ continue;
991
+ }
992
+ lines.push(`──── ${entry.skill}${entry.truncated ? ' (truncated)' : ''} ────`);
993
+ lines.push(entry.body);
994
+ lines.push('');
995
+ }
996
+ lines.push('═══ END SKILL BODIES ═══');
997
+ lines.push('');
998
+ lines.push('═══ DRIVING RULES (apply during work) ═══');
999
+ lines.push('- Each skill above carries operative rules. Apply them as you draft, edit, and tool-call.');
1000
+ lines.push('- Do NOT emit lens blocks as ceremony at end-of-turn. The lens IS the thinking that already happened.');
1001
+ lines.push('- If a skill names a doctrine memory, treat it as an active constraint, not a citation.');
1002
+ lines.push('- If two skills conflict, the more specific one (e.g., aria-harness-deploy) outranks the general (e.g., aria-forge-guardrails).');
1003
+ lines.push('');
1004
+ lines.push('═══ COGNITION VOCABULARY ═══');
1005
+ lines.push(`Use these named lenses for substantive emissions: ${cognitionVocab.join(', ')}`);
1006
+ lines.push('Per substantive action emit:');
1007
+ lines.push(' <cognition> with all 8 named lenses (≥20 chars per lens, anchored to substrate)');
1008
+ lines.push(' <expected> with measurable predicate');
1009
+ lines.push(' <applied_cognition> with decision_delta + dominant_domain + binds_to + expected_predicate + artifact_change');
1010
+ lines.push('');
1011
+ lines.push('═══ POST-QA CRITERIA (verify before completion claim) ═══');
1012
+ lines.push('- Did at least one substrate change as a result of cognition firing?');
1013
+ lines.push('- Is every readiness/completion word ("done", "fixed", "shipped", "verified") backed by tool-output evidence?');
1014
+ lines.push('- Does the closing prose match output discipline (no raw IPs/SHAs/file-paths in chat; semantic reframing applied)?');
1015
+ lines.push('- Are unresolved discoveries either fixed-now or tracked-as-task before turn end?');
1016
+ if (redirectOnly) {
1017
+ lines.push('');
1018
+ lines.push('NOTE: redirectOnly mode — gate guides not hard-blocks. Treat guidance as quality bar, not skip-license.');
1019
+ }
1020
+ if (recentBlocks && recentBlocks.length > 0) {
1021
+ lines.push('');
1022
+ lines.push('═══ STAGE 5 — RECENT GATE BLOCKS (cross-turn substrate feedback) ═══');
1023
+ lines.push(`Past ${recentBlocks.length} block(s) within last 30 minutes for this session — adjust this turn to NOT recur:`);
1024
+ for (const b of recentBlocks) {
1025
+ lines.push(` - [${b.hook}] ${b.source}: ${b.reason}`);
1026
+ }
1027
+ lines.push('Apply the lesson: the same block reason in this turn means the same drift pattern; address the root, not the surface.');
1028
+ }
1029
+ return lines.join('\n');
1030
+ }
1031
+
1032
+ // Baseline skill set that loads unconditionally for any non-empty prompt.
1033
+ // Per Hamza directive 2026-05-12: the autoloader is NOT cheap — any 1%
1034
+ // chance a skill helps must fire it; no non-trivial prompt continues
1035
+ // without at least one skill loaded. aria-cognition-autofire is the
1036
+ // foundational substrate trigger that every turn deserves in context.
1037
+ const BASELINE_SKILLS = ['aria-cognition-autofire'];
1038
+
1039
+ // AI-11803-F5 (2026-05-12): active-workflow skill allow-list. These
1040
+ // skills have explicit "Required Workflow" / "Apply the pipeline" /
1041
+ // "TRIGGER for cognitive turn" imperatives in their bodies. Loading
1042
+ // them as context is NOT the same as running their workflow — the LLM
1043
+ // MUST invoke them via the Skill tool when their body is loaded.
1044
+ // See feedback_autoload_does_not_invoke_skills.md for the full Recovery
1045
+ // Contract (classification A/B/C/D, 5-per-turn cap, parent composition).
1046
+ // Maintenance protocol: review new skills' frontmatter for active-shape
1047
+ // signals; add to this list. False-positive operator-frustration → move
1048
+ // back to passive-substrate (default).
1049
+ // QA-FIX-1 (2026-05-12, qiyas Tadabbur EXCAVATE): allow-list expanded from
1050
+ // 5 to 8 after qiyas+tadabbur QA pass found 3 missing active-workflow
1051
+ // skills. ghazali-8lens has explicit Required Workflow + 8-lens validation
1052
+ // pipeline. aria-decision-mizan is active refusal-shape (refuses to choose
1053
+ // for owner, surfaces both options — active not passive). tafakkur has
1054
+ // explicit 5-lens contemplation workflow. Cap is per-TURN INVOCATION count
1055
+ // (5), not list size; list can grow as more active skills are identified.
1056
+ const ACTIVE_WORKFLOW_SKILLS = new Set([
1057
+ 'tadabbur',
1058
+ 'qiyas-analogy',
1059
+ 'aria-cognition-batch',
1060
+ 'mizan',
1061
+ 'aria-forge-guardrails',
1062
+ 'ghazali-8lens',
1063
+ 'aria-decision-mizan',
1064
+ 'tafakkur',
1065
+ ]);
1066
+ const INVOCATION_CAP_PER_TURN = 5;
1067
+
1068
+ function main() {
1069
+ const event = readEvent();
1070
+ const prompt = String(
1071
+ event.user_prompt ??
1072
+ event.userPrompt ??
1073
+ event.prompt ??
1074
+ event.text ??
1075
+ event.message ??
1076
+ ''
1077
+ ).trim();
1078
+
1079
+ // ARIA_AUTOLOAD_DISABLE is the proper kill switch for this hook
1080
+ // specifically. Use only when debugging the autoload itself. The
1081
+ // gates-off marker is for blocking gates, NOT for disabling content
1082
+ // enrichment — disabling enrichment is exactly what made cognition
1083
+ // ceremonial in the first place.
1084
+ if (/^(?:1|true|yes|on)$/i.test(String(process.env.ARIA_AUTOLOAD_DISABLE || ''))) {
1085
+ appendGateLedger({ hook: 'pre-emit-autoload', event: HOOK_EVENT_NAME, decision: 'bypass', source: 'pre-emit/autoload-disabled-env', reasonShort: 'ARIA_AUTOLOAD_DISABLE=1', sessionId: event.session_id });
1086
+ emitNoop('ARIA_AUTOLOAD_DISABLE=1');
1087
+ }
1088
+
1089
+ if (!prompt) {
1090
+ appendGateLedger({ hook: 'pre-emit-autoload', event: HOOK_EVENT_NAME, decision: 'allow', source: 'pre-emit/empty-prompt', sessionId: event.session_id });
1091
+ emitNoop('empty user prompt');
1092
+ }
1093
+
1094
+ let classified;
1095
+ try {
1096
+ classified = classifyRequiredSkills({
1097
+ text: prompt,
1098
+ isOutputCloseout: false,
1099
+ });
1100
+ } catch (err) {
1101
+ // Fail-allow on classifier crash. Record the error for postmortem.
1102
+ appendGateLedger({
1103
+ hook: 'pre-emit-autoload',
1104
+ event: HOOK_EVENT_NAME,
1105
+ decision: 'allow',
1106
+ source: 'pre-emit/classifier-error',
1107
+ reasonShort: err instanceof Error ? err.message : String(err),
1108
+ sessionId: event.session_id,
1109
+ });
1110
+ emitNoop(`classifier error: ${err instanceof Error ? err.message : String(err)}`);
1111
+ }
1112
+
1113
+ // Abundance doctrine — two-component substrate provisioning:
1114
+ // (1) BASELINE_SKILLS unconditionally for any non-empty prompt
1115
+ // (2) keyword classifier results (already in classified.requiredSkills)
1116
+ //
1117
+ // No LLM-call semantic backstop. Per Hamza directive 2026-05-12:
1118
+ // adding an LLM call to teach the LLM which skills to use is
1119
+ // regressive — it outsources meta-cognition the model is supposed
1120
+ // to perform from the substrate already loaded. The keyword
1121
+ // classifier picks obvious matches; the baseline ensures non-empty
1122
+ // substrate; the model itself is accountable for applying the
1123
+ // loaded skills correctly (forced by the anchor-verification gate
1124
+ // and the cognition vocabulary requirements downstream).
1125
+ const initialSkillSet = new Set(classified.requiredSkills || []);
1126
+ for (const s of BASELINE_SKILLS) {
1127
+ if (existsSync(`${SKILLS_DIR}/${s}/SKILL.md`)) initialSkillSet.add(s);
1128
+ }
1129
+
1130
+ // AI-11803-F3: parent-handoff substrate inheritance. If this autoload
1131
+ // is firing inside a sub-agent session, layer the parent's pinned
1132
+ // skill names into the load set BEFORE cascade expansion. Sub-agent's
1133
+ // own classifier output is preserved (already in initialSkillSet);
1134
+ // parent pins are additive — sub-agent sees its own narrow-prompt
1135
+ // skills + the parent's broader doctrine context.
1136
+ const parentHandoffRead = readParentHandoffAutoload();
1137
+ const parentHandoff = parentHandoffRead.result;
1138
+ if (parentHandoff && Array.isArray(parentHandoff.requiredSkills)) {
1139
+ let inheritedCount = 0;
1140
+ for (const s of parentHandoff.requiredSkills) {
1141
+ if (typeof s !== 'string') continue;
1142
+ if (existsSync(`${SKILLS_DIR}/${s}/SKILL.md`) && !initialSkillSet.has(s)) {
1143
+ initialSkillSet.add(s);
1144
+ inheritedCount++;
1145
+ }
1146
+ }
1147
+ process.stderr.write(`[aria-pre-emit-autoload:parent-handoff-inherited] skills=${inheritedCount} memories=${(parentHandoff.memoryFilenames||[]).length} cookbooks=${(parentHandoff.cookbookSelections||[]).length} ageMs=${parentHandoffRead.ageMs}\n`);
1148
+ }
1149
+
1150
+ const cognitionVocab = chooseCognitionVocabulary();
1151
+
1152
+ // AI-11803-LOOP1 (2026-05-12) — cascade expansion replaces the prior
1153
+ // single-pass body-injection loop. The cascade reads each skill body,
1154
+ // parses its Load First / Mode Selection / Load Order sections, and
1155
+ // recursively enqueues the named skills (existence-filtered, cycle-safe,
1156
+ // budget-capped). Final requiredSkills reflects the FULL loaded set so
1157
+ // sidecar + ledger downstream consumers see what actually ran in context.
1158
+ const cascade = expandSkillCascade([...initialSkillSet]);
1159
+ classified.requiredSkills = [...cascade.order].sort();
1160
+ const skillBodies = cascade.order.map((skill) => ({ skill, ...cascade.loadedBodies.get(skill) }));
1161
+ const totalBytes = cascade.totalBytes;
1162
+ const cascadeDepth = cascade.cascadeDepth;
1163
+ const depthInjected = cascade.depthInjected;
1164
+ const depthAttempted = cascade.depthAttempted;
1165
+ const cascadedSkills = cascade.order.filter((s) => !initialSkillSet.has(s));
1166
+
1167
+ // AI-11803-LOOP2: doctrine-trigger pre-emit scan. Matches the prompt
1168
+ // against the 79-trigger map. Computed here (before sidecar+ledger writes)
1169
+ // so its results land in the meta + sidecar telemetry too.
1170
+ const doctrineScan = scanDoctrineTriggers(prompt);
1171
+
1172
+ // AI-11803-F5 (2026-05-12) — compute invocationRequired set: which of
1173
+ // the loaded skills this turn are active-workflow (Skill tool MUST be
1174
+ // called) vs passive-substrate (body-as-context is sufficient). Capped
1175
+ // at INVOCATION_CAP_PER_TURN to prevent operator-overhead from too many
1176
+ // sequential invocations. The list is surfaced to the LLM via a
1177
+ // dedicated additionalContext section AND persisted to sidecar so the
1178
+ // future F5.c stop-gate can verify the named skills were actually
1179
+ // invoked before turn-close.
1180
+ //
1181
+ // QA-FIX-2 (2026-05-12): source the candidate skills from cascade.order
1182
+ // (the FINAL loaded set after cascade expansion) instead of
1183
+ // classified.requiredSkills (initial classifier output). Cascade can
1184
+ // pull active-workflow skills depth-N (e.g. aria-cognition-batch in
1185
+ // initial set loads tadabbur via Load First section); those depth-N
1186
+ // active skills must also appear in invocationRequired or the contract
1187
+ // misses them.
1188
+ //
1189
+ // QA-FIX-3 (2026-05-12): include parent-handoff inherited active skills
1190
+ // so sub-agents continue to honor the parent's invocation requirements
1191
+ // even when the sub-agent's own classifier didn't trigger them.
1192
+ const invocationRequiredSet = new Set();
1193
+ for (const skill of cascade.order) {
1194
+ if (invocationRequiredSet.size >= INVOCATION_CAP_PER_TURN) break;
1195
+ if (ACTIVE_WORKFLOW_SKILLS.has(skill)) invocationRequiredSet.add(skill);
1196
+ }
1197
+ if (parentHandoff && Array.isArray(parentHandoff.invocationRequired)) {
1198
+ for (const skill of parentHandoff.invocationRequired) {
1199
+ if (invocationRequiredSet.size >= INVOCATION_CAP_PER_TURN) break;
1200
+ if (typeof skill === 'string' && ACTIVE_WORKFLOW_SKILLS.has(skill)) {
1201
+ invocationRequiredSet.add(skill);
1202
+ }
1203
+ }
1204
+ }
1205
+ const invocationRequired = [...invocationRequiredSet];
1206
+
1207
+ // AI-11803-STEP4 (2026-05-12) — MEMORY.md auto-load + top-N body injection.
1208
+ // Dedup set: memories already injected via trigger-map this turn must not
1209
+ // double-inject as top-N bodies (would waste budget + repeat content).
1210
+ // QA-FIX-2 (2026-05-12): kill switch parity with cascade + trigger-map.
1211
+ // ARIA_AUTOLOAD_MEMORY_OFF=1 disables memory autoload while leaving the
1212
+ // other primitives running, for isolated debugging of this primitive.
1213
+ const memoryAutoloadDisabled = /^(?:1|true|yes|on)$/i.test(String(process.env.ARIA_AUTOLOAD_MEMORY_OFF || ''));
1214
+ const triggerMatchedMemories = new Set(doctrineScan.matches.map((m) => m.memory));
1215
+ const memoryIndexResult = memoryAutoloadDisabled
1216
+ ? { body: '', bytes: 0, totalLines: 0, droppedLines: 0, reason: 'env-disabled' }
1217
+ : readMemoryIndex();
1218
+ const memoryBodyResult = memoryAutoloadDisabled
1219
+ ? { injected: [], totalBytes: 0, dedupedFilenames: [], scoredCount: 0, errors: [] }
1220
+ : selectTopNMemoryBodies(triggerMatchedMemories);
1221
+
1222
+ // AI-11803-STEP5 (2026-05-12) — cookbook auto-pull from loaded skill bodies.
1223
+ // Scans skillBodies for `references/<name>.md` patterns, parses each
1224
+ // cookbook's sections, scores by prompt-keyword overlap, injects top-1
1225
+ // section per cookbook above min-score threshold. Same-turn dedup via
1226
+ // Set of absPath. Loop-safe: depth cap = 1 (cookbooks don't transitively
1227
+ // pull other cookbooks). Kill switch: ARIA_AUTOLOAD_COOKBOOK_OFF=1.
1228
+ const promptKeywords = extractPromptKeywords(prompt);
1229
+ const cookbookResult = autoloadCookbookSections(skillBodies, promptKeywords);
1230
+
1231
+ const sidecar = {
1232
+ schema: 'aria-current-turn-context.v2',
1233
+ ts: new Date().toISOString(),
1234
+ sessionId: event.session_id ?? null,
1235
+ // AI-11803-F3: chain-depth marker — if this autoload inherited parent
1236
+ // handoff substrate, downstream Agent dispatch hook reads this and
1237
+ // SKIPS propagating to grandchild (chain depth cap = 1).
1238
+ parentHandoffChainDepth: parentHandoff ? 1 : 0,
1239
+ parentHandoffSkipped: parentHandoffRead.skipped,
1240
+ // AI-11803-F5: active-workflow skills that MUST be invoked via the
1241
+ // Skill tool this turn. Doctrine: feedback_autoload_does_not_invoke_skills.md.
1242
+ // The F5.c stop-gate (future step) reads this and verifies invocations
1243
+ // before turn-close.
1244
+ invocationRequired,
1245
+ promptHash: createHash('sha256').update(prompt).digest('hex').slice(0, 16),
1246
+ requiredSkills: classified.requiredSkills,
1247
+ redirectOnly: classified.redirectOnly === true,
1248
+ reasons: classified.reasons,
1249
+ cognitionVocabulary: cognitionVocab,
1250
+ injection: {
1251
+ totalBytes,
1252
+ perSkill: skillBodies.map(s => ({
1253
+ skill: s.skill,
1254
+ bytes: s.bytes,
1255
+ fullBytes: s.fullBytes,
1256
+ truncated: !!s.truncated,
1257
+ redacted: !!s.redacted,
1258
+ reason: s.reason,
1259
+ // First 600 chars of injected body so post-phase can verify what
1260
+ // was actually visible to the agent.
1261
+ excerpt: typeof s.body === 'string' ? s.body.slice(0, 600) : '',
1262
+ })),
1263
+ },
1264
+ memoryAutoload: {
1265
+ indexBytes: memoryIndexResult.bytes,
1266
+ indexReason: memoryIndexResult.reason,
1267
+ indexDroppedLines: memoryIndexResult.droppedLines,
1268
+ bodiesBytes: memoryBodyResult.totalBytes,
1269
+ bodiesInjected: memoryBodyResult.injected.map((e) => ({
1270
+ filename: e.filename, tier: e.tier, score: e.score, bytes: e.bytes,
1271
+ })),
1272
+ bodiesDeduped: memoryBodyResult.dedupedFilenames,
1273
+ scoredCount: memoryBodyResult.scoredCount,
1274
+ },
1275
+ cookbookAutoload: {
1276
+ scannedCount: cookbookResult.scannedCount,
1277
+ keywordCount: promptKeywords.size,
1278
+ totalBytes: cookbookResult.totalBytes,
1279
+ injected: cookbookResult.injected.map((e) => ({
1280
+ skill: e.skill,
1281
+ cookbookName: e.cookbookName,
1282
+ sectionTitle: e.sectionTitle,
1283
+ score: e.score,
1284
+ bytes: e.bytes,
1285
+ })),
1286
+ skippedBelowThreshold: cookbookResult.skippedBelowThreshold,
1287
+ skipped: cookbookResult.skipped,
1288
+ errors: cookbookResult.errors,
1289
+ },
1290
+ };
1291
+ writeSidecar(sidecar);
1292
+
1293
+ appendGateLedger({
1294
+ hook: 'pre-emit-autoload',
1295
+ event: HOOK_EVENT_NAME,
1296
+ decision: 'allow',
1297
+ source: 'pre-emit/autoload',
1298
+ reasonShort: classified.requiredSkills.length > 0
1299
+ ? `injected=${totalBytes}B skills=${classified.requiredSkills.join(',')}`
1300
+ : 'no doctrine-bound skills required',
1301
+ meta: {
1302
+ requiredSkills: classified.requiredSkills,
1303
+ redirectOnly: classified.redirectOnly === true,
1304
+ promptLen: prompt.length,
1305
+ injectedBytes: totalBytes,
1306
+ injectedSkills: skillBodies.filter(s => s.bytes > 0).map(s => s.skill),
1307
+ skippedSkills: skillBodies.filter(s => s.bytes === 0).map(s => ({ skill: s.skill, reason: s.reason })),
1308
+ cascadeDepth,
1309
+ depthInjected,
1310
+ depthAttempted,
1311
+ cascadedSkills,
1312
+ doctrineTriggerMatchCount: doctrineScan.matches.length,
1313
+ doctrineTriggersMatched: doctrineScan.matches.map((m) => m.trigger),
1314
+ doctrineTriggerSkipped: doctrineScan.skipped,
1315
+ memoryIndexBytes: memoryIndexResult.bytes,
1316
+ memoryIndexReason: memoryIndexResult.reason,
1317
+ memoryIndexDroppedLines: memoryIndexResult.droppedLines,
1318
+ memoryBodiesInjected: memoryBodyResult.injected.length,
1319
+ memoryBodiesInjectedBytes: memoryBodyResult.totalBytes,
1320
+ memoryBodiesScoredCount: memoryBodyResult.scoredCount,
1321
+ memoryBodiesDeduped: memoryBodyResult.dedupedFilenames,
1322
+ memoryBodiesSelected: memoryBodyResult.injected.map((e) => ({ filename: e.filename, tier: e.tier, bytes: e.bytes })),
1323
+ cookbookScannedCount: cookbookResult.scannedCount,
1324
+ cookbookInjectedCount: cookbookResult.injected.length,
1325
+ cookbookInjectedBytes: cookbookResult.totalBytes,
1326
+ cookbookKeywordCount: promptKeywords.size,
1327
+ cookbookSkippedReasons: cookbookResult.skippedBelowThreshold.map((s) => `${s.cookbookName}:${s.reason}`),
1328
+ cookbookSkipped: cookbookResult.skipped,
1329
+ invocationRequired,
1330
+ invocationRequiredCount: invocationRequired.length,
1331
+ },
1332
+ sessionId: event.session_id,
1333
+ });
1334
+
1335
+ // Stage 5: pull recent gate-blocks for this session so the agent sees
1336
+ // them as pre-flight FRAME context and cannot drift the same way twice.
1337
+ const recentBlocks = readRecentGateBlocks({ sessionId: event.session_id });
1338
+
1339
+ const doctrineInjection = buildDoctrineTriggerInjection(doctrineScan.matches);
1340
+
1341
+ const memoryInjection = buildMemoryAutoloadInjection({
1342
+ indexResult: memoryIndexResult,
1343
+ bodyResult: memoryBodyResult,
1344
+ });
1345
+
1346
+ const frameInjection = buildFrameInjection({
1347
+ requiredSkills: classified.requiredSkills,
1348
+ reasons: classified.reasons,
1349
+ redirectOnly: classified.redirectOnly === true,
1350
+ cognitionVocab,
1351
+ skillBodies,
1352
+ totalBytes,
1353
+ recentBlocks,
1354
+ });
1355
+
1356
+ const cookbookInjection = buildCookbookInjection({
1357
+ result: cookbookResult,
1358
+ promptKeywords,
1359
+ });
1360
+
1361
+ // AI-11803-F5: INVOCATION REQUIRED section — make it explicit that
1362
+ // active-workflow skills loaded as bodies still need Skill tool
1363
+ // invocation. Doctrine drift if skipped (see
1364
+ // feedback_autoload_does_not_invoke_skills.md).
1365
+ let invocationInjection = '';
1366
+ if (invocationRequired.length > 0) {
1367
+ const lines = [];
1368
+ lines.push('═══ INVOCATION REQUIRED (active-workflow skills — body in context is NOT enough) ═══');
1369
+ lines.push(`The following loaded skills are ACTIVE-WORKFLOW. You MUST invoke each via the Skill tool BEFORE drafting substantive work this turn. Reading the body in context does NOT run the workflow.`);
1370
+ lines.push('');
1371
+ for (const skill of invocationRequired) {
1372
+ lines.push(` • ${skill}`);
1373
+ }
1374
+ lines.push('');
1375
+ lines.push('Doctrine: feedback_autoload_does_not_invoke_skills.md');
1376
+ lines.push('Recovery Contract — every loaded active-workflow skill closes the turn classified as:');
1377
+ lines.push(' A. INVOKED — Skill tool call visible in transcript');
1378
+ lines.push(' B. COMPOSED-VIA-PARENT — parent skill (e.g., aria-cognition-batch) invoked, child is a composition member');
1379
+ lines.push(' C. SCOPE-EXEMPT — prompt is read-only inspection of the skill body, not asking the workflow to run');
1380
+ lines.push(' D. CAP-DEFERRED — > 5 active-workflow skills loaded; deferred to follow-up');
1381
+ lines.push(`No other classifications permitted. "I considered it" / "it's loaded" / "substrate has it" = the antipattern.`);
1382
+ invocationInjection = lines.join('\n');
1383
+ }
1384
+
1385
+ const parts = [frameInjection];
1386
+ if (invocationInjection) parts.push(invocationInjection);
1387
+ if (doctrineInjection) parts.push(doctrineInjection);
1388
+ if (memoryInjection) parts.push(memoryInjection);
1389
+ if (cookbookInjection) parts.push(cookbookInjection);
1390
+ const additionalContext = parts.join('\n\n');
1391
+
1392
+ emit({
1393
+ hookSpecificOutput: {
1394
+ hookEventName: HOOK_EVENT_NAME,
1395
+ additionalContext,
1396
+ },
1397
+ });
1398
+ }
1399
+
1400
+ main();