@smeltjs/core 0.1.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (319) hide show
  1. package/README.md +4 -4
  2. package/dist/apply.d.ts.map +1 -1
  3. package/dist/apply.js.map +1 -1
  4. package/dist/cache/prefix.d.ts.map +1 -1
  5. package/dist/cache/prefix.js.map +1 -1
  6. package/dist/cli/args.d.ts +16 -59
  7. package/dist/cli/args.d.ts.map +1 -1
  8. package/dist/cli/args.js +18 -277
  9. package/dist/cli/args.js.map +1 -1
  10. package/dist/cli/bin.d.ts.map +1 -1
  11. package/dist/cli/bin.js.map +1 -1
  12. package/dist/cli/config.d.ts +62 -0
  13. package/dist/cli/config.d.ts.map +1 -1
  14. package/dist/cli/config.js +87 -2
  15. package/dist/cli/config.js.map +1 -1
  16. package/dist/cli/hooks.d.ts +148 -0
  17. package/dist/cli/hooks.d.ts.map +1 -0
  18. package/dist/cli/hooks.js +835 -0
  19. package/dist/cli/hooks.js.map +1 -0
  20. package/dist/cli/init.d.ts +30 -13
  21. package/dist/cli/init.d.ts.map +1 -1
  22. package/dist/cli/init.js +173 -38
  23. package/dist/cli/init.js.map +1 -1
  24. package/dist/cli/report.d.ts.map +1 -1
  25. package/dist/cli/report.js +2 -2
  26. package/dist/cli/report.js.map +1 -1
  27. package/dist/cli/run.d.ts +25 -88
  28. package/dist/cli/run.d.ts.map +1 -1
  29. package/dist/cli/run.js +32 -322
  30. package/dist/cli/run.js.map +1 -1
  31. package/dist/cli/shell.d.ts +106 -0
  32. package/dist/cli/shell.d.ts.map +1 -0
  33. package/dist/cli/shell.js +100 -0
  34. package/dist/cli/shell.js.map +1 -0
  35. package/dist/cli/subcommands/flags.d.ts +141 -0
  36. package/dist/cli/subcommands/flags.d.ts.map +1 -0
  37. package/dist/cli/subcommands/flags.js +208 -0
  38. package/dist/cli/subcommands/flags.js.map +1 -0
  39. package/dist/cli/subcommands/hooks.d.ts +18 -0
  40. package/dist/cli/subcommands/hooks.d.ts.map +1 -0
  41. package/dist/cli/subcommands/hooks.js +64 -0
  42. package/dist/cli/subcommands/hooks.js.map +1 -0
  43. package/dist/cli/subcommands/init.d.ts +19 -0
  44. package/dist/cli/subcommands/init.d.ts.map +1 -0
  45. package/dist/cli/subcommands/init.js +44 -0
  46. package/dist/cli/subcommands/init.js.map +1 -0
  47. package/dist/cli/subcommands/map.d.ts +75 -0
  48. package/dist/cli/subcommands/map.d.ts.map +1 -0
  49. package/dist/cli/subcommands/map.js +132 -0
  50. package/dist/cli/subcommands/map.js.map +1 -0
  51. package/dist/cli/subcommands/registry.d.ts +80 -0
  52. package/dist/cli/subcommands/registry.d.ts.map +1 -0
  53. package/dist/cli/subcommands/registry.js +138 -0
  54. package/dist/cli/subcommands/registry.js.map +1 -0
  55. package/dist/cli/subcommands/retrieve.d.ts +74 -0
  56. package/dist/cli/subcommands/retrieve.d.ts.map +1 -0
  57. package/dist/cli/subcommands/retrieve.js +84 -0
  58. package/dist/cli/subcommands/retrieve.js.map +1 -0
  59. package/dist/cli/subcommands/smelt.d.ts +107 -0
  60. package/dist/cli/subcommands/smelt.d.ts.map +1 -0
  61. package/dist/cli/subcommands/smelt.js +304 -0
  62. package/dist/cli/subcommands/smelt.js.map +1 -0
  63. package/dist/cli/subcommands/stats.d.ts +43 -0
  64. package/dist/cli/subcommands/stats.d.ts.map +1 -0
  65. package/dist/cli/subcommands/stats.js +62 -0
  66. package/dist/cli/subcommands/stats.js.map +1 -0
  67. package/dist/cli/subcommands/subcommand.d.ts +113 -0
  68. package/dist/cli/subcommands/subcommand.d.ts.map +1 -0
  69. package/dist/cli/subcommands/subcommand.js +3 -0
  70. package/dist/cli/subcommands/subcommand.js.map +1 -0
  71. package/dist/cli/usage.d.ts +3 -0
  72. package/dist/cli/usage.d.ts.map +1 -0
  73. package/dist/cli/usage.js +95 -0
  74. package/dist/cli/usage.js.map +1 -0
  75. package/dist/detect.d.ts.map +1 -1
  76. package/dist/detect.js.map +1 -1
  77. package/dist/errors.d.ts +21 -1
  78. package/dist/errors.d.ts.map +1 -1
  79. package/dist/errors.js +33 -1
  80. package/dist/errors.js.map +1 -1
  81. package/dist/harness/aider.d.ts +10 -0
  82. package/dist/harness/aider.d.ts.map +1 -0
  83. package/dist/harness/aider.js +21 -0
  84. package/dist/harness/aider.js.map +1 -0
  85. package/dist/harness/claude-code.d.ts +3 -0
  86. package/dist/harness/claude-code.d.ts.map +1 -0
  87. package/dist/harness/claude-code.js +68 -0
  88. package/dist/harness/claude-code.js.map +1 -0
  89. package/dist/harness/cline.d.ts +3 -0
  90. package/dist/harness/cline.d.ts.map +1 -0
  91. package/dist/harness/cline.js +54 -0
  92. package/dist/harness/cline.js.map +1 -0
  93. package/dist/harness/codex.d.ts +3 -0
  94. package/dist/harness/codex.d.ts.map +1 -0
  95. package/dist/harness/codex.js +91 -0
  96. package/dist/harness/codex.js.map +1 -0
  97. package/dist/harness/cursor.d.ts +3 -0
  98. package/dist/harness/cursor.d.ts.map +1 -0
  99. package/dist/harness/cursor.js +54 -0
  100. package/dist/harness/cursor.js.map +1 -0
  101. package/dist/harness/gemini.d.ts +3 -0
  102. package/dist/harness/gemini.d.ts.map +1 -0
  103. package/dist/harness/gemini.js +59 -0
  104. package/dist/harness/gemini.js.map +1 -0
  105. package/dist/harness/grok.d.ts +3 -0
  106. package/dist/harness/grok.d.ts.map +1 -0
  107. package/dist/harness/grok.js +46 -0
  108. package/dist/harness/grok.js.map +1 -0
  109. package/dist/harness/hermes.d.ts +3 -0
  110. package/dist/harness/hermes.d.ts.map +1 -0
  111. package/dist/harness/hermes.js +71 -0
  112. package/dist/harness/hermes.js.map +1 -0
  113. package/dist/harness/kilocode.d.ts +3 -0
  114. package/dist/harness/kilocode.d.ts.map +1 -0
  115. package/dist/harness/kilocode.js +35 -0
  116. package/dist/harness/kilocode.js.map +1 -0
  117. package/dist/harness/opencode.d.ts +3 -0
  118. package/dist/harness/opencode.d.ts.map +1 -0
  119. package/dist/harness/opencode.js +97 -0
  120. package/dist/harness/opencode.js.map +1 -0
  121. package/dist/harness/paths.d.ts +17 -0
  122. package/dist/harness/paths.d.ts.map +1 -0
  123. package/dist/harness/paths.js +45 -0
  124. package/dist/harness/paths.js.map +1 -0
  125. package/dist/harness/profile.d.ts +184 -0
  126. package/dist/harness/profile.d.ts.map +1 -0
  127. package/dist/harness/profile.js +26 -0
  128. package/dist/harness/profile.js.map +1 -0
  129. package/dist/harness/registry.d.ts +51 -0
  130. package/dist/harness/registry.d.ts.map +1 -0
  131. package/dist/harness/registry.js +87 -0
  132. package/dist/harness/registry.js.map +1 -0
  133. package/dist/harness/snippet.d.ts +19 -0
  134. package/dist/harness/snippet.d.ts.map +1 -0
  135. package/dist/harness/snippet.js +41 -0
  136. package/dist/harness/snippet.js.map +1 -0
  137. package/dist/hash.d.ts.map +1 -1
  138. package/dist/hash.js.map +1 -1
  139. package/dist/hooks/guard-core.d.ts +164 -0
  140. package/dist/hooks/guard-core.d.ts.map +1 -0
  141. package/dist/hooks/guard-core.js +491 -0
  142. package/dist/hooks/guard-core.js.map +1 -0
  143. package/dist/hooks/shim.d.ts +176 -0
  144. package/dist/hooks/shim.d.ts.map +1 -0
  145. package/dist/hooks/shim.js +192 -0
  146. package/dist/hooks/shim.js.map +1 -0
  147. package/dist/hooks/shims/claude-code.d.ts +10 -0
  148. package/dist/hooks/shims/claude-code.d.ts.map +1 -0
  149. package/dist/hooks/shims/claude-code.js +14 -0
  150. package/dist/hooks/shims/claude-code.js.map +1 -0
  151. package/dist/hooks/shims/cline.d.ts +10 -0
  152. package/dist/hooks/shims/cline.d.ts.map +1 -0
  153. package/dist/hooks/shims/cline.js +14 -0
  154. package/dist/hooks/shims/cline.js.map +1 -0
  155. package/dist/hooks/shims/codex.d.ts +10 -0
  156. package/dist/hooks/shims/codex.d.ts.map +1 -0
  157. package/dist/hooks/shims/codex.js +14 -0
  158. package/dist/hooks/shims/codex.js.map +1 -0
  159. package/dist/hooks/shims/cursor.d.ts +10 -0
  160. package/dist/hooks/shims/cursor.d.ts.map +1 -0
  161. package/dist/hooks/shims/cursor.js +14 -0
  162. package/dist/hooks/shims/cursor.js.map +1 -0
  163. package/dist/hooks/shims/gemini.d.ts +10 -0
  164. package/dist/hooks/shims/gemini.d.ts.map +1 -0
  165. package/dist/hooks/shims/gemini.js +14 -0
  166. package/dist/hooks/shims/gemini.js.map +1 -0
  167. package/dist/hooks/shims/grok.d.ts +10 -0
  168. package/dist/hooks/shims/grok.d.ts.map +1 -0
  169. package/dist/hooks/shims/grok.js +14 -0
  170. package/dist/hooks/shims/grok.js.map +1 -0
  171. package/dist/hooks/shims/hermes.d.ts +10 -0
  172. package/dist/hooks/shims/hermes.d.ts.map +1 -0
  173. package/dist/hooks/shims/hermes.js +14 -0
  174. package/dist/hooks/shims/hermes.js.map +1 -0
  175. package/dist/index.d.ts +33 -76
  176. package/dist/index.d.ts.map +1 -1
  177. package/dist/index.js +13 -67
  178. package/dist/index.js.map +1 -1
  179. package/dist/lang/bash.d.ts.map +1 -1
  180. package/dist/lang/bash.js.map +1 -1
  181. package/dist/lang/c.d.ts.map +1 -1
  182. package/dist/lang/c.js.map +1 -1
  183. package/dist/lang/c_sharp.d.ts.map +1 -1
  184. package/dist/lang/c_sharp.js.map +1 -1
  185. package/dist/lang/cpp.d.ts.map +1 -1
  186. package/dist/lang/cpp.js.map +1 -1
  187. package/dist/lang/go.d.ts.map +1 -1
  188. package/dist/lang/go.js.map +1 -1
  189. package/dist/lang/java.d.ts.map +1 -1
  190. package/dist/lang/java.js.map +1 -1
  191. package/dist/lang/javascript.d.ts.map +1 -1
  192. package/dist/lang/javascript.js.map +1 -1
  193. package/dist/lang/kotlin.d.ts.map +1 -1
  194. package/dist/lang/kotlin.js.map +1 -1
  195. package/dist/lang/php.d.ts.map +1 -1
  196. package/dist/lang/php.js.map +1 -1
  197. package/dist/lang/profile.d.ts.map +1 -1
  198. package/dist/lang/profile.js.map +1 -1
  199. package/dist/lang/python.d.ts.map +1 -1
  200. package/dist/lang/python.js.map +1 -1
  201. package/dist/lang/registry.d.ts.map +1 -1
  202. package/dist/lang/registry.js.map +1 -1
  203. package/dist/lang/ruby.d.ts.map +1 -1
  204. package/dist/lang/ruby.js.map +1 -1
  205. package/dist/lang/rust.d.ts.map +1 -1
  206. package/dist/lang/rust.js.map +1 -1
  207. package/dist/lang/swift.d.ts.map +1 -1
  208. package/dist/lang/swift.js.map +1 -1
  209. package/dist/lang/tsx.d.ts.map +1 -1
  210. package/dist/lang/tsx.js.map +1 -1
  211. package/dist/lang/typescript.d.ts.map +1 -1
  212. package/dist/lang/typescript.js.map +1 -1
  213. package/dist/net/policy.d.ts +18 -1
  214. package/dist/net/policy.d.ts.map +1 -1
  215. package/dist/net/policy.js +7 -4
  216. package/dist/net/policy.js.map +1 -1
  217. package/dist/ops/index.d.ts +39 -0
  218. package/dist/ops/index.d.ts.map +1 -0
  219. package/dist/ops/index.js +37 -0
  220. package/dist/ops/index.js.map +1 -0
  221. package/dist/ops/inputs.d.ts +170 -0
  222. package/dist/ops/inputs.d.ts.map +1 -0
  223. package/dist/ops/inputs.js +142 -0
  224. package/dist/ops/inputs.js.map +1 -0
  225. package/dist/ops/verbs.d.ts +136 -0
  226. package/dist/ops/verbs.d.ts.map +1 -0
  227. package/dist/ops/verbs.js +76 -0
  228. package/dist/ops/verbs.js.map +1 -0
  229. package/dist/plan/auto.d.ts +69 -0
  230. package/dist/plan/auto.d.ts.map +1 -0
  231. package/dist/plan/auto.js +70 -0
  232. package/dist/plan/auto.js.map +1 -0
  233. package/dist/plan/budget.d.ts +21 -0
  234. package/dist/plan/budget.d.ts.map +1 -0
  235. package/dist/plan/budget.js +26 -0
  236. package/dist/plan/budget.js.map +1 -0
  237. package/dist/plan/grammar.d.ts +14 -0
  238. package/dist/plan/grammar.d.ts.map +1 -1
  239. package/dist/plan/grammar.js +47 -6
  240. package/dist/plan/grammar.js.map +1 -1
  241. package/dist/plan/lexical.d.ts.map +1 -1
  242. package/dist/plan/lexical.js +1 -7
  243. package/dist/plan/lexical.js.map +1 -1
  244. package/dist/plan/planners.d.ts +35 -2
  245. package/dist/plan/planners.d.ts.map +1 -1
  246. package/dist/plan/planners.js +35 -2
  247. package/dist/plan/planners.js.map +1 -1
  248. package/dist/plan/structural.d.ts +19 -5
  249. package/dist/plan/structural.d.ts.map +1 -1
  250. package/dist/plan/structural.js +180 -33
  251. package/dist/plan/structural.js.map +1 -1
  252. package/dist/repomap/cache.d.ts +48 -0
  253. package/dist/repomap/cache.d.ts.map +1 -1
  254. package/dist/repomap/cache.js +112 -13
  255. package/dist/repomap/cache.js.map +1 -1
  256. package/dist/repomap/io.d.ts +24 -0
  257. package/dist/repomap/io.d.ts.map +1 -0
  258. package/dist/repomap/io.js +34 -0
  259. package/dist/repomap/io.js.map +1 -0
  260. package/dist/repomap/map.d.ts +69 -6
  261. package/dist/repomap/map.d.ts.map +1 -1
  262. package/dist/repomap/map.js +104 -22
  263. package/dist/repomap/map.js.map +1 -1
  264. package/dist/repomap/rank.d.ts +26 -2
  265. package/dist/repomap/rank.d.ts.map +1 -1
  266. package/dist/repomap/rank.js +20 -0
  267. package/dist/repomap/rank.js.map +1 -1
  268. package/dist/repomap/reader.d.ts +73 -0
  269. package/dist/repomap/reader.d.ts.map +1 -0
  270. package/dist/repomap/reader.js +30 -0
  271. package/dist/repomap/reader.js.map +1 -0
  272. package/dist/repomap/tags.d.ts.map +1 -1
  273. package/dist/repomap/tags.js.map +1 -1
  274. package/dist/retrieve.d.ts +8 -0
  275. package/dist/retrieve.d.ts.map +1 -1
  276. package/dist/retrieve.js +12 -1
  277. package/dist/retrieve.js.map +1 -1
  278. package/dist/smelter.d.ts +79 -0
  279. package/dist/smelter.d.ts.map +1 -0
  280. package/dist/smelter.js +65 -0
  281. package/dist/smelter.js.map +1 -0
  282. package/dist/stages.d.ts.map +1 -1
  283. package/dist/stages.js +2 -2
  284. package/dist/stages.js.map +1 -1
  285. package/dist/stats.d.ts +2 -1
  286. package/dist/stats.d.ts.map +1 -1
  287. package/dist/stats.js +2 -1
  288. package/dist/stats.js.map +1 -1
  289. package/dist/store-dir.d.ts +43 -4
  290. package/dist/store-dir.d.ts.map +1 -1
  291. package/dist/store-dir.js +48 -5
  292. package/dist/store-dir.js.map +1 -1
  293. package/dist/store.d.ts +6 -0
  294. package/dist/store.d.ts.map +1 -1
  295. package/dist/store.js +6 -0
  296. package/dist/store.js.map +1 -1
  297. package/dist/types.d.ts +35 -3
  298. package/dist/types.d.ts.map +1 -1
  299. package/dist/types.js.map +1 -1
  300. package/grammars/tree-sitter-bash.wasm +0 -0
  301. package/grammars/tree-sitter-c.wasm +0 -0
  302. package/grammars/tree-sitter-c_sharp.wasm +0 -0
  303. package/grammars/tree-sitter-cpp.wasm +0 -0
  304. package/grammars/tree-sitter-go.wasm +0 -0
  305. package/grammars/tree-sitter-java.wasm +0 -0
  306. package/grammars/tree-sitter-javascript.wasm +0 -0
  307. package/grammars/tree-sitter-kotlin.wasm +0 -0
  308. package/grammars/tree-sitter-php.wasm +0 -0
  309. package/grammars/tree-sitter-python.wasm +0 -0
  310. package/grammars/tree-sitter-ruby.wasm +0 -0
  311. package/grammars/tree-sitter-rust.wasm +0 -0
  312. package/grammars/tree-sitter-swift.wasm +0 -0
  313. package/grammars/tree-sitter-tsx.wasm +0 -0
  314. package/grammars/tree-sitter-typescript.wasm +0 -0
  315. package/package.json +22 -14
  316. package/dist/cli/resolve.d.ts +0 -103
  317. package/dist/cli/resolve.d.ts.map +0 -1
  318. package/dist/cli/resolve.js +0 -106
  319. package/dist/cli/resolve.js.map +0 -1
