Repository navigation
Expand file tree
/
Copy pathinstall.ts
More file actions
725 lines (642 loc) · 51.6 KB
/
Copy pathinstall.ts
File metadata and controls
725 lines (642 loc) · 51.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
/** Install / uninstall token-goat's hooks in Claude Code settings. Ports the `patch_settings_json` / `unpatch_settings_json` slice of `install.py` to TypeScript. Claude Code reads hook wiring from `~/.claude/settings.json` (user scope) or `<project>/.claude/settings.json` (project scope). Each token-goat hook is a `{ type: "command", command: ... }` entry under the matching event key, where the command invokes the generated shim at {@link claudeHookScriptPath} via {@link hookCommandFor} — `"<node>" "<shim>" <event> "<entry>"`. Going through the shim rather than the bare `token-goat hook <event>` PATH lookup buys two things: the shim's in-process fast path imports `dist/token-goat-hook.mjs` and calls `relayInProcess` directly instead of spawning a second process, and naming the node binary explicitly skips the npm bin wrapper (on Windows, a `cmd.exe` layer) that a PATH lookup would pay for on every single hook. Measured at ~480ms → ~324ms per invocation. Writes go through {@link atomicWriteText}; an absent settings file is created with only the hooks section. Installation is idempotent — re-running never duplicates an entry — and uninstall removes only token-goat's own entries plus the generated shim, leaving any user-authored hooks intact. */
import * as fs from 'node:fs'
import * as path from 'node:path'
import { CLAUDECODE_HOOK_SCRIPT } from './bridges/claudecode.js'
import { LEGACY_SHIM_FILE, SHIM_FILE, legacyShimForwarder } from './bridges/shim_common.js'
import { buildGuidanceBlock } from './bridges/guidance_block.js'
import { CANONICAL_SKILL_MD } from './canonical_skill.js'
import { claudeConfigDir } from './claude_config_dir.js'
import { compareSemver } from './cli_upgrade.js'
import { loadConfig } from './config.js'
import { nativeHookBinary, nativeHookCommandLine, nativeHookExecParts, parseNativeInvocation, splitHookCommand } from './native_hook.js'
import { toolMatcherFor } from './hook_registry.js'
import { normalizeDarwinSystemAlias } from './paths.js'
import { resolveOnPath, spawnResolvedSync } from './process_util.js'
import type { HookEventName } from './types.js'
import { ensureDirRecordingCreation, recordCreatedBy, recordCreatedConfig, removeCreatedBackups, removeCreatedIfEmpty, removeCreatedTree } from './bridges/created_configs.js'
import { assertWriteInScope, withInstallScope } from './bridges/project_scope_guard.js'
import { atomicWriteText, backupFile, ensureDirSync, escapeRegExp, extractErrorMessage, hookCommandFor, hookExecPartsFor, removeFileInScope, stripDelimitedBlock, stripOwnHooksFromMap, upsertDelimitedBlock, writeIfDifferent, writeJsonSettings } from './util.js'
import { commandHookFields, isOwnHookEntry } from './util_config.js'
import { stripBom } from './jsonc_text.js'
import { echoedValue } from './hint_suggestion_guard.js'
/** Where to install: the user's home `~/.claude` or the project's `.claude`. */
export type HookScope = 'user' | 'project'
/** Outcome of an {@link installHooks} call. */
export interface InstallResult {
/** Scope the hooks were written to. */
readonly scope: HookScope
/** Absolute path to the settings file that was written. */
readonly settingsPath: string
/** True when every token-goat hook was already present (no write needed). */
readonly alreadyInstalled: boolean
/** Event keys left untouched because the file holds a non-list value there. */
readonly skippedEvents?: readonly string[]
}
/** Claude Code event names token-goat wires, mapped to their internal event arg. The settings key is Claude Code's PascalCase event name; the value is the arg passed to `token-goat hook <event>`, matching the internal HookEventName spellings the relay dispatches on. */
const HOOK_EVENT_MAP: ReadonlyArray<readonly [string, string]> = [
['PreToolUse', 'pre_tool_use'],
['PostToolUse', 'post_tool_use'],
// A failed call never reaches PostToolUse: Claude Code 2.1.281 sends a missing-file Read and a non-zero Bash exit here instead, carrying `error`, `is_interrupt` and `duration_ms` (captured, 2026-09-24).
['PostToolUseFailure', 'post_tool_use_failure'],
['PreCompact', 'pre_compact'],
['PostCompact', 'post_compact'],
['UserPromptSubmit', 'user_prompt_submit'],
['Stop', 'stop'],
['SubagentStop', 'subagent_stop'],
['SessionStart', 'session_start'],
]
/** Marker substring identifying the CURRENT, shim-based hook command. Deliberately `token-goat-shim` and not `token-goat-hook`: the latter is reserved in {@link LEGACY_COMMAND_MARKERS} for the dead Python-era exe wrapper, so a shim path carrying it would be classified as stale cruft and stripped on every single reinstall -- silently reverting the wiring it had just applied. `bridges/codex_install.ts` hit and solved this exact collision first (`CODEX_COMMAND_MARKER`); this is the same solution ported to the base Claude Code path. */
const SHIM_COMMAND_MARKER = 'token-goat-shim'
/** Marker substring identifying the pre-shim `token-goat hook <event>` command. */
const COMMAND_MARKER = 'token-goat hook'
/** Command substrings from earlier product eras that must still be recognized as token-goat's own, so an upgrade doesn't leave a dead duplicate behind: - `tokenwise` — the pre-rename product name (2026-05-13 rename to token-goat). - `token_goat` — the pre-TS-port Python invocation (`pythonw -m token_goat.cli hook ...`). - `tg-hook` — the Python-era persistent wrapper script (`tg-hook.cmd` / `tg-hook.sh`). - `token-goat-hook` — the Python-era GUI-subsystem exe wrapper (`token-goat-hook.exe`). None of these resolve on a machine running the current build, so a settings.json entry carrying one is always a stale leftover to detect and strip, never a legitimately different install to leave alone. */
const LEGACY_COMMAND_MARKERS = ['tokenwise', 'token_goat', 'tg-hook', 'token-goat-hook']
/** Builds a regex that matches `marker` only at a word/path boundary, so a plain substring check can't false-positive on a marker embedded inside a longer identifier (e.g. a user hook literally named `my-token-goat-hook-config`). */
export function anchoredMarkerPattern(marker: string): RegExp {
const escaped = escapeRegExp(marker)
return new RegExp(`(?<![a-zA-Z0-9_-])${escaped}(?![a-zA-Z0-9_-])`)
}
const HOOK_MARKER_PATTERNS = [SHIM_COMMAND_MARKER, COMMAND_MARKER, ...LEGACY_COMMAND_MARKERS].map(anchoredMarkerPattern)
/** True when `command`/`args` is any token-goat hook invocation: current shim (string- or exec-form), pre-shim, or legacy alias. Exec-form carries the shim path in `args` rather than `command`, so both are joined before testing the markers. */
function isTokenGoatHookCommand(command: string, args?: readonly string[]): boolean {
const haystack = args !== undefined && args.length > 0 ? `${command} ${args.join(' ')}` : command
return HOOK_MARKER_PATTERNS.some((pattern) => pattern.test(haystack))
}
/** Minimum Claude Code version whose hook schema accepts the `args` array (exec form). Below this the key is unknown and a hook carrying it may be ignored outright -- disabling token-goat silently -- so any probe failure below falls back to string form. */
const CLAUDE_EXEC_FORM_MIN_VERSION = '2.1.139'
let _claudeExecFormHooksSupported: boolean | undefined
/** True when the installed `claude` binary is new enough to accept exec-form hooks ({@link CLAUDE_EXEC_FORM_MIN_VERSION}). Probed via `claude --version` and cached for the life of the process -- so an install run that writes many event keys shells out at most once, not once per hook. `TOKEN_GOAT_CLAUDE_EXEC_FORM_HOOKS` (`'1'`/`'0'`) overrides the probe entirely, for tests and for a user working around a bad detection. */
export function claudeExecFormHooksSupported(): boolean {
const override = process.env['TOKEN_GOAT_CLAUDE_EXEC_FORM_HOOKS']
if (override === '1') return true
if (override === '0') return false
if (_claudeExecFormHooksSupported !== undefined) return _claudeExecFormHooksSupported
_claudeExecFormHooksSupported = probeClaudeExecFormHooksSupported()
return _claudeExecFormHooksSupported
}
/** The actual probe behind {@link claudeExecFormHooksSupported}: absent binary, a spawn error, a non-zero exit, or unparsable output all fall back to `false` (string form) rather than risk registering a hook the running Claude Code might silently drop. Runs the binary as cli_doctor.ts's checkInstall does, through spawnResolvedSync, since a global npm install puts a `.cmd` shim on PATH that Node refuses to spawn directly. */
function probeClaudeExecFormHooksSupported(): boolean {
const resolved = resolveOnPath('claude')
if (resolved === null) return false
try {
const result = spawnResolvedSync(resolved, ['--version'], { encoding: 'utf-8', timeout: 5000, windowsHide: true })
if (result.status !== 0) return false
return execFormSupportedForVersionOutput(result.stdout ?? '')
} catch {
return false
}
}
/** The version decision inside {@link probeClaudeExecFormHooksSupported}, split out so it is testable without a `claude` binary on PATH: the spawn plumbing around it can only be exercised by a real install, but the parse and the comparison are where a silent wrong answer would come from. Output with no `x.y.z` in it is unparsable and answers false, so an unrecognised future format falls back to string form rather than guessing. */
export function execFormSupportedForVersionOutput(stdout: string): boolean {
const m = /(\d+\.\d+\.\d+)/.exec(stdout)
if (!m) return false
return compareSemver(m[1]!, CLAUDE_EXEC_FORM_MIN_VERSION) >= 0
}
/** The hook entry this build wires for `event`: exec-form when {@link claudeExecFormHooksSupported}, string-form otherwise, each with the native client in front of the Node command when {@link nativeHookBinary} names one. The native string form is quoted for a POSIX shell on every platform: Claude Code runs a string-form hook through Git Bash on Windows and /bin/sh elsewhere. */
export function expectedHookEntryFor(scriptPath: string, event: string, opts: { sync?: boolean } = {}): { command: string; args?: string[] } {
const bin = nativeHookBinary(process.argv[1], opts)
if (claudeExecFormHooksSupported()) return (bin === undefined ? undefined : nativeHookExecParts(bin, 'claudecode', scriptPath, event)) ?? hookExecPartsFor(scriptPath, event)
return { command: (bin === undefined ? undefined : nativeHookCommandLine('sh', bin, 'claudecode', scriptPath, event)) ?? hookCommandFor(scriptPath, event) }
}
/** The real location of an absolute path that exists, else null. Relative words (an event name) and missing paths compare by spelling alone. */
function realPathOrNull(p: string): string | null {
if (!path.isAbsolute(p)) return null
try {
return fs.realpathSync.native(p)
} catch {
return null
}
}
/** Two argv words name the same thing: the same spelling, or two spellings of one file that exists. The bundle path in a hook comes from `process.argv[1]` of whichever process ran `install`, so a global npm install reached through a symlink or `npm link` writes one spelling and a `doctor` launched the other way expects the other, while both run the same file. */
function sameHookWord(a: string, b: string): boolean {
if (a === b) return true
const realA = realPathOrNull(a)
return realA !== null && realA === realPathOrNull(b)
}
/** The words of a string-form hook command, in the quoting token-goat writes: {@link hookCommandFor}'s double quotes (backslash-escaped off Windows) and the native form's POSIX single quotes. */
function stringFormHookWords(command: string): string[] {
return splitHookCommand(command, 'sh')
}
/** True when `command`/`args` is the hook `expected` describes -- the same words in the same order, never `command` alone: an exec-form entry's `command` is just `"node"`, shared by every event and by a stale entry whose `args` point at a deleted shim. A path word matches another spelling of the same existing file (see {@link sameHookWord}); a string-form entry never matches an exec-form expectation or the reverse, so `install` still upgrades one to the other. */
function hookEntryMatches(command: string, args: readonly string[] | undefined, expected: { command: string; args?: string[] }): boolean {
const execForm = expected.args !== undefined
if (!execForm && args !== undefined && args.length > 0) return false
const a = execForm ? [command, ...(args ?? [])] : stringFormHookWords(command)
const b = execForm ? [expected.command, ...expected.args!] : stringFormHookWords(expected.command)
return a.length === b.length && a.every((v, i) => sameHookWord(v, b[i]!))
}
/** Absolute path to the generated Claude Code hook shim. Always under the user's home `~/.claude/hooks`, never the project's, even for a project-scope install: the shim is a generated file whose invocation bakes in absolute machine-specific paths (this node binary, this token-goat entry), so a copy inside a repo would be both useless to a teammate and an unexpected generated artifact in their working tree. A project-scope `settings.json` simply points at the home-scoped shim by absolute path. */
export function claudeHookScriptPath(): string {
return path.join(claudeConfigDir(), 'hooks', SHIM_FILE)
}
/** The shim's pre-`.cjs` path, now a forwarder to it (see {@link LEGACY_SHIM_FILE}). */
function claudeLegacyHookScriptPath(): string {
return path.join(claudeConfigDir(), 'hooks', LEGACY_SHIM_FILE)
}
/** Does any installed scope still wire a hook command pointing at one of `scriptPaths`, the shim and the forwarder at its old `.js` path, which a scope wired by an earlier install still runs and which needs the shim beside it? Both scopes share the single home-scoped shim, so uninstalling one must not delete the file the other still depends on. `alreadyStripped` is the in-memory hooks map of the scope currently being uninstalled, passed in because its entries have already been removed there but not yet written to disk -- re-reading that file would see the stale pre-strip content and always report the shim as still needed. */
function anyScopeReferencesShim(
scriptPaths: readonly string[],
currentScope: HookScope,
alreadyStripped: Record<string, HookMatcherGroup[]>,
): boolean {
const referencesIn = (map: Record<string, HookMatcherGroup[]> | undefined): boolean => {
for (const groups of Object.values(map ?? {})) {
for (const group of Array.isArray(groups) ? groups : []) {
for (const h of hooksOf(group)) {
// Exec form carries the shim path in `args`, not `command` (which is just the node binary).
const fields = commandHookFields(h)
if (fields !== undefined && scriptPaths.some((p) => fields.command.includes(p) || (fields.args ?? []).some((a) => a.includes(p)))) return true
}
}
}
return false
}
// The scope being uninstalled is judged from the in-memory post-strip map only: its file on disk still holds the pre-strip entries, so re-reading it here would always find the shim "still referenced" and no uninstall would ever remove it.
if (referencesIn(alreadyStripped)) return true
for (const scope of ['user', 'project'] as const) {
if (scope === currentScope) continue
let other: Settings
try {
other = readSettings(settingsPath(scope), { strict: true })
} catch (e) {
// A scope whose settings file is there but cannot be read or parsed may still name the shim, so it keeps it: deleting the shim leaves every hook such a file wires erroring on every tool call once the file is fixed, where keeping it leaves one generated file behind. Either way this uninstall goes on rather than abort on someone else's broken JSON.
if (e instanceof SettingsParseError) return true
throw e
}
// A scope with no settings file names nothing.
if (referencesIn(other.hooks)) return true
}
return false
}
/** Return the `~/.claude` (or `$CLAUDE_CONFIG_DIR`) or `<cwd>/.claude` settings path for `scope`. */
export function settingsPath(scope: HookScope): string {
// User scope resolves through claudeConfigDir() because that is where Claude Code reads its user settings.json from; project scope stays relative to the cwd, which Claude Code resolves independently of the config home. Only fix the macOS /var vs /private/var alias split (os.tmpdir() vs process.cwd() disagree on this after chdir) — not the full resolveIndexPath pipeline, whose unconditional drive-letter lowercasing would otherwise leak into this user-visible, printed-to-the-console path on Windows.
const base = scope === 'user' ? claudeConfigDir() : path.join(normalizeDarwinSystemAlias(process.cwd()), '.claude')
return path.join(base, 'settings.json')
}
/** A single hook command entry as Claude Code stores it. */
interface HookCommandEntry {
type: string
/** Absent on Claude Code's `prompt`, `agent`, `http` and `mcp_tool` hooks, which run no command; read it through {@link commandHookFields}. */
command?: unknown
/** Exec-form argv (Claude Code >= {@link CLAUDE_EXEC_FORM_MIN_VERSION}). Absent for a string-form entry. */
args?: unknown
}
/** A matcher group: an optional matcher plus the list of hook commands. */
interface HookMatcherGroup {
matcher?: string
hooks?: HookCommandEntry[]
}
/** The settings shape we read/write; unknown keys are preserved verbatim. */
interface Settings {
hooks?: Record<string, HookMatcherGroup[]>
[key: string]: unknown
}
/** Thrown by {@link readSettings} in strict mode when the settings file exists but cannot be read, isn't parseable JSON, or parses to something other than a JSON object. A caller about to overwrite the file (installHooks) or strip it (uninstallHooks) must let this propagate rather than silently proceeding as if the file were empty -- otherwise a single JSON typo in the user's settings.json gets clobbered on write, or the shim its hooks still run is deleted from under them. */
export class SettingsParseError extends Error {}
/** Parse the settings file at `p`. A missing file always yields `{}` -- that's the legitimate "nothing installed yet" case. When `opts.strict` is true, a file that *exists* but cannot be read, fails to parse, or parses to something other than a JSON object throws {@link SettingsParseError} instead of returning `{}`, so a caller about to overwrite or strip the file can tell "genuinely empty" apart from "corrupt, do not touch"; `opts.command` names the command the message tells the user to run again. Non-strict callers (read-only, or a no-op on corrupt) keep the old lenient `{}` fallback. */
function readSettings(p: string, opts: { strict?: boolean; command?: 'install' | 'uninstall' } = {}): Settings {
// Worded for the command that stopped: install has written nothing yet, and uninstall has removed nothing, neither the shim this file's hooks may run nor the file's backups.
const refuse = (problem: string, detail?: string): SettingsParseError =>
new SettingsParseError(
(opts.command === 'uninstall'
? `settings file ${echoedValue(p)} is unreadable: it ${problem}. Uninstall left it untouched, along with the hook shim it may still name and the file's backups; fix the file and run uninstall again.`
: `settings file ${echoedValue(p)} ${problem}. Fix or back up the file before running install.`) + (detail === undefined ? '' : ` (${detail})`),
)
let raw: string
try {
raw = fs.readFileSync(p, 'utf8')
} catch (e) {
const code = (e as NodeJS.ErrnoException).code
// Only an absent file is the "nothing installed yet" case. One that is there but cannot be read (a directory, a permission, another process's lock) is refused in strict mode like one that does not parse: read as empty, install went on writing until backing the file up failed with a raw file-system error, and uninstall would delete the shim its hooks may run.
if (opts.strict === true && code !== 'ENOENT' && code !== 'ENOTDIR') throw refuse('exists but cannot be read', code ?? extractErrorMessage(e))
return {}
}
let parsed: unknown
try {
parsed = JSON.parse(stripBom(raw))
} catch {
if (opts.strict === true) throw refuse('exists but contains invalid JSON')
// Corrupt JSON: do not clobber it silently — but for our read we treat it as empty so callers can decide. (installHooks rewrites the whole file.)
return {}
}
if (typeof parsed === 'object' && parsed !== null && !Array.isArray(parsed)) {
const hooksValue = (parsed as Settings).hooks
if (hooksValue === undefined || (typeof hooksValue === 'object' && hooksValue !== null && !Array.isArray(hooksValue))) return parsed as Settings
// A `hooks` that is not a JSON object cannot be merged into or stripped: strict callers refuse and leave the file alone, read-only ones see no hooks.
if (opts.strict === true) throw refuse('has a "hooks" value that is not a JSON object')
const { hooks: _ignored, ...rest } = parsed as Settings
return rest
}
if (opts.strict === true) throw refuse('does not contain a JSON object at the top level')
return {}
}
/** The argv words of every token-goat hook entry in the `scope` settings file: an exec-form entry's command and args, a string-form entry split the way the POSIX shell Claude Code runs it in would. */
export function wiredClaudeHookWords(scope: HookScope): string[][] {
const out: string[][] = []
for (const groups of Object.values(readSettings(settingsPath(scope)).hooks ?? {})) {
for (const g of Array.isArray(groups) ? groups : []) {
for (const h of Array.isArray(g?.hooks) ? g.hooks : []) {
const fields = commandHookFields(h)
if (fields === undefined || !isTokenGoatHookCommand(fields.command, fields.args)) continue
out.push(fields.args !== undefined && fields.args.length > 0 ? [fields.command, ...fields.args] : stringFormHookWords(fields.command))
}
}
}
return out
}
/** The hook entries of a matcher group, or none when the group is not an object or its `hooks` is not an array (a hand-edited file can hold anything). */
function hooksOf(group: HookMatcherGroup | null | undefined): HookCommandEntry[] {
return Array.isArray(group?.hooks) ? group.hooks : []
}
/** True when `groups` contains a hook command matching `predicate`. */
function groupHasTokenGoat(
groups: HookMatcherGroup[] | undefined,
predicate: (command: string, args?: readonly string[]) => boolean,
): boolean {
// A hand-edited `hooks.<Event>` can hold a string or an object where Claude Code expects an array of groups; it holds no token-goat entry.
if (!Array.isArray(groups)) return false
for (const group of groups) {
for (const h of hooksOf(group)) {
if (isOwnHookEntry(h, predicate)) return true
}
}
return false
}
/** Install token-goat hooks into the `scope` settings file. Reads the existing settings (creating an empty doc when absent), adds any missing current-format token-goat hook entries under each mapped event key, and writes the result atomically. A legacy-only entry for an event key (see {@link LEGACY_COMMAND_MARKERS}) does not count as already installed -- it is stripped and replaced with the current command, so an upgrade from a tokenwise/token_goat-era install ends up with exactly one, working, entry per event key rather than a dead leftover sitting next to a new one. `alreadyInstalled` is true when nothing had to change. */
export function installHooks(scope: HookScope = 'user'): InstallResult {
return withInstallScope(hookScopeRoot(scope), () => installHooksScoped(scope))
}
/** The confinement root for a hook scope. `'project'` writes `<cwd>/.claude/settings.json`, so the cwd is the root; `'user'` writes under the home directory and is deliberately unconfined, for the dotfiles-symlink reason bridges/project_scope_guard.ts spells out. */
function hookScopeRoot(scope: HookScope): string | undefined {
return scope === 'project' ? normalizeDarwinSystemAlias(process.cwd()) : undefined
}
function installHooksScoped(scope: HookScope): InstallResult {
const p = settingsPath(scope)
// strict: true -- a settings file that exists but fails to parse must abort before any write (see SettingsParseError), not silently proceed as if it were empty and get clobbered below.
const settings = readSettings(p, { strict: true })
const hooks = settings.hooks ?? {}
// The shim is a generated, never-user-edited file: refresh it on every install call so it tracks the running token-goat version, independent of whether the settings.json wiring itself needs any change. Mirrors bridges/codex_install.ts. writeIfDifferent rather than an unconditional atomicWriteText so a genuine no-op install touches nothing on disk, and so a repaired shim (user deleted ~/.claude/hooks, or an older build left stale content) counts as a real change via `scriptChanged` -- reporting "already installed" while having just rewritten the file the hooks depend on would be a lie to anyone running install precisely to repair it.
const scriptPath = claudeHookScriptPath()
// The shim is home-scoped even on a project-scope install -- BOTH scopes share the one copy at `~/.claude/hooks/token-goat-shim.cjs` (see uninstallHooks' anyScopeReferencesShim) -- so this write is declared user scope explicitly rather than inheriting the project confinement, which would otherwise refuse it. Written down rather than exempted by path: `~/.claude` is the user's own directory, and a dotfiles symlink pointing it elsewhere is the setup bridges/project_scope_guard.ts deliberately allows.
const scriptChanged = withInstallScope(undefined, () => {
ensureDirRecordingCreation(path.dirname(scriptPath))
const forwarderChanged = writeIfDifferent(claudeLegacyHookScriptPath(), legacyShimForwarder('{}'))
const scriptChanged = writeIfDifferent(scriptPath, CLAUDECODE_HOOK_SCRIPT)
return scriptChanged || forwarderChanged
})
let settingsChanged = false
const skippedEvents: string[] = []
for (const [eventKey, eventArg] of HOOK_EVENT_MAP) {
const expected = expectedHookEntryFor(scriptPath, eventArg)
// A non-array value (a string or an object) is the user's own and cannot be merged into; it is left byte-for-byte as it was and the event is skipped, as the settings file is reported at the end.
const rawGroups: unknown = hooks[eventKey]
if (rawGroups !== undefined && !Array.isArray(rawGroups)) {
skippedEvents.push(eventKey)
continue
}
const existingGroups: HookMatcherGroup[] = (rawGroups as HookMatcherGroup[] | undefined) ?? []
// Strip every token-goat entry that is not byte-identical to what this build wires, whether or not a correct entry also already exists -- a wrong entry coexisting with a right one violates "exactly one, working, entry per event key" just as much as a wrong entry sitting alone does. Exact-match rather than marker-match is what makes this cover all four staleness shapes at once: a legacy alias (tokenwise/token_goat/tg-hook), a pre-shim bare `token-goat hook <event>`, a shim command whose baked absolute paths have since moved (node upgraded, token-goat reinstalled elsewhere), and a string-form entry once exec form becomes available (or vice versa, if a user downgrades Claude Code). A marker check would call any of those "already installed" and leave the hook pointing at a binary that no longer exists, or in a form the running Claude Code can't use.
const groups: HookMatcherGroup[] = []
let strippedStale = false
for (const group of existingGroups) {
if (typeof group !== 'object' || group === null) {
groups.push(group)
continue
}
const keptHooks = hooksOf(group).filter((h) => {
const isStale = isOwnHookEntry(h, (command, args) => isTokenGoatHookCommand(command, args) && !hookEntryMatches(command, args, expected))
if (isStale) strippedStale = true
return !isStale
})
if (keptHooks.length > 0) {
groups.push({ ...group, hooks: keptHooks })
} else if (hooksOf(group).length === 0) {
// A group that had no hooks to begin with is user data; preserve it.
groups.push(group)
}
}
const isOurs = (command: string, args?: readonly string[]): boolean => hookEntryMatches(command, args, expected)
if (groupHasTokenGoat(groups, isOurs)) {
// Re-narrow an already-installed entry. Without this the matcher improvement below would only ever reach brand-new installs: every existing user would keep the catch-all they were installed with and see no benefit. Only groups whose hooks are all token-goat's own are touched -- a group the user has added their own commands to is left exactly as-is.
const narrowed = toolMatcherFor(eventArg as HookEventName)
let renarrowed = false
for (let i = 0; i < groups.length; i++) {
const group = groups[i]
if (group === undefined) continue
const ownHooks = hooksOf(group)
const isOwnGroup = ownHooks.length > 0 && ownHooks.every((h) => isOwnHookEntry(h, isOurs))
if (isOwnGroup) {
if (narrowed !== null && group.matcher !== narrowed) {
groups[i] = { ...group, matcher: narrowed }
renarrowed = true
} else if (narrowed === null && group.matcher !== undefined) {
const { matcher: _dropped, ...rest } = group
groups[i] = rest
renarrowed = true
}
}
}
if (strippedStale || renarrowed) {
hooks[eventKey] = groups
settingsChanged = true
}
continue
}
// Narrow the matcher to the tools this event actually has handlers for. Claude Code spawns a process per matcher hit and ~90% of that cost is Node startup plus bundle evaluation, so a catch-all makes every unhandled tool pay full price twice (pre + post). toolMatcherFor returns null when narrowing would be unsafe -- a non-tool event, or a handler that really does want everything -- and the catch-all is the correct answer then (where matcher is omitted entirely, since Claude Code schema forbids empty string matchers).
const matcher = toolMatcherFor(eventArg as HookEventName)
groups.push({ ...(matcher !== null ? { matcher } : {}), hooks: [{ type: 'command', command: expected.command, ...(expected.args !== undefined ? { args: expected.args } : {}) }] })
hooks[eventKey] = groups
settingsChanged = true
}
if (skippedEvents.length > 0) {
process.stderr.write(`token-goat: left ${p} untouched under hooks.${skippedEvents.join(', hooks.')}: not a list of hook groups, so no token-goat hook was added there. Fix the value and run install again.\n`)
}
if (!settingsChanged && !scriptChanged) {
return { scope, settingsPath: p, alreadyInstalled: true, ...(skippedEvents.length > 0 ? { skippedEvents } : {}) }
}
// Only touch settings.json when its own content actually changed: a run that merely repaired the shim must not rewrite (and re-timestamp) a file the user may be watching or version-controlling.
if (settingsChanged) {
settings.hooks = hooks
recordCreatedBy([p], () => writeJsonSettings(p, settings))
}
return { scope, settingsPath: p, alreadyInstalled: false, ...(skippedEvents.length > 0 ? { skippedEvents } : {}) }
}
/** Remove token-goat hooks from the `scope` settings file. Strips every hook entry whose command targets `token-goat hook ...`, prunes now-empty matcher groups and event keys, and drops the `hooks` section if it becomes empty. Returns true when at least one entry was removed; false when none were present (no write occurs in that case). */
export function uninstallHooks(scope: HookScope = 'user'): boolean {
return withInstallScope(hookScopeRoot(scope), () => uninstallHooksScoped(scope))
}
function uninstallHooksScoped(scope: HookScope): boolean {
const p = settingsPath(scope)
// Strict, as install reads it: a file that is there but cannot be read or parsed may still wire hooks that run the shim, so uninstall stops here with the file, the shim and the file's backups as they were, rather than read it as holding no hooks and delete what those hooks run.
const settings = readSettings(p, { strict: true, command: 'uninstall' })
// A file with no `hooks` map reads as an empty one rather than ending the uninstall here: the shim, its directory and the file's backups below are token-goat's own litter whether or not an earlier uninstall, or the user, already took the entries out.
const hooks = settings.hooks ?? {}
const removed = stripOwnHooksFromMap(hooks, isTokenGoatHookCommand)
// Remove the generated shim too, mirroring bridges/codex_install.ts -- but ONLY once no scope still points at it. Unlike Codex, which has a single config location, token-goat has two scopes that share one home-scoped shim: deleting it on `uninstall --project` while a user-scope install is still wired would leave every user-scope hook invoking a file that no longer exists, failing silently on every tool call. Checked after the strip above so this scope's own now-removed entries don't count as a reason to keep it.
const scriptPath = claudeHookScriptPath()
let removedScript = false
if (!anyScopeReferencesShim([scriptPath, claudeLegacyHookScriptPath()], scope, hooks)) {
// Declared USER scope explicitly, exactly as the matching write in installHooksScoped is: the shim lives at `~/.claude/hooks/token-goat-shim.cjs` and is shared by both scopes, so under a project-scope uninstall the ambient confinement would refuse to remove it. Removal has to be symmetric with the write or `uninstall --project` leaves the file it installed behind -- which is what the built-bundle matrix caught the first time this was routed through the scope-checked helper without the wrapper. Already-absent is not an error, which is exactly removeFileInScope's contract.
removedScript = withInstallScope(undefined, () => {
const removedAny = [scriptPath, claudeLegacyHookScriptPath()].map((p) => removeFileInScope(p)).some(Boolean)
removeCreatedIfEmpty(path.dirname(scriptPath))
return removedAny
})
}
const result = finishHookUninstall(p, settings, removed) || removedScript
// A settings file left holding `{}`, and the `.claude` directory above it, go only when the ledger says this install created them.
removeCreatedTree([p])
return result
}
/** The end of every JSON-settings hook uninstall, whatever it found. When `removed` says token-goat's entries were just stripped from `settings`, the file is written back, dropping a `hooks` map left empty. Either way the timestamped backups token-goat made of the file are deleted: they are its own litter, so they leave with it, including when an earlier uninstall or the user already took the entries out. The Claude Code, Gemini CLI and Qwen Code uninstalls all end here and return what this returns, which is `removed`. `write` defaults to the plain JSON writer; the Gemini and Qwen uninstalls pass the comment-keeping one. */
export function finishHookUninstall(p: string, settings: { hooks?: Record<string, unknown> }, removed: boolean, write: (p: string, settings: unknown) => void = writeJsonSettings): boolean {
if (removed) {
if (settings.hooks !== undefined && Object.keys(settings.hooks).length === 0) delete settings.hooks
write(p, settings)
}
removeCreatedBackups(p)
return removed
}
/** Are token-goat hooks installed in `scope`? True only when every mapped event key carries a *current-format* token-goat hook command — a legacy-only entry does not count, since it is dead on this build, and a partial install (some events wired, some not) reads as not installed so {@link installHooks} will top up the missing entries. */
export function isInstalled(scope: HookScope = 'user'): boolean {
// A wired command whose baked shim path no longer exists on disk cannot fire, so it must read as not-installed and let installHooks regenerate it -- otherwise a user who deleted ~/.claude/hooks would be told they are installed while every hook silently no-ops.
if (!fs.existsSync(claudeHookScriptPath())) return false
const gaps = hookEventGaps(scope)
return gaps !== null && gaps.missing.length === 0 && gaps.outdated.length === 0 && gaps.broken.length === 0
}
/** Does `scope` wire at least one token-goat hook that still fires? A partial install counts (a wired event runs whatever the others lack), where {@link isInstalled} wants every event; a hook whose shim or native client is gone cannot fire and does not. */
function hasFiringHook(scope: HookScope): boolean {
const gaps = hookEventGaps(scope)
return gaps !== null && gaps.missing.length + gaps.broken.length < HOOK_EVENT_MAP.length
}
/** Whether token-goat's Claude Code hooks fire from either scope, even a partial install: the one test doctor's VS Code chat.useClaudeHooks row and Cursor row, `install --vscode` and `doctor --repair` all apply before treating Claude's hooks as a duplicate of token-goat's own. VS Code and Cursor run every wired event, so one event left over from an older release still doubles up; waiting for a complete install would leave the setting on and the duplicate firing. The project scope is the working directory's, as for every other scope-aware row doctor prints: a workspace elsewhere cannot be enumerated from here. */
export function claudeHooksInstalledAnyScope(): boolean {
return hasFiringHook('user') || hasFiringHook('project')
}
/** Claude Code event keys in `scope` that lack this build's exact hook entry, split by whether the event still reaches token-goat. */
export interface HookEventGaps {
/** No live token-goat hook at all (none, or only a {@link LEGACY_COMMAND_MARKERS} leftover that no longer resolves): the event never reaches token-goat. */
readonly missing: string[]
/** A shim or pre-shim token-goat hook that still runs, just not the entry this build writes (older shim path, string form where exec form is expected, another bundle path, the Node command where this build wires the native client or the other way round). */
readonly outdated: string[]
/** A native-form hook whose tg-hook binary is gone: the harness cannot start it, so the event fails rather than falling back to Node. */
readonly broken: string[]
}
const LIVE_HOOK_MARKER_PATTERNS = [SHIM_COMMAND_MARKER, COMMAND_MARKER].map(anchoredMarkerPattern)
/** A command word naming a shim file, current `.cjs` or pre-rename `.js`, under either path separator. */
const SHIM_FILE_WORD = /(?:^|[\\/])token-goat-shim\.c?js$/
/** True when `command`/`args` is a token-goat hook of an era that still runs on this build: the shim (any file name or form) whose file is still on disk, or the pre-shim `token-goat hook <event>`, which resolves through PATH; never a legacy alias. */
function isLiveTokenGoatHookCommand(command: string, args?: readonly string[]): boolean {
const execForm = args !== undefined && args.length > 0
const haystack = execForm ? `${command} ${args.join(' ')}` : command
if (!LIVE_HOOK_MARKER_PATTERNS.some((pattern) => pattern.test(haystack))) return false
const words = execForm ? [command, ...args] : stringFormHookWords(command)
// A native entry runs only if its binary does: with the binary gone the harness cannot start it, and nothing falls back to the Node command it wraps.
const native = parseNativeInvocation(words)
if (native !== undefined && !fs.existsSync(native.bin)) return false
const shimFile = words.find((word) => SHIM_FILE_WORD.test(word))
return shimFile === undefined || fs.existsSync(shimFile)
}
/** True when `command`/`args` is a native-form token-goat hook whose tg-hook binary no longer exists. */
function isBrokenNativeHookCommand(command: string, args?: readonly string[]): boolean {
const words = args !== undefined && args.length > 0 ? [command, ...args] : stringFormHookWords(command)
const native = parseNativeInvocation(words)
return native !== undefined && native.wrapped.some((word) => SHIM_FILE_WORD.test(word)) && !fs.existsSync(native.bin)
}
/** The {@link HookEventGaps} of `scope`, or null when the scope wires no token-goat hook at all, so there is no install there to be partial. A release that adds an event reaches an existing user only when `token-goat install` (or `upgrade`, which re-runs it) tops the key up, and an older build's entry is rewritten by the same run; this is how `doctor` says which of the two applies in the meantime. */
export function hookEventGaps(scope: HookScope = 'user'): HookEventGaps | null {
const hooks = readSettings(settingsPath(scope)).hooks
if (hooks === undefined) return null
if (!HOOK_EVENT_MAP.some(([eventKey]) => groupHasTokenGoat(hooks[eventKey], isTokenGoatHookCommand))) return null
const scriptPath = claudeHookScriptPath()
const missing: string[] = []
const outdated: string[] = []
const broken: string[] = []
for (const [eventKey, eventArg] of HOOK_EVENT_MAP) {
// A read, never a repair: a stale Windows copy of the native binary makes its entries outdated here, and `install` is what refreshes it.
const expected = expectedHookEntryFor(scriptPath, eventArg, { sync: false })
// An entry equal to this build's own is not wired if the shim it runs was deleted: the harness cannot start it, so it falls through to missing (or broken, for a native entry whose binary went too).
if (groupHasTokenGoat(hooks[eventKey], (c, a) => hookEntryMatches(c, a, expected) && isLiveTokenGoatHookCommand(c, a))) continue
if (groupHasTokenGoat(hooks[eventKey], isLiveTokenGoatHookCommand)) outdated.push(eventKey)
else if (groupHasTokenGoat(hooks[eventKey], isBrokenNativeHookCommand)) broken.push(eventKey)
else missing.push(eventKey)
}
return { missing, outdated, broken }
}
// --- CLAUDE.md delimited-block writer --- README documents this as part of the base Claude Code install -- run by a bare `install` (or `--hermes`, gated in cli_install.ts's wantsClaudeCodeBase), never by a scoped harness flag like --vscode: a delimited block in the user's own ~/.claude/CLAUDE.md telling the agent to prefer token-goat commands over Read/Grep. Mirrors bridges/codex_install.ts's AGENTS.md writer -- same idempotent merge-or-append pattern, same "preserve everything outside the markers" guarantee for a file the user edits directly.
const CLAUDE_MD_BEGIN = '<!-- token-goat-begin -->'
const CLAUDE_MD_END = '<!-- token-goat-end -->'
/** Absolute path to `~/.claude/CLAUDE.md` (or `$CLAUDE_CONFIG_DIR/CLAUDE.md`), or with `'project'` the `CLAUDE.md` at the working directory's root, which Claude Code loads as that project's memory. */
export function claudeMdPath(scope: HookScope = 'user'): string {
return scope === 'user' ? path.join(claudeConfigDir(), 'CLAUDE.md') : path.join(normalizeDarwinSystemAlias(process.cwd()), 'CLAUDE.md')
}
function buildClaudeMdBlock(): string {
return buildGuidanceBlock({
beginMarker: CLAUDE_MD_BEGIN,
endMarker: CLAUDE_MD_END,
fallbackToolClause: "Claude Code's own Read, Grep, and Glob preference rules",
gdrive: loadConfig().gdrive.enabled,
})
}
function writeClaudeMdBlock(p: string): boolean {
return upsertDelimitedBlock(p, CLAUDE_MD_BEGIN, CLAUDE_MD_END, buildClaudeMdBlock())
}
function stripClaudeMdBlock(p: string): boolean {
return stripDelimitedBlock(p, CLAUDE_MD_BEGIN, CLAUDE_MD_END)
}
/** The token-goat block as it sits in `~/.claude/CLAUDE.md` now, markers included, or null when the file or either marker is missing. Read from disk rather than rebuilt with {@link buildClaudeMdBlock}, because the file is what a session loads: an install from an older version, or a hand edit, is what the user pays for until the next install refreshes it. */
export function installedClaudeMdBlock(): string | null {
let text: string
try {
text = fs.readFileSync(claudeMdPath(), 'utf8')
} catch {
return null
}
const begin = text.indexOf(CLAUDE_MD_BEGIN)
if (begin === -1) return null
const end = text.indexOf(CLAUDE_MD_END, begin + CLAUDE_MD_BEGIN.length)
return end === -1 ? null : text.slice(begin, end + CLAUDE_MD_END.length)
}
/** Outcome of an {@link installClaudeMd} call. */
export interface ClaudeMdInstallResult {
readonly path: string
/** True when the block was already present and up to date (no write needed). */
readonly alreadyInstalled: boolean
}
/** Add or refresh the token-goat block in the `scope` CLAUDE.md, preserving any existing content. */
export function installClaudeMd(scope: HookScope = 'user'): ClaudeMdInstallResult {
return withInstallScope(hookScopeRoot(scope), () => {
const p = claudeMdPath(scope)
const existed = fs.existsSync(p)
const changed = writeClaudeMdBlock(p)
if (!existed) recordCreatedConfig(p)
return { path: p, alreadyInstalled: !changed }
})
}
/** Remove the token-goat block from the `scope` CLAUDE.md, leaving the rest of the file intact, and the file itself when {@link installClaudeMd} created it and nothing but the block was ever in it. */
export function uninstallClaudeMd(scope: HookScope = 'user'): boolean {
return withInstallScope(hookScopeRoot(scope), () => {
const p = claudeMdPath(scope)
const stripped = stripClaudeMdBlock(p)
removeCreatedIfEmpty(p)
return stripped
})
}
/** Find token-goat marker blocks sitting in some markdown file *other* than `~/.claude/CLAUDE.md`. The block is plain markdown in a file the user is explicitly told they own and edit, so relocating it into a tidier "reference" file is a natural thing to do -- and it silently breaks: {@link installClaudeMd} and {@link uninstallClaudeMd} both resolve the single hardcoded {@link claudeMdPath}, so a relocated copy is never refreshed (it freezes at whatever version was current when it moved) and never removed on uninstall. Worse, the next install sees CLAUDE.md missing its block and appends a fresh one, leaving the guidance duplicated across two files with only one of them live. Detection only -- callers report; nothing here edits or deletes a user's file. Matches a real block, not a mention of one: both markers must appear on their own lines. Prose that references `<!-- token-goat-begin -->` inline -- a pointer explaining where the managed block actually lives, which is exactly what a user is told to leave behind after relocating one -- would otherwise be flagged forever as the very thing it documents. Bounded walk: skips `node_modules`/`.git`, caps depth, and ignores symlinked directories (`Dirent.isDirectory()` is false for a symlink), so it cannot loop. */
export function findStrayClaudeMdBlocks(searchRoot?: string): string[] {
const root = searchRoot ?? claudeConfigDir()
const canonical = path.resolve(claudeMdPath())
const found: string[] = []
if (!fs.existsSync(root)) return found
const SKIP_DIRS = new Set(['node_modules', '.git'])
const MAX_DEPTH = 6
const hasRealBlock = (text: string): boolean => {
let sawBegin = false
for (const line of text.split(/\r?\n/)) {
const trimmed = line.trim()
if (trimmed === CLAUDE_MD_BEGIN) sawBegin = true
else if (sawBegin && trimmed === CLAUDE_MD_END) return true
}
return false
}
const walk = (dir: string, depth: number): void => {
if (depth > MAX_DEPTH) return
let entries: fs.Dirent[]
try {
entries = fs.readdirSync(dir, { withFileTypes: true })
} catch {
return
}
for (const entry of entries) {
const full = path.join(dir, entry.name)
if (entry.isDirectory()) {
if (!SKIP_DIRS.has(entry.name)) walk(full, depth + 1)
continue
}
if (!entry.isFile() || !entry.name.toLowerCase().endsWith('.md')) continue
if (path.resolve(full) === canonical) continue
let text: string
try {
text = fs.readFileSync(full, 'utf8')
} catch {
continue
}
if (hasRealBlock(text)) found.push(full)
}
}
walk(root, 0)
return found.sort()
}
// --- token-goat skill writer --- README documents ~/.claude/skills/token-goat/SKILL.md as part of the base install too -- "the same routing guidance in skill form", run under the same wantsClaudeCodeBase gate as the CLAUDE.md block above, never by a scoped harness flag. Unlike CLAUDE.md, this directory belongs entirely to token-goat (nothing else writes into it), so install/uninstall can write/remove the whole file rather than patching a delimited region.
// The whole skill, frontmatter `description` included, is CANONICAL_SKILL_MD, generated from src/canonical_skill.md by `npm run skill:canonical`; edit the .md, never this writer. Its description stays separate from the Kimi skill's shared line in bridges/guidance_block.ts on purpose: it must fit the 240-character limit of the skill collection the file is synced into, and it names `/token-goat audit`; tests/skill_description_shared.test.ts keeps the two opening with the same routing pitch. The allowed-tools frontmatter keeps Copilot-style loaders from body-scanning the skill prose and mistaking quoted command names for implicit tool identifiers. It MUST list real harness tool identifiers, not token-goat subcommands: loaders validate every entry against their tool registry and warn on each miss, so a subcommand list here produces one "Unknown tool name in the tool allowlist" warning per entry. token-goat itself runs through the shell tool.
function skillMdContent(): string {
return CANONICAL_SKILL_MD
}
/** Absolute path to the token-goat skill directory, `~/.claude/skills/token-goat`, or with `'project'` the `.claude/skills/token-goat` under the working directory. */
export function skillDir(scope: HookScope = 'user'): string {
return path.join(scope === 'user' ? claudeConfigDir() : path.join(normalizeDarwinSystemAlias(process.cwd()), '.claude'), 'skills', 'token-goat')
}
/** Absolute path to `~/.claude/skills/token-goat/SKILL.md` (the `scope` skill directory's file). */
export function skillPath(scope: HookScope = 'user'): string {
return path.join(skillDir(scope), 'SKILL.md')
}
/** The frontmatter `description:` line of the installed skill as it sits on disk, or null when the skill is absent or its frontmatter has none. */
export function installedSkillDescription(): string | null {
let text: string
try {
text = fs.readFileSync(skillPath(), 'utf8')
} catch {
return null
}
const lines = text.split(/\r?\n/)
if (lines[0] !== '---') return null
for (const line of lines.slice(1)) {
if (line === '---') return null
if (line.startsWith('description:')) return line
}
return null
}
/** Outcome of an {@link installSkill} call. */
export interface SkillInstallResult {
readonly path: string
/** True when the file was already present and up to date (no write needed). */
readonly alreadyInstalled: boolean
}
/** Write (or refresh) the token-goat skill at the `scope` `skills/token-goat/SKILL.md`. */
export function installSkill(scope: HookScope = 'user'): SkillInstallResult {
return withInstallScope(hookScopeRoot(scope), () => installSkillScoped(scope))
}
function installSkillScoped(scope: HookScope): SkillInstallResult {
const p = skillPath(scope)
let existing: string | null = null
try {
existing = fs.readFileSync(p, 'utf8')
} catch {
// Absent; falls through to the write below.
}
const skillContent = skillMdContent()
if (existing === skillContent) return { path: p, alreadyInstalled: true }
recordCreatedBy([skillDir(scope)], () => ensureDirSync(skillDir(scope)))
backupFile(p)
atomicWriteText(p, skillContent)
return { path: p, alreadyInstalled: false }
}
/** Remove the token-goat skill directory entirely, then each directory above it that {@link installSkill} created and that nothing else lives in. */
export function uninstallSkill(scope: HookScope = 'user'): boolean {
return withInstallScope(hookScopeRoot(scope), () => uninstallSkillScoped(scope))
}
function uninstallSkillScoped(scope: HookScope): boolean {
const dir = skillDir(scope)
const present = fs.existsSync(dir)
if (present) {
// The directory removal below takes SKILL.md's own timestamped backups with it; this only drops the now-dangling ledger entries for them, mirroring uninstallHooks's cleanup.
removeCreatedBackups(skillPath(scope))
// Written out rather than routed through a helper because no helper fits: this is a RECURSIVE DIRECTORY removal and `removeFileInScope` is deliberately file-only. The check is the same one the write helpers make. It is a no-op in user scope, and in project scope it stops the project's skill directory being deleted through a checked-in directory symlink.
assertWriteInScope(dir)
fs.rmSync(dir, { recursive: true, force: true })
}
// Whether or not the skill directory was still there: an empty `skills` directory, and a `.claude` directory above it, that this install created are litter either way.
removeCreatedTree([dir])
return present
}