@gaunt-sloth/core 2.0.0-alpha.3 → 2.0.0-alpha.31

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 (271) hide show
  1. package/README.md +52 -20
  2. package/dist/config/colour.d.ts +38 -0
  3. package/dist/config/colour.js +36 -0
  4. package/dist/config/colour.js.map +1 -0
  5. package/dist/config/defaults.d.ts +84 -0
  6. package/dist/config/defaults.js +99 -0
  7. package/dist/config/defaults.js.map +1 -0
  8. package/dist/config/filesystem-tools.d.ts +41 -0
  9. package/dist/config/filesystem-tools.js +56 -0
  10. package/dist/config/filesystem-tools.js.map +1 -0
  11. package/dist/config/jsonc.d.ts +12 -0
  12. package/dist/config/jsonc.js +41 -0
  13. package/dist/config/jsonc.js.map +1 -0
  14. package/dist/config/loader.d.ts +246 -0
  15. package/dist/config/loader.js +1321 -0
  16. package/dist/config/loader.js.map +1 -0
  17. package/dist/config/mouse.d.ts +50 -0
  18. package/dist/config/mouse.js +44 -0
  19. package/dist/config/mouse.js.map +1 -0
  20. package/dist/config/profiles.d.ts +68 -0
  21. package/dist/config/profiles.js +93 -0
  22. package/dist/config/profiles.js.map +1 -0
  23. package/dist/config/providerKeys.d.ts +69 -0
  24. package/dist/config/providerKeys.js +69 -0
  25. package/dist/config/providerKeys.js.map +1 -0
  26. package/dist/config/schema.d.ts +2999 -0
  27. package/dist/config/schema.js +1519 -0
  28. package/dist/config/schema.js.map +1 -0
  29. package/dist/config/shell-policy.d.ts +896 -0
  30. package/dist/config/shell-policy.js +750 -0
  31. package/dist/config/shell-policy.js.map +1 -0
  32. package/dist/config/tool-descriptions.d.ts +211 -0
  33. package/dist/config/tool-descriptions.js +272 -0
  34. package/dist/config/tool-descriptions.js.map +1 -0
  35. package/dist/config/types.d.ts +760 -0
  36. package/dist/config/types.js +13 -0
  37. package/dist/config/types.js.map +1 -0
  38. package/dist/config.d.ts +34 -827
  39. package/dist/config.js +25 -657
  40. package/dist/config.js.map +1 -1
  41. package/dist/constants.d.ts +46 -0
  42. package/dist/constants.js +46 -0
  43. package/dist/constants.js.map +1 -1
  44. package/dist/core/GthAbstractAgent.d.ts +135 -2
  45. package/dist/core/GthAbstractAgent.js +496 -30
  46. package/dist/core/GthAbstractAgent.js.map +1 -1
  47. package/dist/core/GthAgentRunner.d.ts +568 -54
  48. package/dist/core/GthAgentRunner.js +1537 -136
  49. package/dist/core/GthAgentRunner.js.map +1 -1
  50. package/dist/core/GthLangChainAgent.d.ts +115 -0
  51. package/dist/core/GthLangChainAgent.js +644 -17
  52. package/dist/core/GthLangChainAgent.js.map +1 -1
  53. package/dist/core/approvals/annotations.d.ts +122 -0
  54. package/dist/core/approvals/annotations.js +137 -0
  55. package/dist/core/approvals/annotations.js.map +1 -0
  56. package/dist/core/approvals/grants.d.ts +216 -0
  57. package/dist/core/approvals/grants.js +469 -0
  58. package/dist/core/approvals/grants.js.map +1 -0
  59. package/dist/core/approvals/matcher.d.ts +202 -0
  60. package/dist/core/approvals/matcher.js +267 -0
  61. package/dist/core/approvals/matcher.js.map +1 -0
  62. package/dist/core/approvals/mcpSubjects.d.ts +40 -0
  63. package/dist/core/approvals/mcpSubjects.js +99 -0
  64. package/dist/core/approvals/mcpSubjects.js.map +1 -0
  65. package/dist/core/approvals/toolAnnotationSources.d.ts +105 -0
  66. package/dist/core/approvals/toolAnnotationSources.js +277 -0
  67. package/dist/core/approvals/toolAnnotationSources.js.map +1 -0
  68. package/dist/core/approvals/toolHost.d.ts +46 -0
  69. package/dist/core/approvals/toolHost.js +108 -0
  70. package/dist/core/approvals/toolHost.js.map +1 -0
  71. package/dist/core/debugCapture.d.ts +75 -0
  72. package/dist/core/debugCapture.js +101 -0
  73. package/dist/core/debugCapture.js.map +1 -0
  74. package/dist/core/gthLeanAgentFactory.d.ts +9 -0
  75. package/dist/core/gthLeanAgentFactory.js +10 -0
  76. package/dist/core/gthLeanAgentFactory.js.map +1 -0
  77. package/dist/core/launchBanner.d.ts +120 -0
  78. package/dist/core/launchBanner.js +418 -0
  79. package/dist/core/launchBanner.js.map +1 -0
  80. package/dist/core/plainToolIndication.d.ts +15 -0
  81. package/dist/core/plainToolIndication.js +174 -0
  82. package/dist/core/plainToolIndication.js.map +1 -0
  83. package/dist/core/reasoningBlocks.d.ts +60 -0
  84. package/dist/core/reasoningBlocks.js +98 -0
  85. package/dist/core/reasoningBlocks.js.map +1 -0
  86. package/dist/core/refusal.d.ts +53 -0
  87. package/dist/core/refusal.js +133 -0
  88. package/dist/core/refusal.js.map +1 -0
  89. package/dist/core/runStats.d.ts +52 -0
  90. package/dist/core/runStats.js +118 -0
  91. package/dist/core/runStats.js.map +1 -0
  92. package/dist/core/shell/ShellCommandFailedError.d.ts +54 -0
  93. package/dist/core/shell/ShellCommandFailedError.js +68 -0
  94. package/dist/core/shell/ShellCommandFailedError.js.map +1 -0
  95. package/dist/core/shell/abstention.d.ts +88 -0
  96. package/dist/core/shell/abstention.js +184 -0
  97. package/dist/core/shell/abstention.js.map +1 -0
  98. package/dist/core/shell/approvalCapture.d.ts +271 -0
  99. package/dist/core/shell/approvalCapture.js +108 -0
  100. package/dist/core/shell/approvalCapture.js.map +1 -0
  101. package/dist/core/shell/approvalStop.d.ts +84 -0
  102. package/dist/core/shell/approvalStop.js +119 -0
  103. package/dist/core/shell/approvalStop.js.map +1 -0
  104. package/dist/core/shell/arity.d.ts +6 -0
  105. package/dist/core/shell/arity.js +20 -6
  106. package/dist/core/shell/arity.js.map +1 -1
  107. package/dist/core/shell/denylist.d.ts +11 -0
  108. package/dist/core/shell/denylist.js +37 -0
  109. package/dist/core/shell/denylist.js.map +1 -0
  110. package/dist/core/shell/escalationSeverity.d.ts +141 -0
  111. package/dist/core/shell/escalationSeverity.js +89 -0
  112. package/dist/core/shell/escalationSeverity.js.map +1 -0
  113. package/dist/core/shell/framing.d.ts +190 -0
  114. package/dist/core/shell/framing.js +633 -0
  115. package/dist/core/shell/framing.js.map +1 -0
  116. package/dist/core/shell/hardline.d.ts +81 -0
  117. package/dist/core/shell/hardline.js +607 -0
  118. package/dist/core/shell/hardline.js.map +1 -0
  119. package/dist/core/shell/negotiation.d.ts +249 -0
  120. package/dist/core/shell/negotiation.js +355 -0
  121. package/dist/core/shell/negotiation.js.map +1 -0
  122. package/dist/core/shell/normalize.d.ts +44 -4
  123. package/dist/core/shell/normalize.js +61 -7
  124. package/dist/core/shell/normalize.js.map +1 -1
  125. package/dist/core/shell/openWorld.d.ts +263 -0
  126. package/dist/core/shell/openWorld.js +1188 -0
  127. package/dist/core/shell/openWorld.js.map +1 -0
  128. package/dist/core/shell/rater.d.ts +935 -0
  129. package/dist/core/shell/rater.js +1473 -0
  130. package/dist/core/shell/rater.js.map +1 -0
  131. package/dist/core/shell/raterModel.d.ts +41 -0
  132. package/dist/core/shell/raterModel.js +51 -0
  133. package/dist/core/shell/raterModel.js.map +1 -0
  134. package/dist/core/shell/rejection.d.ts +69 -0
  135. package/dist/core/shell/rejection.js +38 -0
  136. package/dist/core/shell/rejection.js.map +1 -0
  137. package/dist/core/toolCallRepair/grammar.d.ts +41 -0
  138. package/dist/core/toolCallRepair/grammar.js +116 -0
  139. package/dist/core/toolCallRepair/grammar.js.map +1 -0
  140. package/dist/core/toolCallRepair/index.d.ts +2 -0
  141. package/dist/core/toolCallRepair/index.js +7 -0
  142. package/dist/core/toolCallRepair/index.js.map +1 -0
  143. package/dist/core/toolCallRepair/payload.d.ts +36 -0
  144. package/dist/core/toolCallRepair/payload.js +341 -0
  145. package/dist/core/toolCallRepair/payload.js.map +1 -0
  146. package/dist/core/toolCallRepair/promote.d.ts +45 -0
  147. package/dist/core/toolCallRepair/promote.js +90 -0
  148. package/dist/core/toolCallRepair/promote.js.map +1 -0
  149. package/dist/core/toolDisplay.d.ts +123 -0
  150. package/dist/core/toolDisplay.js +451 -0
  151. package/dist/core/toolDisplay.js.map +1 -0
  152. package/dist/core/toolOutputChannel.d.ts +95 -0
  153. package/dist/core/toolOutputChannel.js +165 -0
  154. package/dist/core/toolOutputChannel.js.map +1 -0
  155. package/dist/core/types.d.ts +294 -12
  156. package/dist/core/types.js.map +1 -1
  157. package/dist/history/historyFormat.d.ts +28 -0
  158. package/dist/history/historyFormat.js +127 -0
  159. package/dist/history/historyFormat.js.map +1 -0
  160. package/dist/history/historyStore.d.ts +198 -0
  161. package/dist/history/historyStore.js +482 -0
  162. package/dist/history/historyStore.js.map +1 -0
  163. package/dist/history/recordSession.d.ts +37 -0
  164. package/dist/history/recordSession.js +56 -0
  165. package/dist/history/recordSession.js.map +1 -0
  166. package/dist/index.d.ts +4 -0
  167. package/dist/index.js +4 -0
  168. package/dist/index.js.map +1 -1
  169. package/dist/providers/anthropic.d.ts +1 -1
  170. package/dist/providers/anthropic.js +5 -10
  171. package/dist/providers/anthropic.js.map +1 -1
  172. package/dist/providers/deepseek.d.ts +1 -1
  173. package/dist/providers/deepseek.js +5 -10
  174. package/dist/providers/deepseek.js.map +1 -1
  175. package/dist/providers/geminiSchemaSanitizer.d.ts +55 -0
  176. package/dist/providers/geminiSchemaSanitizer.js +347 -0
  177. package/dist/providers/geminiSchemaSanitizer.js.map +1 -0
  178. package/dist/providers/geminiThinking.d.ts +52 -0
  179. package/dist/providers/geminiThinking.js +72 -0
  180. package/dist/providers/geminiThinking.js.map +1 -0
  181. package/dist/providers/google-genai.d.ts +1 -1
  182. package/dist/providers/google-genai.js +12 -11
  183. package/dist/providers/google-genai.js.map +1 -1
  184. package/dist/providers/groq.d.ts +1 -1
  185. package/dist/providers/groq.js +5 -10
  186. package/dist/providers/groq.js.map +1 -1
  187. package/dist/providers/huggingface.d.ts +25 -0
  188. package/dist/providers/huggingface.js +69 -0
  189. package/dist/providers/huggingface.js.map +1 -0
  190. package/dist/providers/modelCatalog.d.ts +109 -0
  191. package/dist/providers/modelCatalog.js +245 -0
  192. package/dist/providers/modelCatalog.js.map +1 -0
  193. package/dist/providers/modelDiscovery.d.ts +153 -6
  194. package/dist/providers/modelDiscovery.js +295 -41
  195. package/dist/providers/modelDiscovery.js.map +1 -1
  196. package/dist/providers/ollama.d.ts +19 -5
  197. package/dist/providers/ollama.js +60 -52
  198. package/dist/providers/ollama.js.map +1 -1
  199. package/dist/providers/openai.d.ts +1 -1
  200. package/dist/providers/openai.js +39 -10
  201. package/dist/providers/openai.js.map +1 -1
  202. package/dist/providers/openrouter.d.ts +4 -5
  203. package/dist/providers/openrouter.js +20 -35
  204. package/dist/providers/openrouter.js.map +1 -1
  205. package/dist/providers/vertexai.d.ts +1 -1
  206. package/dist/providers/vertexai.js +12 -11
  207. package/dist/providers/vertexai.js.map +1 -1
  208. package/dist/providers/xai.d.ts +1 -1
  209. package/dist/providers/xai.js +5 -10
  210. package/dist/providers/xai.js.map +1 -1
  211. package/dist/runtime/askStructured.d.ts +105 -0
  212. package/dist/runtime/askStructured.js +120 -0
  213. package/dist/runtime/askStructured.js.map +1 -0
  214. package/dist/runtime/conversation.d.ts +60 -0
  215. package/dist/runtime/conversation.js +151 -0
  216. package/dist/runtime/conversation.js.map +1 -0
  217. package/dist/runtime/singleShot.d.ts +25 -5
  218. package/dist/runtime/singleShot.js +95 -36
  219. package/dist/runtime/singleShot.js.map +1 -1
  220. package/dist/runtime/structuredOutput.d.ts +104 -0
  221. package/dist/runtime/structuredOutput.js +393 -0
  222. package/dist/runtime/structuredOutput.js.map +1 -0
  223. package/dist/utils/ProgressIndicator.d.ts +21 -0
  224. package/dist/utils/ProgressIndicator.js +30 -3
  225. package/dist/utils/ProgressIndicator.js.map +1 -1
  226. package/dist/utils/aiignoreUtils.js.map +1 -1
  227. package/dist/utils/binaryOutputUtils.js.map +1 -1
  228. package/dist/utils/consoleUtils.d.ts +52 -0
  229. package/dist/utils/consoleUtils.js +72 -2
  230. package/dist/utils/consoleUtils.js.map +1 -1
  231. package/dist/utils/crashHandler.d.ts +87 -0
  232. package/dist/utils/crashHandler.js +128 -0
  233. package/dist/utils/crashHandler.js.map +1 -0
  234. package/dist/utils/debugDump.d.ts +134 -0
  235. package/dist/utils/debugDump.js +381 -0
  236. package/dist/utils/debugDump.js.map +1 -0
  237. package/dist/utils/debugUtils.d.ts +13 -4
  238. package/dist/utils/debugUtils.js +36 -13
  239. package/dist/utils/debugUtils.js.map +1 -1
  240. package/dist/utils/displayWidth.d.ts +53 -0
  241. package/dist/utils/displayWidth.js +195 -0
  242. package/dist/utils/displayWidth.js.map +1 -0
  243. package/dist/utils/fileUtils.d.ts +24 -2
  244. package/dist/utils/fileUtils.js +54 -12
  245. package/dist/utils/fileUtils.js.map +1 -1
  246. package/dist/utils/llmUtils.d.ts +39 -8
  247. package/dist/utils/llmUtils.js +76 -8
  248. package/dist/utils/llmUtils.js.map +1 -1
  249. package/dist/utils/redactSecrets.d.ts +63 -0
  250. package/dist/utils/redactSecrets.js +286 -0
  251. package/dist/utils/redactSecrets.js.map +1 -0
  252. package/dist/utils/systemPromptNotes.d.ts +225 -0
  253. package/dist/utils/systemPromptNotes.js +340 -0
  254. package/dist/utils/systemPromptNotes.js.map +1 -0
  255. package/dist/utils/systemUtils.d.ts +49 -1
  256. package/dist/utils/systemUtils.js +67 -3
  257. package/dist/utils/systemUtils.js.map +1 -1
  258. package/dist/utils/toolMatching.d.ts +30 -0
  259. package/dist/utils/toolMatching.js +44 -0
  260. package/dist/utils/toolMatching.js.map +1 -0
  261. package/dist/utils/untrustedText.d.ts +66 -0
  262. package/dist/utils/untrustedText.js +80 -0
  263. package/dist/utils/untrustedText.js.map +1 -0
  264. package/package.json +22 -6
  265. package/schema/gsloth-config.schema.json +3134 -0
  266. package/dist/core/shell/allowlist.d.ts +0 -75
  267. package/dist/core/shell/allowlist.js +0 -187
  268. package/dist/core/shell/allowlist.js.map +0 -1
  269. package/dist/core/shell/judge.d.ts +0 -161
  270. package/dist/core/shell/judge.js +0 -261
  271. package/dist/core/shell/judge.js.map +0 -1