@@ -1,8 +1,9 @@
1
1
  import { existsSync, readFileSync } from 'node:fs';
2
2
  import { dirname, join, resolve } from 'node:path';
3
3
  import { CliUsageError } from '../errors.js';
4
+ import { ENFORCEMENT_MODES } from '../hooks/guard-core.js';
4
5
  import { isStrategy, STRATEGIES } from '../plan/planners.js';
5
- import { CLI_NAME } from './args.js';
6
+ import { CLI_NAME } from './shell.js';
6
7
  /**
7
8
  * `smelt.config.json` — CLI defaults, and nothing more.
8
9
  *
@@ -84,7 +85,7 @@ export function parseConfig(text, path) {
84
85
  `${String(CONFIG_VERSION)}. The schema is versioned so a mismatch is visible ` +
85
86
  `instead of half-understood.`);
86
87
  }
87
- const known = ['smeltConfig', 'defaultBudgetBytes', 'strategy', 'store'];
88
+ const known = ['smeltConfig', 'defaultBudgetBytes', 'strategy', 'store', 'hooks'];
88
89
  const unknown = Object.keys(fields).filter((key) => !known.includes(key));
89
90
  if (unknown.length > 0) {
90
91
  throw bad(`unknown key${unknown.length === 1 ? '' : 's'} ${unknown.map((k) => `"${k}"`).join(', ')}. ` +
@@ -104,11 +105,53 @@ export function parseConfig(text, path) {
104
105
  `got ${JSON.stringify(strategy)}.`);
105
106
  }
106
107
  const store = parseStore(fields['store'], bad);
108
+ const hooks = parseHooks(fields['hooks'], bad);
107
109
  return {
108
110
  smeltConfig: CONFIG_VERSION,
109
111
  ...(budget === undefined ? {} : { defaultBudgetBytes: budget }),
110
112
  ...(strategy === undefined ? {} : { strategy }),
111
113
  ...(store === undefined ? {} : { store }),
114
+ ...(hooks === undefined ? {} : { hooks }),
115
+ };
116
+ }
117
+ /**
118
+ * Serialize a config back to the bytes of a `smelt.config.json` — {@link parseConfig}'s
119
+ * inverse, and the **only** writer of this file.
120
+ *
121
+ * The module that owns the schema owns both directions. It used to own only the read:
122
+ * two modules hand-built a config object and stringified it — the `init` wizard and
123
+ * `hooks install` — and they had already drifted, one always emitting `strategy` and
124
+ * the other only when it was carried. A sixth key would have been written by whichever
125
+ * module its author was editing and silently dropped by the other, which is the
126
+ * "setting the user believed was in force" failure this file refuses everywhere else.
127
+ *
128
+ * Key order is fixed here — the reader's own key order, top level and inside `store`
129
+ * and `hooks` — so a re-run diffs cleanly no matter which verb wrote the file, and two
130
+ * writers can never disagree about shape. What goes *into* the config stays each
131
+ * verb's policy: the wizard's choices, and `hooks install`'s directory-store injection.
132
+ * Absent keys are omitted rather than written as `null`, so
133
+ * `parseConfig(renderConfig(c))` returns `c` field for field —
134
+ * `test/guards/config-writer.test.ts` pins that round trip.
135
+ */
136
+ export function renderConfig(config) {
137
+ const ordered = {
138
+ smeltConfig: CONFIG_VERSION,
139
+ ...(config.defaultBudgetBytes === undefined
140
+ ? {}
141
+ : { defaultBudgetBytes: config.defaultBudgetBytes }),
142
+ ...(config.strategy === undefined ? {} : { strategy: config.strategy }),
143
+ ...(config.store === undefined ? {} : { store: renderStore(config.store) }),
144
+ ...(config.hooks === undefined ? {} : { hooks: renderHooks(config.hooks) }),
145
+ };
146
+ return `${JSON.stringify(ordered, null, 2)}\n`;
147
+ }
148
+ function renderStore(store) {
149
+ return store.kind === 'memory' ? { kind: 'memory' } : { kind: 'directory', path: store.path };
150
+ }
151
+ function renderHooks(hooks) {
152
+ return {
153
+ ...(hooks.thresholdBytes === undefined ? {} : { thresholdBytes: hooks.thresholdBytes }),
154
+ ...(hooks.enforcement === undefined ? {} : { enforcement: hooks.enforcement }),
112
155
  };
113
156
  }
114
157
  function parseStore(value, bad) {
@@ -137,8 +180,50 @@ function parseStore(value, bad) {
137
180
  }
138
181
  throw bad(`"store".kind must be "memory" or "directory", got ${JSON.stringify(kind)}.`);
139
182
  }
