@gaunt-sloth/core 2.0.0-alpha.9 → 2.0.0-beta.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (275) hide show
  1. package/.gsloth.review.md +2 -0
  2. package/README.md +71 -20
  3. package/dist/config/colour.d.ts +38 -0
  4. package/dist/config/colour.js +36 -0
  5. package/dist/config/colour.js.map +1 -0
  6. package/dist/config/configDiscovery.d.ts +79 -0
  7. package/dist/config/configDiscovery.js +80 -0
  8. package/dist/config/configDiscovery.js.map +1 -0
  9. package/dist/config/defaults.d.ts +20 -20
  10. package/dist/config/defaults.js +10 -8
  11. package/dist/config/defaults.js.map +1 -1
  12. package/dist/config/filesystem-tools.d.ts +41 -0
  13. package/dist/config/filesystem-tools.js +56 -0
  14. package/dist/config/filesystem-tools.js.map +1 -0
  15. package/dist/config/loader.d.ts +171 -19
  16. package/dist/config/loader.js +1054 -144
  17. package/dist/config/loader.js.map +1 -1
  18. package/dist/config/mouse.d.ts +50 -0
  19. package/dist/config/mouse.js +44 -0
  20. package/dist/config/mouse.js.map +1 -0
  21. package/dist/config/profiles.d.ts +68 -0
  22. package/dist/config/profiles.js +93 -0
  23. package/dist/config/profiles.js.map +1 -0
  24. package/dist/config/providerKeys.d.ts +69 -0
  25. package/dist/config/providerKeys.js +69 -0
  26. package/dist/config/providerKeys.js.map +1 -0
  27. package/dist/config/schema.d.ts +2671 -138
  28. package/dist/config/schema.js +1361 -85
  29. package/dist/config/schema.js.map +1 -1
  30. package/dist/config/shell-policy.d.ts +899 -111
  31. package/dist/config/shell-policy.js +800 -70
  32. package/dist/config/shell-policy.js.map +1 -1
  33. package/dist/config/tool-descriptions.d.ts +211 -0
  34. package/dist/config/tool-descriptions.js +272 -0
  35. package/dist/config/tool-descriptions.js.map +1 -0
  36. package/dist/config/types.d.ts +352 -41
  37. package/dist/config/types.js +1 -0
  38. package/dist/config/types.js.map +1 -1
  39. package/dist/config.d.ts +35 -1
  40. package/dist/config.js +16 -1
  41. package/dist/config.js.map +1 -1
  42. package/dist/constants.d.ts +28 -1
  43. package/dist/constants.js +28 -1
  44. package/dist/constants.js.map +1 -1
  45. package/dist/core/GthAbstractAgent.d.ts +166 -11
  46. package/dist/core/GthAbstractAgent.js +484 -45
  47. package/dist/core/GthAbstractAgent.js.map +1 -1
  48. package/dist/core/GthAgentRunner.d.ts +543 -57
  49. package/dist/core/GthAgentRunner.js +1494 -140
  50. package/dist/core/GthAgentRunner.js.map +1 -1
  51. package/dist/core/GthLangChainAgent.d.ts +117 -2
  52. package/dist/core/GthLangChainAgent.js +602 -29
  53. package/dist/core/GthLangChainAgent.js.map +1 -1
  54. package/dist/core/approvals/annotations.d.ts +122 -0
  55. package/dist/core/approvals/annotations.js +137 -0
  56. package/dist/core/approvals/annotations.js.map +1 -0
  57. package/dist/core/approvals/grants.d.ts +216 -0
  58. package/dist/core/approvals/grants.js +469 -0
  59. package/dist/core/approvals/grants.js.map +1 -0
  60. package/dist/core/approvals/matcher.d.ts +202 -0
  61. package/dist/core/approvals/matcher.js +267 -0
  62. package/dist/core/approvals/matcher.js.map +1 -0
  63. package/dist/core/approvals/mcpSubjects.d.ts +40 -0
  64. package/dist/core/approvals/mcpSubjects.js +99 -0
  65. package/dist/core/approvals/mcpSubjects.js.map +1 -0
  66. package/dist/core/approvals/promptHeader.d.ts +28 -0
  67. package/dist/core/approvals/promptHeader.js +62 -0
  68. package/dist/core/approvals/promptHeader.js.map +1 -0
  69. package/dist/core/approvals/toolAnnotationSources.d.ts +105 -0
  70. package/dist/core/approvals/toolAnnotationSources.js +277 -0
  71. package/dist/core/approvals/toolAnnotationSources.js.map +1 -0
  72. package/dist/core/approvals/toolHost.d.ts +46 -0
  73. package/dist/core/approvals/toolHost.js +108 -0
  74. package/dist/core/approvals/toolHost.js.map +1 -0
  75. package/dist/core/debugCapture.d.ts +74 -0
  76. package/dist/core/debugCapture.js +100 -0
  77. package/dist/core/debugCapture.js.map +1 -0
  78. package/dist/core/gthLeanAgentFactory.d.ts +4 -4
  79. package/dist/core/gthLeanAgentFactory.js +4 -4
  80. package/dist/core/launchBanner.d.ts +127 -0
  81. package/dist/core/launchBanner.js +414 -0
  82. package/dist/core/launchBanner.js.map +1 -0
  83. package/dist/core/modelLabel.d.ts +19 -0
  84. package/dist/core/modelLabel.js +26 -0
  85. package/dist/core/modelLabel.js.map +1 -0
  86. package/dist/core/plainToolIndication.d.ts +15 -0
  87. package/dist/core/plainToolIndication.js +174 -0
  88. package/dist/core/plainToolIndication.js.map +1 -0
  89. package/dist/core/reasoningBlocks.d.ts +65 -0
  90. package/dist/core/reasoningBlocks.js +103 -0
  91. package/dist/core/reasoningBlocks.js.map +1 -0
  92. package/dist/core/refusal.d.ts +53 -0
  93. package/dist/core/refusal.js +133 -0
  94. package/dist/core/refusal.js.map +1 -0
  95. package/dist/core/runHeader.d.ts +38 -0
  96. package/dist/core/runHeader.js +42 -0
  97. package/dist/core/runHeader.js.map +1 -0
  98. package/dist/core/runStats.d.ts +14 -3
  99. package/dist/core/runStats.js +48 -3
  100. package/dist/core/runStats.js.map +1 -1
  101. package/dist/core/shell/ShellCommandFailedError.d.ts +3 -4
  102. package/dist/core/shell/ShellCommandFailedError.js +3 -4
  103. package/dist/core/shell/ShellCommandFailedError.js.map +1 -1
  104. package/dist/core/shell/abstention.d.ts +88 -0
  105. package/dist/core/shell/abstention.js +184 -0
  106. package/dist/core/shell/abstention.js.map +1 -0
  107. package/dist/core/shell/approvalCapture.d.ts +271 -0
  108. package/dist/core/shell/approvalCapture.js +108 -0
  109. package/dist/core/shell/approvalCapture.js.map +1 -0
  110. package/dist/core/shell/approvalStop.d.ts +123 -0
  111. package/dist/core/shell/approvalStop.js +269 -0
  112. package/dist/core/shell/approvalStop.js.map +1 -0
  113. package/dist/core/shell/arity.d.ts +6 -0
  114. package/dist/core/shell/arity.js +20 -6
  115. package/dist/core/shell/arity.js.map +1 -1
  116. package/dist/core/shell/denylist.d.ts +11 -0
  117. package/dist/core/shell/denylist.js +37 -0
  118. package/dist/core/shell/denylist.js.map +1 -0
  119. package/dist/core/shell/escalationSeverity.d.ts +141 -0
  120. package/dist/core/shell/escalationSeverity.js +89 -0
  121. package/dist/core/shell/escalationSeverity.js.map +1 -0
  122. package/dist/core/shell/framing.d.ts +190 -0
  123. package/dist/core/shell/framing.js +633 -0
  124. package/dist/core/shell/framing.js.map +1 -0
  125. package/dist/core/shell/hardline.d.ts +103 -0
  126. package/dist/core/shell/hardline.js +780 -0
  127. package/dist/core/shell/hardline.js.map +1 -0
  128. package/dist/core/shell/negotiation.d.ts +328 -0
  129. package/dist/core/shell/negotiation.js +488 -0
  130. package/dist/core/shell/negotiation.js.map +1 -0
  131. package/dist/core/shell/normalize.d.ts +44 -4
  132. package/dist/core/shell/normalize.js +61 -7
  133. package/dist/core/shell/normalize.js.map +1 -1
  134. package/dist/core/shell/openWorld.d.ts +263 -0
  135. package/dist/core/shell/openWorld.js +1188 -0
  136. package/dist/core/shell/openWorld.js.map +1 -0
  137. package/dist/core/shell/rater.d.ts +873 -0
  138. package/dist/core/shell/rater.js +1454 -0
  139. package/dist/core/shell/rater.js.map +1 -0
  140. package/dist/core/shell/raterModel.d.ts +41 -0
  141. package/dist/core/shell/raterModel.js +51 -0
  142. package/dist/core/shell/raterModel.js.map +1 -0
  143. package/dist/core/shell/raterVocabulary.d.ts +121 -0
  144. package/dist/core/shell/raterVocabulary.js +116 -0
  145. package/dist/core/shell/raterVocabulary.js.map +1 -0
  146. package/dist/core/shell/rejection.d.ts +69 -0
  147. package/dist/core/shell/rejection.js +38 -0
  148. package/dist/core/shell/rejection.js.map +1 -0
  149. package/dist/core/toolCallRepair/grammar.d.ts +41 -0
  150. package/dist/core/toolCallRepair/grammar.js +116 -0
  151. package/dist/core/toolCallRepair/grammar.js.map +1 -0
  152. package/dist/core/toolCallRepair/index.d.ts +2 -0
  153. package/dist/core/toolCallRepair/index.js +7 -0
  154. package/dist/core/toolCallRepair/index.js.map +1 -0
  155. package/dist/core/toolCallRepair/payload.d.ts +36 -0
  156. package/dist/core/toolCallRepair/payload.js +341 -0
  157. package/dist/core/toolCallRepair/payload.js.map +1 -0
  158. package/dist/core/toolCallRepair/promote.d.ts +45 -0
  159. package/dist/core/toolCallRepair/promote.js +90 -0
  160. package/dist/core/toolCallRepair/promote.js.map +1 -0
  161. package/dist/core/toolDisplay.d.ts +123 -0
  162. package/dist/core/toolDisplay.js +451 -0
  163. package/dist/core/toolDisplay.js.map +1 -0
  164. package/dist/core/toolOutputChannel.d.ts +95 -0
  165. package/dist/core/toolOutputChannel.js +165 -0
  166. package/dist/core/toolOutputChannel.js.map +1 -0
  167. package/dist/core/types.d.ts +349 -16
  168. package/dist/core/types.js.map +1 -1
  169. package/dist/history/historyFormat.d.ts +12 -3
  170. package/dist/history/historyFormat.js +50 -8
  171. package/dist/history/historyFormat.js.map +1 -1
  172. package/dist/history/historyStore.d.ts +77 -0
  173. package/dist/history/historyStore.js +173 -6
  174. package/dist/history/historyStore.js.map +1 -1
  175. package/dist/history/recordSession.d.ts +10 -1
  176. package/dist/history/recordSession.js +27 -0
  177. package/dist/history/recordSession.js.map +1 -1
  178. package/dist/providers/anthropic.js +12 -0
  179. package/dist/providers/anthropic.js.map +1 -1
  180. package/dist/providers/configurationPassthrough.d.ts +107 -0
  181. package/dist/providers/configurationPassthrough.js +148 -0
  182. package/dist/providers/configurationPassthrough.js.map +1 -0
  183. package/dist/providers/geminiSchemaSanitizer.d.ts +55 -0
  184. package/dist/providers/geminiSchemaSanitizer.js +347 -0
  185. package/dist/providers/geminiSchemaSanitizer.js.map +1 -0
  186. package/dist/providers/geminiThinking.d.ts +60 -0
  187. package/dist/providers/geminiThinking.js +92 -0
  188. package/dist/providers/geminiThinking.js.map +1 -0
  189. package/dist/providers/google-genai.js +18 -1
  190. package/dist/providers/google-genai.js.map +1 -1
  191. package/dist/providers/groq.js +12 -0
  192. package/dist/providers/groq.js.map +1 -1
  193. package/dist/providers/huggingface.d.ts +25 -0
  194. package/dist/providers/huggingface.js +69 -0
  195. package/dist/providers/huggingface.js.map +1 -0
  196. package/dist/providers/modelCatalog.d.ts +109 -0
  197. package/dist/providers/modelCatalog.js +245 -0
  198. package/dist/providers/modelCatalog.js.map +1 -0
  199. package/dist/providers/modelDiscovery.d.ts +99 -5
  200. package/dist/providers/modelDiscovery.js +191 -35
  201. package/dist/providers/modelDiscovery.js.map +1 -1
  202. package/dist/providers/ollama.d.ts +18 -4
  203. package/dist/providers/ollama.js +67 -37
  204. package/dist/providers/ollama.js.map +1 -1
  205. package/dist/providers/openai.js +34 -0
  206. package/dist/providers/openai.js.map +1 -1
  207. package/dist/providers/openrouter.d.ts +26 -4
  208. package/dist/providers/openrouter.js +83 -26
  209. package/dist/providers/openrouter.js.map +1 -1
  210. package/dist/providers/vertexai.js +19 -1
  211. package/dist/providers/vertexai.js.map +1 -1
  212. package/dist/providers/xai.js +20 -0
  213. package/dist/providers/xai.js.map +1 -1
  214. package/dist/runtime/askStructured.d.ts +105 -0
  215. package/dist/runtime/askStructured.js +120 -0
  216. package/dist/runtime/askStructured.js.map +1 -0
  217. package/dist/runtime/conversation.d.ts +64 -0
  218. package/dist/runtime/conversation.js +171 -0
  219. package/dist/runtime/conversation.js.map +1 -0
  220. package/dist/runtime/singleShot.d.ts +37 -6
  221. package/dist/runtime/singleShot.js +113 -67
  222. package/dist/runtime/singleShot.js.map +1 -1
  223. package/dist/runtime/structuredOutput.d.ts +104 -0
  224. package/dist/runtime/structuredOutput.js +393 -0
  225. package/dist/runtime/structuredOutput.js.map +1 -0
  226. package/dist/utils/ProgressIndicator.d.ts +21 -0
  227. package/dist/utils/ProgressIndicator.js +30 -3
  228. package/dist/utils/ProgressIndicator.js.map +1 -1
  229. package/dist/utils/aiignoreUtils.js.map +1 -1
  230. package/dist/utils/binaryOutputUtils.js.map +1 -1
  231. package/dist/utils/consoleUtils.d.ts +95 -0
  232. package/dist/utils/consoleUtils.js +112 -2
  233. package/dist/utils/consoleUtils.js.map +1 -1
  234. package/dist/utils/crashHandler.d.ts +87 -0
  235. package/dist/utils/crashHandler.js +128 -0
  236. package/dist/utils/crashHandler.js.map +1 -0
  237. package/dist/utils/debugDump.d.ts +134 -0
  238. package/dist/utils/debugDump.js +381 -0
  239. package/dist/utils/debugDump.js.map +1 -0
  240. package/dist/utils/debugUtils.d.ts +13 -4
  241. package/dist/utils/debugUtils.js +36 -13
  242. package/dist/utils/debugUtils.js.map +1 -1
  243. package/dist/utils/displayWidth.d.ts +53 -0
  244. package/dist/utils/displayWidth.js +195 -0
  245. package/dist/utils/displayWidth.js.map +1 -0
  246. package/dist/utils/fileUtils.js.map +1 -1
  247. package/dist/utils/globalConfigUtils.d.ts +14 -2
  248. package/dist/utils/globalConfigUtils.js +22 -4
  249. package/dist/utils/globalConfigUtils.js.map +1 -1
  250. package/dist/utils/llmUtils.d.ts +39 -8
  251. package/dist/utils/llmUtils.js +76 -8
  252. package/dist/utils/llmUtils.js.map +1 -1
  253. package/dist/utils/redactSecrets.d.ts +63 -0
  254. package/dist/utils/redactSecrets.js +286 -0
  255. package/dist/utils/redactSecrets.js.map +1 -0
  256. package/dist/utils/systemPromptNotes.d.ts +222 -0
  257. package/dist/utils/systemPromptNotes.js +338 -0
  258. package/dist/utils/systemPromptNotes.js.map +1 -0
  259. package/dist/utils/systemUtils.d.ts +18 -1
  260. package/dist/utils/systemUtils.js +38 -3
  261. package/dist/utils/systemUtils.js.map +1 -1
  262. package/dist/utils/toolMatching.d.ts +30 -0
  263. package/dist/utils/toolMatching.js +44 -0
  264. package/dist/utils/toolMatching.js.map +1 -0
  265. package/dist/utils/untrustedText.d.ts +86 -0
  266. package/dist/utils/untrustedText.js +101 -0
  267. package/dist/utils/untrustedText.js.map +1 -0
  268. package/package.json +21 -7
  269. package/schema/gsloth-config.schema.json +1921 -326
  270. package/dist/core/shell/allowlist.d.ts +0 -75
  271. package/dist/core/shell/allowlist.js +0 -187
  272. package/dist/core/shell/allowlist.js.map +0 -1
  273. package/dist/core/shell/judge.d.ts +0 -161
  274. package/dist/core/shell/judge.js +0 -261
  275. package/dist/core/shell/judge.js.map +0 -1
