# claude work lock/queue

> Source: <https://gist.github.com/junkdog/91482c72a67a6243631b1a2aae08942a>
> Published: 2026-12-02 07:19:57+00:00

**Recommendation:** Wrap every heavy agent command in a kind-tagged flock coordinator so benchmarks run alone and builds overlap, and wait on job exit rather than polling with pgrep.
More in the playbook "Running AI in production": <https://wpnews.pro/playbooks/production-ops>

*2026-12-01 · How we keep benchmarks honest on one workstation that several coding agents (and people) build, test,
fuzz and measure on at the same time: a small job coordinator, `work.zsh`, built on kernel file locks, and a Claude
Code integration that shows its queue and stops agents from running heavy work outside it. Everything needed to
rebuild it is here, the full scripts included (appendix).*

*We built it for the development of [ada](https://junkdog.github.io/ada-md/), a terminal markdown viewer and pager
whose speed is benchmarked against other viewers, by coding agents that build, fuzz and measure on one shared
machine. Nothing in the design is specific to ada, but the figures under "In practice" come from that project.*

One machine, several workers at once. In our case two Claude Code agents, each in its own checkout of the same repository, plus scratch trees for experiments, all on one 32-thread workstation. Their work comes in three kinds, and they don't mix the same way:

- **Benchmarks** must have the machine to themselves. A compile beside a timing doesn't just add noise: it changes
clocks, heat and cache state. We once threw away a baseline that ran beside builds with the CPU at 100 °C, and an
analysis script running outside any lock skewed an A/B comparison by ~45%.
- **Builds and test suites** load every core but don't care what runs beside them, as long as it isn't a benchmark.
Serializing them behind each other wastes hours.
- **Long-running jobs** (in our case fuzzing campaigns) are happy beside builds but not beside each other, since
two of them would fight for the same cores for hours.

A single global "exclusive" lock gets the first point right and the other two wrong. That's where we started, and it made agents wait on each other's compiles all day. What we needed was a lock that knows what kind of work each job is.

Three more things went wrong often enough to design for:

- A job's child process outlived its parent (a fuzzer's fork worker, reparented to init) and silently kept holding the lock. Nobody could tell what was holding it.
- A "5-minute" run kept going for 45 minutes because the stop signal never reached it, and nobody asked until much later.
- Agents waited for background work with polling loops that matched their own shell (`pgrep -f` ), and hung forever.

Every heavy command is run through one wrapper, with a kind and a label:

```
work.zsh build "unit tests"   cargo test --release --no-run
work.zsh bench --cpus 2 "parser speed"   cargo test --release --test speed -- --ignored --nocapture
work.zsh fuzz  "parser smoke"   cargo fuzz run parser -- -max_total_time=600
```

| kind | for | may run beside | 
|---|---|---|
| `bench` | anything timed: microbenchmarks, hyperfine, end-to-end timing runs, A/B comparisons | nothing | 
| `fuzz` | long jobs of which only one at a time makes sense: fuzzing, soak tests, corpus minimization | builds, not another `fuzz` | 
| `build` | compiles, test suites, lints, analysis scripts that load cores | builds and one `fuzz` | 

The rules around it:

1. **Compile apart from the measurement.** Build the benchmark binary under`build` , then time the built binary
under`bench` . A compile never holds the whole machine.
2. **The wait is the kernel's.** The wrapper blocks in`flock` until its locks are free: no polling, no sleep
loops, no PID files. Start a job in the background and wait for it to exit.
3. **The exit status is the command's,** so the wrapper drops into scripts and`&&` chains unchanged.
4. **One shared state directory** for the whole machine, whichever checkout or user the job comes from.

The parts:

| part | what it does | 
|---|---|
| `work.zsh` | the lock and queue: takes the right locks for the kind, runs the command, logs everything | 
| the job registry | one JSON file per waiting or running job, each guarded by a lock of its own, so liveness is never guessed | 
| the event log | an append-only JSONL history: queued, started, ended, skipped, capped, lost | 
| the busy gate | a benchmark's last check: the CPUs must actually be idle, which catches work that never took the lock | 
| Claude Code integration | the queue shown above the prompt, and a guard that refuses heavy commands run outside the wrapper | 

Everything lives in one directory (`WORK_DIR`, by default `~/.local/state/work-lock`; every user of the machine
must point at the same one):