183
+ function parseHooks(value, bad) {
184
+ if (value === undefined)
185
+ return undefined;
186
+ if (typeof value !== 'object' || value === null || Array.isArray(value)) {
187
+ throw bad(`"hooks" must be an object like {"thresholdBytes":8192,"enforcement":"deny"}.`);
188
+ }
189
+ const fields = value;
190
+ const extra = Object.keys(fields).filter((key) => key !== 'thresholdBytes' && key !== 'enforcement');
191
+ if (extra.length > 0) {
192
+ throw bad(`"hooks" takes only "thresholdBytes" and "enforcement", ` +
193
+ `got ${extra.map((k) => `"${k}"`).join(', ')}.`);
194
+ }
195
+ const threshold = fields['thresholdBytes'];
196
+ if (threshold !== undefined &&
197
+ (typeof threshold !== 'number' || !Number.isInteger(threshold) || threshold <= 0)) {
198
+ throw bad(`"hooks".thresholdBytes must be a whole number of bytes greater than zero.`);
199
+ }
200
+ const enforcement = fields['enforcement'];
201
+ if (enforcement !== undefined &&
202
+ !ENFORCEMENT_MODES.includes(enforcement)) {
203
+ throw bad(`"hooks".enforcement must be ${ENFORCEMENT_MODES.map((m) => `"${m}"`).join(' or ')}, ` +
204
+ `got ${JSON.stringify(enforcement)}.`);
205
+ }
206
+ return {
207
+ ...(threshold === undefined ? {} : { thresholdBytes: threshold }),
208
+ ...(enforcement === undefined ? {} : { enforcement: enforcement }),
209
+ };
210
+ }
140
211
  /** `store.path` is relative to the config file, so the config works from any cwd. */
141
212
  export function resolveStorePath(loaded, path) {
142
213
  return resolve(dirname(loaded.path), path);
143
214
  }
215
+ /**
216
+ * The store leg of every merge, read once here rather than in each verb that needs it.
217
+ *
218
+ * There is no store flag, so this leg is config-or-built-in only — which is exactly
219
+ * why it belongs to the config module and not to a verb: `smelt` builds a store from
220
+ * it, and `retrieve`/`stats` refuse when it is not a directory (see `resolveStoreRun`
221
+ * in `subcommands/retrieve.ts`). Three verbs, one reading of the same key.
222
+ */
223
+ export function configuredStore(config) {
224
+ if (config?.config.store === undefined || config.config.store.kind === 'memory') {
225
+ return { kind: 'memory' };
226
+ }
227
+ return { kind: 'directory', path: resolveStorePath(config, config.config.store.path) };
228
+ }
144
229
  //# sourceMappingURL=config.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"config.js","sourceRoot":"","sources":["../../src/cli/config.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AACnD,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAEnD,OAAO,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAC7C,OAAO,EAAE,UAAU,EAAE,UAAU,EAAE,MAAM,qBAAqB,CAAC;AAG7D,OAAO,EAAE,QAAQ,EAAE,MAAM,WAAW,CAAC;AAErC;;;;;;;;;;;;;;;GAeG;AAEH,mEAA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+B,iBAAiB,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,MAAM,CAAC,IAAI;YACpF,OAAO,IAAI,CAAC,SAAS,CAAC,WAAW,CAAC,GAAG,CACxC,CAAC;IACJ,CAAC;IACD,OAAO;QACL,GAAG,CAAC,SAAS,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,cAAc,EAAE,SAAmB,EAAE,CAAC;QAC3E,GAAG,CAAC,WAAW,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,WAAW,EAAE,WAA8B,EAAE,CAAC;KACtF,CAAC;AACJ,CAAC;AAED,qFAAqF;AACrF,MAAM,UAAU,gBAAgB,CAAC,MAAoB,EAAE,IAAY;IACjE,OAAO,OAAO,CAAC,OAAO,CAAC,MAAM,CAAC,IAAI,CAAC,EAAE,IAAI,CAAC,CAAC;AAC7C,CAAC;AAUD;;;;;;;GAOG;AACH,MAAM,UAAU,eAAe,CAAC,MAAgC;IAC9D,IAAI,MAAM,EAAE,MAAM,CAAC,KAAK,KAAK,SAAS,IAAI,MAAM,CAAC,MAAM,CAAC,KAAK,CAAC,IAAI,KAAK,QAAQ,EAAE,CAAC;QAChF,OAAO,EAAE,IAAI,EAAE,QAAQ,EAAE,CAAC;IAC5B,CAAC;IACD,OAAO,EAAE,IAAI,EAAE,WAAW,EAAE,IAAI,EAAE,gBAAgB,CAAC,MAAM,EAAE,MAAM,CAAC,MAAM,CAAC,KAAK,CAAC,IAAI,CAAC,EAAE,CAAC;AACzF,CAAC","sourcesContent":["import { existsSync, readFileSync } from 'node:fs';\nimport { dirname, join, resolve } from 'node:path';\n\nimport { CliUsageError } from '../errors.ts';\nimport { ENFORCEMENT_MODES } from '../hooks/guard-core.ts';\nimport type { EnforcementMode } from '../hooks/guard-core.ts';\nimport { isStrategy, STRATEGIES } from '../plan/planners.ts';\nimport type { Strategy } from '../plan/planners.ts';\n\nimport { CLI_NAME } from './shell.ts';\n\n/**\n * `smelt.config.json` — CLI defaults, and nothing more.\n *\n * This file exists so `smelt` can be run without retyping the same flags, and it is\n * deliberately a *CLI* concern: the programmatic API never reads it. A library that\n * reads config files off the caller's disk is a library whose behaviour depends on\n * where it was invoked from, which is exactly the class of invisible input smelt\n * refuses. `createSmelter()` takes explicit arguments; the CLI translates this file\n * into those arguments, and explicit flags always win over it.\n *\n * The schema is versioned (`\"smeltConfig\": 1`) for the same reason the marker and the\n * `--json` envelope are: files outlive the binaries that wrote them, and a mismatch\n * must be identifiable rather than half-understood. Parsing is strict — an unknown\n * key, a wrong type, or an unknown version is a {@link CliUsageError}, never a shrug.\n * A config the CLI silently ignored would be a budget the user *thought* they set.\n */\n\n/** The file name looked for, from the working directory upward. */\nexport const CONFIG_FILE_NAME = 'smelt.config.json';\n\n/** The schema version this build reads and writes. */\nexport const CONFIG_VERSION = 1;\n\n/** Where the CLI's elision store lives between runs. */\nexport type SmeltConfigStore =\n | { readonly kind: 'memory' }\n | {\n readonly kind: 'directory';\n /** Resolved relative to the directory holding the config file, not the cwd. */\n readonly path: string;\n };\n\n/**\n * The `hooks` block — settings for the harness guard (`smelt hooks install`).\n *\n * Parsed strictly here, like every other key: the CLI refuses a malformed config.\n * The guard core (`src/hooks/guard-core.ts`) reads the same file with its own\n * *tolerant* reader — a guard running inside somebody's session fails open where the\n * CLI correctly refuses — and `test/hooks-guard-core.test.ts` pins the two readers to\n * the same key names and defaults so they cannot drift apart.\n */\nexport interface SmeltConfigHooks {\n /** Reads at or under this many bytes pass the guard untouched. Default 8192. */\n readonly thresholdBytes?: number;\n /**\n * `'deny'` (default): oversized raw reads are refused with a reason naming the\n * exact replacement command. `'rewrite'`: on harnesses whose hooks can modify tool\n * input, the command is substituted instead (never silently — the reason says so).\n */\n readonly enforcement?: EnforcementMode;\n}\n\n/** The parsed shape of `smelt.config.json`. Every field beyond the version is optional. */\nexport interface SmeltConfig {\n readonly smeltConfig: typeof CONFIG_VERSION;\n /** Used when a `smelt` run omits `--budget`. UTF-8 bytes, like every smelt budget. */\n readonly defaultBudgetBytes?: number;\n /** Used when a run omits `--strategy`. Validated against the {@link PLANNERS} registry. */\n readonly strategy?: Strategy;\n /** Used for every run; there is no store flag. Defaults to memory when absent. */\n readonly store?: SmeltConfigStore;\n /** Settings for the harness guard. See {@link SmeltConfigHooks}. */\n readonly hooks?: SmeltConfigHooks;\n}\n\n/** A config plus where it was found — the path matters for resolving `store.path`. */\nexport interface LoadedConfig {\n readonly path: string;\n readonly config: SmeltConfig;\n}\n\n/**\n * The nearest `smelt.config.json`, walking up from `cwd` to the filesystem root —\n * the same discovery shape as `package.json`, so a config at a repo root covers the\n * whole tree. `undefined` when there is none, which is not an error: flags alone are\n * a complete interface.\n */\nexport function findConfigFile(cwd: string): string | undefined {\n let dir = resolve(cwd);\n for (;;) {\n const candidate = join(dir, CONFIG_FILE_NAME);\n if (existsSync(candidate)) return candidate;\n const parent = dirname(dir);\n if (parent === dir) return undefined;\n dir = parent;\n }\n}\n\n/**\n * Find and parse the nearest config. `undefined` when no file exists; a file that\n * exists but is malformed **throws** — see {@link parseConfig}. The distinction is the\n * point: \"no config\" is a fine state, \"a config you cannot have meant\" is not.\n *\n * @throws {CliUsageError} when a config file exists and is malformed.\n */\nexport function loadNearestConfig(cwd: string): LoadedConfig | undefined {\n const path = findConfigFile(cwd);\n if (path === undefined) return undefined;\n return { path, config: parseConfig(readFileSync(path, 'utf8'), path) };\n}\n\n/**\n * Parse and validate one config file, strictly.\n *\n * Strict means: unknown keys are refused, not skipped. A typo'd `defaultBudgetByte`\n * that parsed cleanly would leave the user believing a default was set while every\n * run ignored it — a config error whose failure mode is *silence*, which is the one\n * failure shape this project refuses everywhere else too.\n *\n * @throws {CliUsageError} naming the file and the exact problem.\n */\nexport function parseConfig(text: string, path: string): SmeltConfig {\n const bad = (why: string): CliUsageError =>\n new CliUsageError(\n `${CLI_NAME}: malformed ${CONFIG_FILE_NAME} at ${path}: ${why}\\n` +\n `Fix it or delete it — a config smelt cannot read is never silently ignored. ` +\n `\\`${CLI_NAME} init\\` can rewrite it.`,\n );\n\n let value: unknown;\n try {\n value = JSON.parse(text);\n } catch (cause) {\n throw bad(`not JSON (${cause instanceof Error ? cause.message : String(cause)}).`);\n }\n if (typeof value !== 'object' || value === null || Array.isArray(value)) {\n throw bad('expected a JSON object at the top level.');\n }\n const fields = value as Record<string, unknown>;\n\n if (fields['smeltConfig'] !== CONFIG_VERSION) {\n throw bad(\n `\"smeltConfig\" is ${JSON.stringify(fields['smeltConfig'])}; this build reads version ` +\n `${String(CONFIG_VERSION)}. The schema is versioned so a mismatch is visible ` +\n `instead of half-understood.`,\n );\n }\n\n const known = ['smeltConfig', 'defaultBudgetBytes', 'strategy', 'store', 'hooks'];\n const unknown = Object.keys(fields).filter((key) => !known.includes(key));\n if (unknown.length > 0) {\n throw bad(\n `unknown key${unknown.length === 1 ? '' : 's'} ${unknown.map((k) => `\"${k}\"`).join(', ')}. ` +\n `Known keys: ${known.join(', ')}. Unknown keys are refused because a typo that ` +\n `parsed cleanly would be a setting you believed was set.`,\n );\n }\n\n const budget = fields['defaultBudgetBytes'];\n if (budget !== undefined && (typeof budget !== 'number' || !Number.isInteger(budget))) {\n throw bad(`\"defaultBudgetBytes\" must be a whole number of UTF-8 bytes.`);\n }\n if (typeof budget === 'number' && budget <= 0) {\n throw bad(`\"defaultBudgetBytes\" must be greater than zero, got ${String(budget)}.`);\n }\n\n const strategy = fields['strategy'];\n if (strategy !== undefined && (typeof strategy !== 'string' || !isStrategy(strategy))) {\n throw bad(\n `\"strategy\" must be ${STRATEGIES.map((s) => `\"${s}\"`).join(' or ')}, ` +\n `got ${JSON.stringify(strategy)}.`,\n );\n }\n\n const store = parseStore(fields['store'], bad);\n const hooks = parseHooks(fields['hooks'], bad);\n\n return {\n smeltConfig: CONFIG_VERSION,\n ...(budget === undefined ? {} : { defaultBudgetBytes: budget }),\n ...(strategy === undefined ? {} : { strategy }),\n ...(store === undefined ? {} : { store }),\n ...(hooks === undefined ? {} : { hooks }),\n };\n}\n\n/**\n * Serialize a config back to the bytes of a `smelt.config.json` — {@link parseConfig}'s\n * inverse, and the **only** writer of this file.\n *\n * The module that owns the schema owns both directions. It used to own only the read:\n * two modules hand-built a config object and stringified it — the `init` wizard and\n * `hooks install` — and they had already drifted, one always emitting `strategy` and\n * the other only when it was carried. A sixth key would have been written by whichever\n * module its author was editing and silently dropped by the other, which is the\n * \"setting the user believed was in force\" failure this file refuses everywhere else.\n *\n * Key order is fixed here — the reader's own key order, top level and inside `store`\n * and `hooks` — so a re-run diffs cleanly no matter which verb wrote the file, and two\n * writers can never disagree about shape. What goes *into* the config stays each\n * verb's policy: the wizard's choices, and `hooks install`'s directory-store injection.\n * Absent keys are omitted rather than written as `null`, so\n * `parseConfig(renderConfig(c))` returns `c` field for field —\n * `test/guards/config-writer.test.ts` pins that round trip.\n */\nexport function renderConfig(config: SmeltConfig): string {\n const ordered: SmeltConfig = {\n smeltConfig: CONFIG_VERSION,\n ...(config.defaultBudgetBytes === undefined\n ? {}\n : { defaultBudgetBytes: config.defaultBudgetBytes }),\n ...(config.strategy === undefined ? {} : { strategy: config.strategy }),\n ...(config.store === undefined ? {} : { store: renderStore(config.store) }),\n ...(config.hooks === undefined ? {} : { hooks: renderHooks(config.hooks) }),\n };\n return `${JSON.stringify(ordered, null, 2)}\\n`;\n}\n\nfunction renderStore(store: SmeltConfigStore): SmeltConfigStore {\n return store.kind === 'memory' ? { kind: 'memory' } : { kind: 'directory', path: store.path };\n}\n\nfunction renderHooks(hooks: SmeltConfigHooks): SmeltConfigHooks {\n return {\n ...(hooks.thresholdBytes === undefined ? {} : { thresholdBytes: hooks.thresholdBytes }),\n ...(hooks.enforcement === undefined ? {} : { enforcement: hooks.enforcement }),\n };\n}\n\nfunction parseStore(\n value: unknown,\n bad: (why: string) => CliUsageError,\n): SmeltConfigStore | undefined {\n if (value === undefined) return undefined;\n if (typeof value !== 'object' || value === null || Array.isArray(value)) {\n throw bad(`\"store\" must be an object like {\"kind\":\"memory\"} or {\"kind\":\"directory\",\"path\":…}.`);\n }\n const fields = value as Record<string, unknown>;\n const kind = fields['kind'];\n if (kind === 'memory') {\n const extra = Object.keys(fields).filter((key) => key !== 'kind');\n if (extra.length > 0) throw bad(`\"store\" of kind \"memory\" takes no other keys.`);\n return { kind: 'memory' };\n }\n if (kind === 'directory') {\n const path = fields['path'];\n if (typeof path !== 'string' || path === '') {\n throw bad(`\"store\" of kind \"directory\" needs a non-empty \"path\".`);\n }\n const extra = Object.keys(fields).filter((key) => key !== 'kind' && key !== 'path');\n if (extra.length > 0) throw bad(`\"store\" of kind \"directory\" takes only \"kind\" and \"path\".`);\n return { kind: 'directory', path };\n }\n throw bad(`\"store\".kind must be \"memory\" or \"directory\", got ${JSON.stringify(kind)}.`);\n}\n\nfunction parseHooks(\n value: unknown,\n bad: (why: string) => CliUsageError,\n): SmeltConfigHooks | undefined {\n if (value === undefined) return undefined;\n if (typeof value !== 'object' || value === null || Array.isArray(value)) {\n throw bad(`\"hooks\" must be an object like {\"thresholdBytes\":8192,\"enforcement\":\"deny\"}.`);\n }\n const fields = value as Record<string, unknown>;\n const extra = Object.keys(fields).filter(\n (key) => key !== 'thresholdBytes' && key !== 'enforcement',\n );\n if (extra.length > 0) {\n throw bad(\n `\"hooks\" takes only \"thresholdBytes\" and \"enforcement\", ` +\n `got ${extra.map((k) => `\"${k}\"`).join(', ')}.`,\n );\n }\n const threshold = fields['thresholdBytes'];\n if (\n threshold !== undefined &&\n (typeof threshold !== 'number' || !Number.isInteger(threshold) || threshold <= 0)\n ) {\n throw bad(`\"hooks\".thresholdBytes must be a whole number of bytes greater than zero.`);\n }\n const enforcement = fields['enforcement'];\n if (\n enforcement !== undefined &&\n !(ENFORCEMENT_MODES as readonly unknown[]).includes(enforcement)\n ) {\n throw bad(\n `\"hooks\".enforcement must be ${ENFORCEMENT_MODES.map((m) => `\"${m}\"`).join(' or ')}, ` +\n `got ${JSON.stringify(enforcement)}.`,\n );\n }\n return {\n ...(threshold === undefined ? {} : { thresholdBytes: threshold as number }),\n ...(enforcement === undefined ? {} : { enforcement: enforcement as EnforcementMode }),\n };\n}\n\n/** `store.path` is relative to the config file, so the config works from any cwd. */\nexport function resolveStorePath(loaded: LoadedConfig, path: string): string {\n return resolve(dirname(loaded.path), path);\n}\n\n/**\n * The store decision a config carries, with `path` already resolved against the config\n * file's directory — one config serves every subdirectory it covers without scattering\n * store roots. `'memory'` is the built-in default: a fresh in-memory store per run.\n */\nexport type ConfiguredStore =\n { readonly kind: 'memory' } | { readonly kind: 'directory'; readonly path: string };\n\n/**\n * The store leg of every merge, read once here rather than in each verb that needs it.\n *\n * There is no store flag, so this leg is config-or-built-in only — which is exactly\n * why it belongs to the config module and not to a verb: `smelt` builds a store from\n * it, and `retrieve`/`stats` refuse when it is not a directory (see `resolveStoreRun`\n * in `subcommands/retrieve.ts`). Three verbs, one reading of the same key.\n */\nexport function configuredStore(config: LoadedConfig | undefined): ConfiguredStore {\n if (config?.config.store === undefined || config.config.store.kind === 'memory') {\n return { kind: 'memory' };\n }\n return { kind: 'directory', path: resolveStorePath(config, config.config.store.path) };\n}\n"]}
