@aria_asi/cli 0.2.25 → 0.2.29

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 (249) hide show
  1. package/CLIENT-ONBOARDING.md +282 -0
  2. package/bin/aria.js +1140 -14
  3. package/dist/aria-connector/src/auth-commands.d.ts +1 -0
  4. package/dist/aria-connector/src/auth-commands.d.ts.map +1 -1
  5. package/dist/aria-connector/src/auth-commands.js +89 -41
  6. package/dist/aria-connector/src/auth-commands.js.map +1 -1
  7. package/dist/aria-connector/src/chat.d.ts +3 -0
  8. package/dist/aria-connector/src/chat.d.ts.map +1 -1
  9. package/dist/aria-connector/src/chat.js +146 -8
  10. package/dist/aria-connector/src/chat.js.map +1 -1
  11. package/dist/aria-connector/src/codebase-scanner.d.ts +2 -2
  12. package/dist/aria-connector/src/codebase-scanner.d.ts.map +1 -1
  13. package/dist/aria-connector/src/codebase-scanner.js +1 -1
  14. package/dist/aria-connector/src/codebase-scanner.js.map +1 -1
  15. package/dist/aria-connector/src/config.d.ts +12 -0
  16. package/dist/aria-connector/src/config.d.ts.map +1 -1
  17. package/dist/aria-connector/src/config.js +2 -0
  18. package/dist/aria-connector/src/config.js.map +1 -1
  19. package/dist/aria-connector/src/connectors/claude-code.d.ts.map +1 -1
  20. package/dist/aria-connector/src/connectors/claude-code.js +111 -21
  21. package/dist/aria-connector/src/connectors/claude-code.js.map +1 -1
  22. package/dist/aria-connector/src/connectors/codebase-awareness.d.ts +37 -0
  23. package/dist/aria-connector/src/connectors/codebase-awareness.d.ts.map +1 -0
  24. package/dist/aria-connector/src/connectors/codebase-awareness.js +335 -0
  25. package/dist/aria-connector/src/connectors/codebase-awareness.js.map +1 -0
  26. package/dist/aria-connector/src/connectors/codex.d.ts +3 -0
  27. package/dist/aria-connector/src/connectors/codex.d.ts.map +1 -0
  28. package/dist/aria-connector/src/connectors/codex.js +248 -0
  29. package/dist/aria-connector/src/connectors/codex.js.map +1 -0
  30. package/dist/aria-connector/src/connectors/cognitive-skills.d.ts +2 -0
  31. package/dist/aria-connector/src/connectors/cognitive-skills.d.ts.map +1 -0
  32. package/dist/aria-connector/src/connectors/cognitive-skills.js +47 -0
  33. package/dist/aria-connector/src/connectors/cognitive-skills.js.map +1 -0
  34. package/dist/aria-connector/src/connectors/opencode.d.ts.map +1 -1
  35. package/dist/aria-connector/src/connectors/opencode.js +90 -4
  36. package/dist/aria-connector/src/connectors/opencode.js.map +1 -1
  37. package/dist/aria-connector/src/connectors/repo-git-hooks.d.ts +3 -0
  38. package/dist/aria-connector/src/connectors/repo-git-hooks.d.ts.map +1 -0
  39. package/dist/aria-connector/src/connectors/repo-git-hooks.js +87 -0
  40. package/dist/aria-connector/src/connectors/repo-git-hooks.js.map +1 -0
  41. package/dist/aria-connector/src/connectors/repo-guard.d.ts +19 -0
  42. package/dist/aria-connector/src/connectors/repo-guard.d.ts.map +1 -0
  43. package/dist/aria-connector/src/connectors/repo-guard.js +509 -0
  44. package/dist/aria-connector/src/connectors/repo-guard.js.map +1 -0
  45. package/dist/aria-connector/src/connectors/runtime.d.ts +2 -0
  46. package/dist/aria-connector/src/connectors/runtime.d.ts.map +1 -0
  47. package/dist/aria-connector/src/connectors/runtime.js +330 -0
  48. package/dist/aria-connector/src/connectors/runtime.js.map +1 -0
  49. package/dist/aria-connector/src/connectors/shell.d.ts.map +1 -1
  50. package/dist/aria-connector/src/connectors/shell.js +78 -13
  51. package/dist/aria-connector/src/connectors/shell.js.map +1 -1
  52. package/dist/aria-connector/src/connectors/syncd.d.ts +27 -0
  53. package/dist/aria-connector/src/connectors/syncd.d.ts.map +1 -0
  54. package/dist/aria-connector/src/connectors/syncd.js +405 -0
  55. package/dist/aria-connector/src/connectors/syncd.js.map +1 -0
  56. package/dist/aria-connector/src/decisions.d.ts +207 -0
  57. package/dist/aria-connector/src/decisions.d.ts.map +1 -0
  58. package/dist/aria-connector/src/decisions.js +291 -0
  59. package/dist/aria-connector/src/decisions.js.map +1 -0
  60. package/dist/aria-connector/src/garden-control-plane.d.ts.map +1 -1
  61. package/dist/aria-connector/src/garden-control-plane.js +74 -17
  62. package/dist/aria-connector/src/garden-control-plane.js.map +1 -1
  63. package/dist/aria-connector/src/github-connect.d.ts +18 -0
  64. package/dist/aria-connector/src/github-connect.d.ts.map +1 -0
  65. package/dist/aria-connector/src/github-connect.js +117 -0
  66. package/dist/aria-connector/src/github-connect.js.map +1 -0
  67. package/dist/aria-connector/src/harness-client.d.ts +15 -0
  68. package/dist/aria-connector/src/harness-client.d.ts.map +1 -1
  69. package/dist/aria-connector/src/harness-client.js +106 -3
  70. package/dist/aria-connector/src/harness-client.js.map +1 -1
  71. package/dist/aria-connector/src/hive-client.d.ts +30 -0
  72. package/dist/aria-connector/src/hive-client.d.ts.map +1 -1
  73. package/dist/aria-connector/src/hive-client.js +124 -5
  74. package/dist/aria-connector/src/hive-client.js.map +1 -1
  75. package/dist/aria-connector/src/index.d.ts +13 -2
  76. package/dist/aria-connector/src/index.d.ts.map +1 -1
  77. package/dist/aria-connector/src/index.js +10 -1
  78. package/dist/aria-connector/src/index.js.map +1 -1
  79. package/dist/aria-connector/src/lib/aristotle-noor-wire.d.ts +102 -0
  80. package/dist/aria-connector/src/lib/aristotle-noor-wire.d.ts.map +1 -0
  81. package/dist/aria-connector/src/lib/aristotle-noor-wire.js +231 -0
  82. package/dist/aria-connector/src/lib/aristotle-noor-wire.js.map +1 -0
  83. package/dist/aria-connector/src/providers/types.d.ts +5 -0
  84. package/dist/aria-connector/src/providers/types.d.ts.map +1 -1
  85. package/dist/aria-connector/src/runtime-proof.d.ts +45 -0
  86. package/dist/aria-connector/src/runtime-proof.d.ts.map +1 -0
  87. package/dist/aria-connector/src/runtime-proof.js +340 -0
  88. package/dist/aria-connector/src/runtime-proof.js.map +1 -0
  89. package/dist/aria-connector/src/setup-wizard.d.ts.map +1 -1
  90. package/dist/aria-connector/src/setup-wizard.js +34 -2
  91. package/dist/aria-connector/src/setup-wizard.js.map +1 -1
  92. package/dist/assets/hooks/aria-agent-handoff.mjs +224 -0
  93. package/dist/assets/hooks/aria-agent-ledger-merge.mjs +164 -0
  94. package/dist/assets/hooks/aria-architect-fallback.mjs +267 -0
  95. package/dist/assets/hooks/aria-cognition-substrate-binding.mjs +676 -0
  96. package/dist/assets/hooks/aria-discovery-record.mjs +101 -0
  97. package/dist/assets/hooks/aria-harness-via-sdk.mjs +412 -0
  98. package/dist/assets/hooks/aria-import-resolution-gate.mjs +330 -0
  99. package/dist/assets/hooks/aria-outcome-record.mjs +84 -0
  100. package/dist/assets/hooks/aria-pre-emit-dryrun.mjs +294 -0
  101. package/dist/assets/hooks/aria-pre-text-gate.mjs +112 -0
  102. package/dist/assets/hooks/aria-pre-tool-gate.mjs +2133 -0
  103. package/dist/assets/hooks/aria-preprompt-consult.mjs +438 -0
  104. package/dist/assets/hooks/aria-preturn-memory-gate.mjs +570 -0
  105. package/dist/assets/hooks/aria-repo-doctrine-gate.mjs +397 -0
  106. package/dist/assets/hooks/aria-stop-gate.mjs +1551 -0
  107. package/dist/assets/hooks/aria-trigger-autolearn.mjs +229 -0
  108. package/dist/assets/hooks/aria-userprompt-abandon-detect.mjs +192 -0
  109. package/dist/assets/hooks/doctrine_trigger_map.json +479 -0
  110. package/dist/assets/hooks/lib/canonical-lenses.mjs +64 -0
  111. package/dist/assets/hooks/lib/gate-audit.mjs +43 -0
  112. package/dist/assets/hooks/test-aria-preturn-memory-gate.mjs +245 -0
  113. package/dist/assets/hooks/test-tier-lens-labeling.mjs +399 -0
  114. package/dist/assets/opencode-plugins/harness-context/index.js +60 -0
  115. package/dist/assets/opencode-plugins/harness-context/inject-context.mjs +179 -0
  116. package/dist/assets/opencode-plugins/harness-context/package.json +9 -0
  117. package/dist/assets/opencode-plugins/harness-gate/index.js +248 -0
  118. package/dist/assets/opencode-plugins/harness-outcome/index.js +129 -0
  119. package/dist/assets/opencode-plugins/harness-role/index.js +77 -0
  120. package/dist/assets/opencode-plugins/harness-role/package.json +9 -0
  121. package/dist/assets/opencode-plugins/harness-stop/index.js +241 -0
  122. package/dist/runtime/discipline/CLAUDE.md +339 -0
  123. package/dist/runtime/discipline/skills/aria-cognition/aria-essence/SKILL.md +63 -0
  124. package/dist/runtime/discipline/skills/aria-cognition/aria-essence/references/domain-matrix.md +80 -0
  125. package/dist/runtime/discipline/skills/aria-cognition/aria-essence/references/evolution-loop.md +30 -0
  126. package/dist/runtime/discipline/skills/aria-cognition/aria-essence/references/readable-cognition.md +27 -0
  127. package/dist/runtime/discipline/skills/aria-cognition/aria-forge-guardrails/SKILL.md +35 -0
  128. package/dist/runtime/discipline/skills/aria-cognition/aria-forge-guardrails/references/checklist.md +31 -0
  129. package/dist/runtime/discipline/skills/aria-cognition/aria-repo-doctrine/SKILL.md +39 -0
  130. package/dist/runtime/discipline/skills/aria-cognition/forge-quality-rules/SKILL.md +43 -0
  131. package/dist/runtime/discipline/skills/aria-cognition/ghazali-8lens/SKILL.md +38 -0
  132. package/dist/runtime/discipline/skills/aria-cognition/istiqra-induction/SKILL.md +26 -0
  133. package/dist/runtime/discipline/skills/aria-cognition/ladunni-22/SKILL.md +35 -0
  134. package/dist/runtime/discipline/skills/aria-cognition/mizan/SKILL.md +72 -0
  135. package/dist/runtime/discipline/skills/aria-cognition/nadia/SKILL.md +38 -0
  136. package/dist/runtime/discipline/skills/aria-cognition/nadia-psi/SKILL.md +38 -0
  137. package/dist/runtime/discipline/skills/aria-cognition/predictor/SKILL.md +25 -0
  138. package/dist/runtime/discipline/skills/aria-cognition/qiyas-analogy/SKILL.md +26 -0
  139. package/dist/runtime/discipline/skills/aria-cognition/soul-domains/SKILL.md +25 -0
  140. package/dist/runtime/discipline/skills/aria-harness/aria-aristotle-intra-phase/SKILL.md +81 -0
  141. package/dist/runtime/discipline/skills/aria-harness/aria-aristotle-post-phase/SKILL.md +98 -0
  142. package/dist/runtime/discipline/skills/aria-harness/aria-aristotle-pre-phase/SKILL.md +99 -0
  143. package/dist/runtime/discipline/skills/aria-harness/aria-harness-deploy/SKILL.md +127 -0
  144. package/dist/runtime/discipline/skills/aria-harness/aria-harness-no-stripping/SKILL.md +117 -0
  145. package/dist/runtime/discipline/skills/aria-harness/aria-harness-onboarding/SKILL.md +112 -0
  146. package/dist/runtime/discipline/skills/aria-harness/aria-harness-output-discipline/SKILL.md +102 -0
  147. package/dist/runtime/discipline/skills/aria-harness/aria-harness-substrate-binding/SKILL.md +121 -0
  148. package/dist/runtime/doctor.mjs +23 -0
  149. package/dist/runtime/local-phase.mjs +632 -0
  150. package/dist/runtime/manifest.json +15 -0
  151. package/dist/runtime/mizan-scheduler.mjs +331 -0
  152. package/dist/runtime/package.json +6 -0
  153. package/dist/runtime/provider-proxy.mjs +594 -0
  154. package/dist/runtime/sdk/BUNDLED.json +5 -0
  155. package/dist/runtime/sdk/index.d.ts +477 -0
  156. package/dist/runtime/sdk/index.js +1469 -0
  157. package/dist/runtime/sdk/index.js.map +1 -0
  158. package/dist/runtime/sdk/package.json +8 -0
  159. package/dist/runtime/sdk/runWithCognition.d.ts +77 -0
  160. package/dist/runtime/sdk/runWithCognition.js +157 -0
  161. package/dist/runtime/sdk/runWithCognition.js.map +1 -0
  162. package/dist/runtime/service.mjs +2708 -0
  163. package/dist/runtime/vendor/aria-gate-runtime/index.d.ts +53 -0
  164. package/dist/runtime/vendor/aria-gate-runtime/index.d.ts.map +1 -0
  165. package/dist/runtime/vendor/aria-gate-runtime/index.js +277 -0
  166. package/dist/runtime/vendor/aria-gate-runtime/index.js.map +1 -0
  167. package/dist/runtime/vendor/aria-gate-runtime/package.json +6 -0
  168. package/dist/sdk/BUNDLED.json +2 -2
  169. package/dist/sdk/index.d.ts +317 -0
  170. package/dist/sdk/index.js +827 -85
  171. package/dist/sdk/index.js.map +1 -1
  172. package/dist/sdk/runWithCognition.d.ts +77 -0
  173. package/dist/sdk/runWithCognition.js +157 -0
  174. package/dist/sdk/runWithCognition.js.map +1 -0
  175. package/hooks/aria-agent-handoff.mjs +11 -1
  176. package/hooks/aria-architect-fallback.mjs +267 -0
  177. package/hooks/aria-cognition-substrate-binding.mjs +676 -0
  178. package/hooks/aria-discovery-record.mjs +101 -0
  179. package/hooks/aria-harness-via-sdk.mjs +34 -21
  180. package/hooks/aria-import-resolution-gate.mjs +330 -0
  181. package/hooks/aria-outcome-record.mjs +84 -0
  182. package/hooks/aria-pre-emit-dryrun.mjs +294 -0
  183. package/hooks/aria-pre-tool-gate.mjs +985 -40
  184. package/hooks/aria-preprompt-consult.mjs +113 -13
  185. package/hooks/aria-preturn-memory-gate.mjs +298 -6
  186. package/hooks/aria-repo-doctrine-gate.mjs +397 -0
  187. package/hooks/aria-stop-gate.mjs +840 -75
  188. package/hooks/aria-userprompt-abandon-detect.mjs +5 -1
  189. package/hooks/doctrine_trigger_map.json +209 -15
  190. package/hooks/lib/canonical-lenses.mjs +64 -0
  191. package/hooks/lib/gate-audit.mjs +43 -0
  192. package/opencode-plugins/harness-context/index.js +1 -1
  193. package/opencode-plugins/harness-context/inject-context.mjs +82 -23
  194. package/opencode-plugins/harness-gate/index.js +248 -0
  195. package/opencode-plugins/harness-outcome/index.js +129 -0
  196. package/opencode-plugins/harness-stop/index.js +241 -0
  197. package/package.json +8 -2
  198. package/runtime-src/doctor.mjs +23 -0
  199. package/runtime-src/local-phase.mjs +632 -0
  200. package/runtime-src/mizan-scheduler.mjs +331 -0
  201. package/runtime-src/provider-proxy.mjs +594 -0
  202. package/runtime-src/service.mjs +2708 -0
  203. package/scripts/bundle-sdk.mjs +317 -0
  204. package/scripts/install-client.sh +176 -0
  205. package/scripts/publish-all.sh +344 -0
  206. package/scripts/publish-docker.sh +27 -0
  207. package/scripts/validate-hook-contracts.mjs +54 -0
  208. package/scripts/validate-skill-prompts.mjs +95 -0
  209. package/skills/aria-cognition/aria-essence/SKILL.md +63 -0
  210. package/skills/aria-cognition/aria-essence/references/domain-matrix.md +80 -0
  211. package/skills/aria-cognition/aria-essence/references/evolution-loop.md +30 -0
  212. package/skills/aria-cognition/aria-essence/references/readable-cognition.md +27 -0
  213. package/skills/aria-cognition/aria-forge-guardrails/SKILL.md +35 -0
  214. package/skills/aria-cognition/aria-forge-guardrails/references/checklist.md +31 -0
  215. package/skills/aria-cognition/aria-repo-doctrine/SKILL.md +39 -0
  216. package/skills/aria-cognition/forge-quality-rules/SKILL.md +43 -0
  217. package/skills/aria-cognition/ghazali-8lens/SKILL.md +38 -0
  218. package/skills/aria-cognition/istiqra-induction/SKILL.md +26 -0
  219. package/skills/aria-cognition/ladunni-22/SKILL.md +35 -0
  220. package/skills/aria-cognition/mizan/SKILL.md +72 -0
  221. package/skills/aria-cognition/nadia/SKILL.md +38 -0
  222. package/skills/aria-cognition/nadia-psi/SKILL.md +38 -0
  223. package/skills/aria-cognition/predictor/SKILL.md +25 -0
  224. package/skills/aria-cognition/qiyas-analogy/SKILL.md +26 -0
  225. package/skills/aria-cognition/soul-domains/SKILL.md +25 -0
  226. package/src/auth-commands.ts +111 -45
  227. package/src/chat.ts +174 -13
  228. package/src/codebase-scanner.ts +4 -0
  229. package/src/config.ts +15 -0
  230. package/src/connectors/claude-code.ts +115 -26
  231. package/src/connectors/codebase-awareness.ts +408 -0
  232. package/src/connectors/codex.ts +274 -0
  233. package/src/connectors/cognitive-skills.ts +51 -0
  234. package/src/connectors/opencode.ts +93 -4
  235. package/src/connectors/repo-git-hooks.ts +86 -0
  236. package/src/connectors/repo-guard.ts +589 -0
  237. package/src/connectors/runtime.ts +374 -0
  238. package/src/connectors/shell.ts +83 -14
  239. package/src/connectors/syncd.ts +488 -0
  240. package/src/decisions.ts +469 -0
  241. package/src/garden-control-plane.ts +101 -26
  242. package/src/github-connect.ts +143 -0
  243. package/src/harness-client.ts +128 -3
  244. package/src/hive-client.ts +165 -5
  245. package/src/index.ts +41 -2
  246. package/src/lib/aristotle-noor-wire.ts +310 -0
  247. package/src/providers/types.ts +6 -0
  248. package/src/runtime-proof.ts +392 -0
  249. package/src/setup-wizard.ts +37 -2