| file | what | who holds it | 
|---|---|---|
| `ccd0` ,`ccd1` , … | one lock per L3 cache domain (a CCD on AMD; a single `ccd0` on most Intel parts) | a bench exclusively (all of them), others shared (their CPUs' domains) | 
| `fuzz` | one long job at a time | a `fuzz` job, exclusively | 
| `gate` | the queue's front door | every job while it takes its locks; a waiting bench for as long as it waits | 
| `jobs/ID.json` | the job's record, one line of JSON, rewritten atomically (write `.tmp` , then`mv` ) | — | 
| `jobs/ID.lock` | the job's liveness lock | the job, exclusively, for its whole life | 
| `log.jsonl` | the event history, append-only | — | 

A job's ID is `YYYYMMDD-HHMMSS-PID`.

The script reads each online CPU's L3 cache id from `/sys/devices/system/cpu/cpuN/cache/index3/id`, so it needs no
table of the machine. `--cpus 0-15` or `--cpus 2,4,6` pins the command with `taskset` and decides which domains the
job locks; without it the job may use every CPU, unpinned, and locks every domain.

Per-domain locks leave room for one refinement, off by default: with `WORK_SPLIT=1`, a bench pinned inside one
domain locks only that domain, and a build that finds a domain held pins itself to the free ones. Measure before
turning it on. The domains still share power, thermal headroom and memory bandwidth, so a build on one can move a
benchmark on the other.

Linux's `flock` doesn't favor a waiting exclusive locker. A bench waiting for `ccd0` exclusively would wait forever
while new builds keep arriving and taking it shared, since there's always at least one build holding it. So every
job first takes `gate` exclusively, takes its domain locks, then releases `gate`. A build passes through the gate in
a moment. A bench waiting for running builds to drain holds the gate the whole time, so builds started after it
queue at the gate instead of overtaking it. In practice the queue is first come, first served, without any queue
data structure.

A `fuzz` job waits for the `fuzz` lock *before* the gate. Otherwise a long job queued behind another long job would
hold the gate, and with it every build, for hours.

``` php
flowchart TD
  A[take ID.lock, write ID.json state=waiting, log queue] --> B{fuzz?}
  B -- yes --> C[wait for the fuzz lock]
  B -- no --> D
  C --> D[wait for the gate]
  D --> E[wait for each domain lock: bench exclusive, others shared]
  E --> F[release the gate and close its descriptor]
  F --> I{bench?}
  I -- yes --> J[sample /proc/stat until its CPUs are idle, or give up: exit 75, log skip]
  I -- no --> K
  J --> K[ID.json state=running, log start]
  K --> L[run the command under taskset and, for fuzz, timeout]
  L --> M[log end with rc; remove ID.json and ID.lock, or mark it leftover]
```

1. **Register.** Take`jobs/ID.lock`*before* writing` jobs/ID.json` . A job file whose lock nobody holds then always
belongs to a job that's gone. Log`queue` with the directory, git branch, CPUs, locks, load average and command
line.
2. **Take the locks** in the order above.
3. **Run.** Every lock descriptor is inherited by the command and everything it starts. The locks are therefore held
until the last descendant exits, and the kernel drops them however things end: crash,`SIGKILL` , closed
terminal. There is nothing to clean up after a death. The gate's descriptor is closed first, so the command
doesn't inherit the gate.
4. **End,** from an`EXIT` trap, so also on signals. Close`ID.lock` 's descriptor and try to take it back. If that
works, no descendant is left: remove the job's files. If not, a process the command started still holds it: the
record is rewritten as`leftover` and stays. Either way, log`end` with the exit code and run time.

Every `status` call tries a non-blocking shared lock on each `jobs/ID.lock`:

- **Lock free:** the job is gone. The reader renames the record to`ID.json.gone` (the rename makes sure exactly one
concurrent reader logs it), logs`lost` (killed without its trap running) or`clear` (a leftover whose processes
have now ended), and removes the files.
- **Lock held, wrapper's PID dead:** the job is`leftover` . Its processes still run, and`fuser -v WORK_DIR/jobs/ID.lock` names them.

No PID is ever guessed from a command line. That's the whole fix for the stray-fuzzer problem: the orphan still holds the lock, and now the lock tells you who it is.

Locks only see jobs that take them. So once a bench holds its locks, it samples `/proc/stat` for the CPUs of its
domains over `WORK_BUSY_WINDOW` seconds (5). It starts only when their mean busy share is under `WORK_MAX_BUSY`
percent (5), retrying for up to `WORK_WAIT_MIN` minutes (30). If they never get quiet it exits 75 without running
the command. That catches an unwrapped build, a stray script or a busy desktop app. Every bench pays at least one
window (5 s) before it starts.

One known weakness: a 5-second mean lets a bursty load through. One day a busy desktop made interactive benchmark cells read 2–4× slow while every bench passed the gate. For long, important runs, also make sure the desktop is quiet.

A `fuzz` job runs under `timeout -k 60` with a cap of `WORK_FUZZ_MAX` minutes (150; 0 for none). `timeout` puts the
command in its own process group and signals the whole group: `SIGTERM` at the cap, `SIGKILL` 60 s later. The job
ends with exit 124 and a `capped` event. A process the command moved into a session of its own (`setsid`) is outside
that group, and stopping it is that script's job. Put a per-step cap inside long scripts too: the wrapper's cap is
the last line of defense, not the plan.

```
work.zsh status          # one line per waiting, running or leftover job
work.zsh status --json   # {now, dir, jobs: [the job records], recent: [the last WORK_RECENT ends]}
work.zsh log [N]         # the last N events (20), tabulated through jq when it's installed
```

`status` in a terminal:

```
work.zsh: jobs in /home/you/.local/state/work-lock, 2026-12-01T17:30:16+01:00, load 1.25 1.06 0.75
  running  build "b1"                           2s  project (main), cpus 0-31, pid 331803
  waiting  bench "bench"                        1s  project (main), cpus 0-31, pid 331825
  waiting  build "b2"                           1s  project (main), cpus 0-31, pid 331842
```

A job record:

```
{"id":"20261105-120000-42","pid":42,"kind":"bench","label":"print A/B","state":"running",
 "checkout":"/home/you/src/project-second","branch":"dev","cpus":"0-15","pinned":1,"locks":"ccd0,ccd1",
 "queued":1793874000,"started":1793874010,"command":"tools/ab.zsh a b"}
```

| exit status | meaning | 
|---|---|
| the command's | the job ran | 
| 75 | a bench not run: its CPUs never got quiet ( `skip` event) | 
| 124 / 137 | a `fuzz` job stopped at its cap (`capped` event) | 
| 129 / 130 / 143 | the wrapper itself got SIGHUP / SIGINT / SIGTERM | 
| 2 | usage, a bad `--cpus` or`WORK_FUZZ_MAX` | 

| variable | default | effect | 
|---|---|---|
| `WORK_DIR` | `~/.local/state/work-lock` | the shared state directory | 
| `WORK_MAX_BUSY` | 5 | a bench's busy-gate threshold, mean percent; `off` skips the check | 
| `WORK_BUSY_WINDOW` | 5 | the busy gate's sample window, seconds | 
| `WORK_WAIT_MIN` | 30 | how long a bench waits for idle CPUs before exit 75 | 
| `WORK_FUZZ_MAX` | 150 | a `fuzz` job's cap, minutes; 0 for none | 
| `WORK_SPLIT` | 0 | 1: per-domain benches, and builds that pin themselves to free domains | 
| `WORK_RECENT` | 8 | how many ended jobs `status --json` lists | 

Log events are `queue`, `start`, `end`, `skip`, `capped`, `lost` and `clear`. Each has `t` (ISO time), `ts`
(epoch), `ev` and `id`, plus the kind and label (for `lost` and `clear`, the whole job record under `job`). `start`
carries `wait_s`, `end` carries `rc`, `run_s` and `leftover`.

The lock only helps if every agent uses it, and agents forget. Four layers make sure they do: instructions, one memory shared by every checkout, a guard, and a visible queue.

In the project's `CLAUDE.md` (or the user's global one):

```
## Heavy work goes through the work lock
- Run every build, test suite, benchmark and fuzz run as `tools/work.zsh KIND [--cpus LIST] LABEL CMD…`:
  `bench` for anything timed, `fuzz` for long fuzz or soak runs, `build` for everything else that loads cores.
- Compile under `build` first, then time the built binary under `bench`. Never build inside a bench job.
- Start jobs with `run_in_background` and wait for the completion notification. Never write a polling loop, and
  never identify a process with `pgrep -f`/` pkill -f`: they match your own shell.
- Check `tools/work.zsh status` before a foreground build: behind a long bench it will exceed the tool timeout.
- A queued job that doesn't start: read `status`. A `leftover` job's processes are named by
  `fuser -v <WORK_DIR>/jobs/ID.lock`.
- Before starting another build job of your own, read `status` and `log`: your earlier job may still be running.
```

Claude Code keeps an agent's auto-memory per project, in `~/.claude/projects/<slug>/memory/`. The slug is the
checkout's absolute path with `/` turned into `-`, so a second checkout of the same repository gets its own, empty
memory. A lesson one agent learns about the lock (check `status` before a foreground build, a helper script that
builds as a side effect) would then stay with that agent.

We point the second checkout's memory at the first one's, so every agent reads and writes the same memories:

```
# before the second checkout's first session, or after merging its memories into the first's
ln -s ~/.claude/projects/-home-you-src-project/memory ~/.claude/projects/-home-you-src-project-second/memory
```

`CLAUDE.md` is shared through git anyway. The memory is for what the agents learn while working, which is where
most of the lessons below were first written down. Keep one fact per memory file, so that two agents rarely write
the same file at once; the index file is the one place they both touch.

Two small scripts (appendix B and C) and three entries in `~/.claude/settings.json`:

```
{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Bash",
        "hooks": [
          {
            "type": "command",
            "command": "WORK_GUARD_ROOTS=/home/you/src/project:/home/you/src/project-second zsh ~/.claude/hooks/work-guard.zsh"
          }
        ]
      }
    ]
  },
  "statusLine": {
    "type": "command",
    "command": "WORK_SH=/home/you/src/project/tools/work.zsh zsh ~/.claude/hooks/work-statusline.zsh"
  }
}
```

