@smeltjs/core 0.3.0 → 0.4.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 (89) hide show
  1. package/dist/agents/guide.d.ts +68 -0
  2. package/dist/agents/guide.d.ts.map +1 -0
  3. package/dist/agents/guide.js +72 -0
  4. package/dist/agents/guide.js.map +1 -0
  5. package/dist/agents/instructions.d.ts +133 -0
  6. package/dist/agents/instructions.d.ts.map +1 -0
  7. package/dist/agents/instructions.js +212 -0
  8. package/dist/agents/instructions.js.map +1 -0
  9. package/dist/agents/lint.d.ts +154 -0
  10. package/dist/agents/lint.d.ts.map +1 -0
  11. package/dist/agents/lint.js +761 -0
  12. package/dist/agents/lint.js.map +1 -0
  13. package/dist/agents/split.d.ts +113 -0
  14. package/dist/agents/split.d.ts.map +1 -0
  15. package/dist/agents/split.js +234 -0
  16. package/dist/agents/split.js.map +1 -0
  17. package/dist/cli/agents.d.ts +39 -0
  18. package/dist/cli/agents.d.ts.map +1 -0
  19. package/dist/cli/agents.js +121 -0
  20. package/dist/cli/agents.js.map +1 -0
  21. package/dist/cli/args.d.ts +1 -0
  22. package/dist/cli/args.d.ts.map +1 -1
  23. package/dist/cli/args.js.map +1 -1
  24. package/dist/cli/config.d.ts +20 -0
  25. package/dist/cli/config.d.ts.map +1 -1
  26. package/dist/cli/config.js +34 -1
  27. package/dist/cli/config.js.map +1 -1
  28. package/dist/cli/hooks.d.ts +25 -16
  29. package/dist/cli/hooks.d.ts.map +1 -1
  30. package/dist/cli/hooks.js +71 -178
  31. package/dist/cli/hooks.js.map +1 -1
  32. package/dist/cli/report.d.ts +23 -0
  33. package/dist/cli/report.d.ts.map +1 -1
  34. package/dist/cli/report.js +140 -2
  35. package/dist/cli/report.js.map +1 -1
  36. package/dist/cli/run.d.ts +5 -3
  37. package/dist/cli/run.d.ts.map +1 -1
  38. package/dist/cli/run.js +2 -1
  39. package/dist/cli/run.js.map +1 -1
  40. package/dist/cli/subcommands/agents.d.ts +72 -0
  41. package/dist/cli/subcommands/agents.d.ts.map +1 -0
  42. package/dist/cli/subcommands/agents.js +162 -0
  43. package/dist/cli/subcommands/agents.js.map +1 -0
  44. package/dist/cli/subcommands/flags.d.ts +3 -0
  45. package/dist/cli/subcommands/flags.d.ts.map +1 -1
  46. package/dist/cli/subcommands/flags.js +13 -1
  47. package/dist/cli/subcommands/flags.js.map +1 -1
  48. package/dist/cli/subcommands/hooks.d.ts.map +1 -1
  49. package/dist/cli/subcommands/hooks.js +19 -3
  50. package/dist/cli/subcommands/hooks.js.map +1 -1
  51. package/dist/cli/subcommands/registry.d.ts +2 -1
  52. package/dist/cli/subcommands/registry.d.ts.map +1 -1
  53. package/dist/cli/subcommands/registry.js +3 -0
  54. package/dist/cli/subcommands/registry.js.map +1 -1
  55. package/dist/cli/subcommands/subcommand.d.ts +1 -1
  56. package/dist/cli/subcommands/subcommand.d.ts.map +1 -1
  57. package/dist/cli/subcommands/subcommand.js.map +1 -1
  58. package/dist/harness/codex.d.ts.map +1 -1
  59. package/dist/harness/codex.js +1 -0
  60. package/dist/harness/codex.js.map +1 -1
  61. package/dist/harness/gemini.d.ts.map +1 -1
  62. package/dist/harness/gemini.js +1 -0
  63. package/dist/harness/gemini.js.map +1 -1
  64. package/dist/harness/grok.d.ts.map +1 -1
  65. package/dist/harness/grok.js +1 -0
  66. package/dist/harness/grok.js.map +1 -1
  67. package/dist/harness/hermes.d.ts.map +1 -1
  68. package/dist/harness/hermes.js +1 -0
  69. package/dist/harness/hermes.js.map +1 -1
  70. package/dist/harness/profile.d.ts +26 -1
  71. package/dist/harness/profile.d.ts.map +1 -1
  72. package/dist/harness/profile.js +15 -0
  73. package/dist/harness/profile.js.map +1 -1
  74. package/dist/harness/registry.d.ts +55 -6
  75. package/dist/harness/registry.d.ts.map +1 -1
  76. package/dist/harness/registry.js +63 -6
  77. package/dist/harness/registry.js.map +1 -1
  78. package/dist/index.d.ts +10 -0
  79. package/dist/index.d.ts.map +1 -1
  80. package/dist/index.js +8 -0
  81. package/dist/index.js.map +1 -1
  82. package/dist/text/json-edit.d.ts +71 -0
  83. package/dist/text/json-edit.d.ts.map +1 -0
  84. package/dist/text/json-edit.js +219 -0
  85. package/dist/text/json-edit.js.map +1 -0
  86. package/dist/types.d.ts +0 -11
  87. package/dist/types.d.ts.map +1 -1
  88. package/dist/types.js.map +1 -1
  89. package/package.json +1 -1