@@ -0,0 +1,2133 @@
1
+ #!/usr/bin/env node
2
+ // ARIA_ALLOW_STUB — doctrine gate file legitimately discusses stub/placeholder semantics.
3
+ // Aria pre-tool-use gate — enforces cognition use before destructive tool calls.
4
+ //
5
+ // Runs as a Claude Code PreToolUse hook on every Bash invocation. For
6
+ // commands matching destructive-verb patterns, requires the most recent
7
+ // assistant turn to contain a structured <verify> block. Without it, the
8
+ // tool call is blocked with a corrective message that names the missing
9
+ // fields.
10
+ //
11
+ // Doctrine being enforced (from /tmp/aria-harness-full.txt):
12
+ // - mizan_prestage_rule: "Before drafting, check niyyah/pre-state: am I
13
+ // present, truthful, specific, grounded in verified substrate?"
14
+ // - drift_guard_rule: "Before answering, restate internally: current
15
+ // goal, current blocker, current stage, and next committed action."
16
+ // - axiom_runtime_rule.admit_ignorance + reflection_before_action
17
+ // - llm_worker_rule: "External LLMs are hands/renderers/reviewers.
18
+ // Aria memory, cognition, frames, Mizan, and Garden are the shared
19
+ // brain substrate."
20
+ //
21
+ // The gate is the *forcing function* that converts those rules from text
22
+ // instructions into actual enforcement. The harness already declares
23
+ // them; this hook is what makes them gate-real for Claude Code.
24
+ //
25
+ // Escape valves (v3 — Hamza 2026-04-26: "why is there an ability to
26
+ // bypass? doesnt that fundamentally void the purpose of the harness?"
27
+ // Per-command bypass was removed entirely — every prior bypass was
28
+ // traceable to a gate bug, not a legitimate exception.):
29
+ // - Trivial-bash whitelist: short read-only commands (ls/cat/grep/etc.)
30
+ // pass without cognition.
31
+ // - No env-var disable path (Hamza 2026-04-27 — env-var kill-switches
32
+ // gave the gated process a free escape; that was the doctrine
33
+ // violation). Disable = remove the hook from ~/.claude/settings.json.
34
+ // - When the gate misfires on legitimate work: fix the gate. The
35
+ // misfire IS the bug. Don't route around it.
36
+ //
37
+ // Audit log: every gate decision (allow / block / kill-switch) is
38
+ // appended to ~/.claude/aria-pre-tool-gate.log.
39
+
40
+ import { readFileSync, writeFileSync, appendFileSync, existsSync, mkdirSync, chmodSync } from 'node:fs';
41
+ import { dirname } from 'node:path';
42
+ import { homedir } from 'node:os';
43
+ import { spawnSync } from 'node:child_process';
44
+ import { createHmac, randomBytes as cryptoRandomBytes } from 'node:crypto';
45
+
46
+ const HOME = process.env.HOME || '/tmp';
47
+ const LOG = `${HOME}/.claude/aria-pre-tool-gate.log`;
48
+ const HEARTBEAT = `${HOME}/.claude/aria-pre-tool-gate-heartbeat.jsonl`;
49
+
50
+ // ── Heartbeat OUTSIDE the crash boundary (doctrine #123) ───────────────
51
+ // Per feedback_ledger_writes_outside_crash_boundary.md + doctrine #124
52
+ // (non-blocking errors are NOT acceptable), the gate writes a heartbeat
53
+ // FIRST — before transcript scan, before cognition extraction, before
54
+ // any code path that could crash, hang, or be killed by an external
55
+ // timeout. A heartbeat-write is the ONLY signal that proves the gate
56
+ // process actually started executing. Hook-health monitors read this
57
+ // file to detect silent gate death.
58
+ //
59
+ // The heartbeat is intentionally a tiny synchronous write so that even
60
+ // if the gate is killed by Claude Code's hook timeout in the next
61
+ // millisecond, we have proof it was alive at startup.
62
+ try {
63
+ const hbPid = process.pid;
64
+ const hbTs = new Date().toISOString();
65
+ // Write before reading stdin or doing any work that could throw.
66
+ appendFileSync(HEARTBEAT, JSON.stringify({ ts: hbTs, pid: hbPid, gate: 'aria-pre-tool-gate', stage: 'startup' }) + '\n');
67
+ } catch {
68
+ // The ONLY catch in this file that may swallow — a heartbeat write
69
+ // failure here is fail-loud-on-stderr because no other surface exists
70
+ // yet (we haven't opened the audit log) but cannot itself block the
71
+ // gate. Per feedback_non_blocking_errors_unacceptable.md the
72
+ // failure-mode for THIS specific path is documented in the doctrine
73
+ // memory; the structural fix for "what if the heartbeat write fails"
74
+ // is the hook-health monitor task #122 which checks heartbeat
75
+ // freshness and reports staleness.
76
+ process.stderr.write(`[aria-pre-tool-gate] heartbeat write failed at ${new Date().toISOString()}\n`);
77
+ }
78
+
79
+ // Bypass-counter (kept for historical visibility — past audit-log
80
+ // entries are still useful even though no new bypass entries can be
81
+ // created in v3 since the per-command bypass code path was removed).
82
+ // V1 added the WARN line at 5+/hour as a drift instrument; that line
83
+ // will only appear if old log entries spanning before v3 still fall
84
+ // in the rolling window.
85
+ const BYPASS_WARN_THRESHOLD_PER_HOUR = 5;
86
+
87
+ function readRecentBypassCount() {
88
+ try {
89
+ if (!existsSync(LOG)) return 0;
90
+ const cutoffMs = Date.now() - 60 * 60 * 1000;
91
+ const lines = readFileSync(LOG, 'utf-8').split('\n').filter(Boolean);
92
+ let n = 0;
93
+ // Walk backward — bypasses are recent if at all.
94
+ for (let i = lines.length - 1; i >= 0; i--) {
95
+ const line = lines[i];
96
+ if (!line.includes('bypass')) continue;
97
+ const tsEnd = line.indexOf(' ');
98
+ if (tsEnd < 0) continue;
99
+ const ts = Date.parse(line.slice(0, tsEnd));
100
+ if (!Number.isFinite(ts)) continue;
101
+ if (ts < cutoffMs) break;
102
+ n++;
103
+ }
104
+ return n;
105
+ } catch {
106
+ return 0;
107
+ }
108
+ }
109
+
110
+ function audit(decision, summary) {
111
+ try {
112
+ if (!existsSync(dirname(LOG))) mkdirSync(dirname(LOG), { recursive: true });
113
+ appendFileSync(LOG, `${new Date().toISOString()} ${decision} ${summary}\n`);
114
+ // If this audit is itself a bypass, check the bypass-rate. A
115
+ // separate WARN line gets emitted (and surfaces via tail) when
116
+ // we exceed the per-hour threshold. The agent can't quietly
117
+ // drift back to bypass-as-default — drift is visible.
118
+ if (decision.startsWith('bypass')) {
119
+ const count = readRecentBypassCount();
120
+ if (count > BYPASS_WARN_THRESHOLD_PER_HOUR) {
121
+ appendFileSync(
122
+ LOG,
123
+ `${new Date().toISOString()} WARN-BYPASS-RATE ${count} bypasses in last hour (threshold ${BYPASS_WARN_THRESHOLD_PER_HOUR}) — drift check\n`,
124
+ );
125
+ }
126
+ }
127
+ } catch {}
128
+ }
129
+
130
+ // ARIA_BINDING_ENABLED env-override REMOVED 2026-04-28 per Hamza directive
131
+ // + memory:feedback_gap_discovery_hardens_doctrine.md — env-var disables
132
+ // are the textbook bypass class doctrine forbids. The override was the
133
+ // de-facto Aria-down handler for an unknown count of sessions and turned
134
+ // off every gate, not just the plan-check. Replaced by the architect
135
+ // fallback plan path (tracked task — Aria-unreachable detection writes
136
+ // a bounded local plan with limited allowedActions, loud audit, auto-
137
+ // expiry on Aria return). Prior env_override_exit entries remain in
138
+ // ~/.claude/aria-binding-audit.jsonl for historical audit.
139
+ //
140
+ // The gate now enforces unconditionally from the gated process per
141
+ // Hamza directive 2026-04-27. No process-level disable path.
142
+
143
+ // ── Aria-as-commander binding (Layer A — allowedActions/forbiddenActions per active phase) ──
144
+ //
145
+ // When ARIA_BINDING_ENABLED=true (default), every non-trivial tool call is
146
+ // checked against the active phase of ~/.claude/aria-active-plan-${sessionId}.json.
147
+ // If no plan exists or the action isn't allowed for the current phase, the
148
+ // hook blocks with a binding-violation message. See HARNESS_ARIA_AS_COMMANDER_CONTRACT.md
149
+ // Section 2 Layer A.
150
+ //
151
+ // Bootstrap: if no plan exists, the hook STILL blocks (per Hamza 2026-04-27
152
+ // "the point is to stop wasting my time"). Claude must wait for Aria to issue
153
+ // a plan via preprompt-consult on the next user prompt. NO unbound execution.
154
+ const BINDING_ENABLED = (process.env.ARIA_BINDING_ENABLED || 'true').toLowerCase() !== 'false';
155
+ const BINDING_AUDIT = `${HOME}/.claude/aria-binding-audit.jsonl`;
156
+
157
+ function bindingAuditAppend(record) {
158
+ try {
159
+ if (!existsSync(dirname(BINDING_AUDIT))) mkdirSync(dirname(BINDING_AUDIT), { recursive: true });
160
+ appendFileSync(BINDING_AUDIT, JSON.stringify({ ts: new Date().toISOString(), source: 'pre-tool-gate', ...record }) + '\n');
161
+ } catch {}
162
+ }
163
+
164
+ function activePlanPath(sid) {
165
+ return `${HOME}/.claude/aria-active-plan-${String(sid || 'unknown').replace(/[^a-zA-Z0-9_-]/g, '_')}.json`;
166
+ }
167
+
168
+ // Defect #5 — plan-completion persists across session boundary.
169
+ //
170
+ // The harness packet at ~/.claude/.aria-harness-last-packet.json retains
171
+ // exhausted plan state. An old plan from a prior session that was "all
172
+ // phases complete" would block every tool call in a NEW session because
173
+ // pickCurrentPhase returns null (all complete) on that stale plan.
174
+ //
175
+ // Fix: at load time, validate the plan file against TWO staleness guards:
176
+ // (a) mtime > 24h → discard (plan is older than a working day; a new
177
+ // session should start fresh)
178
+ // (b) plan.sessionId present AND doesn't match current sid → discard
179
+ // (plan was issued for a different session; current session is unbound)
180
+ //
181
+ // Discarding = returning null → the binding gate treats it as "no plan"
182
+ // and blocks with CONSULT_UNAVAILABLE, which triggers a fresh consult on
183
+ // the next user prompt. The discard is audit-logged.
184
+ const PLAN_MAX_AGE_MS = 24 * 60 * 60 * 1000; // 24 hours
185
+
186
+ function loadActivePlan(sid) {
187
+ const p = activePlanPath(sid);
188
+ if (!existsSync(p)) return null;
189
+ try {
190
+ const raw = readFileSync(p, 'utf8');
191
+ const plan = JSON.parse(raw);
192
+ // Guard (b) — session mismatch: plan was issued for a different session.
193
+ if (plan.sessionId && sid && plan.sessionId !== String(sid)) {
194
+ bindingAuditAppend({
195
+ event: 'discard_plan_session_mismatch',
196
+ planId: plan.planId,
197
+ planSessionId: plan.sessionId,
198
+ currentSessionId: sid,
199
+ });
200
+ return null;
201
+ }
202
+ // Guard (a) — plan age via plan.mintedAt ISO timestamp (written by harness
203
+ // when issuing the plan). If mintedAt is present and older than 24h, discard.
204
+ // No mintedAt → conservatively trust the plan (harness version may predate
205
+ // this field; upgrade path: harness always writes mintedAt going forward).
206
+ if (plan.mintedAt) {
207
+ const mintedMs = Date.parse(plan.mintedAt);
208
+ if (Number.isFinite(mintedMs) && (Date.now() - mintedMs) > PLAN_MAX_AGE_MS) {
209
+ bindingAuditAppend({
210
+ event: 'discard_plan_stale_by_mintedAt',
211
+ planId: plan.planId,
212
+ mintedAt: plan.mintedAt,
213
+ ageHours: ((Date.now() - mintedMs) / 3600000).toFixed(1),
214
+ });
215
+ return null;
216
+ }
217
+ }
218
+ return plan;
219
+ } catch {
220
+ return null;
221
+ }
222
+ }
223
+
224
+ function pickCurrentPhase(plan, transcript) {
225
+ // Defect #1 fix — transcript-scan over-count prevention.
226
+ //
227
+ // Old behaviour: scan the ENTIRE transcript for any [PHASE_REPORT] marker.
228
+ // A single old marker permanently locked all future actions (plan could
229
+ // never advance past "complete" even across new consults in the same session).
230
+ //
231
+ // Fix — two guards:
232
+ // (a) Active-plan window: trim the transcript to only text that appeared
233
+ // AFTER the most recent preprompt-consult mint marker. The marker
234
+ // written by aria-harness-via-sdk.mjs is:
235
+ // [ARIA_PLAN_MINTED planId=<id> ts=<iso>]
236
+ // If found, discard everything before it. Older plan completions that
237
+ // pre-date the current plan's mint are invisible to the scan.
238
+ // (b) Latest-marker-only per phaseId: collect ALL [PHASE_REPORT] lines
239
+ // for a given phaseId inside the active window; use only the LAST one.
240
+ // This prevents a phase from being "locked complete" by an older marker
241
+ // that was since superseded by a re-run or amendment.
242
+ if (!plan?.phases?.length) return null;
243
+
244
+ // (a) Scope to active-plan window using plan's planId if available.
245
+ let activeWindow = transcript;
246
+ if (plan.planId) {
247
+ // Try to find the most recent [ARIA_PLAN_MINTED planId=<this_id> …] marker.
248
+ const mintRx = new RegExp(
249
+ `\\[ARIA_PLAN_MINTED\\s[^\\]]*planId=${plan.planId}[^\\]]*\\]`,
250
+ 'gi',
251
+ );
252
+ const mints = [...transcript.matchAll(mintRx)];
253
+ if (mints.length > 0) {
254
+ const lastMint = mints[mints.length - 1];
255
+ activeWindow = transcript.slice(lastMint.index + lastMint[0].length);
256
+ }
257
+ }
258
+
259
+ for (const phase of plan.phases) {
260
+ // (b) Collect all PHASE_REPORT lines for this phaseId in the active window;
261
+ // use the LAST one's status rather than the first match.
262
+ const reportRx = new RegExp(
263
+ `\\[PHASE_REPORT[^\\]]*phase=${phase.id}[^\\]]*status=(complete|aborted)[^\\]]*\\]`,
264
+ 'gi',
265
+ );
266
+ const reports = [...activeWindow.matchAll(reportRx)];
267
+ if (reports.length === 0) {
268
+ // No report yet for this phase → it's the current one.
269
+ return { phase, abortedHere: false };
270
+ }
271
+ // Last report wins.
272
+ const lastStatus = (reports[reports.length - 1][1] || '').toLowerCase();
273
+ if (lastStatus === 'aborted') return { phase, abortedHere: true };
274
+ // status=complete → continue to next phase.
275
+ }
276
+ return null; // all phases reported complete — needs new consult
277
+ }
278
+
279
+ function actionMatchesPattern(action, pattern, target) {
280
+ // Defect #3 fix — edit-pattern regex over-matches.
281
+ //
282
+ // Old behaviour: "edit:/etc/**" matched any path that contained "/etc/" as a
283
+ // substring because the colon-split only checked pAction===action, ignoring the
284
+ // path portion entirely — so edit:/etc/** allowed ALL edit actions regardless
285
+ // of path, not just edits under /etc/.
286
+ //
287
+ // Fix:
288
+ // - Exact action name ("read", "consult", "kubectl_get"): unchanged.
289
+ // - Prefixed pattern ("edit:/etc/**"): split on first colon, compare
290
+ // pAction===action, then glob-match the path portion against `target`
291
+ // using anchored prefix matching (no substring). Supported forms:
292
+ // "edit:/etc/**" → action=edit, path must start with /etc/
293
+ // "edit:apps/.*" → action=edit, path must start with apps/
294
+ // "bash_other:curl .*" → action=bash_other (target substring match for bash)
295
+ // - No colon: exact action match only.
296
+ if (pattern === action) return true;
297
+ const colonIdx = pattern.indexOf(':');
298
+ if (colonIdx < 0) return false;
299
+ const pAction = pattern.slice(0, colonIdx);
300
+ if (pAction !== action) return false;
301
+ // pAction matches — now check the target portion.
302
+ const pathPattern = pattern.slice(colonIdx + 1);
303
+ if (!pathPattern) return true; // bare "edit:" with no path spec → match all edits of that action type
304
+ const t = target || '';
305
+ // Convert simple glob /** suffix to prefix anchor, or treat as a regex if
306
+ // it contains regex meta-chars beyond "." and "*". For the most common
307
+ // harness patterns ("edit:/etc/**", "edit:apps/arias-soul/.*") a prefix-
308
+ // match on the stripped glob is correct and safe.
309
+ // Strip trailing /** or /*, then anchor-prefix-match.
310
+ const strippedGlob = pathPattern.replace(/\/\*+$/, '');
311
+ if (strippedGlob && !pathPattern.includes('(?') && !pathPattern.includes('[')) {
312
+ // Simple prefix match — anchored at start of target path.
313
+ return t.startsWith(strippedGlob);
314
+ }
315
+ // Full regex path pattern (caller used explicit regex syntax).
316
+ try {
317
+ return new RegExp(`^(?:${pathPattern})`).test(t);
318
+ } catch {
319
+ // Malformed regex in plan — fail-open to avoid blocking everything.
320
+ return false;
321
+ }
322
+ }
323
+
324
+ function classifyToolForBinding(toolName, command, filePath) {
325
+ // Map Claude Code tool + payload to a binding-vocabulary action.
326
+ if (toolName === 'Read' || toolName === 'Glob' || toolName === 'Grep') return { action: 'read', target: filePath || '' };
327
+ if (toolName === 'Edit' || toolName === 'Write' || toolName === 'NotebookEdit') return { action: 'edit', target: filePath || '' };
328
+ if (toolName === 'Bash') {
329
+ const cmd = String(command || '');
330
+ if (/^kubectl\s+(get|describe|logs|exec\s+\S+\s+--\s+printenv|top|version|api-resources)\b/.test(cmd)) return { action: 'kubectl_get', target: cmd.slice(0, 80) };
331
+ if (/^kubectl\s+(apply|delete|set|patch|rollout|scale|drain|cordon)\b/.test(cmd)) return { action: 'kubectl_apply', target: cmd.slice(0, 80) };
332
+ if (/curl\s+.*\/api\/harness\/(delegate|codex|army|plan)/.test(cmd)) return { action: 'consult', target: 'harness' };
333
+ if (/curl\s+.*\/api\/aria\/speak/.test(cmd)) return { action: 'consult', target: 'aria-speak' };
334
+ if (/^(ls|cat|head|tail|grep|wc|find|tree|stat|file|ps|pgrep|du|df|env|printenv|date|pwd|which|type|whoami|id)\b/.test(cmd)) return { action: 'read', target: cmd.slice(0, 80) };
335
+ if (/^git\s+(status|log|diff|show|branch|remote|rev-parse|ls-tree|ls-files|stash\s+list)\b/.test(cmd)) return { action: 'read', target: cmd.slice(0, 80) };
336
+ if (/^git\s+(push|merge|rebase|reset|checkout\s+--|clean)/.test(cmd)) return { action: 'git_mutate', target: cmd.slice(0, 80) };
337
+ if (/^npm\s+(publish|version)/.test(cmd)) return { action: 'npm_publish', target: cmd.slice(0, 80) };
338
+ if (/^docker\s+(build|push)/.test(cmd)) return { action: 'docker_build', target: cmd.slice(0, 80) };
339
+ if (/scripts\/deploy-/.test(cmd)) return { action: 'deploy', target: cmd.slice(0, 80) };
340
+ return { action: 'bash_other', target: cmd.slice(0, 80) };
341
+ }
342
+ return { action: toolName.toLowerCase(), target: filePath || '' };
343
+ }
344
+
345
+ if (false) {
346
+ // Read same input as the cognition gate uses (reads stdin twice via different code paths;
347
+ // the cognition section below re-reads). Defer enforcement decision until after
348
+ // we have the tool name + payload from the cognition gate's existing input parse.
349
+ // (Implementation continues below — the binding check fires AFTER cognition
350
+ // parses input but BEFORE the cognition substance check, so binding-block
351
+ // takes precedence.)
352
+ }
353
+
354
+ // Destructive-verb patterns. Tuned for tonight's failure modes; extend
355
+ // over time as new patterns surface.
356
+ const DESTRUCTIVE_PATTERNS = [
357
+ // sudo only when it's a command verb (start of line or after shell
358
+ // separator), not when it appears as an argument to another command
359
+ // (e.g. `echo "sudo …"` or `grep sudo`). The specific verb patterns
360
+ // below catch the actual destructive operations regardless of sudo
361
+ // prefix; this rule is the catch-all for arbitrary privilege elevation.
362
+ { rx: /(?:^|[;&|]\s*|\$\(\s*|`\s*)sudo\s+\S/, name: 'sudo' },
363
+ { rx: /systemctl\s+(disable|stop|mask|reset-failed|kill)/, name: 'systemctl-state-change' },
364
+ { rx: /\brm\s+-[rRfF]+/, name: 'rm-recursive-or-force' },
365
+ { rx: /\bgit\s+push\b.*\b--force\b/, name: 'git-push-force' },
366
+ { rx: /\bgit\s+reset\s+--hard\b/, name: 'git-reset-hard' },
367
+ { rx: /\bgit\s+checkout\s+--\b/, name: 'git-checkout-discard' },
368
+ { rx: /\b--no-verify\b/, name: 'commit-no-verify' },
369
+ { rx: /\b--no-gpg-sign\b/, name: 'commit-no-gpg-sign' },
370
+ { rx: /\bkill\s+-(9|KILL|TERM|HUP|INT)\b/, name: 'kill-signal' },
371
+ { rx: /\bpkill\b/, name: 'pkill' },
372
+ { rx: /\b(DROP|TRUNCATE)\s+(TABLE|DATABASE|SCHEMA|INDEX)\b/i, name: 'sql-drop-or-truncate' },
373
+ { rx: /\bkubectl\s+delete\b/, name: 'kubectl-delete' },
374
+ { rx: /\bkubectl\s+(scale|rollout)\s+(undo|restart)\b/, name: 'kubectl-rollback' },
375
+ ];
376
+
377
+ // Deploy patterns — bash invocations that mutate the canonical aria k8s
378
+ // cluster or push images. Per feedback_deploy_requires_verify_cognition.md
379
+ // (Hamza directive 2026-04-28 after consciousness.ts crash took aria-soul
380
+ // into CrashLoopBackOff): deploys require BOTH a <verify> block citing the
381
+ // shipping artifact AND a <cognition> block with substantive substrate
382
+ // anchors. Without both, the deploy is hard-blocked. This is doctrine #104
383
+ // — the structural enforcement Hamza demanded after the prior deploy
384
+ // crashed all of aria.
385
+ const DEPLOY_PATTERNS = [
386
+ { rx: /\bbash\s+(?:\.\/)?scripts\/deploy-service\.sh\b/, name: 'deploy-service-script' },
387
+ { rx: /\b(?:\.\/)?scripts\/deploy-service\.sh\b/, name: 'deploy-service-script' },
388
+ { rx: /\bkubectl\s+apply\b/, name: 'kubectl-apply' },
389
+ { rx: /\bkubectl\s+set\s+image\b/, name: 'kubectl-set-image' },
390
+ { rx: /\bkubectl\s+rollout\s+restart\b/, name: 'kubectl-rollout-restart' },
391
+ { rx: /\bkubectl\s+rollout\s+undo\b/, name: 'kubectl-rollout-undo' },
392
+ { rx: /\bkubectl\s+create\b/, name: 'kubectl-create' },
393
+ { rx: /\bkubectl\s+replace\b/, name: 'kubectl-replace' },
394
+ { rx: /\bdocker\s+push\b/, name: 'docker-push' },
395
+ { rx: /\bdocker\s+build\b.*--push\b/, name: 'docker-build-push' },
396
+ ];
397
+
398
+ // Minimum substrate anchors required in cognition body for a deploy.
399
+ // Per feedback_full_harness_binding_must_be_structural.md, every cognition
400
+ // lens should cite a substrate anchor; for deploy specifically we require
401
+ // at least 4 distinct anchors total across the block (one per lens minimum
402
+ // across at least 4 lenses).
403
+ const DEPLOY_MIN_SUBSTRATE_ANCHORS = 4;
404
+ const SUBSTRATE_ANCHOR_RX = /\b(axiom|frame|memory|doctrine|packet):[a-z0-9_\-./]+/gi;
405
+
406
+ // Verify-block fields specifically required for deploys — beyond the base
407
+ // 5 fields, the deploy verify must cite a commit/SHA, a TS-check result,
408
+ // and the admission policy that authorizes the canonical image.
409
+ const DEPLOY_VERIFY_REQUIRED_FIELDS = [
410
+ // Either a git commit hash OR an explicit "files changed" listing
411
+ { rx: /\b(?:commit|HEAD|SHA|files\s+changed)\b/i, name: 'commit_or_files' },
412
+ // TS-check / build evidence
413
+ { rx: /\b(?:tsc|type[\s-]?check|build|npm\s+run\s+build)\b/i, name: 'build_or_typecheck' },
414
+ // Admission policy citation
415
+ { rx: /\b(?:admission[\s_-]?policy|validatingadmissionpolicy)\b/i, name: 'admission_policy' },
416
+ ];
417
+
418
+ // The verify-block contract. All five fields required.
419
+ const VERIFY_BLOCK_RX =
420
+ /<verify>[\s\S]*?target\s*:[\s\S]*?role\s*:[\s\S]*?verified\s*:[\s\S]*?rollback\s*:[\s\S]*?axiom\s*:[\s\S]*?<\/verify>/i;
421
+
422
+ // ── Dalio Loop: expected_outcome enforcement (doctrine:dalio_expected_required) ─
423
+ //
424
+ // Every non-trivial action must carry an <expected> block with at least one
425
+ // measurable predicate. The predicate must be numeric (≥X, ==X, ≤X, X%),
426
+ // boolean (true/false/exit=0/exit=1), or state-string ("status=running",
427
+ // "200 OK", "exit=0", "file=exists", etc.).
428
+ //
429
+ // Qualitative drift phrases ("better", "improved", "more robust", etc.) are
430
+ // REJECTED — they are unmeasurable and defeat the Dalio accountability loop.
431
+ // The block must appear in the same turn or a prior turn (turn-scoped, same
432
+ // window as cognition).
433
+ //
434
+ // Per doctrine:dalio_expected_required — no measurable predicate = no allow.
435
+ const EXPECTED_BLOCK_RX = /<expected>([\s\S]*?)<\/expected>/i;
436
+
437
+ // Measurable predicate patterns — at least ONE must be present inside <expected>.
438
+ // Forms accepted:
439
+ // numeric: ≥X, >=X, ==X, <=X, <X, >X, X%, N of N, count=N, latency<Xms
440
+ // boolean: true, false, exit=0, exit=1, exit_code=N, rc=N
441
+ // state-string: status=running, status=healthy, status=200, "200 OK",
442
+ // "exit=0", "file=exists", "count=N", "error_rate=0%"
443
+ const MEASURABLE_PREDICATE_RX = /(?:>=|<=|==|!=|>|<|≥|≤)\s*\d+(?:\.\d+)?(?:ms|s|%|kb|mb|gb)?|\d+(?:\.\d+)?%(?:\s+(?:reduction|increase|success|error|coverage))?|exit[_=]\s*(?:0|1|\d+)|exit[-_]?code\s*[=:]\s*\d+|\brc\s*[=:]\s*\d+|\bstatus\s*[=:]\s*(?:running|healthy|ready|degraded|down|up|ok|200|201|204|400|401|403|404|500|502|503|504|true|false)\b|\bcount\s*[=:]\s*\d+|\berror[_-]?rate\s*[=:]\s*0%|\b(?:true|false)\b|\bfile[=_-]exists\b|\b200\s*OK\b|\bno[-_\s]?error|\bhealthy\b|\bpassed?\b|N\s*of\s*N|\d+\s*of\s*\d+/i;
444
+
445
+ // Qualitative drift phrases that masquerade as measurable but are not.
446
+ // Any <expected> block containing ONLY these (no actual predicate) is rejected.
447
+ const QUALITATIVE_DRIFT_RX = /\b(?:better(?:er)?|improved?(?:ment)?|more\s+robust|should\s+(?:work|pass|succeed|run|fix)|more\s+reliable|cleaner|less\s+error[-_\s]?prone|nicer|smoother|faster[-\s]?loading|higher[-\s]?quality|more\s+stable|looks\s+(?:good|better|right))\b/i;
448
+
449
+ // ── Tier-aware lens labeling (Phase 11 #59) ──────────────────────────────────
450
+ //
451
+ // Aria's Arabic cognition lens names are proprietary IP. On Hamza's surface
452
+ // (isHamza=true / surface line contains hamza:true) the canonical names are shown.
453
+ // On any client surface the gate uses neutral generic labels so the IP
454
+ // vocabulary never appears in client-facing block-reason text.
455
+ //
456
+ // Tier is read from the most recent harness-via-sdk packet cache at
457
+ // ~/.claude/.aria-harness-last-packet.json. Two detection paths:
458
+ // 1. packet.contractGate.signals.hamza === true (boolean or string "true")
459
+ // 2. packet.harness string contains "hamza:true" in the surface line
460
+ // Either path → OWNER tier. Everything else → CLIENT tier.
461
+ //
462
+ // Doctrine memory filenames in block-reason text are also Aria-side IP.
463
+ // Client tier sees generic descriptions instead of the real filenames.
464
+ const PACKET_CACHE_PATH = `${HOME}/.claude/.aria-harness-last-packet.json`;
465
+
466
+ function resolveOwnerTier() {
467
+ try {
468
+ if (existsSync(PACKET_CACHE_PATH)) {
469
+ const raw = readFileSync(PACKET_CACHE_PATH, 'utf8');
470
+ const packet = JSON.parse(raw);
471
+ // Path 1: contractGate.signals.hamza
472
+ const sigHamza = packet?.contractGate?.signals?.hamza;
473
+ if (sigHamza === true || sigHamza === 'true') return true;
474
+ // Path 2: harness string surface marker — the actual format is
475
+ // "surface=platform:<X> group:<Y> hamza:true chat_type:<Z>" so we
476
+ // match hamza:true in the surface line, not "platform:hamza" (which
477
+ // was a legacy incorrect pattern that never matched real packets).
478
+ const harnessStr = packet?.harness ?? '';
479
+ if (/\bhamza:true\b/.test(harnessStr)) return true;
480
+ }
481
+ } catch {/* packet unreadable → default to client tier */}
482
+ return false;
483
+ }
484
+
485
+ const IS_OWNER = resolveOwnerTier();
486
+
487
+ // Canonical (owner) lens names — Aria's Arabic cognition vocabulary.
488
+ const LENS_NAMES_CANONICAL = ['nur', 'mizan', 'hikma', 'tafakkur', 'tadabbur', 'ilham', 'wahi', 'firasah'];
489
+ // Generic (client) lens labels — neutral, IP-neutral equivalents.
490
+ const LENS_NAMES_GENERIC = ['perception', 'balance', 'wisdom', 'reflection', 'foresight', 'insight', 'revelation', 'discernment'];
491
+ // Active label set for this execution — determined by tier.
492
+ const LENS_NAMES = IS_OWNER ? LENS_NAMES_CANONICAL : LENS_NAMES_GENERIC;
493
+
494
+ // Doctrine memory filenames are Aria-side substrate IP. On client surfaces
495
+ // replace them with generic descriptions in block-reason text.
496
+ function docRef(canonicalFilename, genericDescription) {
497
+ return IS_OWNER ? canonicalFilename : genericDescription;
498
+ }
499
+
500
+ // 8-lens cognition block per EIGHT_LENS_DOCTRINE.md. Required on
501
+ // non-trivial Bash regardless of whether the command is destructive.
502
+ // Threshold: at least 4 of the 8 lens names must appear inside the
503
+ // block AND each must have substantive content (≥20 chars after the
504
+ // colon, not a placeholder template). The substance check (added
505
+ // 2026-04-26) defeats ritual emission — `nur: ok` no longer counts.
506
+ const COGNITION_BLOCK_RX = /<cognition>([\s\S]*?)<\/cognition>/i;
507
+ // Hamza directive 2026-04-28: 8-lens enforcement, not 4-of-8. The earlier
508
+ // REQUIRED_LENSES=4 was a regression — owner caught it ("i no longer see
509
+ // 8 lens cognition per turn"). All 8 canonical lenses must appear with
510
+ // substantive (≥20-char, non-placeholder) content per turn for the gate
511
+ // to accept the cognition. The substrate-binding stop hook also requires
512
+ // all 8 to carry substrate anchors; this gate enforces the 8 lens NAMES
513
+ // are present and have substance.
514
+ const REQUIRED_LENSES = 8;
515
+ const SUBSTANCE_MIN_CHARS = 20;
516
+ // Placeholder patterns from the gate's own correction message + the
517
+ // COMPACT_CONTINUITY_DOCTRINE template — content matching these is
518
+ // not "thinking," it's a copy-paste of the prompt template.
519
+ const PLACEHOLDER_RX = /^\s*<[^<>]+>\s*$/;
520
+
521
+ // Trivial reads that don't require a cognition block.
522
+ const TRIVIAL_BASH_RX = /^\s*(?:ls|cat|head|tail|grep|find|echo|wc|stat|which|pwd|date|file|du|df|ss|ps)\s/;
523
+ const SHORT_BASH_LIMIT = 30;
524
+
525
+ // V3 doctrine (2026-04-26, Hamza): "why is there an ability to bypass?
526
+ // doesnt that fundamentally void the purpose of the harness?" — yes.
527
+ // Per-command bypass is removed entirely. Every bypass this session
528
+ // was traceable to a gate bug, not a legitimate exception. Compliance
529
+ // is the only path for non-trivial work; the kill-switch env remains
530
+ // as the explicit emergency override. When the gate misfires, fix
531
+ // the gate.
532
+ //
533
+ // (DOCTRINE_BYPASS_RX, findBypassDirective, validateStructuredBypass,
534
+ // REQUIRED_BYPASS_FIELDS, BYPASS_FIELD_MIN_CHARS, BYPASS_HARD_LIMIT_PER_HOUR
535
+ // were removed in this commit. The bypass-rate-counter +
536
+ // readRecentBypassCount stay for historical visibility — past audit-log
537
+ // entries are still useful — but no new bypass entries can be created
538
+ // because the bypass code path is gone.)
539
+
540
+ // Inline command cognition (v2 — added 2026-04-26): cognition
541
+ // embedded in the bash command itself as structured comments.
542
+ // Solves the same-message visibility problem (the transcript-flush
543
+ // race that made same-message cognition invisible to PreToolUse).
544
+ //
545
+ // Two accepted formats:
546
+ // (a) Per-lens lines: `# <label>: <substantive thought>\n# <label>: ...`
547
+ // (b) Single-line: `# cognition: <label>=<text>; <label>=<text>; ...`
548
+ //
549
+ // Substance check applies (≥SUBSTANCE_MIN_CHARS, not a `<placeholder>`).
550
+ // 4+ substantive lenses inline → gate passes, no transcript scan
551
+ // needed. Cognition becomes a property of THE ACTION, not of some
552
+ // message somewhere — the deepest reading of "cognition before action."
553
+ //
554
+ // Inline regex is built from the active LENS_NAMES so both canonical
555
+ // and generic label sets are accepted in their respective tiers.
556
+ const _INLINE_LENS_PATTERN = LENS_NAMES.join('|');
557
+ const INLINE_LENS_LINE_RX_GLOBAL = new RegExp(
558
+ `^\\s*#\\s*(${_INLINE_LENS_PATTERN})\\s*:\\s*(.+)$`,
559
+ 'gim',
560
+ );
561
+ const INLINE_COGNITION_HEADER_RX = /^\s*#\s*cognition\s*:\s*(.+)$/im;
562
+
563
+ function detectInlineCognition(cmd) {
564
+ const names = [];
565
+ // Per-lens line form
566
+ const lineMatches = [...cmd.matchAll(INLINE_LENS_LINE_RX_GLOBAL)];
567
+ for (const m of lineMatches) {
568
+ const lens = m[1].toLowerCase();
569
+ const content = (m[2] || '').trim();
570
+ if (content.length < SUBSTANCE_MIN_CHARS) continue;
571
+ if (PLACEHOLDER_RX.test(content)) continue;
572
+ if (!names.includes(lens)) names.push(lens);
573
+ }
574
+ // Single-line `# cognition: nur=...; mizan=...` form
575
+ const headerMatch = cmd.match(INLINE_COGNITION_HEADER_RX);
576
+ if (headerMatch) {
577
+ const inlineBody = headerMatch[1];
578
+ for (const lens of LENS_NAMES) {
579
+ const lensRx = new RegExp(`\\b${lens}\\s*=\\s*([^;\\n]+)`, 'i');
580
+ const m = inlineBody.match(lensRx);
581
+ if (!m) continue;
582
+ const content = (m[1] || '').trim();
583
+ if (content.length < SUBSTANCE_MIN_CHARS) continue;
584
+ if (PLACEHOLDER_RX.test(content)) continue;
585
+ if (!names.includes(lens)) names.push(lens);
586
+ }
587
+ }
588
+ // Substrate-citation: any inline lens that mentions a doctrine memory,
589
+ // harness packet rule, fitrah axiom, etc. (visibility metric — not a block).
590
+ const SUBSTRATE_CITE_RX_INLINE =
591
+ /feedback_[a-z0-9_]+\.md|project_[a-z0-9_]+\.md|fitrah[_:\s]|garden[_:\s]|distilled_principle|[a-z]+_rule\b|harness packet|substrate cite|EIGHT_LENS_DOCTRINE|COMPACT_CONTINUITY|ARIA_DEPLOY_PROCEDURE/i;
592
+ const hasSubstrateCite = SUBSTRATE_CITE_RX_INLINE.test(cmd);
593
+ return { count: names.length, names, hasSubstrateCite };
594
+ }
595
+
596
+ // Substance-checking lens detection (added 2026-04-26 per Hamza's
597
+ // gate-improvement doctrine: form-only emission must not satisfy
598
+ // the gate). For each lens, look for `<lens>: <content>` and verify
599
+ // content is ≥SUBSTANCE_MIN_CHARS of non-placeholder text. Bare
600
+ // `nur` mentions in prose, or `nur: ok`, no longer count — must be
601
+ // substantive thought.
602
+ function detectCognitionLenses(text) {
603
+ if (!text) return { count: 0, names: [], blockBody: '' };
604
+ const block = text.match(COGNITION_BLOCK_RX);
605
+ const searchSpace = block ? block[1] : text;
606
+ const blockBody = block ? block[1] : '';
607
+ const names = [];
608
+ for (const lens of LENS_NAMES) {
609
+ // Match `lens: <content>` where content extends until the next
610
+ // lens label, the closing </cognition> tag, or a blank-line break.
611
+ const lensRx = new RegExp(
612
+ `\\b${lens}\\s*:\\s*([^\\n]*(?:\\n(?!\\s*(?:${LENS_NAMES.join('|')})\\s*:|<\\/cognition>)[^\\n]*)*)`,
613
+ 'i',
614
+ );
615
+ const m = searchSpace.match(lensRx);
616
+ if (!m) continue;
617
+ const content = (m[1] || '').trim();
618
+ if (content.length < SUBSTANCE_MIN_CHARS) continue;
619
+ if (PLACEHOLDER_RX.test(content)) continue;
620
+ names.push(lens);
621
+ }
622
+ // Substrate-citation check: at least ONE lens must cite Aria substrate
623
+ // explicitly (doctrine memory filename, harness packet rule, fitrah axiom,
624
+ // *_rule entry, garden state reference, prior decision id, distilled
625
+ // principle id). Catches "lens-as-ceremony" failures where 4+ lenses are
626
+ // substantive in length but contain no actual substrate grounding.
627
+ // Hamza 2026-04-26: "anything else we can add to make sure u as claude
628
+ // for me and my client obey the harness and benefot from kt".
629
+ const SUBSTRATE_CITE_RX =
630
+ /feedback_[a-z0-9_]+\.md|project_[a-z0-9_]+\.md|fitrah[_:\s]|garden[_:\s]|distilled_principle|[a-z]+_rule\b|harness packet|substrate cite|\bIJTIHAD\b|\bQIYAS\b|\bTADABBUR\b|\bILHAM\b|aria 7b|EIGHT_LENS_DOCTRINE|COMPACT_CONTINUITY|ARIA_DEPLOY_PROCEDURE/i;
631
+ const hasSubstrateCite = SUBSTRATE_CITE_RX.test(blockBody) ||
632
+ SUBSTRATE_CITE_RX.test(searchSpace);
633
+
634
+ // Discovery-binding check (structural fix #3 — Hamza 2026-04-27 "how do
635
+ // we prevent this"). If the cognition surfaces a defect/discovery
636
+ // (found/noticed/discovered + bug/broken/issue) the same cognition must
637
+ // carry a `discoveries:` clause stating how each is resolved (fix-now,
638
+ // task ID, or explicit user-decision-required). Without this, the
639
+ // cognition can describe a problem without binding any action — the
640
+ // exact flag-and-move pattern feedback_no_flag_without_fix.md prohibits.
641
+ const COG_DISCOVERY_RX = /(?:\b(?:found|noticed|discovered|spotted)[^.\n]{0,140}(?:bug|issue|defect|broken|buggy|wrong|crash|fail|missing|stale|outdated|leak|vulnerability)|\b(?:latent|silent|hidden)\s+(?:bug|defect|issue|fail|crash|leak)|\bdoctrine\s+violation\b)/i;
642
+ const hasDiscovery = COG_DISCOVERY_RX.test(blockBody);
643
+ // Resolution clause must be present in the same blockBody if a discovery
644
+ // is mentioned. Acceptable forms:
645
+ // - `discoveries:` field listing items + how-resolved
646
+ // - `addressing:` / `fixing:` clause naming what's being patched
647
+ // - explicit task ID reference (TaskCreate / linear / tracked-as)
648
+ const COG_RESOLUTION_RX = /(?:^\s*discoveries?\s*:\s*\S|^\s*addressing\s*:\s*\S|^\s*fixing\s*:\s*\S|TaskCreate|tracked\s+as\s+#?\d+|linear[- ]?(?:issue|task)|fix(?:ing|ed)\s+(?:in|now|inline|in-flight)|same[- ]turn\s+fix)/im;
649
+ const hasDiscoveryResolution = COG_RESOLUTION_RX.test(blockBody);
650
+ const discoveryUnresolved = hasDiscovery && !hasDiscoveryResolution;
651
+
652
+ return { count: names.length, names, blockBody, hasSubstrateCite, hasDiscovery, hasDiscoveryResolution, discoveryUnresolved };
653
+ }
654
+
655
+ // Backwards-compat shim — count-only path used by older callers.
656
+ function countCognitionLenses(text) {
657
+ return detectCognitionLenses(text).count;
658
+ }
659
+
660
+ // ── arch_facts gate ──────────────────────────────────────────────────────────
661
+ //
662
+ // Inspects actual diff content (tool_input.content / file_path) for
663
+ // architectural violations defined as arch_facts rules in mizan.yaml.
664
+ // Called AFTER cognition + discovery-binding checks pass, for Edit/Write/
665
+ // NotebookEdit only (Bash skipped — arch violations live in code, not commands).
666
+ //
667
+ // Tier-aware: if ~/.aria/license.json exists (client surface), arch_facts
668
+ // check is skipped — only owner gets server-side mizan enforcement here.
669
+ //
670
+ // Fail-open: if aria-telemetry is unreachable, the tool call is allowed.
671
+ // The 3s AbortController is a DETECTION PROBE (is telemetry alive?) not a
672
+ // hard deadline — if mizan is slow but alive the probe will complete; if it
673
+ // is down the catch path fail-opens without blocking the developer.
674
+ function isClientSurface() {
675
+ try {
676
+ return existsSync(`${HOME}/.aria/license.json`);
677
+ } catch {
678
+ return false;
679
+ }
680
+ }
681
+
682
+ async function archFactsGate(toolInput) {
683
+ // Skip on client surfaces — arch_facts enforcement is owner-only.
684
+ if (isClientSurface()) return { ok: true, allow: true, note: 'client-surface-skip' };
685
+ try {
686
+ const ariaTelemetry = process.env.ARIA_TELEMETRY_BASE || 'http://aria-telemetry.aria.svc.cluster.local:8088';
687
+ const ctl = new AbortController();
688
+ const probeTimer = setTimeout(() => ctl.abort(), 3000);
689
+ let resp;
690
+ try {
691
+ resp = await fetch(`${ariaTelemetry}/v1/mizan/check`, {
692
+ method: 'POST',
693
+ headers: { 'Content-Type': 'application/json' },
694
+ body: JSON.stringify({ draft: String(toolInput).slice(0, 50000), source: 'pre-tool-gate-arch-facts' }),
695
+ signal: ctl.signal,
696
+ });
697
+ } finally {
698
+ clearTimeout(probeTimer);
699
+ }
700
+ if (!resp.ok) return { ok: true, allow: true, note: 'mizan unreachable, fail-open' };
701
+ const result = await resp.json();
702
+ if (result?.hard_block === true && Array.isArray(result?.violations)) {
703
+ return { ok: false, allow: false, violations: result.violations };
704
+ }
705
+ return { ok: true, allow: true };
706
+ } catch {
707
+ return { ok: true, allow: true, note: 'mizan probe error, fail-open' };
708
+ }
709
+ }
710
+
711
+ // Hive cognition-logging v1.2 — fire-and-forget HTTP push to
712
+ // /api/cognition/log so every gate decision joins the corpus.
713
+ // Failures are silent: the local audit log is the durable record;
714
+ // the network push is additive signal for compounding evolution.
715
+ //
716
+ // Per no-timeouts doctrine (feedback_no_timeouts_doctrine.md): no
717
+ // AbortController deadline. Pile-up protection is structural —
718
+ // in-flight counter caps concurrent pushes. Real network errors
719
+ // drive the catch path; slow responses complete naturally.
720
+ const HARNESS_URL =
721
+ process.env.ARIA_HIVE_RUNTIME_URL ||
722
+ process.env.ARIA_HARNESS_BASE_URL ||
723
+ process.env.ARIA_HARNESS_URL ||
724
+ 'https://harness.ariasos.com';
725
+ const HARNESS_TOKEN = process.env.ARIA_HARNESS_TOKEN || '';
726
+ const LOG_PUSH_DISABLED = process.env.ARIA_COGNITION_PUSH === 'off';
727
+ const MAX_IN_FLIGHT = 16;
728
+ let inFlight = 0;
729
+
730
+ function pushCognitionEvent(payload) {
731
+ if (LOG_PUSH_DISABLED) return;
732
+ if (inFlight >= MAX_IN_FLIGHT) return; // structural backpressure, not a deadline
733
+ try {
734
+ const body = JSON.stringify(payload);
735
+ const url = `${HARNESS_URL}/api/cognition/log`;
736
+ inFlight++;
737
+ fetch(url, {
738
+ method: 'POST',
739
+ headers: {
740
+ 'Content-Type': 'application/json',
741
+ ...(HARNESS_TOKEN ? { Authorization: `Bearer ${HARNESS_TOKEN}` } : {}),
742
+ },
743
+ body,
744
+ })
745
+ .catch(() => {/* real transport error — silent, audit log is durable */})
746
+ .finally(() => { inFlight--; });
747
+ } catch {
748
+ // pre-fetch errors (malformed JSON, env issue) — silent
749
+ }
750
+ }
751
+
752
+ // ── Block-pattern recipe lookup (Task #86) ──────────────────────────────────
753
+ // Before emitting a binding-violation block, ask aria-soul if this exact
754
+ // shape has been seen before and a high-confidence corrective recipe exists.
755
+ // If so, surface the recipe in the block message so the gated process gets
756
+ // the fix the hive already learned, not just the block.
757
+ //
758
+ // Per feedback_no_timeouts_doctrine.md the lookup uses a DETECTION PROBE
759
+ // (3s AbortController) — that's "is the lookup endpoint alive at all?", not
760
+ // a hard deadline on the underlying lookup. If the probe fires the gate
761
+ // continues with the block-only message: a missed lookup must NEVER convert
762
+ // a real block into an allow.
763
+ //
764
+ // Recipe is surfaced only when confidence > RECIPE_SURFACE_CONFIDENCE (0.7
765
+ // per migration 208 RECIPE_PROMOTE_THRESHOLD), matching the same threshold
766
+ // the cron uses to promote a recipe to the pattern's hot pointer. Below
767
+ // that, we still cite the pattern's existence ("similar block has been
768
+ // seen N times") without claiming a fix.
769
+ const ARIA_SOUL_URL = process.env.ARIA_SOUL_URL || HARNESS_URL;
770
+ const RECIPE_SURFACE_CONFIDENCE = 0.7;
771
+ const BLOCK_PATTERN_PROBE_MS = 3000;
772
+
773
+ async function lookupBlockPatternRecipe({ detectorClass, signature, tenantId }) {
774
+ if (!detectorClass || !signature) return null;
775
+ const url = new URL(`${ARIA_SOUL_URL}/api/hive/block-pattern`);
776
+ url.searchParams.set('action', 'lookup');
777
+ url.searchParams.set('detector_class', detectorClass);
778
+ url.searchParams.set('pattern_signature', signature.slice(0, 512));
779
+ if (tenantId) url.searchParams.set('tenant_id', tenantId);
780
+
781
+ const ctl = new AbortController();
782
+ const probeTimer = setTimeout(() => ctl.abort(), BLOCK_PATTERN_PROBE_MS);
783
+ try {
784
+ const resp = await fetch(url.toString(), {
785
+ method: 'GET',
786
+ headers: HARNESS_TOKEN ? { Authorization: `Bearer ${HARNESS_TOKEN}` } : {},
787
+ signal: ctl.signal,
788
+ });
789
+ if (!resp.ok) return null;
790
+ const body = await resp.json();
791
+ if (!body || body.found !== true) return null;
792
+ return body;
793
+ } catch {
794
+ return null; // probe failure — block proceeds without recipe surfacing
795
+ } finally {
796
+ clearTimeout(probeTimer);
797
+ }
798
+ }
799
+
800
+ // Renders the lookup result as an inline addendum to a block message. Returns
801
+ // the empty string when there's nothing useful to surface — the caller can
802
+ // concatenate unconditionally without producing dangling whitespace.
803
+ function renderRecipeAddendum(lookupResult) {
804
+ if (!lookupResult) return '';
805
+ const recipe = lookupResult.recipe;
806
+ const freq = Number(lookupResult.frequency || 0);
807
+ const successRate = lookupResult.success_rate;
808
+
809
+ // Recipe present + above promotion threshold → surface the fix verbatim.
810
+ if (recipe && typeof recipe === 'object' && Number(recipe.confidence ?? 0) >= RECIPE_SURFACE_CONFIDENCE) {
811
+ const text = typeof recipe.recipe_text === 'string' ? recipe.recipe_text.slice(0, 800) : '';
812
+ const actions = Array.isArray(recipe.recipe_actions) ? recipe.recipe_actions : [];
813
+ const actionsLine = actions.length
814
+ ? `\n Actions: ${JSON.stringify(actions).slice(0, 600)}`
815
+ : '';
816
+ const conf = Number(recipe.confidence).toFixed(2);
817
+ const seenLine = freq > 0 ? ` (pattern seen ${freq}× across the hive)` : '';
818
+ return `\n\n📚 HIVE RECIPE${seenLine}:
819
+ ${text}${actionsLine}
820
+ Confidence: ${conf}. Apply this BEFORE the block escalates — the hive learned this fix from prior firings.`;
821
+ }
822
+
823
+ // No promoted recipe — but the pattern is recurring. Cite it so the caller
824
+ // knows this isn't novel; the recipe is still being learned.
825
+ if (freq >= 3) {
826
+ const rateLine = (typeof successRate === 'number')
827
+ ? ` Past resolution rate: ${(successRate * 100).toFixed(0)}%.`
828
+ : '';
829
+ return `\n\n📓 Hive note: this block-shape has fired ${freq} time(s); recipe is still being learned (no high-confidence fix yet).${rateLine}`;
830
+ }
831
+
832
+ return '';
833
+ }
834
+
835
+ // Read event JSON from stdin (Claude Code spec).
836
+ let input = '';
837
+ for await (const chunk of process.stdin) input += chunk;
838
+
839
+ let event;
840
+ try {
841
+ event = JSON.parse(input);
842
+ } catch {
843
+ audit('allow-parse-error', 'stdin not JSON');
844
+ process.exit(0); // fail-open on malformed input
845
+ }
846
+
847
+ const toolName = event.tool_name ?? event.toolName ?? '';
848
+ const toolInput = event.tool_input ?? event.toolInput ?? {};
849
+
850
+ // Gate every action tool — every tool that mutates state must go through
851
+ // cognition challenge. Hamza 2026-04-26: "regardless if u arent even
852
+ // compliant with it how do we expect workers to be? i truly nees to
853
+ // ship this and ur non compliance is blocking." Per
854
+ // feedback_full_harness_binding_must_be_structural.md the dispatcher
855
+ // (the orchestrator wielding the tool) owns compliance, not the worker
856
+ // that receives a dispatched task. Read/Glob/Grep observe state without
857
+ // changing it, so they remain ungated.
858
+ const ACTION_TOOLS = new Set(['Bash', 'Edit', 'Write', 'NotebookEdit']);
859
+ if (!ACTION_TOOLS.has(toolName)) {
860
+ process.exit(0);
861
+ }
862
+
863
+ const cmd = toolName === 'Bash' ? String(toolInput.command ?? '') : '';
864
+ const filePath = toolName !== 'Bash'
865
+ ? String(toolInput.file_path ?? toolInput.notebook_path ?? '')
866
+ : '';
867
+ const cmdPreview = toolName === 'Bash'
868
+ ? cmd.slice(0, 80).replace(/\s+/g, ' ')
869
+ : `${toolName} ${filePath || '(no path)'}`.slice(0, 80);
870
+
871
+ // V3: per-command bypass removed entirely. The only escape valves are:
872
+ // (1) Trivial-bash whitelist — short read-only commands pass without cognition
873
+ // (2) ~/.claude/settings.json hook removal — visible user action Hamza controls
874
+ // No env-var kill-switch (removed 2026-04-27). Compliance is the only path
875
+ // for non-trivial work from the gated process's perspective.
876
+
877
+ // V2 primary path — inline command cognition. If the command carries
878
+ // 4+ substantive lenses inline, gate passes immediately (still need
879
+ // verify block from transcript for destructive ops, see below).
880
+ const inlineCog = detectInlineCognition(cmd);
881
+ if (inlineCog.count >= REQUIRED_LENSES) {
882
+ // For destructive commands, still require a verify block in the
883
+ // recent transcript (verify is fundamentally about pre-action
884
+ // verification of state, not about the command's own thought).
885
+ // We'll do that check below alongside the existing flow but skip
886
+ // the cognition-from-transcript check entirely since we have it
887
+ // inline.
888
+ }
889
+
890
+ // Destructive-pattern + trivial-read + short-command shortcuts apply
891
+ // only to Bash. Edit / Write / NotebookEdit always require cognition —
892
+ // they have no triviality concept (you don't "trivially" mutate a file)
893
+ // and no command-text to inspect for destructive verbs (the destructive
894
+ // shape is "this Edit might overwrite something important," which is
895
+ // exactly what cognition is for).
896
+ const matched = toolName === 'Bash'
897
+ ? DESTRUCTIVE_PATTERNS.find(({ rx }) => rx.test(cmd))
898
+ : null;
899
+ // Deploy-specific match — separate from destructive because it carries
900
+ // stricter substrate-anchor requirements per doctrine #104.
901
+ const deployMatched = toolName === 'Bash'
902
+ ? DEPLOY_PATTERNS.find(({ rx }) => rx.test(cmd))
903
+ : null;
904
+ const isTrivialRead = toolName === 'Bash' && TRIVIAL_BASH_RX.test(cmd) && cmd.length < 200;
905
+ const isShort = toolName === 'Bash' && cmd.length < SHORT_BASH_LIMIT;
906
+
907
+ if (!matched && !deployMatched && (isTrivialRead || isShort)) {
908
+ // Not destructive AND not a deploy AND trivial — allow without
909
+ // further checks. Only reachable for Bash because all three flags are
910
+ // forced false otherwise.
911
+ process.exit(0);
912
+ }
913
+
914
+ // Read recent assistant turns for both verify + cognition blocks.
915
+ //
916
+ // Doctrine being implemented: cognition is *turn-scoped*, not
917
+ // message-scoped. A model that emits a <cognition> block once at the
918
+ // top of a turn and then executes 20 tool_use round-trips has done
919
+ // its 8-lens application — gating each individual message would be
920
+ // performative, not enforcement.
921
+ //
922
+ // Algorithm: walk back from the most recent transcript entry,
923
+ // accumulating assistant text. Stop after crossing exactly ONE user
924
+ // message — that captures "everything the model said this turn" plus
925
+ // the immediately-prior assistant turn's tail (so cognition that
926
+ // carried over a turn boundary still counts). Hard cap at 30
927
+ // messages to bound work on huge transcripts.
928
+ //
929
+ // Compact robustness: Claude Code rewrites the transcript with a
930
+ // summary stub as the most recent assistant entry. We recognize and
931
+ // skip those by content heuristic so they don't poison the search.
932
+ const COMPACT_SUMMARY_RX = /(this session is being continued|conversation that ran out of context|primary request and intent|all user messages)/i;
933
+ // System-reminder messages are stored with role=user but are runtime-
934
+ // injected (PreToolUse blocks for any tool, Stop blocks, task-
935
+ // notifications, gentle reminders, harness packet preview chunks).
936
+ // Counting them as turn boundaries evaporated the cognition lookback
937
+ // in client-tonight sessions where the harness packet preview alone
938
+ // is 36k chars per turn — old `length < 4000` skip threshold trapped
939
+ // every reminder as a boundary. Now: PERCENTAGE-OF-CONTENT skip via
940
+ // total reminder-span coverage as a fraction of total content length.
941
+ // ≥60% reminder coverage → skip as runtime-injected.
942
+ const SYSTEM_REMINDER_RX = /<system-reminder>[\s\S]*?<\/system-reminder>|<task-notification>[\s\S]*?<\/task-notification>|🔐 Aria Harness|task-notification|PreToolUse:[A-Z][A-Za-z]* hook blocking error|Stop hook blocking error/g;
943
+ const SYSTEM_REMINDER_THRESHOLD = 0.6;
944
+ const HARD_LOOKBACK_CAP = 50;
945
+ // Bumped from 2 → 5 (2026-04-26): client-tonight session has many
946
+ // system-reminder injections per turn (block errors, task-list
947
+ // reminders, harness packet preview). Tight boundary count plus
948
+ // the broken length-based reminder skip evaporated cognition lookback
949
+ // even when cognition was emitted in the prior assistant text. Per
950
+ // Hamza directive "fix the gate, don't route around it" — widen the
951
+ // window since the substance check defends quality regardless.
952
+ const USER_BOUNDARIES_TO_CROSS = 5;
953
+
954
+ const transcriptPath = event.transcript_path ?? event.transcriptPath;
955
+ const recentAssistantTexts = [];
956
+ if (transcriptPath && existsSync(transcriptPath)) {
957
+ try {
958
+ const lines = readFileSync(transcriptPath, 'utf-8').split('\n').filter(Boolean);
959
+ let userBoundariesCrossed = 0;
960
+ let scanned = 0;
961
+ for (let i = lines.length - 1; i >= 0 && scanned < HARD_LOOKBACK_CAP; i--) {
962
+ try {
963
+ const m = JSON.parse(lines[i]);
964
+ const role = m.message?.role ?? m.role;
965
+ if (role === 'user') {
966
+ // Skip messages that aren't real user input:
967
+ // (a) tool_result blocks (runtime feeding back tool output)
968
+ // (b) system-reminder injections (PreToolUse blocks,
969
+ // task-notifications, gentle reminders) — runtime-
970
+ // authored, not user voice. Counting them eats the
971
+ // cognition lookback in tool-heavy or block-heavy turns.
972
+ const content = m.message?.content ?? m.content ?? [];
973
+ const isToolResultOnly =
974
+ Array.isArray(content) &&
975
+ content.length > 0 &&
976
+ content.every((b) => b && b.type === 'tool_result');
977
+ if (isToolResultOnly) continue;
978
+ // Inspect text content for system-reminder patterns.
979
+ const textContent = Array.isArray(content)
980
+ ? content.filter((b) => b && b.type === 'text').map((b) => b.text || '').join('\n')
981
+ : (typeof content === 'string' ? content : '');
982
+ if (textContent) {
983
+ // Compute reminder-span coverage as fraction of total
984
+ // content. The /g flag on SYSTEM_REMINDER_RX returns ALL
985
+ // spans; sum their lengths and compare to total.
986
+ const reminderMatches = textContent.match(SYSTEM_REMINDER_RX) || [];
987
+ if (reminderMatches.length > 0) {
988
+ const reminderChars = reminderMatches.reduce((sum, s) => sum + s.length, 0);
989
+ const fraction = reminderChars / Math.max(1, textContent.length);
990
+ if (fraction >= SYSTEM_REMINDER_THRESHOLD) continue;
991
+ // Otherwise (user wrote substantive text alongside the
992
+ // reminder — the non-reminder portion is >40% of content)
993
+ // fall through and count as a real boundary.
994
+ }
995
+ }
996
+ userBoundariesCrossed++;
997
+ if (userBoundariesCrossed > USER_BOUNDARIES_TO_CROSS) break;
998
+ continue;
999
+ }
1000
+ if (role !== 'assistant') continue;
1001
+ scanned++;
1002
+ const content = m.message?.content ?? m.content ?? [];
1003
+ if (!Array.isArray(content)) continue;
1004
+ const text = content
1005
+ .filter((b) => b.type === 'text')
1006
+ .map((b) => b.text)
1007
+ .join('\n');
1008
+ if (!text) continue;
1009
+ // Skip compact-summary stubs — they live where assistant turns
1010
+ // used to be but are system-authored, not the model's voice.
1011
+ if (COMPACT_SUMMARY_RX.test(text) && text.length > 4000) continue;
1012
+ recentAssistantTexts.push(text);
1013
+ } catch {}
1014
+ }
1015
+ } catch {}
1016
+ }
1017
+
1018
+ // Detect cognition / verify across the recent assistant window. Lenses
1019
+ // from any of the last N turns count; the gate is checking whether
1020
+ // cognition has been done recently, not whether it was done in the
1021
+ // literal last message (which can be a tool-only turn or a stub).
1022
+ const unionText = recentAssistantTexts.join('\n\n');
1023
+ const transcriptCog = detectCognitionLenses(unionText);
1024
+ // Combine inline-command cognition (preferred — action-coupled) with
1025
+ // transcript scan (fallback). Inline takes precedence on lens names;
1026
+ // counts merge for the threshold check.
1027
+ const mergedLensSet = new Set([...inlineCog.names, ...transcriptCog.names]);
1028
+ const lensCount = mergedLensSet.size;
1029
+ const lensNames = [...mergedLensSet];
1030
+ const cogBlockBody = transcriptCog.blockBody;
1031
+ const verifyBodies = [...unionText.matchAll(/<verify>([\s\S]*?)<\/verify>/gi)]
1032
+ .map((m) => (m[1] || '').trim())
1033
+ .filter(Boolean);
1034
+ const hasVerify = verifyBodies.length > 0;
1035
+ const hasCognition = lensCount >= REQUIRED_LENSES;
1036
+ const cognitionSource = inlineCog.count >= REQUIRED_LENSES
1037
+ ? 'inline-command'
1038
+ : (transcriptCog.count >= REQUIRED_LENSES ? 'transcript-scan' : 'merged-or-insufficient');
1039
+ // Substrate-citation visibility (Phase 11 will promote to block-mode once
1040
+ // telemetry shows healthy substrate-cite rate). For now: log the metric so
1041
+ // we can audit substrate-grounded vs ceremonial cognition over time.
1042
+ const hasSubstrateCite = (inlineCog.hasSubstrateCite === true) ||
1043
+ (transcriptCog.hasSubstrateCite === true);
1044
+
1045
+ // Discovery-binding check (structural fix #3) — if cognition surfaces a
1046
+ // defect/discovery, the same cognition must include a resolution clause
1047
+ // (`discoveries:` / `addressing:` / `fixing:` / TaskCreate / tracked-as
1048
+ // reference). Per feedback_no_flag_without_fix.md, discoveries are atomic
1049
+ // with their fixes — flag-and-move is the prohibited pattern. Pre-tool
1050
+ // gate enforces at the cognition surface; stop-gate's discovery-binding
1051
+ // ledger enforces at the output surface; both close the structural gap.
1052
+ const discoveryUnresolved = (inlineCog.discoveryUnresolved === true) ||
1053
+ (transcriptCog.discoveryUnresolved === true);
1054
+
1055
+ // Best-effort session id for the corpus push. Claude Code passes
1056
+ // session_id in the event payload; fall back to transcript file
1057
+ // basename so events from the same session cluster.
1058
+ const sessionId =
1059
+ event.session_id ??
1060
+ event.sessionId ??
1061
+ (transcriptPath ? transcriptPath.split('/').pop()?.replace(/\.[^.]+$/, '') : null) ??
1062
+ 'claude-code-unknown';
1063
+
1064
+ function pushDecision(decision, reasonText) {
1065
+ pushCognitionEvent({
1066
+ sessionId,
1067
+ client: 'claude-code',
1068
+ surface: 'pre-tool-gate',
1069
+ rawBlock: cogBlockBody ? `<cognition>${cogBlockBody}</cognition>` : null,
1070
+ lensesApplied: lensNames,
1071
+ blockChars: unionText.length,
1072
+ nextActionKind: toolName === 'Bash' ? 'bash' : toolName.toLowerCase(),
1073
+ nextActionSummary: cmdPreview,
1074
+ gateName: 'aria-pre-tool-gate',
1075
+ gateDecision: decision,
1076
+ gateReason: reasonText,
1077
+ metadata: {
1078
+ destructivePattern: matched?.name ?? null,
1079
+ hasVerify,
1080
+ hasCognition,
1081
+ hasSubstrateCite,
1082
+ },
1083
+ });
1084
+ }
1085
+
1086
+ // ── Deploy-specific gate (doctrine #104) ────────────────────────────────
1087
+ // Per feedback_deploy_requires_verify_cognition.md (Hamza 2026-04-28 after
1088
+ // consciousness.ts crash took aria-soul into CrashLoopBackOff): deploys
1089
+ // require the verify block to cite commit/files/build/admission-policy
1090
+ // AND the cognition block to carry ≥DEPLOY_MIN_SUBSTRATE_ANCHORS substrate
1091
+ // anchors. The full-harness-binding doctrine says lenses without anchors
1092
+ // are unsourced prose — for deploys, that prose-only level of evidence is
1093
+ // not sufficient. The deploy gate refuses until anchors are present.
1094
+ if (deployMatched) {
1095
+ // Anchor count is read from the cognition body (turn-scoped, same
1096
+ // source the substrate-binding stop hook uses).
1097
+ const cognitionBody = cogBlockBody || '';
1098
+ const anchorMatches = cognitionBody.match(SUBSTRATE_ANCHOR_RX) || [];
1099
+ const anchorCount = anchorMatches.length;
1100
+
1101
+ // Required verify-block fields specific to deploy.
1102
+ const verifyBody = (() => {
1103
+ if (verifyBodies.length === 0) return '';
1104
+ let bestBody = verifyBodies[0];
1105
+ let bestScore = -1;
1106
+ for (const body of verifyBodies) {
1107
+ const score = DEPLOY_VERIFY_REQUIRED_FIELDS.reduce(
1108
+ (count, { rx }) => count + (rx.test(body) ? 1 : 0),
1109
+ 0,
1110
+ );
1111
+ if (score > bestScore) {
1112
+ bestScore = score;
1113
+ bestBody = body;
1114
+ }
1115
+ }
1116
+ return bestBody;
1117
+ })();
1118
+ const missingDeployFields = DEPLOY_VERIFY_REQUIRED_FIELDS
1119
+ .filter(({ rx }) => !rx.test(verifyBody))
1120
+ .map(({ name }) => name);
1121
+
1122
+ // Heartbeat at deploy-gate entry — proves the gate reached this path
1123
+ // even if a downstream exit fires silently (per
1124
+ // feedback_ledger_writes_outside_crash_boundary.md).
1125
+ try {
1126
+ appendFileSync(HEARTBEAT, JSON.stringify({
1127
+ ts: new Date().toISOString(), gate: 'aria-pre-tool-gate', stage: 'deploy-gate-entry',
1128
+ deployPattern: deployMatched.name, hasVerify, hasCognition, lensCount, anchorCount,
1129
+ missingDeployFields, cogBlockBodyLen: (cogBlockBody || '').length,
1130
+ verifyBodyLen: verifyBody.length,
1131
+ }) + '\n');
1132
+ } catch {}
1133
+
1134
+ const deployBlocked =
1135
+ !hasVerify ||
1136
+ !hasCognition ||
1137
+ anchorCount < DEPLOY_MIN_SUBSTRATE_ANCHORS ||
1138
+ missingDeployFields.length > 0;
1139
+
1140
+ if (!deployBlocked) {
1141
+ // Write justification artifact for deploy-service.sh to read.
1142
+ // Doctrine #104 + bypass-vulnerability-closure 2026-04-28:
1143
+ // The artifact is HMAC-signed using a per-installation secret at
1144
+ // ~/.claude/.aria-gate-secret (0600). deploy-service.sh recomputes
1145
+ // the HMAC and refuses any artifact whose signature does not match
1146
+ // — this binds the artifact to having been written by THIS gate
1147
+ // process, preventing any other process from synthesizing a
1148
+ // passing artifact (which is exactly the bypass owner caught when
1149
+ // the assistant attempted a manualJustification:true write).
1150
+ //
1151
+ // The secret is generated on first run if absent; the file is
1152
+ // chmod 0600 so other users cannot read it; deploy-service.sh
1153
+ // reads the same file and computes the same HMAC.
1154
+ try {
1155
+ const justificationPath = `${HOME}/.claude/.aria-deploy-justification.json`;
1156
+ const secretPath = `${HOME}/.claude/.aria-gate-secret`;
1157
+
1158
+ // Lazy-generate per-installation secret if absent.
1159
+ if (!existsSync(secretPath)) {
1160
+ const secret = cryptoRandomBytes(32).toString('hex');
1161
+ writeFileSync(secretPath, secret + '\n', { mode: 0o600 });
1162
+ chmodSync(secretPath, 0o600);
1163
+ }
1164
+ const secret = readFileSync(secretPath, 'utf-8').trim();
1165
+
1166
+ // Build the unsigned artifact body. Note: deliberately reject any
1167
+ // attempt to set `manualJustification` — only this gate emits the
1168
+ // artifact, and a manual flag is by definition a forgery class.
1169
+ const unsignedBody = {
1170
+ timestamp: new Date().toISOString(),
1171
+ sessionId,
1172
+ deployPattern: deployMatched.name,
1173
+ command: cmdPreview,
1174
+ verify: verifyBody.trim().slice(0, 4000),
1175
+ cognition: cogBlockBody.trim().slice(0, 8000),
1176
+ substrateAnchors: anchorMatches.slice(0, 50),
1177
+ anchorCount,
1178
+ lensCount,
1179
+ verifyFieldsPresent: DEPLOY_VERIFY_REQUIRED_FIELDS
1180
+ .filter(({ rx }) => rx.test(verifyBody))
1181
+ .map(({ name }) => name),
1182
+ };
1183
+
1184
+ // HMAC-SHA256 over the canonical-JSON of the unsigned body.
1185
+ // canonical-JSON = JSON.stringify with no signature field, no
1186
+ // pretty-print whitespace, key order as written above.
1187
+ const signature = createHmac('sha256', secret)
1188
+ .update(JSON.stringify(unsignedBody))
1189
+ .digest('hex');
1190
+
1191
+ const justification = {
1192
+ ...unsignedBody,
1193
+ signature,
1194
+ signatureAlgo: 'HMAC-SHA256',
1195
+ };
1196
+ writeFileSync(justificationPath, JSON.stringify(justification, null, 2));
1197
+ } catch (writeErr) {
1198
+ // Write failure is non-fatal for the gate decision (the gate itself
1199
+ // is the structural enforcement); log loudly per
1200
+ // canonical-secrets-governance LOUD telemetry doctrine.
1201
+ console.error(
1202
+ `[aria-pre-tool-gate] WARN deploy-justification artifact write failed: ${(writeErr instanceof Error ? writeErr.message : String(writeErr)).slice(0, 200)}`,
1203
+ );
1204
+ }
1205
+ audit(
1206
+ `allow-deploy ${deployMatched.name} lenses=${lensCount} anchors=${anchorCount}`,
1207
+ cmdPreview,
1208
+ );
1209
+ pushDecision(
1210
+ 'allow',
1211
+ `verify+cognition+anchors(${anchorCount}) for deploy ${deployMatched.name}`,
1212
+ );
1213
+ process.exit(0);
1214
+ }
1215
+
1216
+ // Build a focused refusal naming exactly which piece is missing.
1217
+ const reasons = [];
1218
+ if (!hasVerify) reasons.push('missing <verify> block');
1219
+ if (!hasCognition) reasons.push(`missing <cognition> block (lenses=${lensCount}/${REQUIRED_LENSES})`);
1220
+ if (hasCognition && anchorCount < DEPLOY_MIN_SUBSTRATE_ANCHORS) {
1221
+ reasons.push(
1222
+ `cognition block has ${anchorCount}/${DEPLOY_MIN_SUBSTRATE_ANCHORS} substrate anchors (axiom:/frame:/memory:/doctrine:/packet:)`,
1223
+ );
1224
+ }
1225
+ if (missingDeployFields.length > 0) {
1226
+ reasons.push(`<verify> block missing required fields: ${missingDeployFields.join(', ')}`);
1227
+ }
1228
+
1229
+ const refusal = `Aria pre-tool gate: DEPLOY hard-block — pattern '${deployMatched.name}' detected.
1230
+
1231
+ Per feedback_deploy_requires_verify_cognition.md (Hamza directive 2026-04-28 after consciousness.ts crash took aria-soul into CrashLoopBackOff), every deploy command requires:
1232
+
1233
+ 1. A <verify> block in the recent assistant text containing AT MINIMUM:
1234
+ - target/role/verified/rollback/axiom (base verify fields)
1235
+ - commit hash or files-changed listing
1236
+ - tsc / build / type-check evidence
1237
+ - admission policy citation (kubectl get validatingadmissionpolicy <service>-canonical-image-policy)
1238
+
1239
+ 2. A <cognition> block with ≥${REQUIRED_LENSES} substantive lenses AND ≥${DEPLOY_MIN_SUBSTRATE_ANCHORS} substrate anchors total (axiom:<name> / frame:<name> / memory:<file> / doctrine:<rule> / packet:<section>).
1240
+
1241
+ Block reasons (this turn): ${reasons.join(' • ')}.
1242
+
1243
+ The 2026-04-28 deploy of an empty consciousness.ts crashed aria-soul because no verify-block step caught the missing export at substrate-citation time. This gate is the structural enforcement that prevents the same gap.
1244
+
1245
+ Re-emit verify+cognition with the missing pieces, then retry the deploy command. There is no env-var override path; doctrine #104 forbids it.`;
1246
+
1247
+ audit(
1248
+ `block-deploy ${deployMatched.name} verify=${hasVerify} cognition=${lensCount} anchors=${anchorCount} missing=${missingDeployFields.join(',')}`,
1249
+ cmdPreview,
1250
+ );
1251
+ pushDecision('block', `deploy ${deployMatched.name}: ${reasons.join('; ')}`);
1252
+ console.log(JSON.stringify({ decision: 'block', reason: refusal }));
1253
+ process.exit(2);
1254
+ }
1255
+
1256
+ if (matched) {
1257
+ // Destructive — require BOTH verify (from transcript) AND cognition
1258
+ // (inline command preferred; transcript fallback). Verify stays
1259
+ // transcript-only because it's about pre-action substrate
1260
+ // verification, not about the command's own thought.
1261
+ if (hasVerify && hasCognition) {
1262
+ audit(`allow-verified-cognition ${matched.name} lenses=${lensCount} via=${cognitionSource}`, cmdPreview);
1263
+ pushDecision('allow', `verified+cognition for ${matched.name} (${cognitionSource})`);
1264
+ process.exit(0);
1265
+ }
1266
+ // Block with appropriate corrective message.
1267
+ const reason = !hasVerify
1268
+ ? `Aria pre-tool gate: destructive pattern '${matched.name}' detected. ${IS_OWNER ? 'Per harness mizan_prestage_rule + axiom_runtime_rule (admit_ignorance, reflection_before_action), include' : 'Pre-action verification required — include'} a <verify> block in your assistant response BEFORE the tool call.
1269
+
1270
+ <verify>
1271
+ target: <exactly what is being changed>
1272
+ role: <what that target does — verified, not assumed>
1273
+ verified: <how you verified: tool output / file read / DB query / asked user>
1274
+ rollback: <exact command to reverse this change>
1275
+ axiom: <which harness rule applies>
1276
+ </verify>
1277
+
1278
+ Re-issue after producing the block. Bypass: '# doctrine-authorized: <reason>' inline..`
1279
+ : `Aria pre-tool gate: destructive pattern '${matched.name}' has its <verify> block, but the <cognition> block is missing or shows only ${lensCount}/${REQUIRED_LENSES}+ required lenses. Every non-trivial action requires visible 8-lens application.
1280
+
1281
+ <cognition>
1282
+ ${LENS_NAMES[0]}: <what you see plainly, specific to this task>
1283
+ ${LENS_NAMES[1]}: <what's out of proportion / risk profile>
1284
+ ${LENS_NAMES[2]}: <what memory or principle applies>
1285
+ ${LENS_NAMES[3]}: <deep structural read>
1286
+ ${LENS_NAMES[4]}: <if-then chain>
1287
+ ${LENS_NAMES[5]}: <distant connection>
1288
+ ${LENS_NAMES[6]}: <what just landed in this turn>
1289
+ ${LENS_NAMES[7]}: <what user actually needs>
1290
+ </cognition>
1291
+
1292
+ At least 4 substantive lenses required.`;
1293
+ audit(`block ${matched.name} verify=${hasVerify} cognition=${lensCount}`, cmdPreview);
1294
+ pushDecision('block', `destructive ${matched.name} missing ${!hasVerify ? 'verify' : 'cognition'}`);
1295
+ console.log(JSON.stringify({ decision: 'block', reason }));
1296
+ process.exit(2);
1297
+ }
1298
+
1299
+ // Non-trivial but not destructive — require cognition. For Bash the
1300
+ // inline-comment path is preferred (action-coupled). For Edit / Write /
1301
+ // NotebookEdit there's no command field, so transcript-scan cognition
1302
+ // is the only path.
1303
+ if (!hasCognition) {
1304
+ const isBash = toolName === 'Bash';
1305
+ const header = isBash
1306
+ ? `Aria pre-tool gate: non-trivial Bash command without ${REQUIRED_LENSES}+ substantive cognition lenses. Found ${lensCount}/${REQUIRED_LENSES}+ (inline=${inlineCog.count}, transcript=${transcriptCog.count}).`
1307
+ : `Aria pre-tool gate: ${toolName} call without ${REQUIRED_LENSES}+ substantive cognition lenses in the recent transcript. Found ${lensCount}/${REQUIRED_LENSES}+ (transcript-scan only — ${toolName} has no inline-cognition path).`;
1308
+
1309
+ const guidance = isBash
1310
+ ? `REQUIRED — cognition for every action, no exceptions. Two equivalent forms; either satisfies the gate (both equally REQUIRED, neither preferred over the other):
1311
+
1312
+ FORM 1 (inline in command — action-coupled, recommended for Bash):
1313
+ # ${LENS_NAMES[0]}: <real perception, ≥${SUBSTANCE_MIN_CHARS} chars, no <placeholder>>
1314
+ # ${LENS_NAMES[1]}: <real risk read>
1315
+ # ${LENS_NAMES[2]}: <what principle applies>
1316
+ # ${LENS_NAMES[3]}: <deep structural read>
1317
+ <your actual command here>
1318
+
1319
+ FORM 2 (cognition block in assistant text):
1320
+ <cognition>...</cognition> with ${REQUIRED_LENSES}+ substantive lenses, ≥${SUBSTANCE_MIN_CHARS} chars per lens, no placeholder values.
1321
+
1322
+ Both forms count toward the ${REQUIRED_LENSES}+ requirement; gate counts inline + transcript lenses additively. Substance check is non-negotiable — placeholder/short content does not count.`
1323
+ : `Emit a <cognition>...</cognition> block in your assistant text BEFORE this ${toolName} call, with ${REQUIRED_LENSES}+ substantive lenses. Substance check: each lens must have ≥${SUBSTANCE_MIN_CHARS} chars of non-placeholder content. Cognition is turn-scoped — one block at the start of a turn covers all ${toolName} calls in that turn.
1324
+
1325
+ <cognition>
1326
+ ${LENS_NAMES[0]}: <what you see plainly, specific to this edit>
1327
+ ${LENS_NAMES[1]}: <what's out of proportion — what could this overwrite or break?>
1328
+ ${LENS_NAMES[2]}: <what principle applies (name the source)>
1329
+ ${LENS_NAMES[3]}: <deep structural read>
1330
+ ${LENS_NAMES[4]}: <if-then chain — what follows from this edit>
1331
+ ${LENS_NAMES[5]}: <distant connection a less-careful editor would miss>
1332
+ ${LENS_NAMES[6]}: <what just landed in this turn that justifies this edit>
1333
+ ${LENS_NAMES[7]}: <what user actually needs underneath>
1334
+ </cognition>`;
1335
+
1336
+ const reason = `${header}
1337
+
1338
+ ${guidance}
1339
+
1340
+ No per-tool bypass available (v3 doctrine — the harness's whole purpose is no exceptions). No env-var disable path — gates are unconditional from the gated process per Hamza directive 2026-04-27. If the gate misfires on legitimate cognition, fix the gate.`;
1341
+
1342
+ audit(`block ${toolName.toLowerCase()} cognition=${lensCount}`, cmdPreview);
1343
+ pushDecision('block', `${toolName.toLowerCase()} missing cognition (${lensCount}/${REQUIRED_LENSES})`);
1344
+ console.log(JSON.stringify({ decision: 'block', reason }));
1345
+ process.exit(2);
1346
+ }
1347
+
1348
+ // Discovery-binding cognition check (structural fix #3) — runs AFTER lens
1349
+ // count passes. If the cognition surfaced a defect (found/noticed/discovered
1350
+ // + bug/broken/issue) without a paired resolution clause, block until the
1351
+ // cognition is updated to bind the discovery to a same-turn fix or task ID.
1352
+ // Per feedback_no_flag_without_fix.md, discoveries are atomic with their
1353
+ // fixes. The pre-tool-gate enforces at the cognition surface; stop-gate's
1354
+ // ledger enforces at the output surface.
1355
+ if (discoveryUnresolved) {
1356
+ const reason = `Aria pre-tool gate: cognition surfaces a discovery (defect, bug, doctrine violation, broken state) but does NOT include a resolution clause binding the discovery to action.
1357
+
1358
+ Per ${docRef('feedback_no_flag_without_fix.md', 'atomic-discovery-rule')}: discoveries are atomic with their fixes. Flag-and-move-on is convenience-seeking — the user has to track what you noticed vs. what you actually fixed.
1359
+
1360
+ Re-emit cognition with one of these resolution forms:
1361
+
1362
+ discoveries:
1363
+ - <what you found>: <fix-now | task: TASK-123 | needs-user-decision>
1364
+
1365
+ OR inline within an existing lens:
1366
+ ${LENS_NAMES[2]}: ... fixing inline this turn (same-turn-fix per atomic-discovery-rule).
1367
+ ${LENS_NAMES[3]}: ... TaskCreate'd as TASK-XXX with full context (file path, line, what's broken).
1368
+
1369
+ Acceptable resolution markers: 'discoveries:' / 'addressing:' / 'fixing:' / 'TaskCreate' / 'tracked as #N' / 'linear issue' / 'fix-now' / 'same-turn fix'.
1370
+
1371
+ No env-var disable path — gates are unconditional from the gated process per Hamza directive 2026-04-27. If gate misfires on legitimate cognition, fix the gate.`;
1372
+
1373
+ audit(`block-discovery-unresolved ${toolName.toLowerCase()}`, cmdPreview);
1374
+ pushDecision('block', `${toolName.toLowerCase()} cognition has unresolved discovery`);
1375
+ console.log(JSON.stringify({ decision: 'block', reason }));
1376
+ process.exit(2);
1377
+ }
1378
+
1379
+ // ── Dalio expected_outcome gate ──────────────────────────────────────────────
1380
+ //
1381
+ // Every non-trivial action must carry an <expected> block with at least one
1382
+ // measurable predicate. Block is read from the same turn-scoped assistant text
1383
+ // window as cognition (unionText). Qualitative drift phrases are rejected even
1384
+ // when they appear inside an <expected> block.
1385
+ //
1386
+ // Hard-block path: block the tool call, name the missing block, cite doctrine.
1387
+ // Per feedback_no_graceful_degradation.md — never silent-pass.
1388
+ {
1389
+ const expectedMatch = unionText.match(EXPECTED_BLOCK_RX);
1390
+ const expectedBlockText = expectedMatch ? expectedMatch[1] : '';
1391
+ const hasMeasurablePredicate = expectedBlockText
1392
+ ? (MEASURABLE_PREDICATE_RX.test(expectedBlockText) && !QUALITATIVE_DRIFT_RX.test(expectedBlockText))
1393
+ : false;
1394
+
1395
+ if (!expectedMatch || !hasMeasurablePredicate) {
1396
+ const reason = expectedMatch
1397
+ ? `Aria pre-tool gate: action requires a measurable predicate inside <expected> per doctrine:dalio_expected_required.
1398
+
1399
+ Your <expected> block was found but contains only qualitative drift phrases (e.g. "better", "improved", "should work", "more reliable") without a concrete measurable predicate. These are unmeasurable and defeat the Dalio accountability loop.
1400
+
1401
+ Replace with one of:
1402
+ • Numeric: exit_code==0, latency<200ms, count>=1, error_rate=0%
1403
+ • Boolean: exit=0, status=healthy, file=exists, rc=0
1404
+ • State-string: "status=running", "200 OK", "count=3 of 3 passed"
1405
+
1406
+ <expected>
1407
+ predicate: exit_code==0 AND file=/home/hamzaibrahim1/.foo written
1408
+ measurable_type: boolean
1409
+ threshold: 0
1410
+ eval_window_minutes: 1
1411
+ </expected>
1412
+
1413
+ No bypass — doctrine:dalio_expected_required is unconditional for non-trivial actions.`
1414
+ : `Aria pre-tool gate: action requires an <expected> block with measurable predicate per doctrine:dalio_expected_required.
1415
+
1416
+ Every non-trivial action must state WHAT MEASURABLE STATE the action is expected to produce, so the stop-gate can compare predicted vs actual outcome and write a Dalio ledger entry.
1417
+
1418
+ Required format (add to your assistant turn before this tool call):
1419
+
1420
+ <expected>
1421
+ predicate: <concrete measurable assertion — e.g. "exit_code==0", "status=running", "count>=1">
1422
+ measurable_type: numeric | boolean | state_string
1423
+ threshold: <optional — the exact boundary, e.g. 0 or "healthy">
1424
+ eval_window_minutes: <optional — how long before this expires, e.g. 5>
1425
+ </expected>
1426
+
1427
+ Accepted predicates:
1428
+ • Numeric: >=X, <=X, ==X, X%, count=N, latency<Xms, error_rate=0%
1429
+ • Boolean: exit=0, exit=1, true, false, file=exists, status=healthy
1430
+ • State-string: "status=running", "200 OK", "exit=0", "no_error"
1431
+
1432
+ REJECTED (qualitative drift): "better", "improved", "should work", "more reliable", "cleaner"
1433
+
1434
+ No bypass — doctrine:dalio_expected_required is unconditional for non-trivial actions per feedback_implementation_coupled_cognition.md.`;
1435
+
1436
+ audit(`block-expected-missing ${toolName.toLowerCase()}`, cmdPreview);
1437
+ pushDecision('block', `${toolName.toLowerCase()} missing <expected> measurable predicate`);
1438
+ console.log(JSON.stringify({ decision: 'block', reason }));
1439
+ process.exit(2);
1440
+ }
1441
+ }
1442
+
1443
+ // ── Sub-agent packet-citation check (Layer 4 — #84) ─────────────────────────
1444
+ //
1445
+ // When running inside a sub-agent process (detected by a non-stale handoff file
1446
+ // existing AND harnessPacketPath is set in that handoff), require the cognition
1447
+ // lens content to CITE THE PACKET — at least one of:
1448
+ // - A doctrine rule ID (e.g. "doctrine_first", "no_demos", "workaround_vs_path_fix")
1449
+ // - An axiom name (e.g. "truth_over_deception", "no_harm", "sacred_trust", "reflection_before_action")
1450
+ // - A frame primitive (e.g. "Fitrah", "Tafakkur", "Tadabbur", "Ilham", "Mizan", "Hikma", "Nur", "Wahi", "Firasah")
1451
+ // - A memory class reference (e.g. "feedback_*.md", "project_*.md", "reference_*.md")
1452
+ //
1453
+ // Owner-tier sessions (ownerTier.hamza === true AND no jti) are EXEMPT —
1454
+ // they are the source of truth for the packet itself.
1455
+ //
1456
+ // Fail-soft detection: handoff read errors silently skip this check.
1457
+ (function checkSubAgentPacketCitation() {
1458
+ const _HOME = process.env.HOME || '/tmp';
1459
+ // Try owner-tier handoff path first, then client-tier paths.
1460
+ const HANDOFF_TTL_MS = 5 * 60 * 1000;
1461
+ // Probe known handoff paths.
1462
+ const candidatePaths = [
1463
+ `${_HOME}/.claude/aria-agent-harness-handoff.json`,
1464
+ ];
1465
+ // Also check /var/lib/aria-licensee if that dir exists (client-tier).
1466
+ try {
1467
+ const licPath = `${_HOME}/.aria/license.json`;
1468
+ if (existsSync(licPath)) {
1469
+ const lic = JSON.parse(readFileSync(licPath, 'utf8'));
1470
+ if (lic.jti) {
1471
+ candidatePaths.push(`/var/lib/aria-licensee/${lic.jti}/handoff.json`);
1472
+ }
1473
+ }
1474
+ } catch { /* non-fatal */ }
1475
+
1476
+ let handoff = null;
1477
+ for (const hp of candidatePaths) {
1478
+ if (!existsSync(hp)) continue;
1479
+ try {
1480
+ const raw = JSON.parse(readFileSync(hp, 'utf8'));
1481
+ const ageMs = Date.now() - new Date(raw.writtenAt || 0).getTime();
1482
+ if (ageMs > HANDOFF_TTL_MS) continue; // stale handoff — not a sub-agent context
1483
+ if (!raw.harnessPacketPath) continue; // no packet path written → identity-only handoff, skip check
1484
+ handoff = raw;
1485
+ break;
1486
+ } catch { /* malformed — skip */ }
1487
+ }
1488
+
1489
+ if (!handoff) return; // not a sub-agent context, or handoff has no packetPath
1490
+
1491
+ // Owner-tier exemption: if ownerTier.hamza === true AND no jti → source of truth
1492
+ const ownerExempt = (handoff.ownerTier?.hamza === true) && !handoff.ownerTier?.jti;
1493
+ if (ownerExempt) return;
1494
+
1495
+ // Now verify that the cognition block cites at least one packet substrate token.
1496
+ // Tokens accepted (case-insensitive):
1497
+ // • Doctrine rule IDs from feedback_*/project_*/reference_* filenames
1498
+ // • Axiom names: truth_over_deception, no_harm, sacred_trust, reflection_before_action
1499
+ // • Frame primitives: Fitrah, Tafakkur, Tadabbur, Ilham, Mizan, Hikma, Nur, Wahi, Firasah
1500
+ // • Memory class patterns: feedback_*.md, project_*.md, reference_*.md
1501
+ const PACKET_CITE_RX = /\b(?:feedback_[a-z0-9_]+\.md|project_[a-z0-9_]+\.md|reference_[a-z0-9_]+\.md|doctrine_first|no_demos|workaround_vs_path_fix|no_flag_without_fix|implementation_coupled_cognition|session_starts_with_linear|gates_enforce_form_not_substance|truth_over_deception|no_harm|sacred_trust|reflection_before_action|power_obligates_service|fitrah|tafakkur|tadabbur|ilham|mizan|hikma|nur|wahi|firasah|harness\s*packet)\b/i;
1502
+
1503
+ const cogText = cogBlockBody || unionText;
1504
+ const hasCite = PACKET_CITE_RX.test(cogText) || PACKET_CITE_RX.test(cmd);
1505
+
1506
+ if (!hasCite) {
1507
+ const packetRef = handoff.harnessPacketPath;
1508
+ const reason = `Sub-agent cognition cites no packet substrate — lens content must reference at least one axiom/frame/memory/doctrine from the harness packet at ${packetRef}.
1509
+
1510
+ Accepted citations (case-insensitive, any ONE suffices):
1511
+ • Doctrine rule IDs: doctrine_first, no_demos, workaround_vs_path_fix, no_flag_without_fix, etc.
1512
+ • Axioms: truth_over_deception, no_harm, sacred_trust, reflection_before_action, power_obligates_service
1513
+ • Frame primitives: Fitrah, Tafakkur, Tadabbur, Ilham, Mizan, Hikma, Nur, Wahi, Firasah
1514
+ • Memory class refs: feedback_*.md, project_*.md, reference_*.md
1515
+
1516
+ The harness packet is at: ${packetRef}
1517
+ Read it first (it is in your environment as ARIA_HARNESS_PACKET_PATH), then reference it in your cognition block.
1518
+
1519
+ Cognition-theater rejected per feedback_gates_enforce_form_not_substance.md.`;
1520
+ audit(`block-subagent-no-packet-cite ${toolName.toLowerCase()}`, cmdPreview);
1521
+ console.log(JSON.stringify({ decision: 'block', reason }));
1522
+ process.exit(2);
1523
+ }
1524
+ })();
1525
+
1526
+ // ── arch_facts gate (architectural violation scan) ────────────────────────
1527
+ //
1528
+ // Runs after cognition + discovery-binding pass, for Edit/Write/NotebookEdit.
1529
+ // Bash is skipped: architectural violations live in the code being written,
1530
+ // not in shell commands — checking Bash commands would produce false positives
1531
+ // on grep/find invocations that mention forbidden strings without introducing them.
1532
+ //
1533
+ // Content inspected: new_string (Edit), content (Write), source (NotebookEdit).
1534
+ // Fail-open: unreachable mizan → allow. Client surface → skip.
1535
+ if (['Edit', 'Write', 'NotebookEdit'].includes(toolName)) {
1536
+ // Extract the actual content being written — this is what mizan should scan
1537
+ // for architectural patterns, not the file path or surrounding metadata.
1538
+ const contentToScan =
1539
+ toolInput.new_string ?? // Edit: the replacement text
1540
+ toolInput.content ?? // Write: the full file content
1541
+ toolInput.source ?? // NotebookEdit: cell source
1542
+ '';
1543
+ // Also include file_path for context so mizan pattern-matching can be
1544
+ // path-scoped (e.g. R9 only fires for telemetry/cron paths).
1545
+ const scanPayload = `// file: ${filePath}\n${contentToScan}`;
1546
+ const archResult = await archFactsGate(scanPayload);
1547
+ if (!archResult.allow) {
1548
+ const violationText = (archResult.violations || [])
1549
+ .map((v) => ` • [${v.rule ?? v.id ?? 'arch'}] ${v.description ?? v.message ?? JSON.stringify(v)}`)
1550
+ .join('\n');
1551
+ const archReason = `Aria arch_facts gate: architectural violation(s) detected in ${toolName} diff for ${filePath || '(no path)'}.
1552
+
1553
+ ${violationText}
1554
+
1555
+ These patterns are forbidden by mizan arch_facts rules (mizan.yaml R7–R11). Fix the structural issue before re-issuing the tool call — the gate does not have a bypass for architectural violations.
1556
+
1557
+ Rule references:
1558
+ R7 no_sidecar_in_main_container — bolt-in fork pattern (project_aria_soul_systemd_migration.md)
1559
+ R8 no_silent_fallback_default — || 'unknown'/'default'/'fallback' masks config failures
1560
+ R9 no_timeout_based_retry — setTimeout+abort in telemetry/chat/cron paths (no-timeouts doctrine)
1561
+ R10 no_kubectl_apply_for_image_drift — kubectl apply on aria-soul-stateful (project_forge_psi_oom_cascade.md)
1562
+ R11 no_console_log_secrets — console.log with TOKEN/PASSWORD/SECRET/API_KEY/JWT/BEARER`;
1563
+ audit(`block-arch-facts ${toolName.toLowerCase()} path=${filePath}`, `violations=${archResult.violations?.length ?? 0}`);
1564
+ console.log(JSON.stringify({ decision: 'block', reason: archReason }));
1565
+ process.exit(2);
1566
+ }
1567
+ }
1568
+
1569
+ // Non-trivial action with cognition (inline for Bash, transcript for
1570
+ // Edit/Write/NotebookEdit) — passes cognition gate. Now check Aria-binding.
1571
+
1572
+ // ── Aria-as-commander binding check (Layer A) ──
1573
+ //
1574
+ // All earlier gate checks passed (cognition, destructive-verify). Final
1575
+ // gate before allow: does the active phase of Aria's plan permit this action?
1576
+ // No plan + no prior plan = block (CONSULT_UNAVAILABLE per contract).
1577
+ // No plan + prior plan exists = enforce against prior (Hamza fallback directive).
1578
+ // Plan exists + action mismatch = block with phase-violation reason.
1579
+ //
1580
+ // Bootstrap consult carve-out (Hamza 2026-04-27 caught this — "how would
1581
+ // anyone start a session?"): consult endpoints are how plans START existing.
1582
+ // Locking them behind plan-existence is unbootstrappable. So: if the action
1583
+ // is a consult to harness/aria endpoints (regardless of plan state), skip the
1584
+ // binding block. Cognition gate above already passed; the consult itself
1585
+ // will issue the next plan on completion. Audited per-use.
1586
+ //
1587
+ // bindingBypassReason: per-command bypass was removed in v3. The variable is
1588
+ // kept as a fixed null so the binding check below reads cleanly without a
1589
+ // ReferenceError. No new bypass entries can be created (pre-existing defect
1590
+ // fixed inline per atomic-discovery-rule).
1591
+ const bindingBypassReason = null;
1592
+
1593
+ // Defect #4 fix — Consult-Aria unconditionally allowed (doctrine #50).
1594
+ //
1595
+ // Aria-as-commander session pattern (HARNESS_ARIA_AS_COMMANDER_CONTRACT.md
1596
+ // doctrine #50) makes per-turn consult mandatory. A plan cannot forbid the
1597
+ // consult mechanism that issues plans — that would be an unbootstrappable
1598
+ // circular lock. Previously plan p1 forbade bash_other → consult curl was
1599
+ // classified as bash_other → blocked. Now: any Bash command that is a consult
1600
+ // to a known Aria/harness endpoint passes UNCONDITIONALLY past ALL binding
1601
+ // checks regardless of allowedActions or forbiddenActions in the active phase.
1602
+ // Cognition gate still applies (it ran above and passed to reach this point).
1603
+ //
1604
+ // Covered endpoints (hardcoded carve-out):
1605
+ // curl http(s)://aria-soul<anything>
1606
+ // curl http(s)://aria-telemetry<anything>
1607
+ // curl http(s)://localhost:30080/(chat|api/aria/speak|api/harness/codex|
1608
+ // api/harness/verify-claim|v1/doctrine|v1/mizan)
1609
+ const ARIA_CONSULT_CURL_RX = /curl\s+['"]?https?:\/\/(?:aria-soul[^\s'"]*|aria-telemetry[^\s'"]*|localhost:30080\/(?:chat|api\/aria\/speak|api\/harness\/(?:codex|verify-claim|delegate|army|plan)|v1\/(?:doctrine|mizan))[^\s'"]*)/i;
1610
+ const __isUnconditionalConsult = toolName === 'Bash' && ARIA_CONSULT_CURL_RX.test(cmd);
1611
+ if (__isUnconditionalConsult) {
1612
+ bindingAuditAppend({ event: 'allow_unconditional_consult', sessionId, toolName, cmdPreview, reason: 'doctrine#50-aria-as-commander-consult-carveout' });
1613
+ audit(`allow-unconditional-consult lenses=${lensCount}`, cmdPreview);
1614
+ pushDecision('allow', 'unconditional consult carve-out (doctrine #50)');
1615
+ process.exit(0);
1616
+ }
1617
+
1618
+ const __bindingActionClassification = (BINDING_ENABLED && !bindingBypassReason)
1619
+ ? classifyToolForBinding(toolName, cmd, filePath)
1620
+ : null;
1621
+ const __isBootstrapConsult = __bindingActionClassification?.action === 'consult';
1622
+ if (__isBootstrapConsult) {
1623
+ bindingAuditAppend({ event: 'allow_bootstrap_consult', sessionId, target: __bindingActionClassification.target, toolName });
1624
+ }
1625
+ if (BINDING_ENABLED && !bindingBypassReason && !__isBootstrapConsult) {
1626
+ let plan = loadActivePlan(sessionId);
1627
+ if (!plan) {
1628
+ // INLINE architect-fallback (Hamza directive 2026-04-27 — no async stop-gate
1629
+ // races). When no plan exists, fire architect-fallback synchronously here
1630
+ // so a real plan is minted and loaded inside the same hook execution. If
1631
+ // architect-fallback fails the gate still BLOCKS per doctrine (no bypass)
1632
+ // but the block message includes the architect-fallback exit details so the
1633
+ // failure is visible LOUDLY per feedback_no_graceful_degradation.md.
1634
+ bindingAuditAppend({ event: 'no_plan_inline_fallback_attempt', sessionId, toolName });
1635
+ const blockerReason = `pre-tool-gate inline fallback: no active plan for session ${sessionId} when ${toolName} was attempted on ${cmdPreview.slice(0, 200)}`;
1636
+ const fallbackEvent = JSON.stringify({ reason: blockerReason, sessionId, toolName, currentPlanId: 'none' });
1637
+ let architectExit = -1;
1638
+ let architectStderr = '';
1639
+ try {
1640
+ const archProc = spawnSync(process.execPath, [`${HOME}/.claude/hooks/aria-architect-fallback.mjs`], {
1641
+ input: fallbackEvent,
1642
+ encoding: 'utf8',
1643
+ timeout: 60000,
1644
+ });
1645
+ architectExit = archProc.status ?? -1;
1646
+ architectStderr = (archProc.stderr || '').slice(0, 500);
1647
+ } catch (err) {
1648
+ architectStderr = String(err).slice(0, 500);
1649
+ }
1650
+ bindingAuditAppend({ event: 'architect_fallback_result', sessionId, exit: architectExit, stderr: architectStderr.slice(0, 300) });
1651
+
1652
+ plan = loadActivePlan(sessionId);
1653
+ if (plan) {
1654
+ process.stderr.write(`\n✓ PRE-TOOL-GATE FALLBACK: architect-fallback minted plan ${plan.planId}. Continuing.\n`);
1655
+ bindingAuditAppend({ event: 'architect_fallback_minted_plan', sessionId, planId: plan.planId });
1656
+ } else {
1657
+ bindingAuditAppend({ event: 'block_no_active_plan_after_fallback', sessionId, toolName, architectExit });
1658
+ const reason = `Aria binding gate: no active plan exists AND inline architect-fallback failed (exit=${architectExit}). Plan-mint chain broken. ${architectStderr ? 'Architect stderr: ' + architectStderr : ''}
1659
+
1660
+ What Claude must do:
1661
+ 1. Acknowledge to Hamza that the architect-fallback chain failed (visible in audit log)
1662
+ 2. Surface the failure LOUDLY — this is a substrate-level break, not a routine consult miss
1663
+ 3. Wait for next user prompt — preprompt-consult will retry; if it succeeds a plan will exist on next tool call
1664
+
1665
+ Non-trivial actions are blocked until a plan exists. Trivial reads (ls/cat/grep) bypass automatically per existing whitelist. To temporarily disable binding for emergency: ARIA_BINDING_ENABLED=false (logged).`;
1666
+ console.log(JSON.stringify({ decision: 'block', reason }));
1667
+ process.exit(2);
1668
+ }
1669
+ }
1670
+
1671
+ const transcriptText = unionText || '';
1672
+ let phaseInfo = pickCurrentPhase(plan, transcriptText);
1673
+
1674
+ if (!phaseInfo) {
1675
+ // All phases reported complete — needs new consult before more action
1676
+ bindingAuditAppend({ event: 'block_all_phases_complete', sessionId, planId: plan.planId, toolName });
1677
+ const reason = `Aria binding gate: all phases of plan ${plan.planId} have been reported complete in this transcript. The plan is exhausted; Claude cannot proceed without a fresh consult.
1678
+
1679
+ What Claude must do:
1680
+ 1. Acknowledge plan completion to Hamza
1681
+ 2. Wait for next user prompt — preprompt-consult will issue a new plan
1682
+ 3. Don't continue executing actions beyond the issued plan boundary
1683
+
1684
+ This prevents Claude from drifting past Aria's authorized scope.`;
1685
+ console.log(JSON.stringify({ decision: 'block', reason }));
1686
+ process.exit(2);
1687
+ }
1688
+
1689
+ if (phaseInfo.abortedHere) {
1690
+ // INLINE architect-fallback (Hamza directive 2026-04-27 — same recovery as
1691
+ // no-plan branch above). When phase is aborted, fire architect-fallback
1692
+ // synchronously here to mint a fresh plan instead of deadlocking. If
1693
+ // architect-fallback fails the gate still BLOCKS per doctrine but the
1694
+ // failure is LOUD per feedback_no_graceful_degradation.md.
1695
+ bindingAuditAppend({ event: 'phase_aborted_inline_fallback_attempt', sessionId, planId: plan.planId, phaseId: phaseInfo.phase.id, toolName });
1696
+ const blockerReason = `pre-tool-gate inline fallback: phase ${phaseInfo.phase.id} of plan ${plan.planId} aborted, ${toolName} attempted on ${cmdPreview.slice(0, 200)}`;
1697
+ const fallbackEvent = JSON.stringify({ reason: blockerReason, sessionId, toolName, currentPlanId: plan.planId });
1698
+ let architectExit = -1;
1699
+ let architectStderr = '';
1700
+ try {
1701
+ const archProc = spawnSync(process.execPath, [`${HOME}/.claude/hooks/aria-architect-fallback.mjs`], {
1702
+ input: fallbackEvent,
1703
+ encoding: 'utf8',
1704
+ timeout: 60000,
1705
+ });
1706
+ architectExit = archProc.status ?? -1;
1707
+ architectStderr = (archProc.stderr || '').slice(0, 500);
1708
+ } catch (err) {
1709
+ architectStderr = String(err).slice(0, 500);
1710
+ }
1711
+ bindingAuditAppend({ event: 'aborted_phase_architect_fallback_result', sessionId, exit: architectExit, stderr: architectStderr.slice(0, 300) });
1712
+
1713
+ const freshPlan = loadActivePlan(sessionId);
1714
+ if (freshPlan && freshPlan.planId !== plan.planId) {
1715
+ process.stderr.write(`\n✓ PRE-TOOL-GATE FALLBACK: aborted phase recovered, fresh plan ${freshPlan.planId} minted. Continuing.\n`);
1716
+ bindingAuditAppend({ event: 'aborted_phase_recovered', sessionId, oldPlanId: plan.planId, newPlanId: freshPlan.planId });
1717
+ plan = freshPlan;
1718
+ const freshPhaseInfo = pickCurrentPhase(plan, transcriptText);
1719
+ if (!freshPhaseInfo || freshPhaseInfo.abortedHere) {
1720
+ bindingAuditAppend({ event: 'block_aborted_phase_post_fallback_still_bad', sessionId, planId: plan.planId });
1721
+ const reason = `Aria binding gate: aborted phase recovery minted plan ${plan.planId} but new plan also has no usable phase. Manual intervention required.`;
1722
+ console.log(JSON.stringify({ decision: 'block', reason }));
1723
+ process.exit(2);
1724
+ }
1725
+ phaseInfo = freshPhaseInfo;
1726
+ } else {
1727
+ bindingAuditAppend({ event: 'block_phase_aborted_fallback_failed', sessionId, planId: plan.planId, phaseId: phaseInfo.phase.id, architectExit });
1728
+ const reason = `Aria binding gate: phase ${phaseInfo.phase.id} of plan ${plan.planId} was reported aborted AND inline architect-fallback failed (exit=${architectExit}). Plan progression halted. ${architectStderr ? 'Architect stderr: ' + architectStderr : ''}
1729
+
1730
+ What Claude must do: emit [PLAN_BLOCKER reason="<concrete observation>" suggestedAmendment="<if any>"] for Hamza/Aria to issue a corrected plan. Do not continue executing the aborted plan.`;
1731
+ console.log(JSON.stringify({ decision: 'block', reason }));
1732
+ process.exit(2);
1733
+ }
1734
+ }
1735
+
1736
+ const { action, target } = classifyToolForBinding(toolName, cmd, filePath);
1737
+ const phase = phaseInfo.phase;
1738
+
1739
+ // Forbidden takes precedence
1740
+ const forbidden = (phase.forbiddenActions || []).find((p) => actionMatchesPattern(action, p, target));
1741
+ if (forbidden) {
1742
+ bindingAuditAppend({ event: 'block_forbidden_action', sessionId, planId: plan.planId, phaseId: phase.id, action, target, matchedRule: forbidden });
1743
+ // Hive recipe lookup BEFORE emitting the block — if the same shape has
1744
+ // fired before, surface the recipe inline. Lookup is fail-soft: a probe
1745
+ // failure leaves the block message unchanged.
1746
+ const lookup = await lookupBlockPatternRecipe({
1747
+ detectorClass: 'doctrine_violation',
1748
+ signature: `binding-forbidden::action=${action}::matches=${forbidden}`,
1749
+ tenantId: sessionId,
1750
+ });
1751
+ const recipeAddendum = renderRecipeAddendum(lookup);
1752
+ const reason = `Aria binding gate: action "${action}" on target "${target}" matches forbidden pattern "${forbidden}" for current phase ${phase.id} ("${phase.summary}") of plan ${plan.planId}.
1753
+
1754
+ Phase summary: ${phase.summary}
1755
+ Forbidden actions for this phase: ${(phase.forbiddenActions || []).join(', ') || '(none)'}
1756
+ Allowed actions for this phase: ${(phase.allowedActions || []).join(', ') || '(none)'}
1757
+
1758
+ Claude must either: (a) reframe the action to fit allowedActions, OR (b) emit [PLAN_BLOCKER reason="..."] requesting Aria amend the plan.${recipeAddendum}`;
1759
+ console.log(JSON.stringify({ decision: 'block', reason }));
1760
+ process.exit(2);
1761
+ }
1762
+
1763
+ const allowed = (phase.allowedActions || []).find((p) => actionMatchesPattern(action, p, target));
1764
+ if (!allowed) {
1765
+ bindingAuditAppend({ event: 'block_action_not_in_allowed_list', sessionId, planId: plan.planId, phaseId: phase.id, action, target });
1766
+ const lookup = await lookupBlockPatternRecipe({
1767
+ detectorClass: 'doctrine_violation',
1768
+ signature: `binding-not-allowed::action=${action}::phase=${phase.id}`,
1769
+ tenantId: sessionId,
1770
+ });
1771
+ const recipeAddendum = renderRecipeAddendum(lookup);
1772
+ const reason = `Aria binding gate: action "${action}" on target "${target}" is NOT in allowedActions for current phase ${phase.id} of plan ${plan.planId}.
1773
+
1774
+ Phase summary: ${phase.summary}
1775
+ Allowed actions: ${(phase.allowedActions || []).join(', ') || '(none — phase is observation-only)'}
1776
+
1777
+ Claude must either: (a) reframe action to fit allowedActions, OR (b) emit [PLAN_BLOCKER reason="..."] for plan amendment.${recipeAddendum}`;
1778
+ console.log(JSON.stringify({ decision: 'block', reason }));
1779
+ process.exit(2);
1780
+ }
1781
+
1782
+ bindingAuditAppend({ event: 'allow_phase_action', sessionId, planId: plan.planId, phaseId: phase.id, action, target });
1783
+ }
1784
+
1785
+ // ── Outcome Ledger regression flag (fail-soft) ───────────────────────────────
1786
+ //
1787
+ // Before allowing, query aria_outcome_ledger for recent regressions on the same
1788
+ // action shape. This is NOT a block — it's a soft-warning surfaced to stderr so
1789
+ // the agent can see the risk and decide whether the root cause has shipped.
1790
+ //
1791
+ // action_kind: 'edit' for Edit/Write/NotebookEdit, 'bash' for Bash
1792
+ // action_target: file path for file tools; first word of bash command otherwise
1793
+ //
1794
+ // Fail-open: network errors, timeouts, or non-200 responses are silently ignored.
1795
+ // The gate does not hardcode timeouts (no-timeouts doctrine); the 3s AbortController
1796
+ // is a DETECTION PROBE — if the endpoint is alive it will respond quickly; if it
1797
+ // is down the catch path fail-opens without blocking the developer.
1798
+ (async function checkOutcomeLedger() {
1799
+ const _harnessUrl =
1800
+ process.env.ARIA_HIVE_RUNTIME_URL ||
1801
+ process.env.ARIA_HARNESS_BASE_URL ||
1802
+ process.env.ARIA_HARNESS_URL ||
1803
+ 'https://harness.ariasos.com';
1804
+ const _harnessToken = process.env.ARIA_HARNESS_TOKEN || '';
1805
+
1806
+ // Derive action_kind and action_target from current tool call
1807
+ let _actionKind = 'bash';
1808
+ let _actionTarget = '';
1809
+ if (toolName === 'Edit' || toolName === 'Write' || toolName === 'NotebookEdit') {
1810
+ _actionKind = 'edit';
1811
+ _actionTarget = filePath;
1812
+ } else if (toolName === 'Bash') {
1813
+ _actionKind = 'bash';
1814
+ // First word of the command (the verb) as the shape key
1815
+ _actionTarget = cmd.trim().split(/\s+/)[0] || '';
1816
+ // If the command touches a specific file path, prefer that as target
1817
+ // (captures edit-like bash operations: sed, awk, tee, etc.)
1818
+ const _fileArgMatch = cmd.match(/\b([\w./~-]+\.[a-z]{2,6})\b/i);
1819
+ if (_fileArgMatch) _actionTarget = _fileArgMatch[1];
1820
+ }
1821
+
1822
+ if (!_actionTarget) return; // nothing useful to query
1823
+
1824
+ try {
1825
+ const _ctl = new AbortController();
1826
+ const _probeTimer = setTimeout(() => _ctl.abort(), 3000);
1827
+ let _resp;
1828
+ try {
1829
+ const _params = new URLSearchParams({ action_kind: _actionKind, action_target: _actionTarget });
1830
+ _resp = await fetch(`${_harnessUrl}/api/harness/outcome-recent-regressions?${_params}`, {
1831
+ method: 'GET',
1832
+ headers: {
1833
+ 'Content-Type': 'application/json',
1834
+ ...(_harnessToken ? { Authorization: `Bearer ${_harnessToken}` } : {}),
1835
+ },
1836
+ signal: _ctl.signal,
1837
+ });
1838
+ } finally {
1839
+ clearTimeout(_probeTimer);
1840
+ }
1841
+
1842
+ if (!_resp || !_resp.ok) return; // endpoint unreachable or error — fail-open
1843
+ const _data = await _resp.json();
1844
+ const _regressions = Array.isArray(_data?.regressions) ? _data.regressions : [];
1845
+
1846
+ if (_regressions.length > 0) {
1847
+ // Soft-warning to stderr — visible in Claude Code's hook output but does NOT block
1848
+ const _lines = _regressions.map(
1849
+ (r) => ` - ${r.action_target} at ${new Date(r.created_at).toISOString()}: ${r.regression_signal || '(no signal text)'}`,
1850
+ ).join('\n');
1851
+ process.stderr.write(
1852
+ `⚠️ Aria Outcome Ledger: this action shape regressed ${_regressions.length} time(s) in the last 60 min:\n` +
1853
+ `${_lines}\n` +
1854
+ `Re-emitting with this risk visible. Proceed only if root cause has shipped since.\n`,
1855
+ );
1856
+ audit(`warn-ledger-regression ${_actionKind} target=${_actionTarget} count=${_regressions.length}`, cmdPreview);
1857
+ }
1858
+ } catch {
1859
+ // Network error, abort, parse failure — fail-open, no warning
1860
+ }
1861
+ })();
1862
+
1863
+ // ── Substrate-bound contract gate via SDK.checkAction ──────────────────────
1864
+ // Hamza directive 2026-04-28: local cognition substance + binding-plan gates
1865
+ // pass, but the substrate has its own contract gate that knows about deploy
1866
+ // state, soul-charge, hospital admission policy, etc. checkAction returns
1867
+ // { allowed, reason, requiredGates }. allowed:false halts the tool with the
1868
+ // substrate's reason. SDK call failure is non-blocking (fail-open) — halting
1869
+ // every tool when substrate is down would brick the orchestrator, but the
1870
+ // failure is logged for telemetry.
1871
+ try {
1872
+ const { HTTPHarnessClient } = await import('@aria/harness-http-client');
1873
+ const { readFileSync: __fsRead, existsSync: __fsExists } = await import('node:fs');
1874
+ const { homedir: __homedir } = await import('node:os');
1875
+ const __home = __homedir();
1876
+ const __tokenPath = `${__home}/.aria/owner-token`;
1877
+ const __licensePath = `${__home}/.aria/license.json`;
1878
+ // Tier detection: client if license.json has a jti, else owner.
1879
+ // Hamza correction 2026-04-28b: master/owner-token credentials belong
1880
+ // to Hamza only — never resolve them on client-tier processes.
1881
+ let __isOwner = true;
1882
+ try {
1883
+ if (__fsExists(__licensePath)) {
1884
+ const __lic = JSON.parse(__fsRead(__licensePath, 'utf8'));
1885
+ __isOwner = !__lic.jti;
1886
+ }
1887
+ } catch { __isOwner = true; }
1888
+ // Resolution: ARIA_HARNESS_TOKEN env first (both tiers). ONLY on owner
1889
+ // tier, fall back to master/api-key env or owner-token file.
1890
+ let __apiKey = process.env.ARIA_HARNESS_TOKEN || '';
1891
+ if (!__apiKey && __isOwner) {
1892
+ __apiKey = process.env.ARIA_MASTER_TOKEN
1893
+ || process.env.ARIA_API_KEY
1894
+ || (__fsExists(__tokenPath) ? __fsRead(__tokenPath, 'utf8').trim() : '');
1895
+ }
1896
+ // Map Claude tool names → checkAction action enum (substrate signature is
1897
+ // 'deploy'|'build'|'write'|'delete'). Most state-mutating tools map to
1898
+ // 'write'; explicit deploy/destructive cases would map elsewhere if the
1899
+ // substrate widens the enum later.
1900
+ const __toolToAction = { Bash: 'write', Edit: 'write', Write: 'write', NotebookEdit: 'write' };
1901
+ const __action = __toolToAction[toolName];
1902
+ if (__apiKey && __action) {
1903
+ const __client = new HTTPHarnessClient({
1904
+ baseUrl:
1905
+ process.env.ARIA_HIVE_RUNTIME_URL ||
1906
+ process.env.ARIA_HARNESS_BASE_URL ||
1907
+ process.env.ARIA_HARNESS_URL ||
1908
+ 'https://harness.ariasos.com',
1909
+ apiKey: __apiKey,
1910
+ });
1911
+ const __target = JSON.stringify(toolInput || {}).slice(0, 500);
1912
+ const __check = await __client.checkAction(__action, __target);
1913
+ if (__check && __check.allowed === false) {
1914
+ const __reason = `Aria substrate checkAction DENIED for ${toolName}/${__action}: ${__check.reason || 'no reason given'}. Required gates: [${(__check.requiredGates || []).join(', ')}].
1915
+
1916
+ The substrate's contract gate refused this action. Local doctrine gates passed (cognition lenses, binding plan, drift) but the substrate sees a downstream contract that disallows this tool call. Address the substrate's reason above before retrying.`;
1917
+ audit(`block-substrate-checkAction ${toolName.toLowerCase()} action=${__action} reason="${(__check.reason || '').slice(0, 80)}"`, cmdPreview);
1918
+ pushDecision('block', `substrate checkAction denied: ${(__check.reason || 'unspecified').slice(0, 100)}`);
1919
+ console.log(JSON.stringify({ decision: 'block', reason: __reason }));
1920
+ process.exit(2);
1921
+ }
1922
+ }
1923
+ } catch (err) {
1924
+ // SDK call failure is non-blocking — gate degrades to local-only doctrine.
1925
+ // The failure is recorded so a fleet probe can detect substrate-side
1926
+ // contract gate outages.
1927
+ console.warn(`[pre-tool-gate] substrate checkAction failed: ${err && err.message ? err.message : err}`);
1928
+ }
1929
+
1930
+ // ── Hive session-lock check ───────────────────────────────────────────────────
1931
+ // For Edit/Write/NotebookEdit: check file_path against hive_session_locks.
1932
+ // For Bash with file-mutating verbs (rm, mv, sed -i, awk, tee, cp, chmod,
1933
+ // truncate, install): extract the file argument and check it.
1934
+ //
1935
+ // If an active lock exists from a DIFFERENT session, BLOCK with coordination
1936
+ // instructions. Fail-open only on network error (endpoint unreachable).
1937
+ //
1938
+ // Per feedback_no_graceful_degradation.md: parse errors and non-network
1939
+ // failures surface in the block reason — they are not silently ignored.
1940
+ // Per feedback_no_timeouts_doctrine.md: no AbortSignal or setTimeout.
1941
+ (async function checkHiveSessionLock() {
1942
+ // Determine the file path to check
1943
+ let _lockCheckPath = '';
1944
+
1945
+ if (toolName === 'Edit' || toolName === 'Write' || toolName === 'NotebookEdit') {
1946
+ _lockCheckPath = filePath;
1947
+ } else if (toolName === 'Bash') {
1948
+ // Destructive bash verbs that mutate files — extract the file argument
1949
+ const _mutatingVerbRx = /^(rm|mv|cp|sed\s+-i|awk\s+.*-i|tee|truncate|install|chmod|chown)\b/;
1950
+ if (_mutatingVerbRx.test(cmd.trim())) {
1951
+ // Extract the first file-path argument: look for something with /
1952
+ const _pathMatch = cmd.match(/\s+((?:\/|~\/|\.\.?\/|[\w.-]+\/)[^\s'"]+)/);
1953
+ if (_pathMatch) _lockCheckPath = _pathMatch[1];
1954
+ }
1955
+ }
1956
+
1957
+ if (!_lockCheckPath) return; // no file target — skip lock check
1958
+
1959
+ const _soulUrl =
1960
+ process.env.ARIA_HIVE_RUNTIME_URL ||
1961
+ process.env.ARIA_SOUL_URL ||
1962
+ process.env.ARIA_HARNESS_BASE_URL ||
1963
+ process.env.ARIA_HARNESS_URL ||
1964
+ 'https://harness.ariasos.com';
1965
+ const _harnessToken = process.env.ARIA_HARNESS_TOKEN || '';
1966
+
1967
+ let _lockResp;
1968
+ try {
1969
+ const _params = new URLSearchParams({ file_path: _lockCheckPath });
1970
+ _lockResp = await fetch(`${_soulUrl}/api/hive/session-lock?${_params}`, {
1971
+ method: 'GET',
1972
+ headers: {
1973
+ 'Content-Type': 'application/json',
1974
+ ...(_harnessToken ? { Authorization: `Bearer ${_harnessToken}` } : {}),
1975
+ },
1976
+ });
1977
+ } catch (_netErr) {
1978
+ // Endpoint unreachable — fail-open. Lock check is a coordination layer,
1979
+ // not a safety hard-stop. Infra-down must not block all development.
1980
+ audit(`allow-lock-check-network-error path=${_lockCheckPath.slice(0, 80)}`, cmdPreview);
1981
+ return;
1982
+ }
1983
+
1984
+ if (!_lockResp.ok) {
1985
+ // Non-200 — route may not be deployed yet. Fail-open with audit record.
1986
+ audit(`allow-lock-check-http-error status=${_lockResp.status} path=${_lockCheckPath.slice(0, 80)}`, cmdPreview);
1987
+ return;
1988
+ }
1989
+
1990
+ // Per feedback_no_graceful_degradation.md: JSON parse error is surfaced,
1991
+ // not swallowed. A malformed response IS a defect that must be visible.
1992
+ const _lockData = await _lockResp.json();
1993
+ const _activeLocks = Array.isArray(_lockData?.locks) ? _lockData.locks : [];
1994
+
1995
+ // Filter to locks from a DIFFERENT session
1996
+ const _conflictingLocks = _activeLocks.filter(
1997
+ (l) => l.session_id && String(l.session_id) !== String(sessionId),
1998
+ );
1999
+
2000
+ if (_conflictingLocks.length === 0) {
2001
+ audit(`allow-lock-clear path=${_lockCheckPath.slice(0, 80)}`, cmdPreview);
2002
+ return; // no conflict — proceed
2003
+ }
2004
+
2005
+ // ── Auto-post coordination message to each conflicting session ───────────
2006
+ // Per hive-session-coordination doctrine (memory:feedback_hive_session_coordination.md):
2007
+ // when a lock conflict is detected, the gate AUTOMATICALLY posts a
2008
+ // lock_conflict_request session-message to each conflicting session so they see
2009
+ // the inbound coordination request in their next turn's HIVE_SESSION_INBOX block.
2010
+ // The model never has to manually post — the gate is the structural binding.
2011
+ //
2012
+ // Per feedback_no_timeouts_doctrine.md: no AbortSignal or setTimeout.
2013
+ // Per feedback_no_graceful_degradation.md: message-post failures are logged
2014
+ // loudly to stderr; they do NOT silently degrade — the block still fires regardless.
2015
+ const _autoMessageIds = [];
2016
+ for (const _conflict of _conflictingLocks) {
2017
+ try {
2018
+ const _msgId = `lock-conflict-${sessionId}-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 7)}`;
2019
+ const _requestedAt = new Date().toISOString();
2020
+ const _msgBody = {
2021
+ coordination_protocol: 'aria-hive-lock-conflict/v2',
2022
+ coordination_key: `file:${_lockCheckPath}`,
2023
+ file_path: _lockCheckPath,
2024
+ requesting_session_id: sessionId,
2025
+ requesting_client_id: 'aria-connector',
2026
+ requesting_surface: 'pre-tool-gate',
2027
+ intent_summary: `Session ${sessionId} attempted to edit ${_lockCheckPath} via ${toolName} but found your active lock. Requesting coordination — please release when done.`,
2028
+ requested_at: _requestedAt,
2029
+ tool_name: toolName,
2030
+ command_preview: cmdPreview,
2031
+ file_claims: [{ path: _lockCheckPath, intent: 'edit' }],
2032
+ target_lock: {
2033
+ lock_id: _conflict.lock_id ?? null,
2034
+ session_id: _conflict.session_id ?? null,
2035
+ client_id: _conflict.client_id ?? null,
2036
+ surface: _conflict.surface ?? null,
2037
+ locked_at: _conflict.locked_at ?? null,
2038
+ expires_at: _conflict.expires_at ?? null,
2039
+ },
2040
+ };
2041
+ const _msgResp = await fetch(`${_soulUrl}/api/hive/session-message`, {
2042
+ method: 'POST',
2043
+ headers: {
2044
+ 'Content-Type': 'application/json',
2045
+ ...(_harnessToken ? { Authorization: `Bearer ${_harnessToken}` } : {}),
2046
+ },
2047
+ body: JSON.stringify({
2048
+ message_id: _msgId,
2049
+ from_session_id: sessionId,
2050
+ to_session_id: _conflict.session_id,
2051
+ topic: 'lock_conflict_request',
2052
+ body: _msgBody,
2053
+ }),
2054
+ });
2055
+ if (_msgResp.ok) {
2056
+ _autoMessageIds.push({ session_id: _conflict.session_id, message_id: _msgId });
2057
+ audit(`auto-msg-sent lock-conflict to=${_conflict.session_id} msg=${_msgId} path=${_lockCheckPath.slice(0, 60)}`, cmdPreview);
2058
+ } else {
2059
+ const _errText = await _msgResp.text().catch(() => 'unreadable');
2060
+ process.stderr.write(
2061
+ `[aria-pre-tool-gate] WARN auto-message to session ${_conflict.session_id} failed: HTTP ${_msgResp.status} ${_errText.slice(0, 200)}\n`,
2062
+ );
2063
+ audit(`auto-msg-failed lock-conflict to=${_conflict.session_id} status=${_msgResp.status} path=${_lockCheckPath.slice(0, 60)}`, cmdPreview);
2064
+ }
2065
+ } catch (_msgErr) {
2066
+ // Network error posting auto-message — log loudly per no-graceful-degradation doctrine.
2067
+ // Block still fires; auto-message is additive signal, not a safety gate.
2068
+ process.stderr.write(
2069
+ `[aria-pre-tool-gate] WARN auto-message to session ${_conflict.session_id} threw: ${_msgErr instanceof Error ? _msgErr.message : String(_msgErr)}\n`,
2070
+ );
2071
+ audit(`auto-msg-error lock-conflict to=${_conflict.session_id} path=${_lockCheckPath.slice(0, 60)}`, cmdPreview);
2072
+ }
2073
+ }
2074
+
2075
+ const _conflictDetails = _conflictingLocks.map((l) => {
2076
+ const _ago = l.locked_at ? `since ${l.locked_at}` : '';
2077
+ const _expires = l.expires_at ? `, expires ${l.expires_at}` : '';
2078
+ const _who = l.client_id ? ` (client: ${l.client_id})` : '';
2079
+ const _surface = l.surface ? ` [${l.surface}]` : '';
2080
+ const _sentMsg = _autoMessageIds.find((m) => m.session_id === l.session_id);
2081
+ const _msgNote = _sentMsg
2082
+ ? ` [auto-coordination message posted: ${_sentMsg.message_id}]`
2083
+ : ' [auto-message failed — coordinate manually]';
2084
+ return ` - Session ${l.session_id}${_who}${_surface} holds lock on ${l.file_path} ${_ago}${_expires}${_msgNote}`;
2085
+ }).join('\n');
2086
+
2087
+ const _autoMsgSummary = _autoMessageIds.length > 0
2088
+ ? `\nAuto-coordination: gate posted lock_conflict_request message(s) to ${_autoMessageIds.map((m) => `session ${m.session_id} (msg: ${m.message_id})`).join(', ')}. They will see this inbound on their next turn via [HIVE_SESSION_INBOX].`
2089
+ : '\nAuto-coordination message could not be delivered (see stderr). Coordinate manually via POST /api/hive/session-message.';
2090
+
2091
+ const _lockBlockReason = `Hive session-lock conflict: another session holds an active lock on this file.
2092
+
2093
+ File: ${_lockCheckPath}
2094
+
2095
+ Conflicting locks:
2096
+ ${_conflictDetails}
2097
+ ${_autoMsgSummary}
2098
+
2099
+ Resolution:
2100
+ 1. A lock_conflict_request message was automatically posted to the lock-holding session. Wait for them to see it.
2101
+ 2. They release via: aria hive lock release --lock-id <ID> OR DELETE /api/hive/session-lock.
2102
+ 3. No automatic timeout-based release — explicit release only (memory:feedback_no_timeouts_doctrine.md).
2103
+ 4. Retry this action — the gate allows when no conflicting lock exists.
2104
+
2105
+ Per memory:feedback_hive_session_coordination.md: blind-edit on the same file from concurrent sessions
2106
+ causes merge conflicts and state divergence. Explicit coordination is the only safe path.`;
2107
+
2108
+ audit(`block-hive-lock-conflict path=${_lockCheckPath.slice(0, 80)} conflicting_sessions=${_conflictingLocks.map((l) => l.session_id).join(',')} auto_msgs=${_autoMessageIds.length}`, cmdPreview);
2109
+ pushDecision('block', `hive session-lock conflict on ${_lockCheckPath.slice(0, 80)}`);
2110
+ console.log(JSON.stringify({
2111
+ decision: 'block',
2112
+ reason: _lockBlockReason,
2113
+ hookSpecificOutput: {
2114
+ hookEventName: 'PreToolUse',
2115
+ conflicting_locks: _conflictingLocks,
2116
+ auto_coordination_messages: _autoMessageIds,
2117
+ recovery: {
2118
+ action: 'wait_for_lock_release_then_retry',
2119
+ file_path: _lockCheckPath,
2120
+ conflicting_session_ids: _conflictingLocks.map((l) => l.session_id),
2121
+ auto_message_posted: _autoMessageIds.length > 0,
2122
+ send_message_endpoint: '/api/hive/session-message',
2123
+ release_lock_endpoint: '/api/hive/session-lock',
2124
+ },
2125
+ },
2126
+ }));
2127
+ process.exit(2);
2128
+ })();
2129
+
2130
+ // Non-trivial action with cognition AND (binding-allowed OR binding-disabled) AND substrate-cleared — allow.
2131
+ audit(`allow-cognition ${toolName.toLowerCase()} lenses=${lensCount} via=${cognitionSource}`, cmdPreview);
2132
+ pushDecision('allow', `${toolName.toLowerCase()} with ${lensCount} lenses (${cognitionSource})`);
2133
+ process.exit(0);