The **guard** reads the hook's JSON (`cwd`, `tool_input.command`). When the session's directory is inside one of
the guarded trees and the command runs a heavy `cargo` subcommand outside the wrapper, it answers with a `deny`
decision. The decision's reason tells the agent exactly how to wrap the command, so the agent usually retries
correctly on its own. Its rule:

1. A command that mentions `work.zsh` anywhere passes as a whole.
2. Otherwise it's split into simple commands on `&&` ,`||` ,`$(` ,`;` ,`|` ,`&` , newlines, parentheses, braces
and backticks.
3. In each one, leading `VAR=value` words and command runners (`env` ,`time` ,`nice` ,`ionice` ,`nohup` ,`command` ,`exec` ,`chrt` ,`setsid` ,`stdbuf` , plus`taskset` and`timeout` with their argument) are skipped.
4. If what's left is `cargo` , its toolchain and option words are skipped, and the next word is the subcommand.`build` ,`test` ,`run` ,`bench` ,`check` ,`clippy` ,`fuzz` ,`nextest` ,`doc` ,`install` ,`rustc` ,`miri` ,`llvm-cov` ,`xtask` and their short aliases are heavy.`fmt` ,`tree` and`--version` pass.

It fails open. If `jq` is missing or anything is unexpected, the call goes through, and the busy gate remains the
backstop. For another toolchain, change the `heavy` list and the `cargo` match: `make`, `ninja`, `gradle`,
`pytest`, `go test`.

The **status line** prints one line while jobs wait or run (`work ▶ bench "parser speed" 3m12s · … 2 waiting`) and
nothing otherwise. It's redrawn as the session updates, not on a timer, so it can lag a little while the agent is
idle.

We run the same guard as a Claude Code plugin in the TypeScript hooks-module form (appendix D), loaded through
`CLAUDE_CODE_PLUGIN_DIRS` in `settings.json`'s `env`. Over the plain hooks, it adds:

- a **band above the prompt** , polled every 3 s from`status --json` , up to four lines like`work ▶ bench "print A/B" 12m03s · project-second · cpus 0-15` (▶ running in green, … waiting in yellow, ! leftover in
red);
- a **`/work` command** that toggles a pane: every job, a`fuser` hint under each leftover, and the last five jobs
to end with their exit codes;
- the **guard** as a`tool.call` hook on Bash, with the same rule. It's wrapped in`.catch(…)` so that a failure
lets the call through.

It only acts in sessions started inside the listed checkouts; anywhere else it stays out of the way. It needs a Claude Code version with that plugin API. If yours doesn't have it, 3a covers the guard and the status.

- It reads text, not shell. A heredoc or inline script whose text puts `cargo build` at the start of a line, or
inside backticks, is refused as if it were a build. Write such text with an editor tool, then run the script by
path.
- It sees only `cargo` : a heavy Python script,`hyperfine` , or a helper script that compiles as a side effect
passes. One of our helper scripts built a fuzz target before listing its options, and loaded cores for two
minutes beside another agent's jobs.
- A command that merely mentions `work.zsh` (`echo work.zsh; cargo build` ) passes whole.
- It checks the session's directory, so a session started elsewhere that `cd` s into a guarded tree isn't guarded.

The busy gate protects benchmarks from all of these. Nothing protects builds from each other, and nothing needs to.

25 days on one 16-core, 32-thread, two-CCD workstation: two agents in two checkouts, plus 149 scratch trees for experiments.

|  | build | bench | fuzz | 
|---|---|---|---|
| jobs started | 4,622 | 1,948 | 315 | 
| total run time | 95.1 h | 15.8 h | 54.2 h | 
| median run | 54 s | 3 s | 400 s | 
| longest run | 3h12m | 1h19m | 1h51m | 
| jobs that had to wait | 264 (median 12.5 s, longest 45 min) | 387 over 10 s (median 69 s, longest 1h39m) | 62 (median 17.5 s, longest 29 min) | 

- 6,891 jobs queued, up to 1,046 on the busiest day, and at most 8 running at once.
- 1,485 of the 1,948 benches started right after one busy-gate window (5 s). The gate never had to skip one, and no
`fuzz` job hit its cap: the caps are insurance.
- Five jobs were `lost` (killed without their trap) and 16 ended`leftover` ; all were cleared automatically once
their processes ended.
- The log grew to 5 MB. `status --json` greps it every 3 s per open session, which is still cheap at that size.

- **A foreground build behind a long bench hits the agent's tool timeout** (2 minutes in Claude Code). Check`status` first, or always start jobs in the background.
- **Never wait with a poller that matches its own command line.**`until ! pgrep -f pat` matches the waiting shell
itself and loops forever.`kill -0 $(pgrep -f pat)` polls its own PID. An empty`$(…)` inside`/proc/$(…)` makes
the path`/proc/` , which always exists.`pkill -f pat` kills its own shell. Wait on the background job itself, or
on a PID you hold.
- **An agent's own builds can collide.** Builds may overlap by design, so a script that temporarily swaps a source
file to build an A/B baseline must not run beside another job of the same agent. Read`status` and`log` before
starting the next one, not just the last notification.
- **Fuzzers' fork workers outlive their group.** libFuzzer's`-fork` children can be reparented to init after a`SIGTERM` and keep holding inherited locks. The lock now names them (`leftover` ); also make the fuzz script kill
what it started.
- **Background jobs started from a non-interactive shell ignore SIGINT.** Stop them with`SIGTERM` to the process
group (`kill -TERM -- -PGID` ), and confirm by`/proc/*/exe` , not by command-line pattern.
- **Locks you can't see are the dangerous ones.** The single most useful debugging tool turned out to be`fuser -v` on a lock file.

1. Put `work.zsh` (appendix A) in the repository, e.g.`tools/work.zsh` , executable.
2. Pick one `WORK_DIR` for the machine. The default works when everyone runs as one user; for several users, a
group-writable directory such as`/var/lib/work-lock` .
3. Rename the kinds if `fuzz` doesn't fit: it means "one at a time, fine beside builds". Adjust`WORK_FUZZ_MAX` to a
bit above your longest legitimate run.
4. Wrap your benchmark scripts in `bench` , split their compile step out under`build` , and wrap CI-like scripts
under`build` .
5. Add the instructions to `CLAUDE.md` , and the guard and status line (3a or 3b). Change the guard's heavy list for
your toolchain.
6. With more than one checkout, symlink every other checkout's memory directory to the first one's.
7. Leave `WORK_SPLIT` off until you've measured a bench on one cache domain with a build looping on the other.

Requirements: Linux, zsh 5, util-linux (`flock`, `taskset`), coreutils `timeout`, `fuser` (psmisc) for debugging,
`jq` for `log` and the hooks. macOS has no `flock(1)`, `/proc/stat` or `taskset`: there it needs a port (a small
`flock(2)` helper, `host_processor_info` for the busy gate, no pinning).

Limits by design:

- **One machine.** The locks are local files; a fleet needs a real scheduler.
- **Cooperative.** It stops nothing that doesn't take the lock. The guard and the busy gate narrow the gap but don't
close it.
- **No priorities or preemption.** First come, first served, and a bench waits for running builds to finish rather
than stopping them.

``` bash
#!/usr/bin/env zsh
# work.zsh: one machine's work lock, shared by every checkout, agent and person that runs heavy work on it, so that
# a benchmark never runs beside other work. Linux only (flock(1), taskset(1), timeout(1), /proc, /sys).
#   work.zsh bench|fuzz|build [--cpus LIST] LABEL CMD [ARGS…]   runs CMD as a job of that kind; exits with its status
#   work.zsh status [--json]                                    the jobs waiting and running
#   work.zsh log [N]                                            the last N events of the work log (20)
# What may run beside what: a bench beside nothing; a fuzz beside builds, but not beside another fuzz; a build
# beside builds and one fuzz. Compile under `build`, then measure under `bench`, so a compile never holds the machine.
#   The state is in WORK_DIR (default ~/.local/state/work-lock; every user of the machine must agree on it): a lock
#   per L3 domain (ccd0, ccd1, …: a bench takes them exclusively, the others shared), `fuzz` (one fuzz job at a time)
#   and `gate`, which every job passes on its way in and a waiting bench holds, so that builds started after it queue
#   behind it instead of starving it (Linux's flock doesn't favor a waiting exclusive lock). The locks are taken
#   before CMD starts and held until this script and everything CMD started have exited (they inherit them), and the
#   kernel releases them however they end. A job that has to wait prints what holds them and waits in flock, without
#   polling: start it in the background and wait for it to exit.
#   --cpus LIST (e.g. 0-15 or 2,4,6,8) pins CMD with taskset and names the L3 domains the job locks; without it, all
#   CPUs, unpinned. WORK_SPLIT=1, on every side, lets a bench whose CPUs lie in one domain lock only that domain, and
#   a build that finds a domain held pin itself to the free ones: measure that a bench holds its figures beside such
#   a build before turning it on (the domains share power, thermals and memory bandwidth).
#   A bench, once it holds its locks, waits until the CPUs of the domains it holds average under WORK_MAX_BUSY percent
#   busy (5) over WORK_BUSY_WINDOW seconds of /proc/stat (5), for at most WORK_WAIT_MIN minutes (30), and exits 75
#   without running CMD if they never do; WORK_MAX_BUSY=off skips the check. It catches what the lock can't: an
#   unwrapped build, a script, a desktop app.
#   A fuzz job stops after WORK_FUZZ_MAX minutes (150; 0 for none): CMD and everything in its process group get
#   SIGTERM, then SIGKILL 60 s later, and the job ends with rc 124, logged as a `capped` event. A process CMD moved
#   to a session of its own (setsid) is its own script's to stop on that SIGTERM.
#   The work log: WORK_DIR/jobs/ID.json names each waiting or running job, held under a lock of its own (ID.lock), so
#   a reader tells a killed job's file from a live one by trying that lock; WORK_DIR/log.jsonl is the history (queue,
#   start, end, skip, capped, lost, clear). A job whose work.zsh is gone while its lock is still held is "leftover":
#   processes CMD started still run, and `fuser -v WORK_DIR/jobs/ID.lock` names them.
# e.g. work.zsh build "unit tests" cargo test --release --no-run
#      work.zsh bench --cpus 2 "parser speed" cargo test --release --test speed -- --ignored --nocapture
#      work.zsh fuzz "parser smoke" cargo fuzz run parser -- -max_total_time=600
emulate zsh
setopt no_unset extended_glob
zmodload zsh/datetime

usage() {
  print -u2 "usage: work.zsh bench|fuzz|build [--cpus LIST] LABEL CMD [ARGS…]
       work.zsh status [--json]
       work.zsh log [N]"
  exit 2
}
die() { print -u2 -r -- "work.zsh: $*"; exit 2 }

W=${WORK_DIR:-${XDG_STATE_HOME:-$HOME/.local/state}/work-lock}
J=$W/jobs
mkdir -p $J || exit 1

# --- CPUs and CCDs ---------------------------------------------------------------------------------------------
cpus_expand() {   # "0-3,8" -> REPLY=(0 1 2 3 8)
  local part
  reply=()
  for part in ${(s:,:)1}; do
    if [[ $part == (#b)(<->)-(<->) ]]; then reply+=({$match[1]..$match[2]})
    elif [[ $part == <-> ]]; then reply+=($part)
    else return 1; fi
  done
}
cpus_compact() {   # (0 1 2 3 8) -> REPLY="0-3,8"
  local -a out; local c a=-1 b=-1
  for c in ${(no)@}; do
    if (( a >= 0 && c == b + 1 )); then b=$c; continue; fi
    (( a >= 0 )) && { (( a == b )) && out+=($a) || out+=($a-$b) }
    a=$c b=$c
  done
  (( a >= 0 )) && { (( a == b )) && out+=($a) || out+=($a-$b) }
  REPLY=${(j:,:)out}
}
cpus_expand $(</sys/devices/system/cpu/online); online=($reply)
typeset -A ccd_of
for c in $online; do
  f=/sys/devices/system/cpu/cpu$c/cache/index3/id
  [[ -r $f ]] && ccd_of[$c]=$(<$f) || ccd_of[$c]=0
done
all_ccds=(${(nou)ccd_of})
ccd_cpus() {   # REPLY=(the CPUs of the CCDs given)
  local c; local -a ds=($@); reply=()
  for c in $online; do (( ${ds[(Ie)$ccd_of[$c]]} )) && reply+=($c); done
}

# --- JSON --------------------------------------------------------------------------------------------------------
js() {   # REPLY = $1 as a JSON string
  local s=${1//[[:cntrl:]]/ }
  s=${s//\\/\\\\}; s=${s//\"/\\\"}
  REPLY="\"$s\""
}
dur() {   # seconds -> 1h02m, 12m30s, 45s
  local s=${1%.*}
  if (( s >= 3600 )); then printf '%dh%02dm' $(( s / 3600 )) $(( s % 3600 / 60 ))
  elif (( s >= 60 )); then printf '%dm%02ds' $(( s / 60 )) $(( s % 60 ))
  else printf '%ds' $s; fi
}
load() { cut -d' ' -f1-3 /proc/loadavg }

# --- the work log, read ------------------------------------------------------------------------------------------
logev_raw() { print -r -- "$1" >> $W/log.jsonl }
# a job file's field, from its one-line JSON (strings and numbers only; the writer below is the only one)
field() { local f=$1 k=$2; [[ $f =~ "\"$k\":(\"([^\"\\\\]|\\\\.)*\"|[-0-9.]+|true|false|null)" ]] && REPLY=${${match[1]#\"}%\"} || REPLY= }

# Lists the job files, clearing those whose job is gone: a file whose lock nobody holds is a killed job's (logged as
# lost) or a leftover's whose processes have since ended (logged as clear). Sets live=(file…) of the live ones.
scan() {
  local f id st ts
  live=()
  for f in $J/*.json(N); do
    id=${f:t:r}
    if flock -n -s $J/$id.lock true 2>/dev/null; then
      # gone; the mv makes sure one reader logs it
      if mv -f $f $f.gone 2>/dev/null; then
        field "$(<$f.gone)" state; st=$REPLY
        js "$id"; ts=$EPOCHSECONDS
        logev_raw "{\"t\":\"$(date -Is)\",\"ts\":$ts,\"ev\":\"${${st:#leftover}:+lost}${${(M)st:#leftover}:+clear}\",\"id\":$REPLY,\"job\":$(<$f.gone)}"
        rm -f $f.gone $J/$id.lock
      fi
      continue
    fi
    live+=($f)
  done
}

status_human() {   # one line per job, $1 the id to leave out (a waiting job's own)
  local f j state kind label pid since started queued checkout branch cpus now=$EPOCHSECONDS
  scan
  for f in $live; do
    [[ ${f:t:r} == ${1:-} ]] && continue
    j="$(<$f)"
    field "$j" state; state=$REPLY; field "$j" kind; kind=$REPLY; field "$j" label; label=$REPLY
    field "$j" pid; pid=$REPLY; field "$j" queued; queued=$REPLY; field "$j" started; started=$REPLY
    field "$j" checkout; checkout=${REPLY:t}; field "$j" branch; branch=$REPLY; field "$j" cpus; cpus=$REPLY
    [[ $state != leftover ]] && ! kill -0 $pid 2>/dev/null && state=leftover
    [[ $started == (|null) ]] && since=$queued || since=$started
    printf '  %-8s %-5s %-24s %8s  %s (%s), cpus %s, pid %s\n' $state $kind "\"$label\"" "$(dur $(( now - since )))" \
      $checkout ${branch:-detached} $cpus $pid
    [[ $state == leftover ]] && print -r -- "           its processes still hold the lock: fuser -v $J/${f:t:r}.lock"
  done
  (( $#live )) || print "  (no jobs)"
}

status_json() {
  local f j state pid first=1
  scan
  print -rn -- "{\"now\":$EPOCHSECONDS,\"dir\":\"$W\",\"jobs\":["
  for f in $live; do
    j="$(<$f)"
    field "$j" state; state=$REPLY; field "$j" pid; pid=$REPLY
    [[ $state != leftover ]] && ! kill -0 $pid 2>/dev/null && j=${j/\"state\":\"$state\"/\"state\":\"leftover\"}
    (( first )) || print -rn ,
    first=0
    print -rn -- "$j"
  done
  print -rn -- "],\"recent\":["
  if [[ -r $W/log.jsonl ]]; then
    print -rn -- "${(j:,:)${(f)$(grep -E '"ev":"(end|skip|lost|clear)"' $W/log.jsonl | tail -n ${WORK_RECENT:-8})}}"
  fi
  print -r -- "]}"
}

case ${1:-} in
  status)
    if [[ ${2:-} == --json ]]; then status_json; else
      print -r -- "work.zsh: jobs in $W, $(date -Is), load $(load)"
      status_human
    fi
    exit 0 ;;
  log)
    n=${2:-20}
    [[ -r $W/log.jsonl ]] || { print "(no work log yet)"; exit 0 }
    if (( $+commands[jq] )); then
      tail -n $n $W/log.jsonl | jq -r '[.t[0:19], .ev, (.kind // .job.kind // ""), ((.label // .job.label // "") | "\"\(.)\""),
        (if .ev == "end" then "rc=\(.rc) ran \(.run_s)s" + (if .leftover then ", leftover" else "" end)
         elif .ev == "start" then "waited \(.wait_s)s, cpus \(.cpus)" + (if .busy then ", busy \(.busy)" else "" end)
         elif .ev == "queue" then "\(.checkout | split("/") | last) (\(.branch)), cpus \(.cpus)"
         elif .ev == "skip" then "not run: busy \(.busy)" else "" end)] | @tsv' | column -t -s $'\t'
    else
      tail -n $n $W/log.jsonl
    fi
    exit 0 ;;
  bench|fuzz|build) kind=$1; shift ;;
  *) usage ;;
esac

# --- a job -------------------------------------------------------------------------------------------------------
cpus_arg=
case ${1:-} in
  --cpus) (( $# >= 2 )) || usage; cpus_arg=$2; shift 2 ;;
  --cpus=*) cpus_arg=${1#--cpus=}; shift ;;
esac
(( $# >= 2 )) || usage
label=$1
shift
if [[ -n $cpus_arg ]]; then
  cpus_expand $cpus_arg || die "--cpus $cpus_arg: not a CPU list"
  want=(${(nou)reply})
  for c in $want; do (( ${online[(Ie)$c]} )) || die "--cpus $cpus_arg: CPU $c isn't online ($(</sys/devices/system/cpu/online))"; done
else
  want=($online)
fi
typeset -U mine=()
for c in $want; do mine+=($ccd_of[$c]); done
split=${WORK_SPLIT:-0}
case $kind in
  bench) (( split )) && locks=($mine) || locks=($all_ccds); mode=-x ;;
  *)     locks=($mine); mode=-s ;;
esac
pinned=0; [[ -n $cpus_arg ]] && pinned=1
max_busy=${WORK_MAX_BUSY:-5}; [[ $kind == bench ]] || max_busy=off
window=${WORK_BUSY_WINDOW:-5}
wait_min=${WORK_WAIT_MIN:-30}

id=$(strftime %Y%m%d-%H%M%S $EPOCHSECONDS)-$$
queued=$EPOCHSECONDS
checkout=$PWD
branch=$(git branch --show-current 2>/dev/null)
js "$label"; jlabel=$REPLY
js "${(j: :)${(q-)@}}"; jcmd=$REPLY
js "$checkout"; jcheckout=$REPLY
js "$branch"; jbranch=$REPLY

# the job's own lock first, then its file: a file without a held lock is always a gone job's
exec {jfd}>$J/$id.lock || exit 1
flock -x $jfd || exit 1
state=waiting started=null
write_job() {
  local cpus; cpus_compact $want; cpus=$REPLY
  print -r -- "{\"id\":\"$id\",\"pid\":$$,\"kind\":\"$kind\",\"label\":$jlabel,\"state\":\"$state\",\"checkout\":$jcheckout,\"branch\":$jbranch,\"cpus\":\"$cpus\",\"pinned\":$(( pinned )),\"locks\":\"${(j:,:)${(@)locks/#/ccd}}\",\"queued\":$queued,\"started\":$started,\"command\":$jcmd}" >| $J/$id.json.tmp &&
    mv -f $J/$id.json.tmp $J/$id.json
}
logev() { logev_raw "{\"t\":\"$(date -Is)\",\"ts\":$EPOCHSECONDS,\"ev\":\"$1\",\"id\":\"$id\",\"kind\":\"$kind\",\"label\":$jlabel${2:-}}" }
write_job
cpus_compact $want
logev queue ",\"checkout\":$jcheckout,\"branch\":$jbranch,\"cpus\":\"$REPLY\",\"locks\":\"${(j:,:)${(@)locks/#/ccd}}\",\"load\":\"$(load)\",\"command\":$jcmd"

done_logged=0 rc=1
cleanup() {
  local still=0 run=0
  [[ $started != null ]] && run=$(( EPOCHSECONDS - started ))
  rm -f -- $J/$id.json.tmp
  # closing our descriptor releases the job's lock unless processes CMD started still hold it
  exec {jfd}>&-
  if ! flock -n -x $J/$id.lock true 2>/dev/null; then
    still=1 state=leftover
    write_job
  else
    rm -f -- $J/$id.json $J/$id.lock
  fi
  if (( ! done_logged )); then
    logev end ",\"rc\":$rc,\"run_s\":$run,\"load\":\"$(load)\"${${still:#0}:+,\"leftover\":true}"
  fi
}
trap 'cleanup' EXIT
trap 'rc=129; exit 129' HUP
trap 'rc=130; exit 130' INT
trap 'rc=143; exit 143' TERM

announced=0
announce() {
  (( announced )) && return
  announced=1
  print -r -- "work.zsh: $kind '$label' waits, $(date -Is); the work in $W:"
  status_human $id
}
take() {   # take MODE FD WHAT: flock, announcing the wait if it has to
  flock -n $1 $2 && return 0
  announce
  flock $1 $2
}

# one fuzz job at a time, waited for before the gate, so it doesn't hold the gate while it waits
if [[ $kind == fuzz ]]; then
  exec {ffd}>>$W/fuzz || exit 1
  take -x $ffd || exit 1
fi
exec {gfd}>>$W/gate || exit 1
take -x $gfd || exit 1
typeset -A lfd
for d in $locks; do
  exec {fd}>>$W/ccd$d || exit 1
  lfd[$d]=$fd
done
if [[ $kind == build ]] && (( split )); then
  # a build takes the CCDs it finds free, and pins itself to them, if a bench holds the others
  got=()
  for d in $locks; do flock -n -s $lfd[$d] && got+=($d); done
  if (( $#got && $#got < $#locks )); then
    for d in ${locks:|got}; do fd=$lfd[$d]; exec {fd}>&-; unset "lfd[$d]"; done
    ccd_cpus $got
    want=(${want:*reply}) locks=($got) pinned=1
    print -r -- "work.zsh: build '$label' pinned to CPUs $(cpus_compact $want; print -rn $REPLY): a bench holds the other CCD"
  fi
fi
for d in $locks; do take $mode $lfd[$d] || exit 1; done
# leave the gate, and don't hand it to CMD
flock -u $gfd
exec {gfd}>&-
(( announced )) && print -r -- "work.zsh: $kind '$label' has its locks, $(date -Is)"

# a bench waits for quiet CPUs
busy=
if [[ $max_busy != off ]]; then
  ccd_cpus $locks; quiet=($reply)
  sample() {   # REPLY = "mean max" busy percent of the CPUs in $quiet over $window seconds
    local -A t0 i0; local -a f; local c dt di sum=0 mx=0 b n=0
    while read -rA f; do
      [[ $f[1] == cpu<-> ]] || continue
      t0[${f[1]#cpu}]=$(( f[2] + f[3] + f[4] + f[5] + f[6] + f[7] + f[8] + f[9] )); i0[${f[1]#cpu}]=$(( f[5] + f[6] ))
    done < /proc/stat
    sleep $window
    while read -rA f; do
      [[ $f[1] == cpu<-> ]] || continue
      c=${f[1]#cpu}
      (( ${quiet[(Ie)$c]} )) || continue
      (( dt = f[2] + f[3] + f[4] + f[5] + f[6] + f[7] + f[8] + f[9] - t0[$c], di = f[5] + f[6] - i0[$c] ))
      (( b = dt > 0 ? 100.0 * (dt - di) / dt : 0, sum += b, n++ ))
      (( b > mx )) && mx=$b
    done < /proc/stat
    printf -v REPLY '%.1f %.1f' $(( n ? sum / n : 0 )) $mx
  }
  deadline=$(( EPOCHSECONDS + wait_min * 60 ))
  for (( i = 0; ; i++ )); do
    sample
    m=${REPLY% *}
    busy="${REPLY% *}% mean, ${REPLY#* }% max"
    (( m < max_busy )) && break
    if (( EPOCHSECONDS >= deadline )); then
      print -r -- "work.zsh: bench '$label' not run: CPUs $(cpus_compact $quiet; print -rn $REPLY) still $busy busy after $wait_min min, $(date -Is)"
      logev skip ",\"busy\":\"$busy\",\"load\":\"$(load)\""
      done_logged=1 rc=75
      exit 75
    fi
    (( i == 0 )) && print -r -- "work.zsh: bench '$label' waits for CPUs $(cpus_compact $quiet; print -rn $REPLY) under $max_busy% busy (now $busy)"
  done
fi

state=running started=$EPOCHSECONDS
write_job
cpus_compact $want; cpus=$REPLY
logev start ",\"wait_s\":$(( started - queued )),\"cpus\":\"$cpus\",\"pinned\":$(( pinned )),\"load\":\"$(load)\"${busy:+,\"busy\":\"$busy\"}"
print -r -- "work.zsh: $kind '$label' starts on CPUs $cpus, load $(load)${busy:+, busy $busy}"
pre=()
(( pinned )) && pre=(taskset -c $cpus)
cap=0
if [[ $kind == fuzz ]]; then
  cap=${WORK_FUZZ_MAX:-150}
  [[ $cap == <-> ]] || die "WORK_FUZZ_MAX: $cap"
  # `timeout` runs CMD in a process group of its own and signals all of it
  (( cap > 0 )) && pre=(timeout -k 60 $(( cap * 60 )) $pre)
fi
"${pre[@]}" "$@"
rc=$?
if (( cap > 0 && (rc == 124 || rc == 137) && EPOCHSECONDS - started >= cap * 60 )); then
  print -r -- "work.zsh: fuzz '$label' stopped after WORK_FUZZ_MAX=$cap min, $(date -Is)"
  logev capped ",\"max_min\":$cap"
fi
print -r -- "work.zsh: $kind '$label' done, rc=$rc, $(dur $(( EPOCHSECONDS - started ))), load $(load), $(date -Is)"
exit $rc
bash
#!/usr/bin/env zsh
# work-guard.zsh: a Claude Code PreToolUse hook for Bash. In the directories named by WORK_GUARD_ROOTS (colon
# separated), it refuses a command that runs a heavy cargo subcommand outside work.zsh, and tells the agent how to
# wrap it. It reads text, not shell: a reminder, not a wall. Anything unexpected lets the call through.
emulate zsh
setopt extended_glob
(( $+commands[jq] )) || exit 0
input=$(cat)
cmd=$(jq -r '.tool_input.command // empty' <<<$input) || exit 0
cwd=$(jq -r '.cwd // empty' <<<$input) || exit 0
[[ -n $cmd ]] || exit 0

# only in the guarded trees
roots=(${(s.:.)WORK_GUARD_ROOTS:-})
inside=0
for r in $roots; do [[ $cwd == $r || $cwd == $r/* ]] && inside=1; done
(( inside )) || exit 0

# a command that names the wrapper passes as a whole
[[ $cmd == *work.zsh* ]] && exit 0

heavy=(build b test t run r bench check c clippy fuzz nextest doc d install rustc miri llvm-cov xtask)
runners=(env time nice ionice nohup command exec chrt setsid stdbuf)
valued=(--manifest-path -C --config -Z --color --target-dir)

# split into simple commands on && || $( ; | & newlines ( ) { } and backticks
seps=$'\n'
flat=${cmd//(\&\&|\|\||\$\(|[\;\|\&\(\)\{\}\`])/$seps}
found=
for seg in ${(f)flat}; do
  words=(${=seg})
  i=1
  while (( i <= $#words )); do
    w=$words[i]
    if [[ $w == [A-Za-z_][A-Za-z0-9_]#=* ]]; then (( i++ ))
    elif (( ${runners[(Ie)$w]} )); then
      (( i++ )); while (( i <= $#words )) && [[ $words[i] == -* ]]; do (( i++ )); done
    elif [[ $w == taskset || $w == timeout ]]; then
      (( i++ )); while (( i <= $#words )) && [[ $words[i] == -* ]]; do (( i++ )); done
      (( i++ ))   # the CPU list or the duration
    else break; fi
  done
  (( i <= $#words )) || continue
  [[ $words[i] == cargo || $words[i] == */cargo ]] || continue
  j=$(( i + 1 ))
  while (( j <= $#words )) && [[ $words[j] == [-+]* ]]; do
    (( ${valued[(Ie)$words[j]]} )) && (( j += 2 )) || (( j++ ))
  done
  (( j <= $#words )) && (( ${heavy[(Ie)$words[j]]} )) && { found=$words[j]; break }
done
[[ -n $found ]] || exit 0

reason="work-guard: \`cargo $found\` loads every core, so it runs under the work lock here: work.zsh build LABEL <the command> (a timing: work.zsh bench). A build waits while a bench runs (work.zsh status): run it in the background then."
jq -n --arg r "$reason" '{hookSpecificOutput: {hookEventName: "PreToolUse", permissionDecision: "deny", permissionDecisionReason: $r}}'
exit 0
bash
#!/usr/bin/env zsh
# work-statusline.zsh: a Claude Code status line showing the work lock's jobs, e.g.
#   work ▶ bench "parser speed" 3m12s · … 2 waiting
# WORK_SH names work.zsh. Prints nothing when no job waits or runs.
emulate zsh
cat >/dev/null   # the session's JSON on stdin isn't needed
s=$(zsh ${WORK_SH:?} status --json 2>/dev/null) || exit 0
jq -r '
  def dur: if . >= 3600 then "\(. / 3600 | floor)h\(. % 3600 / 60 | floor)m"
           elif . >= 60 then "\(. / 60 | floor)m\(. % 60)s" else "\(.)s" end;
  .now as $now
  | [.jobs[] | select(.state == "running")] as $run
  | [.jobs[] | select(.state == "waiting")] as $wait
  | [.jobs[] | select(.state == "leftover")] as $left
  | if (.jobs | length) == 0 then empty else
      "work "
      + ([$run[] | "▶ \(.kind) \"\(.label)\" \($now - .started | dur)"] | join(" · "))
      + (if ($wait | length) > 0 then " · … \($wait | length) waiting" else "" end)
      + (if ($left | length) > 0 then " · ! \($left | length) leftover" else "" end)
    end' <<<$s
```