@@ -1 +1 @@
1
- {"version":3,"file":"hooks.d.ts","sourceRoot":"","sources":["../../src/cli/hooks.ts"],"names":[],"mappings":"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","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"]}
1
+ {"version":3,"file":"hooks.d.ts","sourceRoot":"","sources":["../../src/cli/hooks.ts"],"names":[],"mappings":"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","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 harnessNames,\n JSON_HOOK_FILES,\n LIFECYCLE_EVENTS,\n lifecycleHarnesses,\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';\nimport {\n editTopLevelProperty,\n jsonStyle,\n stripMarkerBlock,\n upsertMarkerBlock,\n} from '../text/json-edit.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 hooks merge (which entries\n * are ours, what a re-run replaces), the wizard, and the two plans below — folds over\n * `profile.install`, with no case list of its own. The byte-faithful editing itself —\n * one top-level JSON property, one delimited text block — is `src/text/json-edit.ts`,\n * which knows nothing about harnesses.\n *\n * Harnesses come in three honesty tiers (docs/research/2026-09-02-harness-capability-matrix.md),\n * and which harness sits at which is `HarnessProfile.tier` — read through\n * `harnessesByTier()`, never listed again here:\n *\n * - **verified** — schemas verified against primary docs and exercised against\n * recorded fixtures; first-class targets.\n * - **experimental** — hook schemas mapped from the capability matrix but not yet\n * smoke-tested green against the real binary. Labelled as such in code, docs, and\n * this installer's output.\n * - **advisory** — no usable hook API, so what ships is instructions (and, for\n * KiloCode, a permissions/MCP sketch). Nothing enforces them, and the output says\n * 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 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 *\n * The two `SessionStart` toggles — the opening map and the instruction-file lint —\n * are **concatenated into one array**, not spread as two objects. Spreading would put\n * the same computed key twice in one literal, and the second would silently replace\n * the first: turning the lint on would turn the map off, with no error anywhere. It is\n * the shape of bug this file exists to refuse, one layer up from the config it writes.\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_ON_START_ARGS} --budget ${String(ctx.budgetBytes)} --cache .smelt/tags`,\n )} 2>/dev/null || true # ${OURS_TOKEN}`;\n const lint = `${nodeCommand(\n ctx.cwd,\n smeltBinPath(),\n AGENTS_LINT_ARGS,\n )} 2>/dev/null || true # ${OURS_TOKEN}`;\n\n const sessionStart = [\n ...(ctx.mapOnStart ? [commandEntry(SESSION_START_MATCHER, map)] : []),\n ...(ctx.lintOnStart ? [commandEntry(SESSION_START_MATCHER, lint)] : []),\n ];\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 && sessionStart.length > 0 ? { [LIFECYCLE_EVENTS.map]: sessionStart } : {}),\n };\n}\n\n/** The matcher both `SessionStart` entries fire under — a session opening, however. */\nconst SESSION_START_MATCHER = 'startup|resume|clear|compact';\n\n/**\n * The two `SessionStart` commands' distinguishing arguments, and **the substrings a\n * re-run recognises each entry by**. Spelled once so the writer and the reader cannot\n * drift: `presetToggles` tells the two entries apart by the command each one runs, and\n * a wizard that wrote `agents lint .` while its reader looked for `agents lint` would\n * read every re-run's lint toggle back as off and quietly delete it.\n */\nconst MAP_ON_START_ARGS = 'map .';\nexport const AGENTS_LINT_ARGS = 'agents lint .';\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 // The style is read once, off the original: a second edit must match the first.\n const style = jsonStyle(existingText);\n let text: string | undefined = existingText;\n\n if (hooksChanged) {\n text = editTopLevelProperty(text, 'hooks', mergedHooks, style);\n /* v8 ignore next -- unreachable: JSON.parse accepted the same text above */\n if (text === undefined) return undefined;\n }\n if (needsVersion) {\n text = editTopLevelProperty(text, 'version', shape.version, style);\n /* v8 ignore next -- unreachable: every splice above keeps the text valid JSON */\n if (text === undefined) return undefined;\n }\n return text;\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 lintOnStart: 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 lintOnStart: choices.lintOnStart,\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 *\n * \"Carried verbatim\" is spelled as a spread rather than as a list of the fields to\n * copy, and that is load-bearing: the list version silently dropped every key nobody\n * remembered to add to it — `agents` was added to the schema and this function kept\n * writing configs without it, which is a setting the user believed was in force,\n * caught by `test/guards/config-writer.test.ts`. Only the two fields this verb\n * actually decides are named.\n */\nexport function renderConfigWithHooks(\n existing: SmeltConfig | undefined,\n hooks: SmeltConfigHooks,\n): string {\n return renderConfig({\n ...existing,\n smeltConfig: CONFIG_VERSION,\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 the ` +\n `harnesses whose hooks carry session events (${harnessNames(lifecycleHarnesses())}).`,\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 the harnesses whose hooks carry session events ` +\n `(${harnessNames(lifecycleHarnesses())}).`,\n choices.mapOnStart,\n (on) => {\n choices.mapOnStart = on;\n },\n ),\n async (io_, ask_) =>\n stepToggle(\n io_,\n ask_,\n 'instruction-file lint on SessionStart',\n `\\`smelt agents lint .\\` runs at session start and reports on the AGENTS.md, ` +\n `CLAUDE.md and GEMINI.md this session is about to load on every request — ` +\n `bytes per level, and any path or link in them that no longer resolves. ` +\n `Advisory: it never blocks, and it exits 0 unless you set ` +\n `agents.budgetBytes in ${CONFIG_FILE_NAME}. Wired for verified-tier ` +\n `harnesses (Claude Code, Codex).`,\n choices.lintOnStart,\n (on) => {\n choices.lintOnStart = 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 *\n * The two `SessionStart` toggles share one event, so they are told apart by **the\n * command each entry runs**, not by the key it sits under. Reading `SessionStart` as\n * one boolean would make a re-run with the map on and the lint off write both back —\n * or neither — which is a toggle the user believed they had set.\n */\nfunction presetToggles(\n cwd: string,\n): Pick<HooksChoices, 'guard' | 'statsOnStop' | 'mapOnStart' | 'lintOnStart'> {\n const defaults = { guard: true, statsOnStop: true, mapOnStart: false, lintOnStart: false };\n let anyOurs = false;\n let guard = false;\n let statsOnStop = false;\n let mapOnStart = false;\n let lintOnStart = 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 oursUnder = (event: string): readonly unknown[] =>\n Array.isArray(installed[event])\n ? (installed[event] as unknown[]).filter((entry) => isOursEntry(entry))\n : [];\n const hasOurs = (event: string): boolean => oursUnder(event).length > 0;\n /** One of ours under `event` whose command carries `needle`. */\n const hasOursRunning = (event: string, needle: string): boolean =>\n oursUnder(event).some((entry) => (JSON.stringify(entry) ?? '').includes(needle));\n if (!MANAGED_EVENTS.some((event) => hasOurs(event))) continue;\n anyOurs = true;\n guard ||= GUARD_EVENTS.some((event) => hasOurs(event));\n statsOnStop ||= hasOurs(LIFECYCLE_EVENTS.stats);\n mapOnStart ||= hasOursRunning(LIFECYCLE_EVENTS.map, MAP_ON_START_ARGS);\n lintOnStart ||= hasOursRunning(LIFECYCLE_EVENTS.lint, AGENTS_LINT_ARGS);\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, lintOnStart } : 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"]}
package/dist/cli/hooks.js CHANGED
@@ -4,9 +4,10 @@ import { dirname, join } from 'node:path';
4
4
  import { CliUsageError } from '../errors.js';