@@ -0,0 +1,148 @@
1
+ import type { HarnessProfile } from '../harness/profile.ts';
2
+ import { instructionSnippet, SNIPPET_END_MD, SNIPPET_START_MD } from '../harness/snippet.ts';
3
+ import type { EnforcementMode } from '../hooks/guard-core.ts';
4
+ import type { AnswerStream } from './shell.ts';
5
+ import type { SmeltConfig, SmeltConfigHooks } from './config.ts';
6
+ /**
7
+ * `smelt hooks install` / `smelt hooks remove` — the multi-harness guard preset.
8
+ *
9
+ * The design: one zero-dependency guard core
10
+ * (`src/hooks/guard-core.ts`), thin per-harness shims mapping each harness's native
11
+ * hook schema onto it, and this installer, which writes the harness config that wires
12
+ * a shim in — plus an instruction-file snippet as belt and braces, because the
13
+ * snippet is also what teaches the model to run `smelt retrieve` after a deny.
14
+ *
15
+ * Every per-harness fact lives in that harness's {@link HarnessProfile}
16
+ * (`src/harness/<id>.ts`), including what to write and how to take it back out. This
17
+ * module owns only what is the *same* for every harness: the byte-faithful JSON merge,
18
+ * the marker-block upsert, the wizard, and the two plans below — folds over
19
+ * `profile.install`, with no case list of its own.
20
+ *
21
+ * Harnesses come in three honesty tiers (docs/research/2026-09-02-harness-capability-matrix.md):
22
+ *
23
+ * - **verified** — Claude Code, Codex: schemas verified against primary docs and
24
+ * exercised against recorded fixtures; first-class targets.
25
+ * - **experimental** — Gemini, Grok, Hermes, Cursor, opencode, Cline: hook schemas
26
+ * mapped from the capability matrix but not yet smoke-tested green against the
27
+ * real binary. Labelled as such in code, docs, and this installer's output.
28
+ * - **advisory** — KiloCode, Aider: no usable hook API, so what ships is
29
+ * instructions (and, for KiloCode, a permissions/MCP sketch). Nothing enforces
30
+ * them, and the output says so rather than implying a guard exists.
31
+ *
32
+ * The wizard discipline is `smelt init`'s, verbatim: every step accepts `back`,
33
+ * nothing is written until a final confirm that lists every file, and an existing
34
+ * file is never overwritten without an explicit per-file `yes` — guarded by
35
+ * `test/guards/hooks-preset.test.ts`, with mutation `hooks-install-overwrite-without-consent`
36
+ * proving the guard goes red.
37
+ */
38
+ /** Where the wizard's bytes come from and go. Injected so `runHooks` tests in-process. */
39
+ export interface HooksIo {
40
+ /**
41
+ * Scripted answers in, one line at a time. Structural on purpose; see
42
+ * {@link AnswerStream}.
43
+ */
44
+ readonly input: AnswerStream;
45
+ readonly output: (text: string) => void;
46
+ /** Project directory: detection, config discovery, and every write are relative to it. */
47
+ readonly cwd: string;
48
+ /** Home directory for detection only. Tests point it at a temp dir; nothing writes here. */
49
+ readonly home?: string;
50
+ }
51
+ export { instructionSnippet, SNIPPET_END_MD, SNIPPET_START_MD };
52
+ /** A harness whose config directory exists in the project or the home directory. */
53
+ export declare function detectedHarnesses(cwd: string, home: string): readonly HarnessProfile[];
54
+ /**
55
+ * Merge our hook entries into a JSON settings file, preserving everything foreign
56
+ * **byte-faithfully**: the merged `hooks` value is spliced into the original text, so
57
+ * unknown top-level keys, string escapes, number spellings, indentation and key order
58
+ * outside the `hooks` property ride through verbatim (an installer
59
+ * that reformats somebody's settings file has edited what it was never asked to).
60
+ * Inside `hooks`, unmanaged events and other people's entries under managed events
61
+ * are preserved; our previous entries are replaced (that is what makes a re-run edit
62
+ * toggles), and events left with no entries disappear. A semantic no-op returns the
63
+ * input text unchanged. Returns `undefined` when the existing file is not a JSON
64
+ * object — the caller skips the file rather than clobbering something it cannot
65
+ * understand.
66
+ */
67
+ export declare function mergeJsonHooks(existingText: string | undefined, events: Record<string, readonly unknown[]>, shape?: {
68
+ readonly version?: number;
69
+ }): string | undefined;
70
+ /** Replace this installer's marker block in `existingText`, or append it. */
71
+ export declare function upsertMarkerBlock(existingText: string | undefined, block: string, start: string, end: string): string;
72
+ /** Remove the marker block. `undefined` when nothing (or only whitespace) remains. */
73
+ export declare function stripMarkerBlock(existingText: string, start: string, end: string): string | undefined;
74
+ interface PlannedFile {
75
+ /** Display path, relative to the project. */
76
+ readonly name: string;
77
+ readonly path: string;
78
+ readonly content: string;
79
+ readonly exists: boolean;
80
+ readonly unchanged: boolean;
81
+ /** chmod after writing (the cline hook must be executable). */
82
+ readonly mode?: number;
83
+ }
84
+ interface SkippedFile {
85
+ readonly name: string;
86
+ readonly why: string;
87
+ }
88
+ interface PlannedRemoval {
89
+ readonly name: string;
90
+ readonly path: string;
91
+ /** `'delete'` removes the file; `'modify'` writes `content` (ours stripped out). */
92
+ readonly action: 'delete' | 'modify';
93
+ readonly content?: string;
94
+ }
95
+ export interface HooksChoices {
96
+ harnesses: HarnessProfile[];
97
+ guard: boolean;
98
+ statsOnStop: boolean;
99
+ mapOnStart: boolean;
100
+ enforcement: EnforcementMode;
101
+ thresholdBytes: number;
102
+ }
103
+ interface InstallPlan {
104
+ readonly files: readonly PlannedFile[];
105
+ readonly skipped: readonly SkippedFile[];
106
+ readonly notes: readonly string[];
107
+ }
108
+ /**
109
+ * Every file `install` would write, computed against the current disk state — pure
110
+ * planning, nothing written. A fold over each chosen profile's `install` list and its
111
+ * instruction layer; all per-harness knowledge is in the profiles. Shared instruction
112
+ * files (several harnesses read AGENTS.md) are planned once.
113
+ *
114
+ * @throws {CliUsageError} when an existing `smelt.config.json` is malformed — the
115
+ * same refusal every other subcommand makes; an installer that guessed around a
116
+ * broken config would write settings the guard then ignores.
117
+ */
118
+ export declare function planInstall(cwd: string, choices: HooksChoices): InstallPlan;
119
+ /** Where the installed config points the persistent store, relative to the config file. */
120
+ export declare const DEFAULT_STORE_DIR = ".smelt/store";
121
+ /**
122
+ * Existing config re-rendered with the hooks block, other fields carried verbatim —
123
+ * except that a config with **no** store block gains a directory store. The deny
124
+ * reasons and the instruction snippet teach `smelt retrieve <hash>`, and retrieval
125
+ * across processes needs a persistent store (`smelt retrieve` refuses a memory
126
+ * store, exit 2) — an install whose own guard promises a command the installed
127
+ * config cannot run would be the exact silent-failure shape this project refuses.
128
+ * An *explicit* `{"kind":"memory"}` is respected; the guard then conditions its
129
+ * retrieve promise on the store kind instead (`retrieveSentence` in guard-core).
130
+ *
131
+ * That store injection is this verb's **policy**, which is why it lives here; the
132
+ * bytes are written by `renderConfig` in `config.ts`, the one writer, so a key added
133
+ * to the schema reaches this file and `init`'s together or not at all.
134
+ */
135
+ export declare function renderConfigWithHooks(existing: SmeltConfig | undefined, hooks: SmeltConfigHooks): string;
136
+ /**
137
+ * Everything `remove` would delete or strip, computed against the current disk state.
138
+ * The mirror image of {@link planInstall}, over the same data: each install step's
139
+ * kind is also how it comes back out — a JSON hook file is strip-merged, a marker
140
+ * block is stripped, a file that is entirely ours is deleted.
141
+ */
142
+ export declare function planRemove(cwd: string, harnesses: readonly HarnessProfile[]): readonly PlannedRemoval[];
143
+ /**
144
+ * `smelt hooks <install|remove>`, start to finish. The same testability pattern as
145
+ * `runInit`: a pure function over an input/output pair, exit code returned.
146
+ */
147
+ export declare function runHooks(action: 'install' | 'remove', harnessFlag: string | undefined, io: HooksIo): Promise<number>;
148
+ //# sourceMappingURL=hooks.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"hooks.d.ts","sourceRoot":"","sources":["../../src/cli/hooks.ts"],"names":[],"mappings":"AAOA,OAAO,KAAK,EAGV,cAAc,EACf,MAAM,uBAAuB,CAAC;AAU/B,OAAO,EACL,kBAAkB,EAElB,cAAc,EACd,gBAAgB,EACjB,MAAM,uBAAuB,CAAC;AAE/B,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,wBAAwB,CAAC;AAG9D,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,YAAY,CAAC;AAQ/C,OAAO,KAAK,EAAE,WAAW,EAAE,gBAAgB,EAAE,MAAM,aAAa,CAAC;AAEjE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+BG;AAEH,0FAA0F;AAC1F,MAAM,WAAW,OAAO;IACtB;;;OAGG;IACH,QAAQ,CAAC,KAAK,EAAE,YAAY,CAAC;IAC7B,QAAQ,CAAC,MAAM,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,IAAI,CAAC;IACxC,0FAA0F;IAC1F,QAAQ,CAAC,GAAG,EAAE,MAAM,CAAC;IACrB,4FAA4F;IAC5F,QAAQ,CAAC,IAAI,CAAC,EAAE,MAAM,CAAC;CACxB;AAED,OAAO,EAAE,kBAAkB,EAAE,cAAc,EAAE,gBAAgB,EAAE,CAAC;AAEhE,oFAAoF;AACpF,wBAAgB,iBAAiB,CAAC,GAAG,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,GAAG,SAAS,cAAc,EAAE,CAMtF;AA8ED;;;;;;;;;;;;GAYG;AACH,wBAAgB,cAAc,CAC5B,YAAY,EAAE,MAAM,GAAG,SAAS,EAChC,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,SAAS,OAAO,EAAE,CAAC,EAC1C,KAAK,GAAE;IAAE,QAAQ,CAAC,OAAO,CAAC,EAAE,MAAM,CAAA;CAAO,GACxC,M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QAAQ,CAAC,KAAK,EAAE,SAAS,WAAW,EAAE,CAAC;IACvC,QAAQ,CAAC,OAAO,EAAE,SAAS,WAAW,EAAE,CAAC;IACzC,QAAQ,CAAC,KAAK,EAAE,SAAS,MAAM,EAAE,CAAC;CACnC;AAaD;;;;;;;;;GASG;AACH,wBAAgB,WAAW,CAAC,GAAG,EAAE,MAAM,EAAE,OAAO,EAAE,YAAY,GAAG,WAAW,CA+G3E;AAED,2FAA2F;AAC3F,eAAO,MAAM,iBAAiB,iBAAiB,CAAC;AAEhD;;;;;;;;;;;;;GAaG;AACH,wBAAgB,qBAAqB,CACnC,QAAQ,EAAE,WAAW,GAAG,SAAS,EACjC,KAAK,EAAE,gBAAgB,GACtB,MAAM,CAUR;AAED;;;;;GAKG;AACH,wBAAgB,UAAU,CACxB,GAAG,EAAE,MAAM,EACX,SAAS,EAAE,SAAS,cAAc,EAAE,GACnC,SAAS,cAAc,EAAE,CAiE3B;AAQD;;;GAGG;AACH,wBAAsB,QAAQ,CAC5B,MAAM,EAAE,SAAS,GAAG,QAAQ,EAC5B,WAAW,EAAE,MAAM,GAAG,SAAS,EAC/B,EAAE,EAAE,OAAO,GACV,OAAO,CAAC,MAAM,CAAC,CAsBjB","sourcesContent":["import { chmodSync, existsSync, mkdirSync, readFileSync, unlinkSync, writeFileSync } from 'node:fs';\nimport { homedir } from 'node:os';\nimport { dirname, join } from 'node:path';\n\nimport { CliUsageError } from '../errors.ts';\nimport { nodeCommand, portablePath, shimScriptPath, smeltBinPath } from '../harness/paths.ts';\nimport { hasShim, TIER_HONESTY } from '../harness/profile.ts';\nimport type {\n HarnessInstallContext,\n HarnessJsonHooks,\n HarnessProfile,\n} from '../harness/profile.ts';\nimport {\n GUARD_EVENTS,\n GUARD_ONLY_FILES,\n HARNESSES,\n harnessById,\n JSON_HOOK_FILES,\n LIFECYCLE_EVENTS,\n MANAGED_EVENTS,\n} from '../harness/registry.ts';\nimport {\n instructionSnippet,\n OURS_TOKEN,\n SNIPPET_END_MD,\n SNIPPET_START_MD,\n} from '../harness/snippet.ts';\nimport { DEFAULT_SUGGESTION_BUDGET_BYTES, DEFAULT_THRESHOLD_BYTES } from '../hooks/guard-core.ts';\nimport type { EnforcementMode } from '../hooks/guard-core.ts';\n\nimport { answerReader, CLI_NAME } from './shell.ts';\nimport type { AnswerStream } from './shell.ts';\nimport {\n CONFIG_FILE_NAME,\n CONFIG_VERSION,\n findConfigFile,\n parseConfig,\n renderConfig,\n} from './config.ts';\nimport type { SmeltConfig, SmeltConfigHooks } from './config.ts';\n\n/**\n * `smelt hooks install` / `smelt hooks remove` — the multi-harness guard preset.\n *\n * The design: one zero-dependency guard core\n * (`src/hooks/guard-core.ts`), thin per-harness shims mapping each harness's native\n * hook schema onto it, and this installer, which writes the harness config that wires\n * a shim in — plus an instruction-file snippet as belt and braces, because the\n * snippet is also what teaches the model to run `smelt retrieve` after a deny.\n *\n * Every per-harness fact lives in that harness's {@link HarnessProfile}\n * (`src/harness/<id>.ts`), including what to write and how to take it back out. This\n * module owns only what is the *same* for every harness: the byte-faithful JSON merge,\n * the marker-block upsert, the wizard, and the two plans below — folds over\n * `profile.install`, with no case list of its own.\n *\n * Harnesses come in three honesty tiers (docs/research/2026-09-02-harness-capability-matrix.md):\n *\n * - **verified** — Claude Code, Codex: schemas verified against primary docs and\n * exercised against recorded fixtures; first-class targets.\n * - **experimental** — Gemini, Grok, Hermes, Cursor, opencode, Cline: hook schemas\n * mapped from the capability matrix but not yet smoke-tested green against the\n * real binary. Labelled as such in code, docs, and this installer's output.\n * - **advisory** — KiloCode, Aider: no usable hook API, so what ships is\n * instructions (and, for KiloCode, a permissions/MCP sketch). Nothing enforces\n * them, and the output says so rather than implying a guard exists.\n *\n * The wizard discipline is `smelt init`'s, verbatim: every step accepts `back`,\n * nothing is written until a final confirm that lists every file, and an existing\n * file is never overwritten without an explicit per-file `yes` — guarded by\n * `test/guards/hooks-preset.test.ts`, with mutation `hooks-install-overwrite-without-consent`\n * proving the guard goes red.\n */\n\n/** Where the wizard's bytes come from and go. Injected so `runHooks` tests in-process. */\nexport interface HooksIo {\n /**\n * Scripted answers in, one line at a time. Structural on purpose; see\n * {@link AnswerStream}.\n */\n readonly input: AnswerStream;\n readonly output: (text: string) => void;\n /** Project directory: detection, config discovery, and every write are relative to it. */\n readonly cwd: string;\n /** Home directory for detection only. Tests point it at a temp dir; nothing writes here. */\n readonly home?: string;\n}\n\nexport { instructionSnippet, SNIPPET_END_MD, SNIPPET_START_MD };\n\n/** A harness whose config directory exists in the project or the home directory. */\nexport function detectedHarnesses(cwd: string, home: string): readonly HarnessProfile[] {\n return HARNESSES.filter(\n (profile) =>\n profile.detect.some((path) => existsSync(join(cwd, path))) ||\n profile.detectHome.some((path) => existsSync(join(home, path))),\n );\n}\n\n/* ------------------------------------------------------------------------------------\n * Generated content\n * ---------------------------------------------------------------------------------- */\n\n/** Claude-style hook entry: one command under an optional matcher. */\nfunction commandEntry(matcher: string | undefined, command: string): unknown {\n return {\n ...(matcher === undefined ? {} : { matcher }),\n hooks: [{ type: 'command', command }],\n };\n}\n\n/**\n * The hook command a harness's entries run: its own shim script, through node.\n *\n * @throws {Error} when a profile declares a JSON hook file but ships no shim — a\n * registry bug, pinned by `test/guards/harness-registry.test.ts`, not a user error.\n */\nfunction shimCommand(profile: HarnessProfile, cwd: string): string {\n /* v8 ignore next 5 -- unreachable: pinned by the harness-registry guard */\n if (!hasShim(profile)) {\n throw new Error(\n `smelt: harness \"${profile.id}\" wires a hook command but ships no shim script.`,\n );\n }\n return nodeCommand(cwd, shimScriptPath(profile));\n}\n\n/**\n * One harness's hook entries: the guard under each matcher its schema spells, plus\n * the two session-lifecycle hooks for the harnesses whose schema carries them. Every\n * toggle the wizard offers is a key that is present or absent here — an absent key is\n * how a re-run turns a toggle *off*, because the merge deletes what it no longer sees.\n */\nfunction jsonHookEvents(\n step: HarnessJsonHooks,\n ctx: HarnessInstallContext,\n command: string,\n): Record<string, readonly unknown[]> {\n // The trailing shell comment tags the entry as this installer's (see isOursEntry):\n // a bare `cli/bin.js` substring would also match some other npm CLI's built binary.\n const stats = `${nodeCommand(ctx.cwd, smeltBinPath(), 'stats')} 2>/dev/null || true # ${OURS_TOKEN}`;\n const map = `${nodeCommand(\n ctx.cwd,\n smeltBinPath(),\n `map . --budget ${String(ctx.budgetBytes)} --cache .smelt/tags`,\n )} 2>/dev/null || true # ${OURS_TOKEN}`;\n\n return {\n ...(ctx.guard\n ? {\n [step.event]: step.matchers.map((matcher) =>\n step.entry === 'bare-command' ? { command } : commandEntry(matcher, command),\n ),\n }\n : {}),\n ...(step.lifecycle && ctx.statsOnStop\n ? { [LIFECYCLE_EVENTS.stats]: [commandEntry(undefined, stats)] }\n : {}),\n ...(step.lifecycle && ctx.mapOnStart\n ? { [LIFECYCLE_EVENTS.map]: [commandEntry('startup|resume|clear|compact', map)] }\n : {}),\n };\n}\n\n/**\n * True for a hook entry this installer wrote. Matched on the shim script paths and the\n * `smelt:hooks` token the stats/map commands carry — never on a substring as generic\n * as `cli/bin.js`, which another npm CLI's built binary could share: remove and\n * re-install may only ever touch entries that are provably smelt's.\n */\nfunction isOursEntry(entry: unknown): boolean {\n const text = JSON.stringify(entry) ?? '';\n return text.includes('hooks/shims/') || text.includes(OURS_TOKEN);\n}\n\n/**\n * Merge our hook entries into a JSON settings file, preserving everything foreign\n * **byte-faithfully**: the merged `hooks` value is spliced into the original text, so\n * unknown top-level keys, string escapes, number spellings, indentation and key order\n * outside the `hooks` property ride through verbatim (an installer\n * that reformats somebody's settings file has edited what it was never asked to).\n * Inside `hooks`, unmanaged events and other people's entries under managed events\n * are preserved; our previous entries are replaced (that is what makes a re-run edit\n * toggles), and events left with no entries disappear. A semantic no-op returns the\n * input text unchanged. Returns `undefined` when the existing file is not a JSON\n * object — the caller skips the file rather than clobbering something it cannot\n * understand.\n */\nexport function mergeJsonHooks(\n existingText: string | undefined,\n events: Record<string, readonly unknown[]>,\n shape: { readonly version?: number } = {},\n): string | undefined {\n let root: Record<string, unknown> = {};\n if (existingText !== undefined) {\n try {\n const parsed: unknown = JSON.parse(existingText);\n if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) return undefined;\n root = parsed as Record<string, unknown>;\n } catch {\n return undefined;\n }\n }\n const hooksValue = root['hooks'];\n const existingHooks =\n typeof hooksValue === 'object' && hooksValue !== null && !Array.isArray(hooksValue)\n ? (hooksValue as Record<string, unknown>)\n : undefined;\n const hooks = { ...existingHooks };\n\n for (const event of MANAGED_EVENTS) {\n const existing = Array.isArray(hooks[event]) ? (hooks[event] as unknown[]) : [];\n const foreign = existing.filter((entry) => !isOursEntry(entry));\n const ours = events[event] ?? [];\n const merged = [...foreign, ...ours];\n if (merged.length > 0) hooks[event] = merged;\n else delete hooks[event];\n }\n\n const mergedHooks = Object.keys(hooks).length > 0 ? hooks : undefined;\n\n // A brand-new file: nothing to preserve, render fresh two-space JSON.\n if (existingText === undefined) {\n const fresh: Record<string, unknown> = {};\n if (mergedHooks !== undefined) fresh['hooks'] = mergedHooks;\n if (shape.version !== undefined) fresh['version'] = shape.version;\n return `${JSON.stringify(fresh, null, 2)}\\n`;\n }\n\n const hooksChanged =\n JSON.stringify(existingHooks ?? null) !== JSON.stringify(mergedHooks ?? null);\n const needsVersion = shape.version !== undefined && root['version'] === undefined;\n if (!hooksChanged && !needsVersion) return existingText;\n\n const newline = existingText.includes('\\r\\n') ? '\\r\\n' : '\\n';\n const indent = /\\n([ \\t]+)\"/.exec(existingText)?.[1] ?? ' ';\n let text = existingText;\n\n if (hooksChanged) {\n const scan = scanJsonTopLevel(text);\n /* v8 ignore next -- unreachable: JSON.parse accepted the same text above */\n if (scan === undefined) return undefined;\n const property = scan.properties.find((candidate) => candidate.key === 'hooks');\n if (mergedHooks === undefined) {\n if (property !== undefined) text = removeJsonProperty(text, scan, property);\n } else {\n const rendered = renderJsonValue(mergedHooks, indent, newline);\n text =\n property !== undefined\n ? `${text.slice(0, property.valueStart)}${rendered}${text.slice(property.valueEnd)}`\n : insertJsonProperty(text, scan, 'hooks', rendered, indent, newline);\n }\n }\n if (needsVersion) {\n const scan = scanJsonTopLevel(text);\n /* v8 ignore next -- unreachable: every splice above keeps the text valid JSON */\n if (scan === undefined) return undefined;\n text = insertJsonProperty(\n text,\n scan,\n 'version',\n JSON.stringify(shape.version),\n indent,\n newline,\n );\n }\n return text;\n}\n\n/** One top-level property of a JSON object, located by offsets in its source text. */\ninterface JsonTopLevelProperty {\n readonly key: string;\n /** Offset of the key's opening quote. */\n readonly keyStart: number;\n /** Offset of the value's first byte. */\n readonly valueStart: number;\n /** Offset one past the value's last byte. */\n readonly valueEnd: number;\n}\n\ninterface JsonTopLevelScan {\n /** Offset of the root object's `{`. */\n readonly open: number;\n /** Offset of the root object's `}`. */\n readonly close: number;\n readonly properties: readonly JsonTopLevelProperty[];\n}\n\n/**\n * Locate the top-level properties of a JSON object *in its source text*, so one\n * property can be replaced, inserted or removed while every other byte of the file\n * rides through verbatim. `undefined` when the text is not an object — callers have\n * already `JSON.parse`d it, so that is belt and braces, not a validator.\n */\nfunction scanJsonTopLevel(text: string): JsonTopLevelScan | undefined {\n let i = skipJsonWhitespace(text, 0);\n if (text[i] !== '{') return undefined;\n const open = i;\n i = skipJsonWhitespace(text, i + 1);\n const properties: JsonTopLevelProperty[] = [];\n if (text[i] === '}') return { open, close: i, properties };\n for (;;) {\n if (text[i] !== '\"') return undefined;\n const keyStart = i;\n const keyEnd = skipJsonString(text, i);\n if (keyEnd === undefined) return undefined;\n const key = JSON.parse(text.slice(keyStart, keyEnd)) as string;\n i = skipJsonWhitespace(text, keyEnd);\n if (text[i] !== ':') return undefined;\n const valueStart = skipJsonWhitespace(text, i + 1);\n const valueEnd = skipJsonValue(text, valueStart);\n if (valueEnd === undefined) return undefined;\n properties.push({ key, keyStart, valueStart, valueEnd });\n i = skipJsonWhitespace(text, valueEnd);\n if (text[i] === ',') {\n i = skipJsonWhitespace(text, i + 1);\n continue;\n }\n if (text[i] === '}') return { open, close: i, properties };\n return undefined;\n }\n}\n\nfunction skipJsonWhitespace(text: string, from: number): number {\n let i = from;\n while (i < text.length && ' \\t\\r\\n'.includes(text[i]!)) i += 1;\n return i;\n}\n\n/** `from` points at `\"`; returns the offset one past the closing quote. */\nfunction skipJsonString(text: string, from: number): number | undefined {\n let i = from + 1;\n while (i < text.length) {\n if (text[i] === '\\\\') i += 2;\n else if (text[i] === '\"') return i + 1;\n else i += 1;\n }\n return undefined;\n}\n\nfunction skipJsonValue(text: string, from: number): number | undefined {\n const first = text[from];\n if (first === '\"') return skipJsonString(text, from);\n if (first === '{' || first === '[') {\n let depth = 0;\n let i = from;\n while (i < text.length) {\n const ch = text[i]!;\n if (ch === '\"') {\n const end = skipJsonString(text, i);\n if (end === undefined) return undefined;\n i = end;\n continue;\n }\n if (ch === '{' || ch === '[') depth += 1;\n else if (ch === '}' || ch === ']') {\n depth -= 1;\n if (depth === 0) return i + 1;\n }\n i += 1;\n }\n return undefined;\n }\n // number / true / false / null\n let i = from;\n while (i < text.length && !',}] \\t\\r\\n'.includes(text[i]!)) i += 1;\n return i > from ? i : undefined;\n}\n\n/** A JSON value indented for embedding at a top-level property position. */\nfunction renderJsonValue(value: unknown, indent: string, newline: string): string {\n return JSON.stringify(value, null, indent).split('\\n').join(`${newline}${indent}`);\n}\n\nfunction removeJsonProperty(\n text: string,\n scan: JsonTopLevelScan,\n property: JsonTopLevelProperty,\n): string {\n const index = scan.properties.indexOf(property);\n const next = scan.properties[index + 1];\n if (next !== undefined) {\n // Delete through the separating comma and whitespace, up to the next key.\n return text.slice(0, property.keyStart) + text.slice(next.keyStart);\n }\n const previous = scan.properties[index - 1];\n // Last (or only) property: delete the preceding comma (if any) with it.\n const from = previous !== undefined ? previous.valueEnd : scan.open + 1;\n return text.slice(0, from) + text.slice(property.valueEnd);\n}\n\nfunction insertJsonProperty(\n text: string,\n scan: JsonTopLevelScan,\n key: string,\n renderedValue: string,\n indent: string,\n newline: string,\n): string {\n const entry = `${JSON.stringify(key)}: ${renderedValue}`;\n if (scan.properties.length === 0) {\n return `${text.slice(0, scan.open + 1)}${newline}${indent}${entry}${newline}${text.slice(scan.close)}`;\n }\n const last = scan.properties[scan.properties.length - 1]!;\n return `${text.slice(0, last.valueEnd)},${newline}${indent}${entry}${text.slice(last.valueEnd)}`;\n}\n\n/** Replace this installer's marker block in `existingText`, or append it. */\nexport function upsertMarkerBlock(\n existingText: string | undefined,\n block: string,\n start: string,\n end: string,\n): string {\n if (existingText === undefined || existingText.trim() === '') return block;\n const startIndex = existingText.indexOf(start);\n const endIndex = existingText.indexOf(end);\n if (startIndex !== -1 && endIndex !== -1 && endIndex > startIndex) {\n const before = existingText.slice(0, startIndex);\n const after = existingText.slice(endIndex + end.length).replace(/^\\n/, '');\n return `${before}${block}${after}`;\n }\n return `${existingText.replace(/\\n*$/, '\\n\\n')}${block}`;\n}\n\n/** Remove the marker block. `undefined` when nothing (or only whitespace) remains. */\nexport function stripMarkerBlock(\n existingText: string,\n start: string,\n end: string,\n): string | undefined {\n const startIndex = existingText.indexOf(start);\n const endIndex = existingText.indexOf(end);\n if (startIndex === -1 || endIndex === -1 || endIndex <= startIndex) return existingText;\n const stripped =\n existingText.slice(0, startIndex).replace(/\\n+$/, '\\n') +\n existingText.slice(endIndex + end.length).replace(/^\\n+/, '');\n return stripped.trim() === '' ? undefined : stripped;\n}\n\n/* ------------------------------------------------------------------------------------\n * Planning\n * ---------------------------------------------------------------------------------- */\n\ninterface PlannedFile {\n /** Display path, relative to the project. */\n readonly name: string;\n readonly path: string;\n readonly content: string;\n readonly exists: boolean;\n readonly unchanged: boolean;\n /** chmod after writing (the cline hook must be executable). */\n readonly mode?: number;\n}\n\ninterface SkippedFile {\n readonly name: string;\n readonly why: string;\n}\n\ninterface PlannedRemoval {\n readonly name: string;\n readonly path: string;\n /** `'delete'` removes the file; `'modify'` writes `content` (ours stripped out). */\n readonly action: 'delete' | 'modify';\n readonly content?: string;\n}\n\nexport interface HooksChoices {\n harnesses: HarnessProfile[];\n guard: boolean;\n statsOnStop: boolean;\n mapOnStart: boolean;\n enforcement: EnforcementMode;\n thresholdBytes: number;\n}\n\ninterface InstallPlan {\n readonly files: readonly PlannedFile[];\n readonly skipped: readonly SkippedFile[];\n readonly notes: readonly string[];\n}\n\nfunction planFile(cwd: string, name: string, content: string, mode?: number): PlannedFile {\n const path = join(cwd, name);\n const exists = existsSync(path);\n const unchanged = exists && readFileSync(path, 'utf8') === content;\n return { name, path, content, exists, unchanged, ...(mode === undefined ? {} : { mode }) };\n}\n\nfunction readIfExists(path: string): string | undefined {\n return existsSync(path) ? readFileSync(path, 'utf8') : undefined;\n}\n\n/**\n * Every file `install` would write, computed against the current disk state — pure\n * planning, nothing written. A fold over each chosen profile's `install` list and its\n * instruction layer; all per-harness knowledge is in the profiles. Shared instruction\n * files (several harnesses read AGENTS.md) are planned once.\n *\n * @throws {CliUsageError} when an existing `smelt.config.json` is malformed — the\n * same refusal every other subcommand makes; an installer that guessed around a\n * broken config would write settings the guard then ignores.\n */\nexport function planInstall(cwd: string, choices: HooksChoices): InstallPlan {\n const files = new Map<string, PlannedFile>();\n const skipped: SkippedFile[] = [];\n const notes: string[] = [];\n\n // -- smelt.config.json: the guard's runtime settings live here, not in any harness\n // file, so every shim reads one source of truth.\n const configPath = findConfigFile(cwd) ?? join(cwd, CONFIG_FILE_NAME);\n const existingConfig =\n readIfExists(configPath) === undefined\n ? undefined\n : parseConfig(readFileSync(configPath, 'utf8'), configPath);\n const hooksBlock: SmeltConfigHooks = {\n thresholdBytes: choices.thresholdBytes,\n enforcement: choices.enforcement,\n };\n const budgetBytes = existingConfig?.defaultBudgetBytes ?? DEFAULT_SUGGESTION_BUDGET_BYTES;\n files.set(configPath, {\n name: portablePath(cwd, configPath),\n path: configPath,\n content: renderConfigWithHooks(existingConfig, hooksBlock),\n exists: existsSync(configPath),\n unchanged: readIfExists(configPath) === renderConfigWithHooks(existingConfig, hooksBlock),\n });\n\n const ctx: HarnessInstallContext = {\n cwd,\n guard: choices.guard,\n statsOnStop: choices.statsOnStop,\n mapOnStart: choices.mapOnStart,\n thresholdBytes: choices.thresholdBytes,\n budgetBytes,\n };\n const snippet = instructionSnippet(choices.thresholdBytes, budgetBytes);\n\n const planJsonHooks = (\n name: string,\n events: Record<string, readonly unknown[]>,\n shape: { readonly version?: number } = {},\n ): void => {\n const path = join(cwd, name);\n // Nothing to install and nothing to strip: don't create an empty hooks file.\n if (Object.keys(events).length === 0 && !existsSync(path)) return;\n const merged = mergeJsonHooks(readIfExists(path), events, shape);\n if (merged === undefined) {\n skipped.push({\n name,\n why: 'exists but is not a JSON object — fix or remove it, then re-run',\n });\n return;\n }\n files.set(path, planFile(cwd, name, merged));\n };\n\n const planBlockFile = (\n name: string,\n block: string,\n start: string,\n end: string,\n skipWhen?: { readonly contains: string; readonly why: string },\n ): void => {\n const path = join(cwd, name);\n if (files.has(path)) return; // a shared file (AGENTS.md), already planned\n const existing = readIfExists(path);\n // A file that already carries its owner's version of what this block does is\n // theirs to edit, not ours: say so, and touch nothing.\n if (\n skipWhen !== undefined &&\n existing !== undefined &&\n !existing.includes(start) &&\n existing.includes(skipWhen.contains)\n ) {\n skipped.push({ name, why: skipWhen.why });\n return;\n }\n files.set(path, planFile(cwd, name, upsertMarkerBlock(existing, block, start, end)));\n };\n\n for (const profile of choices.harnesses) {\n for (const step of profile.install) {\n switch (step.kind) {\n case 'json-hooks':\n planJsonHooks(\n step.file,\n jsonHookEvents(step, ctx, shimCommand(profile, cwd)),\n step.shape ?? {},\n );\n break;\n case 'marker-block':\n planBlockFile(step.file, step.block(ctx), step.start, step.end, step.skipWhen);\n break;\n case 'own-file':\n if (step.guardOnly && !ctx.guard) break;\n files.set(join(cwd, step.file), planFile(cwd, step.file, step.content(ctx), step.mode));\n break;\n }\n }\n\n if (profile.instructions === 'snippet') {\n planBlockFile(profile.instructionFile, snippet, SNIPPET_START_MD, SNIPPET_END_MD);\n } else {\n files.set(\n join(cwd, profile.instructionFile),\n planFile(cwd, profile.instructionFile, profile.instructions(ctx)),\n );\n }\n\n for (const caveat of profile.caveats) notes.push(`${profile.name}: ${caveat}`);\n }\n\n return { files: [...files.values()], skipped, notes };\n}\n\n/** Where the installed config points the persistent store, relative to the config file. */\nexport const DEFAULT_STORE_DIR = '.smelt/store';\n\n/**\n * Existing config re-rendered with the hooks block, other fields carried verbatim —\n * except that a config with **no** store block gains a directory store. The deny\n * reasons and the instruction snippet teach `smelt retrieve <hash>`, and retrieval\n * across processes needs a persistent store (`smelt retrieve` refuses a memory\n * store, exit 2) — an install whose own guard promises a command the installed\n * config cannot run would be the exact silent-failure shape this project refuses.\n * An *explicit* `{\"kind\":\"memory\"}` is respected; the guard then conditions its\n * retrieve promise on the store kind instead (`retrieveSentence` in guard-core).\n *\n * That store injection is this verb's **policy**, which is why it lives here; the\n * bytes are written by `renderConfig` in `config.ts`, the one writer, so a key added\n * to the schema reaches this file and `init`'s together or not at all.\n */\nexport function renderConfigWithHooks(\n existing: SmeltConfig | undefined,\n hooks: SmeltConfigHooks,\n): string {\n return renderConfig({\n smeltConfig: CONFIG_VERSION,\n ...(existing?.defaultBudgetBytes === undefined\n ? {}\n : { defaultBudgetBytes: existing.defaultBudgetBytes }),\n ...(existing?.strategy === undefined ? {} : { strategy: existing.strategy }),\n store: existing?.store ?? { kind: 'directory', path: DEFAULT_STORE_DIR },\n hooks,\n });\n}\n\n/**\n * Everything `remove` would delete or strip, computed against the current disk state.\n * The mirror image of {@link planInstall}, over the same data: each install step's\n * kind is also how it comes back out — a JSON hook file is strip-merged, a marker\n * block is stripped, a file that is entirely ours is deleted.\n */\nexport function planRemove(\n cwd: string,\n harnesses: readonly HarnessProfile[],\n): readonly PlannedRemoval[] {\n const removals = new Map<string, PlannedRemoval>();\n\n const planJsonStrip = (name: string): void => {\n const path = join(cwd, name);\n const existing = readIfExists(path);\n if (existing === undefined) return;\n const stripped = mergeJsonHooks(existing, {});\n if (stripped === undefined || stripped === existing) return;\n const remains: unknown = JSON.parse(stripped);\n const empty =\n typeof remains === 'object' &&\n remains !== null &&\n Object.keys(remains as Record<string, unknown>).filter((key) => key !== 'version').length ===\n 0;\n removals.set(\n path,\n empty && existing.includes('hooks')\n ? { name, path, action: 'delete' }\n : { name, path, action: 'modify', content: stripped },\n );\n };\n\n const planBlockStrip = (name: string, start: string, end: string): void => {\n const path = join(cwd, name);\n const existing = readIfExists(path);\n if (existing === undefined || !existing.includes(start)) return;\n const stripped = stripMarkerBlock(existing, start, end);\n removals.set(\n path,\n stripped === undefined\n ? { name, path, action: 'delete' }\n : { name, path, action: 'modify', content: stripped },\n );\n };\n\n const planWholeFileDelete = (name: string): void => {\n const path = join(cwd, name);\n const existing = readIfExists(path);\n if (existing === undefined || !existing.includes(OURS_TOKEN)) return;\n removals.set(path, { name, path, action: 'delete' });\n };\n\n for (const profile of harnesses) {\n for (const step of profile.install) {\n switch (step.kind) {\n case 'json-hooks':\n planJsonStrip(step.file);\n break;\n case 'marker-block':\n planBlockStrip(step.file, step.start, step.end);\n break;\n case 'own-file':\n planWholeFileDelete(step.file);\n break;\n }\n }\n if (profile.instructions === 'snippet') {\n planBlockStrip(profile.instructionFile, SNIPPET_START_MD, SNIPPET_END_MD);\n } else {\n planWholeFileDelete(profile.instructionFile);\n }\n }\n\n return [...removals.values()];\n}\n\n/* ------------------------------------------------------------------------------------\n * The wizard\n * ---------------------------------------------------------------------------------- */\n\ntype Asker = (prompt: string) => Promise<string>;\n\n/**\n * `smelt hooks <install|remove>`, start to finish. The same testability pattern as\n * `runInit`: a pure function over an input/output pair, exit code returned.\n */\nexport async function runHooks(\n action: 'install' | 'remove',\n harnessFlag: string | undefined,\n io: HooksIo,\n): Promise<number> {\n // Same adapter, same reason, as `runInit` — see the note on `answerReader`.\n const lines = answerReader(io.input);\n const ask = async (prompt: string): Promise<string> => {\n io.output(prompt);\n const next = await lines.next();\n if (next === undefined) {\n throw new CliUsageError(\n `${CLI_NAME} hooks: input ended before the wizard finished. ` +\n `Files already confirmed and written stay; nothing further was written.`,\n );\n }\n return next.trim();\n };\n\n try {\n return action === 'install'\n ? await installFlow(io, ask, harnessFlag)\n : await removeFlow(io, ask, harnessFlag);\n } finally {\n await lines.release();\n }\n}\n\nfunction resolveHarnessFlag(flag: string): HarnessProfile {\n const profile = harnessById(flag);\n if (profile === undefined) {\n throw new CliUsageError(\n `${CLI_NAME} hooks: unknown harness \"${flag}\". ` +\n `Known: ${HARNESSES.map((h) => h.id).join(', ')}.`,\n );\n }\n return profile;\n}\n\nfunction tierLabel(profile: HarnessProfile): string {\n return `${profile.id.padEnd(12)} ${profile.name.padEnd(14)} [${profile.tier}] — ${TIER_HONESTY[profile.tier]}`;\n}\n\nasync function installFlow(\n io: HooksIo,\n ask: Asker,\n harnessFlag: string | undefined,\n): Promise<number> {\n const home = io.home ?? homedir();\n const detected = detectedHarnesses(io.cwd, home);\n\n io.output(\n `${CLI_NAME} hooks install — wires the smelt guard into agent-harness hooks.\\n` +\n `Answer \\`back\\` at any step to return to the previous one. Nothing is written ` +\n `until you confirm at the end.\\n\\n`,\n );\n\n const choices: HooksChoices = {\n harnesses: harnessFlag !== undefined ? [resolveHarnessFlag(harnessFlag)] : [...detected],\n ...presetToggles(io.cwd),\n enforcement: 'deny',\n thresholdBytes: DEFAULT_THRESHOLD_BYTES,\n };\n\n // With --harness the selection step is skipped, so the tier label — and its one\n // line of honesty about what the tier means — is printed here instead.\n if (harnessFlag !== undefined) {\n for (const profile of choices.harnesses) io.output(` ${tierLabel(profile)}\\n`);\n }\n\n const steps: readonly ((io_: HooksIo, ask_: Asker) => Promise<'ok' | 'back'>)[] = [\n async (io_, ask_) =>\n harnessFlag !== undefined ? 'ok' : stepHarnesses(io_, ask_, choices, detected),\n async (io_, ask_) =>\n stepToggle(io_, ask_, 'PreToolUse size-guard', guardCopy(), choices.guard, (on) => {\n choices.guard = on;\n }),\n async (io_, ask_) =>\n stepToggle(\n io_,\n ask_,\n 'stats on Stop',\n `\\`smelt stats\\` runs when a session ends — the honest signal (expansion rate) ` +\n `surfaced where the turn ends. Observation only; never blocks. Wired for ` +\n `verified-tier harnesses (Claude Code, Codex).`,\n choices.statsOnStop,\n (on) => {\n choices.statsOnStop = on;\n },\n ),\n async (io_, ask_) =>\n stepToggle(\n io_,\n ask_,\n 'repo map on SessionStart',\n `\\`smelt map . --budget …\\` runs at session start and its output opens the ` +\n `context — the agent starts oriented. Costs one map build per session. ` +\n `Wired for verified-tier harnesses (Claude Code, Codex).`,\n choices.mapOnStart,\n (on) => {\n choices.mapOnStart = on;\n },\n ),\n async (io_, ask_) => stepEnforcement(io_, ask_, choices),\n async (io_, ask_) => stepThreshold(io_, ask_, choices),\n ];\n\n let index = 0;\n for (;;) {\n while (index < steps.length) {\n const outcome = await steps[index]!(io, ask);\n if (outcome === 'back') {\n if (index === 0) io.output(`This is the first step — there is nothing before it.\\n`);\n else index -= 1;\n } else {\n index += 1;\n }\n }\n if (choices.harnesses.length === 0) {\n io.output(`No harness selected. Nothing to do; nothing was written.\\n`);\n return 0;\n }\n const verdict = await confirmAndInstall(io, ask, choices);\n if (verdict !== 'back') return 0;\n index = steps.length - 1;\n }\n}\n\nfunction guardCopy(): string {\n return (\n `Denies raw Reads (and simple \\`cat\\`s) of files over the size threshold, with a ` +\n `reason naming the exact \\`smelt\\` replacement — the model still sees everything: ` +\n `smelted first, \\`smelt retrieve\\` for the rest. Windowed reads (offset/limit) ` +\n `always pass.`\n );\n}\n\nasync function stepHarnesses(\n io: HooksIo,\n ask: Asker,\n choices: HooksChoices,\n detected: readonly HarnessProfile[],\n): Promise<'ok' | 'back'> {\n io.output(`\\nHarnesses — detected by their config directories (project or home):\\n`);\n for (const profile of HARNESSES) {\n const mark = detected.includes(profile) ? '*' : ' ';\n io.output(` ${mark} ${tierLabel(profile)}\\n`);\n }\n io.output(`(* = detected here)\\n`);\n for (;;) {\n const current = choices.harnesses.map((profile) => profile.id).join(',') || '(none)';\n const answer = await ask(\n `install for which? (comma-separated ids, Enter = ${current}, or back)\\n> `,\n );\n if (answer === 'back') return 'back';\n if (answer === '') return 'ok';\n const ids = answer\n .split(',')\n .map((id) => id.trim())\n .filter((id) => id !== '');\n const chosen: HarnessProfile[] = [];\n let bad: string | undefined;\n for (const id of ids) {\n const profile = harnessById(id);\n if (profile === undefined) bad = id;\n else if (!chosen.includes(profile)) chosen.push(profile);\n }\n if (bad !== undefined) {\n io.output(`Unknown harness \"${bad}\". Known: ${HARNESSES.map((h) => h.id).join(', ')}.\\n`);\n continue;\n }\n choices.harnesses = chosen;\n return 'ok';\n }\n}\n\nasync function stepToggle(\n io: HooksIo,\n ask: Asker,\n name: string,\n copy: string,\n current: boolean,\n set: (on: boolean) => void,\n): Promise<'ok' | 'back'> {\n io.output(`\\n${name} — ${copy}\\n`);\n for (;;) {\n const answer = await ask(`${name}? (on/off) [${current ? 'on' : 'off'}] (or back)> `);\n if (answer === 'back') return 'back';\n if (answer === '') return 'ok';\n if (answer === 'on' || answer === 'off') {\n set(answer === 'on');\n return 'ok';\n }\n io.output(`on, off, or back.\\n`);\n }\n}\n\nasync function stepEnforcement(\n io: HooksIo,\n ask: Asker,\n choices: HooksChoices,\n): Promise<'ok' | 'back'> {\n io.output(\n `\\nEnforcement — what happens when the guard catches an oversized raw read:\\n` +\n ` 1. deny — refuse with a reason naming the exact replacement command. The\\n` +\n ` transcript stays truthful; the model runs the replacement itself.\\n` +\n ` 2. rewrite — on harnesses whose hooks can modify tool input, substitute the\\n` +\n ` replacement in-flight (grep/cat piped through smelt). Never\\n` +\n ` silent: the substitution is announced in the decision reason\\n` +\n ` where the harness has one, on stderr where it does not.\\n` +\n ` Harnesses that cannot rewrite fall back to deny.\\n`,\n );\n for (;;) {\n const current = choices.enforcement === 'deny' ? '1' : '2';\n const answer = await ask(`enforcement (1/2) [${current}] (or back)> `);\n if (answer === 'back') return 'back';\n const pick = answer === '' ? current : answer;\n if (pick === '1' || pick === '2') {\n choices.enforcement = pick === '1' ? 'deny' : 'rewrite';\n return 'ok';\n }\n io.output(`1 for deny, 2 for rewrite, or back.\\n`);\n }\n}\n\nasync function stepThreshold(\n io: HooksIo,\n ask: Asker,\n choices: HooksChoices,\n): Promise<'ok' | 'back'> {\n io.output(\n `\\nSize threshold — reads at or under this many bytes always pass. The ${String(\n DEFAULT_THRESHOLD_BYTES,\n )}-byte default comes from the measured validation in ` +\n `docs/research/2026-09-02-agent-enforcement.md § 5.\\n`,\n );\n for (;;) {\n const answer = await ask(`threshold in bytes [${String(choices.thresholdBytes)}] (or back)> `);\n if (answer === 'back') return 'back';\n if (answer === '') return 'ok';\n if (/^\\d+$/.test(answer) && Number(answer) > 0) {\n choices.thresholdBytes = Number(answer);\n return 'ok';\n }\n io.output(`A whole number of bytes greater than zero, e.g. 8192.\\n`);\n }\n}\n\n/**\n * A re-run reads the toggles back off what is actually installed — every JSON hook\n * file this installer writes, plus the guard-only shim files, both derived from the\n * registry — so it edits instead of resetting. Harnesses that only wire the guard\n * (gemini, grok, cursor, hermes, opencode, cline) persist no stats/map entries, so\n * after a re-run scoped to them those toggles read back as off; the defaults below\n * apply only when nothing of smelt's is installed at all.\n */\nfunction presetToggles(cwd: string): Pick<HooksChoices, 'guard' | 'statsOnStop' | 'mapOnStart'> {\n const defaults = { guard: true, statsOnStop: true, mapOnStart: false };\n let anyOurs = false;\n let guard = false;\n let statsOnStop = false;\n let mapOnStart = false;\n\n for (const name of JSON_HOOK_FILES) {\n const text = readIfExists(join(cwd, name));\n if (text === undefined) continue;\n let hooks: Record<string, unknown> | undefined;\n try {\n const parsed: unknown = JSON.parse(text);\n const hooksValue =\n typeof parsed === 'object' && parsed !== null && !Array.isArray(parsed)\n ? (parsed as Record<string, unknown>)['hooks']\n : undefined;\n hooks =\n typeof hooksValue === 'object' && hooksValue !== null && !Array.isArray(hooksValue)\n ? (hooksValue as Record<string, unknown>)\n : undefined;\n } catch {\n hooks = undefined;\n }\n if (hooks === undefined) continue;\n const installed = hooks;\n const hasOurs = (event: string): boolean =>\n Array.isArray(installed[event]) &&\n (installed[event] as unknown[]).some((entry) => isOursEntry(entry));\n if (!MANAGED_EVENTS.some((event) => hasOurs(event))) continue;\n anyOurs = true;\n guard ||= GUARD_EVENTS.some((event) => hasOurs(event));\n statsOnStop ||= hasOurs('Stop');\n mapOnStart ||= hasOurs('SessionStart');\n }\n\n for (const name of GUARD_ONLY_FILES) {\n const text = readIfExists(join(cwd, name));\n if (text !== undefined && text.includes(OURS_TOKEN)) {\n anyOurs = true;\n guard = true;\n }\n }\n\n return anyOurs ? { guard, statsOnStop, mapOnStart } : defaults;\n}\n\nconst fileLabel = (file: PlannedFile): string => {\n if (file.unchanged) return 'unchanged — nothing to write';\n return file.exists ? 'exists — will ask before overwriting' : 'new';\n};\n\nasync function confirmAndInstall(\n io: HooksIo,\n ask: Asker,\n choices: HooksChoices,\n): Promise<'done' | 'back'> {\n const plan = planInstall(io.cwd, choices);\n\n io.output(\n `\\nAbout to write, into ${io.cwd}:\\n` +\n plan.files.map((file) => ` ${file.name.padEnd(32)} (${fileLabel(file)})\\n`).join('') +\n plan.skipped.map((skip) => ` ${skip.name.padEnd(32)} (SKIPPED: ${skip.why})\\n`).join('') +\n `Nothing has been written yet.\\n`,\n );\n\n for (;;) {\n const answer = await ask(`confirm (yes / no / back)> `);\n if (answer === 'back') return 'back';\n if (answer === 'no') {\n io.output(`Nothing was written.\\n`);\n return 'done';\n }\n if (answer === 'yes') break;\n io.output(`yes to write, no to leave everything untouched, back to change a setting.\\n`);\n }\n\n for (const file of plan.files) {\n if (file.unchanged) {\n io.output(` ${file.name} — unchanged, not rewritten\\n`);\n continue;\n }\n if (file.exists) {\n // The one hard rule, same as `smelt init`: an existing file is never touched\n // without an explicit per-file yes — not `y`, not Enter, a literal `yes`.\n const answer = await ask(` ${file.name} exists — overwrite it? (yes/no)> `);\n if (answer !== 'yes') {\n io.output(` skipped ${file.name} — the existing file was not touched\\n`);\n continue;\n }\n }\n mkdirSync(dirname(file.path), { recursive: true });\n writeFileSync(file.path, file.content);\n if (file.mode !== undefined) chmodSync(file.path, file.mode);\n io.output(` wrote ${file.name}\\n`);\n }\n\n for (const note of plan.notes) io.output(`note: ${note}\\n`);\n io.output(\n `Done. Re-run \\`${CLI_NAME} hooks install\\` to edit toggles; ` +\n `\\`${CLI_NAME} hooks remove\\` takes it all back out.\\n`,\n );\n return 'done';\n}\n\nasync function removeFlow(\n io: HooksIo,\n ask: Asker,\n harnessFlag: string | undefined,\n): Promise<number> {\n const harnesses = harnessFlag !== undefined ? [resolveHarnessFlag(harnessFlag)] : [...HARNESSES];\n const removals = planRemove(io.cwd, harnesses);\n\n if (removals.length === 0) {\n io.output(`${CLI_NAME} hooks remove: nothing of smelt's found to remove in ${io.cwd}.\\n`);\n return 0;\n }\n\n io.output(\n `${CLI_NAME} hooks remove — takes smelt's hook wiring back out.\\n\\nPlanned:\\n` +\n removals\n .map(\n (removal) =>\n ` ${removal.name.padEnd(32)} (${\n removal.action === 'delete' ? 'delete' : 'remove smelt entries, keep the rest'\n })\\n`,\n )\n .join('') +\n `${CONFIG_FILE_NAME} is left untouched — its hooks block is your config now; ` +\n `edit or remove it there.\\nNothing has been changed yet.\\n`,\n );\n\n for (;;) {\n const answer = await ask(`confirm (yes / no)> `);\n if (answer === 'no') {\n io.output(`Nothing was changed.\\n`);\n return 0;\n }\n if (answer === 'yes') break;\n io.output(`yes to proceed, no to leave everything untouched.\\n`);\n }\n\n for (const removal of removals) {\n const verb = removal.action === 'delete' ? 'delete' : 'modify';\n const answer = await ask(` ${removal.name} — ${verb} it? (yes/no)> `);\n if (answer !== 'yes') {\n io.output(` skipped ${removal.name} — not touched\\n`);\n continue;\n }\n if (removal.action === 'delete') {\n unlinkSync(removal.path);\n io.output(` deleted ${removal.name}\\n`);\n } else {\n writeFileSync(removal.path, removal.content ?? '');\n io.output(` cleaned ${removal.name}\\n`);\n }\n }\n io.output(`Done.\\n`);\n return 0;\n}\n"]}