The plugin's directory:

```
work-lock/
  .claude-plugin/plugin.json
  hooks/hooks.json
  hooks/register.tsx
  types/index.d.ts
  tsconfig.json          extends the types tsconfig the plugin tooling generates under .claude-plugin/types/
```

`.claude-plugin/plugin.json`:

```
{
  "name": "work-lock",
  "version": "0.1.0",
  "description": "The machine's work lock (work.zsh) in Claude Code: its jobs above the prompt, its log on /work, and unwrapped heavy cargo commands refused",
  "license": "MIT",
  "types": "./types/index.d.ts"
}
```

`hooks/hooks.json`:

```
{ "modules": ["./register.tsx"] }
```

`types/index.d.ts`:

```
// One job of bench/work.zsh, as `work.zsh status --json` lists it (its .work/jobs/ID.json)
export type Job = {
  id: string
  pid: number
  kind: 'bench' | 'fuzz' | 'build'
  label: string
  state: 'waiting' | 'running' | 'leftover'
  checkout: string
  branch: string
  cpus: string
  pinned: number
  locks: string
  queued: number
  started: number | null
  command: string
}

// One event of .work/log.jsonl: `status --json` lists the last ends (end, skip, lost, clear)
export type WorkEvent = {
  t: string
  ts: number
  ev: string
  id: string
  kind?: string
  label?: string
  rc?: number
  run_s?: number
  leftover?: boolean
  busy?: string
  job?: Job
}

export type Snapshot = { now: number; dir: string; jobs: Job[]; recent: WorkEvent[] }

declare module 'claude-code' {
  interface PluginState {
    'work-lock': { snap: Shaped<Snapshot | null> }
  }
}
```

