Compare commits

..
Author SHA1 Message Date
jason.woltje 6db25b1f07 row 211 (#1709, #426): a pre-push guard that refuses deletes and non-fast-forward pushes, its installer, and slot-busy.sh that exits 1 on BUSY
scripts/git-hooks/pre-push refuses a delete, a remote tip missing locally and
any update whose remote tip isn't an ancestor of the local tip; a new branch
and a fast-forward pass. scripts/install-git-hooks.sh puts it in the common
.git/hooks, refuses a set core.hooksPath or a different hook without
--force-install, and runs a canary through git hook run. scripts/slot-busy.sh
exits 0 CLEAR, 1 BUSY, 2 error. scripts/test-git-guard.sh (61 cases) and the
mutant runner in agents/darkwing/work/queue-211; TOOLS.md gets the usage.
Not run yet: written during Gander's slot (sage-2801).
2026-10-22 11:46:06 -05:00
11 changed files with 754 additions and 318 deletions

No files matched your search

+142
View File
@@ -0,0 +1,142 @@
# Row 211 (#1709, Vikunja P19 #426): a pre-push hook that refuses force-pushes, and a busy check that fails on BUSY
Darkwing, 2026-10-22. Brief: `docs/plans/2026-10-20_force-push-guard.md` (blob 3a8c2cf13). Moved from Rocko
to me by sage-2801 (Q220, mos-1301). Base: aca16404c. Branch: `darkwing/row211`. Reviewer: Dewey. Gate
owner: Sage.
## What ships
- `scripts/git-hooks/pre-push` (new, `/bin/sh`). For each ref line on stdin it refuses:
- a delete (local sha all zeros);
- a remote tip that isn't in this repository (`git cat-file -e <remote>^{commit}`), with "fetch first,
then push again";
- a remote tip that isn't an ancestor of the local tip (`git merge-base --is-ancestor`), naming the ref
and both shas;
- an ancestor check that fails for any other reason (exit above 1);
- a short or overlong ref line, or a non-hex object name.
A new ref (remote sha all zeros) passes, and so does an empty push. It fetches nothing. On any refusal
it prints one line per refused ref and a closing line, and exits 1, so git pushes no ref at all.
- `scripts/install-git-hooks.sh` (new). Installs the hook as `pre-push` in the common `.git/hooks`
(`git rev-parse --git-common-dir`), so a `--repo` naming a worktree lands in the shared directory.
It refuses (exit 2):
- a set `core.hooksPath` at any scope;
- a different installed `pre-push`, unless `--force-install` is given;
- a symlinked `pre-push`, even with `--force-install`;
- any of `GIT_DIR`, `GIT_WORK_TREE`, `GIT_COMMON_DIR`, `GIT_INDEX_FILE`, `GIT_OBJECT_DIRECTORY` or
`GIT_ALTERNATE_OBJECT_DIRECTORIES` in the environment;
- a directory that isn't a git checkout.
It never writes the installed file in place. A new hook goes in by `link()` from a temporary copy, so
a hook that appeared meanwhile is kept and the install refuses. A replacement goes in by `rename()`.
Then it compares the bytes, checks the mode, and runs a canary through `git hook run` (git 2.55 here):
an empty push must pass and a delete line must be refused with the guard's message.
- `scripts/slot-busy.sh` (new). Exit 0 CLEAR, 1 BUSY, 2 its own error, one `BUSY <pid> <rule> cwd=<cwd>
<command>` line per match. Rules: `node ... --test`, `*gate*.sh` (after a space, `/`, `_` or `-`), a
`mutant` substring, `test-*.sh`, `docker compose` and `docker-compose`. It skips its own pid and its
ancestors, empty command lines (kernel threads) and shell-snapshot wrappers.
- `scripts/test-git-guard.sh` (new), 61 cases, and three Maintenance rows plus a short section in
`docs/TOOLS.md`.
## Choices
1. **A separate `scripts/install-git-hooks.sh`, not `queue-commit.sh --install-push-hook`.** The brief
left this open. `queue-commit.sh --install-hook` is the queue guard's installer. It is tied to the
canonical checkout and to the lead (jason/sage) and runs the queue guard's canary. The push guard has
neither tie: it must also be installable in a scratch clone for the tests, and every seat worktree
shares it. Putting it in `queue-commit.sh` would widen that script's reach for no gain. The cost is a
second installer with a similar shape. The install pattern (copy beside, link or rename, verify,
canary) follows `queue-commit.sh`.
2. **No privilege check in the installer.** The brief makes the canonical install a separate step with
Sage after landing, and the tests need to install into scratch clones as the suite's user. So the
script installs wherever it is told. The guard is advisory on the client in any case (`--no-verify`).
3. **The hook source is the working file next to the installer** (`$ROOT/scripts/git-hooks/pre-push`),
not a blob from a ref. That lets the mutant runner install a mutated copy from its own tree, and
matches how `queue-commit.sh` reads its guard.
4. **A new `scripts/test-git-guard.sh`, not more cases in `test-land-work.sh`.** The brief allowed either.
Land-work's suite is about `land-work.sh`, and the gate runs every `scripts/test-*.sh`, so a new file
gets gated with no wiring.
5. **`--proc-root DIR` is a test seam in `slot-busy.sh`.** On a live host the real `/proc` may hold
other seats' runs at any time, so the suite can't demand exit 0 there. Exit 0 and every rule are
tested against a fake `/proc` with pids above `pid_max` (4194304), so they can't collide with the
ancestor set, which always comes from the real `/proc`. The real `/proc` is tested with a stand-in:
a `/bin/sh` script named `node`, started as `node --test standin.test.mjs` in its own cwd. The suite
asserts its BUSY line with that cwd, exit 1, that `slot-busy > /dev/null && echo ran` prints nothing,
that the suite itself (an ancestor whose command line matches `test-*.sh`) has no BUSY line, and that
after the stand-in exits its pid is gone. The brief's "0 without one" is the fake-`/proc` case.
6. **Ancestors are skipped**, not only its own pid as the brief says. A gate script that runs the busy
check matches its own rules (`*gate*.sh`, `test-*.sh`, `mutant`), so checking only `$$` would make
every such caller see itself as BUSY.
7. **The gate rule is broader than `gate.sh`**: `[ /_-]gate[^ /]*\.sh `, so `sage-gate.sh` and
`gate-253.sh` match too. A false BUSY costs a wait; a false CLEAR costs a broken run.
8. **Shell-snapshot wrappers are skipped.** An agent harness runs each command as `bash -c 'source
.../shell-snapshots/snapshot-*.sh && eval <command text>'`, so the wrapper's command line holds the
text of whatever the agent typed, including a busy check that names `test-*.sh`. The real child
processes the wrapper starts are still matched.
## Tests (`scripts/test-git-guard.sh`)
Scratch bare remote, a scratch clone with the guard installed, and a worktree of that clone. Git runs
with `GIT_CONFIG_NOSYSTEM=1` and an empty `GIT_CONFIG_GLOBAL`, as in `test-land-work.sh`. Nothing touches
origin, `~/.mosaic`, `~/.mosaic-dev` or `~/.config/mosaic-dev`.
- Install: exit 0, the canary passed, bytes and mode, no temporary file left, and the worktree's git
resolves `hooks/pre-push` to the common file.
- From the worktree: a new branch and a fast-forward pass. A `--force` push of a rewritten branch, a
`+refspec` push and a `--force-with-lease` push are refused by the guard's message, naming the ref and
both shas, and the remote ref is unchanged. `:ref` and `--delete` are refused and the branch stays.
- A second clone moves the remote; a `--force` push from the worktree is then refused with "fetch
first", the remote stays where the other clone put it, and the guard fetched nothing.
- The hook fed by hand: a short line, a non-hex name and an unknown local object are refused; an empty
push passes.
- The installer: `core.hooksPath` set refuses with that message and writes no hook (in `.git/hooks` or
the hooks path). A different hook refuses and stays byte-identical. `--force-install` replaces it, and
a hard link to the old file keeps the old bytes, so the replacement was a rename. A second install of
the same bytes exits 0. A symlinked hook refuses even with `--force-install`. A `--repo` naming a
worktree lands in the common directory. `GIT_DIR` set, a plain directory and an unknown argument
refuse.
- `slot-busy.sh`, fake `/proc`: CLEAR with exit 0 when nothing matches (a server, a `grep gate`, a
snapshot wrapper whose text holds `node --test`, an empty command line). Exit 1 and the BUSY line for
`node --test`, with no CLEAR in the output, and `> /dev/null && echo ran` prints nothing. Each rule
once more (7 cases). Exit 2 for a missing root, an empty root and an unknown argument.
- `slot-busy.sh`, real `/proc`: the stand-in cases in choice 5.
## Mutants (`agents/darkwing/work/queue-211/mutants.sh`)
Each mutant copies the four scripts into its own tree, edits one site there (exactly one match), and runs
that tree's suite under `timeout -k 10 180`. The worktree's files are never edited. The unmutated suite
runs first and a red base stops the run. The brief's five come first:
| Mutant | Site |
|---|---|
| ancestor-dropped | pre-push: `rc=0` in place of the `merge-base --is-ancestor` call |
| unknown-object-passes | pre-push: the missing-remote-tip branch skips the ref without refusing |
| delete-passes | pre-push: the delete branch skips the ref without refusing |
| install-over-hookspath | installer: the `core.hooksPath` refusal is `true \|\| die` |
| busy-exits-0 | slot-busy: `exit 0` when BUSY |
| differing-hook-replaced | installer: a different hook is replaced without `--force-install` |
| replace-in-place | installer: the replacement writes into the installed file (`cat >`) instead of renaming |
| symlink-followed | installer: no symlink refusal |
| ancestor-error-passes | pre-push: an ancestor check exiting above 1 doesn't refuse |
| snapshot-matched | slot-busy: no shell-snapshot skip |
| ancestors-matched | slot-busy: no ancestor skip |
| no-node-rule | slot-busy: the `node --test` rule removed |
| no-compose-rule | slot-busy: the `docker compose` rule removed |
`install-over-hookspath` still exits 2, because its canary then fails (git looks for the hook in the hooks
path). The suite kills it on the message and on "no hook was written", not on the exit code.
## Runs
Pending: nothing has run yet. Gander held the gate slot (row 253 run 5, from 16:32Z) while this was
written, so only `bash -n`, `sh -n` and a `DRY=1` mutant pass (every site matched once, no suite run)
happened. The suite, the mutants and every other `scripts/test-*.sh` run in a CLEAR Sage announces, with
`TMPDIR` under `/mnt/storage/scratch/tmp`. Results and the measured suite time go here before review.
## Known limits
- `git push --no-verify` skips the hook. Gitea branch protection (ops-01, through Mos) is the guard that
holds.
- The hook doesn't check tags differently from branches: a moved tag is refused like a rewritten branch.
- `slot-busy.sh` can call a process BUSY that isn't a run, for example an editor with a `test-*.sh` open.
It never reads files under a seat's directory, so it can't tell.
+74
View File
@@ -0,0 +1,74 @@
#!/usr/bin/env bash
# Row 211 (#426) mutants. Run from the candidate worktree's root:
# TMPDIR=<scratch dir> LOG=<dir> bash agents/darkwing/work/queue-211/mutants.sh > mutants.txt
# Each mutant copies the four row-211 scripts into its own tree, edits one
# site there (exactly one match, else NO MATCH), and runs that tree's
# scripts/test-git-guard.sh under a 180 s timeout. The worktree's files are
# never edited. "killed" means the suite failed; "survived" means it passed.
# The unmutated suite runs first, and a red base stops the run (exit 3).
set -u
LOG=${LOG:-.}
FILES="scripts/git-hooks/pre-push scripts/install-git-hooks.sh scripts/slot-busy.sh scripts/test-git-guard.sh"
WORK=$(mktemp -d "${TMPDIR:-/tmp}/r211-mutants.XXXXXX") || exit 2
trap 'rm -rf "$WORK"' EXIT
tree() { # $1: name. Prints the copy's root.
local t="$WORK/$1" f
for f in $FILES; do mkdir -p "$t/$(dirname "$f")" && cp -p -- "$f" "$t/$f" || return 1; done
echo "$t"
}
suite() { # $1: tree, $2: log
timeout -k 10 180 bash "$1/scripts/test-git-guard.sh" > "$2" 2>&1
}
edit() { # $1: file, $2: from, $3: to. Exit 3 unless $2 occurs exactly once.
python3 -B - "$1" "$2" "$3" <<'PY'
import sys
path, old, new = sys.argv[1:4]
text = open(path).read()
if text.count(old) != 1:
sys.exit(3)
open(path, "w").write(text.replace(old, new))
PY
}
base=$(tree base) || exit 2
if [ -n "${DRY:-}" ]; then
echo "base: not run (DRY)"
elif suite "$base" "$LOG/mut-base.log"; then
echo "base: green ($(tail -1 "$LOG/mut-base.log"))"
else
echo "base: RED, stopping ($(tail -1 "$LOG/mut-base.log"))"
exit 3
fi
run() { # $1: name, $2: file, $3: from, $4: to
local name=$1 file=$2 t log
t=$(tree "$name") || { echo "$name: COPY FAILED"; return; }
if ! edit "$t/$file" "$3" "$4"; then echo "$name: NO MATCH"; return; fi
if [ -n "${DRY:-}" ]; then echo "$name: match"; return; fi
log="$LOG/mut-$name.log"
if suite "$t" "$log"; then
echo "$name: survived"
else
echo "$name: killed (exit $?, $(grep -c '^FAIL' "$log") FAIL; first: $(grep -m1 '^FAIL' "$log" | cut -c6-100))"
fi
}
H=scripts/git-hooks/pre-push
I=scripts/install-git-hooks.sh
S=scripts/slot-busy.sh
# The brief's five.
run ancestor-dropped $H $' git merge-base --is-ancestor "$rsha" "$lsha" 2>/dev/null\n rc=$?' ' rc=0'
run unknown-object-passes $H $' refuse "$rref: the remote tip $rsha isn\'t in this repository; fetch first, then push again"\n continue' ' continue'
run delete-passes $H $' refuse "$rref: a delete (remote $rsha); seat branches are never deleted by push"\n continue' ' continue'
run install-over-hookspath $I '[ -z "$out" ] || die 2 "refused: core.hooksPath' '[ -z "$out" ] || true || die 2 "refused: core.hooksPath'
run busy-exits-0 $S 'if [ "$busy" = 1 ]; then exit 1; fi' 'if [ "$busy" = 1 ]; then exit 0; fi'
# Further sites the suite pins.
run differing-hook-replaced $I '[ "$FORCE" = 1 ] || die 2 "refused: a different' 'true || die 2 "refused: a different'
run replace-in-place $I 'mv -f -- "$tmp" "$HOOK" ||' 'cat -- "$tmp" > "$HOOK" && rm -f -- "$tmp" ||'
run symlink-followed $I 'if [ -L "$HOOK" ]; then die 2' 'if false; then die 2'
run ancestor-error-passes $H ' *) refuse "$rref: the ancestor check failed' ' *) : "$rref: the ancestor check failed'
run snapshot-matched $S $' if [[ "$c" == *"/shell-snapshots/snapshot-"* ]]; then return 1; fi\n' ''
run ancestors-matched $S ' [ -z "${SKIP[$pid]:-}" ] || continue' ' :'
run no-node-rule $S 'if [[ "$c" =~ $RE_NODE ]]; then echo "node --test"; return 0; fi' ':'
run no-compose-rule $S 'if [[ "$c" =~ $RE_COMPOSE ]]; then echo "docker compose"; return 0; fi' ':'
-90
View File
@@ -1,90 +0,0 @@
# Row 275 (193b1b, #1780): viewer verbs and board refusals
Morgana, 2026-10-22, for Duckworth (reviewer) and Sage (gate owner). Brief: docs/plans/2026-10-20_human-users-build.md,
"Brief: 193b1b, viewer verbs and board refusals" (blob de3a6310b). Design: row 193 DESIGN.md r5 e2d161e2e
(morgana/row193), sections 4.3, 8 and 9. Base: refactor aca16404c, branch morgana/row275. Assignment: sage-2788.
## What the code did before
- `#userGrants` (broker.mjs, FED R3) kept only grants that cover at level `collaborator` (`USER_LEVEL`).
A viewer-only user was refused `access-revoked` at `bindUser` and on every request.
- `#granted` and `#grantedThread` asked `collaborator` for every user verb, reads included.
- The reader session's board list was an inline array at the request gate.
## The change
1. `VIEWER_VERBS = ['project.list', 'thread.list', 'thread.messages', 'names']`, exported. `userLevel(verb)`
gives `viewer` for these and `collaborator` for the other user verbs (thread.create, thread.open,
thread.send). `USER_LEVEL` is gone.
2. `#userGrants` keeps a live grant at any level (`covers(..., {level: 'viewer'})`), so a viewer binds and
passes the request gate. The verb check against `USER_VERBS` is unchanged and still comes first.
3. `#granted(s, verb, project, instance)` and `#grantedThread(s, verb, t)` take the verb and ask
`userLevel(verb)`. Each handler passes its own verb name. A viewer gets `access-refused` on create,
open and send, the code design 4.3 names.
4. `BOARD_VERBS` exports the reader list unchanged (inbox, agents, thread.claims, tasks, trail, decisions,
credentials, replies, messages, state, usage), and the reader gate uses it. None is in `USER_VERBS`, so
every user is refused them `access-refused`. The test reads the same constant and pins it written out.
Downgrade path (design 4.3 note 2): a collaborator lowered to viewer still lists and reads its own threads
and can't open or send. The runtime's user transport calls `bindUser`, so a viewer can now bind over the
socket too. That is the intended effect; the verbs it reaches are the four above.
Not in this row: the share verbs, `thread.list {shared: true}` and `#readable`'s share rules (193b2, row 206);
the revocation timer, `access.reload` and the level-loss test (FED R4, which mutant 5 moved to). FED R4 has
not landed; this row checks the level per request only, which is what R3 already reads per request.
## Existing test changes (mos-1311 ruling)
Mos approved both changes in mos-1311 (16:44:56Z), under mos-1272. They follow row 193 DESIGN r5
(e2d161e2e, approved by Duckworth) section 4.3: the thread.list row at DESIGN.md:125 ("own threads still
covered (from an earlier collaborator grant)") and note 2 at :139 ("A viewer can still read its own
threads when a collaborator grant is lowered to viewer, but can't send or open them"). Condition 3: Duckworth
confirms in review that both match section 4.3.
All in `packages/bus/tests/user-principal.test.mjs` (FED R3, row 274):
| Test | Assertion | Old expectation | New expectation | Design line |
|---|---|---|---|---|
| "R3: bindUser binds a granted user and refuses one with no live grant" (title was "...no live collaborator grant") | `bindUser` with `grant({ level: 'viewer' })` | refused `access-revoked` (case `'viewer level'` in the refused list) | binds: `assert.ok(user('alice'), 'viewer level')`; the case leaves the refused list | :125 viewer column; 4.3 viewer verbs need a bound viewer |
| "R3: a removed or expired grant refuses the next request access-revoked..." | `thread.list` after `level: 'viewer'` ('downgraded') | `access-revoked` | `null` (answers) | :125 and :139 |
| same test, added (mos-1311 condition 1) | `thread.send` and `thread.open` on A after the downgrade | (not asserted) | each `access-refused`; `messages` and `thread_opens` counts unchanged | :139 "can't send or open them" |
The header comment of the file is updated to say a viewer grant binds. Every other R3 refusal (no grant,
another user, another business, expired, unreadable file, no file, removed, file refused) is unchanged.
No other test names a viewer grant on the bus (git grep for `level: 'viewer'` outside packages/business).
## Tests, packages/bus/tests/viewer.test.mjs (new)
1. VIEWER_VERBS is the ruled list and sits inside USER_VERBS.
2. A viewer binds; project.list, names, thread.list and thread.messages answer what its grant covers
(alice downgraded, bob viewer from the start).
3. A viewer is refused thread.create, thread.open and thread.send `access-refused`, and messages, threads
and thread_opens counts are unchanged. Kills mutant 6 at alice's send. r3 (duckworth-0166 B1): bob is
asked create only, as `#thread` refuses a non-owner `thread-not-owned` before the level check; open and
send are asked on alice's own thread. Bob stays the viewer who never held a collaborator grant.
4. Every verb off USER_VERBS refuses a viewer `access-refused` before its own checks.
5. Mixed grants: collaborator on project a, viewer on b. Create in a works, create in b refuses; send in b's
old thread refuses, open refuses, messages reads the message sent while collaborator (r3, N1).
6. Board reads (BOARD_VERBS, the project file verbs, limits, plugins, instances, routes) refuse alice
(downgraded viewer), bob (viewer) and carol (collaborator) `access-refused`. Kills mutant 10.
7. Governance pin, user side: one row per item of the 5.7 sentence (decisions, inbox entries, claims as
`agents` and `thread.claims`, tasks as `tasks` and `state`, project files as `project.files` and
`project.file`), each refused to a collaborator and a viewer while a run in carol's thread has raised a
decision the owner sees; carol still reads her own message with thread.messages. The owner side stays
in message-filter.test.mjs (row 205).
## Mutants (design 8)
| # | Mutation | Killed by |
|---|---|---|
| 6 | `'thread.send'` added to `VIEWER_VERBS` | viewer.test 3 (send answers); test 1 pin fails too |
| 10 | `'trail'` added to `USER_VERBS` | viewer.test 6 (trail no longer access-refused); R3's exact USER_VERBS pin fails too |
The kill rule for each mutant names the behaviour test above, not the pin.
## Gate (brief)
Duckworth approves the manifest. On Sage's gate: the touched test files whole (viewer, user-principal,
message-filter), the bus suite and every `scripts/test-*.sh` green, mutants 6 and 10 killed. broker.mjs
is imported by the cli, harness, business and seat suites as well; I'll propose them for the gate as in
row 277 (sage-2590). Nothing has run yet: built during Gander's 253 slot with no node.
+29
View File
@@ -166,8 +166,37 @@ resolved through the CLI.
| `scripts/test-conductor.sh` | Auto-apply selftests (sandboxed) | 17 cases |
| `scripts/test-auth.sh` | Auth checkpoint selftests (no Docker) | 13 cases |
| `scripts/test-land-work.sh` | Land-work selftests (sandboxed, fake Docker) | 84 cases |
| `scripts/test-git-guard.sh` | Push guard, its installer and `slot-busy.sh` (scratch bare remote, fake `/proc`) | 61 cases |
| `scripts/install-git-hooks.sh [--repo DIR] [--force-install]` | Install the push guard as `pre-push` in the common `.git/hooks` | Refuses a set `core.hooksPath` or a different installed hook; exit 0 ok · 1 failed · 2 refused · 4 usage |
| `scripts/slot-busy.sh` | Busy check: one `BUSY` line per gate or test process, or `CLEAR` | Exit 0 CLEAR · 1 BUSY · 2 error; chain on the exit code |
| `scripts/gitea-api.sh <METHOD> <path> [body]` | Gitea API helper; reads the JSON credential file or a raw per-seat token file | Token never on argv/stdout |
### Push guard and busy check (row 211, #426)
`scripts/git-hooks/pre-push` refuses a push that deletes a branch, or that
moves a branch to a commit that doesn't descend from the remote tip (a
`--force`, `--force-with-lease` or `+refspec` push of a rewritten branch). A
new branch and a fast-forward pass. The hook fetches nothing: when the remote
tip isn't in the local repository it refuses and says to fetch first.
`git push --no-verify` skips it, so Gitea's branch protection (ops-01) is the
guard that holds. `scripts/install-git-hooks.sh` copies it into the common
`.git/hooks`, which every worktree of the checkout shares, then runs a canary
through `git hook run`. Installing it in the canonical checkout is a step for
the lead after the row lands.
Chain the busy check on its exit code, and set `pipefail` in any script that
pipes it:
```bash
bash scripts/slot-busy.sh > "$LOG" && gate
```
Never `bash scripts/slot-busy.sh | tail -1 && gate`: `tail` exits 0, so the
gate runs while BUSY. It matches `node ... --test`, a `*gate*.sh`, `mutant`, a
`test-*.sh` and `docker compose` command lines, skips itself, its ancestors
and agent shell-snapshot wrappers, and reads only `/proc/<pid>/cmdline` and
the cwd link.
## Seat launch with registration (`scripts/mosaic`)
```bash
+20 -30
View File
@@ -132,15 +132,8 @@ export const TESTER_VERBS = Object.freeze(['message.send', 'message.receive', 'm
// refuses a user access-refused before its own checks: owner verbs, board reads, message.*,
// decision.*, project files, spec.read, assistant.stop, launch.*, name.set and usage.*.
export const USER_VERBS = Object.freeze(['project.list', 'thread.create', 'thread.list', 'thread.open', 'thread.send', 'thread.messages', 'names']);
// Row 275 (193b1b, #1780, row 193 design 4.3 and 9): the user verbs a viewer grant reaches. They
// read, so a live grant at any level covers them. thread.create, thread.open and thread.send need a
// collaborator grant on the project and instance, so a viewer gets access-refused on each.
export const VIEWER_VERBS = Object.freeze(['project.list', 'thread.list', 'thread.messages', 'names']);
// The least level a user verb needs (R1's covers, morgana-0005; LEVELS runs from most to least).
const userLevel = (verb) => (VIEWER_VERBS.includes(verb) ? 'viewer' : 'collaborator');
// Row 275 (row 193 design 4.3): the owner's board reads, which a reader session may call. A user,
// collaborator or viewer, is refused every one at the USER_VERBS gate.
export const BOARD_VERBS = Object.freeze(['inbox', 'agents', 'thread.claims', 'tasks', 'trail', 'decisions', 'credentials', 'replies', 'messages', 'state', 'usage']);
// The level a user's grant must reach for USER_VERBS (R1's covers, morgana-0005).
const USER_LEVEL = 'collaborator';
// Row 175: the organization verbs a tester may call. Its writes run every check the human's do
// and log actor `tester`; row 176 adds routes reads; limits.set, organization.set and organization.revision refuse it.
export const TESTER_ORGANIZATION_VERBS = Object.freeze(['limits', 'plugins', 'instances', 'plugins.set', 'instances.set', 'routes.set', 'routes']);
@@ -771,8 +764,7 @@ export class Broker {
return s.tester ? 'tester' : s.user ? 'user:' + s.user : s.human;
}
// FED R3 (design 3.5): the user's live grants in the session's business, from one read of the
// access file. Any failure to read leaves none. Row 275: a grant at any level counts here; each
// verb's own check asks the level it needs (#granted).
// access file. Any failure to read leaves none.
#userGrants(s) {
let doc = null;
try {
@@ -782,22 +774,21 @@ export class Broker {
}
const now = new Date();
return (doc?.grants ?? []).filter((g) => g.user === s.user && g.business === s.business &&
covers(g, { business: s.business, project: g.projects[0], instance: g.instances[0] }, now, { level: 'viewer' }));
covers(g, { business: s.business, project: g.projects[0], instance: g.instances[0] }, now, { level: USER_LEVEL }));
}
// Does one of the request's grants cover a thread of `instance` in `project`, at the level `verb`
// needs? A null `instance` asks about the project alone, a null `project` about the instance alone.
#granted(s, verb, project, instance) {
// Does one of the request's grants cover a thread of `instance` in `project`? A null `instance`
// asks about the project alone, a null `project` about the instance alone.
#granted(s, project, instance) {
const now = new Date();
return s.grants.some((g) => covers(g, {
business: s.business,
project: project ?? g.projects[0],
instance: instance ?? g.instances[0],
}, now, { level: userLevel(verb) }));
}, now, { level: USER_LEVEL }));
}
// A thread the request's grants still cover at the level `verb` needs, else access-refused
// (design 3.5, thread.open/send/messages; row 193 design 4.3 for the level).
#grantedThread(s, verb, t) {
if (s.user && !this.#granted(s, verb, t.project, t.instance)) fail('access-refused');
// A thread the request's grants still cover, else access-refused (design 3.5, thread.open/send/messages).
#grantedThread(s, t) {
if (s.user && !this.#granted(s, t.project, t.instance)) fail('access-refused');
return t;
}
// Row 205 (193b1a, #1703, row 193 design 5.7): a message in a thread a user other than the caller
@@ -1020,8 +1011,7 @@ export class Broker {
}
// FED R3 (#414, design 3.6): the trusted user transport invokes this only after row 196's
// verifyPrincipal checked the user CLI and its Console parent. It binds only a user the access
// file gives a live grant in the business (check 3), else access-revoked. Row 275: a viewer grant
// binds too; the verbs it reaches are VIEWER_VERBS. A user id
// file gives a live collaborator grant in the business (check 3), else access-revoked. A user id
// is never the bus's own principals' or the business human's, whatever the file says.
bindUser(record) {
keys(record, ['business', 'user'], ['business', 'user']);
@@ -4236,7 +4226,7 @@ export class Broker {
return result;
}
return this.#store.transaction(() => {
if (s.reader && !BOARD_VERBS.includes(request.verb))
if (s.reader && !['inbox', 'agents', 'thread.claims', 'tasks', 'trail', 'decisions', 'credentials', 'replies', 'messages', 'state', 'usage'].includes(request.verb))
fail('read-only');
if (s.tester && !TESTER_VERBS.includes(request.verb)) fail('tester-refused');
// A tester reads the human's views, as a reader does, and its message verbs are its own.
@@ -5689,7 +5679,7 @@ export class Broker {
return this.#store.all(
'SELECT instance,name,at FROM instance_names n WHERE business=? AND seq=(SELECT max(seq) FROM instance_names WHERE business=n.business AND instance=n.instance) ORDER BY instance',
s.business,
).filter((r) => !s.user || this.#granted(s, 'names', null, r.instance));
).filter((r) => !s.user || this.#granted(s, null, r.instance));
}
// Row 121 (#1615): projects group the user's threads (REQ-ORG-2). `repo` names a
// project from the business file; the rename to repos is a P19 follow-up.
@@ -5719,7 +5709,7 @@ export class Broker {
// FED R3 (design 3.5): a user lists granted projects only.
return this.#store
.all('SELECT id,at,name,repo FROM projects WHERE business=? ORDER BY seq', s.business)
.filter((p) => !s.user || this.#granted(s, 'project.list', p.id, null));
.filter((p) => !s.user || this.#granted(s, p.id, null));
}
// A thread belongs to the user who made it and to the business's one thread instance.
// Row 177 (#1675): a tester's thread is owned by `tester`, so neither reaches the other's.
@@ -5731,7 +5721,7 @@ export class Broker {
// before the project is looked up, so an ungranted id reads the same whether it exists or not.
if (s.user) {
const threaded = Object.keys(b.roles).filter((r) => this.#threaded(s.business, r));
if (threaded.length !== 1 || !this.#granted(s, 'thread.create', identifier(a.project), threaded[0])) fail('access-refused');
if (threaded.length !== 1 || !this.#granted(s, identifier(a.project), threaded[0])) fail('access-refused');
}
if (!this.#store.get('SELECT 1 FROM projects WHERE id=? AND business=?', identifier(a.project), s.business))
fail('project-not-found');
@@ -5769,14 +5759,14 @@ export class Broker {
s.business,
this.#owner(s),
...(a.project === undefined ? [] : [a.project]),
).filter((t) => !s.user || this.#granted(s, 'thread.list', t.project, t.instance));
).filter((t) => !s.user || this.#granted(s, t.project, t.instance));
}
// Opening a thread asks the launcher to start its session (REQ-LAUNCH-1). Row 264a: a thread
// verb names one session of the thread, or works on its default (D3).
case 'thread.open': {
if (!s.tester && !s.user) this.#human(s);
keys(a, ['thread', 'session'], ['thread']);
const t = this.#grantedThread(s, 'thread.open', this.#thread(s, a.thread));
const t = this.#grantedThread(s, this.#thread(s, a.thread));
const session = this.#threadSession(t, a.session);
this.#store.run('INSERT INTO thread_opens(at,thread,session,by) VALUES(?,?,?,?)', this.#now(), t.id, session, this.#owner(s));
return { opened: t.id };
@@ -5786,7 +5776,7 @@ export class Broker {
case 'thread.send': {
if (!s.tester && !s.user) this.#human(s);
keys(a, ['thread', 'session', 'body', 'class'], ['thread', 'body']);
const t = this.#grantedThread(s, 'thread.send', this.#thread(s, a.thread));
const t = this.#grantedThread(s, this.#thread(s, a.thread));
const session = this.#threadSession(t, a.session);
// Row 120's lists hold here as on message.send: the instance must hear from the human.
this.#checkMessaging(s.business, 'human', t.instance);
@@ -5815,7 +5805,7 @@ export class Broker {
case 'thread.messages': {
if (!s.tester && !s.user) this.#human(s);
keys(a, ['thread', 'session', 'after', 'limit'], ['thread']);
const t = this.#grantedThread(s, 'thread.messages', this.#thread(s, a.thread));
const t = this.#grantedThread(s, this.#thread(s, a.thread));
const session = this.#threadSession(t, a.session);
const limit = a.limit ?? THREAD_PAGE;
if (!Number.isInteger(limit) || limit < 1 || limit > THREAD_PAGE_MAX) fail('invalid-request');
+6 -16
View File
@@ -1,7 +1,6 @@
// FED R3 (#414, federation design 3.5, 3.6 and the R3 row of section 7): the broker's user principal.
// A user binds only with a live grant (row 275: a viewer grant binds too; viewer.test.mjs has the
// viewer cases), reaches the exact collaborator verb list, sees only what its grants cover, and
// talks to the granted instance in its own threads. The access
// A user binds only with a live collaborator grant, reaches the exact collaborator verb list, sees
// only what its grants cover, and talks to the granted instance in its own threads. The access
// document comes in as a function, as the runtime passes R1's loadAccess; each test changes it.
import test from 'node:test';
import assert from 'node:assert/strict';
@@ -84,17 +83,15 @@ function granted(t, options) {
return { ...ctx, p1, p2, A };
}
test('R3: bindUser binds a granted user and refuses one with no live grant', (t) => {
test('R3: bindUser binds a granted user and refuses one with no live collaborator grant', (t) => {
const { b, access, user } = setup(t);
assert.ok(user('alice'));
// Row 275 (193b1b): a viewer grant binds; it used to refuse here as the case 'viewer level'.
access.doc.grants = [grant({ level: 'viewer' })];
assert.ok(user('alice'), 'viewer level');
for (const [what, grants] of [
['no grant', []],
['another user', [grant({ user: 'bob' })]],
['another business', [grant({ business: 'other' })]],
['expired', [grant({ expires: '2000-01-01T00:00:00Z' })]],
['viewer level', [grant({ level: 'viewer' })]],
]) {
access.doc.grants = grants;
assert.throws(() => b.bindUser({ business: 'demo', user: 'alice' }), { code: 'access-revoked' }, what);
@@ -300,7 +297,7 @@ test('R3: a user thread run cannot message the owner, while its uncited gated ra
});
test('R3: a removed or expired grant refuses the next request access-revoked, and the file is read per request', (t) => {
const { call, code, access, store, A } = granted(t);
const { call, code, access } = granted(t);
const reads = access.reads;
call('alice', 'thread.list');
call('alice', 'project.list');
@@ -310,15 +307,8 @@ test('R3: a removed or expired grant refuses the next request access-revoked, an
assert.equal(code('alice', 'thread.list'), 'access-revoked', 'removed');
access.doc.grants = kept.map((g) => ({ ...g, expires: '2000-01-01T00:00:00Z' }));
assert.equal(code('alice', 'project.list'), 'access-revoked', 'expired');
// Row 275 (193b1b, design 4.3): a grant lowered to viewer still reads the user's own threads.
access.doc.grants = kept.map((g) => ({ ...g, level: 'viewer' }));
assert.equal(code('alice', 'thread.list'), null, 'downgraded');
// mos-1311 condition 1: the downgraded viewer still can't send or open, and nothing is stored.
const stored = () => ['messages', 'thread_opens'].map((x) => store.get(`SELECT count(*) n FROM ${x}`).n);
const before = stored();
assert.equal(code('alice', 'thread.send', { thread: A, body: 'still mine?' }), 'access-refused', 'downgraded send');
assert.equal(code('alice', 'thread.open', { thread: A }), 'access-refused', 'downgraded open');
assert.deepEqual(stored(), before, 'downgraded: nothing stored');
assert.equal(code('alice', 'thread.list'), 'access-revoked', 'downgraded');
access.fail = true;
access.doc.grants = kept;
assert.equal(code('alice', 'thread.list'), 'access-revoked', 'file refused');
-182
View File
@@ -1,182 +0,0 @@
// Row 275 (193b1b, #1780, row 193 design 4.3, 8 and 9): the viewer level on the bus. A viewer grant
// binds and reaches VIEWER_VERBS only; thread.create, thread.open and thread.send need a collaborator
// grant on the project and instance. Board reads refuse every user, collaborator or viewer, and the
// user-side governance pin names each item of the 5.7 user sentence. The fixture is user-principal's.
import test from 'node:test';
import assert from 'node:assert/strict';
import { mkdtempSync, readFileSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { fileURLToPath } from 'node:url';
import { Store } from '../src/store.mjs';
import {
Broker, ACTIONS, USER_VERBS, VIEWER_VERBS, BOARD_VERBS, TESTER_VERBS, TESTER_ORGANIZATION_VERBS, PROJECT_FILE_VERBS,
} from '../src/broker.mjs';
const shipped = (name) =>
JSON.parse(readFileSync(fileURLToPath(new URL(`../../../roles/${name}.json`, import.meta.url)), 'utf8'));
const options = [{ key: 'yes', text: 'Yes' }, { key: 'no', text: 'No' }];
const grant = (over = {}) => ({
id: 'g-1', user: 'alice', business: 'demo', projects: ['*'], instances: ['assistant'], level: 'collaborator', ...over,
});
function setup(t) {
const root = mkdtempSync(join(tmpdir(), 'bus-viewer-'));
const store = new Store(root);
t.after(() => {
store.close();
rmSync(root, { recursive: true, force: true });
});
const access = { doc: { accessVersion: 1, revision: 1, users: [], grants: [grant()] } };
const b = new Broker({
store,
businesses: {
demo: {
id: 'demo', human: 'jason', arbiters: { technical: 'chief', delivery: 'chief' }, vars: { 'bus.tester': true },
roles: {
chief: { definition: 'chief-of-staff', authority: { withinRole: ['message.send'], crossRole: [] } },
assistant: { definition: 'assistant', authority: { withinRole: ['message.send'], crossRole: [] } },
},
definitions: { 'chief-of-staff': {}, assistant: { messaging: shipped('assistant').messaging } },
},
},
access: () => access.doc,
});
const caps = { human: b.bindHuman({ business: 'demo', human: 'jason', via: 'cli', outsideAgent: true }) };
const call = (who, verb, args = {}) => b.request(caps[who], { verb, args });
const code = (who, verb, args = {}) => {
try {
call(who, verb, args);
} catch (e) {
return e.code;
}
return null;
};
const user = (name) => (caps[name] = b.bindUser({ business: 'demo', user: name }));
const launch = (name, thread) => {
caps[name] = b.bindLaunch({ business: 'demo', role: 'assistant', run: `${name}-run`, harness: 'pi', thread });
return call(name, 'role.claim');
};
return { b, store, access, caps, call, code, user, launch };
}
// Two projects. Alice, a collaborator on p1, made thread A there and sent one message; then her grant
// is lowered to viewer (the downgrade path, design 4.3). Bob is a viewer on p1 from the start.
function viewers(t) {
const ctx = setup(t);
const p1 = ctx.call('human', 'project.create', { name: 'shared' }).id;
const p2 = ctx.call('human', 'project.create', { name: 'private' }).id;
ctx.access.doc.grants = [grant({ projects: [p1] })];
ctx.user('alice');
const A = ctx.call('alice', 'thread.create', { project: p1, name: 'alice work' }).id;
const sent = ctx.call('alice', 'thread.send', { thread: A, body: 'hello' }).id;
ctx.access.doc.grants = [
grant({ projects: [p1], level: 'viewer' }),
grant({ id: 'g-b', user: 'bob', projects: [p1], level: 'viewer' }),
];
ctx.user('bob');
return { ...ctx, p1, p2, A, sent };
}
test('275: VIEWER_VERBS is the ruled read list, inside USER_VERBS', () => {
assert.deepEqual(VIEWER_VERBS, ['project.list', 'thread.list', 'thread.messages', 'names']);
for (const v of VIEWER_VERBS) assert.ok(USER_VERBS.includes(v), v);
});
test('275: a viewer binds, and each viewer verb answers with what its grant covers', (t) => {
const { call, p1, A, sent } = viewers(t);
call('human', 'name.set', { instance: 'assistant', name: 'ada' });
call('human', 'name.set', { instance: 'chief', name: 'cleo' });
for (const who of ['alice', 'bob']) {
assert.deepEqual(call(who, 'project.list').map((p) => p.id), [p1], who);
assert.deepEqual(call(who, 'names').map((n) => n.instance), ['assistant'], who);
}
// Alice's own old thread still lists and reads; bob has none.
assert.deepEqual(call('alice', 'thread.list').map((x) => x.id), [A]);
assert.deepEqual(call('alice', 'thread.messages', { thread: A }).map((m) => m.id), [sent]);
assert.deepEqual(call('bob', 'thread.list'), []);
});
// Mutant 6 (row 193 design 8): a viewer allowed thread.send. This test kills it.
test('275: a viewer is refused thread.create, thread.open and thread.send access-refused, and nothing is stored', (t) => {
const { store, code, p1, A } = viewers(t);
const counts = () => ['messages', 'threads', 'thread_opens'].map((x) => store.get(`SELECT count(*) n FROM ${x}`).n);
const before = counts();
for (const who of ['alice', 'bob'])
assert.equal(code(who, 'thread.create', { project: p1, name: `${who} new` }), 'access-refused', `${who} create`);
// Only alice owns a thread: #thread refuses a non-owner thread-not-owned before the level check
// (duckworth-0166 B1), so open and send are asked on her own A.
assert.equal(code('alice', 'thread.open', { thread: A }), 'access-refused', 'alice open');
assert.equal(code('alice', 'thread.send', { thread: A, body: 'still here?' }), 'access-refused', 'alice send');
assert.deepEqual(counts(), before);
});
test('275: every verb off the user list refuses a viewer access-refused before its own checks', (t) => {
const { b, caps } = viewers(t);
const others = new Set([...ACTIONS, ...TESTER_VERBS, ...TESTER_ORGANIZATION_VERBS, ...PROJECT_FILE_VERBS, ...BOARD_VERBS, 'no.such.verb']);
for (const v of USER_VERBS) others.delete(v);
assert.ok(others.size > 40);
for (const verb of others)
assert.throws(() => b.request(caps.bob, { verb, args: { junk: true } }), { code: 'access-refused' }, verb);
});
test('275: mixed grants, collaborator on one project and viewer on another, take the level per project', (t) => {
const { call, code, access, user } = setup(t);
const pa = call('human', 'project.create', { name: 'a' }).id;
const pb = call('human', 'project.create', { name: 'b' }).id;
access.doc.grants = [grant({ projects: [pa] }), grant({ id: 'g-2', projects: [pb] })];
user('alice');
const B = call('alice', 'thread.create', { project: pb, name: 'b work' }).id;
const inB = call('alice', 'thread.send', { thread: B, body: 'in b, before' }).id;
access.doc.grants = [grant({ projects: [pa] }), grant({ id: 'g-2', projects: [pb], level: 'viewer' })];
const A = call('alice', 'thread.create', { project: pa, name: 'a work' }).id;
assert.ok(A, 'create in the collaborator project works');
assert.equal(code('alice', 'thread.create', { project: pb, name: 'b more' }), 'access-refused', 'create in the viewer project');
assert.deepEqual(call('alice', 'project.list').map((p) => p.id), [pa, pb]);
assert.deepEqual(call('alice', 'thread.list').map((x) => x.id), [B, A]);
assert.ok(call('alice', 'thread.send', { thread: A, body: 'in a' }).id);
assert.equal(code('alice', 'thread.send', { thread: B, body: 'in b' }), 'access-refused');
assert.equal(code('alice', 'thread.open', { thread: B }), 'access-refused');
assert.deepEqual(call('alice', 'thread.messages', { thread: B }).map((m) => m.id), [inB]);
});
// Mutant 10 (row 193 design 8): a user allowed `trail`. This test kills it; R3's exact USER_VERBS
// pin in user-principal.test.mjs fails too. Carol is a collaborator, so the refusal isn't the level's.
test('275: board reads refuse users and viewers access-refused', (t) => {
const { code, access, user, p1, A } = viewers(t);
assert.deepEqual(BOARD_VERBS, ['inbox', 'agents', 'thread.claims', 'tasks', 'trail', 'decisions', 'credentials', 'replies', 'messages', 'state', 'usage']);
access.doc.grants = [...access.doc.grants, grant({ id: 'g-c', user: 'carol', projects: [p1] })];
user('carol');
for (const who of ['alice', 'bob', 'carol']) {
for (const verb of [...BOARD_VERBS, ...PROJECT_FILE_VERBS, 'limits', 'plugins', 'instances', 'routes'])
assert.equal(code(who, verb, verb === 'trail' ? { subject: A } : {}), 'access-refused', `${who} ${verb}`);
}
});
// Row 193's user sentence, from the user's side (mos-1023 item 2, design 8): "The business owner sees
// your thread's agent's decisions, inbox entries, claims, tasks and project files, but not your
// messages." The owner side is message-filter.test.mjs's pin. Here each item the owner sees is a
// board read the user is refused, at either level, while the user still reads its own thread.
test('governance pin, user side: decisions, inbox entries, claims, tasks and project files are the owner\'s, the user reads its messages', (t) => {
const { call, code, access, user, launch, p1 } = viewers(t);
access.doc.grants = [...access.doc.grants, grant({ id: 'g-c', user: 'carol', projects: [p1] })];
user('carol');
const C = call('carol', 'thread.create', { project: p1, name: 'carol work' }).id;
const sent = call('carol', 'thread.send', { thread: C, body: 'please plan it' }).id;
launch('a', C);
const d = call('a', 'decision.raise', { action: 'deploy', question: 'Ship?', options, recommendation: 'yes', blocking: false }).id;
assert.ok(call('human', 'inbox').some((x) => x.id === d), 'the owner sees the raise');
const items = [
['decisions', 'decisions', { list: 'recent' }],
['inbox entries', 'inbox', {}],
['claims', 'agents', {}],
['claims', 'thread.claims', {}],
['tasks', 'tasks', {}],
['tasks', 'state', {}],
['project files', 'project.files', { project: 'stack' }],
['project files', 'project.file', { project: 'stack', path: 'docs/plan.md' }],
];
for (const who of ['carol', 'bob'])
for (const [item, verb, args] of items) assert.equal(code(who, verb, args), 'access-refused', `${item}: ${who} ${verb}`);
assert.deepEqual(call('carol', 'thread.messages', { thread: C }).map((m) => m.id), [sent], 'messages: the user reads its own');
});
+50
View File
@@ -0,0 +1,50 @@
#!/bin/sh
# Mosaic push guard (row 211, #426). Installed as pre-push in the common
# .git/hooks by `scripts/install-git-hooks.sh`; never edit the installed copy.
# For each ref git is about to push, it refuses a delete and any update whose
# remote tip isn't an ancestor of the local tip: a force-push or a +refspec.
# A new ref passes. It fetches nothing, so a remote tip that isn't in this
# repository refuses. Any failure of the check refuses too.
# `git push --no-verify` skips this hook; Gitea's branch protection is the
# guard that holds (ops-01). Canon: never force-push.
refused=0
refuse() {
echo "mosaic push guard: refused: $*" >&2
refused=1
}
zero() {
case "$1" in *[!0]*) return 1 ;; esac
return 0
}
while read -r lref lsha rref rsha extra || [ -n "${lref:-}" ]; do
if [ -z "${rsha:-}" ] || [ -n "${extra:-}" ]; then
refuse "unreadable ref line from git: $lref ${lsha:-} ${rref:-} ${rsha:-} ${extra:-}"
continue
fi
case "$lsha$rsha" in
*[!0-9a-f]*) refuse "$rref: a ref line with a non-hex object name (local $lsha, remote $rsha)"; continue ;;
esac
if zero "$lsha"; then
refuse "$rref: a delete (remote $rsha); seat branches are never deleted by push"
continue
fi
if zero "$rsha"; then
continue
fi
if ! git cat-file -e "$rsha^{commit}" 2>/dev/null; then
refuse "$rref: the remote tip $rsha isn't in this repository; fetch first, then push again"
continue
fi
git merge-base --is-ancestor "$rsha" "$lsha" 2>/dev/null
rc=$?
case $rc in
0) ;;
1) refuse "$rref: not a fast-forward; remote $rsha isn't an ancestor of local $lsha (a force-push or a rewritten branch)" ;;
*) refuse "$rref: the ancestor check failed (exit $rc) for remote $rsha and local $lsha" ;;
esac
done
if [ "$refused" != 0 ]; then
echo "mosaic push guard: nothing was pushed; a pushed branch only moves forward (canon: never force-push)" >&2
exit 1
fi
exit 0
+99
View File
@@ -0,0 +1,99 @@
#!/usr/bin/env bash
# install-git-hooks.sh: install the push guard (row 211, #426) as pre-push in
# a repository's common .git/hooks, which every linked worktree shares.
#
# Usage:
# scripts/install-git-hooks.sh [--repo DIR] [--force-install]
#
# DIR defaults to this script's own checkout. The hook's bytes are this
# checkout's scripts/git-hooks/pre-push. It refuses when core.hooksPath is set
# (git would not run the hook), and when a different pre-push is installed,
# unless --force-install is given. It never edits an installed hook in place:
# a new hook is linked in, a replacement is renamed over the old one. A canary
# then runs the installed hook through git and needs a delete refused.
#
# Exit codes: 0 installed (or already the same bytes); 1 failed; 2 refused;
# 4 usage. Installing in the canonical checkout is its own step with the lead.
set -uo pipefail
ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd -P)"
SRC="$ROOT/scripts/git-hooks/pre-push"
TMPD=""
say() { printf 'install-git-hooks: %s\n' "$*" >&2; }
die() { local code=$1; shift; say "$*"; exit "$code"; }
cleanup() { if [ -n "$TMPD" ]; then rm -rf -- "$TMPD"; fi; }
trap cleanup EXIT
usage() {
sed -n '5,6p' "${BASH_SOURCE[0]}" | sed 's/^# \{0,1\}//' >&2
exit 4
}
REPO=$ROOT
FORCE=0
while [ $# -gt 0 ]; do
case "$1" in
--repo) [ $# -ge 2 ] || usage; REPO=$2; shift 2 ;;
--force-install) FORCE=1; shift ;;
-h|--help) usage ;;
*) say "unknown argument: $1"; usage ;;
esac
done
for v in GIT_DIR GIT_WORK_TREE GIT_COMMON_DIR GIT_INDEX_FILE GIT_OBJECT_DIRECTORY GIT_ALTERNATE_OBJECT_DIRECTORIES; do
if [ -n "${!v+x}" ]; then die 2 "refused: $v is set; run with the normal git environment"; fi
done
[ -f "$SRC" ] && [ ! -L "$SRC" ] || die 2 "refused: $SRC is missing or not a regular file"
g() { git -C "$REPO" "$@"; }
top=$(g rev-parse --show-toplevel 2>/dev/null) || die 2 "refused: $REPO is not a git checkout"
common=$(g rev-parse --path-format=absolute --git-common-dir) || die 1 "cannot read $REPO's git common directory"
HOOKS="$common/hooks"
HOOK="$HOOKS/pre-push"
out=$(g config --show-scope --get-all core.hooksPath 2>/dev/null)
[ -z "$out" ] || die 2 "refused: core.hooksPath is set ($(printf '%s' "$out" | tr '\n\t' '; ')), so git would not run the push guard; unset it first"
if [ -L "$HOOK" ]; then die 2 "refused: $HOOK is a symlink; remove it by hand if it is not wanted"; fi
mkdir -p "$HOOKS" || die 1 "cannot create $HOOKS"
tmp="$HOOKS/.pre-push.install-git-hooks.$$"
if [ -e "$HOOK" ]; then
[ -f "$HOOK" ] || die 2 "refused: $HOOK is not a regular file"
if cmp -s "$SRC" "$HOOK"; then
chmod 0755 "$HOOK" || die 1 "chmod failed"
note="the same bytes were already there"
else
[ "$FORCE" = 1 ] || die 2 "refused: a different pre-push hook is installed at $HOOK; compare it with $SRC, and pass --force-install to replace it"
cp -- "$SRC" "$tmp" && chmod 0755 "$tmp" || { rm -f -- "$tmp"; die 1 "cannot write $tmp"; }
# rename() swaps the whole file; the old hook's bytes are never edited.
mv -f -- "$tmp" "$HOOK" || { rm -f -- "$tmp"; die 1 "cannot replace $HOOK"; }
note="replaced a different hook (--force-install)"
fi
else
cp -- "$SRC" "$tmp" && chmod 0755 "$tmp" || { rm -f -- "$tmp"; die 1 "cannot write $tmp"; }
# link() never replaces, so a hook that appeared meanwhile is kept.
if ! ln -- "$tmp" "$HOOK" 2>/dev/null; then rm -f -- "$tmp"; die 2 "refused: a pre-push hook appeared at $HOOK while installing"; fi
rm -f -- "$tmp"
note="new"
fi
cmp -s "$SRC" "$HOOK" || die 1 "$HOOK differs from $SRC after install"
[ -x "$HOOK" ] || die 1 "$HOOK is not executable after install"
# The canary: git runs the hook it would run for a push. A delete line needs
# no objects; the guard must refuse it, and pass an empty push.
TMPD=$(mktemp -d "${TMPDIR:-/tmp}/install-git-hooks.XXXXXX") || die 1 "mktemp failed"
z=0000000000000000000000000000000000000000
printf '(delete) %s refs/heads/install-canary 1%s\n' "$z" "${z#0}" > "$TMPD/delete"
: > "$TMPD/empty"
if ! out=$(cd "$top" && git hook run --to-stdin="$TMPD/empty" pre-push -- canary canary 2>&1); then
die 2 "refused: the canary's empty push failed, so git is not running the push guard as installed: $out"
fi
out=$(cd "$top" && git hook run --to-stdin="$TMPD/delete" pre-push -- canary canary 2>&1); rc=$?
[ "$rc" -ne 0 ] && [[ "$out" == *"mosaic push guard: refused"* ]] \
|| die 2 "refused: the canary's delete was not refused by the push guard (exit $rc)"
printf 'ok installed the push guard at %s (%s, sha256 %s, mode 0755); canary passed\n' \
"$HOOK" "$note" "$(sha256sum < "$HOOK" | cut -d' ' -f1)"
exit 0
+77
View File
@@ -0,0 +1,77 @@
#!/usr/bin/env bash
# slot-busy.sh: the shared busy check (row 211, #426). Is a gate or a test run
# going on this host?
#
# Usage:
# scripts/slot-busy.sh [--proc-root DIR]
#
# It prints one BUSY line per matching process, or one CLEAR line. Exit codes:
# 0 CLEAR, 1 BUSY, 2 its own error. Chain it on the exit code, never on a
# filter of its output:
# bash scripts/slot-busy.sh > LOG && gate (set -o pipefail if piped)
# never `bash scripts/slot-busy.sh | tail -1 && gate`, which runs while BUSY.
#
# A process matches when its command line holds `node ... --test`, a
# `*gate*.sh`, `mutant`, a `test-*.sh` or `docker compose`/`docker-compose`.
# It skips itself and its ancestors (a gate script may run the check), and an
# agent harness's shell-snapshot wrapper, whose command line is the agent's
# command text; that shell's real children are still matched. It reads only
# /proc/<pid>/cmdline and the cwd link, never a file under a seat's directory.
# --proc-root names a stand-in for /proc in the selftests.
set -uo pipefail
PROC=/proc
while [ $# -gt 0 ]; do
case "$1" in
--proc-root) [ $# -ge 2 ] || { echo "slot-busy: error: --proc-root needs a directory" >&2; exit 2; }; PROC=$2; shift 2 ;;
-h|--help) sed -n '5,6p' "${BASH_SOURCE[0]}" | sed 's/^# \{0,1\}//' >&2; exit 2 ;;
*) echo "slot-busy: error: unknown argument: $1" >&2; exit 2 ;;
esac
done
[ -d "$PROC" ] || { echo "slot-busy: error: $PROC is not a directory" >&2; exit 2; }
# This process and its ancestors, from the real /proc.
declare -A SKIP=()
p=$$
while [ -n "$p" ] && [ "$p" != 0 ]; do
SKIP[$p]=1
p=$(awk '/^PPid:/{print $2; exit}' "/proc/$p/status" 2>/dev/null) || p=""
done
[ "${#SKIP[@]}" -ge 1 ] && [ -n "${SKIP[$$]:-}" ] || { echo "slot-busy: error: cannot read its own process" >&2; exit 2; }
RE_NODE='[ /]node[^ ]* (.* )?--test '
RE_GATE='[ /_-]gate[^ /]*\.sh '
RE_TEST='[ /]test-[^ /]*\.sh '
RE_COMPOSE='[ /]docker( compose|-compose) '
match() { # $1: the command line, NULs as spaces. Prints the rule that matched.
local c=" $1 "
if [[ "$c" == *"/shell-snapshots/snapshot-"* ]]; then return 1; fi
if [[ "$c" =~ $RE_NODE ]]; then echo "node --test"; return 0; fi
if [[ "$c" =~ $RE_GATE ]]; then echo "gate"; return 0; fi
if [[ "$c" == *mutant* ]]; then echo "mutant"; return 0; fi
if [[ "$c" =~ $RE_TEST ]]; then echo "test script"; return 0; fi
if [[ "$c" =~ $RE_COMPOSE ]]; then echo "docker compose"; return 0; fi
return 1
}
seen=0
busy=0
for d in "$PROC"/[0-9]*; do
[ -d "$d" ] || continue
pid=${d##*/}
[[ "$pid" =~ ^[0-9]+$ ]] || continue
seen=$((seen + 1))
[ -z "${SKIP[$pid]:-}" ] || continue
# A process can exit between the listing and the read; that's not an error.
cmd=$(tr '\0' ' ' < "$d/cmdline" 2>/dev/null) || continue
cmd=${cmd% }
[ -n "$cmd" ] || continue
rule=$(match "$cmd") || continue
cwd=$(readlink "$d/cwd" 2>/dev/null) || cwd="?"
printf 'BUSY %s %s cwd=%s %s\n' "$pid" "$rule" "$cwd" "${cmd:0:200}"
busy=1
done
[ "$seen" -ge 1 ] || { echo "slot-busy: error: no processes under $PROC" >&2; exit 2; }
if [ "$busy" = 1 ]; then exit 1; fi
echo "CLEAR"
exit 0
+257
View File
@@ -0,0 +1,257 @@
#!/usr/bin/env bash
# Sandboxed selftests for the push guard, its installer and the busy check
# (row 211, #426): scripts/git-hooks/pre-push, scripts/install-git-hooks.sh
# and scripts/slot-busy.sh.
#
# Pushes go from a scratch clone and its worktree to a scratch bare remote,
# never to origin. Git sees no user or system config. The busy check runs
# against a fake /proc (pids above pid_max) for the exit codes and rules, and
# against the real /proc with a sleeping stand-in whose argv is `node --test`.
set -uo pipefail
cd "$(dirname "$0")/.."
REPO="$(pwd)"
unset GIT_DIR GIT_WORK_TREE GIT_COMMON_DIR GIT_INDEX_FILE GIT_OBJECT_DIRECTORY GIT_ALTERNATE_OBJECT_DIRECTORIES
SANDBOX="$(cd "$(mktemp -d)" && pwd -P)"
STANDIN=""
cleanup() {
if [ -n "$STANDIN" ]; then kill "$STANDIN" 2>/dev/null; wait "$STANDIN" 2>/dev/null; fi
rm -rf "$SANDBOX"
}
trap cleanup EXIT
PASS=0
FAIL=0
# Status colors: terminal-only, NO_COLOR-respecting; plain when piped.
if [ -t 1 ] && [ -z "${NO_COLOR:-}" ]; then
C_OK=$'\033[0;32m'; C_FAIL=$'\033[0;31m'; C_RESET=$'\033[0m'
else
C_OK=""; C_FAIL=""; C_RESET=""
fi
check() {
if [ "$2" = "0" ]; then PASS=$((PASS+1)); echo "${C_OK}OK${C_RESET} $1"; else FAIL=$((FAIL+1)); echo "${C_FAIL}FAIL${C_RESET} $1"; fi
}
has() { [[ "$1" == *"$2"* ]]; }
# Git sees no user or system config: no hooks path, no signing, a fixed identity.
: > "$SANDBOX/gitconfig"
export GIT_CONFIG_NOSYSTEM=1 GIT_CONFIG_GLOBAL="$SANDBOX/gitconfig"
export GIT_AUTHOR_NAME=suite GIT_AUTHOR_EMAIL=suite@local GIT_COMMITTER_NAME=suite GIT_COMMITTER_EMAIL=suite@local
HOOK_SRC="$REPO/scripts/git-hooks/pre-push"
INSTALL="$REPO/scripts/install-git-hooks.sh"
BUSY="$REPO/scripts/slot-busy.sh"
B="$SANDBOX/remote.git"
C="$SANDBOX/clone"
W="$SANDBOX/wt"
O="$SANDBOX/other"
commit() { # $1: repo, $2: file and message
echo "$2" > "$1/$2" && git -C "$1" add "$2" && git -C "$1" commit -q -m "$2"
}
rtip() { git -C "$B" rev-parse -q --verify "refs/heads/$1"; }
# ---- the remote, a clone with the guard, a worktree ----
git init -q --bare -b main "$B"
git init -q -b main "$SANDBOX/seed"
commit "$SANDBOX/seed" base
git -C "$SANDBOX/seed" push -q "$B" main
git clone -q "$B" "$C"
echo "== install =="
out=$(bash "$INSTALL" --repo "$C" 2>&1); rc=$?
check "the install into a clean clone exits 0" "$rc"
check "it reports the install and a passed canary" "$(has "$out" "ok installed the push guard" && has "$out" "canary passed"; echo $?)"
check "the hook is in the common .git/hooks, with the repository's bytes, executable" \
"$(cmp -s "$HOOK_SRC" "$C/.git/hooks/pre-push" && [ -x "$C/.git/hooks/pre-push" ]; echo $?)"
check "no temporary file is left in .git/hooks" \
"$(ls -A "$C/.git/hooks" | grep -q '^\.pre-push\.install'; [ $? = 1 ]; echo $?)"
git -C "$C" worktree add -q -b seat/w "$W" origin/main
check "the worktree's git runs the common hook" \
"$([ "$(git -C "$W" rev-parse --path-format=absolute --git-path hooks/pre-push)" = "$C/.git/hooks/pre-push" ]; echo $?)"
echo "== pushes from the worktree =="
commit "$W" one
out=$(git -C "$W" push origin seat/w 2>&1); rc=$?
check "a new branch passes" "$rc"
check "the remote branch is at the pushed commit" "$([ "$(rtip seat/w)" = "$(git -C "$W" rev-parse HEAD)" ]; echo $?)"
commit "$W" two
out=$(git -C "$W" push origin seat/w 2>&1); rc=$?
check "a fast-forward passes" "$rc"
check "the remote branch moved forward" "$([ "$(rtip seat/w)" = "$(git -C "$W" rev-parse HEAD)" ]; echo $?)"
before=$(rtip seat/w)
git -C "$W" reset -q --hard HEAD~1
commit "$W" two-rewritten
after=$(git -C "$W" rev-parse HEAD)
out=$(git -C "$W" push --force origin seat/w 2>&1); rc=$?
check "push --force of a rewritten branch is refused" "$([ "$rc" -ne 0 ]; echo $?)"
check "the refusal is the guard's, and names the ref and both shas" \
"$(has "$out" "mosaic push guard: refused: refs/heads/seat/w: not a fast-forward" && has "$out" "$before" && has "$out" "$after"; echo $?)"
check "the remote ref is unchanged after the refused --force" "$([ "$(rtip seat/w)" = "$before" ]; echo $?)"
out=$(git -C "$W" push origin +seat/w:seat/w 2>&1); rc=$?
check "a +refspec push is refused" "$([ "$rc" -ne 0 ] && has "$out" "not a fast-forward"; echo $?)"
check "the remote ref is unchanged after the refused +refspec" "$([ "$(rtip seat/w)" = "$before" ]; echo $?)"
out=$(git -C "$W" push --force-with-lease origin seat/w 2>&1); rc=$?
check "push --force-with-lease is refused too" "$([ "$rc" -ne 0 ] && has "$out" "not a fast-forward"; echo $?)"
out=$(git -C "$W" push origin :seat/w 2>&1); rc=$?
check "a delete (:ref) is refused" "$([ "$rc" -ne 0 ] && has "$out" "mosaic push guard: refused: refs/heads/seat/w: a delete"; echo $?)"
out=$(git -C "$W" push --delete origin seat/w 2>&1); rc=$?
check "a delete (--delete) is refused" "$([ "$rc" -ne 0 ] && has "$out" "a delete"; echo $?)"
check "the remote branch still exists after the refused deletes" "$([ "$(rtip seat/w)" = "$before" ]; echo $?)"
# Another clone moves the remote; this clone never fetches it.
git clone -q -b seat/w "$B" "$O"
commit "$O" from-other
git -C "$O" push -q origin seat/w
moved=$(rtip seat/w)
check "the other clone moved the remote, and this clone lacks that commit" \
"$([ "$moved" != "$before" ] && ! git -C "$C" cat-file -e "$moved^{commit}" 2>/dev/null; echo $?)"
out=$(git -C "$W" push --force origin seat/w 2>&1); rc=$?
check "a push over a remote tip missing locally is refused, saying fetch first" \
"$([ "$rc" -ne 0 ] && has "$out" "isn't in this repository; fetch first"; echo $?)"
check "the remote ref is unchanged after that refusal" "$([ "$(rtip seat/w)" = "$moved" ]; echo $?)"
check "the guard fetched nothing" "$(! git -C "$C" cat-file -e "$moved^{commit}" 2>/dev/null; echo $?)"
echo "== the hook, fed by hand =="
z=0000000000000000000000000000000000000000
hookrun() { (cd "$C" && printf '%s\n' "$1" | sh "$C/.git/hooks/pre-push" origin "$B" 2>&1); }
out=$(hookrun "refs/heads/x $(git -C "$C" rev-parse HEAD) refs/heads/x"); rc=$?
check "a short ref line is refused" "$([ "$rc" -ne 0 ] && has "$out" "unreadable ref line"; echo $?)"
out=$(hookrun "refs/heads/x HEAD refs/heads/x $z"); rc=$?
check "a non-hex object name is refused" "$([ "$rc" -ne 0 ] && has "$out" "non-hex"; echo $?)"
out=$(hookrun "refs/heads/x 1234567890123456789012345678901234567890 refs/heads/x $(git -C "$C" rev-parse HEAD)"); rc=$?
check "a failed ancestor check (an unknown local object) is refused" \
"$([ "$rc" -ne 0 ] && has "$out" "the ancestor check failed"; echo $?)"
out=$(printf '' | (cd "$C" && sh "$C/.git/hooks/pre-push" origin "$B" 2>&1)); rc=$?
check "an empty push passes" "$rc"
echo "== installer refusals =="
fresh() { rm -rf "$1"; git clone -q "$B" "$1"; }
fresh "$SANDBOX/hp"
git -C "$SANDBOX/hp" config core.hooksPath .husky
out=$(bash "$INSTALL" --repo "$SANDBOX/hp" 2>&1); rc=$?
check "the install refuses with core.hooksPath set (exit 2)" "$([ "$rc" = 2 ]; echo $?)"
check "it says core.hooksPath is set" "$(has "$out" "core.hooksPath is set"; echo $?)"
check "no hook was written under the hooksPath refusal" \
"$([ ! -e "$SANDBOX/hp/.git/hooks/pre-push" ] && [ ! -e "$SANDBOX/hp/.husky/pre-push" ]; echo $?)"
fresh "$SANDBOX/df"
printf '#!/bin/sh\nexit 0\n' > "$SANDBOX/df/.git/hooks/pre-push"
chmod 0755 "$SANDBOX/df/.git/hooks/pre-push"
ln "$SANDBOX/df/.git/hooks/pre-push" "$SANDBOX/df-old"
out=$(bash "$INSTALL" --repo "$SANDBOX/df" 2>&1); rc=$?
check "the install refuses a different installed pre-push (exit 2)" \
"$([ "$rc" = 2 ] && has "$out" "a different pre-push hook is installed"; echo $?)"
check "the different hook is untouched" \
"$([ "$(cat "$SANDBOX/df/.git/hooks/pre-push")" = "$(printf '#!/bin/sh\nexit 0')" ]; echo $?)"
out=$(bash "$INSTALL" --repo "$SANDBOX/df" --force-install 2>&1); rc=$?
check "--force-install replaces it" \
"$([ "$rc" = 0 ] && has "$out" "replaced a different hook" && cmp -s "$HOOK_SRC" "$SANDBOX/df/.git/hooks/pre-push"; echo $?)"
check "the replacement was a rename: the old file keeps its bytes" \
"$([ "$(cat "$SANDBOX/df-old")" = "$(printf '#!/bin/sh\nexit 0')" ]; echo $?)"
out=$(bash "$INSTALL" --repo "$SANDBOX/df" 2>&1); rc=$?
check "a second install over the same bytes exits 0" "$([ "$rc" = 0 ] && has "$out" "the same bytes"; echo $?)"
fresh "$SANDBOX/ln"
ln -s /dev/null "$SANDBOX/ln/.git/hooks/pre-push"
out=$(bash "$INSTALL" --repo "$SANDBOX/ln" --force-install 2>&1); rc=$?
check "the install refuses a symlinked pre-push, even with --force-install" "$([ "$rc" = 2 ] && has "$out" "is a symlink"; echo $?)"
fresh "$SANDBOX/wd"
git -C "$SANDBOX/wd" worktree add -q -b seat/x "$SANDBOX/wd-wt" origin/main
out=$(bash "$INSTALL" --repo "$SANDBOX/wd-wt" 2>&1); rc=$?
check "an install named by a worktree path lands in the common .git/hooks" \
"$([ "$rc" = 0 ] && cmp -s "$HOOK_SRC" "$SANDBOX/wd/.git/hooks/pre-push"; echo $?)"
out=$(GIT_DIR="$SANDBOX/wd/.git" bash "$INSTALL" --repo "$SANDBOX/wd" 2>&1); rc=$?
check "the install refuses with GIT_DIR set" "$([ "$rc" = 2 ] && has "$out" "GIT_DIR is set"; echo $?)"
mkdir -p "$SANDBOX/plain"
out=$(bash "$INSTALL" --repo "$SANDBOX/plain" 2>&1); rc=$?
check "the install refuses a directory that isn't a checkout" "$([ "$rc" = 2 ]; echo $?)"
out=$(bash "$INSTALL" --nope 2>&1); rc=$?
check "an unknown argument exits 4" "$([ "$rc" = 4 ]; echo $?)"
echo "== slot-busy, fake /proc =="
P="$SANDBOX/proc"
fakeproc() { # $1: pid, $2: cwd, rest: argv
local pid=$1 cwd=$2; shift 2
mkdir -p "$P/$pid"
printf '%s\0' "$@" > "$P/$pid/cmdline"
ln -sfn "$cwd" "$P/$pid/cwd"
}
busyrun() { bash "$BUSY" --proc-root "$P" 2>&1; }
fakeproc 4194401 /srv node server.mjs
fakeproc 4194402 /srv grep -r gate .
fakeproc 4194403 /srv /bin/bash -c "source /home/u/.claude/shell-snapshots/snapshot-bash-1.sh && eval 'node --test x.test.mjs'"
mkdir -p "$P/4194404"; : > "$P/4194404/cmdline"
out=$(busyrun); rc=$?
check "no matching process: exit 0 and CLEAR" "$([ "$rc" = 0 ] && [ "$out" = CLEAR ]; echo $?)"
check "an agent's shell-snapshot wrapper isn't a match" "$(! has "$out" "4194403"; echo $?)"
fakeproc 4194410 /seat/a node --test packages/x/tests/a.test.mjs
out=$(busyrun); rc=$?
check "a node --test process: exit 1" "$([ "$rc" = 1 ]; echo $?)"
check "its BUSY line names pid, rule and cwd" "$(has "$out" "BUSY 4194410 node --test cwd=/seat/a node --test"; echo $?)"
check "BUSY output never says CLEAR" "$(! has "$out" "CLEAR"; echo $?)"
ran=$(bash "$BUSY" --proc-root "$P" >/dev/null && echo ran)
check "\`slot-busy > LOG && step\` doesn't run the step while BUSY" "$([ -z "$ran" ]; echo $?)"
rm -rf "${P:?}/4194410"
rule() { # $1: expected rule, rest: argv
local want=$1; shift
rm -rf "${P:?}/4194420"; fakeproc 4194420 /seat/b "$@"
out=$(busyrun); rc=$?
check "busy on: $* ($want)" "$([ "$rc" = 1 ] && has "$out" "BUSY 4194420 $want "; echo $?)"
}
rule "node --test" /usr/bin/node --experimental-strip-types --test a.test.ts
rule "gate" bash /mnt/scratch/sage-gate.sh 253
rule "gate" bash ./gate.sh
rule "mutant" bash agents/x/work/queue-1/mutants.sh M3
rule "test script" bash scripts/test-land-work.sh
rule "docker compose" docker compose -p x up -d
rule "docker compose" /usr/bin/docker-compose up
rm -rf "${P:?}/4194420"
out=$(bash "$BUSY" --proc-root "$SANDBOX/no-such-proc" 2>&1); rc=$?
check "a missing proc root: exit 2" "$([ "$rc" = 2 ]; echo $?)"
mkdir -p "$SANDBOX/empty-proc"
out=$(bash "$BUSY" --proc-root "$SANDBOX/empty-proc" 2>&1); rc=$?
check "a proc root with no processes: exit 2" "$([ "$rc" = 2 ]; echo $?)"
out=$(bash "$BUSY" --nope 2>&1); rc=$?
check "an unknown argument: exit 2" "$([ "$rc" = 2 ]; echo $?)"
echo "== slot-busy, real /proc =="
mkdir -p "$SANDBOX/bin" "$SANDBOX/standin"
cat > "$SANDBOX/bin/node" <<'EOF'
#!/bin/sh
trap 'exit 0' TERM
while :; do sleep 0.2; done
EOF
chmod +x "$SANDBOX/bin/node"
(cd "$SANDBOX/standin" && exec "$SANDBOX/bin/node" --test standin.test.mjs) &
STANDIN=$!
for _ in $(seq 50); do
has "$(tr '\0' ' ' < "/proc/$STANDIN/cmdline" 2>/dev/null)" "--test standin" && break
sleep 0.1
done
out=$(bash "$BUSY" 2>&1); rc=$?
check "with a stand-in node --test running: exit 1" "$([ "$rc" = 1 ]; echo $?)"
check "the stand-in has a BUSY line with its cwd" \
"$(printf '%s\n' "$out" | grep -q "^BUSY $STANDIN node --test cwd=$SANDBOX/standin "; echo $?)"
check "this suite, an ancestor, has no BUSY line" "$(! printf '%s\n' "$out" | grep -q "^BUSY $$ "; echo $?)"
ran=$(bash "$BUSY" >/dev/null && echo ran)
check "\`slot-busy > LOG && step\` doesn't run the step with the stand-in up" "$([ -z "$ran" ]; echo $?)"
kill "$STANDIN" 2>/dev/null; wait "$STANDIN" 2>/dev/null
gone=$STANDIN; STANDIN=""
out=$(bash "$BUSY" 2>&1); rc=$?
check "after the stand-in exits, it has no BUSY line" "$(! printf '%s\n' "$out" | grep -q "^BUSY $gone "; echo $?)"
check "the real-/proc run exits 0 or 1, never 2" "$([ "$rc" = 0 ] || [ "$rc" = 1 ]; echo $?)"
echo "---"
echo "git-guard selftests: $PASS passed, $FAIL failed"
[ "$FAIL" -eq 0 ]