@@ -1,15 +1,117 @@
1
- import { getEffectiveDevToolsConfig, getShellJudgeSettings, isShellAllowlistEnabled, isShellAllowlistPersisted, isShellJudgeEnabled, } from '#src/config.js';
1
+ import { DEFAULT_APPROVAL_RUNG, describeGrantedBuiltInTools, isNegotiatingRung, isRatedRung, isToolGatedAtRung, resolveApprovals, resolveGatedToolNames, resolveShellApprovalGate, SHELL_TOOL_NAME, TOOL_ANNOTATION_HINTS, } from '#src/config.js';
2
+ import { StatusLevel, } from '#src/core/types.js';
2
3
  import { GthLangChainAgent } from '#src/core/GthLangChainAgent.js';
3
- import { AllowlistStore, PersistedAllowlist, matchesApproval, } from '#src/core/shell/allowlist.js';
4
+ import { annotationWeakenings, ApprovalGrantStore, describeWeakenedGrant, PersistedApprovalGrants, shellGrantEntry, toolGrantEntry, trustWithdrawalWeakens, } from '#src/core/approvals/grants.js';
5
+ import { renderApprovalEntryObject } from '#src/config/schema.js';
4
6
  import { classifyCommand } from '#src/core/shell/arity.js';
7
+ import { describeAbstention } from '#src/core/shell/abstention.js';
5
8
  import { normalizeCommand } from '#src/core/shell/normalize.js';
6
- import { judgeShellCommand, mapVerdictToAction, } from '#src/core/shell/judge.js';
9
+ import { ApprovalStopError, AttackHaltError, NonInteractiveEscalationError, } from '#src/core/shell/approvalStop.js';
10
+ import { applyDestructiveFloor, isBelowDestructiveFloor, isRaterTimeout, mapAllowMatchedVerdictToAction, mapVerdictToAction, openWorldToolFloorReason, preflightFloorFinding, RATER_DEFAULT_TIMEOUT_MS, rateShellCommand, } from '#src/core/shell/rater.js';
11
+ import { ApprovalCaptureLog, } from '#src/core/shell/approvalCapture.js';
12
+ import { buildHardlineRefusal, checkHardline } from '#src/core/shell/hardline.js';
13
+ import { renderNegotiationTranscript, ShellNegotiationState } from '#src/core/shell/negotiation.js';
14
+ import { buildRejectionMessage } from '#src/core/shell/rejection.js';
15
+ import { describeApprovalEntry, resolveApprovalRules, } from '#src/core/approvals/matcher.js';
16
+ import { createEffectiveToolAnnotationSource, trustedAnnotationHints, } from '#src/core/approvals/annotations.js';
17
+ import { approvalSubjectForToolName } from '#src/core/approvals/mcpSubjects.js';
18
+ import { toolCallHosts } from '#src/core/approvals/toolHost.js';
19
+ import { builtInToolAnnotations, mcpDeclaredAnnotationLookup, } from '#src/core/approvals/toolAnnotationSources.js';
20
+ import { resolveRaterModel } from '#src/core/shell/raterModel.js';
7
21
  import { env } from '#src/utils/systemUtils.js';
8
22
  import { getGslothConfigWritePath } from '#src/utils/fileUtils.js';
9
23
  import { SHELL_ALLOWLIST_FILE } from '#src/constants.js';
10
24
  import { enhanceVertexUnauthorizedMessage } from '#src/utils/vertexaiUtils.js';
11
25
  import { getNewRunnableConfig } from '#src/utils/llmUtils.js';
12
26
  import { initDebugLogging, debugLog, debugLogError, debugLogObject, } from '#src/utils/debugUtils.js';
27
+ import { updateCrashContext } from '#src/utils/crashHandler.js';
28
+ import { setToolDisplayConfig } from '#src/core/toolDisplay.js';
29
+ /**
30
+ * GS2-48 — how many trailing messages of the in-flight turn to hand the crash handler as the
31
+ * transcript tail. A crash file is triage, not the full session, so only the last few messages are
32
+ * kept; they are redacted (GS2-47) by the crash snapshot writer before anything reaches disk.
33
+ */
34
+ const CRASH_TRANSCRIPT_TAIL_MESSAGES = 8;
35
+ /**
36
+ * A private copy of a rule entry, for handing to a display. `pattern` is the one field that can be
37
+ * an object (a `hint` pattern, §3.1), so it is copied too — a shallow spread alone would leave the
38
+ * displayed entry sharing the very object the matcher compares against.
39
+ */
40
+ function copyApprovalEntry(entry) {
41
+ if (entry.type === 'shell' || typeof entry.pattern === 'string')
42
+ return { ...entry };
43
+ return { ...entry, pattern: { ...entry.pattern } };
44
+ }
45
+ /**
46
+ * [[EXT-29]] §5.1 — the `justification` argument of a `run_shell_command` call, when the model
47
+ * supplied a usable one.
48
+ *
49
+ * Read defensively for the same reason `command` is: these are model-authored arguments arriving
50
+ * through a schema the graph validated but that this method does not re-validate, so a non-string
51
+ * or a whitespace-only value is *absent* rather than a second spelling of empty.
52
+ *
53
+ * **What the trim buys is the RECORDED ROUND, not the prompt.** The rating prompt is already safe
54
+ * without it — `buildNegotiationContextBlock` drops a blank justification before it renders a fence,
55
+ * and `renderNegotiationTranscript` drops one before it renders a line. What only this can do is
56
+ * keep the round itself honest at the point it is written: a round carrying a whitespace-only
57
+ * justification asserts that the agent argued something it did not, to everything that later reads
58
+ * the transcript rather than a rendering of it. Both downstream guards then stay defence in depth
59
+ * instead of being the only thing between a blank string and that claim.
60
+ */
61
+ function shellJustification(args) {
62
+ const value = args?.justification;
63
+ if (typeof value !== 'string')
64
+ return undefined;
65
+ return value.trim().length === 0 ? undefined : value;
66
+ }
67
+ /**
68
+ * [[EXT-29]] §5.1 — the text of the human messages in a turn's input, for the rater's last-5 window.
69
+ *
70
+ * Structural and fail-soft, like `runStats`'s accumulator: the runner is handed `BaseMessage`s from
71
+ * several surfaces (readline, TUI, ACP, AG-UI) and a multimodal turn's `content` is an array of
72
+ * blocks rather than a string. Only the text is taken — §4.3 admits no file contents, no tool
73
+ * output and no fetched pages, and an image block is none of the three.
74
+ */
75
+ function humanMessageTexts(messages) {
76
+ const texts = [];
77
+ for (const message of messages) {
78
+ try {
79
+ const type = message?.getType?.();
80
+ if (type !== 'human')
81
+ continue;
82
+ const content = message.content;
83
+ if (typeof content === 'string') {
84
+ texts.push(content);
85
+ continue;
86
+ }
87
+ if (!Array.isArray(content))
88
+ continue;
89
+ const parts = content
90
+ .filter((block) => typeof block === 'object' &&
91
+ block !== null &&
92
+ block.type === 'text' &&
93
+ typeof block.text === 'string')
94
+ .map((block) => block.text);
95
+ if (parts.length > 0)
96
+ texts.push(parts.join('\n'));
97
+ }
98
+ catch {
99
+ /* fail-soft: an odd message shape just means that message contributes nothing */
100
+ }
101
+ }
102
+ return texts;
103
+ }
104
+ /**
105
+ * EXT-114 — the page describing the `subagents` config key, pointed at rather than paraphrased in
106
+ * the notice itself.
107
+ *
108
+ * **A GitHub blob URL, matching the other user-facing runtime doc links in this repo** (the
109
+ * approvals-protection pointer in `config/shell-policy.ts` and the 2.0 migration pointer in
110
+ * `config/schema.ts`) — a running CLI's user has no checkout for a relative path to resolve in.
111
+ * `subagentScope.spec.ts` pins that this URL's anchor still resolves to a real heading in the page
112
+ * it names, because a doc link that silently rots is worse than no link.
113
+ */
114
+ export const SUBAGENTS_DOCS_URL = 'https://github.com/pukeko-robotics/gaunt-sloth/blob/main/docs/configuration/profiles.md#named-profile-subagents-subagents';
13
115
  /**
14
116
  * Agent simplifies interaction with LLM and reduces it to calling a few methods
15
117
  * {@link GthAgentRunner#init} and {@link GthAgentRunner#processMessages}.
@@ -28,6 +130,14 @@ export class GthAgentRunner {
28
130
  * for non-interactive entrypoints (a scripted `exec` run with no TTY to prompt on).
29
131
  */
30
132
  toolApprovalCallback = null;
133
+ /**
134
+ * [[TUI-C68]] §6.1 — consumer hook invoked when the rater rates a command an `attack`, so an
135
+ * interactive surface can show the red banner before the run ends. Set via
136
+ * {@link setAttackHaltCallback}; **when unset the runner halts immediately**, which is the
137
+ * behaviour every surface had before a banner existed. A surface that forgets to wire it
138
+ * therefore keeps the halt rather than losing it.
139
+ */
140
+ attackHaltCallback = null;
31
141
  /** The command the runner was initialized for; selects which `devTools` config applies. */
32
142
  command = undefined;
33
143
  /**
@@ -38,33 +148,73 @@ export class GthAgentRunner {
38
148
  */
39
149
  lastRunStats = { tools: [] };
40
150
  /**
41
- * EXT-12 — runtime, session-scoped yolo flag toggled by the `/yolo` slash command. Distinct
42
- * from the static `devTools.shellYolo` config flag (which omits the tool from `interruptOn` at
43
- * agent-build time and cannot be changed mid-session). Because the tool stays gated (in
44
- * `interruptOn`), this flag is consulted at the TOP of {@link decideToolApproval}: when ON, a
45
- * gated `run_shell_command` is auto-approved WITHOUT prompting (yolo behaviour) for the rest of
46
- * this runner's life. Never persisted; defaults OFF. It does NOT disable the hardline floor —
47
- * catastrophic commands are still refused at exec time in `GthDevToolkit.executeCommand`.
151
+ * CFG-27the runtime, session-scoped approvals posture, seeded at {@link init} from
152
+ * {@link resolveApprovals} and thereafter switchable for the session by `/approvals <rung>`.
153
+ * **This field, not the interrupt wiring, is where the rung lives.** The backends wire the
154
+ * interrupt rung-independently, so every tool any rung could gate arrives at the top of
155
+ * {@link decideToolApproval} and is judged against the rung recorded here which is what makes
156
+ * `/approvals manual` take effect mid-session, and what keeps a config that pre-selects
157
+ * `bypass` switchable back. Never persisted.
158
+ *
159
+ * It does NOT disable the hardline floor — catastrophic commands are still refused at exec time
160
+ * in `GthDevToolkit.executeCommand` under every rung.
161
+ */
162
+ sessionApprovals = {
163
+ rung: DEFAULT_APPROVAL_RUNG,
164
+ allow: [],
165
+ deny: [],
166
+ escalate: [],
167
+ };
168
+ /**
169
+ * CFG-26 — the model the AI rater rates with, when `approvals.rater.profile` names an identity
170
+ * profile. Resolved ONCE at {@link init} (never mid-turn) and handed to `rateShellCommand`;
171
+ * `undefined` means no profile is configured and the rater uses the session model.
172
+ */
173
+ raterModel;
174
+ /**
175
+ * EXT-66 — how many rating calls this session gave up on. Counted so the notice can say "3 times
176
+ * this session" rather than repeating an identical line, and so a silent drift toward
177
+ * escalate-everything has a number attached to it.
178
+ */
179
+ raterTimeouts = 0;
180
+ /**
181
+ * EXT-71 §3.1/§6 — what the escalation menu granted at run time, for the life of THIS runner
182
+ * instance: {@link ApprovalEntry} objects, never prefixes, and never anything from config (the
183
+ * declared lists are read-only input consulted straight from the posture). Instance-scoped so
184
+ * concurrent sessions (ACP / AG-UI multi-session) cannot stomp each other's approvals.
185
+ */
186
+ sessionGrants = new ApprovalGrantStore();
187
+ /**
188
+ * CFG-27 §3 — what the escalation menu's *always reject* choice adds at run time, in the same
189
+ * grammar ([[TUI-C26]] wires that writer; the store speaks it already). The entries DECLARED in
190
+ * `approvals.deny` are not here — they are read-only config input, matched from the posture — and
191
+ * both are handed to the same matcher, so a runtime refusal and a declared one are one list.
192
+ */
193
+ denyGrants = new ApprovalGrantStore();
194
+ /**
195
+ * The persisted (`always`) grant store, loaded lazily on first use from
196
+ * `.gsloth/.gsloth-settings/shell-allowlist.json`. Null until a gated call actually needs it, and
197
+ * null when the file cannot be loaded at all (in which case `always` grants degrade to session).
48
198
  */
49
- sessionYolo = false;
199
+ persistedGrants = null;
200
+ persistedGrantsLoaded = false;
50
201
  /**
51
- * EXT-9 Tier-2 session allow-list approved command prefixes that auto-approve for the
52
- * life of THIS runner instance. Instance-scoped (not module-global) so concurrent
53
- * sessions (ACP / AG-UI multi-session) cannot stomp each other's approvals.
202
+ * [[EXT-29]] §5 the state of the agent↔rater negotiation at `auto`: the transcript, §5.3's
203
+ * consecutive-rejection counter and the reachability bound. Instance-scoped for the same reason
204
+ * the grant stores are — a concurrent ACP / AG-UI session must not inherit another's argument.
54
205
  */
55
- sessionAllowlist = new AllowlistStore();
206
+ negotiation = new ShellNegotiationState();
56
207
  /**
57
- * EXT-9 Tier-2 persisted (`always`) allow-list, loaded lazily on first use from
58
- * `.gsloth/.gsloth-settings/shell-allowlist.json`. Null until the shell tool is gated
59
- * and the allow-list is enabled; null also when persistence is disabled by config.
208
+ * [[TUI-C27]] the diagnostic record of every gated decision this session made, for
209
+ * `/debug-dump`. Instance-scoped for the same reason the negotiation and the grant stores are: a
210
+ * concurrent ACP / AG-UI session must not inherit another's approvals history, and a dump taken
211
+ * in one must not describe the other.
60
212
  */
61
- persistedAllowlist = null;
62
- persistedAllowlistLoaded = false;
213
+ approvalCaptures = new ApprovalCaptureLog();
63
214
  /**
64
215
  * @param agentFactory Produces the {@link GthAgentInterface} the runner drives.
65
- * Defaults to the lean {@link GthLangChainAgent} (core). `@gaunt-sloth/agent`
66
- * passes a factory returning a deep `GthDeepAgent` so the same runner can drive a
67
- * `createDeepAgent` graph without core depending on deepagents.
216
+ * Defaults to the lean {@link GthLangChainAgent} (core). The seam stays parameterised so a
217
+ * caller can drive the runner with a different graph builder without core depending on it.
68
218
  */