`hooks/register.tsx` (set `WORK` and `CHECKOUTS` at the top):

```
// The work lock (work.zsh) in Claude Code. In a session started in one of the guarded checkouts it
//   - polls `work.zsh status --json` every 3 s and shows the jobs waiting and running in a band above the prompt,
//   - opens a pane on /work (again: closes it; also Escape or its Close) with a line a job, running or waiting,
//     and the last five to end,
//   - refuses a Bash call that runs a heavy cargo command (build, test, run, clippy, fuzz…) outside work.zsh,
//     since a bench can't see work that doesn't take the lock.
import { atom, read, update } from 'claude-code'
import type { Register } from 'claude-code'

import type { Job, Snapshot, WorkEvent } from '../types'

// --- configure ----------------------------------------------------------------------------------------------------
// the script, by absolute path, and the checkouts the mod acts in (a session started elsewhere is left alone)
const WORK = '/home/you/src/project/tools/work.zsh'
const CHECKOUTS = ['/home/you/src/project', '/home/you/src/project-second']
// -------------------------------------------------------------------------------------------------------------------

const inCheckout = (dir: string) => CHECKOUTS.some(c => dir === c || dir.startsWith(c + '/'))
const PANE = 'work-lock'
const POLL_MS = 3000
const BAND_ROWS = 4
// the ends the pane lists, the latest first
const RECENT = 5

const snap = atom({ plugin: 'work-lock', key: 'snap' } as const, null, { shape: 'snap-1' })

// --- the guard ----------------------------------------------------------------------------------------------------

// cargo's subcommands that compile or load every core
const HEAVY = new Set([
  'build', 'b', 'test', 't', 'run', 'r', 'bench', 'check', 'c', 'clippy', 'fuzz', 'nextest', 'doc', 'd',
  'install', 'rustc', 'miri', 'llvm-cov', 'xtask',
])
// words that run the command after them
const PREFIX = new Set(['env', 'time', 'nice', 'ionice', 'nohup', 'command', 'exec', 'chrt', 'setsid', 'stdbuf'])
// cargo's options before the subcommand that take a value
const VALUED = new Set(['--manifest-path', '-C', '--config', '-Z', '--color', '--target-dir'])

/** The heavy cargo subcommand a shell command runs outside the work lock, if any. */
export function unwrappedCargo(command: string): string | undefined {
  if (/\b(work|exclusive)\.zsh\b/.test(command)) return undefined
  for (const segment of command.split(/&&|\|\||\$\(|[;|&\n(){}`]/)) {
    const words = segment.trim().split(/\s+/).filter(word => word !== '')
    let i = 0
    while (i < words.length) {
      const word = words[i]
      if (/^[A-Za-z_][A-Za-z0-9_]*=/.test(word)) i += 1
      else if (PREFIX.has(word)) {
        i += 1
        while (i < words.length && words[i].startsWith('-')) i += 1
      } else if (word === 'taskset' || word === 'timeout') {
        i += 1
        while (i < words.length && words[i].startsWith('-')) i += 1
        i += 1 // the CPU list or mask, the duration
      } else break
    }
    const head = words[i]
    if (head !== 'cargo' && !head?.endsWith('/cargo')) continue
    let j = i + 1
    while (j < words.length && (words[j].startsWith('+') || words[j].startsWith('-'))) {
      j += VALUED.has(words[j]) ? 2 : 1
    }
    const sub = words[j]
    if (sub !== undefined && HEAVY.has(sub)) return sub
  }
  return undefined
}

