@webpieces/ai-hook-rules 0.4.584 → 0.4.588
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +27 -8
- package/package.json +2 -2
- package/src/adapters/hook-core.js +33 -15
- package/src/adapters/hook-core.js.map +1 -1
- package/src/bin/guarantee-root.d.ts +95 -0
- package/src/bin/guarantee-root.js +284 -0
- package/src/bin/guarantee-root.js.map +1 -0
- package/src/bin/hook-registration.d.ts +134 -0
- package/src/bin/hook-registration.js +320 -0
- package/src/bin/hook-registration.js.map +1 -0
- package/src/bin/l0-allowlist.js +1 -1
- package/src/bin/l0-allowlist.js.map +1 -1
- package/src/bin/setup.d.ts +1 -15
- package/src/bin/setup.js +84 -77
- package/src/bin/setup.js.map +1 -1
- package/src/bin/shim-audit-log.js +21 -4
- package/src/bin/shim-audit-log.js.map +1 -1
- package/src/bin/shim.d.ts +1 -1
- package/src/bin/shim.js +85 -13
- package/src/bin/shim.js.map +1 -1
- package/src/bin/upgrade-shim.js +48 -14
- package/src/bin/upgrade-shim.js.map +1 -1
- package/src/core/decision-log.d.ts +6 -2
- package/src/core/decision-log.js +12 -7
- package/src/core/decision-log.js.map +1 -1
- package/src/core/l0-matrix.js +18 -11
- package/src/core/l0-matrix.js.map +1 -1
- package/src/core/log-stream.d.ts +72 -0
- package/src/core/log-stream.js +104 -0
- package/src/core/log-stream.js.map +1 -0
- package/src/core/main-sync-log.d.ts +2 -1
- package/src/core/main-sync-log.js +9 -5
- package/src/core/main-sync-log.js.map +1 -1
- package/src/core/main-sync-refresh.d.ts +2 -1
- package/src/core/main-sync-refresh.js +2 -1
- package/src/core/main-sync-refresh.js.map +1 -1
- package/src/core/rejection-log.js +3 -2
- package/src/core/rejection-log.js.map +1 -1
- package/templates/ai-hook.sh +51 -10
- package/templates/guarantee-root.sh +110 -0
|
@@ -0,0 +1,284 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.GUARANTEE_ROOT_MARKER = void 0;
|
|
4
|
+
exports.guaranteeRootPath = guaranteeRootPath;
|
|
5
|
+
exports.writeGuaranteeRoot = writeGuaranteeRoot;
|
|
6
|
+
exports.renderGuaranteeRoot = renderGuaranteeRoot;
|
|
7
|
+
exports.committedGuaranteeRootStale = committedGuaranteeRootStale;
|
|
8
|
+
const tslib_1 = require("tslib");
|
|
9
|
+
const fs = tslib_1.__importStar(require("fs"));
|
|
10
|
+
const path = tslib_1.__importStar(require("path"));
|
|
11
|
+
const to_error_1 = require("../core/to-error");
|
|
12
|
+
/**
|
|
13
|
+
* L-1 — the layer BELOW L0: guarantee the shell stays somewhere the RELATIVE guard hooks can launch.
|
|
14
|
+
*
|
|
15
|
+
* ─── Why a layer below L0 exists at all ────────────────────────────────────────────────────────────
|
|
16
|
+
* From the Claude Code hooks reference: exit 2 is the blocking channel, exit 0 carries the JSON
|
|
17
|
+
* decision, and ANY OTHER exit is a "non-blocking error. Execution continues; the action proceeds" —
|
|
18
|
+
* including "File missing or not executable: Error logged; tool proceeds."
|
|
19
|
+
*
|
|
20
|
+
* A HOOK THAT FAILS TO LAUNCH IS A SILENT ALLOW. Not a block, not an error the AI sees.
|
|
21
|
+
*
|
|
22
|
+
* Every layer L0-L4 assumes the hook process ran at all. This file is what makes that assumption true.
|
|
23
|
+
*
|
|
24
|
+
* ─── Why the guard hooks become RELATIVE ───────────────────────────────────────────────────────────
|
|
25
|
+
* `.claude/settings.json` registers hooks as `sh "$CLAUDE_PROJECT_DIR/.claude/webpieces/ai-hook.sh"`,
|
|
26
|
+
* and `$CLAUDE_PROJECT_DIR` NEVER moves — proven from four separate worktrees' own logs, every line
|
|
27
|
+
* reading `root=<worktree> projectDir=<primary>`. So every tree is governed by the PRIMARY's shim and
|
|
28
|
+
* the PRIMARY's binary, forever: a worktree can never be judged by the release its own branch pins, and
|
|
29
|
+
* measuring one tree while running another's binary is the non-convergent "two-tree straddle" recorded
|
|
30
|
+
* in shim.ts (an agent gave up after four cures).
|
|
31
|
+
*
|
|
32
|
+
* The fix is to re-root the WHOLE hook, not to measure differently. The hooks reference says "the hook
|
|
33
|
+
* runs in the cwd value from the JSON input", so a RELATIVE command resolves against the tool call's
|
|
34
|
+
* own tree — each tree runs its own shim, its own binary, its own pin. One version, one tree.
|
|
35
|
+
*
|
|
36
|
+
* That is only safe if the relative path is guaranteed to resolve. Hence this file.
|
|
37
|
+
*
|
|
38
|
+
* ─── Why this is a SEPARATE checked-in file from ai-hook.sh ────────────────────────────────────────
|
|
39
|
+
* 1. It is the ONE file that must stay $CLAUDE_PROJECT_DIR-anchored, so it is the one file that cannot
|
|
40
|
+
* be upgraded per-tree. Its surface is therefore kept minimal: a path check. No drift scraper, no
|
|
41
|
+
* allowlist, no config load, no binary — nothing that needs to change often.
|
|
42
|
+
* 2. Its stability profile is the OPPOSITE of ai-hook.sh's. The shim changes most releases; a `cd`
|
|
43
|
+
* validator should converge and stop. Sharing one file forces the stable half to inherit the
|
|
44
|
+
* volatile half's churn — which is today's problem, one level up.
|
|
45
|
+
* 3. A NEW FILE IS INVISIBLE TO OLD RELEASES; A NEW FLAG BREAKS THEM. Measured 2026-08-06: registering
|
|
46
|
+
* `ai-hook.sh --force-root` made the installed shim read `--force-root` as a BIN NAME, fail to find
|
|
47
|
+
* it, and emit fault U — denying `ls` and the very `cd` that would have fixed it:
|
|
48
|
+
* 16:32:20 --force-root Bash tree=primary fault=U DENY-UNDECLARED ls
|
|
49
|
+
* A separate file is simply not registered until a release that ships it, so old releases are safe.
|
|
50
|
+
*
|
|
51
|
+
* ─── The invariant, maintained inductively ─────────────────────────────────────────────────────────
|
|
52
|
+
* A session always starts at a tree root (primary for the coordinator, the worktree for a subagent).
|
|
53
|
+
* The only thing that moves the shell is a `cd`, and (measured 2026-08-02, effective-tree.ts) a `cd`
|
|
54
|
+
* that stays INSIDE the workspace PERSISTS to later calls, while a `cd` that LEAVES it is RESET by the
|
|
55
|
+
* harness before the next call.
|
|
56
|
+
*
|
|
57
|
+
* If every `cd` that would leave a tree root is refused, "the shell is at a tree root" is an
|
|
58
|
+
* INDUCTIVE INVARIANT — so this hook never inspects cwd as a state, only the command.
|
|
59
|
+
*
|
|
60
|
+
* That is also why it is registered for Bash ALONE: no other tool can move the shell.
|
|
61
|
+
*
|
|
62
|
+
* ─── The predicate, in three tests ─────────────────────────────────────────────────────────────────
|
|
63
|
+
* 1. destination holds `.git` → ALLOW. Complete by construction: the primary clone has a .git DIR,
|
|
64
|
+
* every linked worktree (nested or sibling) has a .git FILE, and a nested foreign clone under
|
|
65
|
+
* repositories/** has its own .git DIR. The first two are where the relative hooks launch; the
|
|
66
|
+
* third is a tree we deliberately do not govern.
|
|
67
|
+
* 2. destination is OUTSIDE $CLAUDE_PROJECT_DIR → ALLOW. The harness resets it before the next call,
|
|
68
|
+
* so at most ONE call runs at a path we do not govern — and there is nothing there to guard.
|
|
69
|
+
* 3. otherwise (inside a governed tree, no .git — `tools/`, `dataform/`, `packages/…`) → DENY. This
|
|
70
|
+
* is the only region that is both STICKY and UNGUARDED.
|
|
71
|
+
*
|
|
72
|
+
* It reads NO config. `excludePaths` governs which FILES are enforced, not whether the hook may run,
|
|
73
|
+
* and it cannot be parsed here anyway (this is sh, pre-config, pre-binary). The one measured divergence
|
|
74
|
+
* is `tools/**`: exempt by excludePaths, denied here — correctly, because the real hooks genuinely
|
|
75
|
+
* cannot launch there and we genuinely want them to. Cost: 4 calls in a 2,236-call sample.
|
|
76
|
+
*
|
|
77
|
+
* ─── Nothing to recover from ───────────────────────────────────────────────────────────────────────
|
|
78
|
+
* A denied `cd` NEVER EXECUTES — PreToolUse denies the whole tool call before the shell moves — so the
|
|
79
|
+
* shell is still at a root. There is no bad state and no cure command that needs allowlisting, which is
|
|
80
|
+
* what keeps this hook from ever being able to wedge a session.
|
|
81
|
+
*
|
|
82
|
+
* Measured cost of the deny: 47 of 2,236 real Bash calls (2.10%), or 9.7% of all `cd` commands.
|
|
83
|
+
*/
|
|
84
|
+
exports.GUARANTEE_ROOT_MARKER = '.claude/webpieces/guarantee-root.sh';
|
|
85
|
+
// webpieces-disable no-function-outside-class -- L-1 sibling of shim.ts's shimPath(); this module is deliberately dependency-free module-scope functions so it stays callable from a tree too broken to build a DI container
|
|
86
|
+
function guaranteeRootPath(projectRoot) {
|
|
87
|
+
return path.join(projectRoot, '.claude', 'webpieces', 'guarantee-root.sh');
|
|
88
|
+
}
|
|
89
|
+
/**
|
|
90
|
+
* Write (or overwrite) the committed L-1 hook. Idempotent — the installer and `wp-upgrade-shim` both
|
|
91
|
+
* call it, and re-running either simply re-arms the file. Twin of setup.ts's writeShim().
|
|
92
|
+
*/
|
|
93
|
+
// webpieces-disable no-function-outside-class -- L-1 sibling of guaranteeRootPath(); this module is deliberately dependency-free module-scope functions
|
|
94
|
+
function writeGuaranteeRoot(projectRoot) {
|
|
95
|
+
const target = guaranteeRootPath(projectRoot);
|
|
96
|
+
fs.mkdirSync(path.dirname(target), { recursive: true });
|
|
97
|
+
fs.writeFileSync(target, renderGuaranteeRoot(), { mode: 0o755 });
|
|
98
|
+
// writeFileSync's mode is only applied when creating the file; force it on overwrite too.
|
|
99
|
+
fs.chmodSync(target, 0o755);
|
|
100
|
+
}
|
|
101
|
+
// Deny REASON constraint, inherited from the shim: the text is interpolated into a `REASON="…"` shell
|
|
102
|
+
// assignment and then printf'd into a JSON string, so it may contain NO double quotes and NO
|
|
103
|
+
// backslashes. Single quotes only — do not "improve" them.
|
|
104
|
+
const DENY_NOT_LITERAL = 'This cd target is not a literal path, so the guards cannot tell where the shell will end up. '
|
|
105
|
+
+ 'Use a literal absolute path: cd /abs/path && <your command>. '
|
|
106
|
+
+ 'A $VAR, ~, $(...) or backtick is never expanded by the guard.';
|
|
107
|
+
const DENY_NO_TARGET = 'A bare cd (or cd -) moves the shell somewhere the guards cannot predict - a bare cd goes to '
|
|
108
|
+
+ 'your home directory, where the webpieces hooks do not exist and every later tool call would '
|
|
109
|
+
+ 'run UNGUARDED. Name the directory: cd /abs/path && <your command>.';
|
|
110
|
+
// `%s` is the destination, then the project root. Kept to one short paragraph on purpose: L0 already
|
|
111
|
+
// ran a message diet and these denies regress straight back to a wall of text if each one argues.
|
|
112
|
+
const DENY_SUBDIR = 'The webpieces guard hooks are registered RELATIVE (.claude/webpieces/ai-hook.sh) so that each '
|
|
113
|
+
+ 'git tree is governed by its own release. %s has no .claude/webpieces/ai-hook.sh, so a shell '
|
|
114
|
+
+ 'parked there launches NO hooks at all and every later tool call runs UNGUARDED - and a cd that '
|
|
115
|
+
+ 'stays inside the project PERSISTS to your next call. Run it from the tree root instead: '
|
|
116
|
+
+ 'cd %s && <your command>. Tools that take their own directory (git -C, pnpm -C, pnpm --filter, '
|
|
117
|
+
+ 'nx) need no cd at all.';
|
|
118
|
+
/**
|
|
119
|
+
* The cd audit trail. A THIRD parallel writer joins guards+rules on every Bash call, so it gets its
|
|
120
|
+
* own file under the same session/agent/hook key LogStream uses — one writer per directory, so an
|
|
121
|
+
* append can never interleave with another's (macOS PIPE_BUF is 512 bytes and real log lines exceed it).
|
|
122
|
+
*
|
|
123
|
+
* Unlike the shim's RESOLVE_LOG_DIR_SH this needs NO worktree resolution: H1 is $CLAUDE_PROJECT_DIR-
|
|
124
|
+
* anchored by definition, so the primary clone's `.webpieces` is always the right home. That is the one
|
|
125
|
+
* upside of being the hook that cannot follow the tree.
|
|
126
|
+
*
|
|
127
|
+
* Every write is swallowed and nothing ever reaches stdout — stdout is the PreToolUse decision channel
|
|
128
|
+
* and a stray byte there would corrupt allow/deny.
|
|
129
|
+
*/
|
|
130
|
+
const CD_AUDIT_SH = `# --- cd audit (best-effort; never blocks, never touches stdout) --------------------------------
|
|
131
|
+
SID="$(printf '%s' "$PAYLOAD" | sed -n 's/.*"session_id"[[:space:]]*:[[:space:]]*"\\([^"\\\\]*\\)".*/\\1/p')"
|
|
132
|
+
AID="$(printf '%s' "$PAYLOAD" | sed -n 's/.*"agent_id"[[:space:]]*:[[:space:]]*"\\([^"\\\\]*\\)".*/\\1/p')"
|
|
133
|
+
# Untrusted payload values are used as path segments, so anything outside [A-Za-z0-9._-] collapses to _
|
|
134
|
+
# and a leading dot is neutralised — ../../etc can never escape the logs directory.
|
|
135
|
+
clean() { printf '%s' "$1" | tr -c 'A-Za-z0-9._-' '_' \\
|
|
136
|
+
| sed -e 's/\\.\\{2,\\}/_/g' -e 's/^\\.\\{1,\\}/_/' | cut -c1-64; }
|
|
137
|
+
wp_cd_log() { # $1 = verdict, $2 = destination (may be empty)
|
|
138
|
+
{
|
|
139
|
+
[ -n "$CLAUDE_PROJECT_DIR" ] || return 0
|
|
140
|
+
_d="$CLAUDE_PROJECT_DIR/.webpieces/logs"
|
|
141
|
+
mkdir -p "$_d" 2>/dev/null || return 0
|
|
142
|
+
# Flat name, same scheme as LogStream.fileName(): <session>-<agent|coordinator>-guarantee-root-<base>
|
|
143
|
+
# ALWAYS prefixed; a missing session_id renders as 'unknown'. No bare-name branch anywhere.
|
|
144
|
+
_p="$(clean "\${SID:-unknown}")-$(clean "\${AID:-coordinator}")-guarantee-root-"
|
|
145
|
+
_f="$_d/\${_p}cd-audit.log"
|
|
146
|
+
_sz="$(wc -c < "$_f" 2>/dev/null | tr -d ' ')"
|
|
147
|
+
case "$_sz" in ''|*[!0-9]*) _sz=0 ;; esac
|
|
148
|
+
[ "$_sz" -gt 524288 ] && mv -f "$_f" "$_d/\${_p}cd-audit.1.log" 2>/dev/null
|
|
149
|
+
printf '%s\\t%s\\tdest=%s\\tcwd=%s\\t%s\\n' \\
|
|
150
|
+
"$(date '+%Y-%m-%dT%H:%M:%S%z' 2>/dev/null)" "$1" "$2" "$CWD" "$CMD" >> "$_f"
|
|
151
|
+
} 2>/dev/null || true
|
|
152
|
+
}
|
|
153
|
+
`;
|
|
154
|
+
// The deny boundary. Extracted for the same reason CD_AUDIT_SH and HEADER_SH are — to keep the
|
|
155
|
+
// renderer inside the 70-line method budget — and spliced back verbatim. Mirrors the shim's own emit:
|
|
156
|
+
// for Bash, permissionDecisionReason is NOT user-visible, so the red systemMessage carries the text.
|
|
157
|
+
const DENY_EMIT_SH = `wp_cd_log DENY "\${ABS:-$DEST}"
|
|
158
|
+
|
|
159
|
+
BS='\\' # one literal backslash, so the \\u001b escape never sits in this source
|
|
160
|
+
ESC="\${BS}u001b" # the 6 chars: backslash u 0 0 1 b — Claude Code parses \\u001b -> ESC
|
|
161
|
+
printf '{"systemMessage":"%s🛑 %s%s","hookSpecificOutput":{"hookEventName":"PreToolUse","permissionDecision":"deny","permissionDecisionReason":"%s"}}\\n' "\${ESC}[31;1m" "$REASON" "\${ESC}[0m" "$REASON"
|
|
162
|
+
exit 0 # the decision is carried by permissionDecision deny, not the exit code
|
|
163
|
+
`;
|
|
164
|
+
// The file's own banner. Extracted to a module const for the same reason renderShim() extracts
|
|
165
|
+
// VERSION_DRIFT_GUARD_SH — to keep the renderer inside the 80-line method budget — and spliced back
|
|
166
|
+
// in verbatim, byte for byte.
|
|
167
|
+
const HEADER_SH = `#!/bin/sh
|
|
168
|
+
# webpieces L-1 hook — GUARANTEE ROOT. Generated by renderGuaranteeRoot(); do not hand-edit.
|
|
169
|
+
#
|
|
170
|
+
# Registered ABSOLUTE in .claude/settings.json, matcher "Bash":
|
|
171
|
+
# sh "$CLAUDE_PROJECT_DIR/.claude/webpieces/guarantee-root.sh"
|
|
172
|
+
#
|
|
173
|
+
# It exists because the GUARD hooks beside it are registered RELATIVE, so that each git tree is
|
|
174
|
+
# governed by its own @webpieces release. A relative hook that cannot resolve does not block — the
|
|
175
|
+
# harness logs it and lets the tool call proceed UNGUARDED. This file makes that unreachable by
|
|
176
|
+
# refusing any cd that would park the shell where the relative hooks cannot launch.
|
|
177
|
+
#
|
|
178
|
+
# Three tests, no config, no binary, no network:
|
|
179
|
+
# 1. destination holds .git -> ALLOW (tree root, worktree, or foreign clone)
|
|
180
|
+
# 2. destination is outside $CLAUDE_PROJECT_DIR -> ALLOW (the harness resets the cwd next call)
|
|
181
|
+
# 3. otherwise -> DENY (sticky AND unguarded)
|
|
182
|
+
#
|
|
183
|
+
# A denied cd never runs, so the shell never leaves the root and there is nothing to recover from.
|
|
184
|
+
`;
|
|
185
|
+
/**
|
|
186
|
+
* The POSIX-sh source. Byte-identical to `templates/guarantee-root.sh`, locked by a unit test, exactly
|
|
187
|
+
* as renderShim()/templates/ai-hook.sh are — so the file a consumer commits and the file this release
|
|
188
|
+
* expects can never silently diverge.
|
|
189
|
+
*/
|
|
190
|
+
// webpieces-disable no-function-outside-class -- L-1 twin of shim.ts's renderShim(), byte-locked to templates/guarantee-root.sh; module-scope for the same dependency-free reason
|
|
191
|
+
function renderGuaranteeRoot() {
|
|
192
|
+
return `${HEADER_SH}
|
|
193
|
+
PAYLOAD="$(cat)"
|
|
194
|
+
CWD="$(printf '%s' "$PAYLOAD" | sed -n 's/.*"cwd"[[:space:]]*:[[:space:]]*"\\([^"\\\\]*\\)".*/\\1/p')"
|
|
195
|
+
TOOL="$(printf '%s' "$PAYLOAD" | sed -n 's/.*"tool_name"[[:space:]]*:[[:space:]]*"\\([^"\\\\]*\\)".*/\\1/p')"
|
|
196
|
+
|
|
197
|
+
# The command PREFIX, not the whole command — note there is no closing " in this pattern.
|
|
198
|
+
# WHY: a JSON payload escapes an embedded double quote as \\", and \`[^"\\\\]*\` stops dead at that
|
|
199
|
+
# backslash, so the usual "capture between quotes" form yields the EMPTY STRING for any command
|
|
200
|
+
# containing a quote at all (measured: \`cd /a/b && echo "hi"\` -> ''). An empty CMD here would mean
|
|
201
|
+
# "no cd found" -> ALLOW, i.e. this guard would fail OPEN for every quoted command — the exact hazard
|
|
202
|
+
# it exists to close. Capturing only up to the first quote/backslash is enough, because everything
|
|
203
|
+
# L-1 needs (is the FIRST word a cd, and what is its target) lives in the prefix; a quote can only
|
|
204
|
+
# appear later, in the part we do not need.
|
|
205
|
+
CMD="$(printf '%s' "$PAYLOAD" | sed -n 's/.*"command"[[:space:]]*:[[:space:]]*"\\([^"\\\\]*\\).*/\\1/p')"
|
|
206
|
+
|
|
207
|
+
# Only Bash can move the shell. Anything else, and any payload we cannot read, is not ours.
|
|
208
|
+
[ "$TOOL" = "Bash" ] || exit 0
|
|
209
|
+
[ -n "$CMD" ] || exit 0
|
|
210
|
+
|
|
211
|
+
${CD_AUDIT_SH}
|
|
212
|
+
|
|
213
|
+
# Does the command OPEN with cd/pushd? Only a LEADING cd counts — the same rule effective-tree.ts
|
|
214
|
+
# enforces, because a later cd cannot retroactively move a command that has already run.
|
|
215
|
+
FIRST="$(printf '%s' "$CMD" | sed -n 's/^[[:space:]]*\\([^[:space:]]\\{1,\\}\\).*/\\1/p')"
|
|
216
|
+
case "$FIRST" in
|
|
217
|
+
cd|pushd) ;;
|
|
218
|
+
*) exit 0 ;; # no leading cd: nothing to audit, nothing to judge
|
|
219
|
+
esac
|
|
220
|
+
|
|
221
|
+
# The target: a single-quoted path first (that is how a path with spaces is spelled), else a bare word.
|
|
222
|
+
DEST="$(printf '%s' "$CMD" | sed -n "s/^[[:space:]]*[a-z]\\{2,5\\}[[:space:]]\\{1,\\}'\\([^']*\\)'.*/\\1/p")"
|
|
223
|
+
[ -n "$DEST" ] || DEST="$(printf '%s' "$CMD" | sed -n 's/^[[:space:]]*[a-z]\\{2,5\\}[[:space:]]\\{1,\\}\\([^[:space:];&|]\\{1,\\}\\).*/\\1/p')"
|
|
224
|
+
|
|
225
|
+
REASON=""
|
|
226
|
+
if [ -z "$DEST" ] || [ "$DEST" = "-" ]; then
|
|
227
|
+
REASON='${DENY_NO_TARGET}'
|
|
228
|
+
else
|
|
229
|
+
# A target the guard cannot expand is a target it cannot judge. sh has no regex here, so test the
|
|
230
|
+
# four unexpandable shapes directly.
|
|
231
|
+
case "$DEST" in
|
|
232
|
+
*'$'*|*'\`'*|'~'|'~/'*) REASON='${DENY_NOT_LITERAL}' ;;
|
|
233
|
+
esac
|
|
234
|
+
fi
|
|
235
|
+
|
|
236
|
+
if [ -z "$REASON" ]; then
|
|
237
|
+
# Resolve against the shell's real cwd. A destination that does not exist needs no verdict: the cd
|
|
238
|
+
# itself will fail and the shell stays exactly where it is.
|
|
239
|
+
ABS="$(CDPATH= cd -- "\${CWD:-.}" 2>/dev/null && CDPATH= cd -- "$DEST" 2>/dev/null && pwd)"
|
|
240
|
+
if [ -z "$ABS" ]; then wp_cd_log ALLOW-NO-SUCH-DIR "$DEST"; exit 0; fi
|
|
241
|
+
|
|
242
|
+
# TEST 1 — a git tree of any kind. A worktree's .git is a FILE, a clone's is a DIR; -e covers both.
|
|
243
|
+
if [ -e "$ABS/.git" ]; then wp_cd_log ALLOW-GIT-TREE "$ABS"; exit 0; fi
|
|
244
|
+
|
|
245
|
+
# TEST 2 — outside the governed project. The harness resets the cwd before the next call, so at most
|
|
246
|
+
# one command runs there, on paths we do not govern anyway.
|
|
247
|
+
case "$ABS/" in
|
|
248
|
+
"$CLAUDE_PROJECT_DIR"/*) ;;
|
|
249
|
+
*) wp_cd_log ALLOW-OUTSIDE "$ABS"; exit 0 ;;
|
|
250
|
+
esac
|
|
251
|
+
|
|
252
|
+
# TEST 3 — inside a governed tree with no shim beside it: sticky AND unguarded.
|
|
253
|
+
REASON="$(printf '${DENY_SUBDIR}' "$ABS" "$CLAUDE_PROJECT_DIR")"
|
|
254
|
+
fi
|
|
255
|
+
|
|
256
|
+
${DENY_EMIT_SH}`;
|
|
257
|
+
}
|
|
258
|
+
/**
|
|
259
|
+
* True when a committed guarantee-root.sh EXISTS but no longer equals renderGuaranteeRoot(). Missing
|
|
260
|
+
* file → false: a repo that has not adopted L-1 yet is not "stale", it is simply still on the two-hook
|
|
261
|
+
* registration, and `wp-install-ai-hooks` is what moves it forward.
|
|
262
|
+
*
|
|
263
|
+
* `root` is the tree whose committed copy this BINARY governs — resolved from the running module's own
|
|
264
|
+
* location by governingShimRoot(), never from cwd and never from $CLAUDE_PROJECT_DIR, for the same
|
|
265
|
+
* reason the shim's own check is anchored that way: it makes the two-tree straddle unconstructible.
|
|
266
|
+
*/
|
|
267
|
+
// webpieces-disable no-function-outside-class -- L-1 twin of shim.ts's committedShimStale(); module-scope for the same dependency-free reason
|
|
268
|
+
function committedGuaranteeRootStale(root) {
|
|
269
|
+
if (root === null)
|
|
270
|
+
return false;
|
|
271
|
+
const file = guaranteeRootPath(root);
|
|
272
|
+
// eslint-disable-next-line @webpieces/no-unmanaged-exceptions
|
|
273
|
+
try {
|
|
274
|
+
if (!fs.existsSync(file))
|
|
275
|
+
return false;
|
|
276
|
+
return fs.readFileSync(file, 'utf8') !== renderGuaranteeRoot();
|
|
277
|
+
}
|
|
278
|
+
catch (err) {
|
|
279
|
+
const error = (0, to_error_1.toError)(err);
|
|
280
|
+
void error; // best-effort: an unreadable tree counts as "not stale" so this never wedges a call
|
|
281
|
+
return false;
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
//# sourceMappingURL=guarantee-root.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"guarantee-root.js","sourceRoot":"","sources":["../../../../../../packages/tooling/ai-hook-rules/src/bin/guarantee-root.ts"],"names":[],"mappings":";;;AAiFA,8CAEC;AAOD,gDAMC;AAsGD,kDAkEC;AAYD,kEAYC;;AAhSD,+CAAyB;AACzB,mDAA6B;AAE7B,+CAA2C;AAE3C;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAuEG;AAEU,QAAA,qBAAqB,GAAG,qCAAqC,CAAC;AAE3E,6NAA6N;AAC7N,SAAgB,iBAAiB,CAAC,WAAmB;IACjD,OAAO,IAAI,CAAC,IAAI,CAAC,WAAW,EAAE,SAAS,EAAE,WAAW,EAAE,mBAAmB,CAAC,CAAC;AAC/E,CAAC;AAED;;;GAGG;AACH,wJAAwJ;AACxJ,SAAgB,kBAAkB,CAAC,WAAmB;IAClD,MAAM,MAAM,GAAG,iBAAiB,CAAC,WAAW,CAAC,CAAC;IAC9C,EAAE,CAAC,SAAS,CAAC,IAAI,CAAC,OAAO,CAAC,MAAM,CAAC,EAAE,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC,CAAC;IACxD,EAAE,CAAC,aAAa,CAAC,MAAM,EAAE,mBAAmB,EAAE,EAAE,EAAE,IAAI,EAAE,KAAK,EAAE,CAAC,CAAC;IACjE,0FAA0F;IAC1F,EAAE,CAAC,SAAS,CAAC,MAAM,EAAE,KAAK,CAAC,CAAC;AAChC,CAAC;AAED,sGAAsG;AACtG,6FAA6F;AAC7F,2DAA2D;AAC3D,MAAM,gBAAgB,GAClB,+FAA+F;MAC7F,+DAA+D;MAC/D,+DAA+D,CAAC;AAEtE,MAAM,cAAc,GAChB,8FAA8F;MAC5F,8FAA8F;MAC9F,oEAAoE,CAAC;AAE3E,qGAAqG;AACrG,kGAAkG;AAClG,MAAM,WAAW,GACb,gGAAgG;MAC9F,8FAA8F;MAC9F,iGAAiG;MACjG,0FAA0F;MAC1F,gGAAgG;MAChG,wBAAwB,CAAC;AAE/B;;;;;;;;;;;GAWG;AACH,MAAM,WAAW,GAAG;;;;;;;;;;;;;;;;;;;;;;;CAuBnB,CAAC;AAGF,+FAA+F;AAC/F,sGAAsG;AACtG,qGAAqG;AACrG,MAAM,YAAY,GAAG;;;;;;CAMpB,CAAC;AAEF,+FAA+F;AAC/F,oGAAoG;AACpG,8BAA8B;AAC9B,MAAM,SAAS,GAAG;;;;;;;;;;;;;;;;;CAiBjB,CAAC;AAEF;;;;GAIG;AACH,kLAAkL;AAClL,SAAgB,mBAAmB;IAC/B,OAAO,GAAG,SAAS;;;;;;;;;;;;;;;;;;;EAmBrB,WAAW;;;;;;;;;;;;;;;;YAgBD,cAAc;;;;;sCAKY,gBAAgB;;;;;;;;;;;;;;;;;;;;;sBAqBhC,WAAW;;;EAG/B,YAAY,EAAE,CAAC;AACjB,CAAC;AAED;;;;;;;;GAQG;AACH,8IAA8I;AAC9I,SAAgB,2BAA2B,CAAC,IAAmB;IAC3D,IAAI,IAAI,KAAK,IAAI;QAAE,OAAO,KAAK,CAAC;IAChC,MAAM,IAAI,GAAG,iBAAiB,CAAC,IAAI,CAAC,CAAC;IACrC,8DAA8D;IAC9D,IAAI,CAAC;QACD,IAAI,CAAC,EAAE,CAAC,UAAU,CAAC,IAAI,CAAC;YAAE,OAAO,KAAK,CAAC;QACvC,OAAO,EAAE,CAAC,YAAY,CAAC,IAAI,EAAE,MAAM,CAAC,KAAK,mBAAmB,EAAE,CAAC;IACnE,CAAC;IAAC,OAAO,GAAY,EAAE,CAAC;QACpB,MAAM,KAAK,GAAG,IAAA,kBAAO,EAAC,GAAG,CAAC,CAAC;QAC3B,KAAK,KAAK,CAAC,CAAC,oFAAoF;QAChG,OAAO,KAAK,CAAC;IACjB,CAAC;AACL,CAAC","sourcesContent":["import * as fs from 'fs';\nimport * as path from 'path';\n\nimport { toError } from '../core/to-error';\n\n/**\n * L-1 — the layer BELOW L0: guarantee the shell stays somewhere the RELATIVE guard hooks can launch.\n *\n * ─── Why a layer below L0 exists at all ────────────────────────────────────────────────────────────\n * From the Claude Code hooks reference: exit 2 is the blocking channel, exit 0 carries the JSON\n * decision, and ANY OTHER exit is a \"non-blocking error. Execution continues; the action proceeds\" —\n * including \"File missing or not executable: Error logged; tool proceeds.\"\n *\n * A HOOK THAT FAILS TO LAUNCH IS A SILENT ALLOW. Not a block, not an error the AI sees.\n *\n * Every layer L0-L4 assumes the hook process ran at all. This file is what makes that assumption true.\n *\n * ─── Why the guard hooks become RELATIVE ───────────────────────────────────────────────────────────\n * `.claude/settings.json` registers hooks as `sh \"$CLAUDE_PROJECT_DIR/.claude/webpieces/ai-hook.sh\"`,\n * and `$CLAUDE_PROJECT_DIR` NEVER moves — proven from four separate worktrees' own logs, every line\n * reading `root=<worktree> projectDir=<primary>`. So every tree is governed by the PRIMARY's shim and\n * the PRIMARY's binary, forever: a worktree can never be judged by the release its own branch pins, and\n * measuring one tree while running another's binary is the non-convergent \"two-tree straddle\" recorded\n * in shim.ts (an agent gave up after four cures).\n *\n * The fix is to re-root the WHOLE hook, not to measure differently. The hooks reference says \"the hook\n * runs in the cwd value from the JSON input\", so a RELATIVE command resolves against the tool call's\n * own tree — each tree runs its own shim, its own binary, its own pin. One version, one tree.\n *\n * That is only safe if the relative path is guaranteed to resolve. Hence this file.\n *\n * ─── Why this is a SEPARATE checked-in file from ai-hook.sh ────────────────────────────────────────\n * 1. It is the ONE file that must stay $CLAUDE_PROJECT_DIR-anchored, so it is the one file that cannot\n * be upgraded per-tree. Its surface is therefore kept minimal: a path check. No drift scraper, no\n * allowlist, no config load, no binary — nothing that needs to change often.\n * 2. Its stability profile is the OPPOSITE of ai-hook.sh's. The shim changes most releases; a `cd`\n * validator should converge and stop. Sharing one file forces the stable half to inherit the\n * volatile half's churn — which is today's problem, one level up.\n * 3. A NEW FILE IS INVISIBLE TO OLD RELEASES; A NEW FLAG BREAKS THEM. Measured 2026-08-06: registering\n * `ai-hook.sh --force-root` made the installed shim read `--force-root` as a BIN NAME, fail to find\n * it, and emit fault U — denying `ls` and the very `cd` that would have fixed it:\n * 16:32:20 --force-root Bash tree=primary fault=U DENY-UNDECLARED ls\n * A separate file is simply not registered until a release that ships it, so old releases are safe.\n *\n * ─── The invariant, maintained inductively ─────────────────────────────────────────────────────────\n * A session always starts at a tree root (primary for the coordinator, the worktree for a subagent).\n * The only thing that moves the shell is a `cd`, and (measured 2026-08-02, effective-tree.ts) a `cd`\n * that stays INSIDE the workspace PERSISTS to later calls, while a `cd` that LEAVES it is RESET by the\n * harness before the next call.\n *\n * If every `cd` that would leave a tree root is refused, \"the shell is at a tree root\" is an\n * INDUCTIVE INVARIANT — so this hook never inspects cwd as a state, only the command.\n *\n * That is also why it is registered for Bash ALONE: no other tool can move the shell.\n *\n * ─── The predicate, in three tests ─────────────────────────────────────────────────────────────────\n * 1. destination holds `.git` → ALLOW. Complete by construction: the primary clone has a .git DIR,\n * every linked worktree (nested or sibling) has a .git FILE, and a nested foreign clone under\n * repositories/** has its own .git DIR. The first two are where the relative hooks launch; the\n * third is a tree we deliberately do not govern.\n * 2. destination is OUTSIDE $CLAUDE_PROJECT_DIR → ALLOW. The harness resets it before the next call,\n * so at most ONE call runs at a path we do not govern — and there is nothing there to guard.\n * 3. otherwise (inside a governed tree, no .git — `tools/`, `dataform/`, `packages/…`) → DENY. This\n * is the only region that is both STICKY and UNGUARDED.\n *\n * It reads NO config. `excludePaths` governs which FILES are enforced, not whether the hook may run,\n * and it cannot be parsed here anyway (this is sh, pre-config, pre-binary). The one measured divergence\n * is `tools/**`: exempt by excludePaths, denied here — correctly, because the real hooks genuinely\n * cannot launch there and we genuinely want them to. Cost: 4 calls in a 2,236-call sample.\n *\n * ─── Nothing to recover from ───────────────────────────────────────────────────────────────────────\n * A denied `cd` NEVER EXECUTES — PreToolUse denies the whole tool call before the shell moves — so the\n * shell is still at a root. There is no bad state and no cure command that needs allowlisting, which is\n * what keeps this hook from ever being able to wedge a session.\n *\n * Measured cost of the deny: 47 of 2,236 real Bash calls (2.10%), or 9.7% of all `cd` commands.\n */\n\nexport const GUARANTEE_ROOT_MARKER = '.claude/webpieces/guarantee-root.sh';\n\n// webpieces-disable no-function-outside-class -- L-1 sibling of shim.ts's shimPath(); this module is deliberately dependency-free module-scope functions so it stays callable from a tree too broken to build a DI container\nexport function guaranteeRootPath(projectRoot: string): string {\n return path.join(projectRoot, '.claude', 'webpieces', 'guarantee-root.sh');\n}\n\n/**\n * Write (or overwrite) the committed L-1 hook. Idempotent — the installer and `wp-upgrade-shim` both\n * call it, and re-running either simply re-arms the file. Twin of setup.ts's writeShim().\n */\n// webpieces-disable no-function-outside-class -- L-1 sibling of guaranteeRootPath(); this module is deliberately dependency-free module-scope functions\nexport function writeGuaranteeRoot(projectRoot: string): void {\n const target = guaranteeRootPath(projectRoot);\n fs.mkdirSync(path.dirname(target), { recursive: true });\n fs.writeFileSync(target, renderGuaranteeRoot(), { mode: 0o755 });\n // writeFileSync's mode is only applied when creating the file; force it on overwrite too.\n fs.chmodSync(target, 0o755);\n}\n\n// Deny REASON constraint, inherited from the shim: the text is interpolated into a `REASON=\"…\"` shell\n// assignment and then printf'd into a JSON string, so it may contain NO double quotes and NO\n// backslashes. Single quotes only — do not \"improve\" them.\nconst DENY_NOT_LITERAL =\n 'This cd target is not a literal path, so the guards cannot tell where the shell will end up. '\n + 'Use a literal absolute path: cd /abs/path && <your command>. '\n + 'A $VAR, ~, $(...) or backtick is never expanded by the guard.';\n\nconst DENY_NO_TARGET =\n 'A bare cd (or cd -) moves the shell somewhere the guards cannot predict - a bare cd goes to '\n + 'your home directory, where the webpieces hooks do not exist and every later tool call would '\n + 'run UNGUARDED. Name the directory: cd /abs/path && <your command>.';\n\n// `%s` is the destination, then the project root. Kept to one short paragraph on purpose: L0 already\n// ran a message diet and these denies regress straight back to a wall of text if each one argues.\nconst DENY_SUBDIR =\n 'The webpieces guard hooks are registered RELATIVE (.claude/webpieces/ai-hook.sh) so that each '\n + 'git tree is governed by its own release. %s has no .claude/webpieces/ai-hook.sh, so a shell '\n + 'parked there launches NO hooks at all and every later tool call runs UNGUARDED - and a cd that '\n + 'stays inside the project PERSISTS to your next call. Run it from the tree root instead: '\n + 'cd %s && <your command>. Tools that take their own directory (git -C, pnpm -C, pnpm --filter, '\n + 'nx) need no cd at all.';\n\n/**\n * The cd audit trail. A THIRD parallel writer joins guards+rules on every Bash call, so it gets its\n * own file under the same session/agent/hook key LogStream uses — one writer per directory, so an\n * append can never interleave with another's (macOS PIPE_BUF is 512 bytes and real log lines exceed it).\n *\n * Unlike the shim's RESOLVE_LOG_DIR_SH this needs NO worktree resolution: H1 is $CLAUDE_PROJECT_DIR-\n * anchored by definition, so the primary clone's `.webpieces` is always the right home. That is the one\n * upside of being the hook that cannot follow the tree.\n *\n * Every write is swallowed and nothing ever reaches stdout — stdout is the PreToolUse decision channel\n * and a stray byte there would corrupt allow/deny.\n */\nconst CD_AUDIT_SH = `# --- cd audit (best-effort; never blocks, never touches stdout) --------------------------------\nSID=\"$(printf '%s' \"$PAYLOAD\" | sed -n 's/.*\"session_id\"[[:space:]]*:[[:space:]]*\"\\\\([^\"\\\\\\\\]*\\\\)\".*/\\\\1/p')\"\nAID=\"$(printf '%s' \"$PAYLOAD\" | sed -n 's/.*\"agent_id\"[[:space:]]*:[[:space:]]*\"\\\\([^\"\\\\\\\\]*\\\\)\".*/\\\\1/p')\"\n# Untrusted payload values are used as path segments, so anything outside [A-Za-z0-9._-] collapses to _\n# and a leading dot is neutralised — ../../etc can never escape the logs directory.\nclean() { printf '%s' \"$1\" | tr -c 'A-Za-z0-9._-' '_' \\\\\n | sed -e 's/\\\\.\\\\{2,\\\\}/_/g' -e 's/^\\\\.\\\\{1,\\\\}/_/' | cut -c1-64; }\nwp_cd_log() { # $1 = verdict, $2 = destination (may be empty)\n {\n [ -n \"$CLAUDE_PROJECT_DIR\" ] || return 0\n _d=\"$CLAUDE_PROJECT_DIR/.webpieces/logs\"\n mkdir -p \"$_d\" 2>/dev/null || return 0\n # Flat name, same scheme as LogStream.fileName(): <session>-<agent|coordinator>-guarantee-root-<base>\n # ALWAYS prefixed; a missing session_id renders as 'unknown'. No bare-name branch anywhere.\n _p=\"$(clean \"\\${SID:-unknown}\")-$(clean \"\\${AID:-coordinator}\")-guarantee-root-\"\n _f=\"$_d/\\${_p}cd-audit.log\"\n _sz=\"$(wc -c < \"$_f\" 2>/dev/null | tr -d ' ')\"\n case \"$_sz\" in ''|*[!0-9]*) _sz=0 ;; esac\n [ \"$_sz\" -gt 524288 ] && mv -f \"$_f\" \"$_d/\\${_p}cd-audit.1.log\" 2>/dev/null\n printf '%s\\\\t%s\\\\tdest=%s\\\\tcwd=%s\\\\t%s\\\\n' \\\\\n \"$(date '+%Y-%m-%dT%H:%M:%S%z' 2>/dev/null)\" \"$1\" \"$2\" \"$CWD\" \"$CMD\" >> \"$_f\"\n } 2>/dev/null || true\n}\n`;\n\n\n// The deny boundary. Extracted for the same reason CD_AUDIT_SH and HEADER_SH are — to keep the\n// renderer inside the 70-line method budget — and spliced back verbatim. Mirrors the shim's own emit:\n// for Bash, permissionDecisionReason is NOT user-visible, so the red systemMessage carries the text.\nconst DENY_EMIT_SH = `wp_cd_log DENY \"\\${ABS:-$DEST}\"\n\nBS='\\\\' # one literal backslash, so the \\\\u001b escape never sits in this source\nESC=\"\\${BS}u001b\" # the 6 chars: backslash u 0 0 1 b — Claude Code parses \\\\u001b -> ESC\nprintf '{\"systemMessage\":\"%s🛑 %s%s\",\"hookSpecificOutput\":{\"hookEventName\":\"PreToolUse\",\"permissionDecision\":\"deny\",\"permissionDecisionReason\":\"%s\"}}\\\\n' \"\\${ESC}[31;1m\" \"$REASON\" \"\\${ESC}[0m\" \"$REASON\"\nexit 0 # the decision is carried by permissionDecision deny, not the exit code\n`;\n\n// The file's own banner. Extracted to a module const for the same reason renderShim() extracts\n// VERSION_DRIFT_GUARD_SH — to keep the renderer inside the 80-line method budget — and spliced back\n// in verbatim, byte for byte.\nconst HEADER_SH = `#!/bin/sh\n# webpieces L-1 hook — GUARANTEE ROOT. Generated by renderGuaranteeRoot(); do not hand-edit.\n#\n# Registered ABSOLUTE in .claude/settings.json, matcher \"Bash\":\n# sh \"$CLAUDE_PROJECT_DIR/.claude/webpieces/guarantee-root.sh\"\n#\n# It exists because the GUARD hooks beside it are registered RELATIVE, so that each git tree is\n# governed by its own @webpieces release. A relative hook that cannot resolve does not block — the\n# harness logs it and lets the tool call proceed UNGUARDED. This file makes that unreachable by\n# refusing any cd that would park the shell where the relative hooks cannot launch.\n#\n# Three tests, no config, no binary, no network:\n# 1. destination holds .git -> ALLOW (tree root, worktree, or foreign clone)\n# 2. destination is outside $CLAUDE_PROJECT_DIR -> ALLOW (the harness resets the cwd next call)\n# 3. otherwise -> DENY (sticky AND unguarded)\n#\n# A denied cd never runs, so the shell never leaves the root and there is nothing to recover from.\n`;\n\n/**\n * The POSIX-sh source. Byte-identical to `templates/guarantee-root.sh`, locked by a unit test, exactly\n * as renderShim()/templates/ai-hook.sh are — so the file a consumer commits and the file this release\n * expects can never silently diverge.\n */\n// webpieces-disable no-function-outside-class -- L-1 twin of shim.ts's renderShim(), byte-locked to templates/guarantee-root.sh; module-scope for the same dependency-free reason\nexport function renderGuaranteeRoot(): string {\n return `${HEADER_SH}\nPAYLOAD=\"$(cat)\"\nCWD=\"$(printf '%s' \"$PAYLOAD\" | sed -n 's/.*\"cwd\"[[:space:]]*:[[:space:]]*\"\\\\([^\"\\\\\\\\]*\\\\)\".*/\\\\1/p')\"\nTOOL=\"$(printf '%s' \"$PAYLOAD\" | sed -n 's/.*\"tool_name\"[[:space:]]*:[[:space:]]*\"\\\\([^\"\\\\\\\\]*\\\\)\".*/\\\\1/p')\"\n\n# The command PREFIX, not the whole command — note there is no closing \" in this pattern.\n# WHY: a JSON payload escapes an embedded double quote as \\\\\", and \\`[^\"\\\\\\\\]*\\` stops dead at that\n# backslash, so the usual \"capture between quotes\" form yields the EMPTY STRING for any command\n# containing a quote at all (measured: \\`cd /a/b && echo \"hi\"\\` -> ''). An empty CMD here would mean\n# \"no cd found\" -> ALLOW, i.e. this guard would fail OPEN for every quoted command — the exact hazard\n# it exists to close. Capturing only up to the first quote/backslash is enough, because everything\n# L-1 needs (is the FIRST word a cd, and what is its target) lives in the prefix; a quote can only\n# appear later, in the part we do not need.\nCMD=\"$(printf '%s' \"$PAYLOAD\" | sed -n 's/.*\"command\"[[:space:]]*:[[:space:]]*\"\\\\([^\"\\\\\\\\]*\\\\).*/\\\\1/p')\"\n\n# Only Bash can move the shell. Anything else, and any payload we cannot read, is not ours.\n[ \"$TOOL\" = \"Bash\" ] || exit 0\n[ -n \"$CMD\" ] || exit 0\n\n${CD_AUDIT_SH}\n\n# Does the command OPEN with cd/pushd? Only a LEADING cd counts — the same rule effective-tree.ts\n# enforces, because a later cd cannot retroactively move a command that has already run.\nFIRST=\"$(printf '%s' \"$CMD\" | sed -n 's/^[[:space:]]*\\\\([^[:space:]]\\\\{1,\\\\}\\\\).*/\\\\1/p')\"\ncase \"$FIRST\" in\n cd|pushd) ;;\n *) exit 0 ;; # no leading cd: nothing to audit, nothing to judge\nesac\n\n# The target: a single-quoted path first (that is how a path with spaces is spelled), else a bare word.\nDEST=\"$(printf '%s' \"$CMD\" | sed -n \"s/^[[:space:]]*[a-z]\\\\{2,5\\\\}[[:space:]]\\\\{1,\\\\}'\\\\([^']*\\\\)'.*/\\\\1/p\")\"\n[ -n \"$DEST\" ] || DEST=\"$(printf '%s' \"$CMD\" | sed -n 's/^[[:space:]]*[a-z]\\\\{2,5\\\\}[[:space:]]\\\\{1,\\\\}\\\\([^[:space:];&|]\\\\{1,\\\\}\\\\).*/\\\\1/p')\"\n\nREASON=\"\"\nif [ -z \"$DEST\" ] || [ \"$DEST\" = \"-\" ]; then\n REASON='${DENY_NO_TARGET}'\nelse\n # A target the guard cannot expand is a target it cannot judge. sh has no regex here, so test the\n # four unexpandable shapes directly.\n case \"$DEST\" in\n *'$'*|*'\\`'*|'~'|'~/'*) REASON='${DENY_NOT_LITERAL}' ;;\n esac\nfi\n\nif [ -z \"$REASON\" ]; then\n # Resolve against the shell's real cwd. A destination that does not exist needs no verdict: the cd\n # itself will fail and the shell stays exactly where it is.\n ABS=\"$(CDPATH= cd -- \"\\${CWD:-.}\" 2>/dev/null && CDPATH= cd -- \"$DEST\" 2>/dev/null && pwd)\"\n if [ -z \"$ABS\" ]; then wp_cd_log ALLOW-NO-SUCH-DIR \"$DEST\"; exit 0; fi\n\n # TEST 1 — a git tree of any kind. A worktree's .git is a FILE, a clone's is a DIR; -e covers both.\n if [ -e \"$ABS/.git\" ]; then wp_cd_log ALLOW-GIT-TREE \"$ABS\"; exit 0; fi\n\n # TEST 2 — outside the governed project. The harness resets the cwd before the next call, so at most\n # one command runs there, on paths we do not govern anyway.\n case \"$ABS/\" in\n \"$CLAUDE_PROJECT_DIR\"/*) ;;\n *) wp_cd_log ALLOW-OUTSIDE \"$ABS\"; exit 0 ;;\n esac\n\n # TEST 3 — inside a governed tree with no shim beside it: sticky AND unguarded.\n REASON=\"$(printf '${DENY_SUBDIR}' \"$ABS\" \"$CLAUDE_PROJECT_DIR\")\"\nfi\n\n${DENY_EMIT_SH}`;\n}\n\n/**\n * True when a committed guarantee-root.sh EXISTS but no longer equals renderGuaranteeRoot(). Missing\n * file → false: a repo that has not adopted L-1 yet is not \"stale\", it is simply still on the two-hook\n * registration, and `wp-install-ai-hooks` is what moves it forward.\n *\n * `root` is the tree whose committed copy this BINARY governs — resolved from the running module's own\n * location by governingShimRoot(), never from cwd and never from $CLAUDE_PROJECT_DIR, for the same\n * reason the shim's own check is anchored that way: it makes the two-tree straddle unconstructible.\n */\n// webpieces-disable no-function-outside-class -- L-1 twin of shim.ts's committedShimStale(); module-scope for the same dependency-free reason\nexport function committedGuaranteeRootStale(root: string | null): boolean {\n if (root === null) return false;\n const file = guaranteeRootPath(root);\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n if (!fs.existsSync(file)) return false;\n return fs.readFileSync(file, 'utf8') !== renderGuaranteeRoot();\n } catch (err: unknown) {\n const error = toError(err);\n void error; // best-effort: an unreadable tree counts as \"not stale\" so this never wedges a call\n return false;\n }\n}\n"]}
|
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* THE INSTALLED HOOK SURFACE — three hooks, and the ONE place their spelling is defined.
|
|
3
|
+
*
|
|
4
|
+
* ─── Why three, and why two of them are RELATIVE ───────────────────────────────────────────────────
|
|
5
|
+
* `.claude/settings.json` used to register two hooks, BOTH absolute via `$CLAUDE_PROJECT_DIR`. That
|
|
6
|
+
* variable NEVER moves — proven from four separate worktrees' own logs, every line reading
|
|
7
|
+
* `root=<worktree> projectDir=<primary>` — so every tree was governed by the PRIMARY's shim, the
|
|
8
|
+
* PRIMARY's binary and the PRIMARY's pin, forever. A worktree could never be judged by the release its
|
|
9
|
+
* own branch pins, and measuring one tree while running another's binary is the non-convergent
|
|
10
|
+
* "two-tree straddle" recorded in shim.ts (an agent gave up after four cures).
|
|
11
|
+
*
|
|
12
|
+
* The hooks reference says "the hook runs in the `cwd` value from the JSON input", so a RELATIVE
|
|
13
|
+
* command resolves against the tool call's own tree. Hence:
|
|
14
|
+
*
|
|
15
|
+
* H1 absolute sh "$CLAUDE_PROJECT_DIR/.claude/webpieces/guarantee-root.sh" matcher Bash
|
|
16
|
+
* H2 relative sh ".claude/webpieces/ai-hook.sh" wp-ai-guards-hook matcher Write|…|Read
|
|
17
|
+
* H3 relative sh ".claude/webpieces/ai-hook.sh" wp-ai-rules-hook matcher Write|Edit|MultiEdit
|
|
18
|
+
*
|
|
19
|
+
* H1 stays absolute because it is the one hook that must ALWAYS resolve: a relative hook that cannot
|
|
20
|
+
* resolve exits 127, and per the same reference any non-2 non-zero exit is a NON-BLOCKING error — i.e.
|
|
21
|
+
* a SILENT UNGUARDED ALLOW. H1 refuses any `cd` that would park the shell where H2/H3 cannot launch,
|
|
22
|
+
* which is what makes the relative pair admissible at all. See guarantee-root.ts.
|
|
23
|
+
*
|
|
24
|
+
* H1 matches `Bash` alone because only Bash can move the shell — the same reason stated at the top of
|
|
25
|
+
* guarantee-root.ts, and the reason the rendered guarantee-root.sh exits 0 immediately for every other
|
|
26
|
+
* tool. Registering it wider would spawn a process per Write/Read to do nothing.
|
|
27
|
+
*
|
|
28
|
+
* ─── Why the registration is a DRIFT SURFACE, not just an install step ─────────────────────────────
|
|
29
|
+
* Nothing used to validate `.claude/settings.json` at all, so a settings file left on the old
|
|
30
|
+
* two-absolute-hook form silently reverted a repo to per-PRIMARY governance and disabled H1 — the one
|
|
31
|
+
* component whose whole job is failing closed. The installed surface is therefore THREE things
|
|
32
|
+
* (ai-hook.sh, guarantee-root.sh, the registration), all three are compared against this release, and
|
|
33
|
+
* `wp-upgrade-shim` regenerates all three. A cure that fixes one of three is worse than no cure,
|
|
34
|
+
* because it reports success.
|
|
35
|
+
*/
|
|
36
|
+
/** One PreToolUse hook entry as webpieces registers it. Data-only → a class, per CLAUDE.md. */
|
|
37
|
+
export declare class HookRegistrationEntry {
|
|
38
|
+
readonly matcher: string;
|
|
39
|
+
readonly command: string;
|
|
40
|
+
constructor(matcher: string, command: string);
|
|
41
|
+
sameAs(other: HookRegistrationEntry): boolean;
|
|
42
|
+
}
|
|
43
|
+
export interface HookCommand {
|
|
44
|
+
type: string;
|
|
45
|
+
command: string;
|
|
46
|
+
}
|
|
47
|
+
export interface HookEntry {
|
|
48
|
+
matcher: string;
|
|
49
|
+
hooks: HookCommand[];
|
|
50
|
+
}
|
|
51
|
+
export interface ClaudeSettings {
|
|
52
|
+
hooks?: {
|
|
53
|
+
PreToolUse?: HookEntry[];
|
|
54
|
+
};
|
|
55
|
+
[key: string]: unknown;
|
|
56
|
+
}
|
|
57
|
+
export declare const RULES_BIN = "wp-ai-rules-hook";
|
|
58
|
+
export declare const GUARDS_BIN = "wp-ai-guards-hook";
|
|
59
|
+
export declare const RULES_MATCHER = "Write|Edit|MultiEdit";
|
|
60
|
+
export declare const GUARDS_MATCHER = "Write|Edit|MultiEdit|Bash|Read";
|
|
61
|
+
export declare const GUARANTEE_ROOT_MATCHER = "Bash";
|
|
62
|
+
/**
|
|
63
|
+
* The RELATIVE guard-hook command — `sh ".claude/webpieces/ai-hook.sh" <bin>`.
|
|
64
|
+
*
|
|
65
|
+
* Relative, NOT `$CLAUDE_PROJECT_DIR/…`: that is the whole point (see the header). Invoked via `sh
|
|
66
|
+
* <file>` rather than executed directly so a missing executable bit on the checked-in shim (fresh
|
|
67
|
+
* clone, a filesystem that drops the bit, git core.fileMode quirks) can never break the hook with a raw
|
|
68
|
+
* `Permission denied` on every tool call. Quoted to survive spaces in the path.
|
|
69
|
+
*/
|
|
70
|
+
export declare function shimCommand(bin: string): string;
|
|
71
|
+
/** H1's command. ABSOLUTE on purpose — it must resolve from ANY cwd or it cannot fail closed. */
|
|
72
|
+
export declare const GUARANTEE_ROOT_COMMAND = "sh \"$CLAUDE_PROJECT_DIR/.claude/webpieces/guarantee-root.sh\"";
|
|
73
|
+
export declare const GUARANTEE_ROOT_ENTRY: HookRegistrationEntry;
|
|
74
|
+
/** The registration entry for one guard bin. */
|
|
75
|
+
export declare function guardHookEntry(bin: string): HookRegistrationEntry;
|
|
76
|
+
/** True when this PreToolUse command is one webpieces owns (either .sh file, in any spelling). */
|
|
77
|
+
export declare function isManagedCommand(command: string): boolean;
|
|
78
|
+
/** Every webpieces-managed entry of one settings file, flattened to matcher + command pairs. */
|
|
79
|
+
export declare function managedEntries(settings: ClaudeSettings): readonly HookRegistrationEntry[];
|
|
80
|
+
/**
|
|
81
|
+
* Which guard bins this settings file registers, in installer order. A file registering NEITHER is not
|
|
82
|
+
* a project (relative) install and is therefore never judged — a global/absolute install names the bin
|
|
83
|
+
* path directly and carries no shim marker at all.
|
|
84
|
+
*/
|
|
85
|
+
export declare function registeredBins(settings: ClaudeSettings): readonly string[];
|
|
86
|
+
/**
|
|
87
|
+
* The exact set of entries THIS RELEASE expects in a settings file that registers `bins`.
|
|
88
|
+
*
|
|
89
|
+
* H1 rides with the GUARDS hook, not the rules hook: H1 judges Bash, and `Bash` is in the guards
|
|
90
|
+
* matcher. A file carrying only the rules hook (the supported split install, where a team ships the
|
|
91
|
+
* guards and a developer keeps the code-style rules local) gets no H1 and needs none.
|
|
92
|
+
*/
|
|
93
|
+
export declare function expectedEntries(bins: readonly string[]): readonly HookRegistrationEntry[];
|
|
94
|
+
/**
|
|
95
|
+
* True when a settings file registers webpieces hooks in a shape this release does not expect — the
|
|
96
|
+
* old two-absolute-hook form, a missing guarantee-root entry, a stray duplicate, a wrong matcher.
|
|
97
|
+
*
|
|
98
|
+
* Compared as a SET, not a sequence: Claude Code runs all matching hooks in parallel, so array order
|
|
99
|
+
* carries no meaning and reordering must not read as drift.
|
|
100
|
+
*/
|
|
101
|
+
export declare function registrationStale(settings: ClaudeSettings): boolean;
|
|
102
|
+
/** Drop every webpieces-managed PreToolUse command; returns true if anything was removed. */
|
|
103
|
+
export declare function dropManagedEntries(settings: ClaudeSettings): boolean;
|
|
104
|
+
/** Append one PreToolUse entry. */
|
|
105
|
+
export declare function addHookEntry(settings: ClaudeSettings, entry: HookRegistrationEntry): void;
|
|
106
|
+
/**
|
|
107
|
+
* Bring one settings object to the three-hook form IN PLACE. Returns true when it changed.
|
|
108
|
+
*
|
|
109
|
+
* REMOVE-then-ADD, never add-beside: two spellings of one registration is exactly the compatibility
|
|
110
|
+
* shim the backwards-compat reviewer rejects, and leaving the `$CLAUDE_PROJECT_DIR/`-prefixed entry
|
|
111
|
+
* beside the relative one would run the PRIMARY's binary alongside the tree's own — the straddle this
|
|
112
|
+
* whole change exists to delete.
|
|
113
|
+
*/
|
|
114
|
+
export declare function repairRegistration(settings: ClaudeSettings): boolean;
|
|
115
|
+
/** The two project settings files the installer can write. */
|
|
116
|
+
export declare function projectSettingsPaths(projectRoot: string): readonly string[];
|
|
117
|
+
export declare function readSettings(settingsPath: string): ClaudeSettings;
|
|
118
|
+
export declare function writeSettings(settingsPath: string, settings: ClaudeSettings): void;
|
|
119
|
+
/** True when either project settings file under `root` carries a stale registration. */
|
|
120
|
+
export declare function registrationStaleAt(root: string | null): boolean;
|
|
121
|
+
/** Rewrite every stale project settings file under `root`; returns the paths actually changed. */
|
|
122
|
+
export declare function repairRegistrationAt(root: string): readonly string[];
|
|
123
|
+
/** The three names the drift check reports, so a deny can say WHICH of them moved. */
|
|
124
|
+
export declare const SHIM_SURFACE = ".claude/webpieces/ai-hook.sh";
|
|
125
|
+
export declare const GUARANTEE_ROOT_SURFACE = ".claude/webpieces/guarantee-root.sh";
|
|
126
|
+
export declare const REGISTRATION_SURFACE = ".claude/settings.json hook registration";
|
|
127
|
+
/**
|
|
128
|
+
* WHICH of the three managed surfaces disagree with this release — the input to fault S.
|
|
129
|
+
*
|
|
130
|
+
* All three are checked against the SAME root, resolved from the RUNNING MODULE (governingShimRoot),
|
|
131
|
+
* never from cwd and never from `$CLAUDE_PROJECT_DIR`: the files we compare and the renderers we
|
|
132
|
+
* compare them TO must come from one install, or the check straddles two trees and can never converge.
|
|
133
|
+
*/
|
|
134
|
+
export declare function managedSurfaceDrift(root: string | null): readonly string[];
|