@@ -0,0 +1,1519 @@
1
+ /**
2
+ * @packageDocumentation
3
+ * Zod schema for the on-disk raw Gaunt Sloth config (`RawGthConfig`).
4
+ *
5
+ * This is the single source of truth for config validation and for the generated
6
+ * JSON Schema (`packages/core/schema/gsloth-config.schema.json`). It models the
7
+ * canonical config shape only — the deprecated aliases (`contentProvider`,
8
+ * `requirementsProvider`, `contentProviderConfig`, `requirementsProviderConfig`)
9
+ * are intentionally NOT part of the schema. GS2-28 (a 2.0 breaking release with NO
10
+ * back-compat coercion) turns those deprecated shapes into HARD validation errors:
11
+ * {@link findDeprecatedConfigIssues} detects them on the raw input BEFORE the schema
12
+ * parse and each entry point (loader `validateRawConfigLayer`, read-side
13
+ * {@link validateRawGthConfig}) rejects the config with a message naming the canonical
14
+ * replacement + migration path. Detection runs on the RAW input on purpose: zod's
15
+ * per-command `z.object` strips unknown keys, so a nested `commands.*.contentProvider`
16
+ * would vanish before any schema-embedded check could see it.
17
+ *
18
+ * Design notes:
19
+ * - The top-level object is a {@link z.looseObject} so unknown keys PASS THROUGH
20
+ * (they are neither stripped nor a hard failure). The loader separately diffs
21
+ * present-vs-known top-level keys ({@link findUnknownTopLevelKeys}) to warn about
22
+ * likely typos without failing. That typo-tolerance is deliberate: only the KNOWN
23
+ * deprecated names ({@link findDeprecatedConfigIssues}) hard-fail; a genuine typo
24
+ * (e.g. `pulrequest`) still only warns.
25
+ * - Every field is optional. The schema validates the *shape/type of what is
26
+ * present*, not requiredness. In particular `llm` is optional so the loader's
27
+ * existing "must at least define llm.type" checks remain the authority on llm
28
+ * validity (and keep emitting their established messages).
29
+ * - Runtime-object-bearing fields (`tools`, `middleware`, `mcpServers`,
30
+ * `a2aAgents`, `builtInToolsConfig`) are modelled permissively because JS/MJS
31
+ * `configure()` returns live instances/objects there.
32
+ *
33
+ * The exported {@link RawGthConfig}/{@link GthConfig} interfaces in `config.ts`
34
+ * remain the public type surface; the `z.infer` here ({@link RawGthConfigInput})
35
+ * is additive and legitimately differs (no deprecated fields).
36
+ */
37
+ import { z } from 'zod';
38
+ // `constants.ts` is a plain, import-free string module, so this does NOT compromise the purity
39
+ // this file depends on (it feeds `z.toJSONSchema` and must stay cwd/fs-independent).
40
+ import { GSLOTH_DIR, GSLOTH_SETTINGS_DIR } from '#src/constants.js';
41
+ const filesystemSchema = z.union([z.array(z.string()), z.enum(['all', 'read', 'none'])]);
42
+ /**
43
+ * TLS trust for outbound HTTPS (MCP servers over `http` transport, and — because the mechanism is
44
+ * a process-global undici dispatcher — every other `fetch`, including LLM provider calls). Lets a
45
+ * config point Node's `fetch` at a private/corporate CA without prepending `NODE_EXTRA_CA_CERTS`
46
+ * on every invocation (that env var is read once at Node startup and can't be set from config).
47
+ */
48
+ const tlsSchema = z.object({
49
+ // Extra CA cert file(s) to TRUST in ADDITION to Node's built-in roots. Paths resolve
50
+ // relative-to-project (or `~`/absolute). Additive — this never removes a default root.
51
+ extraCaCerts: z.array(z.string()).optional(),
52
+ // DANGER: `false` disables TLS certificate verification for ALL outbound HTTPS this process makes
53
+ // (not just MCP — LLM calls too). Escape hatch only; emits a loud security warning every session.
54
+ rejectUnauthorized: z.boolean().optional(),
55
+ });
56
+ const llmConfigSchema = z.looseObject({
57
+ type: z.string().optional(),
58
+ model: z.string().optional(),
59
+ configuration: z.record(z.string(), z.unknown()).optional(),
60
+ apiKeyEnvironmentVariable: z.string().optional(),
61
+ });
62
+ const ratingConfigSchema = z.object({
63
+ enabled: z.boolean().optional(),
64
+ passThreshold: z.number().optional(),
65
+ maxRating: z.number().optional(),
66
+ minRating: z.number().optional(),
67
+ errorOnReviewFail: z.boolean().optional(),
68
+ });
69
+ const customCommandParameterSchema = z.object({
70
+ description: z.string(),
71
+ allow: z
72
+ .array(z.enum(['absolute-paths', 'directory-traversal', 'shell-injection', 'null-bytes']))
73
+ .optional(),
74
+ });
75
+ const customCommandConfigSchema = z.object({
76
+ command: z.string(),
77
+ description: z.string(),
78
+ parameters: z.record(z.string(), customCommandParameterSchema).optional(),
79
+ timeout: z.number().optional(),
80
+ });
81
+ const customToolsConfigSchema = z.record(z.string(), customCommandConfigSchema);
82
+ const customToolsOrFalseSchema = z.union([z.literal(false), customToolsConfigSchema]);
83
+ const binaryFormatConfigSchema = z.object({
84
+ type: z.enum(['image', 'file', 'audio', 'video', 'binary']),
85
+ extensions: z.array(z.string()),
86
+ maxSize: z.number().optional(),
87
+ mimeTypes: z.record(z.string(), z.string()).optional(),
88
+ });
89
+ const binaryFormatsSchema = z.union([z.literal(false), z.array(binaryFormatConfigSchema)]);
90
+ /**
91
+ * CFG-27 — the five rungs of the approvals ladder, as the schema sees them. Kept as a literal
92
+ * tuple here (rather than imported from `shell-policy.ts`) so the schema module stays the single
93
+ * pre-parse source of truth for what the config channel accepts; `APPROVAL_RUNGS` in
94
+ * `shell-policy.ts` is the runtime twin and `configSchema.spec.ts` pins the two together.
95
+ */
96
+ const APPROVAL_RUNG_VALUES = ['manual', 'write', 'assisted', 'auto', 'bypass'];
97
+ /**
98
+ * The rung names as an error message lists them. Derived from {@link APPROVAL_RUNG_VALUES} rather
99
+ * than written out again at each site: four messages below enumerate the ladder, and a hand-copied
100
+ * list is exactly what goes stale when a rung is renamed — the failure mode being that a config
101
+ * error names values the schema no longer accepts.
102
+ */
103
+ const APPROVAL_RUNG_LIST = APPROVAL_RUNG_VALUES.join(', ');
104
+ /**
105
+ * EXT-71 §3.1 — the **subject** axis of a rule entry, and only that: `shell` is a command, `tool`
106
+ * a built-in or custom in-process tool, `mcpTool` a server's tool. The hand-written twin is
107
+ * `ApprovalEntryType` in `shell-policy.ts`. What holds the two together is
108
+ * `approvalEntrySchema.spec.ts`, where a list of `ApprovalEntry`-typed literals is parsed by this
109
+ * schema: a value either side stops accepting fails there. That is a weaker pin than a direct
110
+ * equality assertion — it catches a narrowing, not a widening on one side alone.
111
+ */
112
+ export const APPROVAL_ENTRY_TYPES = ['shell', 'tool', 'mcpTool'];
113
+ /**
114
+ * EXT-71 §3.1 — the **comparison** axis of a rule entry, and only that. `exact`/`glob`/`regexp`
115
+ * take a string pattern; `hint` takes an object over the annotation names and is valid on tool
116
+ * subjects only (on `shell` it is a config error — see {@link shellEntrySchema}).
117
+ */
118
+ export const APPROVAL_ENTRY_MATCHERS = ['exact', 'glob', 'regexp', 'hint'];
119
+ /**
120
+ * EXT-71 §3.1 / §4.7 — the four MCP `ToolAnnotations` booleans a `hint` pattern may name, and the
121
+ * names a user may list in `approvals.mcp.*.trustAnnotations` (§4.7.1). This is the whole
122
+ * vocabulary: an unknown name is a config error, never an ignored key, because a hint pattern that
123
+ * quietly drops a constraint matches MORE than its author wrote, and a trust list that quietly
124
+ * drops one reads as working while believing something else.
125
+ *
126
+ * **The runtime twin `TOOL_ANNOTATION_HINTS` in `shell-policy.ts` is a deliberate duplicate, and
127
+ * the reason is layering, not oversight.** Neither file may import the other. This module must stay
128
+ * pure and cwd/fs-independent because it feeds `z.toJSONSchema()` (see the header), and importing
129
+ * `shell-policy.ts` would pull `core/types.js` and the whole runtime policy surface into it;
130
+ * importing this module from there would in turn pull zod into every module that only wanted a
131
+ * policy type. So the vocabulary is written once per layer on purpose — do not "simplify" it by
132
+ * making one import the other. The equality assertion in `mcpApprovalsBlock.spec.ts` is what fails
133
+ * when they drift.
134
+ */
135
+ export const HINT_ANNOTATION_KEYS = [
136
+ 'readOnlyHint',
137
+ 'destructiveHint',
138
+ 'idempotentHint',
139
+ 'openWorldHint',
140
+ ];
141
+ /**
142
+ * EXT-71 §3.1 — the length cap on a `regexp` pattern, enforced when the config LOADS.
143
+ *
144
+ * 200 characters. The longest pattern the spec itself writes is under 40, and every rule entry
145
+ * names one command or tool shape rather than a grammar, so 200 is an order of magnitude of
146
+ * headroom over real use while still bounding what the matcher can ever be handed. The cap is a
147
+ * cheap load-time bound, NOT a backtracking defence — a short pattern can backtrack
148
+ * catastrophically too, and the run-time match budget is the separate backstop for that. What the
149
+ * cap buys is that a pattern nobody could have read and reviewed cannot be smuggled past load.
150
+ */
151
+ export const APPROVAL_REGEXP_MAX_LENGTH = 200;
152
+ /**
153
+ * EXT-71 §3.1 — a `hint` pattern: an object over {@link HINT_ANNOTATION_KEYS} mapping each named
154
+ * annotation to the boolean it must effectively hold. All named hints must match (AND within the
155
+ * entry); hints not named are unconstrained; `false` is the spelling of negation.
156
+ *
157
+ * Strict, and non-empty: an empty object or an unknown name is a hard config error and **never a
158
+ * match-everything**. `minProperties` is attached as metadata rather than being left to the
159
+ * refinement alone so the constraint survives into the emitted JSON Schema (zod drops refinements
160
+ * there), which is what the hosted schema channels and editor validation actually read.
161
+ */
162
+ const hintPatternSchema = z
163
+ .strictObject({
164
+ readOnlyHint: z.boolean().optional(),
165
+ destructiveHint: z.boolean().optional(),
166
+ idempotentHint: z.boolean().optional(),
167
+ openWorldHint: z.boolean().optional(),
168
+ })
169
+ .meta({ minProperties: 1 })
170
+ .refine((pattern) => Object.keys(pattern).length > 0, {
171
+ message: 'a hint pattern must name at least one of ' +
172
+ HINT_ANNOTATION_KEYS.join(', ') +
173
+ ' — an empty object is a config error, never a match-everything',
174
+ });
175
+ /**
176
+ * EXT-71 §3.1 — a `regexp` pattern: capped at {@link APPROVAL_REGEXP_MAX_LENGTH} and required to
177
+ * COMPILE when the config loads, never when it first runs. Both failures name the offending
178
+ * pattern in the message: an entry the user cannot trace back to the line they wrote is
179
+ * indistinguishable from a bug.
180
+ *
181
+ * `.max()` is kept alongside the refinement so the cap emits as `maxLength` in the JSON Schema
182
+ * (refinements do not survive `z.toJSONSchema`); the refinement is what produces the message that
183
+ * quotes the pattern.
184
+ */
185
+ const regexpPatternSchema = z
186
+ .string()
187
+ .max(APPROVAL_REGEXP_MAX_LENGTH)
188
+ .superRefine((pattern, ctx) => {
189
+ if (pattern.length > APPROVAL_REGEXP_MAX_LENGTH) {
190
+ ctx.addIssue({
191
+ code: 'custom',
192
+ message: `regexp pattern ${JSON.stringify(pattern)} is ${pattern.length} characters, over the ` +
193
+ `${APPROVAL_REGEXP_MAX_LENGTH}-character cap for an approvals rule pattern`,
194
+ });
195
+ return;
196
+ }
197
+ try {
198
+ new RegExp(pattern);
199
+ }
200
+ catch (e) {
201
+ ctx.addIssue({
202
+ code: 'custom',
203
+ message: `regexp pattern ${JSON.stringify(pattern)} does not compile: ` +
204
+ `${e instanceof Error ? e.message : String(e)}`,
205
+ });
206
+ }
207
+ });
208
+ /** `rate` (§3.2) — optional on EVERY entry type, and the only optional field they all share. */
209
+ const rateField = { rate: z.boolean().optional() };
210
+ /**
211
+ * `host` (§4.7.4) — optional on TOOL subjects only, exact-match. Forbidden on `shell`, where the
212
+ * host is already inside the command string; the shell arms are strict objects, so writing it
213
+ * there is an unrecognized-key error.
214
+ */
215
+ const hostField = { host: z.string().min(1).optional() };
216
+ /**
217
+ * EXT-71 §3.1 — a `shell` entry. `matcher` deliberately omits `hint`: a command carries no tool
218
+ * annotations, so `{"type":"shell","matcher":"hint"}` is a discriminator error naming the three
219
+ * matchers a command actually supports. Neither `server` nor `host` exists here.
220
+ */
221
+ const shellEntrySchema = z.discriminatedUnion('matcher', [
222
+ z.strictObject({
223
+ type: z.literal('shell'),
224
+ matcher: z.literal('exact'),
225
+ pattern: z.string(),
226
+ ...rateField,
227
+ }),
228
+ z.strictObject({
229
+ type: z.literal('shell'),
230
+ matcher: z.literal('glob'),
231
+ pattern: z.string(),
232
+ ...rateField,
233
+ }),
234
+ z.strictObject({
235
+ type: z.literal('shell'),
236
+ matcher: z.literal('regexp'),
237
+ pattern: regexpPatternSchema,
238
+ ...rateField,
239
+ }),
240
+ ]);
241
+ /** EXT-71 §3.1 — a `tool` entry: a built-in or custom in-process tool, matched on its name. */
242
+ const toolEntrySchema = z.discriminatedUnion('matcher', [
243
+ z.strictObject({
244
+ type: z.literal('tool'),
245
+ matcher: z.literal('exact'),
246
+ pattern: z.string(),
247
+ ...hostField,
248
+ ...rateField,
249
+ }),
250
+ z.strictObject({
251
+ type: z.literal('tool'),
252
+ matcher: z.literal('glob'),
253
+ pattern: z.string(),
254
+ ...hostField,
255
+ ...rateField,
256
+ }),
257
+ z.strictObject({
258
+ type: z.literal('tool'),
259
+ matcher: z.literal('regexp'),
260
+ pattern: regexpPatternSchema,
261
+ ...hostField,
262
+ ...rateField,
263
+ }),
264
+ z.strictObject({
265
+ type: z.literal('tool'),
266
+ matcher: z.literal('hint'),
267
+ pattern: hintPatternSchema,
268
+ ...hostField,
269
+ ...rateField,
270
+ }),
271
+ ]);
272
+ /**
273
+ * EXT-71 §3.1 — the reserved MCP server name. `*` in an entry's `server` field means *every
274
+ * server*, so a server actually CALLED `*` would make `{ "server": "*" }` ambiguous — it could not
275
+ * be read as either "every server" or "that one server" without picking, and a rule whose scope
276
+ * depends on which reading won is worse than no rule. The name is therefore refused at load.
277
+ */
278
+ const RESERVED_MCP_SERVER_NAME = '*';
279
+ /**
280
+ * EXT-78 §4.7.5 — the key an MCP server may be configured under, and the one spelling of that rule
281
+ * a JSON Schema can carry. It states exactly what {@link findApprovalsGrammarIssues} refuses ahead
282
+ * of the parse: a name of at least one character (nothing could be written about a server keyed
283
+ * with the empty string) and any name other than {@link RESERVED_MCP_SERVER_NAME}.
284
+ *
285
+ * It is on the record's KEY so the emitted schema carries both rules as `propertyNames`
286
+ * (`minLength` plus `pattern`). Without them the hosted channels publish a contract that accepts
287
+ * two keys the CLI then refuses to start on, and an editor validating against that contract stays
288
+ * silent while the error arrives from somewhere the user is not looking — the one direction they
289
+ * cannot debug from where they are working.
290
+ *
291
+ * The exclusion is EXACT, matching the pre-parse check's own equality test: a longer name that
292
+ * merely begins with the reserved one (`*-jira`) is an ordinary name and stays valid. And the
293
+ * pre-parse check still runs first and still owns the message that explains *why* each key is
294
+ * refused, which a JSON Schema violation can never say.
295
+ */
296
+ /**
297
+ * The exclusion, spelt **without lookaround**, because this pattern is published rather than merely
298
+ * executed here.
299
+ *
300
+ * JSON Schema's `pattern` is nominally ECMA-262, but real validators differ and the ones built on
301
+ * RE2 or Rust's `regex` **cannot compile a lookaround at all** — they reject the document rather
302
+ * than mis-evaluating one keyword. A `^(?!\*$)` spelling therefore risks taking the *whole* hosted
303
+ * schema out of service in those editors, which is a worse failure than the gap this rule closes and
304
+ * defeats the reason the rule exists.
305
+ *
306
+ * Read it as: any single character that is not the reserved one, **or** any string of two or more
307
+ * characters. Only the exact reserved name is left out, which is the pre-parse check's own equality
308
+ * test. The empty string is excluded by `minLength` instead, which is the clearer home for it.
309
+ *
310
+ * **`[\s\S]` and not `.`** — `.` does not match a newline, so a `.`-based spelling refuses a key
311
+ * containing one while the load accepts it. That is a fresh divergence in the opposite direction:
312
+ * an editor red on a config that starts fine, i.e. this rule's own defect class, reintroduced by
313
+ * the fix for it. Measured on `"a\nb"` and `"\n\n"`.
314
+ *
315
+ * The construction assumes a **single-character** reserved name — with a longer one, "not exactly
316
+ * this string" is not expressible as one negated class. {@link mcpServerNameSchema}'s spec asserts
317
+ * that assumption, so changing the constant fails loudly instead of silently emitting a pattern that
318
+ * refuses the wrong set.
319
+ */
320
+ const MCP_SERVER_NAME_PATTERN = `^([^${RESERVED_MCP_SERVER_NAME.replace(/[\\\]^-]/g, '\\$&')}]|[\\s\\S]{2,})$`;
321
+ const mcpServerNameSchema = z.string().min(1).regex(new RegExp(MCP_SERVER_NAME_PATTERN));
322
+ /**
323
+ * EXT-71 §3.1 — an `mcpTool` entry. `server` is **required** here and exists nowhere else: it is
324
+ * the user's own key in `mcpServers` (§4.7.5), the only stable, unique, user-authored identity a
325
+ * server has. The literal `*` is reserved to mean every server, which is why a configured server
326
+ * may not be named `*` ({@link findApprovalsGrammarIssues}).
327
+ */
328
+ const mcpToolEntrySchema = z.discriminatedUnion('matcher', [
329
+ z.strictObject({
330
+ type: z.literal('mcpTool'),
331
+ matcher: z.literal('exact'),
332
+ server: z.string().min(1),
333
+ pattern: z.string(),
334
+ ...hostField,
335
+ ...rateField,
336
+ }),
337
+ z.strictObject({
338
+ type: z.literal('mcpTool'),
339
+ matcher: z.literal('glob'),
340
+ server: z.string().min(1),
341
+ pattern: z.string(),
342
+ ...hostField,
343
+ ...rateField,
344
+ }),
345
+ z.strictObject({
346
+ type: z.literal('mcpTool'),
347
+ matcher: z.literal('regexp'),
348
+ server: z.string().min(1),
349
+ pattern: regexpPatternSchema,
350
+ ...hostField,
351
+ ...rateField,
352
+ }),
353
+ z.strictObject({
354
+ type: z.literal('mcpTool'),
355
+ matcher: z.literal('hint'),
356
+ server: z.string().min(1),
357
+ pattern: hintPatternSchema,
358
+ ...hostField,
359
+ ...rateField,
360
+ }),
361
+ ]);
362
+ /**
363
+ * EXT-71 §3.1 — **one** entry in `allow`, `deny` or `escalate`. All three lists take the same
364
+ * shape, so there is one schema and the list a rule sits in decides only what a match DOES.
365
+ *
366
+ * `type`, `matcher` and `pattern` are required on every arm: no field is inferred, and no entry
367
+ * reads two ways. Every arm is a strict object, so any field the grammar does not define — a typo,
368
+ * a `server` on a `shell` entry, a `host` on a `shell` entry — is an unrecognized-key error rather
369
+ * than a silently-ignored key that would widen what the entry matches.
370
+ *
371
+ * The `id` is what makes the emitted JSON Schema hoist this union into `$defs` and reference it,
372
+ * instead of inlining all eleven arms into each of the twenty-four places a rule list appears
373
+ * (three lists × the root plus seven commands). That is the difference between a schema an editor loads
374
+ * and one it chokes on, and `$ref` is the standard spelling every JSON Schema consumer already
375
+ * understands.
376
+ */
377
+ export const approvalEntrySchema = z
378
+ .discriminatedUnion('type', [shellEntrySchema, toolEntrySchema, mcpToolEntrySchema])
379
+ .meta({ id: 'ApprovalEntry' });
380
+ /** The three rule lists, keyed as they appear under `approvals` (§3, §9). */
381
+ const APPROVAL_LIST_KEYS = ['allow', 'deny', 'escalate'];
382
+ /**
383
+ * EXT-70 §4.7.1/§9.1 — `trustAnnotations`: **the hints believed from one server**, as a LIST of
384
+ * {@link HINT_ANNOTATION_KEYS} names and never a boolean, because trusting `readOnlyHint` while
385
+ * distrusting `openWorldHint` is a coherent position and the common one.
386
+ *
387
+ * An unknown name is a hard config error rather than an ignored member: a list that quietly drops
388
+ * a name the user believed they wrote trusts LESS than they asked in one direction and reads as a
389
+ * working config in the other, and a trust list nobody can verify from its own error output is
390
+ * worse than none. The custom message quotes the offending value, since the path alone gives an
391
+ * index and the user needs the word they mistyped.
392
+ */
393
+ const trustAnnotationsSchema = z.array(z.enum(HINT_ANNOTATION_KEYS, {
394
+ error: (issue) => `${JSON.stringify(issue.input)} is not an MCP tool annotation. trustAnnotations names the ` +
395
+ `hints believed from a server, and the whole vocabulary is ` +
396
+ `${HINT_ANNOTATION_KEYS.join(', ')}.`,
397
+ }));
398
+ /**
399
+ * EXT-70 §4.7/§9 — one server's entry under `approvals.mcp.servers`, and the shape `defaults`
400
+ * takes. **Strict**: an unrecognized key is an error, so a hint list misspelt as a whole key
401
+ * (`trustAnnotation`, `trust`) fails loudly instead of silently trusting nothing while reading as
402
+ * though it trusted something.
403
+ */
404
+ const mcpServerApprovalsSchema = z.strictObject({
405
+ trustAnnotations: trustAnnotationsSchema.optional(),
406
+ });
407
+ /**
408
+ * EXT-70 §4.7/§9 — the `approvals.mcp` block. `defaults` covers servers not named under `servers`;
409
+ * `servers` is keyed by the user's own `mcpServers` config key (§4.7.5) and is deliberately NOT
410
+ * checked against `mcpServers`, so policy may be written before the server it describes.
411
+ *
412
+ * Strict, and it stays strict: `expose` (§4.7.6) belongs to [[EXT-73]] and is not accepted here
413
+ * until that node adds it deliberately. A permissive block would accept `expose` today, do nothing
414
+ * with it, and leave a user believing their tools were filtered.
415
+ */
416
+ const mcpApprovalsSchema = z.strictObject({
417
+ defaults: mcpServerApprovalsSchema.optional(),
418
+ servers: z.record(z.string().min(1), mcpServerApprovalsSchema).optional(),
419
+ });
420
+ /**
421
+ * EXT-71 §3.1 — render an entry in the object form the user would write in a config file, with the
422
+ * fields in grammar order (`type`, `server`, `matcher`, `pattern`, then the optional bounds).
423
+ *
424
+ * The ONE place that spelling is produced, because it is shown in two very different moments that
425
+ * must agree: the load-time error that tells a user what to write instead of their bare string, and
426
+ * the escalation menu's *this is what will be stored* line (§6). A grant the menu describes one way
427
+ * and stores another is exactly the drift this design cannot afford.
428
+ */
429
+ export function renderApprovalEntryObject(entry) {
430
+ const fields = [['type', entry.type]];
431
+ if (entry.server !== undefined)
432
+ fields.push(['server', entry.server]);
433
+ fields.push(['matcher', entry.matcher], ['pattern', entry.pattern]);
434
+ if (entry.host !== undefined)
435
+ fields.push(['host', entry.host]);
436
+ if (entry.rate !== undefined)
437
+ fields.push(['rate', entry.rate]);
438
+ const rendered = fields.map(([key, value]) => `${JSON.stringify(key)}: ${JSON.stringify(value)}`);
439
+ return `{ ${rendered.join(', ')} }`;
440
+ }
441
+ /**
442
+ * EXT-71 §2.3/§9.1 — render the object form of a bare string found in a rule list, so the
443
+ * migration error shows the user the entry they should have written *for their own string*
444
+ * rather than a generic example.
445
+ */
446
+ export function renderApprovalEntryForString(pattern) {
447
+ return renderApprovalEntryObject({ type: 'shell', matcher: 'exact', pattern });
448
+ }
449
+ /**
450
+ * CFG-27 — the `approvals` value: **either the rung name on its own, or an object when the extras
451
+ * are needed** (spec §9). There are no other approvals keys.
452
+ *
453
+ * ```jsonc
454
+ * { "approvals": "assisted" }
455
+ * ```
456
+ * ```jsonc
457
+ * { "approvals": {
458
+ * "mode": "assisted",
459
+ * "rater": "safety-rater", // identity profile the rater runs under
460
+ * "allow": [ { "type": "shell", "matcher": "exact", "pattern": "npm test" } ],
461
+ * "deny": [ { "type": "shell", "matcher": "glob", "pattern": "npm publish*" } ],
462
+ * "escalate": [ { "type": "shell", "matcher": "exact", "pattern": "terraform apply" } ]
463
+ * } }
464
+ * ```
465
+ *
466
+ * - **The scalar form is exactly sugar for `{ "mode": <value> }`** (§9.1). The union exists so the
467
+ * extras have a home when they are needed, not so there are two ways to say the same thing.
468
+ * - `rater` is a **bare identity-profile name**, not an object (strict resolution, GS2-62: a name
469
+ * that does not resolve is a hard config error, never a silent fallback).
470
+ * - `raterTimeoutMs` (EXT-66) is the wall-clock budget for ONE rating call, defaulting to
471
+ * `RATER_DEFAULT_TIMEOUT_MS` (30s) at the read site. **It exists because 30s is a hosted-model
472
+ * number and a local model is knowably slower**: measured 2026-07-31, `gemma4:12b` over Ollama
473
+ * answered a 23-case corpus in 6.0s–114.7s, and at the fixed limit 3 of 18 calls in one run and
474
+ * 9 of 17 in the next were cut off — so a local `auto` session degraded toward escalating
475
+ * everything, which is the opposite of what the rung is for. Deliberately a number the user owns
476
+ * rather than a provider→timeout table: a table is a guess about someone else's hardware, and
477
+ * the failure it causes is silent.
478
+ * - `allow`/`deny`/`escalate` are **read-only input**: merged with the runtime stores the
479
+ * escalation menu writes, and never written back to config. Every entry is the §3.1 object
480
+ * ({@link approvalEntrySchema}); a bare string in any of the three is a hard config error whose
481
+ * message shows the object form of that same string ({@link findApprovalsGrammarIssues}).
482
+ * - `escalate` is the third list (§3, §3.2): a match always asks the human, whatever the rung
483
+ * would have done. It takes the same entries as the other two.
484
+ * - `mcp` (EXT-70 §4.7) holds the per-server relationship — which hints are believed from which
485
+ * server — keyed by the user's own `mcpServers` config key, with `defaults` for servers not
486
+ * named. Absent or empty `trustAnnotations` believes nothing external, which is also the default.
487
+ * - The retired `strictness` / `allowlist` / `persistAllowlist` keys and the retired `auto` / `ask`
488
+ * mode values are hard migration errors naming their replacement — see `RETIRED_APPROVALS_KEYS` /
489
+ * `RETIRED_APPROVAL_MODES` in {@link findDeprecatedConfigIssues}. So is a NON-ARRAY `escalate`,
490
+ * which is the retired severity threshold rather than the new list.
491
+ *
492
+ * Defaults are applied at the READ site (`resolveApprovals` in `shell-policy.ts`), not in
493
+ * DEFAULT_CONFIG, so the effective-config snapshot never churns (à la GS2-34/GS2-63).
494
+ *
495
+ * NOTE: "judge" is reserved for the eval grader (`gth eval --judge <profile>`) — a different
496
+ * concept that keeps its name.
497
+ */
498
+ const approvalsSchema = z.union([
499
+ z.enum(APPROVAL_RUNG_VALUES),
500
+ z.object({
501
+ mode: z.enum(APPROVAL_RUNG_VALUES).optional(),
502
+ rater: z.string().optional(),
503
+ // EXT-71 §3.1 — the three rule lists. Same entry grammar in all three; the list decides only
504
+ // what a match DOES (§3: deny over escalate over allow).
505
+ allow: z.array(approvalEntrySchema).optional(),
506
+ deny: z.array(approvalEntrySchema).optional(),
507
+ escalate: z.array(approvalEntrySchema).optional(),
508
+ // EXT-66 — wall-clock budget (ms) for one rating call. See the note on the union above for
509
+ // why this is a user-owned number rather than a per-provider table.
510
+ // `.min(1)`, not `.positive()`: the latter emits `exclusiveMinimum`, a JSON-Schema draft
511
+ // keyword this repo avoids on principle (GS2-57 — Google GenAI rejects it outright in tool
512
+ // declarations). This schema is not a tool declaration, but one spelling everywhere is what
513
+ // stops the wrong one being copied into somewhere that is.
514
+ raterTimeoutMs: z.number().int().min(1).optional(),
515
+ // EXT-70 §4.7/§9 — the per-server MCP relationship, keyed by the user's own `mcpServers` key.
516
+ mcp: mcpApprovalsSchema.optional(),
517
+ }),
518
+ ]);
519
+ /**
520
+ * EXT-36 — the tool-loop guard (repeated identical `(tool, args)` / no-progress detector), the
521
+ * orthogonal sibling of GS2-36's error budget. A boolean-or-object union: `false` disables
522
+ * it entirely; `true`/absent is warn-on defaults; the object form is fine-grained. `warn` (default
523
+ * ON) injects a control-flow-free nudge at the threshold; `halt` (default OFF, opt-in) ends the run
524
+ * cleanly at the threshold; `threshold` is the number of consecutive identical calls that trip it.
525
+ * The warn-on default is applied at the read site, so this field is intentionally absent from
526
+ * DEFAULT_CONFIG.
527
+ */
528
+ const toolLoopGuardSchema = z.union([
529
+ z.boolean(),
530
+ z.object({
531
+ warn: z.boolean().optional(),
532
+ halt: z.boolean().optional(),
533
+ threshold: z.number().optional(),
534
+ }),
535
+ ]);
536
+ /**
537
+ * CFG-18 — the per-tool config object carried as a value in the widened `builtInTools` registry.
538
+ * One permissive shape covering every tool: `command` for the fixed dev-command tools
539
+ * (run_tests/run_lint/run_build/run_single_test), the EXT-12 execution knobs for
540
+ * `run_shell_command` (`timeout`/`maxOutputBytes`), `fileSet` for `gth_grep` (GS2-51), and
541
+ * `enabled` for a plain built-in tool.
542
+ *
543
+ * CFG-26 — the APPROVAL knobs that used to live here (`allowlist`, `persistAllowlist`, `judge`,
544
+ * `yolo`) moved to the top-level {@link approvalsSchema}. They were fields of the object shared by
545
+ * EVERY built-in tool, which is why a nonsensical `gth_grep: { yolo: true }` validated. Each is now
546
+ * a hard migration error — see `RETIRED_SHELL_TOOL_PAIRS` in {@link findDeprecatedConfigIssues}.
547
+ */
548
+ const builtInToolConfigSchema = z.object({
549
+ enabled: z.boolean().optional(),
550
+ command: z.string().optional(),
551
+ timeout: z.number().optional(),
552
+ maxOutputBytes: z.number().optional(),
553
+ // GS2-51 — `gth_grep`: which corpus to search. `gitignore` (default) respects .gitignore/.ignore
554
+ // and skips hidden dot-files; `all` scans everything but the noise dirs. See BuiltInToolConfig.
555
+ fileSet: z.enum(['gitignore', 'all']).optional(),
556
+ });
557
+ /**
558
+ * CFG-18 — the widened `builtInTools` setting: either the legacy `string[]` (each name enabled) or
559
+ * a registry keyed by tool name whose values enable (`true`), force-disable (`false`), or configure
560
+ * ({@link builtInToolConfigSchema}) each tool. Replaces `builtInTools: string[]` + per-command
561
+ * `devTools`.
562
+ */
563
+ const builtInToolsSchema = z.union([
564
+ z.array(z.string()),
565
+ z.record(z.string(), z.union([z.boolean(), builtInToolConfigSchema])),
566
+ ]);
567
+ /**
568
+ * GS2-43 — one prompt segment inside the {@link promptsSchema} object. Either a `string`
569
+ * (shorthand for `{ path }`) or a config object:
570
+ * - `path` — file to read for this segment (resolved like every prompt file: config dir /
571
+ * identity profile first, then relative to the project root).
572
+ * - `enabled: false` — drop the segment entirely (even its bundled default).
573
+ * - `mode` — `'replace'` (default): the file replaces the built-in segment content;
574
+ * `'append'`: the file content is appended after the built-in content.
575
+ */
576
+ const promptSegmentSchema = z.union([
577
+ z.string(),
578
+ z.object({
579
+ path: z.string().optional(),
580
+ enabled: z.boolean().optional(),
581
+ mode: z.enum(['replace', 'append']).optional(),
582
+ }),
583
+ ]);
584
+ /**
585
+ * GS2-43 — the unified `prompts` config object (CFG-18's flat-key→rich-object precedent).
586
+ * Replaces the removed flat `projectGuidelines` / `projectReviewInstructions` keys and makes
587
+ * ALL seven prompt segments retargetable through config (previously backstory/system/chat/
588
+ * code/exec were reachable only by placing a file in the config dir). Kept as a plain
589
+ * `z.object` of optional sibling keys so a future segment (e.g. GS2-44's `agents`) is a
590
+ * one-line addition with no collision risk.
591
+ */
592
+ const promptsSchema = z.object({
593
+ backstory: promptSegmentSchema.optional(),
594
+ guidelines: promptSegmentSchema.optional(),
595
+ system: promptSegmentSchema.optional(),
596
+ chat: promptSegmentSchema.optional(),
597
+ code: promptSegmentSchema.optional(),
598
+ exec: promptSegmentSchema.optional(),
599
+ review: promptSegmentSchema.optional(),
600
+ });
601
+ const prCommandSchema = z.object({
602
+ contentSource: z.string().optional(),
603
+ requirementSource: z.string().optional(),
604
+ filesystem: filesystemSchema.optional(),
605
+ builtInTools: builtInToolsSchema.optional(),
606
+ // CFG-27/§9.1 — per-command approvals. It overrides only the fields it names: `mode`,
607
+ // `rater`, `raterTimeoutMs` and `allow` replace the root's; `deny`/`escalate` concatenate.
608
+ approvals: approvalsSchema.optional(),
609
+ customTools: customToolsOrFalseSchema.optional(),
610
+ allowedTools: z.array(z.string()).optional(),
611
+ logWorkForReviewInSeconds: z.number().optional(),
612
+ rating: ratingConfigSchema.optional(),
613
+ binaryFormats: binaryFormatsSchema.optional(),
614
+ });
615
+ const reviewCommandSchema = z.object({
616
+ contentSource: z.string().optional(),
617
+ requirementSource: z.string().optional(),
618
+ filesystem: filesystemSchema.optional(),
619
+ builtInTools: builtInToolsSchema.optional(),
620
+ // CFG-27/§9.1 — per-command approvals. It overrides only the fields it names: `mode`,
621
+ // `rater`, `raterTimeoutMs` and `allow` replace the root's; `deny`/`escalate` concatenate.
622
+ approvals: approvalsSchema.optional(),
623
+ customTools: customToolsOrFalseSchema.optional(),
624
+ allowedTools: z.array(z.string()).optional(),
625
+ rating: ratingConfigSchema.optional(),
626
+ binaryFormats: binaryFormatsSchema.optional(),
627
+ });
628
+ const askCommandSchema = z.object({
629
+ filesystem: filesystemSchema.optional(),
630
+ builtInTools: builtInToolsSchema.optional(),
631
+ // CFG-27/§9.1 — per-command approvals. It overrides only the fields it names: `mode`,
632
+ // `rater`, `raterTimeoutMs` and `allow` replace the root's; `deny`/`escalate` concatenate.
633
+ approvals: approvalsSchema.optional(),
634
+ customTools: customToolsOrFalseSchema.optional(),
635
+ allowedTools: z.array(z.string()).optional(),
636
+ binaryFormats: binaryFormatsSchema.optional(),
637
+ });
638
+ const chatCommandSchema = z.object({
639
+ filesystem: filesystemSchema.optional(),
640
+ builtInTools: builtInToolsSchema.optional(),
641
+ // CFG-27/§9.1 — per-command approvals. It overrides only the fields it names: `mode`,
642
+ // `rater`, `raterTimeoutMs` and `allow` replace the root's; `deny`/`escalate` concatenate.
643
+ approvals: approvalsSchema.optional(),
644
+ customTools: customToolsOrFalseSchema.optional(),
645
+ allowedTools: z.array(z.string()).optional(),
646
+ binaryFormats: binaryFormatsSchema.optional(),
647
+ });
648
+ const codeCommandSchema = z.object({
649
+ filesystem: filesystemSchema.optional(),
650
+ builtInTools: builtInToolsSchema.optional(),
651
+ // CFG-27/§9.1 — per-command approvals. It overrides only the fields it names: `mode`,
652
+ // `rater`, `raterTimeoutMs` and `allow` replace the root's; `deny`/`escalate` concatenate.
653
+ approvals: approvalsSchema.optional(),
654
+ customTools: customToolsOrFalseSchema.optional(),
655
+ allowedTools: z.array(z.string()).optional(),
656
+ binaryFormats: binaryFormatsSchema.optional(),
657
+ });
658
+ const execCommandSchema = z.object({
659
+ filesystem: filesystemSchema.optional(),
660
+ builtInTools: builtInToolsSchema.optional(),
661
+ // CFG-27/§9.1 — per-command approvals. It overrides only the fields it names: `mode`,
662
+ // `rater`, `raterTimeoutMs` and `allow` replace the root's; `deny`/`escalate` concatenate.
663
+ approvals: approvalsSchema.optional(),
664
+ customTools: customToolsOrFalseSchema.optional(),
665
+ allowedTools: z.array(z.string()).optional(),
666
+ binaryFormats: binaryFormatsSchema.optional(),
667
+ });
668
+ const apiCommandSchema = z.object({
669
+ filesystem: filesystemSchema.optional(),
670
+ builtInTools: builtInToolsSchema.optional(),
671
+ // CFG-27/§9.1 — per-command approvals. It overrides only the fields it names: `mode`,
672
+ // `rater`, `raterTimeoutMs` and `allow` replace the root's; `deny`/`escalate` concatenate.
673
+ approvals: approvalsSchema.optional(),
674
+ port: z.number().optional(),
675
+ cors: z
676
+ .object({
677
+ allowOrigin: z.string().optional(),
678
+ allowMethods: z.string().optional(),
679
+ allowHeaders: z.string().optional(),
680
+ })
681
+ .optional(),
682
+ });
683
+ /**
684
+ * GS2-33 — one profile-backed subagent: a `name` the model selects it by, an optional
685
+ * `description`, and the named config `profile` the CHILD resolves through the GS2-1 cascade when
686
+ * spawned. See {@link SubagentProfileSpec}.
687
+ */
688
+ const subagentSpecSchema = z.object({
689
+ name: z.string(),
690
+ description: z.string().optional(),
691
+ profile: z.string(),
692
+ });
693
+ const commandsSchema = z.object({
694
+ pr: prCommandSchema.optional(),
695
+ review: reviewCommandSchema.optional(),
696
+ ask: askCommandSchema.optional(),
697
+ chat: chatCommandSchema.optional(),
698
+ code: codeCommandSchema.optional(),
699
+ exec: execCommandSchema.optional(),
700
+ api: apiCommandSchema.optional(),
701
+ });
702
+ /**
703
+ * The command names, derived from {@link commandsSchema}'s own shape so it can never drift
704
+ * from the schema. A command config must live under `commands.<cmd>`; the SAME name appearing
705
+ * at the config ROOT is the removed pre-2.0 top-level shape and is hard-rejected by
706
+ * {@link findDeprecatedConfigIssues}. (None of these are valid top-level keys, so there is no
707
+ * collision with {@link KNOWN_TOP_LEVEL_KEYS}.)
708
+ */
709
+ const COMMAND_KEYS = Object.keys(commandsSchema.shape);
710
+ /**
711
+ * Zod schema for the raw, on-disk Gaunt Sloth config. Loose at the top level so
712
+ * unknown keys are preserved (warn-only via {@link findUnknownTopLevelKeys}).
713
+ */
714
+ export const rawGthConfigSchema = z.looseObject({
715
+ // Allow a JSON Schema reference for editor support; never read at runtime.
716
+ $schema: z.string().optional(),
717
+ llm: llmConfigSchema.optional(),
718
+ // GS2-41 — profile composition. A NAMED profile config may declare `extends: "<base-profile>"` to
719
+ // inherit another profile's config: the base profile resolves FIRST, then this profile's own
720
+ // fields merge on top (last-wins, same GS2-1 deep-merge as the config layers; a base may itself
721
+ // extend another, with a cycle guard). Consumed during load — never appears in the resolved
722
+ // config. See `resolveConfigExtends` in loader.ts.
723
+ extends: z.string().optional(),
724
+ // Selects the agent backend. `lean` (the default when omitted) uses the plain LangChain agent
725
+ // with gsloth's full toolset (no `/large_tool_results` offload). `deep` is the EXPERIMENTAL,
726
+ // opt-in deepagents runtime and emits a warning when selected. The key is COMMAND-SCOPED:
727
+ // `review`/`pr` always run lean and warn when it asks for `deep`; the ACP server is deep-only.
728
+ agent: z
729
+ .object({
730
+ backend: z.enum(['deep', 'lean']).optional(),
731
+ })
732
+ .optional(),
733
+ // GS2-7 (B20) — local, opt-in session history. DEFAULT OFF: absent or `enabled: false` means
734
+ // nothing is persisted and runs behave exactly as before (stateless identity preserved).
735
+ history: z
736
+ .object({
737
+ enabled: z.boolean().optional(),
738
+ dbPath: z.string().optional(),
739
+ })
740
+ .optional(),
741
+ // GS2-7 (B21) — opt-in file-backed memory (MEMORY.md / USER.md). DEFAULT OFF. The toggle exists
742
+ // for forward-compat; the feature itself is a deferred follow-up.
743
+ memory: z
744
+ .object({
745
+ enabled: z.boolean().optional(),
746
+ })
747
+ .optional(),
748
+ binaryFormats: binaryFormatsSchema.optional(),
749
+ contentSource: z.string().optional(),
750
+ requirementSource: z.string().optional(),
751
+ contentSourceConfig: z.record(z.string(), z.unknown()).optional(),
752
+ requirementSourceConfig: z.record(z.string(), z.unknown()).optional(),
753
+ // GS2-43 — the unified prompt-segment config; replaces projectGuidelines/projectReviewInstructions.
754
+ prompts: promptsSchema.optional(),
755
+ identityProfile: z.string().optional(),
756
+ includeCurrentDateAfterGuidelines: z.boolean().optional(),
757
+ organization: z
758
+ .object({
759
+ name: z.string().optional(),
760
+ locale: z.string().optional(),
761
+ timezone: z.string().optional(),
762
+ })
763
+ .optional(),
764
+ noDefaultPrompts: z.boolean().optional(),
765
+ filesystem: filesystemSchema.optional(),
766
+ builtInTools: builtInToolsSchema.optional(),
767
+ // CFG-27 — the approvals ladder: a rung name, or an object carrying the rater profile and the
768
+ // declared allow/deny lists. Settable at the root or per command
769
+ // (`commands.<command>.approvals`, which per §9.1 overrides only the fields it names — the
770
+ // restrictive lists concatenate across scopes, `allow` replaces). Absent = `assisted`
771
+ // (`resolveApprovals` in shell-policy.ts).
772
+ approvals: approvalsSchema.optional(),
773
+ // Live tool instances / toolkits in JS configs — kept permissive.
774
+ tools: z.array(z.unknown()).optional(),
775
+ allowedTools: z.array(z.string()).optional(),
776
+ // Predefined (string/object) or custom (object) middleware — permissive.
777
+ middleware: z.array(z.unknown()).optional(),
778
+ streamOutput: z.boolean().optional(),
779
+ writeOutputToFile: z.union([z.boolean(), z.string()]).optional(),
780
+ writeBinaryOutputsToFile: z.boolean().optional(),
781
+ // CFG-30 — rung 3 of the colour ladder (`config/colour.ts`), NOT the final say: `FORCE_COLOR`
782
+ // and `NO_COLOR` outrank it, and when it is absent colour auto-detects from stdout's TTY status.
783
+ // MUST stay `.optional()` — absence is what distinguishes "the user chose true" from the `true`
784
+ // in `defaults.ts`, and the ladder collapses without that. User docs: docs/configuration/output.md
785
+ useColour: z.boolean().optional(),
786
+ // TUI-C37 — rung 2 of the mouse ladder (`config/mouse.ts`). MUST stay `.optional()` for the same
787
+ // reason as `useColour`: absence is what tells "the user chose true" from the `true` in
788
+ // `defaults.ts`, and rung 2 collapses into rung 4 without it.
789
+ useMouse: z.boolean().optional(),
790
+ // CFG-37 — persistent surface preference for the `chat`/`code` sessions: `true` asks for the Ink
791
+ // TUI, `false` for the plain readline session. MUST stay `.optional()` for the same reason as
792
+ // `useColour`/`useMouse`: absence is what distinguishes "the user chose readline" from "nobody
793
+ // said", and the auto-detect rung collapses without it. Ranked BELOW the `--tui`/`--no-tui` flags
794
+ // and the `GTH_NO_TUI` escape hatch, and below the capability gates (no TTY, `TERM=dumb`, `ink`
795
+ // unavailable) which are checks rather than preferences — so `true` degrades to readline instead
796
+ // of forcing a crash. The decision itself is `shouldUseTui` in the app package.
797
+ // User docs: docs/guides/interactive-sessions.md
798
+ tui: z.boolean().optional(),
799
+ streamSessionInferenceLog: z.boolean().optional(),
800
+ canInterruptInferenceWithEsc: z.boolean().optional(),
801
+ debugLog: z.boolean().optional(),
802
+ recursionLimit: z.number().optional(),
803
+ consoleLevel: z.union([z.string(), z.number()]).optional(),
804
+ customTools: customToolsConfigSchema.optional(),
805
+ // EXT-78 — keyed by the server's own name, whose two refused spellings ride on the key schema so
806
+ // the emitted JSON Schema states them too ({@link mcpServerNameSchema}).
807
+ mcpServers: z.record(mcpServerNameSchema, z.unknown()).optional(),
808
+ tls: tlsSchema.optional(),
809
+ a2aAgents: z.record(z.string(), z.unknown()).optional(),
810
+ builtInToolsConfig: z.record(z.string(), z.unknown()).optional(),
811
+ aiignore: z
812
+ .object({
813
+ enabled: z.boolean().optional(),
814
+ patterns: z.array(z.string()).optional(),
815
+ })
816
+ .optional(),
817
+ commands: commandsSchema.optional(),
818
+ // GS2-35/EXT-83 — identity used in the `Co-Authored-By` trailer of agent-authored git commits.
819
+ // Optional; when omitted the agent is instructed to co-author as the Gaunt Sloth account, whose
820
+ // default NAME carries the resolved active model — `Gaunt Sloth (provider:model)`, falling back
821
+ // to the bare `Gaunt Sloth` when no model resolves or `injectModelContext` is false — at the
822
+ // constant address `code@gauntsloth.app`. A configured name is emitted verbatim. Either field may
823
+ // be set alone; the other falls back to its default (see `appendCommitCoAuthorNote`).
824
+ commit: z
825
+ .object({
826
+ coAuthor: z
827
+ .object({
828
+ name: z.string().optional(),
829
+ email: z.string().optional(),
830
+ })
831
+ .optional(),
832
+ })
833
+ .optional(),
834
+ modelDisplayName: z.string().optional(),
835
+ // GS2-34/EXT-83 — inject the resolved active `provider:model` identity into the system prompt
836
+ // (default ON; set `false` to opt out for reproducible / model-agnostic runs). It governs the
837
+ // identity everywhere in the prompt: the identity line in every mode, AND the model name that
838
+ // decorates the default git commit co-author trailer in `code` mode. Defaulted at the read site,
839
+ // so it is intentionally absent from DEFAULT_CONFIG (no effective-config snapshot churn).
840
+ injectModelContext: z.boolean().optional(),
841
+ // GS2-47 — secret-redaction for `/debug-dump` artifacts. `redact` DEFAULTS ON (omitted = redact);
842
+ // set `false` to write a raw, unredacted archive (the command then shows a loud secrets warning).
843
+ // Defaulted at the read site (`!== false`), not in DEFAULT_CONFIG, to avoid churning the
844
+ // effective-config snapshot (à la GS2-34 injectModelContext).
845
+ debugDump: z
846
+ .object({
847
+ redact: z.boolean().optional(),
848
+ })
849
+ .optional(),
850
+ allowDirs: z.array(z.string()).optional(),
851
+ askWriteMode: z.boolean().optional(),
852
+ // GS2-63 — output surface controls. `header` DEFAULTS ON (omitted = show); set `false` to
853
+ // suppress the technical run-header preamble (the Workdir/Model/Tools/Middleware block, the
854
+ // `Press Escape or Q to interrupt` hint, and their surrounding blank lines) in NON-TUI text
855
+ // modes (`--no-tui`, `ask`, `exec`, `eval`, `pr`, `review`, piped/CI), keeping captured stdout /
856
+ // log diffs clean. The interactive TUI ignores it and always shows the header. Suppresses ONLY
857
+ // that preamble — never model/tool output, errors, or config-validation warnings. Defaulted at
858
+ // the read site (`!== false`), not in DEFAULT_CONFIG, to avoid churning the effective-config
859
+ // snapshot (à la GS2-34 injectModelContext).
860
+ output: z
861
+ .object({
862
+ header: z.boolean().optional(),
863
+ })
864
+ .optional(),
865
+ // EXT-36 — tool-loop guard (repeated identical (tool, args) / no-progress detector), the sibling
866
+ // of GS2-36's error budget. `false` disables; `true`/absent = warn-on defaults; object =
867
+ // fine-grained ({ warn, halt, threshold }). WARN (default ON) injects a control-flow-free nudge;
868
+ // HALT (default OFF, opt-in) ends the run cleanly at the threshold. Defaulted at the read site
869
+ // (warn on), not in DEFAULT_CONFIG, so the effective-config snapshot never churns.
870
+ toolLoopGuard: toolLoopGuardSchema.optional(),
871
+ // BATCH-19 — custom `gth eval` reporters. Maps a reporter NAME (as selected with
872
+ // `--reporter <name>`) to a MODULE PATH (relative to the project dir) whose default export is an
873
+ // `EvalReporterFactory` (`() => EvalReporter`). Registered through the same seam the bundled
874
+ // reporters use; a name here overrides a built-in of the same name.
875
+ reporters: z.record(z.string(), z.string()).optional(),
876
+ // GS2-33 — profile-backed subagents. Each entry names a subagent and the named config profile the
877
+ // CHILD resolves when the deep backend's `task` tool spawns it, so a subagent can run under a
878
+ // different model/tools/prompt than the parent. See {@link subagentSpecSchema}.
879
+ subagents: z.array(subagentSpecSchema).optional(),
880
+ });
881
+ /**
882
+ * The set of known top-level config keys, derived from the schema shape so it can
883
+ * never drift from {@link rawGthConfigSchema}. Includes `$schema`.
884
+ */
885
+ export const KNOWN_TOP_LEVEL_KEYS = new Set(Object.keys(rawGthConfigSchema.shape));
886
+ /**
887
+ * True when a raw config value is a plain (non-null, non-array) object, so the key scans
888
+ * ({@link findDeprecatedConfigIssues}, {@link findUnknownTopLevelKeys}) are safe to run. A
889
+ * `null`/array/primitive config (e.g. a JSON file that is just `null`, or a module
890
+ * `configure()` returning null) must NOT reach those scans — they'd throw on
891
+ * `hasOwnProperty`/`Object.keys`; the entry points instead hand it straight to
892
+ * `rawGthConfigSchema.safeParse`, which reports a clean "expected object" error.
893
+ */
894
+ export function isRecordConfig(value) {
895
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
896
+ }
897
+ /**
898
+ * Return the top-level keys present in `raw` that are not part of the known config
899
+ * surface. KNOWN deprecated names are rejected earlier by {@link findDeprecatedConfigIssues}
900
+ * (the entry points short-circuit on those), so a key that reaches here is a genuinely
901
+ * unknown key (a likely typo) that only warrants a warning.
902
+ */
903
+ export function findUnknownTopLevelKeys(raw) {
904
+ return Object.keys(raw).filter((key) => !KNOWN_TOP_LEVEL_KEYS.has(key));
905
+ }
906
+ /**
907
+ * Render ` - <path>: <message>` lines (one per issue), with `(root)` for an empty
908
+ * path. Shared by {@link formatConfigValidationError} (Zod issues) and
909
+ * {@link formatDeprecatedConfigIssues} (deprecated-shape issues) so both surfaces read
910
+ * identically.
911
+ */
912
+ function formatIssueLines(issues) {
913
+ return issues.map((issue) => ` - ${issue.path || '(root)'}: ${issue.message}`).join('\n');
914
+ }
915
+ /**
916
+ * Render a friendly, path-scoped validation message from a Zod error. Each issue
917
+ * becomes a line ` - <path>: <message>`, with `(root)` for top-level issues.
918
+ */
919
+ export function formatConfigValidationError(error) {
920
+ return formatIssueLines(error.issues.map((issue) => ({
921
+ path: issue.path.length > 0 ? issue.path.join('.') : '',
922
+ message: issue.message,
923
+ })));
924
+ }
925
+ /** Deprecated → canonical key pairs at the config root (SSOT for the rejecter). */
926
+ const DEPRECATED_ROOT_PAIRS = [
927
+ ['contentProvider', 'contentSource'],
928
+ ['requirementsProvider', 'requirementSource'],
929
+ ['contentProviderConfig', 'contentSourceConfig'],
930
+ ['requirementsProviderConfig', 'requirementSourceConfig'],
931
+ // GS2-43 — the flat prompt-path keys were folded into the `prompts` object.
932
+ ['projectGuidelines', 'prompts.guidelines'],
933
+ ['projectReviewInstructions', 'prompts.review'],
934
+ ];
935
+ /** Deprecated → canonical key pairs inside a `commands.<name>` block (SSOT for the rejecter). */
936
+ const DEPRECATED_COMMAND_PAIRS = [
937
+ ['contentProvider', 'contentSource'],
938
+ ['requirementsProvider', 'requirementSource'],
939
+ ];
940
+ /**
941
+ * CFG-18 — removed per-command keys with no 1:1 rename: the config they carried was FOLDED into
942
+ * another key. `[removed, replacement]`. `devTools` (the split dev/shell config) is now configured
943
+ * under the unified `builtInTools` registry. Rejected here specifically because `devTools` lived
944
+ * under a per-command `z.object`, which SILENTLY STRIPS unknown keys — so without this pre-parse
945
+ * reject an old `commands.<cmd>.devTools` block would vanish with no error (worse than today).
946
+ */
947
+ const REMOVED_COMMAND_KEYS = [
948
+ ['devTools', 'builtInTools'],
949
+ ];
950
+ /**
951
+ * CFG-26 — approval knobs retired from the `builtInTools.run_shell_command` entry and moved to the
952
+ * top-level `approvals` block. `[retired, "how to say it now"]`. Rejected pre-parse for the same
953
+ * reason as {@link REMOVED_COMMAND_KEYS}: `builtInToolConfigSchema` is a strict `z.object`, so once
954
+ * the field is gone zod SILENTLY STRIPS it and an old config would run with its approval posture
955
+ * quietly ignored — the worst possible failure for a safety gate.
956
+ *
957
+ * `judge.autoApproveLow` / `judge.blockHigh` have no 1:1 successor (the rung replaced the
958
+ * `low/medium/high` × `destructive` conjunction), so `judge`'s message points at `approvals.mode`
959
+ * and names the outcome scale that took the tiers' place.
960
+ */
961
+ const RETIRED_SHELL_TOOL_PAIRS = [
962
+ ['yolo', '"approvals": "bypass"'],
963
+ [
964
+ 'judge',
965
+ '"approvals": "assisted" (or "auto"), optionally with "approvals.rater" naming an ' +
966
+ 'identity profile — the low/medium/high tiers became the ' +
967
+ 'safe/destructive/catastrophic/attack outcomes, and autoApproveLow/blockHigh are replaced ' +
968
+ 'by the mode you choose',
969
+ ],
970
+ ['allowlist', '"approvals.allow" (a declared list of rule entries)'],
971
+ [
972
+ 'persistAllowlist',
973
+ 'nothing — persistence is a per-decision choice at the approval prompt (approve forgets, ' +
974
+ 'always approve persists)',
975
+ ],
976
+ ];
977
+ /** The `builtInTools` entry the retired approval knobs used to hang off. */
978
+ const SHELL_TOOL_REGISTRY_KEY = 'run_shell_command';
979
+ /**
980
+ * CFG-27 — keys retired from the `approvals` object itself when the four-tier lattice became one
981
+ * ordered ladder of five rungs. `[retired, "how to say it now"]`.
982
+ *
983
+ * Rejected PRE-PARSE rather than left to the union: `approvalsSchema`'s object arm is a `z.object`,
984
+ * which silently strips unknown keys, so an `approvals: { mode: "assisted", strictness: "strict" }`
985
+ * would otherwise run with its declared posture quietly ignored — the worst possible failure for a
986
+ * safety gate, and exactly what CFG-26 fixed for the per-tool knobs.
987
+ *
988
+ * `strictness` is **deleted, not remapped**: there are no severity thresholds and no independent
989
+ * rater switch, so the message points at the rung that expresses the intent.
990
+ *
991
+ * The retired severity threshold `escalate` is NOT in this table, because EXT-71 gave the name back
992
+ * as the third rule list (§3). A non-array `escalate` — the shape the threshold had — is still
993
+ * caught, with the same message, by {@link RETIRED_ESCALATE_THRESHOLD_MESSAGE}.
994
+ */
995
+ const RETIRED_APPROVALS_KEYS = [
996
+ [
997
+ 'strictness',
998
+ 'nothing — there are no strictness levels any more. Choose a mode instead: ' +
999
+ '"manual"/"write" never rate, "assisted" and "auto" escalate anything not rated safe, ' +
1000
+ '"bypass" rates nothing',
1001
+ ],
1002
+ ['allowlist', '"approvals.allow" (a declared list of rule entries)'],
1003
+ [
1004
+ 'persistAllowlist',
1005
+ 'nothing — persistence is a per-decision choice at the approval prompt (approve forgets, ' +
1006
+ 'always approve persists)',
1007
+ ],
1008
+ ];
1009
+ /**
1010
+ * EXT-71 — `approvals.escalate` used to be a SEVERITY THRESHOLD (a string), and is now the third
1011
+ * rule LIST (an array of §3.1 entries). Only the old shape is an error, so the name could be
1012
+ * reused without stranding anyone: a non-array value gets the message that names the rung which
1013
+ * expresses the old intent, instead of a bare "expected array, received string".
1014
+ */
1015
+ const RETIRED_ESCALATE_THRESHOLD_MESSAGE = 'is now the third rule LIST (an array of {type, matcher, pattern} entries that always ask the ' +
1016
+ 'human), not a severity threshold. There is no escalate threshold any more: at "assisted" and ' +
1017
+ '"auto" everything the auto-rater does not rate safe comes to you.';
1018
+ /**
1019
+ * Retired `approvals.mode` VALUES → the rung that replaced them.
1020
+ *
1021
+ * Caught here rather than by the enum so the error NAMES the rung instead of listing five
1022
+ * identifiers and leaving the user to guess which one preserves their intent.
1023
+ *
1024
+ * **No rung is raised without the user choosing it.** That is the property to preserve when adding
1025
+ * an entry: a retired name remapped to something MORE permissive would raise a user's autonomy
1026
+ * setting on their behalf, at the moment they are least watching — the config already worked, so
1027
+ * nothing prompts them to re-read it.
1028
+ *
1029
+ * `manual`/`assisted`/`auto` are pure renames of `read-only`/`auto-safe`/`full-auto` and carry
1030
+ * identical behaviour, so they preserve it trivially. `ask` is the one entry that does not, and the
1031
+ * exception is worth stating rather than glossing: `write` auto-grants working-folder file edits
1032
+ * that `ask` prompted for, which is strictly a widening. It is safe here only because nothing is
1033
+ * remapped silently — every entry is a hard validation ERROR, and this one offers `write` or
1034
+ * `manual` as a labelled choice with the difference spelled out, so the user picks. An entry that
1035
+ * widened while merely warning, or while coercing, would break the property.
1036
+ *
1037
+ * `write` and `bypass` are deliberately ABSENT — they are live rung names, not retired ones.
1038
+ *
1039
+ * **`auto` is deliberately absent too, and that is a reversal.** It named the pre-2.0
1040
+ * rater-mediated mode and used to error here; it is now the canonical name of the most permissive
1041
+ * rated rung. Reviving the token is not a back-compat concern (Andrew, 2026-08-07): the value was
1042
+ * born during 2.0 alpha work, so no released configuration carries it with the old meaning. This
1043
+ * entry and the rename must land together — an `auto` left in this table makes the newly canonical
1044
+ * name a hard validation error on arrival.
1045
+ */
1046
+ const RETIRED_APPROVAL_MODES = [
1047
+ ['read-only', '"manual" (the same mode, renamed)'],
1048
+ ['auto-safe', '"assisted" (the same mode, renamed)'],
1049
+ ['full-auto', '"auto" (the same mode, renamed)'],
1050
+ [
1051
+ 'ask',
1052
+ '"write" (Gaunt Sloth edits files freely and asks about everything else) or "manual" ' +
1053
+ '(it asks before writing too)',
1054
+ ],
1055
+ ];
1056
+ /**
1057
+ * Pointer to the migration path, appended to every deprecated-shape error so the user
1058
+ * always learns HOW to fix it, not just that it broke. Doc link only, per DOC-STYLE
1059
+ * rule 9 (user-visible doc references are absolute GitHub URLs).
1060
+ * GS2-5 (B15) will ship `gth config migrate` / `gth doctor --fix`; restore the command
1061
+ * reference here when that tooling lands.
1062
+ */
1063
+ const MIGRATION_HINT = 'See the 2.0 migration notes: https://github.com/pukeko-robotics/gaunt-sloth/blob/main/docs/MIGRATION.md';
1064
+ /**
1065
+ * CFG-26 — scan one `builtInTools` value (root or per-command) for the retired
1066
+ * `run_shell_command` approval knobs, pushing one issue per occurrence. Only the OBJECT registry
1067
+ * form can carry them (the legacy `string[]` form is names-only), so an array/non-object value is
1068
+ * a no-op. `pathPrefix` is `builtInTools` at the root and `commands.<name>.builtInTools` per
1069
+ * command, so the reported path points exactly at the offending key.
1070
+ */
1071
+ function collectRetiredShellToolIssues(builtInTools, pathPrefix, issues) {
1072
+ if (!builtInTools || typeof builtInTools !== 'object' || Array.isArray(builtInTools))
1073
+ return;
1074
+ const shellEntry = builtInTools[SHELL_TOOL_REGISTRY_KEY];
1075
+ if (!shellEntry || typeof shellEntry !== 'object' || Array.isArray(shellEntry))
1076
+ return;
1077
+ for (const [retired, replacement] of RETIRED_SHELL_TOOL_PAIRS) {
1078
+ if (Object.prototype.hasOwnProperty.call(shellEntry, retired)) {
1079
+ issues.push({
1080
+ path: `${pathPrefix}.${SHELL_TOOL_REGISTRY_KEY}.${retired}`,
1081
+ message: `Config property "${retired}" in ${pathPrefix}.${SHELL_TOOL_REGISTRY_KEY} is no longer ` +
1082
+ `supported in 2.0. Use ${replacement} instead. ${MIGRATION_HINT}`,
1083
+ });
1084
+ }
1085
+ }
1086
+ }
1087
+ /**
1088
+ * CFG-27 — scan one `approvals` value (root or per-command) for the keys and `mode` values the
1089
+ * five-rung ladder retired, pushing one issue per occurrence. The scalar form carries no keys, so
1090
+ * only the object form can offend — except for a retired `mode` VALUE, which the scalar form can
1091
+ * carry directly (`"approvals": "auto"`), so both shapes are checked for that.
1092
+ *
1093
+ * `pathPrefix` is `approvals` at the root and `commands.<name>.approvals` per command, so the
1094
+ * reported path points exactly at the offending key.
1095
+ */
1096
+ function collectRetiredApprovalsIssues(approvals, pathPrefix, issues) {
1097
+ if (approvals === undefined || approvals === null)
1098
+ return;
1099
+ // The scalar sugar form: `"approvals": "auto"`. Only a retired VALUE is an issue here; an
1100
+ // unknown string is left to the enum, which lists the five valid rungs.
1101
+ if (typeof approvals === 'string') {
1102
+ for (const [retired, replacement] of RETIRED_APPROVAL_MODES) {
1103
+ if (approvals === retired) {
1104
+ issues.push({
1105
+ path: pathPrefix,
1106
+ message: `Approval mode "${retired}" is no longer supported: approvals is now one ordered ` +
1107
+ `ladder of five modes (${APPROVAL_RUNG_LIST}). ` +
1108
+ `Use ${replacement} instead. ${MIGRATION_HINT}`,
1109
+ });
1110
+ }
1111
+ }
1112
+ return;
1113
+ }
1114
+ if (typeof approvals !== 'object' || Array.isArray(approvals))
1115
+ return;
1116
+ const block = approvals;
1117
+ for (const [retired, replacement] of RETIRED_APPROVALS_KEYS) {
1118
+ if (Object.prototype.hasOwnProperty.call(block, retired)) {
1119
+ issues.push({
1120
+ path: `${pathPrefix}.${retired}`,
1121
+ message: `Config property "${retired}" in ${pathPrefix} is no longer supported: approvals is now ` +
1122
+ `one ordered ladder of five modes (${APPROVAL_RUNG_LIST}), ` +
1123
+ `and each mode fully determines behaviour. Use ${replacement}. ${MIGRATION_HINT}`,
1124
+ });
1125
+ }
1126
+ }
1127
+ // EXT-71 — `escalate` reused for the third rule list; only the retired THRESHOLD shape errors.
1128
+ if (block.escalate !== undefined && !Array.isArray(block.escalate)) {
1129
+ issues.push({
1130
+ path: `${pathPrefix}.escalate`,
1131
+ message: `Config property "escalate" in ${pathPrefix} ${RETIRED_ESCALATE_THRESHOLD_MESSAGE} ` +
1132
+ MIGRATION_HINT,
1133
+ });
1134
+ }
1135
+ // `rater` flattened from an object to a bare identity-profile name.
1136
+ const rater = block.rater;
1137
+ if (rater !== undefined && typeof rater !== 'string') {
1138
+ issues.push({
1139
+ path: `${pathPrefix}.rater`,
1140
+ message: `Config property "rater" in ${pathPrefix} is now a bare identity-profile name, not an ` +
1141
+ `object or a boolean (e.g. "rater": "safety-rater"). Whether the rater runs at all is ` +
1142
+ `decided by the mode: "assisted" and "auto" rate, the other three never do. ` +
1143
+ MIGRATION_HINT,
1144
+ });
1145
+ }
1146
+ for (const [retired, replacement] of RETIRED_APPROVAL_MODES) {
1147
+ if (block.mode === retired) {
1148
+ issues.push({
1149
+ path: `${pathPrefix}.mode`,
1150
+ message: `Approval mode "${retired}" is no longer supported: approvals is now one ordered ladder ` +
1151
+ `of five modes (${APPROVAL_RUNG_LIST}). Use ${replacement} ` +
1152
+ `instead. ${MIGRATION_HINT}`,
1153
+ });
1154
+ }
1155
+ }
1156
+ }
1157
+ /**
1158
+ * GS2-28 — detect the removed pre-2.0 config shapes on the RAW input (read-only; no
1159
+ * mutation), returning one {@link DeprecatedConfigIssue} per occurrence. A non-empty
1160
+ * result is a HARD validation failure: 2.0 dropped back-compat coercion, so an old shape
1161
+ * must error and point at the fix rather than be silently remapped or ignored.
1162
+ *
1163
+ * Detects:
1164
+ * - (A) a COMMAND name ({@link COMMAND_KEYS}) at the config ROOT — must move under `commands.<cmd>`;
1165
+ * - (C) a deprecated `*Provider*` name ({@link DEPRECATED_ROOT_PAIRS} at root,
1166
+ * {@link DEPRECATED_COMMAND_PAIRS} per command) — must use its `*Source*` replacement;
1167
+ * - (D, CFG-18) a removed per-command key folded into another ({@link REMOVED_COMMAND_KEYS}, e.g.
1168
+ * `commands.<cmd>.devTools` → configure under `builtInTools`);
1169
+ * - (E, CFG-26) a retired `run_shell_command` approval knob ({@link RETIRED_SHELL_TOOL_PAIRS}) at
1170
+ * EITHER `builtInTools.run_shell_command.*` or `commands.<cmd>.builtInTools.run_shell_command.*`
1171
+ * — each message names the `approvals.*` key that replaced it;
1172
+ * - (F, CFG-27) a retired `approvals` key or `mode` value ({@link RETIRED_APPROVALS_KEYS},
1173
+ * {@link RETIRED_APPROVAL_MODES}) at EITHER `approvals.*` or `commands.<cmd>.approvals.*` —
1174
+ * each message names the rung that replaced it.
1175
+ *
1176
+ * Runs on the raw input specifically so nested `commands.*.contentProvider` is still visible
1177
+ * (zod's per-command `z.object` would strip it before any schema-embedded check could fire).
1178
+ * A genuinely-unknown key is NOT flagged here (it stays a warn-only unknown key), preserving
1179
+ * the deliberate typo-tolerance.
1180
+ */
1181
+ export function findDeprecatedConfigIssues(raw) {
1182
+ const issues = [];
1183
+ // (A) Command name used as a top-level key — command configs must live under commands.<cmd>.
1184
+ for (const command of COMMAND_KEYS) {
1185
+ if (Object.prototype.hasOwnProperty.call(raw, command)) {
1186
+ issues.push({
1187
+ path: command,
1188
+ message: `Top-level command config "${command}" is no longer supported in 2.0. ` +
1189
+ `Move it under "commands.${command}". ${MIGRATION_HINT}`,
1190
+ });
1191
+ }
1192
+ }
1193
+ // (C) Deprecated *Provider* names at the config root.
1194
+ for (const [deprecated, canonical] of DEPRECATED_ROOT_PAIRS) {
1195
+ if (Object.prototype.hasOwnProperty.call(raw, deprecated)) {
1196
+ issues.push({
1197
+ path: deprecated,
1198
+ message: `Config property "${deprecated}" was renamed in 2.0. Use "${canonical}" instead. ` +
1199
+ MIGRATION_HINT,
1200
+ });
1201
+ }
1202
+ }
1203
+ // (E, CFG-26) Retired run_shell_command approval knobs at the ROOT builtInTools registry.
1204
+ collectRetiredShellToolIssues(raw.builtInTools, 'builtInTools', issues);
1205
+ // (F, CFG-27) Retired approvals keys / mode values in the ROOT approvals value.
1206
+ collectRetiredApprovalsIssues(raw.approvals, 'approvals', issues);
1207
+ // (C) Deprecated *Provider* names + (CFG-18) removed keys inside each commands.<name> block.
1208
+ const commands = raw.commands;
1209
+ if (commands && typeof commands === 'object' && !Array.isArray(commands)) {
1210
+ for (const [name, cmd] of Object.entries(commands)) {
1211
+ if (cmd && typeof cmd === 'object' && !Array.isArray(cmd)) {
1212
+ for (const [deprecated, canonical] of DEPRECATED_COMMAND_PAIRS) {
1213
+ if (Object.prototype.hasOwnProperty.call(cmd, deprecated)) {
1214
+ issues.push({
1215
+ path: `commands.${name}.${deprecated}`,
1216
+ message: `Config property "${deprecated}" in commands.${name} was renamed in 2.0. ` +
1217
+ `Use "${canonical}" instead. ${MIGRATION_HINT}`,
1218
+ });
1219
+ }
1220
+ }
1221
+ // (CFG-18) removed per-command keys folded into another key (e.g. devTools → builtInTools).
1222
+ for (const [removed, replacement] of REMOVED_COMMAND_KEYS) {
1223
+ if (Object.prototype.hasOwnProperty.call(cmd, removed)) {
1224
+ issues.push({
1225
+ path: `commands.${name}.${removed}`,
1226
+ message: `Config property "${removed}" in commands.${name} is no longer supported in 2.0. ` +
1227
+ `Configure tools under "${replacement}" instead. ${MIGRATION_HINT}`,
1228
+ });
1229
+ }
1230
+ }
1231
+ // (E, CFG-26) retired run_shell_command approval knobs in this command's registry.
1232
+ collectRetiredShellToolIssues(cmd.builtInTools, `commands.${name}.builtInTools`, issues);
1233
+ // (F, CFG-27) retired approvals keys / mode values in this command's approvals value.
1234
+ collectRetiredApprovalsIssues(cmd.approvals, `commands.${name}.approvals`, issues);
1235
+ }
1236
+ }
1237
+ }
1238
+ return issues;
1239
+ }
1240
+ /**
1241
+ * EXT-70 §4.7.5 — the MCP server name that cannot be written about. A server key is
1242
+ * `z.string().min(1)` both under `approvals.mcp.servers` (§9) and on an `mcpTool` entry's `server`
1243
+ * field (§3.1), so a server keyed with the empty string is one no approvals rule and no trust
1244
+ * relationship can ever refer to by name. Its tools resolve to the unattributable-server sentinel:
1245
+ * fail-closed, which is safe, but also silently un-configurable — the user would get a server whose
1246
+ * every call is gated with no way to say anything about it and no error explaining why. Refused at
1247
+ * load, for the same reason as {@link RESERVED_MCP_SERVER_NAME}: a name whose rules cannot be
1248
+ * expressed is worse than a rejected config.
1249
+ */
1250
+ const UNNAMEABLE_MCP_SERVER_NAME = '';
1251
+ /**
1252
+ * EXT-71 §3.1/§9.1 — validate every entry in one `approvals` value's three rule lists (root or per
1253
+ * command), pushing one issue per problem with a path that points at the exact entry and field.
1254
+ *
1255
+ * **Why the entries are checked HERE rather than left to the schema parse**, given that
1256
+ * `approvalsSchema` already carries {@link approvalEntrySchema}: the `approvals` value is a union
1257
+ * (the §9.1 scalar-or-object sugar), and zod reports a failing union as ONE issue at the union's
1258
+ * own path — `approvals: Invalid input` — with every arm's real diagnosis nested out of reach of
1259
+ * the formatter. That is exactly the wrong message for this grammar, where the whole requirement is
1260
+ * that a rejection names the offending field, key or pattern. Parsing each entry on its own gets
1261
+ * the precise issue back, and because this runs BEFORE the parse the precise message is the only
1262
+ * one the user sees. The schema keeps the entries too, so it stays the authority and the emitted
1263
+ * JSON Schema still describes them.
1264
+ *
1265
+ * A bare string is handled separately from the rest, because its message is the migration
1266
+ * affordance: it renders the entry for the string that was actually found rather than a generic
1267
+ * example, since what the user needs is the line they can paste back over the one they wrote.
1268
+ */
1269
+ function collectApprovalEntryIssues(approvals, pathPrefix, issues) {
1270
+ if (!approvals || typeof approvals !== 'object' || Array.isArray(approvals))
1271
+ return;
1272
+ const block = approvals;
1273
+ for (const listKey of APPROVAL_LIST_KEYS) {
1274
+ const list = block[listKey];
1275
+ if (list === undefined)
1276
+ continue;
1277
+ // A list written as something other than an array would otherwise fall back to the union's
1278
+ // bland "approvals: Invalid input" — the same message this whole function exists to replace.
1279
+ // `escalate` is exempt: its non-array shape is the retired severity threshold and gets its own
1280
+ // migration message from `collectRetiredApprovalsIssues`.
1281
+ if (!Array.isArray(list)) {
1282
+ if (listKey !== 'escalate') {
1283
+ issues.push({
1284
+ path: `${pathPrefix}.${listKey}`,
1285
+ message: `must be a LIST of rule entries, not ${typeof list === 'object' ? 'an object' : `a ${typeof list}`}. ` +
1286
+ `Write it as an array, e.g. [ ${renderApprovalEntryForString('npm test')} ]. ` +
1287
+ MIGRATION_HINT,
1288
+ });
1289
+ }
1290
+ continue;
1291
+ }
1292
+ list.forEach((entry, index) => {
1293
+ const entryPath = `${pathPrefix}.${listKey}[${index}]`;
1294
+ if (typeof entry === 'string') {
1295
+ issues.push({
1296
+ path: entryPath,
1297
+ message: 'bare strings are no longer accepted in an approvals rule list. Write the entry ' +
1298
+ `explicitly: ${renderApprovalEntryForString(entry)} — type, matcher and pattern are ` +
1299
+ `always required, and "matcher" may be exact, glob or regexp. ${MIGRATION_HINT}`,
1300
+ });
1301
+ return;
1302
+ }
1303
+ const parsed = approvalEntrySchema.safeParse(entry);
1304
+ if (parsed.success)
1305
+ return;
1306
+ for (const issue of parsed.error.issues) {
1307
+ issues.push({
1308
+ path: issue.path.length > 0 ? `${entryPath}.${issue.path.join('.')}` : entryPath,
1309
+ message: issue.message,
1310
+ });
1311
+ }
1312
+ });
1313
+ }
1314
+ }
1315
+ /**
1316
+ * EXT-70 §4.7/§9 — validate one `approvals.mcp` block, with a path that names the offending field.
1317
+ *
1318
+ * It runs PRE-PARSE for the same reason the rule entries do: `approvalsSchema` is a `z.union`, so a
1319
+ * bad `mcp` block otherwise collapses into the union's bland "approvals: Invalid input" — the
1320
+ * message this whole family of checks exists to replace. Here the user gets the server key, the
1321
+ * field and (for a hint name) the value they mistyped.
1322
+ */
1323
+ function collectMcpApprovalsIssues(approvals, pathPrefix, issues) {
1324
+ if (!approvals || typeof approvals !== 'object' || Array.isArray(approvals))
1325
+ return;
1326
+ const mcp = approvals.mcp;
1327
+ if (mcp === undefined)
1328
+ return;
1329
+ const parsed = mcpApprovalsSchema.safeParse(mcp);
1330
+ if (parsed.success)
1331
+ return;
1332
+ for (const issue of parsed.error.issues) {
1333
+ issues.push({
1334
+ path: issue.path.length > 0 ? `${pathPrefix}.mcp.${issue.path.join('.')}` : `${pathPrefix}.mcp`,
1335
+ message: issue.message,
1336
+ });
1337
+ }
1338
+ }
1339
+ /**
1340
+ * EXT-71 §3.1 — every hard error the rule grammar defines, found on the RAW input: each entry in
1341
+ * `allow`/`deny`/`escalate` validated with a path that names the offending field
1342
+ * ({@link collectApprovalEntryIssues}), the `approvals.mcp` block ({@link collectMcpApprovalsIssues}),
1343
+ * and the two `mcpServers` keys no rule can refer to — `*` ({@link RESERVED_MCP_SERVER_NAME}, which
1344
+ * an entry already reads as "every server") and the empty name
1345
+ * ({@link UNNAMEABLE_MCP_SERVER_NAME}, which no entry's `server` field can hold). Both need to see
1346
+ * `mcpServers`, a sibling of `approvals` rather than a field of it.
1347
+ *
1348
+ * All of them are HARD errors, reported the same way {@link findDeprecatedConfigIssues} reports
1349
+ * its own, and — like it — this runs BEFORE the schema parse so the precise message is the only
1350
+ * one the user sees.
1351
+ *
1352
+ * PURE: it only reads the object. Kept separate from {@link findDeprecatedConfigIssues} because
1353
+ * these are not removed pre-2.0 shapes; they are rules of the current grammar.
1354
+ */
1355
+ export function findApprovalsGrammarIssues(raw) {
1356
+ const issues = [];
1357
+ const mcpServers = raw.mcpServers;
1358
+ if (mcpServers && typeof mcpServers === 'object' && !Array.isArray(mcpServers)) {
1359
+ if (Object.prototype.hasOwnProperty.call(mcpServers, RESERVED_MCP_SERVER_NAME)) {
1360
+ issues.push({
1361
+ path: `mcpServers.${RESERVED_MCP_SERVER_NAME}`,
1362
+ message: `"${RESERVED_MCP_SERVER_NAME}" is a reserved MCP server name: an approvals rule entry ` +
1363
+ `uses it to mean EVERY server, so a server of that name would make ` +
1364
+ `{ "type": "mcpTool", "server": "${RESERVED_MCP_SERVER_NAME}", ... } ambiguous. ` +
1365
+ 'Rename the server to anything else. ' +
1366
+ MIGRATION_HINT,
1367
+ });
1368
+ }
1369
+ if (Object.prototype.hasOwnProperty.call(mcpServers, UNNAMEABLE_MCP_SERVER_NAME)) {
1370
+ issues.push({
1371
+ path: 'mcpServers.""',
1372
+ message: 'an MCP server may not be keyed with an empty name: both an approvals rule entry ' +
1373
+ '({ "type": "mcpTool", "server": ... }) and a trust relationship under ' +
1374
+ '"approvals.mcp.servers" require a server name of at least one character, so nothing ' +
1375
+ "could ever be written about this server's tools — every call it makes would be gated " +
1376
+ 'with no way to say otherwise. Give the server a name. ' +
1377
+ MIGRATION_HINT,
1378
+ });
1379
+ }
1380
+ }
1381
+ const collect = (approvals, prefix) => {
1382
+ collectApprovalEntryIssues(approvals, prefix, issues);
1383
+ collectMcpApprovalsIssues(approvals, prefix, issues);
1384
+ };
1385
+ collect(raw.approvals, 'approvals');
1386
+ const commands = raw.commands;
1387
+ if (commands && typeof commands === 'object' && !Array.isArray(commands)) {
1388
+ for (const [name, cmd] of Object.entries(commands)) {
1389
+ if (cmd && typeof cmd === 'object' && !Array.isArray(cmd)) {
1390
+ collect(cmd.approvals, `commands.${name}.approvals`);
1391
+ }
1392
+ }
1393
+ }
1394
+ return issues;
1395
+ }
1396
+ /**
1397
+ * CFG-26 — collect every `approvals.rater` in a raw config (root + each `commands.<name>`).
1398
+ * CFG-27 flattened the key: it is a BARE identity-profile name, not `rater.profile`.
1399
+ *
1400
+ * PURE — it only reads the object; the caller decides whether each name RESOLVES. That split is
1401
+ * deliberate: profile resolution needs the filesystem, and `schema.ts` must stay pure so
1402
+ * `z.toJSONSchema` and every spec that validates a config object stay cwd-independent. The loader
1403
+ * pairs this with `resolveIdentityProfileConfigPath` to enforce the GS2-62 rule that an
1404
+ * unresolvable profile is a hard error, never a silent fallback to the main model.
1405
+ */
1406
+ export function findApprovalsRaterProfiles(raw) {
1407
+ const refs = [];
1408
+ const collect = (approvals, prefix) => {
1409
+ // The scalar sugar form (`"approvals": "assisted"`) carries no rater.
1410
+ if (!approvals || typeof approvals !== 'object' || Array.isArray(approvals))
1411
+ return;
1412
+ const rater = approvals.rater;
1413
+ if (typeof rater === 'string' && rater.trim().length > 0) {
1414
+ refs.push({ path: `${prefix}.rater`, profile: rater.trim() });
1415
+ }
1416
+ };
1417
+ collect(raw.approvals, 'approvals');
1418
+ const commands = raw.commands;
1419
+ if (commands && typeof commands === 'object' && !Array.isArray(commands)) {
1420
+ for (const [name, cmd] of Object.entries(commands)) {
1421
+ if (cmd && typeof cmd === 'object' && !Array.isArray(cmd)) {
1422
+ collect(cmd.approvals, `commands.${name}.approvals`);
1423
+ }
1424
+ }
1425
+ }
1426
+ return refs;
1427
+ }
1428
+ /**
1429
+ * CFG-26 — the ONE message for an `approvals.rater.profile` that does not resolve. Shared by the
1430
+ * loader (which hard-exits a real run) and {@link validateRawGthConfig} (which backs
1431
+ * `gth config validate`), so the validator can never green-light a config the runtime refuses.
1432
+ */
1433
+ export function unresolvedRaterProfileMessage(ref) {
1434
+ return (`identity profile "${ref.profile}" not found ` +
1435
+ `(checked ${GSLOTH_DIR}/${GSLOTH_SETTINGS_DIR}/${ref.profile}/). ` +
1436
+ 'Create it with `gth config profile create`, or omit approvals.rater to rate ' +
1437
+ 'with the main model.');
1438
+ }
1439
+ /**
1440
+ * Render {@link DeprecatedConfigIssue}s as the same ` - <path>: <message>` block used for
1441
+ * Zod validation errors, so a deprecated-shape rejection reads identically to a type-mismatch
1442
+ * rejection (loader wraps it with `Invalid configuration in <source>:`).
1443
+ */
1444
+ export function formatDeprecatedConfigIssues(issues) {
1445
+ return formatIssueLines(issues);
1446
+ }
1447
+ /**
1448
+ * Generate the JSON Schema for the raw config from {@link rawGthConfigSchema} using
1449
+ * zod 4's native `z.toJSONSchema`. The output is committed to
1450
+ * `packages/core/schema/gsloth-config.schema.json` and asserted by a golden test.
1451
+ */
1452
+ export function generateConfigJsonSchema() {
1453
+ return z.toJSONSchema(rawGthConfigSchema, { io: 'input' });
1454
+ }
1455
+ /**
1456
+ * Validate a freshly-loaded raw config object against {@link rawGthConfigSchema} and
1457
+ * report the outcome as data (a pure function — no `displayWarning`/`exit`). Mirrors the
1458
+ * loader's policy: a removed pre-2.0 shape (a top-level command key or a deprecated
1459
+ * `*Provider*` name) is a HARD failure that names the fix, unknown top-level keys warn but
1460
+ * do not fail, and a genuine type mismatch on a known field fails with a path-scoped message.
1461
+ *
1462
+ * Read-only: `findDeprecatedConfigIssues`, `findUnknownTopLevelKeys` and `safeParse` never
1463
+ * mutate `raw`, so no defensive copy is needed.
1464
+ */
1465
+ export function validateRawGthConfig(raw, options) {
1466
+ const warnings = [];
1467
+ // Only an object config can carry deprecated/unknown keys. A null/array/primitive config is
1468
+ // handed straight to safeParse (below), which returns a clean "expected object" failure — the
1469
+ // scans would otherwise throw a raw TypeError, and coercing to {} would wrongly report ok:true.
1470
+ if (isRecordConfig(raw)) {
1471
+ // Removed pre-2.0 shapes short-circuit before the unknown-key warning: any deprecated name
1472
+ // present is hard-rejected here (and so never doubles as an unknown-key warning).
1473
+ const deprecatedIssues = findDeprecatedConfigIssues(raw);
1474
+ if (deprecatedIssues.length > 0) {
1475
+ return {
1476
+ ok: false,
1477
+ warnings: [],
1478
+ errorMessage: formatDeprecatedConfigIssues(deprecatedIssues),
1479
+ };
1480
+ }
1481
+ // EXT-71 — the rule-grammar errors that need to be seen before the schema parse, so the
1482
+ // message that explains the fix is the only one the user reads.
1483
+ const grammarIssues = findApprovalsGrammarIssues(raw);
1484
+ if (grammarIssues.length > 0) {
1485
+ return {
1486
+ ok: false,
1487
+ warnings: [],
1488
+ errorMessage: formatDeprecatedConfigIssues(grammarIssues),
1489
+ };
1490
+ }
1491
+ const unknownKeys = findUnknownTopLevelKeys(raw);
1492
+ if (unknownKeys.length > 0) {
1493
+ warnings.push(`Unknown top-level config ${unknownKeys.length === 1 ? 'key' : 'keys'}: ` +
1494
+ `${unknownKeys.join(', ')} (kept as-is but ignored by Gaunt Sloth; check for typos).`);
1495
+ }
1496
+ }
1497
+ const result = rawGthConfigSchema.safeParse(raw);
1498
+ if (!result.success) {
1499
+ return { ok: false, warnings, errorMessage: formatConfigValidationError(result.error) };
1500
+ }
1501
+ // CFG-26 — `approvals.rater.profile` strict resolution, when the caller supplies a resolver.
1502
+ // The predicate is INJECTED rather than imported so this module stays pure (it feeds
1503
+ // `z.toJSONSchema`, and every spec that validates a config object must stay cwd-independent),
1504
+ // while `gth config validate` still agrees with the loader instead of green-lighting a config
1505
+ // the next real run hard-exits on. Without a resolver the check is skipped, preserving the
1506
+ // in-memory callers (e.g. the profile scaffolder).
1507
+ if (options?.resolveProfile && isRecordConfig(raw)) {
1508
+ const unresolved = findApprovalsRaterProfiles(raw).filter((ref) => !options.resolveProfile(ref.profile));
1509
+ if (unresolved.length > 0) {
1510
+ return {
1511
+ ok: false,
1512
+ warnings,
1513
+ errorMessage: formatIssueLines(unresolved.map((ref) => ({ path: ref.path, message: unresolvedRaterProfileMessage(ref) }))),
1514
+ };
1515
+ }
1516
+ }
1517
+ return { ok: true, warnings };
1518
+ }
1519
+ //# sourceMappingURL=schema.js.map