diff --git a/CHANGELOG.md b/CHANGELOG.md index 4c11c96c..a7f75833 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,16 @@ Releases 0.4.0 and older are in [CHANGELOG-ARCHIVE.md](CHANGELOG-ARCHIVE.md). ## [Unreleased] +## [0.23.0] — 2026-11-29 + +### Added + +- **`pharn status` reports the two project settings that leave the PHARN write guards off, or failing open, while the hook wiring looks complete** (CORE-594). (1) `"disableAllHooks": true` in `.claude/settings.json` or `.claude/settings.local.json` makes Claude Code run no hook at all for whoever loads that file (`settings.local.json` overrides `settings.json` for its one user, so each file is reported, not the effective value). The `HOOKS` note now names each project file that sets it, as `.claude/settings.json sets "disableAllHooks": true`. (2) A hook that upstream wires with `"onFailure": "block"` blocks the write when it cannot start, exits with a code other than 0 or 2, or times out. A project line wiring the same hook without that field lets the write through, and the note lists it with its file under `FAIL-OPEN`. Both are new [strict conditions](docs/commands/status.md#strict-conditions), so `pharn status --strict` exits 1 on either. Whenever the `HOOKS` note prints, it now ends by saying that user-level `~/.claude/settings.json` is not read, and that this is a report, not a guard: a setting added after the run is not seen. `status --json` adds `hooks.disabledIn` and `hooks.failOpen`, each absent when empty, so neither key appears for a project with no such finding (the `HookEntry` objects themselves gain `onFailure`, below). A key absent, or set to anything but `true`, is no finding. A hook upstream wires without `onFailure` is never reported. `--no-drift` reads no settings file. + +### Changed + +- **The paste-ready hook lines carry `"onFailure": "block"` when upstream sets it.** `status`, `update`, `uninstall` and `init` print each hook as JSON. That JSON now includes the field when the hook sets it, so pasting a line `status` lists as missing no longer wires a guard that fails open. The `HookEntry` objects in the `--json` reports gain an `onFailure: "block"` key on those hooks (absent otherwise). Hook matching is unchanged: `onFailure` is not part of the textual key. + ## [0.22.0] — 2026-11-25 ### Added @@ -541,7 +551,8 @@ _Never released: 0.9.0 followed on the same day, so `0.8.0` was neither tagged n matcher that silently stopped matching, or a comparator read in the wrong direction, would otherwise leave every assertion green. -[Unreleased]: https://github.com/pharn-dev/pharn-cli/compare/v0.22.0...HEAD +[Unreleased]: https://github.com/pharn-dev/pharn-cli/compare/v0.23.0...HEAD +[0.23.0]: https://github.com/pharn-dev/pharn-cli/compare/v0.22.0...v0.23.0 [0.22.0]: https://github.com/pharn-dev/pharn-cli/compare/v0.21.7...v0.22.0 [0.21.7]: https://github.com/pharn-dev/pharn-cli/compare/v0.21.6...v0.21.7 [0.21.6]: https://github.com/pharn-dev/pharn-cli/compare/v0.21.5...v0.21.6 diff --git a/docs/README.md b/docs/README.md index 67b3412b..112a0155 100644 --- a/docs/README.md +++ b/docs/README.md @@ -18,7 +18,7 @@ The CLI version (`pharn --version`) and the content version it installs (`skills - [uninstall](commands/uninstall.md) — remove PHARN, deleting only the files `pharn` wrote and you did not change - [update](commands/update.md) — re-fetch installed capabilities at the latest skills version - [list](commands/list.md) — list installed archetypes + capabilities -- [status](commands/status.md) — read-only version + local-drift check; `--strict` exits 1 on an outdated install, a modified, missing or unreadable file, a surface upstream no longer ships, or an unwired hook ([the full list](commands/status.md#strict-conditions)), and neither `status` nor `list` is ever blocked by another `pharn` run's lock +- [status](commands/status.md) — read-only version + local-drift check; `--strict` exits 1 on an outdated install, a modified, missing or unreadable file, a surface upstream no longer ships, an unwired hook, or a project settings file that switches the hooks off or a guard fail-open ([the full list](commands/status.md#strict-conditions)), and neither `status` nor `list` is ever blocked by another `pharn` run's lock - [verify-archive](commands/verify-archive.md) — check a local pharn-oss `.tar.gz` as an install would, with no network (for pharn-oss CI) ## Reference diff --git a/docs/architecture.md b/docs/architecture.md index c4b7936b..23582a71 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -300,9 +300,10 @@ Strictly read-only. - **Drift** (`lib/diff.ts`): the expected file set against the project. It is a report, not a preview, because it does not read the records; only `update` can tell an upgrade from a skip. - **Hooks** (`lib/hook-wiring.ts`): upstream's hook entries against the project's `settings.json` ∪ - `settings.local.json`. + `settings.local.json`, then `hookGuardSettings`: a project file setting `"disableAllHooks": true`, and a guard + upstream wires with `"onFailure": "block"` that the project wires without it. User-level settings are not read. - `--no-drift` skips the clone. `--strict` exits 1 on an outdated, modified, missing, unreadable or - not-shipped-upstream finding, or an unwired hook (`strictFails`; the user-facing list is + not-shipped-upstream finding, an unwired hook, or either guard setting (`strictFails`; the user-facing list is [`status`'s Strict conditions](commands/status.md#strict-conditions)). Orphans and the `MODELS` and `PRETTIER` notes are advisory. - `--json` prints one object (`schemaVersion: 1`) through `serializeStatusReport`. diff --git a/docs/commands/status.md b/docs/commands/status.md index aaacc719..57be6b39 100644 --- a/docs/commands/status.md +++ b/docs/commands/status.md @@ -180,6 +180,25 @@ project. The `HOOKS` section works like this: - **Local only.** A hook wired **only** in `settings.local.json` counts as wired, since it runs for you, and `--strict` passes. The section still names it, because it reaches neither your teammates nor CI (where that file does not exist). +- **Hooks off.** `"disableAllHooks": true` in `.claude/settings.json` or `.claude/settings.local.json` + makes Claude Code run no hook at all for whoever loads that file, both PHARN write guards + included, while the wiring stays exactly as committed. It is reported per file, not as the + effective value: `settings.local.json` overrides `settings.json` for its one user, so a local + `false` turns hooks back on for you only, while teammates and CI still load the shared `true`. The section names each project file that sets it, as + `.claude/settings.json sets "disableAllHooks": true`, under `HOOKS OFF`, and `--strict` exits `1`. + The key absent, or set to anything but `true`, is no finding. +- **Fail-open.** A hook upstream wires with `"onFailure": "block"` blocks the write when it cannot + start, exits with a code other than 0 or 2, or times out. A project line that wires the same hook + (same textual key) without that field lets the write through instead. The section lists each such + line with its file under `FAIL-OPEN`, and `--strict` exits `1`. A hook upstream wires without the + field (the `Stop` hook, say) is never reported. The paste-ready lines carry the field when upstream + sets it, so pasting one satisfies both checks. +- **What it cannot see.** Whenever the section prints, it ends with two lines: + `~/.claude/settings.json (user level) is not read, so "disableAllHooks" set there is not seen.` and + `This is a report, not a guard: a setting added after this run is not seen.` `status` reads your + settings files once, when it runs. Anything that can write a settings file (an agent with `Bash`, + say) can set either key afterwards, and nothing in `pharn` notices. Run `pharn status --strict` where + it matters, in CI for the committed `settings.json`. CI never sees `settings.local.json`. - **Symlinks.** A symlinked `settings.json` file is read through, as Claude Code does. A symlinked `.claude/` directory is refused. The copied-verbatim trusted docs, `.cjs`/`.mjs` hooks, `pharn/features/README.md`, pharn's `LICENSE` copy, and the contracts, `pharn-core` and floor dirs (`pharn/pharn-contracts/`, @@ -215,8 +234,13 @@ exactly this. `--strict` exits `1` when any of these holds: - one of those hooks is wired in neither `.claude/settings.json` nor `.claude/settings.local.json`; - either of those two files cannot be read (it could wire anything, so the answer is unknown); - neither file exists. +7. **Hooks off.** `.claude/settings.json` or `.claude/settings.local.json` sets `"disableAllHooks": true`. +8. **Fail-open guard.** A hook the upstream `.claude/settings.json` wires with `"onFailure": "block"` is + wired in either project file, under the same event, matcher, command and args, without it. -Under `--no-drift` only condition 1 is checked: there is no clone to compare conditions 2 to 6 against. +Under `--no-drift` only condition 1 is checked: there is no clone to compare conditions 2 to 8 against, +and no settings file is read. User-level `~/.claude/settings.json` is never read, so a +`disableAllHooks` set there fails no condition. These are reported and **never** fail `--strict`: diff --git a/docs/reference/json-output.md b/docs/reference/json-output.md index 31d2e628..7542d79d 100644 --- a/docs/reference/json-output.md +++ b/docs/reference/json-output.md @@ -70,16 +70,16 @@ v0.21.0), and no longer converts the pre-0.7.0 `models` format; the keys above s ## Types used below -| Name | Shape | -| ------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `HookEntry` | `{event, matcher, command, args}`: strings, `args` a string array (empty unless the hook is in exec form) | -| `HookReplace` | `{upstream: HookEntry, existing: [{file, entry: HookEntry}]}`: a missing hook your project wires in another spelling (replace, not add) | -| `Removal` | `{role, name, reason, dir, present, backups}`: `reason` `dropped-unselected` or `dropped-gone`; `dir` the capability directory a real run would delete; `present` whether anything is there; `backups` the files in it copied to `pharn/.backup//` first | -| `IgnoreEdit` | `{action, entries}` with `action` `create` or `append` and `entries` the lines added, or `{action: "refused", reason, entries}` with `reason` `symlink`, `not-a-file` or `unreadable` and the lines to add yourself | -| `Absent` | `{surface, path}`: a declared surface the fetched clone ships no file for; `surface` is `commands`, `hooks`, `trusted-doc`, `license`, `features-readme`, `contracts`, `core` or `floor` | -| `Unknown` | `{role, name, subtree, reason}`: an upstream capability this `pharn` cannot read, skipped | -| `Orphan` | `{path, state}` with `state` `unchanged`, `edited` or `unreadable` (then also `reason`): a recorded file upstream no longer ships, still on disk | -| `Hooks` | `{status, missing: HookEntry[], localOnly: HookEntry[], file, reason}` plus `replace: HookReplace[]` (absent when empty). `status` is `match`, `local-only`, `missing`, `no-upstream`, `project-absent` or `unreadable`; `file`/`reason` name an unreadable settings file, else `null` | +| Name | Shape | +| ------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `HookEntry` | `{event, matcher, command, args}`: strings, `args` a string array (empty unless the hook is in exec form), plus `onFailure: "block"` only when the hook sets it (absent otherwise) | +| `HookReplace` | `{upstream: HookEntry, existing: [{file, entry: HookEntry}]}`: a missing hook your project wires in another spelling (replace, not add) | +| `Removal` | `{role, name, reason, dir, present, backups}`: `reason` `dropped-unselected` or `dropped-gone`; `dir` the capability directory a real run would delete; `present` whether anything is there; `backups` the files in it copied to `pharn/.backup//` first | +| `IgnoreEdit` | `{action, entries}` with `action` `create` or `append` and `entries` the lines added, or `{action: "refused", reason, entries}` with `reason` `symlink`, `not-a-file` or `unreadable` and the lines to add yourself | +| `Absent` | `{surface, path}`: a declared surface the fetched clone ships no file for; `surface` is `commands`, `hooks`, `trusted-doc`, `license`, `features-readme`, `contracts`, `core` or `floor` | +| `Unknown` | `{role, name, subtree, reason}`: an upstream capability this `pharn` cannot read, skipped | +| `Orphan` | `{path, state}` with `state` `unchanged`, `edited` or `unreadable` (then also `reason`): a recorded file upstream no longer ships, still on disk | +| `Hooks` | `{status, missing: HookEntry[], localOnly: HookEntry[], file, reason}` plus `replace: HookReplace[]` (absent when empty). `status` is `match`, `local-only`, `missing`, `no-upstream`, `project-absent` or `unreadable`; `file`/`reason` name an unreadable settings file, else `null`. `status` only, each absent when empty: `disabledIn` (the project settings files setting `"disableAllHooks": true`) and `failOpen: [{file, entry: HookEntry}]` (project lines of an upstream `"onFailure": "block"` hook that lack it) | @@ -183,7 +183,8 @@ pharn init --dry-run --json "event": "PreToolUse", "matcher": "Write|Edit|MultiEdit|NotebookEdit", "command": "node \"${CLAUDE_PROJECT_DIR}\"/.claude/hooks/protect-trusted-paths.cjs", - "args": [] + "args": [], + "onFailure": "block" } ], "otherKeys": [], @@ -376,7 +377,7 @@ The version, drift and hook report, on the default path and under `--no-drift`. | `strict` | `{enabled, failed}` | `--strict` passed, and whether it exits `1` (the [strict conditions](../commands/status.md#strict-conditions)). | Unlike the other two reports, `status --json` reports an empty or skipped part as `null` or `[]` -rather than leaving the key out; only `hooks.replace` is absent when empty. +rather than leaving the key out; only `hooks.replace`, `hooks.disabledIn` and `hooks.failOpen` are absent when empty. ### Example diff --git a/package-lock.json b/package-lock.json index 2b0b8d01..c524ae12 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "@pharn-dev/pharn", - "version": "0.22.0", + "version": "0.23.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@pharn-dev/pharn", - "version": "0.22.0", + "version": "0.23.0", "license": "Apache-2.0", "dependencies": { "@clack/prompts": "^1.8.1", diff --git a/package.json b/package.json index aab72d36..ab73c6fa 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@pharn-dev/pharn", - "version": "0.22.0", + "version": "0.23.0", "description": "Install and update PHARN in any git project. PHARN gets features shipped right with Claude Code, with spec, plan and checks kept in Git.", "keywords": [ "claude-code", diff --git a/src/commands/status.ts b/src/commands/status.ts index 6a55bf8e..1c962876 100644 --- a/src/commands/status.ts +++ b/src/commands/status.ts @@ -1,4 +1,10 @@ -import { diffHookWiring, hookWiringLines } from '../lib/hook-wiring.js'; +import { + diffHookWiring, + HOOK_SETTINGS_SCOPE_LINES, + hookGuardSettings, + hookGuardSettingsLines, + hookWiringLines, +} from '../lib/hook-wiring.js'; import { intro, log, note, outro, spinner } from '@clack/prompts'; import pc from '../lib/color.js'; import { REPO } from '../lib/constants.js'; @@ -65,9 +71,11 @@ import type { InstalledCapability, PharnConfig } from '../types.js'; * * Default clones once for both sections; `--no-drift` checks the version only. * `--strict` exits 1 on an outdated install, a modified, missing or unreadable - * file, a declared surface upstream no longer ships, or an unwired upstream - * hook — `strictFails` (lib/status-report.ts) is the one predicate, and - * docs/commands/status.md lists it. The work is done once into ONE + * file, a declared surface upstream no longer ships, an unwired upstream hook, + * or a project setting that switches the hooks off or a guard fail-open + * (`disableAllHooks`, a missing `onFailure`) — `strictFails` + * (lib/status-report.ts) is the one predicate, and docs/commands/status.md + * lists it. The work is done once into ONE * `StatusReport` (lib/status-report.ts): `--json` prints it, the text notes are * rendered from it, and both read `--strict`'s verdict off it. `--json` emits * ONE object on stdout and nothing else; diagnostics and failures go to @@ -204,6 +212,8 @@ function cloneInput( // settings.json is never compared as a file; what IS checked is whether // every upstream hook is wired here. hooks: diffHookWiring(repo.dir, cwd), + // ...and whether a project setting turns those hooks off or fail-open. + guards: hookGuardSettings(repo.dir, cwd), unknown: index.unknown, orphans: statusOrphans(repo.dir, cwd, config, frozen), }, @@ -225,8 +235,23 @@ function renderStatus(report: StatusReport, input: StatusReportInput): void { // ORPHANED: report only — no pharn command can clear one. const orphanLines = orphanNoteLines(report.orphans ?? []); if (orphanLines) note(orphanLines.join('\n'), 'ORPHANED'); - const hookLines = hookWiringLines(drift.hooks); - if (hookLines) note(hookLines.join('\n'), 'HOOKS'); + printHooks(drift); +} + +// HOOKS note: the wiring drift, then the settings that leave wired guards off +// or fail-open, then what the check cannot see. Silent when all is in order. +function printHooks(drift: NonNullable): void { + const wiring = hookWiringLines(drift.hooks); + const guards = + drift.guards === undefined ? null : hookGuardSettingsLines(drift.guards); + if (wiring === null && guards === null) return; + const lines = [...(wiring ?? [])]; + if (guards !== null) { + if (lines.length > 0) lines.push(''); + lines.push(...guards); + } + lines.push('', ...HOOK_SETTINGS_SCOPE_LINES.map((line) => pc.dim(line))); + note(lines.join('\n'), 'HOOKS'); } // `--no-drift`'s version check without a clone: ONE bounded GET of diff --git a/src/lib/cli-args.ts b/src/lib/cli-args.ts index fcf48ef4..a81b391c 100644 --- a/src/lib/cli-args.ts +++ b/src/lib/cli-args.ts @@ -175,8 +175,10 @@ const OPTIONS: readonly OptionSpec[] = [ commands: ['status'], text: [ 'exit 1 on an outdated install, a modified, missing or unreadable', - 'file, a surface upstream no longer ships, or an unwired hook', - '(under --no-drift, only outdated is checked)', + 'file, a surface upstream no longer ships, an unwired hook, or a', + 'project settings file that sets "disableAllHooks" or wires a guard', + 'without upstream\'s "onFailure" (~/.claude/settings.json is not', + 'read; under --no-drift, only outdated is checked)', ], }, ], diff --git a/src/lib/hook-wiring.ts b/src/lib/hook-wiring.ts index f790a5b4..6f26d0d8 100644 --- a/src/lib/hook-wiring.ts +++ b/src/lib/hook-wiring.ts @@ -29,7 +29,8 @@ import { isPlainObject, safeJoin } from './validate.js'; // // Equality is TEXTUAL over `Event · matcher · command · args`: an equivalent // rewrite reads as missing, and the message says so. Extra user hooks never -// count. +// count. `onFailure` is not part of that key: a guard wired without it is +// wired, and `hookGuardSettings` (below) reports it as fail-open. // --------------------------------------------------------------------------- /** The per-user settings file Claude Code merges over `settings.json`. */ @@ -41,6 +42,12 @@ export interface HookEntry { matcher: string; command: string; args: string[]; + /** + * Present only when the handler sets `"onFailure": "block"`: a guard that + * cannot start, exits other than 0 or 2, or times out then blocks the tool + * call instead of letting it through. Any other value is dropped. + */ + onFailure?: 'block'; } export type HookWiringStatus = @@ -165,13 +172,22 @@ export function hookEntries(settings: unknown): HookEntry[] | null { const args = Array.isArray(hook.args) ? hook.args.filter((a): a is string => typeof a === 'string') : []; - out.push({ event, matcher, command: hook.command, args }); + out.push({ + event, + matcher, + command: hook.command, + args, + ...(hook.onFailure === 'block' + ? { onFailure: 'block' as const } + : {}), + }); } } } return out; } +// `onFailure` is deliberately left out (see the header). function entryKey(e: HookEntry): string { return JSON.stringify([e.event, e.matcher, e.command, e.args]); } @@ -327,6 +343,111 @@ export function hooksReferencing( return out; } +// --------------------------------------------------------------------------- +// Settings that switch wired guards off, or make them fail open, while the +// wiring compared above still looks complete (`pharn status` only): +// +// - `"disableAllHooks": true` in either project settings file: Claude Code +// runs no hook at all for whoever loads that file, both PHARN write guards +// included. Reported per file, not as the effective value: a local `false` +// overrides a shared `true` for its one user only, and CI never has it. +// - a hook upstream wires with `"onFailure": "block"` that a project file +// wires (same textual key) without it: when that guard cannot start, exits +// other than 0 or 2, or times out, the write goes through. +// +// Read as `diffHookWiring` reads. An absent or unreadable file contributes +// nothing here: `diffHookWiring` already reports an unreadable one. User-level +// `~/.claude/settings.json` is not read, and the note says so. A REPORT, not a +// guard: anything able to write a settings file can set either one after the +// run. +// --------------------------------------------------------------------------- + +/** A project wiring of a fail-closed upstream hook that lacks `onFailure`. */ +export interface FailOpenHook { + file: string; + entry: HookEntry; +} + +export interface HookGuardSettings { + /** Project settings files setting `"disableAllHooks": true`, settings.json first. */ + disabledIn: string[]; + /** Upstream `"onFailure": "block"` hooks a project file wires without it. */ + failOpen: FailOpenHook[]; +} + +const PROJECT_SETTINGS_FILES = [ + CLAUDE_SETTINGS_FILE, + LOCAL_SETTINGS_FILE, +] as const; + +/** Read the project's guard-disabling settings against the fetched clone. */ +export function hookGuardSettings( + repoDir: string, + projectRoot: string, +): HookGuardSettings { + const upstream = readSettings(repoDir, CLAUDE_SETTINGS_FILE); + const blocking = new Set( + (upstream.kind === 'ok' ? (hookEntries(upstream.value) ?? []) : []) + .filter((e) => e.onFailure === 'block') + .map(entryKey), + ); + const disabledIn: string[] = []; + const failOpen: FailOpenHook[] = []; + for (const file of PROJECT_SETTINGS_FILES) { + const read = readSettings(projectRoot, file); + if (read.kind !== 'ok') continue; + if (isPlainObject(read.value) && read.value.disableAllHooks === true) + disabledIn.push(file); + for (const entry of hookEntries(read.value) ?? []) + if (entry.onFailure !== 'block' && blocking.has(entryKey(entry))) + failOpen.push({ file, entry }); + } + return { disabledIn, failOpen }; +} + +/** Does either setting fail `status --strict`? Both do: each leaves a guard off. */ +export function hookGuardSettingsFail(g: HookGuardSettings): boolean { + return g.disabledIn.length > 0 || g.failOpen.length > 0; +} + +/** + * The guard-settings part of `status`'s HOOKS note, or `null` when neither + * setting is found. File names are pharn's constants; hooks go through + * `displayHook`. + */ +export function hookGuardSettingsLines(g: HookGuardSettings): string[] | null { + if (!hookGuardSettingsFail(g)) return null; + const lines: string[] = []; + if (g.disabledIn.length > 0) + lines.push( + ' HOOKS OFF — "disableAllHooks": true stops every hook,', + ' both PHARN write guards included, for anyone who loads the file.', + ' settings.local.json overrides settings.json only for its own user;', + ' teammates and CI load settings.json.', + ...g.disabledIn.map((file) => ` ${file} sets "disableAllHooks": true`), + ' Remove the key, or set it to false.', + ); + if (g.failOpen.length > 0) { + if (lines.length > 0) lines.push(''); + lines.push( + ' FAIL-OPEN — upstream wires these guards with "onFailure": "block" and your', + ' line does not, so a guard that cannot start, crashes or times out lets the', + ' write through:', + ...g.failOpen.map( + ({ file, entry }) => ` ${file}: ${displayHook(entry)}`, + ), + ' Add "onFailure": "block" to each of these hooks.', + ); + } + return lines; +} + +/** What `status`'s HOOKS note says about what it cannot see. */ +export const HOOK_SETTINGS_SCOPE_LINES = [ + ` ~/.claude/settings.json (user level) is not read, so "disableAllHooks" set there is not seen.`, + ' This is a report, not a guard: a setting added after this run is not seen.', +]; + /** * Does this diff fail `status --strict`? A hook wired only locally IS wired for * this user, so `local-only` passes. @@ -344,14 +465,17 @@ const MAX_LINE = 300; /** * One display line: `Event [matcher]: `, `args` only when - * present, so exec and shell forms print differently and a pasted line - * satisfies the check. Escaped and capped at MAX_LINE characters. + * present, so exec and shell forms print differently, and `onFailure` only + * when set, so a pasted line satisfies both checks. Escaped and capped at + * MAX_LINE characters. */ export function displayHook(e: HookEntry): string { - const hook = - e.args.length > 0 - ? { type: 'command', command: e.command, args: e.args } - : { type: 'command', command: e.command }; + const hook = { + type: 'command', + command: e.command, + ...(e.args.length > 0 ? { args: e.args } : {}), + ...(e.onFailure !== undefined ? { onFailure: e.onFailure } : {}), + }; const where = e.matcher ? `${e.event} [${e.matcher}]` : e.event; const line = `${escapeUnsafe(where)}: ${escapeUnsafe(JSON.stringify(hook))}`; return line.length > MAX_LINE ? `${line.slice(0, MAX_LINE)}…` : line; diff --git a/src/lib/status-report.ts b/src/lib/status-report.ts index 3bf1cefc..be1f63ff 100644 --- a/src/lib/status-report.ts +++ b/src/lib/status-report.ts @@ -1,7 +1,9 @@ import type { InstallDiff } from './diff.js'; -import { hookWiringFails } from './hook-wiring.js'; +import { hookGuardSettingsFail, hookWiringFails } from './hook-wiring.js'; import type { + FailOpenHook, HookEntry, + HookGuardSettings, HookReplacement, HookWiringDiff, } from './hook-wiring.js'; @@ -76,6 +78,11 @@ export interface StatusReport { // Present ONLY when non-empty: missing hooks the project wires in another // spelling — replace, not add. replace?: HookReplacement[]; + // Present ONLY when non-empty: project settings files that set + // `"disableAllHooks": true`, and project wirings of an upstream + // `"onFailure": "block"` hook that lack it. Both fail `--strict`. + disabledIn?: string[]; + failOpen?: FailOpenHook[]; } | null; // null when the config carries no `models` block. models: { @@ -110,6 +117,9 @@ export interface StatusReportInput { source: SourceSummary; drift: { hooks: HookWiringDiff; + // hookGuardSettings: what switches the wired guards off or fail-open. + // The clone path always sets it; absent reads as nothing found. + guards?: HookGuardSettings; unknown: readonly UnknownCapability[]; // null when they could not be determined (see StatusReport.orphans). orphans: readonly Orphan[] | null; @@ -130,10 +140,11 @@ export function strictFails(input: { outdated: boolean; diff?: InstallDiff; hooks?: HookWiringDiff; + guards?: HookGuardSettings; // A declared surface upstream ships no file for: the install is incomplete. absentUpstream?: readonly AbsentSurface[]; }): boolean { - const { outdated, diff, hooks, absentUpstream } = input; + const { outdated, diff, hooks, guards, absentUpstream } = input; return ( outdated || (absentUpstream !== undefined && absentUpstream.length > 0) || @@ -143,7 +154,9 @@ export function strictFails(input: { diff.unreadable.length > 0)) || // The diff's STATUS, not the note's presence: a hook wired only in // settings.local.json is noted, and is still wired. - (hooks !== undefined && hookWiringFails(hooks)) + (hooks !== undefined && hookWiringFails(hooks)) || + // A wired guard that never runs, or lets a write through when it fails. + (guards !== undefined && hookGuardSettingsFail(guards)) ); } @@ -240,6 +253,12 @@ export function buildStatusReport(input: StatusReportInput): StatusReport { ...(drift.hooks.replace?.length ? { replace: drift.hooks.replace } : {}), + ...(drift.guards?.disabledIn.length + ? { disabledIn: drift.guards.disabledIn } + : {}), + ...(drift.guards?.failOpen.length + ? { failOpen: drift.guards.failOpen } + : {}), }, models: modelsReport(config.models), unknownCapabilities: @@ -273,6 +292,7 @@ export function buildStatusReport(input: StatusReportInput): StatusReport { outdated, diff: drift?.diff, hooks: drift?.hooks, + guards: drift?.guards, absentUpstream: drift?.absentUpstream, }), }, diff --git a/tests/commands/status.test.ts b/tests/commands/status.test.ts index 96d97838..6f3a13ca 100644 --- a/tests/commands/status.test.ts +++ b/tests/commands/status.test.ts @@ -705,6 +705,115 @@ describe('pharn status, end to end', () => { expect(report.hooks?.status).toBe('local-only'); }); + // CORE-594: settings that switch the wired guards off, or make one fail + // open, while the wiring itself matches upstream. + it('HOOKS names each project settings file that sets disableAllHooks, and --strict exits 1; a file without it passes', async () => { + await installFresh(); + const withKey = (value: unknown): string => + JSON.stringify({ + ...(JSON.parse(HOOK_SETTINGS) as object), + disableAllHooks: value, + }); + + // Negative control: the key absent, or false, is no finding. + write(SETTINGS, withKey(false)); + expect(await status({ strict: true })).toBeNull(); + expect(noteTitles()).not.toContain('HOOKS'); + expect((await statusJson()).report.hooks).not.toHaveProperty('disabledIn'); + + write(SETTINGS, withKey(true)); + write('.claude/settings.local.json', '{"disableAllHooks": true}\n'); + expect(await status()).toBeNull(); + const hooks = stripVTControlCharacters(note('HOOKS')); + expect(hooks).toContain('HOOKS OFF'); + expect(hooks).toContain( + '.claude/settings.json sets "disableAllHooks": true', + ); + expect(hooks).toContain( + '.claude/settings.local.json sets "disableAllHooks": true', + ); + expect(hooks).toContain( + '~/.claude/settings.json (user level) is not read, so "disableAllHooks" set there is not seen.', + ); + expect(hooks).toContain( + 'This is a report, not a guard: a setting added after this run is not seen.', + ); + // The wiring itself matches: no unwired-hook part. + expect(hooks).not.toContain('Upstream wires'); + + expect(await status({ strict: true })).toBe(1); + const { report, exitCode } = await statusJson({ strict: true }); + expect(report.hooks).toMatchObject({ + status: 'match', + disabledIn: ['.claude/settings.json', '.claude/settings.local.json'], + }); + expect(report.strict).toEqual({ enabled: true, failed: true }); + expect(exitCode).toBe(1); + + // --no-drift reads no settings file: only the version is checked. + expect(await status({ drift: false, strict: true })).toBeNull(); + }); + + it('HOOKS reports a guard wired without the "onFailure": "block" upstream gives it, and --strict exits 1', async () => { + const blocking = JSON.stringify({ + hooks: { + PreToolUse: [ + { + matcher: 'Write', + hooks: [ + { + type: 'command', + command: 'node .claude/hooks/guard.cjs', + onFailure: 'block', + }, + ], + }, + ], + }, + }); + upstream.tree[SETTINGS] = blocking; + await installFresh(); + // A fresh install copies upstream's wiring verbatim: fail-closed. + expect(await status({ strict: true })).toBeNull(); + expect(noteTitles()).not.toContain('HOOKS'); + + // The same hook, without the field: wired, but failing open. + write(SETTINGS, HOOK_SETTINGS); + expect(await status()).toBeNull(); + const hooks = stripVTControlCharacters(note('HOOKS')); + expect(hooks).toContain('FAIL-OPEN'); + expect(hooks).toContain( + '.claude/settings.json: PreToolUse [Write]: {"type":"command","command":"node .claude/hooks/guard.cjs"}', + ); + expect(hooks).toContain('Add "onFailure": "block" to each of these hooks.'); + expect(hooks).toContain('~/.claude/settings.json (user level) is not read'); + expect(hooks).not.toContain('HOOKS OFF'); + expect(await status({ strict: true })).toBe(1); + const { report } = await statusJson({ strict: true }); + expect(report.hooks).toMatchObject({ + status: 'match', + failOpen: [ + { + file: '.claude/settings.json', + entry: { + event: 'PreToolUse', + matcher: 'Write', + command: 'node .claude/hooks/guard.cjs', + args: [], + }, + }, + ], + }); + + // Unwired altogether: the paste-ready line carries the field. + write(SETTINGS, '{}\n'); + expect(await status()).toBeNull(); + expect(note('HOOKS')).toContain( + 'PreToolUse [Write]: {"type":"command","command":"node .claude/hooks/guard.cjs","onFailure":"block"}', + ); + expect(note('HOOKS')).not.toContain('FAIL-OPEN'); + }); + it('ORPHANED names a recorded file upstream stopped shipping — also from a store stamped for another state — and only with a usable store', async () => { await installWithOrphan(); expect(await status()).toBeNull(); diff --git a/tests/hook-wiring.test.ts b/tests/hook-wiring.test.ts index d5e440c3..18bcd63a 100644 --- a/tests/hook-wiring.test.ts +++ b/tests/hook-wiring.test.ts @@ -7,7 +7,11 @@ import { diffHookWiring, displayHook, freshSettingsHookLines, + HOOK_SETTINGS_SCOPE_LINES, hookEntries, + hookGuardSettings, + hookGuardSettingsFail, + hookGuardSettingsLines, hookWiringFails, hookWiringLines, preservedSettingsHookLines, @@ -1117,3 +1121,304 @@ describe('freshSettingsHookLines', () => { expect(head).toContain('a\\u001bb is a symbolic link'); }); }); + +// CORE-594: two settings leave the guards off, or failing open, while the +// wiring compared above still looks complete. Neither is part of the textual +// key, so `diffHookWiring` alone reported `match` for both. +const GUARD = + 'node "${CLAUDE_PROJECT_DIR}"/.claude/hooks/protect-trusted-paths.cjs'; +const STOP_ARGS = [ + '${CLAUDE_PROJECT_DIR}/.claude/hooks/require-loop-record.cjs', +]; + +/** A settings object: the PreToolUse guard (onFailure as given) and the Stop hook. */ +function guarded(onFailure?: unknown, extra: Record = {}) { + return { + ...extra, + hooks: { + PreToolUse: [ + { + matcher: 'Write|Edit', + hooks: [ + { + type: 'command', + command: GUARD, + ...(onFailure === undefined ? {} : { onFailure }), + }, + ], + }, + ], + Stop: [ + { hooks: [{ type: 'command', command: 'node', args: STOP_ARGS }] }, + ], + }, + }; +} + +describe('hookEntries — onFailure', () => { + const tmp = useTmpDir(); + + it('keeps "onFailure": "block" and drops any other value', () => { + const [blocking] = hookEntries(guarded('block'))!; + expect(blocking).toEqual({ + event: 'PreToolUse', + matcher: 'Write|Edit', + command: GUARD, + args: [], + onFailure: 'block', + }); + for (const other of [undefined, 'continue', true, 'BLOCK']) + expect(hookEntries(guarded(other))![0]).not.toHaveProperty('onFailure'); + }); + + it('is not part of the textual key: a guard without it still matches', () => { + const repo = join(tmp.path(), 'repo'); + const proj = join(tmp.path(), 'proj'); + mkdirSync(join(repo, '.claude'), { recursive: true }); + mkdirSync(join(proj, '.claude'), { recursive: true }); + writeFileSync( + join(repo, '.claude/settings.json'), + JSON.stringify(guarded('block')), + ); + writeFileSync( + join(proj, '.claude/settings.json'), + JSON.stringify(guarded()), + ); + expect(diffHookWiring(repo, proj)).toEqual({ + status: 'match', + missing: [], + }); + }); +}); + +describe('hookGuardSettings', () => { + const tmp = useTmpDir(); + let n = 0; + + // A fresh repo/project pair per call: one test makes several. + function setup( + upstream: unknown, + project: unknown | undefined, + local?: unknown, + ) { + n++; + const repo = join(tmp.path(), `repo${n}`); + const proj = join(tmp.path(), `proj${n}`); + mkdirSync(join(repo, '.claude'), { recursive: true }); + mkdirSync(join(proj, '.claude'), { recursive: true }); + const put = (file: string, v: unknown) => + writeFileSync(file, typeof v === 'string' ? v : JSON.stringify(v)); + if (upstream !== undefined) + put(join(repo, '.claude/settings.json'), upstream); + if (project !== undefined) + put(join(proj, '.claude/settings.json'), project); + if (local !== undefined) + put(join(proj, '.claude/settings.local.json'), local); + return hookGuardSettings(repo, proj); + } + + const CLEAN = { disabledIn: [], failOpen: [] }; + + it('names each project settings file that sets "disableAllHooks": true, settings.json first', () => { + const on = { disableAllHooks: true }; + expect(setup(guarded('block'), guarded('block', on)).disabledIn).toEqual([ + '.claude/settings.json', + ]); + expect(setup(guarded('block'), undefined, on).disabledIn).toEqual([ + '.claude/settings.local.json', + ]); + expect(setup(guarded('block'), guarded('block', on), on)).toEqual({ + disabledIn: ['.claude/settings.json', '.claude/settings.local.json'], + failOpen: [], + }); + // Project-local: reported even when upstream wires nothing at all. + expect(setup(undefined, on).disabledIn).toEqual(['.claude/settings.json']); + }); + + it('negative control: a file without the key, or with any value but true, passes', () => { + expect(setup(guarded('block'), guarded('block'))).toEqual(CLEAN); + for (const value of [false, 'true', 1, null]) + expect( + setup(guarded('block'), guarded('block', { disableAllHooks: value })), + ).toEqual(CLEAN); + // A nested key is not the setting. + expect( + setup(guarded('block'), { hooks: { disableAllHooks: true } }), + ).toEqual(CLEAN); + }); + + it('reports a guard upstream wires with "onFailure": "block" that a project file wires without it', () => { + const got = setup(guarded('block'), guarded()); + expect(got.disabledIn).toEqual([]); + expect(got.failOpen).toEqual([ + { + file: '.claude/settings.json', + entry: { + event: 'PreToolUse', + matcher: 'Write|Edit', + command: GUARD, + args: [], + }, + }, + ]); + expect(setup(guarded('block'), guarded('continue')).failOpen).toHaveLength( + 1, + ); + }); + + it('names settings.local.json when that is the file lacking it, and every lacking line', () => { + const got = setup(guarded('block'), guarded('block'), guarded()); + expect(got.failOpen.map((f) => f.file)).toEqual([ + '.claude/settings.local.json', + ]); + expect( + setup(guarded('block'), guarded(), guarded()).failOpen.map((f) => f.file), + ).toEqual(['.claude/settings.json', '.claude/settings.local.json']); + }); + + it('negative control: no finding when the project carries it, or upstream does not', () => { + expect(setup(guarded('block'), guarded('block'))).toEqual(CLEAN); + // Upstream wires the guard without the field: nothing to compare against. + expect(setup(guarded(), guarded())).toEqual(CLEAN); + // The Stop hook carries no onFailure upstream, so it is never reported. + expect( + setup(guarded('block'), guarded('block')).failOpen.some( + (f) => f.entry.event === 'Stop', + ), + ).toBe(false); + }); + + it('leaves an unwired or differently spelled guard to diffHookWiring', () => { + expect(setup(guarded('block'), {})).toEqual(CLEAN); + const relative = guarded(); + relative.hooks.PreToolUse[0]!.hooks[0]!.command = + 'node .claude/hooks/protect-trusted-paths.cjs'; + expect(setup(guarded('block'), relative)).toEqual(CLEAN); + }); + + it('reads nothing from an absent or unreadable file, and an unreadable upstream reports no fail-open guard', () => { + expect(setup(guarded('block'), undefined)).toEqual(CLEAN); + expect(setup(guarded('block'), '{not json', '[1,')).toEqual(CLEAN); + expect(setup('{not json', guarded())).toEqual(CLEAN); + expect(setup(guarded('block'), '"just a string"')).toEqual(CLEAN); + }); + + it('refuses to read through a symlinked project .claude directory', () => { + const repo = join(tmp.path(), 'repo'); + const real = join(tmp.path(), 'real'); + const proj = join(tmp.path(), 'proj'); + mkdirSync(join(repo, '.claude'), { recursive: true }); + mkdirSync(real, { recursive: true }); + mkdirSync(proj, { recursive: true }); + writeFileSync( + join(repo, '.claude/settings.json'), + JSON.stringify(guarded('block')), + ); + writeFileSync( + join(real, 'settings.json'), + JSON.stringify(guarded(undefined, { disableAllHooks: true })), + ); + symlinkSync(real, join(proj, '.claude')); + expect(hookGuardSettings(repo, proj)).toEqual(CLEAN); + }); +}); + +describe('hookGuardSettingsLines', () => { + const failOpen = { + file: '.claude/settings.json', + entry: { event: 'PreToolUse', matcher: 'Write', command: GUARD, args: [] }, + }; + + it('is null, and never fails --strict, when neither setting is found', () => { + const clean = { disabledIn: [], failOpen: [] }; + expect(hookGuardSettingsLines(clean)).toBeNull(); + expect(hookGuardSettingsFail(clean)).toBe(false); + }); + + it('names each file setting disableAllHooks, and fails --strict', () => { + const g = { + disabledIn: ['.claude/settings.json', '.claude/settings.local.json'], + failOpen: [], + }; + expect(hookGuardSettingsFail(g)).toBe(true); + const text = hookGuardSettingsLines(g)!.join('\n'); + expect(text).toContain('HOOKS OFF'); + expect(text).toContain('both PHARN write guards included'); + expect(text).toContain( + ' .claude/settings.json sets "disableAllHooks": true', + ); + expect(text).toContain( + ' .claude/settings.local.json sets "disableAllHooks": true', + ); + expect(text).toContain('Remove the key, or set it to false.'); + expect(text).not.toContain('FAIL-OPEN'); + }); + + it('lists each fail-open line with its file through displayHook, and fails --strict', () => { + const g = { disabledIn: [], failOpen: [failOpen] }; + expect(hookGuardSettingsFail(g)).toBe(true); + const text = hookGuardSettingsLines(g)!.join('\n'); + expect(text).toContain('FAIL-OPEN'); + expect(text).toContain( + ` .claude/settings.json: ${displayHook(failOpen.entry)}`, + ); + expect(text).toContain('Add "onFailure": "block" to each of these hooks.'); + expect(text).not.toContain('HOOKS OFF'); + }); + + it('separates the two parts with a blank line when both hold', () => { + const lines = hookGuardSettingsLines({ + disabledIn: ['.claude/settings.json'], + failOpen: [failOpen], + })!; + const blank = lines.indexOf(''); + expect(blank).toBeGreaterThan(0); + expect(lines[blank + 1]).toContain('FAIL-OPEN'); + }); + + it('the scope lines say the user-level file is unread and that this is a report, not a guard', () => { + const text = HOOK_SETTINGS_SCOPE_LINES.join('\n'); + expect(text).toContain('~/.claude/settings.json (user level) is not read'); + expect(text).toContain('This is a report, not a guard'); + }); +}); + +describe('displayHook — onFailure', () => { + const tmp = useTmpDir(); + + it('prints "onFailure" only when set, so a pasted guard is wired and fails closed', () => { + const entry = hookEntries(guarded('block'))![0]!; + expect(displayHook(entry)).toBe( + `PreToolUse [Write|Edit]: ${JSON.stringify({ type: 'command', command: GUARD, onFailure: 'block' })}`, + ); + expect(displayHook(hookEntries(guarded())![0]!)).not.toContain('onFailure'); + + // Round trip: upstream's missing lines, pasted, satisfy both checks. + const repo = join(tmp.path(), 'repo'); + const proj = join(tmp.path(), 'proj'); + mkdirSync(join(repo, '.claude'), { recursive: true }); + mkdirSync(join(proj, '.claude'), { recursive: true }); + writeFileSync( + join(repo, '.claude/settings.json'), + JSON.stringify(guarded('block')), + ); + const hooks: Record = {}; + for (const line of diffHookWiring(repo, proj).missing.map(displayHook)) { + const head = line.slice(0, line.indexOf(': {')); + const m = /^(\w+)(?: \[(.*)\])?$/.exec(head)!; + const hook: unknown = JSON.parse(line.slice(line.indexOf(': {') + 2)); + (hooks[m[1]!] ??= []).push( + m[2] ? { matcher: m[2], hooks: [hook] } : { hooks: [hook] }, + ); + } + writeFileSync( + join(proj, '.claude/settings.json'), + JSON.stringify({ hooks }), + ); + expect(diffHookWiring(repo, proj).status).toBe('match'); + expect(hookGuardSettings(repo, proj)).toEqual({ + disabledIn: [], + failOpen: [], + }); + }); +}); diff --git a/tests/release-consistency.test.ts b/tests/release-consistency.test.ts index bb3cb42d..970b51ae 100644 --- a/tests/release-consistency.test.ts +++ b/tests/release-consistency.test.ts @@ -98,6 +98,7 @@ const KNOWN_TAGS: readonly string[] = [ 'v0.21.5', 'v0.21.6', 'v0.21.7', + 'v0.22.0', ]; // Sections with no tag at all, and so no link: 0.8.0 was bumped and superseded // by 0.9.0 on the same day, never tagged or published; 0.2.0 / 0.1.0 predate diff --git a/tests/status-report.test.ts b/tests/status-report.test.ts index 46cc3eb5..952c1a73 100644 --- a/tests/status-report.test.ts +++ b/tests/status-report.test.ts @@ -1,6 +1,9 @@ import { describe, expect, it } from 'vitest'; import type { InstallDiff } from '../src/lib/diff.js'; -import type { HookWiringDiff } from '../src/lib/hook-wiring.js'; +import type { + HookGuardSettings, + HookWiringDiff, +} from '../src/lib/hook-wiring.js'; import type { InstallSource } from '../src/lib/release.js'; import { buildStatusReport, @@ -531,6 +534,80 @@ describe('strictFails', () => { hooks: { status: 'local-only', missing: [], localOnly: [] }, }), ).toBe(false); + }); // CORE-594: either setting leaves a wired guard off, so either fails it. + it('fails on a settings file that sets disableAllHooks, or a fail-open guard', () => { + const entry = { + event: 'PreToolUse', + matcher: 'Write', + command: 'g', + args: [], + }; + expect( + strictFails({ + ...base, + guards: { disabledIn: ['.claude/settings.json'], failOpen: [] }, + }), + ).toBe(true); + expect( + strictFails({ + ...base, + guards: { + disabledIn: [], + failOpen: [{ file: '.claude/settings.local.json', entry }], + }, + }), + ).toBe(true); + // Negative control: neither found. + expect( + strictFails({ ...base, guards: { disabledIn: [], failOpen: [] } }), + ).toBe(false); + }); +}); + +describe('buildStatusReport — hook guard settings', () => { + const entry = { + event: 'PreToolUse', + matcher: 'Write', + command: 'g', + args: [], + }; + const build = (guards: HookGuardSettings | undefined, strict = false) => + buildStatusReport( + input({ + strict, + drift: { + ...SURFACES, + diff: CLEAN, + hooks: HOOKS_OK, + guards, + unknown: [], + orphans: [], + }, + }), + ); + + it('adds hooks.disabledIn and hooks.failOpen only when non-empty, failing --strict', () => { + const failOpen = [{ file: '.claude/settings.json', entry }]; + const r = build( + { disabledIn: ['.claude/settings.local.json'], failOpen }, + true, + ); + expect(r.hooks).toMatchObject({ + status: 'match', + disabledIn: ['.claude/settings.local.json'], + failOpen, + }); + expect(r.strict).toEqual({ enabled: true, failed: true }); + }); + + it('keeps the schemaVersion 1 bytes when neither is found', () => { + const clean = build({ disabledIn: [], failOpen: [] }, true); + expect(clean.hooks).not.toHaveProperty('disabledIn'); + expect(clean.hooks).not.toHaveProperty('failOpen'); + expect(clean.strict.failed).toBe(false); + expect(serializeStatusReport(clean)).toBe( + serializeStatusReport(build(undefined, true)), + ); }); });