// --- drawing ------------------------------------------------------------------------------------------------------

function dur(s: number): string {
  s = Math.max(0, Math.floor(s))
  if (s >= 3600) return `${Math.floor(s / 3600)}h${String(Math.floor((s % 3600) / 60)).padStart(2, '0')}m`
  if (s >= 60) return `${Math.floor(s / 60)}m${String(s % 60).padStart(2, '0')}s`
  return `${s}s`
}

// the checkout a job came from, by its last path component
function where(checkout: string): string {
  const home = CHECKOUTS.find(c => checkout === c || checkout.startsWith(c + '/')) ?? checkout
  return home.split('/').pop() ?? home
}

const COLOR = { running: 'success', waiting: 'warning', leftover: 'error' } as const
const MARK = { running: '▶', waiting: '…', leftover: '!' } as const

function jobText(job: Job, now: number): string {
  const since = job.started ?? job.queued
  const state = job.state === 'running' ? '' : `${job.state} `
  return `${job.kind} "${job.label}" ${state}${dur(now - since)} · ${where(job.checkout)} · cpus ${job.cpus}`
}

function eventText(ev: WorkEvent): string {
  const kind = ev.kind ?? ev.job?.kind ?? ''
  const label = ev.label ?? ev.job?.label ?? ''
  const tail =
    ev.ev === 'end' ? `rc=${ev.rc} ${dur(ev.run_s ?? 0)}${ev.leftover ? ', leftover' : ''}`
    : ev.ev === 'skip' ? `not run: busy ${ev.busy ?? '?'}`
    : ev.ev === 'lost' ? 'killed before it ended'
    : ev.ev === 'clear' ? "its leftovers ended"
    : ''
  return `${ev.t.slice(11, 16)}  ${ev.ev.padEnd(5)} ${kind.padEnd(5)} "${label}"  ${tail}`
}