5
5
  import { nodeCommand, portablePath, shimScriptPath, smeltBinPath } from '../harness/paths.js';
6
6
  import { hasShim, TIER_HONESTY } from '../harness/profile.js';
7
- import { GUARD_EVENTS, GUARD_ONLY_FILES, HARNESSES, harnessById, JSON_HOOK_FILES, LIFECYCLE_EVENTS, MANAGED_EVENTS, } from '../harness/registry.js';
7
+ import { GUARD_EVENTS, GUARD_ONLY_FILES, HARNESSES, harnessById, harnessNames, JSON_HOOK_FILES, LIFECYCLE_EVENTS, lifecycleHarnesses, MANAGED_EVENTS, } from '../harness/registry.js';
8
8
  import { instructionSnippet, OURS_TOKEN, SNIPPET_END_MD, SNIPPET_START_MD, } from '../harness/snippet.js';
9
9
  import { DEFAULT_SUGGESTION_BUDGET_BYTES, DEFAULT_THRESHOLD_BYTES } from '../hooks/guard-core.js';
10
+ import { editTopLevelProperty, jsonStyle, stripMarkerBlock, upsertMarkerBlock, } from '../text/json-edit.js';
10
11
  import { answerReader, CLI_NAME } from './shell.js';
11
12
  import { CONFIG_FILE_NAME, CONFIG_VERSION, findConfigFile, parseConfig, renderConfig, } from './config.js';