69
219
  constructor(statusUpdate, resolvers, agentFactory) {
70
220
  this.statusUpdate = statusUpdate;
@@ -81,38 +231,335 @@ export class GthAgentRunner {
81
231
  this.toolApprovalCallback = callback;
82
232
  }
83
233
  /**
84
- * EXT-12flip the runtime, session-scoped yolo flag (the `/yolo` slash command). When ON,
85
- * gated `run_shell_command` calls auto-approve without prompting for the rest of this session;
86
- * the hardline floor still applies at exec time. Returns the NEW state so the caller can render
87
- * a notice. Session-scoped only nothing is written to config.
234
+ * [[TUI-C68]] §6.1 register the handler that shows the **attack banner**, the one way a human
235
+ * gets past an `attack` verdict. Pass `null` to clear.
236
+ *
237
+ * Separate from {@link setToolApprovalCallback} because it is a separate question with an
238
+ * inverted default: an absent approval callback means *this session has nobody to ask*, and an
239
+ * absent one here means *end the run*. Wiring it is what an interactive surface opts into; every
240
+ * other surface keeps the halt (see {@link attackHaltCallback}).
241
+ */
242
+ setAttackHaltCallback(callback) {
243
+ this.attackHaltCallback = callback;
244
+ }
245
+ /**
246
+ * §6.1 — **the single seam between an `attack` verdict and the end of the run.** Both rating
247
+ * paths — the §3.2 allow-match tripwire and the ordinary rater decision — go through here, so the
248
+ * banner cannot be present on one and missing on the other, which is the shape of bug that leaves
249
+ * a halt answerable in some sessions and not others with nothing on screen to tell them apart.
250
+ *
251
+ * It returns a decision for the one answer that grants and throws for everything else:
252
+ *
253
+ * - **no callback → throw**, immediately and unchanged. §6.2's rule is that a run with nobody to
254
+ * ask never blocks and never times out into a grant; the way that is guaranteed is that waiting
255
+ * is something only a wired surface can cause.
256
+ * - **`run-anyway` → approve, scope `once`.** Exactly one command runs. `once` is not a default
257
+ * restated: it is what keeps §6.1's three "never"s true. Returning here is also returning from
258
+ * *before* the block that records a sticky grant, so no allow-list entry and no session grant
259
+ * can be written on this path — the next identical call is rated again and reaches this banner
260
+ * again. Nothing here touches the rung, and nothing disables the rater, the escalation or the
261
+ * halt for anything else.
262
+ * - **anything else → throw.** `stop`, and equally a value a surface invents or forgets to
263
+ * return: the grant is one exact answer and everything else is a refusal.
264
+ */
265
+ async haltOrRunAnyway(command, reason,
266
+ /** [[TUI-C27]] — this decision's record; the banner's answer is a HUMAN's answer. */
267
+ record) {
268
+ if (this.attackHaltCallback) {
269
+ const answer = await this.attackHaltCallback({ command, reason });
270
+ // [[TUI-C27]] — **recorded here, or a run-anyway is indistinguishable from a `safe`
271
+ // rating.** The banner returns an ordinary approval, so without this line the archive would
272
+ // show `approve` at the `rater` stage with nobody named — i.e. the rater appearing to have
273
+ // approved a command it called an attack. That is precisely the misattribution this node
274
+ // exists to remove, on the branch where it costs the most.
275
+ record.humanAnswer = answer === 'run-anyway' ? 'approve' : 'reject';
276
+ if (answer === 'run-anyway')
277
+ return { type: 'approve', scope: 'once' };
278
+ }
279
+ else {
280
+ // §6.2 — no surface wired the banner, so nobody was asked and the run ends.
281
+ record.humanAnswer = 'no-human';
282
+ }
283
+ throw new AttackHaltError(command, reason);
284
+ }
285
+ /**
286
+ * CFG-27 — switch the session-scoped rung (`/approvals <rung>`). Idempotent; returns the NEW
287
+ * rung so the caller can render a notice. Session-scoped only — nothing is written to config,
288
+ * and the declared allow/deny lists are unaffected (they are config input, not session state).
289
+ */
290
+ setSessionApprovalRung(rung) {
291
+ this.sessionApprovals = { ...this.sessionApprovals, rung };
292
+ return this.sessionApprovals.rung;
293
+ }
294
+ /** CFG-27 — the session's current approvals posture (rung + rater profile + declared lists). */
295
+ getSessionApprovals() {
296
+ return this.sessionApprovals;
297
+ }
298
+ /**
299
+ * [[TUI-C27]] — every gated decision this session made, oldest first, for the `/debug-dump`
300
+ * archive.
301
+ *
302
+ * Threaded by each surface into `writeDebugDump`, exactly as `agent.lastModelRequest` is: the
303
+ * writer redacts it with the same pass it applies to every other artifact, and a surface that
304
+ * does not thread it simply omits the file.
305
+ */
306
+ getApprovalCaptures() {
307
+ return this.approvalCaptures.snapshot();
308
+ }
309
+ /**
310
+ * CFG-26 — the allow-list sizes for the `/approvals` display: how many command prefixes the
311
+ * human has trusted this session, and how many are persisted in the project file.
312
+ *
313
+ * READ-ONLY BY CONSTRUCTION: it reports the persisted count only when the store has ALREADY
314
+ * been loaded (or persistence is on and it can be read), and never through a path that would
315
+ * CREATE the store as a side effect of showing a display — a status command must not mutate
316
+ * session state. `always: undefined` therefore means "not loaded / persistence off", which the
317
+ * caller renders as `—` rather than a misleading `0`.
88
318
  */
89
- toggleSessionYolo() {
90
- this.sessionYolo = !this.sessionYolo;
91
- return this.sessionYolo;
319
+ getAllowlistCounts() {
320
+ const always = this.persistedGrantsLoaded
321
+ ? (this.persistedGrants?.size() ?? undefined)
322
+ : undefined;
323
+ // EXT-71 §3 — every list MUST be inspectable, and the declared entries are in force for this
324
+ // session exactly as the human's own grants are. They are counted alongside them rather than
325
+ // hidden, which is what the count meant before the declared lists stopped seeding the store.
326
+ const session = this.sessionGrants.size() + this.sessionApprovals.allow.length;
327
+ return { session, always };
328
+ }
329
+ /**
330
+ * CFG-27 — the session's deny entries for display: the declared `approvals.deny` entries
331
+ * (rendered one line each) followed by whatever the escalation menu's *always reject* added at
332
+ * run time. Both refuse a call, so both are shown.
333
+ */
334
+ getDenylist() {
335
+ return [...this.sessionApprovals.deny, ...this.denyGrants.entries()].map(describeApprovalEntry);
336
+ }
337
+ /**
338
+ * §3/§4.7.4 — **the grants themselves**, for an approvals view that shows *what* was granted,
339
+ * *when*, and *under which effective annotations*. The counterpart of {@link getAllowlistCounts},
340
+ * which answers only how many.
341
+ *
342
+ * The declared config lists are deliberately NOT here. They are something a human wrote and
343
+ * reviewed, they carry no `grantedAt` and no scope, and `getAllowlistCounts` already counts them
344
+ * alongside these; mixing them in would present a config line as something the session granted.
345
+ *
346
+ * **Read-only in both senses.** It never loads the persisted store — same rule as
347
+ * {@link getAllowlistCounts}: a display must not create the store in order to show it, so a
348
+ * session that has not yet needed the file lists its session grants alone. And every grant is
349
+ * **deep-copied on the way out**, because the stores hand back their live records: the copy on the
350
+ * way in is what makes a snapshot private to its grant, and handing the same object to a renderer
351
+ * would put what the gate matches against one property assignment away from any consumer.
352
+ */
353
+ getGrants() {
354
+ const held = [
355
+ ...this.sessionGrants.list(),
356
+ ...(this.persistedGrantsLoaded ? (this.persistedGrants?.list() ?? []) : []),
357
+ ];
358
+ const seen = new Set();
359
+ const grants = [];
360
+ for (const grant of held) {
361
+ // An `always` grant is written to BOTH stores, so identity de-duplication is what keeps it
362
+ // from being displayed twice. The same question `ApprovalGrantStore.add` asks.
363
+ const key = renderApprovalEntryObject(grant.entry);
364
+ if (seen.has(key))
365
+ continue;
366
+ seen.add(key);
367
+ grants.push({
368
+ ...grant,
369
+ entry: copyApprovalEntry(grant.entry),
370
+ ...(grant.annotations ? { annotations: { ...grant.annotations } } : {}),
371
+ });
372
+ }
373
+ return grants;
92
374
  }
93
- /** EXT-12 — current state of the runtime session-scoped yolo flag (see {@link toggleSessionYolo}). */
94
- isSessionYolo() {
95
- return this.sessionYolo;
375
+ /**
376
+ * §4.7.1 — **which of each server's annotation hints this session believes**, for display.
377
+ *
378
+ * Every key either side names is listed: a configured `mcpServers` key with no policy of its own
379
+ * (which resolves through `defaults`), and a policy key naming a server the config does not have
380
+ * (which is what a typo looks like). Resolution is {@link trustedAnnotationHints}, the same
381
+ * function the gate derives effective annotations through, so the display cannot claim a
382
+ * relationship the gate does not act on.
383
+ */
384
+ getMcpAnnotationTrust() {
385
+ const mcp = this.sessionApprovals.mcp;
386
+ const configured = new Set(this.configuredMcpServerKeys());
387
+ const named = Object.keys(mcp?.servers ?? {});
388
+ const keys = [...new Set([...configured, ...named])];
389
+ return {
390
+ defaults: [...(mcp?.defaults?.trustAnnotations ?? [])],
391
+ servers: keys.map((server) => ({
392
+ server,
393
+ trusted: [...trustedAnnotationHints(mcp, server)],
394
+ configured: configured.has(server),
395
+ })),
396
+ };
397
+ }
398
+ /**
399
+ * §4.7.1 — **believe, or stop believing, specific hints from one server**, for the life of this
400
+ * session. The runtime half of `approvals.mcp.servers.<key>.trustAnnotations` (§9), so a user can
401
+ * do from the TUI what they can do in config.
402
+ *
403
+ * **Per hint, never per server.** `hints` names the hints this call moves and leaves every other
404
+ * hint of that server's exactly as it was, because believing a server's `readOnlyHint` while
405
+ * disbelieving its `openWorldHint` is a coherent position and the common one. A "trust this
406
+ * server" flag is the design §4.7.1 rejects.
407
+ *
408
+ * **The previous set is what was IN FORCE, resolved through `defaults`.** A server not named
409
+ * under `servers` inherits `defaults`, and naming it makes it state its relationship in full (§9)
410
+ * — so seeding from the empty set would mean that believing one more hint silently withdrew every
411
+ * hint `defaults` had granted, which is a weakening the user did not ask for and would invalidate
412
+ * their grants.
413
+ *
414
+ * **Session-scoped only.** Nothing is written to config: the declared block is read-only input
415
+ * (§9.1), exactly as the rung is.
416
+ *
417
+ * A trusted external annotation still never grants more than the same annotation grants one of
418
+ * our own built-ins — that holds in `core/approvals/annotations.ts` by construction, and this
419
+ * changes only which hints are read.
420
+ */
421
+ setMcpAnnotationTrust(server, hints, believe) {
422
+ const mcp = this.sessionApprovals.mcp;
423
+ const before = trustedAnnotationHints(mcp, server);
424
+ const requested = new Set(hints);
425
+ const after = believe
426
+ ? TOOL_ANNOTATION_HINTS.filter((hint) => before.includes(hint) || requested.has(hint))
427
+ : TOOL_ANNOTATION_HINTS.filter((hint) => before.includes(hint) && !requested.has(hint));
428
+ const added = after.filter((hint) => !before.includes(hint));
429
+ const removed = before.filter((hint) => !after.includes(hint));
430
+ const nextMcp = {
431
+ ...mcp,
432
+ servers: {
433
+ ...mcp?.servers,
434
+ [server]: { ...mcp?.servers?.[server], trustAnnotations: after },
435
+ },
436
+ };
437
+ // A fresh posture object, and fresh nested ones above: the resolved posture may share its `mcp`
438
+ // block with the loaded config, and a session change must not rewrite what the user configured.
439
+ this.sessionApprovals = { ...this.sessionApprovals, mcp: nextMcp };
440
+ return {
441
+ server,
442
+ configured: this.configuredMcpServerKeys().includes(server),
443
+ trusted: [...after],
444
+ added,
445
+ removed,
446
+ weakening: removed.filter(trustWithdrawalWeakens),
447
+ invalidates: this.grantsWeakenedByCurrentTrust(server),
448
+ };
449
+ }
450
+ /**
451
+ * §4.7.4 — which of this server's saved approvals the trust now in force weakens, for the notice
452
+ * that reports a trust change. **It predicts; it never removes.** The removal stays where Task
453
+ * 4 put it — at the call being decided — because that is the only moment the tool's declaration
454
+ * can be read for certain; here a server that is merely offline declares nothing and would read
455
+ * as having weakened everything.
456
+ *
457
+ * It compares through the same two functions the gate does: the effective-annotation source built
458
+ * from the posture as it stands *after* the change, and `annotationWeakenings`. A second
459
+ * comparison written for the display is how a warning comes to describe a rule the gate does not
460
+ * have.
461
+ */
462
+ grantsWeakenedByCurrentTrust(server) {
463
+ const source = this.effectiveToolAnnotationSource();
464
+ return this.getGrants()
465
+ .filter((grant) => grant.entry.type === 'mcpTool' &&
466
+ grant.entry.server === server &&
467
+ typeof grant.entry.pattern === 'string' &&
468
+ grant.annotations !== undefined)
469
+ .filter((grant) => {
470
+ // `EffectiveToolAnnotationSource` admits `undefined` for a source that genuinely cannot
471
+ // answer; `createEffectiveToolAnnotationSource` never returns it — a tool nothing has
472
+ // declared for resolves to the fail-closed constant, which for a grant made under anything
473
+ // softer reads as a weakening. The guard is therefore a type-level obligation and not a
474
+ // live branch: it discharges the union the contract declares, and nothing reaches it.
475
+ const current = source({
476
+ kind: 'mcpTool',
477
+ server,
478
+ name: grant.entry.pattern,
479
+ ...(grant.entry.host !== undefined ? { host: grant.entry.host } : {}),
480
+ });
481
+ return current !== undefined && annotationWeakenings(grant.annotations, current).length > 0;
482
+ })
483
+ .map((grant) => describeApprovalEntry(grant.entry));
96
484
  }
97
485
  /**
98
486
  * Init is split into a separate method. This may create a number of connections,
99
487
  * and we'd better have an instance by that moment, for the case things will go wrong,
100
488
  * so we can wrap init into try-catch and then call {@link #cleanup} within finally.
101
489
  */
102
- async init(command, configIn, checkpointSaver) {
490
+ async init(command, configIn, checkpointSaver, options) {
103
491
  this.config = configIn;
104
492
  this.command = command;
493
+ // GS2-48 — register the effective config with the crash handler so an uncaughtException /
494
+ // unhandledRejection mid-run captures it in the (redacted) snapshot. Pure data hand-off; no
495
+ // behaviour change.
496
+ updateCrashContext({ config: configIn, modelDisplayName: configIn.modelDisplayName });
497
+ // TUI-C32 residual a — register the live config with the shared tool-display redactor so its
498
+ // secret-literal collection walks INLINE config secrets (a pasted `apiKey`/`token` value), not
499
+ // only env-derived ones. Both surfaces (plain observer + Ink TUI) render through this module.
500
+ setToolDisplayConfig(configIn);
501
+ // CFG-27 — seed the session posture from config, so a config that pre-selects `bypass` starts
502
+ // there while the shell tool stays gated (see `resolveShellApprovalGate`) and therefore
503
+ // remains switchable (`/approvals write`). Resolved per-command, mirroring where the shell
504
+ // tool is actually emitted; no effect where the tool is ungated.
505
+ this.sessionApprovals = resolveApprovals(configIn, command);
506
+ // §3/§9.1 — the DECLARED lists are read-only config input, consulted through the EXT-71 rule
507
+ // matcher (`core/approvals/matcher.ts`) and NEVER copied into the runtime stores, which hold
508
+ // only what the escalation menu grants at run time. Both are handed to the same matcher, so
509
+ // there is one grammar and one comparison, not a config path and a runtime path.
510
+ this.denyGrants = new ApprovalGrantStore();
511
+ // CFG-26 — resolve the rater's own model when a profile is named, so the documented mitigation
512
+ // for a weak model ("point approvals.rater at a stronger one") actually takes effect.
513
+ //
514
+ // EAGERLY, here, rather than lazily at first use: `initConfig` re-runs discovery and prints
515
+ // "Activating profile: …", which mid-turn would write raw over the Ink TUI's managed frame,
516
+ // and a broken profile should fail at startup rather than three turns in. It deliberately does
517
+ // NOT catch — a named-but-unusable rater profile is an error, never a silent fallback to the
518
+ // session model (GS2-62).
519
+ //
520
+ // Loaded whenever a profile is NAMED, without a second "will the rater actually run?" gate:
521
+ // naming a rater profile at an unrated rung is a config the user can hold (they may switch to
522
+ // `assisted` mid-session with `/approvals`), and a broken profile should still fail loudly at
523
+ // startup rather than at the moment they switch.
524
+ const raterProfile = this.sessionApprovals.rater;
525
+ this.raterModel = raterProfile ? await resolveRaterModel(raterProfile) : undefined;
105
526
  // Initialize debug logging
106
527
  initDebugLogging(configIn.debugLog ?? false);
107
528
  debugLog(`Initializing GthAgentRunner with command: ${command || 'default'}`);
108
529
  this.runConfig = getNewRunnableConfig();
109
530
  debugLogObject('Runnable Config', this.runConfig);
531
+ this.warnIfSubagentsCannotBeHonored(configIn, command ?? options?.owningCommand);
110
532
  this.agent = this.agentFactory(this.statusUpdate, this.resolvers);
111
533
  // Initialize the agent
112
534
  debugLog('Initializing agent...');
113
- await this.agent.init(command, configIn, checkpointSaver);
535
+ await this.agent.init(command, configIn, checkpointSaver, {
536
+ displayCommand: options?.displayCommand,
537
+ });
114
538
  debugLog('Agent initialization complete');
115
539
  }
540
+ /**
541
+ * EXT-114 — `subagents` is configurable but not yet dispatched, and a run that declares them must
542
+ * say so rather than start with a quietly smaller toolset than the config describes.
543
+ *
544
+ * The `task` tool that spawned them belonged to the deepagents runtime, which is gone; the lean
545
+ * primitive that replaces it is GS2-25. Until then a declared subagent is inert. Keeping the key
546
+ * valid is deliberate — a config written for GS2-25 should not have to be un-written and
547
+ * re-written — but inert-and-silent is the failure this notice exists to prevent: the parent
548
+ * simply does the work itself, on the parent's model, and the only visible symptom is the bill.
549
+ *
550
+ * Fires on EVERY run rather than only where a backend could once have honoured it, because there
551
+ * is no longer any run that can.
552
+ */
553
+ warnIfSubagentsCannotBeHonored(config, command) {
554
+ if (!config.subagents || config.subagents.length === 0) {
555
+ return;
556
+ }
557
+ const scope = command ? `the ${command} command` : 'this run';
558
+ const names = config.subagents.map((spec) => spec.name).join(', ');
559
+ this.statusUpdate(StatusLevel.WARNING, `Config declares subagents (${names}), but no agent backend dispatches subagents yet, so ` +
560
+ `${scope} runs without them. See ` +
561
+ SUBAGENTS_DOCS_URL);
562
+ }
116
563
  /**
117
564
  * processMessages deals with both streaming and non-streaming approaches.
118
565
  */
@@ -122,6 +569,14 @@ export class GthAgentRunner {
122
569
  }
123
570
  // GS2-16: start this turn's analytics tally from zero (the runner is reused across turns).
124
571
  this.resetRunStats();
572
+ // GS2-48 — record this turn's transcript tail for the crash handler.
573
+ updateCrashContext({ transcriptTail: messages.slice(-CRASH_TRANSCRIPT_TAIL_MESSAGES) });
574
+ // [[EXT-29]] §5 — a new user turn is the human being reached, so it ends any negotiation still
575
+ // standing from the previous one and clears BOTH bounds. The turn's own messages then enter
576
+ // §5.1's last-5 window, which is what makes "just the last two" reach the rater at all — the
577
+ // reply that narrows what the agent proposes is worthless to the gate if only the agent hears it.
578
+ this.negotiation.humanReached();
579
+ this.negotiation.noteUserMessages(humanMessageTexts(messages));
125
580
  debugLog('Processing messages...');
126
581
  debugLogObject('Input Messages', messages);
127
582
  try {
@@ -139,11 +594,36 @@ export class GthAgentRunner {
139
594
  result += await this.resolveToolInterrupts();
140
595
  }
141
596
  catch (streamError) {
597
+ // CFG-27 — an approvals STOP is not a stream failure: it is the gate deliberately
598
+ // ending the run, and its message IS the explanation the spec requires it to carry.
599
+ // Re-thrown unchanged (the outer catch does the same) so nothing buries it.
600
+ if (streamError instanceof ApprovalStopError)
601
+ throw streamError;
142
602
  // Handle streaming-specific errors
143
603
  debugLogError('Stream processing', streamError);
144
604
  throw new Error(`Stream processing failed: ${streamError instanceof Error ? streamError.message : String(streamError)}`);
145
605
  }
146
606
  debugLog(`Stream completed. Total response length: ${result.length}`);
607
+ // EXT-37: a content-policy refusal (OpenAI content_filter / Anthropic stop_reason=refusal /
608
+ // Bedrock guardrail_intervened) is detected one layer down in GthAbstractAgent — the only
609
+ // place a message's response_metadata is visible — and surfaced there as a clear, non-empty
610
+ // terminal answer. That non-empty result intentionally bypasses this empty-response retry:
611
+ // a refusal is deterministic, so re-invoking the SAME model would only burn a paid call and
612
+ // fail identically. Only a genuinely empty turn reaches the retry below.
613
+ //
614
+ // Fallback-model EXTENSION POINT: hermes tries a *different* model once on refusal (a
615
+ // different model may not refuse). gaunt-sloth has no runtime fallback-model config today
616
+ // (`getCuratedFallbackModel` is init-time per-provider defaulting, not runtime failover), so
617
+ // per YAGNI none is built. When such a config is added, the one-shot fallback belongs where
618
+ // the refusal is detected (GthAbstractAgent.surfaceRefusal): try the fallback model ONCE
619
+ // before surfacing, and never retry the same model.
620
+ // GS2-72: the GS2-36 retry-budget's terminal notice — injected via a jumpTo:'end' STATE
621
+ // update on the lean createAgent graph — is streamed as an AIMessage chunk under
622
+ // streamMode:'messages' (verified on langchain 1.5.x), so it already arrives as a NON-empty
623
+ // `result` above and does NOT reach this fallback. Only a genuinely empty model turn falls
624
+ // through here, where the single retry invoke is the intended recovery. (If a future
625
+ // langchain stops streaming jumpTo-injected messages, the budget notice would drain empty
626
+ // and hit this fallback; GthAbstractAgentTerminalNotice.spec pins the current behaviour.)
147
627
  if (result.trim().length === 0) {
148
628
  debugLog('Stream produced empty response, retrying once with non-streaming invoke.');
149
629
  const fallback = await this.agent.invoke(messages, this.runConfig);
@@ -158,7 +638,15 @@ export class GthAgentRunner {
158
638
  else {
159
639
  // Use non-streaming
160
640
  debugLog('Using non-streaming mode');
161
- const result = await this.agent.invoke(messages, this.runConfig);
641
+ let result = await this.agent.invoke(messages, this.runConfig);
642
+ // EXT-52 — the SAME interrupt drain the streaming branch does above. A gated
643
+ // `run_shell_command` suspends the graph, so `invoke` returns with the tool-calling
644
+ // AIMessage (empty content) as the last message and the command not yet run. Draining here
645
+ // — BEFORE the empty-response check — is what makes the approval prompt fire and the
646
+ // approved command's output reach the caller on `streamOutput: false`; without it the turn
647
+ // died with the misleading empty-response error, so the check may only see a genuinely
648
+ // empty turn.
649
+ result += await this.resolveToolInterrupts();
162
650
  debugLog(`Non-stream response length: ${result.length}`);
163
651
  if (result.trim().length === 0) {
164
652
  throw new Error('Model returned an empty response. Try again or switch to a more stable model.');
@@ -167,6 +655,12 @@ export class GthAgentRunner {
167
655
  }
168
656
  }
169
657
  catch (error) {
658
+ // CFG-27 §4.2/§6.2 — an approvals STOP is not an agent failure and must reach the user with
659
+ // its own words: the command, the rating and its reason are the whole point of it. Wrapping
660
+ // it as "Agent processing failed: …" would bury the explanation the spec requires it to
661
+ // carry, so it is re-thrown unchanged.
662
+ if (error instanceof ApprovalStopError)
663
+ throw error;
170
664
  // Handle agent invocation errors
171
665
  debugLogError('Agent processing', error);
172
666
  const originalMessage = error instanceof Error ? error.message : String(error);
@@ -196,7 +690,10 @@ export class GthAgentRunner {
196
690
  * streamed across all resume turns (empty when nothing was resumed).
197
691
  *
198
692
  * No-ops (returns '') when the agent does not support interrupts (`getPendingToolInterrupts`/
199
- * `streamResume` absent), so the lean agent and non-HITL configs are unaffected.
693
+ * `streamResume` absent) that is the only exemption. As of EXT-52 BOTH backends gate
694
+ * `run_shell_command` and expose the interrupt surface, so the lean (default) agent is now
695
+ * exactly the agent this loop serves; only an agent implementation without those methods
696
+ * (e.g. a test double) skips it.
200
697
  */
201
698
  async resolveToolInterrupts() {
202
699
  const agent = this.agent;
@@ -221,140 +718,982 @@ export class GthAgentRunner {
221
718
  return resumedText;
222
719
  }
223
720
  /**
224
- * Decide a single pending tool call (EXT-9 Tier-2). For the opt-in `run_shell_command`,
225
- * consult the scoped allow-list FIRST: if the command's classified prefix is already
226
- * approved (session or persisted `always`) and survives the safe-bin anti-widening
227
- * re-validation, auto-approve SILENTLY (no human prompt). Otherwise fall through to the
228
- * human callback; when the human grants `session`/`always` scope, record the command's
229
- * classified prefix into the matching store so future flag-variants stop re-prompting.
721
+ * EXT-71 §3.1/§3.2, EXT-70 §4.7.5 — the subject a pending tool call presents to the rule matcher.
722
+ *
723
+ * A gated `run_shell_command` is a **shell** subject and nothing else: it is matched by `shell`
724
+ * entries, against the command. It is deliberately NOT also offered as a `tool` subject named
725
+ * `run_shell_command`, which would create a second allow path to every shell command carrying a
726
+ * different §3.2 `rate` default and a match that never saw the command it was approving.
727
+ *
728
+ * **Everything else splits by provenance**, which is the distinction §4.7.1 rests on: `tool` is
729
+ * the TRUSTED provenance, read verbatim, so an MCP tool arriving as one would be asking the
730
+ * trusted path for a third party's annotations — a gate any server can opt itself out of. Every
731
+ * MCP-namespaced name therefore becomes an `mcpTool` subject carrying the user's own `mcpServers`
732
+ * key, and one whose server cannot be resolved stays an `mcpTool` subject under an unnameable
733
+ * server rather than falling back to `tool` (see `approvalSubjectForToolName`).
230
734
  *
231
- * When no human callback is wired (non-TTY exec run) and nothing is allow-listed, reject
232
- * never auto-approve. Non-shell tools (or any tool when the allow-list is disabled) skip the
233
- * allow-list and go straight to the human callback / default-reject, preserving prior behaviour.
735
+ * **The host (§4.7.4)** is attached here, so the one subject the whole decision runs on carries
736
+ * it: the rule matcher treats a `host` on an entry as an additional exact-match condition, and a
737
+ * grant the menu writes records it. A call naming no single host has none, which fails toward a
738
+ * prompt at both sites.
739
+ *
740
+ * Widening which tools the gate actually suspends on is still [[EXT-30]]; this decides what a
741
+ * suspended call *is* whenever one arrives.
742
+ *
743
+ * @param hosts Every distinct host the call's arguments name ({@link toolCallHosts}).
744
+ */
745
+ approvalSubjectFor(tool, command, hosts) {
746
+ if (tool.name === SHELL_TOOL_NAME && command !== null)
747
+ return { kind: 'shell', command };
748
+ const subject = approvalSubjectForToolName(tool.name, this.configuredMcpServerKeys());
749
+ return hosts.length === 1 ? { ...subject, host: hosts[0] } : subject;
750
+ }
751
+ /**
752
+ * §4.7.5 — the user's own `mcpServers` keys, the only identity a server has here. Own enumerable
753
+ * keys via `Object.keys`, so nothing inherited can pose as a configured server.
754
+ */
755
+ configuredMcpServerKeys() {
756
+ const servers = this.config?.mcpServers;
757
+ return servers && typeof servers === 'object' ? Object.keys(servers) : [];
758
+ }
759
+ /**
760
+ * EXT-70 §4.7.1 — the source a `hint` entry reads a call's EFFECTIVE annotations through, built
761
+ * from the session's `approvals.mcp` block and the two declared-annotation lookups.
762
+ *
763
+ * Built per decision rather than cached at {@link init}, for two reasons that both bite: the
764
+ * agent registers its tools *inside* `agent.init()`, so an init-time snapshot would be empty; and
765
+ * a re-init re-resolves the tool list, which for MCP may hand back different declarations.
766
+ *
767
+ * The two lookups are deliberately different in kind. `builtIn` reads OUR OWN authored table and
768
+ * never the bound tool list — the bound list contains every server's tools, and a `builtIn`
769
+ * lookup over it would read a third party's declaration through the trusted-verbatim path.
770
+ * `mcp` reads what the servers declared, keyed by the registered tool name so the server key is
771
+ * never split apart and re-joined differently.
772
+ */
773
+ effectiveToolAnnotationSource() {
774
+ return createEffectiveToolAnnotationSource({
775
+ mcp: this.sessionApprovals.mcp,
776
+ declared: {
777
+ builtIn: builtInToolAnnotations,
778
+ mcp: mcpDeclaredAnnotationLookup(this.agent?.getDeclaredMcpToolAnnotations?.()),
779
+ },
780
+ });
781
+ }
782
+ /**
783
+ * Decide a single pending tool call. Spec order — **deny → bypass → escalate → allow → rater →
784
+ * human prompt**, with the hardline floor at exec time regardless. The two adjacencies that carry
785
+ * the design are that deny comes BEFORE `bypass` and escalate comes AFTER it:
786
+ *
787
+ * 1. **deny** (§3) — a declared entry or a runtime *always reject* grant is refused with no
788
+ * prompt and no rating call. It is consulted FIRST, and it is the one
789
+ * check that **still applies under `bypass`**: choosing `bypass` says *"stop asking me"*, not
790
+ * *"forget what I told you never to do"*. A deny entry MAY match a compound command, because a
791
+ * prohibition that catches something unresolvable errs in the direction that costs nothing.
792
+ * 2. **`bypass`** — the gate is off for this session; approve at scope `once`.
793
+ * 3. **escalate** (§3.2) — a declared entry always asks the human, whatever the rung would have
794
+ * done, **including outranking the automatic grants of `manual` and `write`** and any allow
795
+ * entry that also matched. It goes straight to the human with **no rating call**, and it never
796
+ * enters the `auto` negotiation. It is **inert at `bypass`**, which is why it sits below
797
+ * the rung check: the rung chosen for this session wins, and a stop that must survive `bypass`
798
+ * is a deny entry and only that.
799
+ * 4. **allow** (§3, §3.2) — a declared entry or a grant the human made at an earlier prompt this
800
+ * session (or persisted), matched against the whole normalized command and only when that
801
+ * command statically resolves. An allow match settles the human's part: no prompt. Whether the rater
802
+ * still reviews the call is the entry's own `rate` (§3.2) — honored at the rater rungs and
803
+ * inert at the deterministic ones, so no entry can smuggle a model call into `manual` or
804
+ * `write` — and a rated allow match is a TRIPWIRE, not a re-adjudication
805
+ * ({@link mapAllowMatchedVerdictToAction}).
806
+ * 5. **auto-rater** (`assisted` / `auto` only) — `safe` approves, `destructive` and
807
+ * `catastrophic` escalate, and `attack` HALTS the run ({@link AttackHaltError}). The other
808
+ * three rungs consult no model at all. A command whose target the gate cannot statically
809
+ * resolve is rated **exactly like any other** ([[EXT-81]]), with a neutral note in the rating
810
+ * prompt naming the shape the parser saw. It used to skip the call and be refused straight
811
+ * back to the model instead; §6.1's rule is that a deterministic layer fires only where it is
812
+ * confident something is a threat, and a parser reporting it could not read a string has
813
+ * detected nothing. At those same two rungs a **tool**
814
+ * call is instead floored deterministically by §4.7.3's open-world rule
815
+ * ({@link openWorldToolFloorReason} into {@link applyDestructiveFloor} — the one floor the
816
+ * shell path also reaches): a call whose effective `openWorldHint` is true is `destructive`,
817
+ * whatever its `readOnlyHint` says.
818
+ * 6. **human prompt** — the approval callback; when the human grants `session`/`always` scope,
819
+ * **that command** is recorded as an `exact` entry (§3.1/§6 — the menu never widens), so the
820
+ * same command stops re-prompting and a longer variant of it still asks.
821
+ *
822
+ * §6.2 — where no human can answer (CI, a one-shot run, a server), an escalation is **not** a
823
+ * rejection handed back to the model: it is an immediate non-zero exit
824
+ * ({@link NonInteractiveEscalationError}) carrying the command, the rating and its reason. No
825
+ * prompt, no waiting, and never a timeout into approval. Declaring commands in `approvals.allow`
826
+ * is the supported way to make a pipeline pass.
234
827
  *
235
828
  * Hardline catastrophic commands remain refused at exec time regardless of any approval here
236
829
  * (defense in depth in `GthDevToolkit.executeCommand`), so an allow-listed `rm -rf /` still
237
830
  * cannot run.
831
+ *
832
+ * **Step 0 is the rung.** The backends wire the interrupt over every tool ANY rung could gate,
833
+ * because the graph is built once and `/approvals <rung>` moves the rung under it for the rest of
834
+ * the session. So a call arriving here has not yet been judged against the rung in force: this is
835
+ * where that happens, on `sessionApprovals.rung`, which a mid-session switch has already updated.
836
+ * A call the live rung does not gate is approved on the spot — no rule matching, no rating, no
837
+ * prompt — which is what keeps `assisted`, `auto` and `bypass` behaving exactly as they did
838
+ * when the interrupt held the shell alone. It sits ABOVE the deny check for the same reason: an
839
+ * ungated call never reached this method at all before, so a deny entry could not fire on one, and
840
+ * a security fix for two rungs is not the place to change that. (The shell is gated at every rung
841
+ * whenever the shell gate is on, so §2.5's rule that the deny list survives `bypass` is untouched.)
238
842
  */
239
843
  async decideToolApproval(tool) {
844
+ // [[TUI-C27]] — the record is opened (and already in the log) BEFORE the decision runs, and
845
+ // filled in as it goes. Assembling it at the end would lose the calls most worth keeping: an
846
+ // `attack` verdict throws `AttackHaltError` out of the decision, so a halted run would carry no
847
+ // record of the rating that halted it — and an approval, which relays nothing to anyone, is
848
+ // exactly the branch that used to leave no trace at all.
849
+ const record = this.approvalCaptures.begin({
850
+ at: new Date().toISOString(),
851
+ tool: tool.name,
852
+ ...(typeof tool.args?.command === 'string' ? { command: tool.args.command } : {}),
853
+ rung: this.sessionApprovals.rung,
854
+ budget: this.negotiation.counters(),
855
+ });
856
+ const decision = await this.recordedDecision(tool, record);
857
+ // [[EXT-29]] §5.3 — **the reset, at the one site that sees every approval.** "A successful
858
+ // intervening tool call — the agent going away to gather information and returning better
859
+ // informed — resets [the count], because that is progress, not ping-pong." Every way a call can
860
+ // be let through arrives here: the rung not gating it, an allow entry, the §3.2 tripwire, a
861
+ // `safe` rating, the human saying yes. Wrapping is what makes that exhaustive — an approval
862
+ // added below cannot forget to reset, and the alternative (a call at each of the six `approve`
863
+ // returns) is a §5.3 hole that is invisible the day it opens.
864
+ //
865
+ // Nothing else resets: a `reject` (the negotiation's own rounds, and the §8 floor's refusal)
866
+ // must not, or the bound it is counted against could never be reached.
867
+ if (decision.type === 'approve')
868
+ this.negotiation.noteProgress();
869
+ return decision;
870
+ }
871
+ /**
872
+ * [[TUI-C27]] — {@link decideToolApprovalInner} with the record closed off on EVERY exit.
873
+ *
874
+ * The final action is written here rather than at each of the decision's many returns, because
875
+ * "what became of the call" is one fact with one source: what this method returns or throws. A
876
+ * per-return assignment is a list that a new branch joins without noticing, and the branch that
877
+ * would be forgotten is the one that ends the run.
878
+ */
879
+ async recordedDecision(tool, record) {
880
+ try {
881
+ const decision = await this.decideToolApprovalInner(tool, record);
882
+ record.action = decision.type === 'approve' ? 'approve' : 'reject';
883
+ if (decision.type === 'approve' && decision.scope)
884
+ record.scope = decision.scope;
885
+ return decision;
886
+ }
887
+ catch (error) {
888
+ if (error instanceof AttackHaltError) {
889
+ record.action = 'halt';
890
+ }
891
+ else if (error instanceof NonInteractiveEscalationError) {
892
+ // §6.2 — there was nobody to ask, so the escalation ended the run instead of reaching one.
893
+ record.action = 'escalate';
894
+ record.humanAnswer = 'no-human';
895
+ }
896
+ else {
897
+ record.action = 'error';
898
+ }
899
+ record.error = error instanceof Error ? `${error.name}: ${error.message}` : String(error);
900
+ throw error;
901
+ }
902
+ }
903
+ /** The decision itself; {@link decideToolApproval} wraps it with §5.3's reset. */
904
+ async decideToolApprovalInner(tool, record) {
240
905
  const command = typeof tool.args?.command === 'string' ? tool.args.command : null;
241
- const isShellCommand = tool.name === 'run_shell_command' && command !== null;
242
- const allowlistApplies = isShellCommand && this.isShellAllowlistOn();
243
- // EXT-12 runtime session yolo (`/yolo`): when ON, auto-approve a gated shell command WITHOUT
244
- // prompting, judging, or persisting. Scope `once` so nothing is written to the allow-list (the
245
- // bypass is intentionally ephemeral and reversible). The hardline floor is NOT bypassed here
246
- // it is enforced at exec time in GthDevToolkit.executeCommand regardless of this decision, so a
247
- // catastrophic command is still refused even under yolo.
248
- if (isShellCommand && this.sessionYolo) {
249
- return { type: 'approve', scope: 'once' };
250
- }
251
- // Auto-approve from the allow-list without prompting. The allow-list ALWAYS wins over the
252
- // judge: a human-trusted prefix shouldn't pay for an LLM call on every variant.
253
- if (allowlistApplies && this.isApprovedByAllowlist(command)) {
254
- return { type: 'approve', scope: 'session' };
255
- }
256
- // EXT-10 LLM-as-judge safety gate (default OFF). Runs BEFORE the human callback for a
257
- // `run_shell_command` not already allow-listed: auto-approve clearly-safe (fatigue reducer),
258
- // reject clearly-catastrophic (only when blockHigh), otherwise fall through to the human with
259
- // the verdict attached. When disabled this is a no-op and behaviour is exactly EXT-9.
260
- let safetyVerdict;
261
- if (isShellCommand && command !== null && this.isShellJudgeOn()) {
262
- const settings = getShellJudgeSettings(getEffectiveDevToolsConfig(this.config ?? undefined, this.command));
263
- const verdict = await judgeShellCommand(command, this.config, {
264
- home: env?.HOME,
265
- });
266
- const action = mapVerdictToAction(command, verdict, {
267
- autoApproveLow: settings.autoApproveLow,
268
- blockHigh: settings.blockHigh,
906
+ const isShellCommand = tool.name === SHELL_TOOL_NAME && command !== null;
907
+ const approvals = this.sessionApprovals;
908
+ // (0) Does the rung IN FORCE gate this tool at all? Same shared predicate the backends built the
909
+ // interrupt from, asked about this one call, so the wiring and the decision cannot disagree.
910
+ // Scope `once`, so nothing is written to any allow-list: this is not a grant, it is the absence
911
+ // of a gate.
912
+ const { gateShell } = resolveShellApprovalGate(this.config ?? undefined, this.command);
913
+ if (!isToolGatedAtRung({ toolName: tool.name, rung: approvals.rung, gateShell })) {
914
+ return this.stage(record, 'not-gated', { type: 'approve', scope: 'once' });
915
+ }
916
+ // [[TUI-C27]] [[EXT-81]]'s surviving observable: what the gate's own parser made of the
917
+ // command, recorded whether or not a rating follows. Computed once here rather than at the
918
+ // rating site, so a call the floor or a list settles still says whether the command was one the
919
+ // parser could resolve.
920
+ if (isShellCommand && command !== null) {
921
+ const defect = describeAbstention(command);
922
+ if (defect)
923
+ record.parserUnresolved = defect;
924
+ }
925
+ // ONE subject and ONE annotation source per decision, shared by the rule matcher and the
926
+ // §4.7.3 floor below. Building a second source for the floor would let a `hint` entry and the
927
+ // floor read different effective values for the same call — the two-derivations-disagreeing
928
+ // failure `core/approvals/annotations.ts` exists to prevent.
929
+ // §4.7.4 — the hosts this call names, read ONCE. The subject carries the single host where
930
+ // there is exactly one; the sticky-grant decision needs the count as well, because "named no
931
+ // host" and "named several" are the same absent `host` on the subject and are not the same
932
+ // question for the menu.
933
+ const hosts = tool.name === SHELL_TOOL_NAME && command !== null ? [] : toolCallHosts(tool.args);
934
+ const subject = this.approvalSubjectFor(tool, command, hosts);
935
+ const annotationSource = this.effectiveToolAnnotationSource();
936
+ // ONE read of that source per decision as well, so the §4.7.4 invalidation below, the §4.7.3
937
+ // floor and the snapshot a grant records are all the same set. A shell subject has none — a
938
+ // command carries no tool annotations.
939
+ const effective = subject.kind === 'shell' ? undefined : annotationSource(subject);
940
+ // §4.7.4 — **before any rule is resolved**, so a grant the tool has since weakened out from
941
+ // under cannot auto-approve the very call that revealed the weakening.
942
+ if (subject.kind !== 'shell' && effective)
943
+ this.invalidateWeakenedGrants(subject, effective);
944
+ // The declared lists AND the runtime grant stores, resolved most-restrictive-wins in ONE pass
945
+ // through the ONE comparison engine, so author order and the order the lists were concatenated
946
+ // in cannot change the outcome — and a grant the menu wrote is compared exactly as a line the
947
+ // user typed into their config is.
948
+ const rule = resolveApprovalRules(subject, this.approvalRuleLists(), {
949
+ // EXT-70 §4.7.1 — a `hint` entry reads EFFECTIVE annotations, which is where per-server,
950
+ // per-hint trust is applied. Without this the matcher falls back to the fail-closed source,
951
+ // where no tool is ever read-only and a `hint` entry could only ever describe the default.
952
+ annotations: annotationSource,
953
+ onNotice: (notice) => this.statusUpdate(notice.level, notice.message),
954
+ });
955
+ // (1) Deny — before everything, including `bypass`.
956
+ if (rule?.action === 'deny') {
957
+ // [[TUI-C26]] §6 — the message names the refusal the user actually made. A deny entry now has
958
+ // two possible authors: a line in `approvals.deny`, and the escalation menu's *always reject*
959
+ // choice earlier in this session. Telling the model (and, through it, the user) to edit a
960
+ // config file that the second kind was never written to is the same class of wrongness as
961
+ // confirming a persistence that did not happen. The declared list is checked FIRST so an
962
+ // entry a user wrote is described as theirs even when the menu recorded the identical one.
963
+ const declared = this.sessionApprovals.deny.some((entry) => renderApprovalEntryObject(entry) === renderApprovalEntryObject(rule.entry));
964
+ const described = describeApprovalEntry(rule.entry);
965
+ record.ruleMatch = { action: 'deny', entry: described };
966
+ return this.stage(record, 'deny-list', {
967
+ type: 'reject',
968
+ message: declared
969
+ ? `Refused: your deny list forbids this call (matched "${described}"). ` +
970
+ 'Remove the entry from approvals.deny if you want it to run.'
971
+ : `Refused: the user chose to always refuse this earlier in this session (matched ` +
972
+ `"${described}"). That refusal lasts until the session ends; ask the user if you ` +
973
+ 'believe it should be lifted.',
269
974
  });
270
- if (action === 'auto-approve') {
271
- // Scope `once`: judge approvals are NEVER persisted to the allow-list.
272
- return { type: 'approve', scope: 'once' };
975
+ }
976
+ // (2) `bypass` (config or `/approvals bypass`): approve a gated shell command WITHOUT
977
+ // prompting or rating. Scope `once` so nothing is written to the allow-list (the bypass is
978
+ // intentionally ephemeral and reversible). The hardline floor is NOT bypassed here — it is
979
+ // enforced at exec time in GthDevToolkit.executeCommand regardless of this decision.
980
+ if (isShellCommand && approvals.rung === 'bypass') {
981
+ return this.stage(record, 'bypass', { type: 'approve', scope: 'once' });
982
+ }
983
+ // (2b) [[EXT-29]] §4.2/§8 — **the hardline floor, consulted BEFORE anything opens.** "If the
984
+ // deterministic floor matches, the command is refused at execution regardless of rating, rung,
985
+ // or approval — so it MUST NOT be negotiated and SHOULD NOT be escalated."
986
+ //
987
+ // **This is a second call site, not the exec-time one, and the promise is different.** The
988
+ // toolkit's check guarantees such a command never RUNS; it does nothing about what happens on
989
+ // the way there, so without this line `auto` spends three rating calls and a human dialog
990
+ // arguing about a fork bomb that was never going to run, and `manual` puts a wipe-the-disk
991
+ // command in front of a person who answers it — and "asking a human to approve something that
992
+ // is then refused anyway teaches them their answer does not count, which is worse than a flat
993
+ // refusal". The exec-time check stays exactly where it is: it is the guarantee, this is the
994
+ // courtesy of not wasting a decision on it.
995
+ //
996
+ // It sits above the allow branch because the floor is unappealable — an allow entry cannot buy
997
+ // past it — and below the deny check because a deny match refuses the same call for the user's
998
+ // own reason.
999
+ //
1000
+ // **`checkHardline` is asked, not `catastrophic`.** They are different predicates and the
1001
+ // difference is measured: EXT-60 recorded `chown -R /` as missing from the floor, so "the floor
1002
+ // matched" and "the rater said catastrophic" name overlapping, non-identical sets. A
1003
+ // `catastrophic` rating still escalates (§4.2 settled that deliberately); only a floor match
1004
+ // refuses here.
1005
+ //
1006
+ // **A floor match refuses; it never halts, whichever of §8's two subsets matched.** The floor is
1007
+ // a lexical test with no notion of direction or role, so it fires on ordinary work — the deploy
1008
+ // authenticated by an identity file, the fetch that writes a credential INBOUND — and ending the
1009
+ // session on one leaves a restart as the only recovery. The run-ending halt stays where a model
1010
+ // has actually said the command is an attack (the rating path below): a floor match is a
1011
+ // model-free assertion, and the model-free consequence is the floor's own refusal, reached
1012
+ // earlier here than at exec and without spending a prompt on it.
1013
+ //
1014
+ // **Every rung that reaches this line, deliberately** — `assisted` and `auto`, and the two
1015
+ // deterministic rungs alike (`bypass` returned above). §4.2 is a statement about the COMMAND,
1016
+ // not about who was going to be asked about it: `assisted` gets the refusal without a prompt
1017
+ // for the same reason `auto` gets it without a round, and `manual`/`write` for the same reason
1018
+ // again. Those two are where the harm bites hardest, because they are the rungs a user picks in
1019
+ // order to answer every call themselves — so they are the rungs whose answers a refusal after
1020
+ // the fact teaches them not to trust.
1021
+ if (isShellCommand && command !== null) {
1022
+ const floor = checkHardline(command);
1023
+ if (floor) {
1024
+ // [[TUI-C27]] — **the archive names the matched pattern; the refusal below does not.**
1025
+ // §8.1 ("the floor is never advertised") and [[CFG-31]] bind USER-FACING rung copy —
1026
+ // text inviting someone to feel safe — and the resolution taken here is that a diagnostic
1027
+ // archive a user opens about their own session is not that surface: "a floor matched"
1028
+ // without saying which rule leaves nobody able to act on it. `buildHardlineRefusal` is
1029
+ // untouched and still carries only the description.
1030
+ record.hardline = { description: floor.description, pattern: floor.pattern };
1031
+ const refusal = buildHardlineRefusal(command, floor);
1032
+ // Visible, because the exec-time refusal is: a refusal the user never sees reads as the
1033
+ // agent quietly deciding not to do what it was asked.
1034
+ this.statusUpdate(StatusLevel.WARNING, `\n⛔ ${refusal}`);
1035
+ // §7's moves are deliberately absent — see `buildHardlineRefusal`. Neither bound moves
1036
+ // either: this refusal opens no round, so counting it would walk an unappealable refusal
1037
+ // toward the human escalation §4.2 says it must not reach. It follows that a model spamming
1038
+ // a floor-matching command is bounded only by the tool-loop guard and `recursionLimit`,
1039
+ // which is the right place for "the model did something unproductive" to end and the wrong
1040
+ // place for a fork bomb to acquire an audience.
1041
+ return this.stage(record, 'hardline-floor', { type: 'reject', message: refusal });
273
1042
  }
274
- if (action === 'reject') {
275
- return {
276
- type: 'reject',
277
- message: `Safety judge blocked the command: ${verdict.reason}`,
278
- };
1043
+ }
1044
+ // (3) Escalate — §3.2 sends it straight to the human with no rating call, outranking any allow
1045
+ // entry that also matched.
1046
+ //
1047
+ // The `bypass` term is deliberate and not redundant with the early return above. That return
1048
+ // only covers a SHELL call, so without this term a non-shell subject would still carry an
1049
+ // escalate match into the prompt at `bypass`, and §2.5's rule is about the rung, not about which
1050
+ // tool asked. Non-shell subjects do reach this line — the deterministic rungs gate the write
1051
+ // built-ins, MCP and custom tools — so the term is doing work rather than guarding a hypothesis.
1052
+ const escalatedBy = rule?.action === 'escalate' && approvals.rung !== 'bypass'
1053
+ ? describeApprovalEntry(rule.entry)
1054
+ : undefined;
1055
+ if (escalatedBy) {
1056
+ record.ruleMatch = { action: 'escalate', entry: escalatedBy };
1057
+ record.stage = 'escalate-entry';
1058
+ }
1059
+ // (4) Approve from the allow list without prompting. It ALWAYS wins over the rater — a
1060
+ // human-trusted call shouldn't pay for an LLM call on every variant — but never over escalate.
1061
+ const allowlistApplies = approvals.rung !== 'bypass' && escalatedBy === undefined;
1062
+ let safetyVerdict;
1063
+ if (allowlistApplies && rule?.action === 'allow') {
1064
+ record.ruleMatch = {
1065
+ action: 'allow',
1066
+ entry: describeApprovalEntry(rule.entry),
1067
+ rate: rule.rate === true,
1068
+ };
1069
+ // §3.2 — `rate` is honored at the rater rungs and INERT at the deterministic ones, so an
1070
+ // entry can never smuggle a model call into `manual` or `write`. A tool subject is not
1071
+ // rated either: the rater's first implementation covers the shell only (§4.3, [[EXT-30]]).
1072
+ if (!rule.rate || !isRatedRung(approvals.rung) || !isShellCommand || command === null) {
1073
+ return this.stage(record, 'allow-list', { type: 'approve', scope: 'session' });
1074
+ }
1075
+ // Attributed once, before the call, for the reason the rater path below is: the tripwire's
1076
+ // own `attack` arm throws, and a second writer on the return would make this one unfalsifiable.
1077
+ record.stage = 'allow-tripwire';
1078
+ const verdict = await this.rateCommand(command, { allowMatched: true }, record);
1079
+ const tripwire = mapAllowMatchedVerdictToAction(verdict);
1080
+ if (tripwire.action === 'approve') {
1081
+ return { type: 'approve', scope: 'session' };
1082
+ }
1083
+ if (tripwire.action === 'halt') {
1084
+ // §3.2/§4.2 — `attack` halts exactly as it would have without the match. A standing human
1085
+ // grant answers "may this run"; it does not answer "is this command's structure hostile".
1086
+ //
1087
+ // §6.1 — and it halts through the SAME seam as the rater's own path below, so an allow
1088
+ // entry does not decide whether the banner appears. The entry has already been overruled by
1089
+ // the time this line is reached; letting it also silence the one way out would make the
1090
+ // recovery depend on a match the human cannot see from the banner.
1091
+ return await this.haltOrRunAnyway(command, tripwire.verdict?.reason ?? '', record);
279
1092
  }
280
- // Escalate: carry the verdict to the human approval surface.
281
- safetyVerdict = verdict;
1093
+ // `catastrophic` the one outcome the tripwire escalates. Fall through to the human.
1094
+ safetyVerdict = tripwire.verdict;
282
1095
  }
1096
+ // (5) What the gate makes of the call itself, at the two rated rungs only. Skipped entirely
1097
+ // for an escalate match (§3.2: the user pre-decided that a human answers, so a rating would
1098
+ // decorate a mandatory prompt) and for a call the tripwire above already rated. The rung test
1099
+ // is the SAME one `mapVerdictToAction` applies, so both arms below floor exactly where the
1100
+ // shell does and nowhere else: `bypass` and the two deterministic rungs consult neither the
1101
+ // rater nor a preflight, and at those rungs the human is asked regardless.
1102
+ if (isRatedRung(approvals.rung) && escalatedBy === undefined && safetyVerdict === undefined) {
1103
+ // **The SUBJECT is what splits the two arms, not a second reading of the tool name.**
1104
+ // `approvalSubjectFor` returns `kind: 'shell'` under exactly the condition `isShellCommand`
1105
+ // states, so branching on the discriminant says the same thing once instead of twice — and
1106
+ // any future divergence in that function sends the call to the FLOOR (fail-closed) rather
1107
+ // than silently past it. It is also what carries the command as a non-null string.
1108
+ if (subject.kind === 'shell') {
1109
+ // The auto-rater. `safe` is approved (the fatigue reducer), `destructive` and
1110
+ // `catastrophic` fall through to the human with the verdict attached, and `attack` ends the
1111
+ // run outright. §4.6's deterministic preflights are applied inside `mapVerdictToAction`,
1112
+ // ahead of the `safe` check.
1113
+ //
1114
+ // **[[EXT-81]] — EVERY shell command reaches this call, including the ones the gate's own
1115
+ // parser cannot resolve.** There used to be a branch above it that skipped the rating for a
1116
+ // composed, substituting or redirecting command and refused the call instead. Two things
1117
+ // followed from that skip, and both are gone with it: `attack` and `catastrophic` were
1118
+ // UNREACHABLE for that entire class (nobody rated, so nobody could say worse than
1119
+ // `destructive`), and the party that heard about it was the parser's, not the rater's — a
1120
+ // component that has just announced it could not read a command is in no position to say
1121
+ // how to rewrite it, and the rewrite it named turned `cd src && ls` into a no-op plus a
1122
+ // listing of the wrong directory, both exit 0. The parser's finding is now a neutral note
1123
+ // in the rating prompt (`buildRaterPrompt`) and nothing else.
1124
+ // [[EXT-29]] §5.1 — the negotiation this rating is a round of. At `assisted` the context is
1125
+ // empty and `negotiable` is false, so the whole call is byte-identical to what it was.
1126
+ const negotiable = isNegotiatingRung(approvals.rung);
1127
+ const justification = negotiable ? shellJustification(tool.args) : undefined;
1128
+ const context = negotiable
1129
+ ? this.negotiation.contextFor(justification)
1130
+ : undefined;
1131
+ // [[TUI-C27]] — attributed BEFORE the call, and ONCE. Before, because `attack` throws out
1132
+ // of the decision below and a record left unattributed would say a halt came from nowhere.
1133
+ // Once, because a second assignment on each `return` would make the first unfalsifiable:
1134
+ // deleting either would leave the other still writing 'rater', and a fact with two writers
1135
+ // is one no test can pin.
1136
+ record.stage = 'rater';
1137
+ const verdict = await this.rateCommand(subject.command, {
1138
+ allowMatched: false,
1139
+ negotiation: context,
1140
+ negotiable,
1141
+ }, record);
1142
+ const decision = mapVerdictToAction(subject.command, verdict, { rung: approvals.rung });
1143
+ // [[TUI-C27]] — WHICH deterministic preflight fired, and whether it actually rewrote the
1144
+ // rating. The two are separate facts: a preflight only ever RAISES, and only `safe` sits
1145
+ // below the floor, so a finding on a `destructive` verdict is the floor AGREEING with the
1146
+ // rater rather than overriding it — and attributing the decision to the floor in that case
1147
+ // would be wrong. Recomputed from the same raw command `mapVerdictToAction` recomputes it
1148
+ // from, through the same one function, so the two cannot disagree.
1149
+ const preflight = preflightFloorFinding(subject.command);
1150
+ if (preflight) {
1151
+ record.preflight = {
1152
+ ...preflight,
1153
+ rewroteRating: isBelowDestructiveFloor(verdict.outcome),
1154
+ };
1155
+ }
1156
+ if (decision.action === 'approve') {
1157
+ // Scope `once`: rater approvals are NEVER persisted to the allow-list.
1158
+ return { type: 'approve', scope: 'once' };
1159
+ }
1160
+ if (decision.action === 'halt') {
1161
+ // §4.2 — not a rejection the model can respond to. It ends the agent loop.
1162
+ //
1163
+ // **`neg-04d`: a negotiation already in flight ends here too**, mid-way and without a
1164
+ // further round. `attack` is exempt from the whole mechanism (§5.1), so the counter, the
1165
+ // transcript and the loop all stop together rather than the argument continuing around a
1166
+ // halt that only ended one call.
1167
+ //
1168
+ // The reset itself is defence in depth: the throw ends `processMessages`, and a later
1169
+ // turn would clear the negotiation on its own first line anyway. **No PRODUCTION reader
1170
+ // sees this state again — which is not the same as it being unobservable**, and the
1171
+ // difference decides whether the line is pinned. `neg-04d` asserts both halves through
1172
+ // the spec harness's private-state cast: the cleared transcript, and `sinceHuman` back at
1173
+ // zero. That second one is what distinguishes this call from `noteProgress()`, which
1174
+ // clears the transcript and the consecutive count and deliberately leaves the
1175
+ // reachability bound standing.
1176
+ this.negotiation.humanReached();
1177
+ // §6.1 — the banner, when an interactive surface wired one, and the halt otherwise. It
1178
+ // sits AFTER the reset above on purpose: a human is reached either way (that is what the
1179
+ // banner is), so the negotiation ends here whichever answer comes back, and neither
1180
+ // answer leaves a transcript behind for a later turn to argue from.
1181
+ return await this.haltOrRunAnyway(subject.command, decision.verdict?.reason ?? '', record);
1182
+ }
1183
+ if (decision.action === 'reject') {
1184
+ // §5 — `destructive` at `auto`. The round is recorded first, so the attempt being ruled
1185
+ // on is itself on the transcript the human sees (§5.6).
1186
+ const outcome = this.negotiation.recordRejection({
1187
+ command: subject.command,
1188
+ ...(justification ? { justification } : {}),
1189
+ outcome: decision.verdict?.outcome ?? 'destructive',
1190
+ reason: decision.verdict?.reason ?? '',
1191
+ });
1192
+ if (outcome === 'reject') {
1193
+ // §7 — the refusal PLUS the moves: re-call with a justification (the tool argument
1194
+ // exists for this), call a different command, or ask the user. Rendered through the
1195
+ // one builder the human's own "no" uses, differing only in who refused, so the model
1196
+ // never meets two shapes of the same event.
1197
+ return {
1198
+ type: 'reject',
1199
+ message: buildRejectionMessage({
1200
+ source: 'rater',
1201
+ toolName: tool.name,
1202
+ verdict: decision.verdict,
1203
+ }),
1204
+ };
1205
+ }
1206
+ // A bound is spent — the agent and the rater cannot agree, and that is a human's call.
1207
+ // Falls through to the escalation below, carrying this last round's verdict.
1208
+ }
1209
+ // Escalate: carry the verdict (the honest one — see mapVerdictToAction) to the human.
1210
+ safetyVerdict = decision.verdict;
1211
+ }
1212
+ else {
1213
+ // EXT-70 §4.7.2/§4.7.3 — a tool call whose EFFECTIVE `openWorldHint` is true is floored at
1214
+ // `destructive`, through the SAME `applyDestructiveFloor` the shell path reaches via
1215
+ // `mapVerdictToAction`. No rating call: §4.3's scope boundary keeps the rater on the shell
1216
+ // until [[EXT-30]], and the floor is deterministic anyway — §4.6 states it as coming
1217
+ // *before* any model call, so it does not wait for one.
1218
+ //
1219
+ // **This is the branch a malformed `run_shell_command` lands in**, and it is the one shape
1220
+ // that reaches this floor under today's gate: a call with no `command` argument, or one
1221
+ // that is not a string, has nothing to rate, so it presents as a `tool` subject — and
1222
+ // `run_shell_command` carries no authored annotations, so its effective set is the
1223
+ // fail-closed one and it floors. That is the right direction: a shell call whose command
1224
+ // cannot even be read is not one anything can say something reassuring about.
1225
+ //
1226
+ // The annotations are the effective set (§4.7.1), read through the same source the `hint`
1227
+ // matcher just used, so an untrusted server's `openWorldHint: false` has already collapsed
1228
+ // to the fail-closed `true` and cannot buy its way past this.
1229
+ //
1230
+ // Reached only when no allow entry claimed the call: §4.6's fourth bullet makes an allow
1231
+ // match lift this floor, and step (4) above has already returned in that case.
1232
+ const toolFloor = openWorldToolFloorReason(effective);
1233
+ if (toolFloor !== null)
1234
+ record.stage = 'tool-open-world-floor';
1235
+ safetyVerdict = applyDestructiveFloor(safetyVerdict, toolFloor);
1236
+ }
1237
+ }
1238
+ // [[EXT-29]] §6 — **the human is shown the whole negotiation, not the last attempt.** Snapshot
1239
+ // it BEFORE the state is cleared, because "that the agent proposed the same command three times
1240
+ // unchanged, against two rejections that each told it what to fix, is itself the most important
1241
+ // thing on the screen". Empty for every escalation that had no negotiation — `catastrophic`
1242
+ // (which §4.2 gives no rounds at all), a declared escalate entry, an unrated rung, a tool
1243
+ // subject — so nothing renders a heading over an argument that never happened.
1244
+ // [[TUI-C27]] — everything that reaches a person has an attribution by now EXCEPT the plainest
1245
+ // case of all: a deterministic rung, no rule matched, no rating made. That is a decision the
1246
+ // rung itself made, so it is named rather than left blank — a record with no stage reads as the
1247
+ // recorder having failed, which is the opposite of what happened.
1248
+ record.stage ??= 'unrated-rung';
1249
+ const negotiationRounds = this.negotiation.transcript();
1250
+ // §5.3 — **the count the human is given, and it is NOT the transcript's length.** An approved
1251
+ // call clears the transcript, so the rounds above are the attempts since the last approval
1252
+ // while the fact the reader is weighing is how hard the agent pushed since the last person:
1253
+ // the agent that stashed between refusals had five refused attempts and three surviving
1254
+ // rounds. Read HERE, one line before `humanReached()` spends it — after, it is zero.
1255
+ const negotiationAttempts = this.negotiation.counters().rejectionsSinceHuman;
1256
+ // Reaching a person ends the negotiation (§5.3) and is the ONE thing that clears the
1257
+ // reachability bound: an escalation the human is about to answer is exactly the event that
1258
+ // bound exists to make happen, so it is spent here rather than accumulated across it.
1259
+ this.negotiation.humanReached();
283
1260
  if (!this.toolApprovalCallback) {
284
- // No interactive handler (e.g. non-TTY exec run): reject rather than auto-approve.
285
- return {
286
- type: 'reject',
287
- message: 'Tool call rejected: no interactive approval handler available.',
288
- };
1261
+ // §6.2 no one to ask. Exit non-zero with everything a person needs, rather than handing
1262
+ // the model a rejection it would just work around. The transcript goes into the message
1263
+ // because that message is the only thing anyone sees on this path.
1264
+ throw new NonInteractiveEscalationError(command ?? tool.name, safetyVerdict?.outcome, safetyVerdict?.reason, escalatedBy, renderNegotiationTranscript(negotiationRounds, negotiationAttempts) ?? undefined);
289
1265
  }
290
- // Surface the judge's verdict to the human prompt (if the judge escalated) without mutating
291
- // the original interrupt object the caller holds.
292
- const pending = safetyVerdict ? { ...tool, safetyVerdict } : tool;
1266
+ // §4.2 **a `catastrophic` approval is NEVER sticky.** "The human may approve this one
1267
+ // invocation, and only this one": no always-allow, and no session-scoped allow either. The
1268
+ // surface withdraws the affordance ([[TUI-C26]] drops `always approve` from the menu for this
1269
+ // outcome), but the allow-list WRITE is decided here, and §3 has the allow-list consulted
1270
+ // *before* the rater — so one sticky grant would remove the command from rating permanently,
1271
+ // and the next `terraform destroy` would never be rated at all. Clamping here means the policy
1272
+ // does not depend on which surface asked, or on a surface that has not been built yet.
1273
+ const catastrophic = safetyVerdict?.outcome === 'catastrophic';
1274
+ // §6 — **the menu must display what it is about to store**, at the moment of the choice, on
1275
+ // every surface. It is rendered from the very grant {@link recordApproval} will write, because a
1276
+ // menu that describes a grant one way and stores it another is the drift this design cannot
1277
+ // afford. Absent exactly where no sticky grant is available — a `catastrophic` outcome (§4.2
1278
+ // withdraws the persistent grants for EVERY subject, not only the shell one), or a call nothing
1279
+ // would remember — so the prompt never advertises a control that has already been withdrawn.
1280
+ const grant = catastrophic ? undefined : this.stickyGrantFor(subject, effective, hosts);
1281
+ const grantPreview = grant ? renderApprovalEntryObject(grant.entry) : undefined;
1282
+ // §6 — the same grant in the words the menu's *always approve* control is written in, through
1283
+ // the one-liner the §4.7.4 withdrawal notice also uses, so the two cannot describe one grant
1284
+ // two ways. For a tool call this is where "the stored thing is the tool, not the arguments"
1285
+ // becomes visible: it names the tool, its server and the host bound, and nothing else.
1286
+ const grantSummary = grant ? describeApprovalEntry(grant.entry) : undefined;
1287
+ // [[TUI-C26]] §6 — the deny half, computed SEPARATELY rather than read off the grant. The two
1288
+ // are available under different conditions and `grant === undefined` is the wrong test for
1289
+ // both: a command that does not statically resolve, and every `catastrophic` verdict, have no
1290
+ // grant on offer and a perfectly good deny entry.
1291
+ const denyEntry = this.denyEntryFor(subject);
1292
+ const denyPreview = denyEntry ? renderApprovalEntryObject(denyEntry) : undefined;
1293
+ const denySummary = denyEntry ? describeApprovalEntry(denyEntry) : undefined;
1294
+ // Surface the rater's verdict, the escalate entry that fired as provenance (§3.2), and what
1295
+ // each sticky choice would store (§6) — without mutating the original interrupt object the
1296
+ // caller holds.
1297
+ //
1298
+ // **`denyPreview` belongs in this condition, and leaving it out is a silent hole rather than a
1299
+ // tidiness question.** The most ordinary prompt in the system — a deterministic rung, no
1300
+ // rating, no escalate entry, no negotiation, a command that does not statically resolve — has
1301
+ // none of the other four, so without this term the interrupt would pass through unchanged and
1302
+ // the *always reject* control would vanish from exactly the case it exists for.
1303
+ //
1304
+ // [[TUI-C67]] — **the subject is attached unconditionally**, outside every optional term above,
1305
+ // because the terminal surfaces render the prompt's opening sentence from it and there is no
1306
+ // call this question does not have an answer for. (The ACP server does not read it yet, and
1307
+ // titles its permission request from its own classifier — [[TUI-C89]]. That narrows who
1308
+ // consumes the field, never whether it has to be set.) It cannot be one more
1309
+ // `...(x ? {x} : {})`:
1310
+ // an `mcpTool` call whose server could not be attributed has neither a grant nor a deny entry
1311
+ // (§4.7.4 / the entry grammar's non-empty `server`), so at an unrated rung with no escalate
1312
+ // entry it is exactly the call that would fall through to a bare `tool` — and it is exactly
1313
+ // the call the new header exists for.
1314
+ const pending = {
1315
+ ...tool,
1316
+ subject,
1317
+ ...(safetyVerdict ? { safetyVerdict } : {}),
1318
+ ...(escalatedBy ? { escalatedBy } : {}),
1319
+ ...(grantPreview ? { grantPreview } : {}),
1320
+ ...(grantSummary ? { grantSummary } : {}),
1321
+ ...(denyPreview ? { denyPreview } : {}),
1322
+ ...(denySummary ? { denySummary } : {}),
1323
+ ...(negotiationRounds.length > 0 ? { negotiationRounds, negotiationAttempts } : {}),
1324
+ };
293
1325
  const decision = await this.toolApprovalCallback(pending);
294
- // Persist the human's scoped grant so future variants of the same operation skip the prompt.
295
- if (decision.type === 'approve' && allowlistApplies && command) {
296
- this.recordApproval(command, decision.scope ?? 'once');
1326
+ // [[TUI-C27]] a person was reached and answered. The STAGE stays whatever decided to ask
1327
+ // them (a rating, an escalate entry, an unrated rung): "who decided to interrupt" and "what
1328
+ // they said" are two different questions, and collapsing them into one field is what makes a
1329
+ // dump unable to tell a rater escalation from a declared one.
1330
+ record.humanAnswer = decision.type === 'approve' ? 'approve' : 'reject';
1331
+ // Record the human's scoped grant so the same call stops re-prompting.
1332
+ if (decision.type === 'approve' && grant) {
1333
+ this.recordApproval(grant, decision.scope ?? 'once');
1334
+ }
1335
+ // §6 — and the mirror: *always reject* records the refusal, so the next identical call is
1336
+ // refused by rule at step (1) without reaching a person. Scoped `session` and nothing else,
1337
+ // because that is the only lifetime the store has (see {@link ToolRejectScope}).
1338
+ if (decision.type === 'reject' && decision.scope === 'session' && denyEntry) {
1339
+ this.recordDenial(denyEntry);
297
1340
  }
298
1341
  return decision;
299
1342
  }
300
- /** Whether the EXT-10 LLM-as-judge safety gate is enabled for the active command's config. */
301
- isShellJudgeOn() {
302
- if (!this.config)
303
- return false;
304
- const devTools = getEffectiveDevToolsConfig(this.config, this.command);
305
- return isShellJudgeEnabled(devTools);
306
- }
307
- /** Whether the EXT-9 Tier-2 allow-list is enabled for the active command's devTools config. */
308
- isShellAllowlistOn() {
309
- const devTools = getEffectiveDevToolsConfig(this.config ?? undefined, this.command);
310
- return isShellAllowlistEnabled(devTools);
1343
+ /**
1344
+ * [[TUI-C27]] — attribute the deciding stage and hand the decision straight back.
1345
+ *
1346
+ * A one-liner so a stage can be recorded ON the `return` that carries it rather than on the line
1347
+ * above: two statements let an early return be added between them, and the record would then name
1348
+ * a stage that did not decide.
1349
+ */
1350
+ stage(record, stage, decision) {
1351
+ record.stage = stage;
1352
+ return decision;
311
1353
  }
312
1354
  /**
313
- * Lazily load (once per instance) the persisted `always` allow-list, unless persistence is
314
- * disabled by config. Returns null when persistence is off so `always` grants behave as
315
- * `session` (in-memory only).
1355
+ * One rating call, with EXT-66's timeout reporting attached. Extracted so the §3.2 tripwire (a
1356
+ * rated allow match) and the ordinary rater path cannot drift apart in WHAT they hand the rater —
1357
+ * only in what they do with the answer.
316
1358
  */
317
- getPersistedAllowlist() {
318
- if (this.persistedAllowlistLoaded)
319
- return this.persistedAllowlist;
320
- this.persistedAllowlistLoaded = true;
321
- const devTools = getEffectiveDevToolsConfig(this.config ?? undefined, this.command);
322
- if (!isShellAllowlistPersisted(devTools)) {
323
- this.persistedAllowlist = null;
324
- return null;
1359
+ async rateCommand(command, opts,
1360
+ /** [[TUI-C27]] — the decision's record; the rating attaches itself to it at the send site. */
1361
+ record) {
1362
+ const approvals = this.sessionApprovals;
1363
+ const verdict = await rateShellCommand(command, this.config, {
1364
+ home: env?.HOME,
1365
+ negotiation: opts.negotiation,
1366
+ negotiable: opts.negotiable,
1367
+ // [[TUI-C27]] — the sink fires BEFORE the model is invoked, with the prompt that is about to
1368
+ // be sent, so the record carries what the rater was SHOWN rather than a later re-render of
1369
+ // it. Assigning it here (rather than pushing a finished record afterwards) is what makes a
1370
+ // hung, timed-out or halting call still leave the question behind.
1371
+ onCapture: (capture) => {
1372
+ record.rating = capture;
1373
+ },
1374
+ raterProfile: approvals.rater,
1375
+ // The profile's model when one is configured; undefined lets rateShellCommand use the
1376
+ // session model. `init` throws rather than leaving this undefined for a NAMED profile, so
1377
+ // a configured profile can never silently degrade to the session model here.
1378
+ model: this.raterModel,
1379
+ // EXT-58 (§4.4) — the already-granted built-ins of the CURRENT rung, so a non-`safe`
1380
+ // outcome can name one the model could call for free instead. Computed per rating rather
1381
+ // than cached at init, because `/approvals <rung>` moves the rung mid-session and a stale
1382
+ // list would offer a tool that is no longer granted.
1383
+ grantedTools: this.getGrantedBuiltInTools(),
1384
+ // EXT-66 — the user-owned budget for ONE rating call, `undefined` when unset so
1385
+ // rateShellCommand applies RATER_DEFAULT_TIMEOUT_MS. 30s is a hosted-model number and a
1386
+ // local rater is knowably slower; without this a local `auto` session drifts toward
1387
+ // escalating everything, which is the failure the rung exists to prevent.
1388
+ timeoutMs: approvals.raterTimeoutMs,
1389
+ });
1390
+ // EXT-66 — a timeout is the gate giving up, not a judgement, and the two were previously
1391
+ // indistinguishable in the action column. Say it once per occurrence: the only symptom
1392
+ // otherwise is the gate becoming mysteriously more talkative, which reads as the rater
1393
+ // working rather than as the rater never being heard from.
1394
+ if (isRaterTimeout(verdict)) {
1395
+ this.raterTimeouts += 1;
1396
+ this.statusUpdate(StatusLevel.WARNING, `The command safety rater did not answer in time (${approvals.raterTimeoutMs ?? RATER_DEFAULT_TIMEOUT_MS}ms), so this command ` +
1397
+ // §3.2 — on an allow match the rating is a tripwire, so a timeout does not escalate: the
1398
+ // human's standing grant still stands and the call runs. Saying "escalated" there would
1399
+ // be simply false, and a notice that misreports the action it accompanies is worse than
1400
+ // none.
1401
+ (opts.allowMatched
1402
+ ? 'ran on its approvals.allow match alone, without the rating that entry asked for'
1403
+ : 'was escalated without being rated') +
1404
+ (this.raterTimeouts > 1 ? ` — ${this.raterTimeouts} times this session` : '') +
1405
+ '. Raise approvals.raterTimeoutMs if the rater is a local model.');
325
1406
  }
1407
+ return verdict;
1408
+ }
1409
+ /**
1410
+ * EXT-58 (§4.3/§4.4) — the built-in tools already granted at the session's CURRENT rung, as
1411
+ * names plus one-line locally-authored descriptions, for the rater prompt.
1412
+ *
1413
+ * Two filters make this safe to place outside the rater's fenced untrusted block:
1414
+ * - the names come from what the agent actually registered
1415
+ * ({@link GthAgentInterface.getRegisteredToolNames}), so the rater can only ever offer a tool
1416
+ * this session has;
1417
+ * - the descriptions come from core's own `BUILT_IN_TOOL_SUMMARIES` table, so no MCP, custom or
1418
+ * A2A tool's own (attacker-influenceable) description can reach the prompt.
1419
+ *
1420
+ * Empty when the agent does not expose its tools — the rater then gets no list and, per the
1421
+ * prompt, offers nothing.
1422
+ */
1423
+ getGrantedBuiltInTools() {
1424
+ const registered = this.agent?.getRegisteredToolNames?.() ?? [];
1425
+ if (registered.length === 0)
1426
+ return [];
1427
+ // The LIVE gated set, from the SAME shared policy `decideToolApproval` decides on and the
1428
+ // backends derive their interrupt from, so "granted" here means exactly what it means at
1429
+ // tool-registration time (§4.5) and at the gate.
1430
+ //
1431
+ // EXT-80 makes this non-drift property load-bearing rather than incidental. At `manual` the
1432
+ // write built-ins are gated, so they are NOT granted, and a summary still offering `write_file`
1433
+ // there would tell the model a tool is free while the gate stops and asks for it — the rater
1434
+ // suggesting the one thing guaranteed to interrupt the user. It is computed per rating from
1435
+ // `sessionApprovals.rung`, so it follows a mid-session `/approvals` change — unlike the
1436
+ // interrupt set, which is fixed when the graph is built and is rung-independent for exactly
1437
+ // that reason.
1438
+ const { gateShell } = resolveShellApprovalGate(this.config ?? undefined, this.command);
1439
+ const gatedTools = resolveGatedToolNames({
1440
+ rung: this.sessionApprovals.rung,
1441
+ gateShell,
1442
+ boundToolNames: registered,
1443
+ });
1444
+ return describeGrantedBuiltInTools(registered, this.sessionApprovals.rung, gatedTools);
1445
+ }
1446
+ /**
1447
+ * §3/§3.3 — the three rule lists this session decides by: the DECLARED entries from config
1448
+ * (read-only input) concatenated with the runtime grants the escalation menu made. One set of
1449
+ * lists, handed to the one comparison engine; the concatenation cannot change any outcome
1450
+ * because `resolveApprovalRules` consults every deny entry before any escalate entry and every
1451
+ * escalate entry before any allow entry.
1452
+ *
1453
+ * The persisted store is loaded here rather than at {@link init} — lazily, once per instance, and
1454
+ * NEVER at `bypass`, where the allow list is moot and a session that has switched the gate off
1455
+ * should not be reading or rewriting the project's grant file.
1456
+ */
1457
+ approvalRuleLists() {
1458
+ const approvals = this.sessionApprovals;
1459
+ const persisted = approvals.rung === 'bypass' ? null : this.getPersistedGrants();
1460
+ return {
1461
+ deny: [...approvals.deny, ...this.denyGrants.entries()],
1462
+ escalate: approvals.escalate,
1463
+ allow: [...approvals.allow, ...this.sessionGrants.entries(), ...(persisted?.entries() ?? [])],
1464
+ };
1465
+ }
1466
+ /**
1467
+ * Lazily load (once per instance) the persisted `always` grant store.
1468
+ *
1469
+ * CFG-27 removed the `persistAllowlist` switch: §3 makes persistence a per-decision choice in
1470
+ * the escalation menu (`approve` forgets, `always approve` persists), and a global "never
1471
+ * persist" setting would only duplicate a keystroke. Returns null when the store cannot be
1472
+ * loaded at all, in which case `always` grants degrade to `session` (in-memory only).
1473
+ *
1474
+ * The v1→v2 migration notice is routed to `statusUpdate` from here, which is the only place that
1475
+ * knows how to reach the user.
1476
+ */
1477
+ getPersistedGrants() {
1478
+ if (this.persistedGrantsLoaded)
1479
+ return this.persistedGrants;
1480
+ this.persistedGrantsLoaded = true;
326
1481
  try {
327
1482
  const filePath = getGslothConfigWritePath(SHELL_ALLOWLIST_FILE);
328
- this.persistedAllowlist = new PersistedAllowlist(filePath);
1483
+ this.persistedGrants = new PersistedApprovalGrants(filePath, {
1484
+ onNotice: (notice) => this.statusUpdate(notice.level, notice.message),
1485
+ });
329
1486
  }
330
1487
  catch (e) {
331
1488
  // Path/IO failure → behave as no persisted store (still safe: just prompts more).
332
- debugLogError('Loading persisted shell allow-list', e);
333
- this.persistedAllowlist = null;
1489
+ debugLogError('Loading persisted shell approvals', e);
1490
+ this.persistedGrants = null;
334
1491
  }
335
- return this.persistedAllowlist;
1492
+ return this.persistedGrants;
336
1493
  }
337
- /** Check the command against the session + persisted stores (with anti-widening re-validation). */
338
- isApprovedByAllowlist(command) {
339
- return matchesApproval(command, {
340
- session: this.sessionAllowlist,
341
- always: this.getPersistedAllowlist() ?? undefined,
342
- });
1494
+ /**
1495
+ * §3.1/§4.7.4/§6 — **the grant a sticky choice would write for this call**, or `undefined` when
1496
+ * none is on offer. The one place that question is answered, so the menu's *this is what will be
1497
+ * stored* line (§6) and the store can never disagree.
1498
+ *
1499
+ * - **A shell call** records the command itself as an `exact` entry (§3.1) — never a prefix,
1500
+ * never a pattern. One that does not statically resolve (composition, substitution,
1501
+ * redirection) is not on offer: no allow entry of any matcher matches such a command, so the
1502
+ * entry would be inert, and an inert entry sitting in a list §3 requires to be inspectable
1503
+ * tells the user something is in force when nothing is.
1504
+ * - **A tool call** records identity — the tool, its server, and the host where the call carries
1505
+ * one (§4.7.4, {@link toolGrantEntry}) — never arguments, which would produce a grant that
1506
+ * never matches twice. A call naming no host records the tool alone, which is §6's own example
1507
+ * (*always approve `mcp__jira__create_issue`*, where no host is involved); what keeps that from
1508
+ * being unbounded is §3.2's default that a tool entry is still `rate: true`, so the rater goes
1509
+ * on seeing every call's full arguments.
1510
+ *
1511
+ * Four cases have **no grant on offer at all**, each fail-closed:
1512
+ *
1513
+ * 1. **`bypass`** — the gate is off for this session and nothing is remembered from it.
1514
+ * 2. **`run_shell_command` arriving as a tool subject.** That is what a shell call with no
1515
+ * readable `command` argument presents as, and it names no host, so without this it would take
1516
+ * the tool-only arm and write a `{"type":"tool","pattern":"run_shell_command"}` grant that
1517
+ * auto-approves every future call whose command cannot even be read. This exclusion is what
1518
+ * stops that, not a side effect of anything else, and it must survive [[EXT-30]] widening the
1519
+ * gate.
1520
+ * 3. **A call naming more than one distinct host.** The grammar has no entry for it. `host` is a
1521
+ * single optional string on every tool arm of `approvalEntrySchema`, and every arm is a
1522
+ * `z.strictObject`, so recording the *set* is not a policy this code may choose — a `hosts`
1523
+ * array is an unrecognized-key error, and writing one would be a §3.1 grammar change. Of the
1524
+ * two entries that would parse, the host-bound one displays a bound the grant does not have,
1525
+ * which §6 forbids (the menu shows exactly what will be stored). And a grammar that did record
1526
+ * the set, matching only when all of it recurred, would fail §4.7.4's opening test anyway: a
1527
+ * tool whose host set varies per call would get a grant that never matches a second time — not
1528
+ * a narrower grant, the useless one §4.7.4 rejects by name.
1529
+ *
1530
+ * **What this arm does not claim.** It is not a narrowing. A hostless entry imposes no host
1531
+ * condition at all (`resolveApprovalRules`), so the tool-only grant that any host-less call to
1532
+ * the same tool produces already auto-approves a multi-host one. Refusing here withholds a
1533
+ * grant; it does not close a hole, and the reason to keep it is the grammar above rather than
1534
+ * any breadth it prevents. Asserted, so this cannot drift back into a claim the system does not
1535
+ * support.
1536
+ * 4. **An MCP call whose server could not be resolved** ({@link toolGrantEntry} returns `null`) —
1537
+ * a call nobody can attribute is not one anything can remember.
1538
+ */
1539
+ stickyGrantFor(subject, effective, hosts) {
1540
+ if (this.sessionApprovals.rung === 'bypass')
1541
+ return undefined;
1542
+ if (subject.kind === 'shell') {
1543
+ if (classifyCommand(subject.command, normalizeCommand) === null)
1544
+ return undefined;
1545
+ return { entry: shellGrantEntry(subject.command) };
1546
+ }
1547
+ if (subject.name === SHELL_TOOL_NAME)
1548
+ return undefined;
1549
+ // A snapshot is what invalidation compares against, so a grant with no readable effective set
1550
+ // is a grant nothing could ever invalidate.
1551
+ if (!effective)
1552
+ return undefined;
1553
+ if (hosts.length > 1)
1554
+ return undefined;
1555
+ const entry = toolGrantEntry(subject);
1556
+ if (!entry)
1557
+ return undefined;
1558
+ // §4.7.4 — the effective set the human approved this tool AS. `annotationWeakenings` compares a
1559
+ // later one against it, and the store copies it so the record is private to this grant.
1560
+ return { entry, annotations: effective };
1561
+ }
1562
+ /**
1563
+ * [[TUI-C26]] §6 — **the entry the escalation menu's *always reject* choice would record**, or
1564
+ * `undefined` when the grammar cannot hold one. The deny mirror of {@link stickyGrantFor}, and a
1565
+ * separate function rather than a flag on it, because the two answer different questions.
1566
+ *
1567
+ * **Nearly every reason an allow entry is withheld does not apply here.** §3 has one rule for
1568
+ * this and it runs the other way — *undecidable is a non-match on the allow side and a match on
1569
+ * the deny side* — so:
1570
+ *
1571
+ * - **A command that does not statically resolve gets an entry.** `stickyGrantFor` refuses one
1572
+ * because no allow entry of any matcher would ever match it, making the entry inert; a deny
1573
+ * entry for the same command is matched against the whole normalized command *and* every
1574
+ * segment a shell would run, so it is the opposite of inert.
1575
+ * - **A `catastrophic` verdict changes nothing.** §4.2 withdraws the sticky grants there; it says
1576
+ * nothing about refusals, and refusing more is never the direction that needs withdrawing.
1577
+ * - **`bypass` changes nothing either**, and that is a positive statement rather than a gap. Deny
1578
+ * is resolved at step (1) of {@link decideToolApprovalInner}, *before* the `bypass` return, so
1579
+ * a recorded refusal is in force at every rung — which is why this does not copy the allow
1580
+ * side's `bypass` guard.
1581
+ * - **A call naming several hosts gets the host-less entry.** On the allow side that would show a
1582
+ * bound the grant does not have; here the entry covers every host of that tool, which is
1583
+ * broader than the call and safe in the direction breadth is safe. The menu shows exactly that
1584
+ * entry, so the breadth is on screen rather than inferred.
1585
+ * - **`run_shell_command` arriving as a TOOL subject gets a tool entry** — a shell call whose
1586
+ * `command` argument cannot even be read. On the allow side that entry would auto-approve every
1587
+ * future unreadable shell call, which is why it is excluded there; as a refusal it stops the
1588
+ * shell tool for the session, and the dialog says so in the words the entry is written in.
1589
+ *
1590
+ * The one genuine exclusion is an **MCP call whose server could not be attributed**
1591
+ * ({@link toolGrantEntry} returns `null`): the grammar's `server` cannot be the empty string, so
1592
+ * the entry would be dropped by its own validator and the human would be told a refusal had been
1593
+ * recorded when none was. A shell command that normalizes to nothing is excluded for the same
1594
+ * reason — an empty `pattern` is not a legal entry.
1595
+ */
1596
+ denyEntryFor(subject) {
1597
+ if (subject.kind === 'shell') {
1598
+ const entry = shellGrantEntry(subject.command);
1599
+ return entry.pattern.length > 0 ? entry : undefined;
1600
+ }
1601
+ return toolGrantEntry(subject) ?? undefined;
1602
+ }
1603
+ /**
1604
+ * §6 — record the menu's *always reject* choice, for the life of this runner instance.
1605
+ *
1606
+ * It lands in the same store `approvals.deny` entries are matched from ({@link approvalRuleLists}
1607
+ * concatenates the two), so a refusal the human made at the prompt and one they wrote in their
1608
+ * config are one list to the matcher and one list to `/approvals`.
1609
+ *
1610
+ * **Session-lifetime, and there is nothing else to choose.** There is no persisted deny file;
1611
+ * whether there should be is a question about a file users live with, not about this prompt. What
1612
+ * the surfaces must not do is say otherwise — a confirmation promising a persistence that did not
1613
+ * happen is §6's *offered and then refused* with the evidence hidden.
1614
+ */
1615
+ recordDenial(entry) {
1616
+ this.denyGrants.add({ entry, grantedAt: new Date().toISOString(), scope: 'session' });
343
1617
  }
344
1618
  /**
345
- * Record a human-granted approval at the given scope. `once` persists nothing. `session`
346
- * adds the classified prefix to the in-memory store. `always` additionally persists it (or
347
- * falls back to session-only when persistence is disabled).
1619
+ * §3.1/§6 — record a human-granted approval at the given scope. `once` remembers nothing.
1620
+ * `session` adds the entry to the in-memory store; `always` additionally persists it (falling
1621
+ * back to session-only when the file cannot be written).
1622
+ *
1623
+ * What is recorded was decided by {@link stickyGrantFor} and shown to the human before they
1624
+ * answered; this only stamps it with when and at what scope.
348
1625
  */
349
- recordApproval(command, scope) {
1626
+ recordApproval(grant, scope) {
350
1627
  if (scope === 'once')
351
1628
  return;
352
- const classification = classifyCommand(command, normalizeCommand);
353
- if (!classification)
354
- return; // unclassifiable (composition/redirection) → never remember.
355
- this.sessionAllowlist.add(classification.prefix);
1629
+ const grantScope = scope;
1630
+ const record = {
1631
+ ...grant,
1632
+ grantedAt: new Date().toISOString(),
1633
+ scope: grantScope,
1634
+ };
1635
+ this.sessionGrants.add(record);
356
1636
  if (scope === 'always') {
357
- this.getPersistedAllowlist()?.add(classification.prefix);
1637
+ this.getPersistedGrants()?.add(record);
1638
+ }
1639
+ }
1640
+ /**
1641
+ * §4.7.4 — **drop a tool grant the tool has since weakened out from under, with a notice naming
1642
+ * the tool, the server and the hint that moved.**
1643
+ *
1644
+ * The human approved a tool *as annotated*; a tool that re-annotates itself into a more dangerous
1645
+ * shape is a different proposition wearing the same name, so the grant is invalidated and the next
1646
+ * call prompts again. Only a **trusted** server can produce a weakening — an untrusted server's
1647
+ * effective set is the constant fail-closed default (§4.7.1) and cannot move — which is exactly
1648
+ * where it matters, since the trusted server is the one whose rug-pull would otherwise ride an
1649
+ * existing grant.
1650
+ *
1651
+ * **Scoped to the call being decided, never a sweep of the store.** A sweep would read every held
1652
+ * grant against a source that can only answer for the tools registered right now, so a server that
1653
+ * happened to be offline would read as having weakened everything it ever declared — and the
1654
+ * grants would be deleted for it.
1655
+ *
1656
+ * **The scope is every grant that could auto-approve THIS call, which is at most two.** A grant
1657
+ * with no `host` imposes no host condition, so it matches a call that carries one; looking up only
1658
+ * the entry this call would grant (`host` included) would miss the tool-only grant that is about
1659
+ * to auto-approve it, and the weakening would ride straight through — the exact failure §4.7.4
1660
+ * exists to stop. The host-bound entry of a DIFFERENT host is deliberately not a candidate: it
1661
+ * does not match this call either, so this call's annotations say nothing about it.
1662
+ *
1663
+ * **Only allow-side grants.** A weakening makes a tool more dangerous, so dropping an *always
1664
+ * reject* over one would be the unsafe direction: the reason to withdraw an approval is the reason
1665
+ * to keep a refusal.
1666
+ */
1667
+ invalidateWeakenedGrants(subject, effective) {
1668
+ const candidates = [
1669
+ toolGrantEntry(subject),
1670
+ ...(subject.host !== undefined ? [toolGrantEntry({ ...subject, host: undefined })] : []),
1671
+ ].filter((entry) => entry !== null);
1672
+ if (candidates.length === 0)
1673
+ return;
1674
+ // Never at `bypass`, for the same reason `approvalRuleLists` does not read the file there: a
1675
+ // session that has switched the gate off should not be rewriting the project's grant file.
1676
+ const persisted = this.sessionApprovals.rung === 'bypass' ? null : this.getPersistedGrants();
1677
+ for (const entry of candidates) {
1678
+ // The session store wins, and a session grant with no snapshot therefore hides a persisted one
1679
+ // that has one. Safe only because all three of these hold, and each is a premise a later change
1680
+ // could break silently: (1) every tool grant this runner writes carries a snapshot — a call with
1681
+ // no readable effective set is refused a grant at all ({@link stickyGrantFor}); (2) a `shell`
1682
+ // subject, the one kind whose grant has no snapshot by design, never reaches this method; and
1683
+ // (3) a persisted grant already in force auto-approves the call, so no prompt happens and no
1684
+ // session grant is written over it. Break any one of them and this line starts skipping a
1685
+ // weakening it should have caught — check both stores then, rather than the first that answers.
1686
+ const held = this.sessionGrants.find(entry) ?? persisted?.find(entry);
1687
+ if (!held?.annotations)
1688
+ continue;
1689
+ const weakened = annotationWeakenings(held.annotations, effective);
1690
+ if (weakened.length === 0)
1691
+ continue;
1692
+ // Removed rather than skipped: the stores de-duplicate by entry identity, so a grant left in
1693
+ // place would silently swallow the human's re-approval of the same tool.
1694
+ this.sessionGrants.remove(entry);
1695
+ persisted?.remove(entry);
1696
+ this.statusUpdate(StatusLevel.WARNING, describeWeakenedGrant(entry, weakened, held.annotations, effective));
358
1697
  }
359
1698
  }
360
1699
  /**
@@ -372,7 +1711,7 @@ export class GthAgentRunner {
372
1711
  * leaves the graph suspended on a `humanInTheLoopMiddleware` interrupt rather than
373
1712
  * completing. This is the event-stream counterpart to the readline path's
374
1713
  * {@link resolveToolInterrupts}: it drains any pending interrupts through
375
- * {@link decideToolApproval} (allow-list → judge → bridged human prompt), resumes via
1714
+ * {@link decideToolApproval} (bypass → allow-list → rater → bridged human prompt), resumes via
376
1715
  * `streamWithEventsResume({ decisions })`, and loops until the graph completes with no
377
1716
  * pending interrupts — so the executed command's output renders into the TUI. Without
378
1717
  * this the TUI silently finalized an empty turn (approval gate was dead code on the
@@ -384,6 +1723,14 @@ export class GthAgentRunner {
384
1723
  }
385
1724
  // GS2-16: start this turn's analytics tally from zero (the runner is reused across turns).
386
1725
  this.resetRunStats();
1726
+ // GS2-48 — record this turn's transcript tail for the crash handler.
1727
+ updateCrashContext({ transcriptTail: messages.slice(-CRASH_TRANSCRIPT_TAIL_MESSAGES) });
1728
+ // [[EXT-29]] §5 — a new user turn is the human being reached, so it ends any negotiation still
1729
+ // standing from the previous one and clears BOTH bounds. The turn's own messages then enter
1730
+ // §5.1's last-5 window, which is what makes "just the last two" reach the rater at all — the
1731
+ // reply that narrows what the agent proposes is worthless to the gate if only the agent hears it.
1732
+ this.negotiation.humanReached();
1733
+ this.negotiation.noteUserMessages(humanMessageTexts(messages));
387
1734
  debugLog('Processing messages (event stream)...');
388
1735
  debugLogObject('Input Messages', messages);
389
1736
  yield* this.agent.streamWithEvents(messages, this.runConfig, signal);
@@ -394,15 +1741,18 @@ export class GthAgentRunner {
394
1741
  * resolve any tool-approval interrupts it suspended on, yielding the resumed run's typed
395
1742
  * {@link AgentStreamEvent}s so the renderer (the Ink TUI) shows the executed command's
396
1743
  * output. Each pending tool call is consulted via {@link decideToolApproval} — the SAME
397
- * three-layer gate the readline path uses (allow-list auto-approve → EXT-10 judge
1744
+ * gate the readline path uses (bypass → allow-list approve → CFG-26 AI rater
398
1745
  * bridged human callback, defaulting to REJECT when no handler is wired) — and the
399
1746
  * collected decisions are sent back via `streamWithEventsResume` as a LangChain HITL
400
1747
  * resume (`{ decisions }`). Because a resumed run can suspend again on the next gated
401
1748
  * tool call, this loops until the graph completes with no pending interrupts.
402
1749
  *
403
1750
  * No-ops (yields nothing) when the agent does not support interrupts
404
- * (`getPendingToolInterrupts`/`streamWithEventsResume` absent), so the lean agent and
405
- * non-HITL configs are unaffected. Aborts (`signal`) propagate through the resumed stream.
1751
+ * (`getPendingToolInterrupts`/`streamWithEventsResume` absent) that is the only exemption.
1752
+ * As of EXT-52 BOTH backends gate `run_shell_command` and expose the interrupt surface, so the
1753
+ * lean (default) agent is now exactly the agent this loop serves; only an agent implementation
1754
+ * without those methods (e.g. a test double) skips it. Aborts (`signal`) propagate through the
1755
+ * resumed stream.
406
1756
  */
407
1757
  async *resolveToolInterruptsWithEvents(signal) {
408
1758
  const agent = this.agent;
@@ -477,6 +1827,10 @@ export class GthAgentRunner {
477
1827
  * of any checkpointer-specific delete API, mirroring how `init()` mints the initial config.
478
1828
  */
479
1829
  resetThread() {
1830
+ // [[EXT-29]] §5.1 — the negotiation goes with the thread, user messages included. The rater's
1831
+ // last-5 window is conversation context; leaving it behind a `/clear` would quote the user's
1832
+ // previous conversation into a rating made after they asked for it to be forgotten.
1833
+ this.negotiation.clear();
480
1834
  this.runConfig = getNewRunnableConfig();
481
1835
  debugLogObject('Reset Runnable Config', this.runConfig);
482
1836
  }