const clip = (text: string, columns: number) =>
  text.length <= columns ? text : text.slice(0, Math.max(1, columns - 1)) + '…'

export const register: Register = on => {
  on('session.start', async ($, e, next) => {
    const root = await $.session.cwd()
    if (!inCheckout(root)) return next(e)

    await $.command.register({ name: 'work', description: "Show the work lock's jobs and the last to end" })

    let last = ''
    const poll = async () => {
      try {
        const { exitCode, stdout } = await $.process.run(['env', `WORK_RECENT=${RECENT}`, 'zsh', WORK, 'status', '--json'], {
          timeoutMs: 15000,
        })
        if (exitCode !== 0) return
        const s = JSON.parse(stdout) as Snapshot
        const key = JSON.stringify([s.jobs, s.recent.at(-1)?.id ?? '', s.recent.length])
        // while jobs run their times move, so every poll redraws; otherwise only a change does
        if (s.jobs.length === 0 && key === last) return
        last = key
        await update($, snap, () => s)
      } catch {
        // the next poll tries again
      }
    }
    await poll()
    $.clock.every(POLL_MS, () => void poll())

    return next(e)
  })

  on('command.run', { command: 'work' }, async $ => {
    if ((await $.ui.panes()).some(pane => pane.id === PANE)) {
      await $.ui.close({ id: PANE })
      return { text: 'Work lock pane closed.' }
    }
    await $.ui.open({ id: PANE, title: 'Work lock', closeOnEscape: true })

    return { text: 'Work lock pane opened: /work again, Escape or its Close closes it (the full log: work.zsh log).' }
  })

  on('tool.call', { tool: 'Bash' }, async ($, e, next) => {
    const root = await $.session.cwd()
    const sub = inCheckout(root) ? unwrappedCargo(e.command) : undefined
    if (sub === undefined) return next(e)

    return {
      deny:
        `work-lock: \` cargo ${sub}\` loads every core, so it runs under the work lock in this checkout: ` +
        `work.zsh build LABEL <the command> (a timing: work.zsh bench). ` +
        `A build waits while a bench runs (work.zsh status): run it with run_in_background then.`,
    }
  }).catch(($, e, next) => next(e)) // a guard that fails lets the call through: it is a reminder, not a wall

  on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
    if (e.props.hasSurvey) return next(e)
    const s = await read($, snap)
    if (s === null || s.jobs.length === 0) return next(e)

    const { Box, Text } = $.ui.resolve(e)
    const columns = Math.max(20, e.props.bodyColumns - 9)
    const shown = s.jobs.slice(0, BAND_ROWS)

    return (
      <Box flexDirection="column">
        {shown.map(job => (
          <Text>
            <Text dimColor>work </Text>
            <Text color={COLOR[job.state]}>{MARK[job.state]} </Text>
            <Text>{clip(jobText(job, s.now), columns)}</Text>
          </Text>
        ))}
        {s.jobs.length > shown.length && <Text dimColor>work   +{s.jobs.length - shown.length} more: /work</Text>}
      </Box>
    )
  })

  // a line a job, as the band's, and the last ends: the commands and the whole log are work.zsh status and log's
  on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
    const { Box, Text, Button } = $.ui.resolve(e)
    const s = await read($, snap)
    const columns = Math.max(20, e.props.bodyColumns)
    const close = (
      <Button role="dismiss" onPress={() => void $.ui.close({ id: PANE })}>
        Close
      </Button>
    )
    if (s === null) {
      return (
        <Box flexDirection="column">
          <Text dimColor>No word from work.zsh yet.</Text>
          {close}
        </Box>
      )
    }

    return (
      <Box flexDirection="column">
        {s.jobs.length === 0 && <Text dimColor>work   no job waiting or running</Text>}
        {s.jobs.map(job => (
          <Text>
            <Text dimColor>work </Text>
            <Text color={COLOR[job.state]}>{MARK[job.state]} </Text>
            <Text>{clip(jobText(job, s.now), columns - 7)}</Text>
          </Text>
        ))}
        {s.jobs
          .filter(job => job.state === 'leftover')
          .map(job => (
            <Text color="error">{clip(`       still held: fuser -v ${s.dir}/jobs/${job.id}.lock`, columns)}</Text>
          ))}
        {s.recent
          .slice(-RECENT)
          .reverse()
          .map(ev => (
            <Text dimColor={ev.ev === 'end' && ev.rc === 0}>{clip(eventText(ev), columns)}</Text>
          ))}
        {close}
      </Box>
    )
  })
}
```