12
13
  export { instructionSnippet, SNIPPET_END_MD, SNIPPET_START_MD };
@@ -40,15 +41,26 @@ function shimCommand(profile, cwd) {
40
41
  }
41
42
  /**
42
43
  * One harness's hook entries: the guard under each matcher its schema spells, plus
43
- * the two session-lifecycle hooks for the harnesses whose schema carries them. Every
44
+ * the session-lifecycle hooks for the harnesses whose schema carries them. Every
44
45
  * toggle the wizard offers is a key that is present or absent here — an absent key is
45
46
  * how a re-run turns a toggle *off*, because the merge deletes what it no longer sees.
47
+ *
48
+ * The two `SessionStart` toggles — the opening map and the instruction-file lint —
49
+ * are **concatenated into one array**, not spread as two objects. Spreading would put
50
+ * the same computed key twice in one literal, and the second would silently replace
51
+ * the first: turning the lint on would turn the map off, with no error anywhere. It is
52
+ * the shape of bug this file exists to refuse, one layer up from the config it writes.
46
53
  */
47
54
  function jsonHookEvents(step, ctx, command) {
48
55
  // The trailing shell comment tags the entry as this installer's (see isOursEntry):
49
56
  // a bare `cli/bin.js` substring would also match some other npm CLI's built binary.
50
57
  const stats = `${nodeCommand(ctx.cwd, smeltBinPath(), 'stats')} 2>/dev/null || true # ${OURS_TOKEN}`;
51
- const map = `${nodeCommand(ctx.cwd, smeltBinPath(), `map . --budget ${String(ctx.budgetBytes)} --cache .smelt/tags`)} 2>/dev/null || true # ${OURS_TOKEN}`;
58
+ const map = `${nodeCommand(ctx.cwd, smeltBinPath(), `${MAP_ON_START_ARGS} --budget ${String(ctx.budgetBytes)} --cache .smelt/tags`)} 2>/dev/null || true # ${OURS_TOKEN}`;
59
+ const lint = `${nodeCommand(ctx.cwd, smeltBinPath(), AGENTS_LINT_ARGS)} 2>/dev/null || true # ${OURS_TOKEN}`;
60
+ const sessionStart = [
61
+ ...(ctx.mapOnStart ? [commandEntry(SESSION_START_MATCHER, map)] : []),
62
+ ...(ctx.lintOnStart ? [commandEntry(SESSION_START_MATCHER, lint)] : []),
63
+ ];
52
64
  return {
53
65
  ...(ctx.guard
54
66
  ? {
@@ -58,11 +70,20 @@ function jsonHookEvents(step, ctx, command) {
58
70
  ...(step.lifecycle && ctx.statsOnStop
59
71
  ? { [LIFECYCLE_EVENTS.stats]: [commandEntry(undefined, stats)] }
60
72
  : {}),
61
- ...(step.lifecycle && ctx.mapOnStart
62
- ? { [LIFECYCLE_EVENTS.map]: [commandEntry('startup|resume|clear|compact', map)] }
63
- : {}),
73
+ ...(step.lifecycle && sessionStart.length > 0 ? { [LIFECYCLE_EVENTS.map]: sessionStart } : {}),
64
74
  };
65
75
  }
76
+ /** The matcher both `SessionStart` entries fire under — a session opening, however. */
77
+ const SESSION_START_MATCHER = 'startup|resume|clear|compact';
78
+ /**
79
+ * The two `SessionStart` commands' distinguishing arguments, and **the substrings a
80
+ * re-run recognises each entry by**. Spelled once so the writer and the reader cannot
81
+ * drift: `presetToggles` tells the two entries apart by the command each one runs, and
82
+ * a wizard that wrote `agents lint .` while its reader looked for `agents lint` would
83
+ * read every re-run's lint toggle back as off and quietly delete it.
84
+ */
85
+ const MAP_ON_START_ARGS = 'map .';
86
+ export const AGENTS_LINT_ARGS = 'agents lint .';
66
87
  /**
67
88
  * True for a hook entry this installer wrote. Matched on the shim script paths and the
68
89
  * `smelt:hooks` token the stats/map commands carry — never on a substring as generic
@@ -128,176 +149,23 @@ export function mergeJsonHooks(existingText, events, shape = {}) {
128
149
  const needsVersion = shape.version !== undefined && root['version'] === undefined;
129
150
  if (!hooksChanged && !needsVersion)
130
151
  return existingText;
131
- const newline = existingText.includes('\r\n') ? '\r\n' : '\n';
132
- const indent = /\n([ \t]+)"/.exec(existingText)?.[1] ?? ' ';
152
+ // The style is read once, off the original: a second edit must match the first.
153
+ const style = jsonStyle(existingText);
133
154
  let text = existingText;
134
155
  if (hooksChanged) {
135
- const scan = scanJsonTopLevel(text);
156
+ text = editTopLevelProperty(text, 'hooks', mergedHooks, style);
136
157
  /* v8 ignore next -- unreachable: JSON.parse accepted the same text above */
137
- if (scan === undefined)
158
+ if (text === undefined)
138
159
  return undefined;
139
- const property = scan.properties.find((candidate) => candidate.key === 'hooks');
140
- if (mergedHooks === undefined) {
141
- if (property !== undefined)
142
- text = removeJsonProperty(text, scan, property);
143
- }
144
- else {
145
- const rendered = renderJsonValue(mergedHooks, indent, newline);
146
- text =
147
- property !== undefined
148
- ? `${text.slice(0, property.valueStart)}${rendered}${text.slice(property.valueEnd)}`
149
- : insertJsonProperty(text, scan, 'hooks', rendered, indent, newline);
150
- }
151
160
  }
152
161
  if (needsVersion) {
153
- const scan = scanJsonTopLevel(text);
162
+ text = editTopLevelProperty(text, 'version', shape.version, style);
154
163
  /* v8 ignore next -- unreachable: every splice above keeps the text valid JSON */
155
- if (scan === undefined)
164
+ if (text === undefined)
156
165
  return undefined;
157
- text = insertJsonProperty(text, scan, 'version', JSON.stringify(shape.version), indent, newline);
158
166
  }
159
167
  return text;
160
168
  }
161
- /**
162
- * Locate the top-level properties of a JSON object *in its source text*, so one
163
- * property can be replaced, inserted or removed while every other byte of the file
164
- * rides through verbatim. `undefined` when the text is not an object — callers have
165
- * already `JSON.parse`d it, so that is belt and braces, not a validator.
166
- */
167
- function scanJsonTopLevel(text) {
168
- let i = skipJsonWhitespace(text, 0);
169
- if (text[i] !== '{')
170
- return undefined;
171
- const open = i;
172
- i = skipJsonWhitespace(text, i + 1);
173
- const properties = [];
174
- if (text[i] === '}')
175
- return { open, close: i, properties };
176
- for (;;) {
177
- if (text[i] !== '"')
178
- return undefined;
179
- const keyStart = i;
180
- const keyEnd = skipJsonString(text, i);
181
- if (keyEnd === undefined)
182
- return undefined;
183
- const key = JSON.parse(text.slice(keyStart, keyEnd));
184
- i = skipJsonWhitespace(text, keyEnd);
185
- if (text[i] !== ':')
186
- return undefined;
187
- const valueStart = skipJsonWhitespace(text, i + 1);
188
- const valueEnd = skipJsonValue(text, valueStart);
189
- if (valueEnd === undefined)
190
- return undefined;
191
- properties.push({ key, keyStart, valueStart, valueEnd });
192
- i = skipJsonWhitespace(text, valueEnd);
193
- if (text[i] === ',') {
194
- i = skipJsonWhitespace(text, i + 1);
195
- continue;
196
- }
197
- if (text[i] === '}')
198
- return { open, close: i, properties };
199
- return undefined;
200
- }
201
- }
202
- function skipJsonWhitespace(text, from) {
203
- let i = from;
204
- while (i < text.length && ' \t\r\n'.includes(text[i]))
205
- i += 1;
206
- return i;
207
- }
208
- /** `from` points at `"`; returns the offset one past the closing quote. */
209
- function skipJsonString(text, from) {
210
- let i = from + 1;
211
- while (i < text.length) {
212
- if (text[i] === '\\')
213
- i += 2;
214
- else if (text[i] === '"')
215
- return i + 1;
216
- else
217
- i += 1;
218
- }
219
- return undefined;
220
- }
221
- function skipJsonValue(text, from) {
222
- const first = text[from];
223
- if (first === '"')
224
- return skipJsonString(text, from);
225
- if (first === '{' || first === '[') {
226
- let depth = 0;
227
- let i = from;
228
- while (i < text.length) {
229
- const ch = text[i];
230
- if (ch === '"') {
231
- const end = skipJsonString(text, i);
232
- if (end === undefined)
233
- return undefined;
234
- i = end;
235
- continue;
236
- }
237
- if (ch === '{' || ch === '[')
238
- depth += 1;
239
- else if (ch === '}' || ch === ']') {
240
- depth -= 1;
241
- if (depth === 0)
242
- return i + 1;
243
- }
244
- i += 1;
245
- }
246
- return undefined;
247
- }
248
- // number / true / false / null
249
- let i = from;
250
- while (i < text.length && !',}] \t\r\n'.includes(text[i]))
251
- i += 1;
252
- return i > from ? i : undefined;
253
- }
254
- /** A JSON value indented for embedding at a top-level property position. */
255
- function renderJsonValue(value, indent, newline) {
256
- return JSON.stringify(value, null, indent).split('\n').join(`${newline}${indent}`);
257
- }
258
- function removeJsonProperty(text, scan, property) {
259
- const index = scan.properties.indexOf(property);
260
- const next = scan.properties[index + 1];
261
- if (next !== undefined) {
262
- // Delete through the separating comma and whitespace, up to the next key.
263
- return text.slice(0, property.keyStart) + text.slice(next.keyStart);
264
- }
265
- const previous = scan.properties[index - 1];
266
- // Last (or only) property: delete the preceding comma (if any) with it.
267
- const from = previous !== undefined ? previous.valueEnd : scan.open + 1;
268
- return text.slice(0, from) + text.slice(property.valueEnd);
269
- }
270
- function insertJsonProperty(text, scan, key, renderedValue, indent, newline) {
271
- const entry = `${JSON.stringify(key)}: ${renderedValue}`;
272
- if (scan.properties.length === 0) {
273
- return `${text.slice(0, scan.open + 1)}${newline}${indent}${entry}${newline}${text.slice(scan.close)}`;
274
- }
275
- const last = scan.properties[scan.properties.length - 1];
276
- return `${text.slice(0, last.valueEnd)},${newline}${indent}${entry}${text.slice(last.valueEnd)}`;
277
- }
278
- /** Replace this installer's marker block in `existingText`, or append it. */
279
- export function upsertMarkerBlock(existingText, block, start, end) {
280
- if (existingText === undefined || existingText.trim() === '')
281
- return block;
282
- const startIndex = existingText.indexOf(start);
283
- const endIndex = existingText.indexOf(end);
284
- if (startIndex !== -1 && endIndex !== -1 && endIndex > startIndex) {
285
- const before = existingText.slice(0, startIndex);
286
- const after = existingText.slice(endIndex + end.length).replace(/^\n/, '');
287
- return `${before}${block}${after}`;
288
- }
289
- return `${existingText.replace(/\n*$/, '\n\n')}${block}`;
290
- }
291
- /** Remove the marker block. `undefined` when nothing (or only whitespace) remains. */
292
- export function stripMarkerBlock(existingText, start, end) {
293
- const startIndex = existingText.indexOf(start);
294
- const endIndex = existingText.indexOf(end);
295
- if (startIndex === -1 || endIndex === -1 || endIndex <= startIndex)
296
- return existingText;
297
- const stripped = existingText.slice(0, startIndex).replace(/\n+$/, '\n') +
298
- existingText.slice(endIndex + end.length).replace(/^\n+/, '');
299
- return stripped.trim() === '' ? undefined : stripped;
300
- }
301
169
  function planFile(cwd, name, content, mode) {
302
170
  const path = join(cwd, name);
303
171
  const exists = existsSync(path);
@@ -344,6 +212,7 @@ export function planInstall(cwd, choices) {
344
212
  guard: choices.guard,
345
213
  statsOnStop: choices.statsOnStop,
346
214
  mapOnStart: choices.mapOnStart,
215
+ lintOnStart: choices.lintOnStart,
347
216
  thresholdBytes: choices.thresholdBytes,
348
217
  budgetBytes,
349
218
  };
@@ -421,14 +290,18 @@ export const DEFAULT_STORE_DIR = '.smelt/store';
421
290
  * That store injection is this verb's **policy**, which is why it lives here; the
422
291
  * bytes are written by `renderConfig` in `config.ts`, the one writer, so a key added
423
292
  * to the schema reaches this file and `init`'s together or not at all.
293
+ *
294
+ * "Carried verbatim" is spelled as a spread rather than as a list of the fields to
295
+ * copy, and that is load-bearing: the list version silently dropped every key nobody
296
+ * remembered to add to it — `agents` was added to the schema and this function kept
297
+ * writing configs without it, which is a setting the user believed was in force,
298
+ * caught by `test/guards/config-writer.test.ts`. Only the two fields this verb
299
+ * actually decides are named.
424
300
  */
425
301
  export function renderConfigWithHooks(existing, hooks) {
426
302
  return renderConfig({
303
+ ...existing,
427
304
  smeltConfig: CONFIG_VERSION,
428
- ...(existing?.defaultBudgetBytes === undefined
429
- ? {}
430
- : { defaultBudgetBytes: existing.defaultBudgetBytes }),
431
- ...(existing?.strategy === undefined ? {} : { strategy: existing.strategy }),
432
305
  store: existing?.store ?? { kind: 'directory', path: DEFAULT_STORE_DIR },
433
306
  hooks,
434
307
  });
@@ -558,15 +431,24 @@ async function installFlow(io, ask, harnessFlag) {
558
431
  choices.guard = on;
559
432
  }),
560
433
  async (io_, ask_) => stepToggle(io_, ask_, 'stats on Stop', `\`smelt stats\` runs when a session ends — the honest signal (expansion rate) ` +
561
- `surfaced where the turn ends. Observation only; never blocks. Wired for ` +
562
- `verified-tier harnesses (Claude Code, Codex).`, choices.statsOnStop, (on) => {
434
+ `surfaced where the turn ends. Observation only; never blocks. Wired for the ` +
435
+ `harnesses whose hooks carry session events (${harnessNames(lifecycleHarnesses())}).`, choices.statsOnStop, (on) => {
563
436
  choices.statsOnStop = on;
564
437
  }),
565
438
  async (io_, ask_) => stepToggle(io_, ask_, 'repo map on SessionStart', `\`smelt map . --budget …\` runs at session start and its output opens the ` +
566
439
  `context — the agent starts oriented. Costs one map build per session. ` +
567
- `Wired for verified-tier harnesses (Claude Code, Codex).`, choices.mapOnStart, (on) => {
440
+ `Wired for the harnesses whose hooks carry session events ` +
441
+ `(${harnessNames(lifecycleHarnesses())}).`, choices.mapOnStart, (on) => {
568
442
  choices.mapOnStart = on;
569
443
  }),
444
+ async (io_, ask_) => stepToggle(io_, ask_, 'instruction-file lint on SessionStart', `\`smelt agents lint .\` runs at session start and reports on the AGENTS.md, ` +
445
+ `CLAUDE.md and GEMINI.md this session is about to load on every request — ` +
446
+ `bytes per level, and any path or link in them that no longer resolves. ` +
447
+ `Advisory: it never blocks, and it exits 0 unless you set ` +
448
+ `agents.budgetBytes in ${CONFIG_FILE_NAME}. Wired for verified-tier ` +
449
+ `harnesses (Claude Code, Codex).`, choices.lintOnStart, (on) => {
450
+ choices.lintOnStart = on;
451
+ }),
570
452
  async (io_, ask_) => stepEnforcement(io_, ask_, choices),
571
453
  async (io_, ask_) => stepThreshold(io_, ask_, choices),
572
454
  ];
@@ -695,13 +577,19 @@ async function stepThreshold(io, ask, choices) {
695
577
  * (gemini, grok, cursor, hermes, opencode, cline) persist no stats/map entries, so
696
578
  * after a re-run scoped to them those toggles read back as off; the defaults below
697
579
  * apply only when nothing of smelt's is installed at all.
580
+ *
581
+ * The two `SessionStart` toggles share one event, so they are told apart by **the
582
+ * command each entry runs**, not by the key it sits under. Reading `SessionStart` as
583
+ * one boolean would make a re-run with the map on and the lint off write both back —
584
+ * or neither — which is a toggle the user believed they had set.
698
585
  */
699
586
  function presetToggles(cwd) {
700
- const defaults = { guard: true, statsOnStop: true, mapOnStart: false };
587
+ const defaults = { guard: true, statsOnStop: true, mapOnStart: false, lintOnStart: false };
701
588
  let anyOurs = false;
702
589
  let guard = false;
703
590
  let statsOnStop = false;
704
591
  let mapOnStart = false;
592
+ let lintOnStart = false;
705
593
  for (const name of JSON_HOOK_FILES) {
706
594
  const text = readIfExists(join(cwd, name));
707
595
  if (text === undefined)
@@ -723,14 +611,19 @@ function presetToggles(cwd) {
723
611
  if (hooks === undefined)
724
612
  continue;
725
613
  const installed = hooks;
726
- const hasOurs = (event) => Array.isArray(installed[event]) &&
727
- installed[event].some((entry) => isOursEntry(entry));
614
+ const oursUnder = (event) => Array.isArray(installed[event])
615
+ ? installed[event].filter((entry) => isOursEntry(entry))
616
+ : [];
617
+ const hasOurs = (event) => oursUnder(event).length > 0;
618
+ /** One of ours under `event` whose command carries `needle`. */
619
+ const hasOursRunning = (event, needle) => oursUnder(event).some((entry) => (JSON.stringify(entry) ?? '').includes(needle));
728
620
  if (!MANAGED_EVENTS.some((event) => hasOurs(event)))
729
621
  continue;
730
622
  anyOurs = true;
731
623
  guard ||= GUARD_EVENTS.some((event) => hasOurs(event));
732
- statsOnStop ||= hasOurs('Stop');
733
- mapOnStart ||= hasOurs('SessionStart');
624
+ statsOnStop ||= hasOurs(LIFECYCLE_EVENTS.stats);
625
+ mapOnStart ||= hasOursRunning(LIFECYCLE_EVENTS.map, MAP_ON_START_ARGS);
626
+ lintOnStart ||= hasOursRunning(LIFECYCLE_EVENTS.lint, AGENTS_LINT_ARGS);
734
627
  }
735
628
  for (const name of GUARD_ONLY_FILES) {
736
629
  const text = readIfExists(join(cwd, name));
@@ -739,7 +632,7 @@ function presetToggles(cwd) {
739
632
  guard = true;
740
633
  }
741
634
  }
742
- return anyOurs ? { guard, statsOnStop, mapOnStart } : defaults;
635
+ return anyOurs ? { guard, statsOnStop, mapOnStart, lintOnStart } : defaults;
743
636
  }
744
637
  const fileLabel = (file) => {
745
638
  if (file.unchanged)