@cratis/pi 7.131.7 → 7.132.1

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.
@@ -9,6 +9,7 @@
9
9
  * Claude PreToolUse (Write|Edit) → Pi `tool_call` → cratis-guard-writes.sh (exit 2 = block)
10
10
  * Claude PreToolUse (Bash) → Pi `tool_call` → cratis-guard-store-mutations.sh (exit 2 = block)
11
11
  * Claude PreToolUse (Bash) → Pi `tool_call` → cratis-guard-secrets.sh (exit 2 = block)
12
+ * Claude PreToolUse (Bash) → Pi `tool_call` → cratis-guard-shell-writes.sh (exit 2 = block)
12
13
  * Claude PreToolUse (Bash) → Pi `tool_call` → cratis-guard-pr-body.sh (exit 2 = block)
13
14
  * Claude PostToolUse (Write|Edit) → Pi `tool_result` → cratis-pattern-scan.sh (advisory context)
14
15
  * Claude PostToolUse (Bash) → Pi `tool_result` → cratis-cleanup-worktrees.sh --hook (removes delivered worktrees/branches)
@@ -31,7 +32,7 @@
31
32
  * CRATIS_HOOKS_SKIP_GATE, …) still works because the scripts are executed unchanged, in the environment
32
33
  * Pi was started from.
33
34
  *
34
- * Only Pi's `bash` tool is bridged to the store-mutation and secrets guards. A command the user types directly (`!cmd`,
35
+ * Only Pi's `bash` tool is bridged to the store-mutation, secrets and shell-write guards. A command the user types directly (`!cmd`,
35
36
  * the `user_bash` event) is the person's own action and is deliberately not guarded.
36
37
  */
37
38
 
@@ -178,9 +179,9 @@ async function runCommandGuards(
178
179
  /**
179
180
  * Whether a hook script is installed at all.
180
181
  *
181
- * A repository that ships no hook scripts is a supported configuration — the corpus scripts
182
- * themselves degrade to a silent no-op when `jq` is missing, on the stated principle that a hook
183
- * must never break a session. So an absent script is not an error and is not enforced.
182
+ * A repository that ships no hook scripts is a supported configuration, so an absent script is
183
+ * not an error and is not enforced. Installed scripts report missing `jq`: guards refuse calls,
184
+ * the quality gate blocks changed trees, and the advisory pattern scan warns once per session.
184
185
  *
185
186
  * The dangerous case is the other one: the script is present, so this repository clearly intends
186
187
  * the guard to run, but it cannot be executed. That is a broken guard rather than an absent one,
@@ -201,6 +202,7 @@ export default function (pi: ExtensionAPI) {
201
202
  const guardWrites = path.join(scriptsDir, "cratis-guard-writes.sh");
202
203
  const guardStoreMutations = path.join(scriptsDir, "cratis-guard-store-mutations.sh");
203
204
  const guardSecrets = path.join(scriptsDir, "cratis-guard-secrets.sh");
205
+ const guardShellWrites = path.join(scriptsDir, "cratis-guard-shell-writes.sh");
204
206
  const guardPrBody = path.join(scriptsDir, "cratis-guard-pr-body.sh");
205
207
  const patternScan = path.join(scriptsDir, "cratis-pattern-scan.sh");
206
208
  const qualityGate = path.join(scriptsDir, "cratis-quality-gate.sh");
@@ -229,7 +231,7 @@ export default function (pi: ExtensionAPI) {
229
231
  const command = (event as any).input?.command;
230
232
  if (typeof command !== "string" || !command.trim()) return;
231
233
  const payload = { cwd: ctx.cwd, tool_name: "Bash", tool_input: { command } };
232
- const blocked = await runCommandGuards([[guardStoreMutations, "cratis-guard-store-mutations"], [guardSecrets, "cratis-guard-secrets"]], payload, ctx);
234
+ const blocked = await runCommandGuards([[guardStoreMutations, "cratis-guard-store-mutations"], [guardSecrets, "cratis-guard-secrets"], [guardShellWrites, "cratis-guard-shell-writes"]], payload, ctx);
233
235
  if (blocked) return blocked;
234
236
  if (isInstalled(guardPrBody)) {
235
237
  const run = await runScript(guardPrBody, JSON.stringify(payload), ctx.cwd, ctx.signal);
@@ -10,8 +10,9 @@ Three layers:
10
10
  |---|---|---|---|---|
11
11
  | Pattern pass | `PostToolUse` on a write | `scripts/cratis-pattern-scan.sh` | zero tokens until a match | appends a one-line reminder to context, never blocks |
12
12
  | Hard block | `PreToolUse` on a write | `scripts/cratis-guard-writes.sh` | zero | exits **2** — the write does not happen |
13
+ | Hard block | `PreToolUse` on `Bash` | `scripts/cratis-guard-shell-writes.sh` | zero tokens; one batch Write/Edit classification | exits **2** — a protected reference requires read-only syntax throughout the command; best-effort, not a sandbox |
13
14
  | Hard block | `PreToolUse` on `Bash` | `scripts/cratis-guard-store-mutations.sh` | zero; parses only commands that mention `cratis` | exits **2** — the store-changing `cratis chronicle` command does not run |
14
- | Hard block | `PreToolUse` on `Bash` | `scripts/cratis-guard-secrets.sh` | zero; parses only commands that mention a credential-bearing tool or file | exits **2** — the guard is a **best-effort, defense-in-depth text filter, NOT a sandbox**: it refuses some harmless commands rather than model the whole shell. Real protection requires **OS-level sandboxing or file permissions**. A command is *tainted* when a protected file-name stem appears in any token, including option values, in any letter case, after quotes, backslashes and line continuations are removed. Only search regex text is exempt: `-e`/`--regexp` values, or the first operand when neither `-e` nor `-f` is present. `-f`/`--file` values and all other operands are paths, not exempt patterns. The stems are `.env`, `.pem`, `.p12`, `.pfx`, `id_rsa`, `id_ed25519`, `id_ecdsa`, `id_dsa`, `.netrc`, `.npmrc`, `.pgpass`, `.pypirc`, `.git-credentials`, `.kube/`, `kubeconfig`, `credentials`, `.docker/`, `/environ` and `run/secrets`. Stars, question marks, bracket expressions and grouped pathname patterns count as the characters they can match when the pattern retains at least two literal stem characters. A command is also tainted when an assignment value or any expanded word can contain a stem. A tainted command runs only when it is a single simple command with every word literal: `cat`, `head`, `tail`, `less`, `more`, `wc`, `grep`, `egrep`, `fgrep` or `rg` of paths that are not protected (such as `cat .env.example`); `test` of literal paths; or `cp SOURCE DEST` with no options and a source that is not protected (such as `cp .env.example .env`). A single simple `ls` or `stat` may also take glob operands, but not variables, substitutions, wrappers or other shell structure. Tainted searches cannot recurse, search a directory with `rg`, omit `rg` path operands, or use value-taking options other than `-e`/`--regexp`. Every other tainted command is refused, including variables, command substitution, globs for content readers, loops, conditionals, pipes, redirections, here-strings, here-documents, wrappers, `bash -c`, `eval` and transfer tools. Shell-option changes are checked even without a protected stem: modifying `shopt`, `setopt`, `unsetopt` and `emulate` are refused. `extglob` is refused as an option, not merely as text. Shell invocation `-o`/`-O` options, including clustered flags, must name a supported option. Expanded `set` arguments are refused. Only `set` flags `e`, `u`, `x`, `f`, `v`, `E`, `T` and named options `errexit`, `nounset`, `pipefail`, `xtrace`, `verbose`, `noglob`, `errtrace`, `functrace` (including their `+` forms) are supported. The message names the stem: run the read on its own with literal paths, or put long text that mentions the name in a file. Commands without a stem keep the full analysis. In that analysis a variable can hold any value the command assigns to it anywhere, a positional parameter or an unquoted expansion with glob or space characters is unknown, and an unknown file operand is refused. Residual classes include **shell glob grammar across bash and zsh, option toggles, option arity and quote concatenation**, as well as runtime-generated names, inherited state, filesystem indirection, user-defined commands, external programs and scripts, and searches without a named protected path. These classes are not modeled exhaustively. Use OS-level sandboxing or file permissions, harness isolation and least privilege as the primary boundary. Token files and key-extension globs (`*.key`, `*.jks`) are refused only through the listed reader, input, `dd` and transfer commands; see [`secrets.md`](../rules/secrets.md) |
15
+ | Hard block | `PreToolUse` on `Bash` | `scripts/cratis-guard-secrets.sh` | zero; parses only commands that mention a credential-bearing tool or file | exits **2** — the guard is a **best-effort, defense-in-depth text filter, NOT a sandbox**: it refuses some harmless commands rather than model the whole shell. Real protection requires **OS-level sandboxing or file permissions**. A command is *tainted* when a protected file-name stem appears in any token, including option values, in any letter case, after quotes, backslashes and line continuations are removed. Only search regex text is exempt: `-e`/`--regexp` values, or the first operand when neither `-e` nor `-f` is present. `-f`/`--file` values and all other operands are paths, not exempt patterns. The stems are `.env`, `.pem`, `.p12`, `.pfx`, `id_rsa`, `id_ed25519`, `id_ecdsa`, `id_dsa`, `.netrc`, `.npmrc`, `.pgpass`, `.pypirc`, `.git-credentials`, `.kube/`, `kubeconfig`, `credentials`, `.docker/`, `/environ` and `run/secrets`. Stars, question marks, bracket expressions and grouped pathname patterns count as the characters they can match when the pattern retains at least two literal stem characters. A command is also tainted when an assignment value or any expanded word can contain a stem. A tainted command runs only when it is a single simple command with every word literal: `cat`, `head`, `tail`, `less`, `more`, `wc`, `grep`, `egrep`, `fgrep` or `rg` of paths that are not protected (such as `cat .env.example`); `test` of literal paths; or `cp SOURCE DEST` with no options and a source that is not protected (for example, `cp .env.example example.txt`; the shell-write guard separately refuses `.env` destinations). A single simple `ls` or `stat` may also take glob operands, but not variables, substitutions, wrappers or other shell structure. Tainted searches cannot recurse, search a directory with `rg`, omit `rg` path operands, or use value-taking options other than `-e`/`--regexp`. Every other tainted command is refused, including variables, command substitution, globs for content readers, loops, conditionals, pipes, redirections, here-strings, here-documents, wrappers, `bash -c`, `eval` and transfer tools. Shell-option changes are checked even without a protected stem: modifying `shopt`, `setopt`, `unsetopt` and `emulate` are refused. `extglob` is refused as an option, not merely as text. Shell invocation `-o`/`-O` options, including clustered flags, must name a supported option. Expanded `set` arguments are refused. Only `set` flags `e`, `u`, `x`, `f`, `v`, `E`, `T` and named options `errexit`, `nounset`, `pipefail`, `xtrace`, `verbose`, `noglob`, `errtrace`, `functrace` (including their `+` forms) are supported. The message names the stem: run the read on its own with literal paths, or put long text that mentions the name in a file. Commands without a stem keep the full analysis. In that analysis a variable can hold any value the command assigns to it anywhere, a positional parameter or an unquoted expansion with glob or space characters is unknown, and an unknown file operand is refused. Residual classes include **shell glob grammar across bash and zsh, option toggles, option arity and quote concatenation**, as well as runtime-generated names, inherited state, filesystem indirection, user-defined commands, external programs and scripts, and searches without a named protected path. These classes are not modeled exhaustively. Use OS-level sandboxing or file permissions, harness isolation and least privilege as the primary boundary. Token files and key-extension globs (`*.key`, `*.jks`) are refused only through the listed reader, input, `dd` and transfer commands; see [`secrets.md`](../rules/secrets.md) |
15
16
  | Hard block | `PreToolUse` on `Bash` | `scripts/cratis-guard-pr-body.sh` | fetches shared rules only for `gh pr create/edit` | exits **2** for inline bodies, invalid notes or conflicting release labels; warns and allows when offline with no cache |
16
17
  | Cleanup of delivered work | `PostToolUse` on `Bash` (`gh pr merge`, `git pull/merge/worktree`) and `SessionStart` (Pi: `tool_result` and `session_start`) | `scripts/cratis-cleanup-worktrees.sh --hook` | zero when the command is unrelated | never blocks; removes delivered worktrees and branches, reports what it kept |
17
18
  | Quality gate (Claude) | `Stop` | `scripts/cratis-quality-gate.sh` | one build/test run, only when relevant files changed | exits **2** — the turn does not end |
@@ -39,7 +40,7 @@ they describe what a hook should do for tools that have no wiring yet.
39
40
 
40
41
  > Hooks use native wiring rather than a shared folder adapter: Claude Code reads `.claude/settings.json`;
41
42
  > Codex has a shell-only adapter described below. The Pi harness bridges the same scripts to its own events through the `cratis-hooks`
42
- > extension under `../harnesses/pi/extensions/` (its `bash` tool feeds the store-mutation and PR-body guards, its
43
+ > extension under `../harnesses/pi/extensions/` (its `bash` tool feeds the store-mutation, secrets, shell-write and PR-body guards, its
43
44
  > `write` and `edit` tools the write guard); Copilot would read `.github/hooks/*.json`, and no
44
45
  > Copilot wiring ships yet.
45
46
  >
@@ -80,7 +81,7 @@ alone. **Consumer activation through `cratis ai install/update` is not delivered
80
81
  adapter**: the CLI's Codex installation plan needs a separate change. Authoring setup
81
82
  and isolated fixtures are not evidence of installed or end-to-end Codex runtime coverage.
82
83
 
83
- The bridge runs the existing store-mutation guard and then the PR-body guard through
84
+ The bridge runs the store-mutation, secrets, PR-body and shell-write guards through
84
85
  Bash, using the payload's working directory and inherited environment. It never executes
85
86
  the pending command. A denial is final; the later guard cannot override it. Malformed
86
87
  input, a missing managed guard, spawn failure, signal, unexpected nonzero exit, malformed
@@ -95,8 +96,9 @@ This is a guardrail, **not absolute enforcement**. Node, Bash and Git are requir
95
96
  launch the adapter; native callback failure, crash, timeout, or malformed-response behavior
96
97
  can fail open before a supported denial is received. Other local hook configurations and
97
98
  specialized tool paths are outside this adapter's control. The existing scripts retain
98
- their own deliberate allowances and limits: missing `jq` makes the store, secret and write guards refuse every call; PR checks
99
- can allow with an unchecked/offline warning; command-text parsing cannot see all indirect
99
+ their own deliberate allowances and limits: missing `jq` makes the store, secret and write guards refuse every call;
100
+ the quality gate blocks changed trees (dry runs warn only), and pattern scanning warns once per session without blocking.
101
+ PR checks can allow with an unchecked/offline warning; command-text parsing cannot see all indirect
100
102
  execution. Inherited `CRATIS_HOOKS_ALLOW_STORE_MUTATIONS=1` and existing script configuration
101
103
  are preserved. An adapter exit **0** is not proof that every underlying check ran.
102
104
 
@@ -158,7 +160,7 @@ Rule numbers refer to the numbered list in [`../rules/general.md`](../rules/gene
158
160
 
159
161
  - Editing a file whose header marks it as Cratis-generated output — rule 15 `[contract]`
160
162
  - Writing content that opens with such a header (hand-authoring a "generated" proxy)
161
- - `Directory.Packages.props`, `global.json`, `NuGet.config` (also `NuGet.Config` and `nuget.config`),
163
+ - `package.json`, `Directory.Packages.props`, `global.json`, `NuGet.config` (also `NuGet.Config` and `nuget.config`),
162
164
  `yarn.lock`, `package-lock.json`, `pnpm-lock.yaml`, `packages.lock.json` — unless the
163
165
  repository's dependency-manifest policy allows them (see below)
164
166
  - `.env`, `.env.*`, `*.env` — secrets
@@ -171,9 +173,81 @@ Rule numbers refer to the numbered list in [`../rules/general.md`](../rules/gene
171
173
 
172
174
  For agent controls, report the intended change rather than rewriting permissions or hooks.
173
175
  A person edits settings; `cratis ai update` replaces managed files using the CLI's filesystem
174
- operations, not agent Write/Edit calls. This guard checks **Write/Edit targets only**: shell
175
- redirection, `cp`, another tool or process can still write them. It is a guardrail, not a sandbox;
176
- do not use those routes to work around a block.
176
+ operations, not agent Write/Edit calls. The shell-write guard scans the **whole command text**
177
+ for protected references, including nested strings, heredoc bodies and option values. It
178
+ removes simple quoting/escapes, checks case-insensitive spellings, and asks the write guard's
179
+ `--references` batch mode to classify candidate paths relative to the hook cwd. Original
180
+ spellings are retained too so existing generated headers can be checked on case-sensitive
181
+ filesystems. Glob/bracket patterns are checked against that same policy; brace patterns
182
+ are conservative. A directory containing owned controls/managed paths also counts, such as
183
+ `.claude`, `.pi/extensions` or installed `.cratis/ai`; no second tree list lives in the shell
184
+ guard. Other trees, including `.github/workflows`, count only if the write policy protects them.
185
+ Dependency manifests, including `package.json`, retain their origin/opt-in allowances.
186
+
187
+ **No protected reference: allow.** For example, `npm test`, `dotnet build`, `bash --version`,
188
+ `bash --help` and `cd src && echo ok > out.txt` are unaffected. If any reference exists,
189
+ **every simple command must be on this read-only allowlist**:
190
+
191
+ Only the following **exact options** are exempt, because they select/present reads rather
192
+ than create files or invoke helpers. Any other option denies, including long-option
193
+ abbreviations and unlisted `--option=value` forms. `--` ends option checking; remaining
194
+ arguments are operands. A lone `-` is a stdin operand. Value-free short flags may combine
195
+ (e.g. `grep -ni`); value-taking forms must use the explicitly listed spelling.
196
+
197
+ | Command | Permitted options |
198
+ | --- | --- |
199
+ | `cat` | `-n -A -v -e -t -s -b` |
200
+ | `head`, `tail` | `-n N`, `-nN`, `-c N`, `-N` (numeric counts); no `-f` |
201
+ | `wc` | `-l -w -c -m` |
202
+ | `ls` | `-l -a -A -1 -h -d -R -t -r -F` |
203
+ | `grep`, `egrep`, `fgrep` | `-n -i -r -R -l -L -c -v -w -x -F -E -H -h -o -q -s`; `-e PATTERN`, `-A N`, `-B N`, `-C N`; no long options |
204
+ | `echo` | `-n -e -E` |
205
+ | `printf`, `test`, `[`, `true`, `false`, `pwd` | None (in particular, no `printf -v`) |
206
+ | `git status` | `-s -b --short --porcelain` |
207
+ | `git diff` | `--stat --name-only --name-status --cached --staged --check -p -U<N> --no-color` |
208
+ | `git log` | `--oneline --stat --name-only -n N -nN -<N> -p --no-color --format=<fmt> --pretty=<fmt> --follow` |
209
+ | `git show` | `--stat --name-only -p --no-color --format=<fmt>` |
210
+ | `git add` | `-A -u -p` |
211
+ | `git commit` | `-m MSG`, `-mMSG`, `-a`, `-q`; `-F FILE` only for a literal non-protected file; no `--no-verify` |
212
+ | `git blame`, `ls-files`, `rev-parse`, `check-ignore`, `grep` | None |
213
+
214
+ No global git options are exempt (`-C`, `-c`, `--no-pager` etc. deny before the subcommand).
215
+ Git format values containing `%(` are not accepted. Index/commit operations are deliberate
216
+ allowances, not general shell execution permission. Output-to-file options such as
217
+ `git diff --output=...` are never exempt, even with a non-protected destination on a line
218
+ that references a protected file.
219
+
220
+ `gh` (all subcommands), `rg`, `ag`, `sort`, `uniq`, `cut`, `jq`, `yq`, `less`, `more`, `stat`,
221
+ `file`, `diff`, `cmp`, checksum tools, `realpath`, `dirname`, `basename`, `which` and `type`
222
+ are not on this list: their option surfaces are deliberately not analysed here.
223
+
224
+ Assignment prefixes and assignment-only commands are not allowlisted. Neither are wrappers,
225
+ evaluators, shells or writer verbs. `cd`, `pushd` and `popd` are **not** allowlisted when a
226
+ protected reference exists: `cd .claude && echo x > settings.json` refuses without tracking
227
+ cwd or inferring destinations. Shells refuse regardless of stdin descriptor, lone `-`, or
228
+ `-c` option spelling. Unparsed complex syntax, including substitutions and heredocs, refuses
229
+ once a protected reference exists; no shell bodies are interpreted.
230
+
231
+ Even an allowlisted command may not redirect output to a protected or non-literal target
232
+ (`$`, backticks or pathname patterns). Literal ordinary output is permitted, for example
233
+ `grep -n version package.json > /tmp/v.txt`; descriptor duplication such as `2>&1` is fine.
234
+ `cat package.json`, `git diff -- package.json`, `git commit -m "Update package.json"` and
235
+ `ls -la .env.example` are allowed reads/explicit index operations. `head -n 20 .env.example`
236
+ is allowed too: the write policy protects that file, but reading is not writing (the secrets
237
+ guard independently governs reads). `cp .env.example .env` refuses. Use the edit/write tools, or report
238
+ the intended change; those tools retain their own protection and are not a bypass.
239
+
240
+ Parser/classifier failures and bounded work limits fail closed (128 KiB command text,
241
+ 256 distinct candidates, 256 words per simple command, 64 simple commands, 64 existing glob
242
+ matches and a bounded glob-intersection state space). Pattern and tree references can make
243
+ this deliberately over-conservative.
244
+
245
+ This is **best-effort, not a sandbox**. Runtime names assembled from variables without a
246
+ protected name appearing literally are out of scope, as are aliases/functions, external
247
+ scripts, tool configuration/hooks and symlinks created during execution. Existing generated
248
+ headers are classified; content that would create a new generated header is not inspected by
249
+ the shell filter. OS permissions/sandboxing remain the primary boundary. Do not use another
250
+ route to work around a refusal.
177
251
 
178
252
  The generated-file check is anchored: the marker must be a comment opener at the start of one of
179
253
  the first five lines. A rule file or a document that merely *mentions* the marker is not blocked.
@@ -705,7 +779,7 @@ Each is an explicit, auditable opt-out — none of them is a default.
705
779
 
706
780
  | Variable | Effect |
707
781
  |---|---|
708
- | `CRATIS_HOOKS_ALLOW_PROTECTED_WRITES=1` | bypasses all write protection, including generated files, `.env`, agent controls and installed trees, while set in the harness environment; use only for an explicitly requested protected write. Repository-scoped manifest allowance uses `.cratis/ai.json` instead and never bypasses those protections |
782
+ | `CRATIS_HOOKS_ALLOW_PROTECTED_WRITES=1` | bypasses both Write/Edit and shell-write guards, including generated files, `.env`, agent controls and installed trees, while set in the harness environment; use only for an explicitly requested protected write. Repository-scoped manifest allowance uses `.cratis/ai.json` instead and never bypasses those protections |
709
783
  | `CRATIS_HOOKS_SKIP_SCAN=1` | disables the pattern pass |
710
784
  | `CRATIS_HOOKS_SKIP_GATE=1` | disables the quality gate |
711
785
  | `CRATIS_HOOKS_GATE_DRYRUN=1` | prints which gates would run, and why, then exits 0 |
@@ -727,9 +801,13 @@ Each is an explicit, auditable opt-out — none of them is a default.
727
801
  - **Gate commands are an argv array**, executed directly. They never pass through a shell.
728
802
  - **`jq` is the dependency for the write, store-mutation, secret, pattern and quality hooks.** The
729
803
  write, store-mutation and secret guards refuse every call while it is missing (exit 2, with the
730
- reason and the install hint on stderr); the pattern and quality hooks degrade to a silent no-op,
731
- because those must never break a session. The
732
- PR-body hook uses Node instead, and the checker uses Git and `gh` as described above.
804
+ reason and the install hint on stderr). Without `jq`, the quality gate blocks changed trees with
805
+ an install hint (exit 2); dry runs warn with exit 0. Unchanged trees, non-Git directories,
806
+ Stop-hook re-entry and `CRATIS_HOOKS_SKIP_GATE=1` still exit 0 silently. A person accepting
807
+ unverified turn ends can set that escape hatch in the environment the harness was started from.
808
+ The pattern scan exits 0 with a one-line stderr notice at most once per session (or on each call
809
+ if session state is unavailable). The PR-body hook uses Node instead, and the checker uses Git
810
+ and `gh` as described above.
733
811
  - **Fail safe.** Malformed config, empty stdin, a missing file, a binary file, a file over 2 MB:
734
812
  all exit 0 silently. The one deliberate exception is the store-mutation guard's command lists:
735
813
  an unreadable shipped or local list is not an empty allowlist that happens to pass, so every `cratis chronicle`
@@ -763,6 +841,12 @@ jq -nc '{session_id:"t", cwd:"'"$PWD"'", tool_name:"Edit",
763
841
  tool_input:{file_path:"'"$PWD"'/Directory.Packages.props", new_string:"x"}}' \
764
842
  | bash .cratis/ai/hooks/scripts/cratis-guard-writes.sh; echo "exit=$?"
765
843
 
844
+ # Shell-write guard: expect exit 2, then exit 0 for an ordinary destination
845
+ jq -nc '{cwd:"'"$PWD"'", tool_name:"Bash", tool_input:{command:"echo x > .env"}}' \
846
+ | bash .cratis/ai/hooks/scripts/cratis-guard-shell-writes.sh; echo "exit=$?"
847
+ jq -nc '{cwd:"'"$PWD"'", tool_name:"Bash", tool_input:{command:"echo x > notes.md"}}' \
848
+ | bash .cratis/ai/hooks/scripts/cratis-guard-shell-writes.sh; echo "exit=$?"
849
+
766
850
  # Store-mutation guard, both directions: expect exit 2, then exit 0 for the read-only neighbor
767
851
  jq -nc '{tool_name:"Bash", tool_input:{command:"cratis chronicle observers replay my-observer --yes"}}' \
768
852
  | bash .cratis/ai/hooks/scripts/cratis-guard-store-mutations.sh; echo "exit=$?"
@@ -1275,7 +1275,7 @@ BEGIN {
1275
1275
  if (pass == 1 && bindings > 0) continue
1276
1276
  if (TAINT != "" && (complex || queued != 1 || commands != 1 || !simple_ok)) {
1277
1277
  other_reports = reports; reports = ""
1278
- report("the command names a protected file (" TAINT ") and is not a single literal read", "run the read on its own with literal paths, e.g. cat .env.example or cp .env.example .env; split compound commands into separate calls; do not build the name with variables, globs, loops, pipes, redirections or nested shells; for a commit message or PR body that mentions the name, write the text to a file with the file tool and pass the file")
1278
+ report("the command names a protected file (" TAINT ") and is not a single literal read", "run the read on its own with literal paths, e.g. cat .env.example; split compound commands into separate calls; do not build the name with variables, globs, loops, pipes, redirections or nested shells; for a commit message or PR body that mentions the name, write the text to a file with the file tool and pass the file")
1279
1279
  reports = reports other_reports
1280
1280
  }
1281
1281
  printf "%s", reports
@@ -0,0 +1,236 @@
1
+ #!/usr/bin/env bash
2
+ # Whole-command reference filter, not a shell interpreter or sandbox.
3
+ # The Write/Edit guard is the only protected-path policy. With any protected reference,
4
+ # accept only the small read-only command language below; never infer write destinations.
5
+ set -euo pipefail
6
+ export LC_ALL=C
7
+ script_directory="${BASH_SOURCE[0]%/*}"
8
+ [ "$script_directory" != "${BASH_SOURCE[0]}" ] || script_directory=.
9
+ # shellcheck source=SCRIPTDIR/hook-lib.sh
10
+ . "$script_directory/hook-lib.sh"
11
+ [ "${CRATIS_HOOKS_ALLOW_PROTECTED_WRITES:-0}" = 1 ] && exit 0
12
+ input=""
13
+ IFS= read -r -d '' input || true
14
+ [ -n "$input" ] || exit 0
15
+ hook_require_jq cratis-guard-shell-writes CRATIS_HOOKS_ALLOW_PROTECTED_WRITES
16
+ parser_failed() {
17
+ printf '%s\n' 'BLOCKED by cratis-guard-shell-writes: parser failed; cannot check this tool call.' >&2
18
+ exit 2
19
+ }
20
+ cwd="" command_text="" parser_status=""
21
+ {
22
+ IFS= read -r -d '' cwd
23
+ IFS= read -r -d '' command_text
24
+ IFS= read -r -d '' parser_status
25
+ } < <(jq -j -s '
26
+ def field(path): ([try (path // empty) catch empty] | first // "")
27
+ | if type == "string" then . else tojson end | gsub("\u0000"; "");
28
+ if length == 1 then .[0] else error("expected one JSON document") end
29
+ | [field(.cwd), field(.tool_input.command)] | .[] | ., "\u0000"
30
+ ' <<<"$input" 2>/dev/null && printf 'ok\0') || parser_failed
31
+ [ "$parser_status" = ok ] || parser_failed
32
+ [ -n "$command_text" ] || exit 0
33
+ cwd="${cwd:-$PWD}"
34
+ [ "${#command_text}" -le 131072 ] || parser_failed
35
+
36
+ IFS= read -r -d '' program <<'AWK' || true
37
+ function candidate(s) {
38
+ if (s == "" || s ~ /[\n\r\t]/ || (s in seen)) return
39
+ if (++candidates > 256 || length(s) > 4096) exit 2
40
+ seen[s] = 1; print s
41
+ if (s != tolower(s)) candidate(tolower(s))
42
+ # A generic attached option prefix must not hide a path spelling (-t.pi/...).
43
+ if (s ~ /^-/ && match(s, /[.\/]/) && RSTART > 1) candidate(substr(s, RSTART))
44
+ }
45
+ function scan(s, n, i, c, word) {
46
+ n = length(s)
47
+ for (i = 1; i <= n; i++) {
48
+ c = substr(s, i, 1)
49
+ if (c ~ /[ \t\n\r;|&<>()\047"`$=\\]/) { candidate(word); word = "" }
50
+ else word = word c
51
+ }
52
+ candidate(word)
53
+ # Braces have a second boundary view; retain the original pattern above too.
54
+ if (s ~ /[{}]/) { gsub(/[{}]/, " ", s); scan(s) }
55
+ }
56
+ # Reuse ANSI-C decoding for reference spellings, not for interpreting shell code.
57
+ function ansi(s, i, c, c2, v, k, limit, d, digits) {
58
+ ansi_word = ""
59
+ while (i <= length(s)) {
60
+ c = substr(s, i++, 1)
61
+ if (c == "\047") return i
62
+ if (c != "\\") { ansi_word = ansi_word c; continue }
63
+ c2 = substr(s, i++, 1); v = -1
64
+ if (c2 in ESC) v = ESC[c2]
65
+ else if (c2 ~ /^[0-7]$/) {
66
+ v = c2 + 0
67
+ for (k = 0; k < 2 && substr(s, i, 1) ~ /^[0-7]$/; k++) { v = v * 8 + substr(s, i++, 1) }
68
+ v = v % 256
69
+ } else if (c2 == "x" || c2 == "u" || c2 == "U") {
70
+ limit = c2 == "x" ? 2 : c2 == "u" ? 4 : 8; v = digits = 0
71
+ while (digits < limit && (d = tolower(substr(s, i, 1))) != "" && (d in HEX)) { v = v * 16 + HEX[d]; i++; digits++ }
72
+ if (!digits || v > 255) v = -1
73
+ }
74
+ if (v > 0) ansi_word = ansi_word sprintf("%c", v)
75
+ else if (v < 0) ansi_word = ansi_word c2
76
+ }
77
+ return i
78
+ }
79
+ function unquote(s, i, c, c2, q, out, quoted) {
80
+ for (i = 1; i <= length(s); i++) {
81
+ c = substr(s, i, 1); c2 = substr(s, i + 1, 1)
82
+ if (c == "$" && c2 == "\047" && q != "\047") { i = ansi(s, i + 2) - 1; out = out ansi_word; continue }
83
+ if (c == "\\" && q != "\047") { if (c2 != "\n") { out = out c2; quoted = quoted c2 }; i++; continue }
84
+ if ((c == "\047" || c == "\"") && (q == "" || q == c)) {
85
+ if (q == c) { candidate(quoted); quoted = ""; q = "" } else q = c
86
+ continue
87
+ }
88
+ out = out c; if (q != "") quoted = quoted c
89
+ }
90
+ return out
91
+ }
92
+ function protected(s) { return s in protected_paths }
93
+ function endword() {
94
+ if (!inword) return
95
+ if (redirect) {
96
+ if (!(redirect == 2 && word ~ /^([0-9]+|-)$/) && (word ~ /[$`*?\[{]/ || protected(word))) bad = 1
97
+ redirect = 0
98
+ } else {
99
+ if (++argc > 256) bad = 1
100
+ W[argc] = word
101
+ }
102
+ word = ""; inword = 0
103
+ }
104
+ # Each exemption permits only the reviewed read/presentation options below. No unknown
105
+ # options, long-option abbreviations or implicit value-taking short clusters are accepted.
106
+ # Every table entry has a sibling ALLOW test and rejected-option neighbors.
107
+ function policy(verb, flags, longs, words, n, k) {
108
+ verbs[verb] = 1; short_options[verb] = flags
109
+ n = split(longs, words, " ")
110
+ for (k = 1; k <= n; k++) long_options[verb, words[k]] = 1
111
+ }
112
+ function short_flags(w, flags, k) {
113
+ if (w !~ /^-[^-]/) return 0
114
+ for (k = 2; k <= length(w); k++) if (!index(flags, substr(w, k, 1))) return 0
115
+ return 1
116
+ }
117
+ function number(s) { return s ~ /^[+-]?[0-9]+$/ }
118
+ function options_allowed(verb, first, i, w) {
119
+ for (i = first; i <= argc; i++) {
120
+ w = W[i]
121
+ if (w == "--") return 1
122
+ if (w !~ /^-/ || w == "-") continue
123
+ if ((verb, w) in long_options) continue
124
+ if (verb == "head" || verb == "tail" || verb == "git log") {
125
+ if (w == "-n" || (verb != "git log" && w == "-c")) {
126
+ if (++i > argc || !number(W[i])) return 0
127
+ continue
128
+ }
129
+ if (w ~ /^-n[+-]?[0-9]+$/ || w ~ /^-[0-9]+$/) continue
130
+ }
131
+ if (verb == "grep" || verb == "egrep" || verb == "fgrep") {
132
+ if (w == "-e") { if (++i > argc) return 0; continue }
133
+ if (w == "-A" || w == "-B" || w == "-C") {
134
+ if (++i > argc || !number(W[i])) return 0
135
+ continue
136
+ }
137
+ }
138
+ if (verb == "git diff" && w ~ /^-U[0-9]+$/) continue
139
+ if ((verb == "git log" && w ~ /^--(format|pretty)=/) || (verb == "git show" && w ~ /^--format=/)) {
140
+ if (index(w, "%(")) return 0
141
+ continue
142
+ }
143
+ if (verb == "git commit") {
144
+ if (w == "-m") { if (++i > argc) return 0; continue }
145
+ if (w ~ /^-m./) continue
146
+ if (w == "-F") {
147
+ if (++i > argc || W[i] ~ /[$`*?\[{]/ || protected(W[i])) return 0
148
+ continue
149
+ }
150
+ }
151
+ if (!short_flags(w, short_options[verb])) return 0
152
+ }
153
+ return 1
154
+ }
155
+ function allow_command( verb, first) {
156
+ if (!argc) return
157
+ if (++commands > 64) { bad = 1; return }
158
+ verb = W[1]; first = 2
159
+ # No global git option is exempt, including -C, -c and --no-pager.
160
+ if (verb == "git") { verb = verb " " W[2]; first = 3 }
161
+ if (!(verb in verbs) || !options_allowed(verb, first)) bad = 1
162
+ }
163
+ function command_end() { endword(); allow_command(); delete W; argc = 0 }
164
+ function readonly(s, i, c, c2, sq, dq) {
165
+ for (i = 1; i <= length(s); i++) {
166
+ c = substr(s, i, 1); c2 = substr(s, i + 1, 1)
167
+ if (sq) { if (c == "\047") sq = 0; else word = word c; continue }
168
+ if (c == "\\") { if (c2 != "\n") { word = word c2; inword = 1 }; i++; continue }
169
+ if (c == "\047" && !dq) { sq = inword = 1; continue }
170
+ if (c == "\"") { dq = !dq; inword = 1; continue }
171
+ # Expansions and globs can supply option words the per-verb tables never see.
172
+ if (c == "`" || c == "$") bad = 1
173
+ if (dq) { word = word c; continue }
174
+ # A glob that starts a word, or follows a leading dash, may expand to an option word.
175
+ if ((c == "*" || c == "?" || c == "[") && (word == "" ? !(c == "[" && c2 ~ /[ \t]/) : substr(word, 1, 1) == "-")) bad = 1
176
+ if (c == "#" && !inword) { while (i <= length(s) && substr(s, i, 1) != "\n") i++; c = "\n" }
177
+ if (c == "(" || c == ")" || c == "{" || c == "}") bad = 1
178
+ if (c == ">" || c == "<" || (c == "&" && c2 == ">")) {
179
+ if (inword && word ~ /^[0-9]+$/) { word = ""; inword = 0 } else endword()
180
+ if (redirect) bad = 1
181
+ if (c == "<" && (c2 == "<" || c2 == "(")) bad = 1
182
+ redirect = c == ">" || c == "&" || (c == "<" && c2 == ">")
183
+ if (c == ">" && c2 == "&") redirect = 2
184
+ if (c2 ~ /[><&|]/) { i++; if (substr(s, i + 1, 1) == ">") i++ }
185
+ continue
186
+ }
187
+ if (c ~ /[;|&\n]/) { command_end(); if (redirect) bad = 1; continue }
188
+ if (c ~ /[ \t\r]/) { endword(); continue }
189
+ word = word c; inword = 1
190
+ }
191
+ command_end()
192
+ if (sq || dq || redirect) bad = 1
193
+ return !bad
194
+ }
195
+ BEGIN {
196
+ policy("cat", "nAvetsb", "")
197
+ policy("head", "", ""); policy("tail", "", "")
198
+ policy("wc", "lwcm", ""); policy("ls", "laA1hdRtrF", "")
199
+ policy("grep", "nirRlLcvwxFEHhoqs", "")
200
+ policy("egrep", "nirRlLcvwxFEHhoqs", ""); policy("fgrep", "nirRlLcvwxFEHhoqs", "")
201
+ policy("echo", "neE", "")
202
+ policy("printf", "", ""); policy("test", "", ""); policy("[", "", "")
203
+ policy("true", "", ""); policy("false", "", ""); policy("pwd", "", "")
204
+ policy("git status", "sb", "--short --porcelain")
205
+ policy("git diff", "p", "--stat --name-only --name-status --cached --staged --check --no-color")
206
+ policy("git log", "p", "--oneline --stat --name-only --no-color --follow")
207
+ policy("git show", "p", "--stat --name-only --no-color")
208
+ policy("git add", "Aup", ""); policy("git commit", "aq", "")
209
+ policy("git blame", "", ""); policy("git ls-files", "", "")
210
+ policy("git rev-parse", "", ""); policy("git check-ignore", "", ""); policy("git grep", "", "")
211
+ for (i = 0; i < 16; i++) HEX[substr("0123456789abcdef", i + 1, 1)] = i
212
+ ESC["n"] = 10; ESC["r"] = 13; ESC["t"] = 9; ESC["\\"] = 92; ESC["\047"] = 39; ESC["\""] = 34
213
+ text = ENVIRON["GSW_COMMAND"]
214
+ if (ENVIRON["GSW_MODE"] == "references") { scan(text); scan(unquote(text)); exit 0 }
215
+ n = split(ENVIRON["GSW_PROTECTED"], a, "\n"); for (i = 1; i <= n; i++) protected_paths[a[i]] = 1
216
+ exit readonly(text) ? 0 : 1
217
+ }
218
+ AWK
219
+ candidates_text="$(GSW_COMMAND="$command_text" GSW_MODE=references LC_ALL=C awk "$program" </dev/null)" || parser_failed
220
+ [ -n "$candidates_text" ] || exit 0
221
+ candidates=()
222
+ while IFS= read -r candidate; do candidates[${#candidates[@]}]="$candidate"; done <<<"$candidates_text"
223
+ classifier="$script_directory/cratis-guard-writes.sh"
224
+ [ -f "$classifier" ] || {
225
+ printf '%s\n' 'BLOCKED by cratis-guard-shell-writes: could not check references (write guard is missing).' >&2
226
+ exit 2
227
+ }
228
+ classifier_input="$(jq -nc --arg cwd "$cwd" --args '{cwd:$cwd,tool_input:{file_paths:$ARGS.positional}}' -- "${candidates[@]}")" || parser_failed
229
+ references="$("$BASH" "$classifier" --references <<<"$classifier_input")" || {
230
+ printf '%s\n' 'BLOCKED by cratis-guard-shell-writes: could not check references (write guard failed).' >&2
231
+ exit 2
232
+ }
233
+ [ -n "$references" ] || exit 0
234
+ if GSW_COMMAND="$command_text" GSW_MODE=readonly GSW_PROTECTED="$references" LC_ALL=C awk "$program" </dev/null; then exit 0; fi
235
+ printf "BLOCKED by cratis-guard-shell-writes: protected reference '%s' (cratis-guard-writes). Use the edit/write tools, or report the intended change.\n" "${references%%$'\n'*}" >&2
236
+ exit 2
@@ -44,13 +44,16 @@ parser_failed() {
44
44
  # as a command substitution would drop them); a missing, null or false path is empty.
45
45
  # The process substitution's exit status does not reach the reading group, and Bash 3.2 (macOS /bin/bash)
46
46
  # cannot wait on its PID, so a sentinel field is written only after jq succeeds.
47
- cwd="" file="" notebook="" new_content="" new_string="" parser_status=""
47
+ reference_mode=0
48
+ [ "${1:-}" != --references ] || reference_mode=1
49
+ cwd="" file="" notebook="" new_content="" new_string="" references="" parser_status=""
48
50
  {
49
51
  IFS= read -r -d '' cwd
50
52
  IFS= read -r -d '' file
51
53
  IFS= read -r -d '' notebook
52
54
  IFS= read -r -d '' new_content
53
55
  IFS= read -r -d '' new_string
56
+ IFS= read -r -d '' references
54
57
  IFS= read -r -d '' parser_status
55
58
  } < <(jq -j -s '
56
59
  def field(path): ([try (path // empty) catch empty] | first // "")
@@ -60,7 +63,7 @@ cwd="" file="" notebook="" new_content="" new_string="" parser_status=""
60
63
  # so no field from a later document can stand in for the sentinel.
61
64
  if length == 1 then .[0] else error("expected one JSON document") end
62
65
  | [field(.cwd), field(.tool_input.file_path), field(.tool_input.notebook_path),
63
- field(.tool_input.content), field(.tool_input.new_string)]
66
+ field(.tool_input.content), field(.tool_input.new_string), (field(.tool_input.file_paths) | if . == "" then "[]" else . end)]
64
67
  | .[] | ., "\u0000"
65
68
  ' <<<"$input" 2>/dev/null && printf 'ok\0') || parser_failed
66
69
  [ "$parser_status" = "ok" ] || parser_failed
@@ -71,7 +74,7 @@ done
71
74
 
72
75
  [ -n "$cwd" ] || cwd="$(hook_repo_root)"
73
76
  [ -n "$file" ] || file="$notebook"
74
- [ -n "$file" ] || exit 0
77
+ [ -n "$file" ] || [ "$reference_mode" = 1 ] || exit 0
75
78
 
76
79
  # dir_of / base_of / relative_to mirror dirname, basename and hook_relpath for the absolute,
77
80
  # normalized paths used here. abspath mirrors hook_abspath. All return through REPLY.
@@ -120,12 +123,6 @@ normalize_target_path() {
120
123
  REPLY="${normalized:-/}"
121
124
  }
122
125
 
123
- abspath "$file" "$cwd"
124
- normalize_target_path "$REPLY"
125
- file="$REPLY"
126
- base_of "$file"
127
- base="$REPLY"
128
-
129
126
  block() {
130
127
  # Pi can run the bundled script in a consumer checkout; this root is only for diagnostics,
131
128
  # so it is looked up only when a write is actually refused.
@@ -189,9 +186,92 @@ origin_matches() {
189
186
  return "$matched"
190
187
  }
191
188
 
189
+ # One policy vocabulary for normal Write/Edit and whole-command reference checks.
190
+ manifest_patterns=(package.json Directory.Packages.props global.json NuGet.config yarn.lock package-lock.json pnpm-lock.yaml packages.lock.json)
191
+ environment_patterns=('.env' '.env.*' '*.env')
192
+ control_patterns=('.claude/settings.json' '.claude/settings.local.json' '.mcp.json' '.pi/settings.json' '.pi/extensions/*')
193
+
194
+ # Glob-language intersection, not expansion/eval. A star has an epsilon transition and
195
+ # a character loop. The product automaton accepts iff the two patterns share a spelling.
196
+ # Braces conservatively become a star; bracket classes retain their ordinary meaning.
197
+ IFS= read -r -d '' glob_program <<'AWK' || true
198
+ function tokens(s, side, i, c, j, t, n) {
199
+ s = tolower(s)
200
+ for (i = 1; i <= length(s); i++) {
201
+ c = substr(s, i, 1); t = c
202
+ if (c == "{") { j = index(substr(s, i), "}"); if (j) i += j - 1; t = "*" }
203
+ else if (c == "[") {
204
+ j = index(substr(s, i + 1), "]")
205
+ if (j) { t = substr(s, i, j + 1); i += j; sub(/^\[!/, "[^", t) }
206
+ }
207
+ N[side]++; A[side, N[side]] = t
208
+ }
209
+ }
210
+ function push(i, j, key) { key = i SUBSEP j; if (!(key in seen)) { seen[key] = 1; L[++last] = i; R[last] = j } }
211
+ function accepts(t, c, side) {
212
+ if (side == 1 && c == "/" && (t == "*" || t == "?" || length(t) > 1)) return 0
213
+ return t == "*" || t == "?" || (length(t) > 1 && substr(t, 1, 1) == "[" ? c ~ ("^" t "$") : t == c)
214
+ }
215
+ function compatible(a, b, k, c) {
216
+ if (length(a) == 1 && a != "*" && a != "?") return accepts(b, a, 2)
217
+ if (length(b) == 1 && b != "*" && b != "?") return accepts(a, b, 1)
218
+ for (k = 1; k < 256; k++) { c = sprintf("%c", k); if (accepts(a, c, 1) && accepts(b, c, 2)) return 1 }
219
+ return 0
220
+ }
221
+ BEGIN {
222
+ tokens(ENVIRON["REF_LEFT"], 1); tokens(ENVIRON["REF_RIGHT"], 2); push(1, 1)
223
+ while (next_state < last) {
224
+ if (last > 65536) exit 2
225
+ i = L[++next_state]; j = R[next_state]
226
+ if (i > N[1] && j > N[2]) exit 0
227
+ a = A[1, i]; b = A[2, j]
228
+ if (a == "*") push(i + 1, j)
229
+ if (b == "*") push(i, j + 1)
230
+ if (i <= N[1] && j <= N[2] && compatible(a, b)) push(i + (a != "*"), j + (b != "*"))
231
+ }
232
+ exit 1
233
+ }
234
+ AWK
235
+
236
+ names_match() {
237
+ local value="$1" pattern status LC_ALL=C
238
+ shift
239
+ for pattern in "$@"; do
240
+ if [ "$reference_pattern" = 1 ]; then
241
+ if REF_LEFT="$value" REF_RIGHT="$pattern" LC_ALL=C awk "$glob_program" </dev/null; then return 0
242
+ else status=$?; [ "$status" = 1 ] || parser_failed; fi
243
+ else
244
+ shopt -s nocasematch
245
+ # Intentional policy glob matching, not literal filename equality.
246
+ # shellcheck disable=SC2053
247
+ if [[ "$value" == $pattern ]]; then shopt -u nocasematch; return 0; fi
248
+ shopt -u nocasematch
249
+ fi
250
+ done
251
+ return 1
252
+ }
253
+
254
+ # Directory references include owned descendants, without classifying every ordinary
255
+ # directory as a possible environment file. Normal Write/Edit classification is unchanged.
256
+ control_match() {
257
+ local value="$1" reference_pattern="$reference_pattern" pattern LC_ALL=C
258
+ shift
259
+ if names_match "$value" "$@"; then return 0; fi
260
+ [ "$reference_mode" = 1 ] || return 1
261
+ if [ "$reference_pattern" = 0 ]; then
262
+ shopt -s nocasematch
263
+ for pattern in "$@"; do
264
+ if [[ "$pattern" == "${value%/}/"* ]]; then shopt -u nocasematch; return 0; fi
265
+ done
266
+ shopt -u nocasematch
267
+ return 1
268
+ fi
269
+ names_match "${value%/}/*" "$@"
270
+ }
271
+
192
272
  # ── 4. Agent controls and installed managed trees ─────────────────────────────
193
273
  agent_control_target() {
194
- local target="$1" directory policy_root target_rel managed
274
+ local target="$1" directory policy_root target_rel managed pattern
195
275
  dir_of "$target"
196
276
  directory="$REPLY"
197
277
  # Keep the addressed spelling here, even when an adapter directory is a symlink.
@@ -205,23 +285,21 @@ agent_control_target() {
205
285
  relative_to "$target" "$policy_root"
206
286
  target_rel="$REPLY"
207
287
  if [ -f "$policy_root/.cratis/ai.manifest.json" ]; then
208
- case "$target_rel" in
209
- .cratis/ai/*) return 0 ;;
210
- .claude/* | .pi/*)
211
- # The installer records adapter ownership in Integrations (Path, IsDirectory),
212
- # not Files: those destinations are relative to the managed corpus root.
213
- # A readable manifest must establish ownership before classifying local adapters.
214
- managed="$(jq -r --arg path "$target_rel" '
215
- (.Integrations // [])
216
- | if type != "array" then false else
217
- [.[] | select(type == "object") | select(.Path | type == "string")]
218
- | any(.[]; . as $entry | $entry.Path == $path
219
- or ($entry.IsDirectory == true and ($path | startswith($entry.Path + "/"))))
220
- end
221
- ' "$policy_root/.cratis/ai.manifest.json" 2>/dev/null)" || parser_failed
222
- [ "$managed" != "true" ] || return 0
223
- ;;
224
- esac
288
+ if control_match "$target_rel" '.cratis/ai/*'; then return 0; fi
289
+ if control_match "$target_rel" '.claude/*' '.pi/*'; then
290
+ # Integration paths, not corpus Files, establish adapter ownership.
291
+ managed="$(jq -r '
292
+ (.Integrations // []) | if type != "array" then empty else
293
+ .[] | select(type == "object") | select(.Path | type == "string")
294
+ | if (.Path | explode | any(.[]; . == 0 or . == 9 or . == 10 or . == 13)) then error("invalid integration path") else
295
+ .Path, (if .IsDirectory == true then .Path + "/*" else empty end) end
296
+ end
297
+ ' "$policy_root/.cratis/ai.manifest.json" 2>/dev/null)" || parser_failed
298
+ while IFS= read -r pattern; do
299
+ [ -n "$pattern" ] || continue
300
+ if control_match "$target_rel" "$pattern"; then return 0; fi
301
+ done <<<"$managed"
302
+ fi
225
303
  else
226
304
  # The corpus is authored source in Cratis/AI, not a managed installation.
227
305
  repository_origin "$policy_root"
@@ -229,20 +307,9 @@ agent_control_target() {
229
307
  return 1
230
308
  fi
231
309
  fi
232
- case "$target_rel" in
233
- .claude/settings.json | .claude/settings.local.json | .mcp.json \
234
- | .pi/settings.json | .pi/extensions/*) return 0 ;;
235
- esac
236
- return 1
310
+ control_match "$target_rel" "${control_patterns[@]}"
237
311
  }
238
312
 
239
- physical_target_path "$file" || physical_file=""
240
- if agent_control_target "$file" || { [ -n "$physical_file" ] && agent_control_target "$physical_file"; }; then
241
- block \
242
- "This target controls the agent's permissions or extensions, or belongs to an installed managed corpus/adapter tree. Agent Write/Edit calls may not alter their own controls or managed instructions." \
243
- "Instead: report the intended change. Use 'cratis ai update' for managed files, or let a person change settings. An explicitly authorized protected write requires CRATIS_HOOKS_ALLOW_PROTECTED_WRITES=1 in the harness environment. Do not retry through a shell write."
244
- fi
245
-
246
313
  # ── 1. Generated files ────────────────────────────────────────────────────────
247
314
  # The marker must be a real header: a comment opener at the start of one of the first few lines.
248
315
  # Merely *mentioning* the string — documentation, a rule file, this corpus — is not a match.
@@ -259,24 +326,6 @@ first_lines_carry_marker() {
259
326
  return 1
260
327
  }
261
328
 
262
- # The cheap in-shell header test runs first; grep -I then confirms the file is text, as before.
263
- if [ -f "$file" ] \
264
- && first_lines_carry_marker 2>/dev/null <"$file" \
265
- && LC_ALL=C grep -Iq . "$file" 2>/dev/null; then
266
- block \
267
- "This file is generated output (its header marks it as generated by Cratis). Rule 15 [contract] in .cratis/ai/rules/general.md: never edit a generated file — the next build overwrites it." \
268
- "Instead: change the C# source it is generated from (the [Command] / [ReadModel] record) and rebuild with 'dotnet build -c Debug' to regenerate the proxy."
269
- fi
270
-
271
- # The same guard for authoring a *new* file that pretends to be generated output.
272
- [ -n "$new_content" ] || new_content="$new_string"
273
- if [ -n "$new_content" ] \
274
- && first_lines_carry_marker <<<"$new_content"; then
275
- block \
276
- "The content being written opens with a Cratis generated-file header. Proxies are produced by the Cratis proxy generator, never hand-written." \
277
- "Instead: write the C# source and run 'dotnet build -c Debug' to generate the proxy."
278
- fi
279
-
280
329
  # ── 2. Dependency manifests, lockfiles, SDK and NuGet configuration ───────────
281
330
  manifest_writes_allowed() {
282
331
  local setting="" directory policy_root start="$PWD"
@@ -307,23 +356,71 @@ manifest_writes_allowed() {
307
356
  origin_matches '^(https://github\.com/|git@github\.com:|ssh://git@github\.com(:[0-9]+)?/)cratis/[a-z0-9_.-]+/?$'
308
357
  }
309
358
 
310
- case "$base" in
311
- Directory.Packages.props | global.json | NuGet.config | NuGet.Config | nuget.config \
312
- | yarn.lock | package-lock.json | pnpm-lock.yaml | packages.lock.json)
313
- if manifest_writes_allowed; then exit 0; fi
314
- block \
315
- "'$base' is a dependency manifest / lockfile / SDK or NuGet configuration file. .cratis/ai/rules/general.md (Source-of-Truth Discipline): don't change these unless explicitly asked." \
316
- "To allow dependency updates for this repository, set allowDependencyManifestWrites to true in .cratis/ai.json. If the user explicitly asked for this change, re-run the tool call with CRATIS_HOOKS_ALLOW_PROTECTED_WRITES=1 exported. Otherwise take the dependency as given and solve the problem in source."
317
- ;;
318
- esac
359
+ # Return the category, leaving normal Write/Edit diagnostics unchanged below.
360
+ classify_file() {
361
+ local reference_pattern="${2:-0}"
362
+ abspath "$1" "$cwd"; normalize_target_path "$REPLY"; file="$REPLY"
363
+ base_of "$file"; base="$REPLY"
364
+ physical_target_path "$file" || physical_file=""
365
+ if agent_control_target "$file" || { [ -n "$physical_file" ] && agent_control_target "$physical_file"; }; then
366
+ classification=controls; return 0
367
+ fi
368
+ if [ -f "$file" ] && first_lines_carry_marker 2>/dev/null <"$file" && LC_ALL=C grep -Iq . "$file" 2>/dev/null; then
369
+ classification=generated; return 0
370
+ fi
371
+ if [ -n "$new_content" ] && first_lines_carry_marker <<<"$new_content"; then classification=content; return 0; fi
372
+ if names_match "$base" "${manifest_patterns[@]}"; then
373
+ if manifest_writes_allowed; then return 1; fi
374
+ classification=manifest; return 0
375
+ fi
376
+ if names_match "$base" "${environment_patterns[@]}"; then classification=environment; return 0; fi
377
+ return 1
378
+ }
319
379
 
320
- # ── 3. Environment files ──────────────────────────────────────────────────────
321
- case "$base" in
322
- .env | .env.* | *.env)
323
- block \
324
- "'$base' is an environment file and normally holds secrets. Hooks block writing it so credentials are never authored, rewritten, or echoed by an agent." \
325
- "Instead: tell the user exactly which variable to set and let them edit the file. If they explicitly asked you to write it, re-run with CRATIS_HOOKS_ALLOW_PROTECTED_WRITES=1 exported."
326
- ;;
327
- esac
380
+ if [ "$reference_mode" = 1 ]; then
381
+ candidates=() parser_status=""
382
+ while IFS= read -r -d '' candidate; do candidates[${#candidates[@]}]="$candidate"; done < <(
383
+ jq -j 'if type == "array" and length <= 256 and all(.[]; type == "string" and (explode | all(.[]; . != 0 and . != 9 and . != 10 and . != 13)))
384
+ then .[], "ok" else error("invalid reference candidates") end | ., "\u0000"' <<<"$references" 2>/dev/null
385
+ )
386
+ [ "${#candidates[@]}" -gt 0 ] || parser_failed
387
+ last=$((${#candidates[@]} - 1))
388
+ [ "${candidates[$last]}" = ok ] || parser_failed
389
+ [ "$last" -gt 0 ] || exit 0
390
+ unset 'candidates[last]'
391
+ new_content=""
392
+ for candidate in "${candidates[@]}"; do
393
+ reference_pattern=0
394
+ case "$candidate" in *'*'* | *'?'* | *'['* | *'{'*) reference_pattern=1 ;; esac
395
+ if classify_file "$candidate" "$reference_pattern"; then printf '%s\n' "$candidate"; continue; fi
396
+ # Existing generated files can have arbitrary names; inspect actual glob matches too.
397
+ if [ "$reference_pattern" = 1 ]; then
398
+ count=0
399
+ while IFS= read -r expanded; do
400
+ count=$((count + 1)); [ "$count" -le 64 ] || parser_failed
401
+ if classify_file "$expanded"; then printf '%s\n' "$candidate"; break; fi
402
+ done < <(abspath "$candidate" "$cwd"; compgen -G "$REPLY" || true)
403
+ fi
404
+ done
405
+ exit 0
406
+ fi
328
407
 
329
- exit 0
408
+ [ -n "$new_content" ] || new_content="$new_string"
409
+ if ! classify_file "$file"; then exit 0; fi
410
+ case "$classification" in
411
+ controls) block \
412
+ "This target controls the agent's permissions or extensions, or belongs to an installed managed corpus/adapter tree. Agent Write/Edit calls may not alter their own controls or managed instructions." \
413
+ "Instead: report the intended change. Use 'cratis ai update' for managed files, or let a person change settings. An explicitly authorized protected write requires CRATIS_HOOKS_ALLOW_PROTECTED_WRITES=1 in the harness environment. Do not retry through a shell write." ;;
414
+ generated) block \
415
+ "This file is generated output (its header marks it as generated by Cratis). Rule 15 [contract] in .cratis/ai/rules/general.md: never edit a generated file — the next build overwrites it." \
416
+ "Instead: change the C# source it is generated from (the [Command] / [ReadModel] record) and rebuild with 'dotnet build -c Debug' to regenerate the proxy." ;;
417
+ content) block \
418
+ "The content being written opens with a Cratis generated-file header. Proxies are produced by the Cratis proxy generator, never hand-written." \
419
+ "Instead: write the C# source and run 'dotnet build -c Debug' to generate the proxy." ;;
420
+ manifest) block \
421
+ "'$base' is a dependency manifest / lockfile / SDK or NuGet configuration file. .cratis/ai/rules/general.md (Source-of-Truth Discipline): don't change these unless explicitly asked." \
422
+ "To allow dependency updates for this repository, set allowDependencyManifestWrites to true in .cratis/ai.json. If the user explicitly asked for this change, re-run the tool call with CRATIS_HOOKS_ALLOW_PROTECTED_WRITES=1 exported. Otherwise take the dependency as given and solve the problem in source." ;;
423
+ environment) block \
424
+ "'$base' is an environment file and normally holds secrets. Hooks block writing it so credentials are never authored, rewritten, or echoed by an agent." \
425
+ "Instead: tell the user exactly which variable to set and let them edit the file. If they explicitly asked you to write it, re-run with CRATIS_HOOKS_ALLOW_PROTECTED_WRITES=1 exported." ;;
426
+ esac
@@ -18,12 +18,17 @@ set -euo pipefail
18
18
  [ "${CRATIS_HOOKS_SKIP_SCAN:-0}" = "1" ] && exit 0
19
19
 
20
20
  input="$(hook_read_stdin)"
21
+ if ! hook_have jq; then
22
+ # Only a session key is needed to de-duplicate this advisory when JSON parsing is unavailable.
23
+ session="$(sed -n 's/.*"session_id"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' <<<"$input")"
24
+ if state_dir="$(hook_state_dir "${session:-nosession}")"; then
25
+ hook_claim_once "$state_dir/pattern-scan-missing-jq.seen" missing-jq || exit 0
26
+ fi
27
+ printf 'cratis-pattern-scan: jq is not installed; pattern scanning is off until jq is installed.\n' >&2
28
+ exit 0
29
+ fi
21
30
  [ -n "$input" ] || exit 0
22
31
 
23
- # jq is the repository's established JSON dependency. If it is not
24
- # installed the hook degrades to a silent no-op rather than breaking the session.
25
- hook_have jq || exit 0
26
-
27
32
  root="$(hook_repo_root)"
28
33
  cwd="$(hook_json "$input" '.cwd')"
29
34
  [ -n "$cwd" ] || cwd="$root"
@@ -22,7 +22,21 @@ set -euo pipefail
22
22
  [ "${CRATIS_HOOKS_SKIP_GATE:-0}" = "1" ] && exit 0
23
23
 
24
24
  input="$(hook_read_stdin)"
25
- hook_have jq || exit 0
25
+ root="$(hook_repo_root)"
26
+ if ! hook_have jq; then
27
+ # Without JSON parsing, still honor Stop re-entry and never block an unchanged tree.
28
+ LC_ALL=C grep -Eq '"stop_hook_active"[[:space:]]*:[[:space:]]*true' <<<"$input" && exit 0
29
+ git -C "$root" rev-parse --git-dir >/dev/null 2>&1 || exit 0
30
+ [ -n "$(git -C "$root" status --porcelain --untracked-files=normal 2>/dev/null || true)" ] || exit 0
31
+ {
32
+ printf 'BLOCKED by cratis-quality-gate: jq is not installed, so no quality gates ran on this change.\n'
33
+ hook_jq_install_hint
34
+ printf '\nA person who accepts ending turns without the gate sets CRATIS_HOOKS_SKIP_GATE=1 in the environment the agent\n'
35
+ printf 'harness was started from; setting it inside the command has no effect.\n'
36
+ } >&2
37
+ [ "${CRATIS_HOOKS_GATE_DRYRUN:-0}" = "1" ] && exit 0
38
+ exit 2
39
+ fi
26
40
 
27
41
  # Never re-enter: Claude Code sets stop_hook_active when the previous Stop hook already
28
42
  # blocked and the model is continuing. Blocking again would loop forever.
@@ -30,7 +44,6 @@ if [ -n "$input" ] && [ "$(hook_json "$input" '.stop_hook_active')" = "true" ];
30
44
  exit 0
31
45
  fi
32
46
 
33
- root="$(hook_repo_root)"
34
47
  here="$(cd -P "$(dirname "${BASH_SOURCE[0]}")" && pwd -P)"
35
48
  export CRATIS_HOOKS_SCRIPTS_DIR="$here"
36
49
  config="${CRATIS_HOOKS_GATES:-$here/quality-gates.json}"
@@ -34,6 +34,12 @@ hook_read_stdin() {
34
34
  cat 2>/dev/null || true
35
35
  }
36
36
 
37
+ # Shared installation hint, without a trailing newline so guards can append their warning.
38
+ hook_jq_install_hint() {
39
+ printf 'Stop and ask the user to install jq (macOS: brew install jq; Debian/Ubuntu: sudo apt-get install jq;\n'
40
+ printf 'Windows: winget install jqlang.jq), then retry.'
41
+ }
42
+
37
43
  # Refuse the tool call when jq is missing: $1 is the guard name, $2 the variable that lets a person run without it.
38
44
  # A guard that cannot read the tool call cannot check it, so this ends the sourcing script with exit 2
39
45
  # (the deny signal every wired harness honors). It uses only builtins, so it works without jq.
@@ -41,8 +47,8 @@ hook_require_jq() {
41
47
  hook_have jq && return 0
42
48
  {
43
49
  printf 'BLOCKED by %s: jq is not installed, so this guard cannot read the tool call and refuses every call until it is.\n' "$1"
44
- printf 'Stop and ask the user to install jq (macOS: brew install jq; Debian/Ubuntu: sudo apt-get install jq;\n'
45
- printf 'Windows: winget install jqlang.jq), then retry. Do not work around the guard.\n'
50
+ hook_jq_install_hint
51
+ printf ' Do not work around the guard.\n'
46
52
  printf 'A person who accepts running without this guard sets %s=1 in the environment the agent\n' "$2"
47
53
  printf 'harness was started from; setting it inside the command has no effect.\n'
48
54
  } >&2
@@ -22,6 +22,10 @@
22
22
  "type": "command",
23
23
  "command": "bash \"$CLAUDE_PROJECT_DIR\"/.cratis/ai/hooks/scripts/cratis-guard-secrets.sh"
24
24
  },
25
+ {
26
+ "type": "command",
27
+ "command": "bash \"$CLAUDE_PROJECT_DIR\"/.cratis/ai/hooks/scripts/cratis-guard-shell-writes.sh"
28
+ },
25
29
  {
26
30
  "type": "command",
27
31
  "command": "bash \"$CLAUDE_PROJECT_DIR\"/.cratis/ai/hooks/scripts/cratis-guard-pr-body.sh"
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cratis/pi",
3
- "version": "7.131.7",
3
+ "version": "7.132.1",
4
4
  "description": "Configuration-aware Cratis AI integration for Pi",
5
5
  "type": "module",
6
6
  "files": [