{"slug": "claude-work-lock-queue", "title": "claude work lock/queue", "summary": "A developer built work.zsh, a small job coordinator on kernel file locks that lets multiple coding agents and people share one workstation for builds, tests, fuzzing and benchmarks. The tool assigns each job a kind (bench, fuzz, build) with different exclusivity rules, so benchmarks run alone while builds can overlap, and it integrates with Claude Code to show the queue and stop agents from running heavy work outside it. The design was motivated by failures including a baseline discarded after running beside builds at 100 °C and an unlocked analysis script skewing an A/B comparison by about 45%.", "body_md": "*2026-12-01 · How we keep benchmarks honest on one workstation that several coding agents (and people) build, test,\nfuzz and measure on at the same time: a small job coordinator, `work.zsh`, built on kernel file locks, and a Claude\nCode integration that shows its queue and stops agents from running heavy work outside it. Everything needed to\nrebuild it is here, the full scripts included (appendix).*\n\n*We built it for the development of [ada](https://junkdog.github.io/ada-md/), a terminal markdown viewer and pager\nwhose speed is benchmarked against other viewers, by coding agents that build, fuzz and measure on one shared\nmachine. Nothing in the design is specific to ada, but the figures under \"In practice\" come from that project.*\n\nOne 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:\n\n- **Benchmarks** must have the machine to themselves. A compile beside a timing doesn't just add noise: it changes\nclocks, heat and cache state. We once threw away a baseline that ran beside builds with the CPU at 100 °C, and an\nanalysis script running outside any lock skewed an A/B comparison by ~45%.\n- **Builds and test suites** load every core but don't care what runs beside them, as long as it isn't a benchmark.\nSerializing them behind each other wastes hours.\n- **Long-running jobs** (in our case fuzzing campaigns) are happy beside builds but not beside each other, since\ntwo of them would fight for the same cores for hours.\n\nA 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.\n\nThree more things went wrong often enough to design for:\n\n- 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.\n- A \"5-minute\" run kept going for 45 minutes because the stop signal never reached it, and nobody asked until much later.\n- Agents waited for background work with polling loops that matched their own shell (`pgrep -f` ), and hung forever.\n\nEvery heavy command is run through one wrapper, with a kind and a label:\n\n```\nwork.zsh build \"unit tests\"   cargo test --release --no-run\nwork.zsh bench --cpus 2 \"parser speed\"   cargo test --release --test speed -- --ignored --nocapture\nwork.zsh fuzz  \"parser smoke\"   cargo fuzz run parser -- -max_total_time=600\n```\n\n| kind | for | may run beside | \n|---|---|---|\n| `bench` | anything timed: microbenchmarks, hyperfine, end-to-end timing runs, A/B comparisons | nothing | \n| `fuzz` | long jobs of which only one at a time makes sense: fuzzing, soak tests, corpus minimization | builds, not another `fuzz` | \n| `build` | compiles, test suites, lints, analysis scripts that load cores | builds and one `fuzz` | \n\nThe rules around it:\n\n1. **Compile apart from the measurement.** Build the benchmark binary under`build` , then time the built binary\nunder`bench` . A compile never holds the whole machine.\n2. **The wait is the kernel's.** The wrapper blocks in`flock` until its locks are free: no polling, no sleep\nloops, no PID files. Start a job in the background and wait for it to exit.\n3. **The exit status is the command's,** so the wrapper drops into scripts and`&&` chains unchanged.\n4. **One shared state directory** for the whole machine, whichever checkout or user the job comes from.\n\nThe parts:\n\n| part | what it does | \n|---|---|\n| `work.zsh` | the lock and queue: takes the right locks for the kind, runs the command, logs everything | \n| the job registry | one JSON file per waiting or running job, each guarded by a lock of its own, so liveness is never guessed | \n| the event log | an append-only JSONL history: queued, started, ended, skipped, capped, lost | \n| the busy gate | a benchmark's last check: the CPUs must actually be idle, which catches work that never took the lock | \n| Claude Code integration | the queue shown above the prompt, and a guard that refuses heavy commands run outside the wrapper | \n\nEverything lives in one directory (`WORK_DIR`, by default `~/.local/state/work-lock`; every user of the machine\nmust point at the same one):\n\n| file | what | who holds it | \n|---|---|---|\n| `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) | \n| `fuzz` | one long job at a time | a `fuzz` job, exclusively | \n| `gate` | the queue's front door | every job while it takes its locks; a waiting bench for as long as it waits | \n| `jobs/ID.json` | the job's record, one line of JSON, rewritten atomically (write `.tmp` , then`mv` ) | — | \n| `jobs/ID.lock` | the job's liveness lock | the job, exclusively, for its whole life | \n| `log.jsonl` | the event history, append-only | — | \n\nA job's ID is `YYYYMMDD-HHMMSS-PID`.\n\nThe script reads each online CPU's L3 cache id from `/sys/devices/system/cpu/cpuN/cache/index3/id`, so it needs no\ntable of the machine. `--cpus 0-15` or `--cpus 2,4,6` pins the command with `taskset` and decides which domains the\njob locks; without it the job may use every CPU, unpinned, and locks every domain.\n\nPer-domain locks leave room for one refinement, off by default: with `WORK_SPLIT=1`, a bench pinned inside one\ndomain locks only that domain, and a build that finds a domain held pins itself to the free ones. Measure before\nturning it on. The domains still share power, thermal headroom and memory bandwidth, so a build on one can move a\nbenchmark on the other.\n\nLinux's `flock` doesn't favor a waiting exclusive locker. A bench waiting for `ccd0` exclusively would wait forever\nwhile new builds keep arriving and taking it shared, since there's always at least one build holding it. So every\njob first takes `gate` exclusively, takes its domain locks, then releases `gate`. A build passes through the gate in\na moment. A bench waiting for running builds to drain holds the gate the whole time, so builds started after it\nqueue at the gate instead of overtaking it. In practice the queue is first come, first served, without any queue\ndata structure.\n\nA `fuzz` job waits for the `fuzz` lock *before* the gate. Otherwise a long job queued behind another long job would\nhold the gate, and with it every build, for hours.\n\n``` php\nflowchart TD\n  A[take ID.lock, write ID.json state=waiting, log queue] --> B{fuzz?}\n  B -- yes --> C[wait for the fuzz lock]\n  B -- no --> D\n  C --> D[wait for the gate]\n  D --> E[wait for each domain lock: bench exclusive, others shared]\n  E --> F[release the gate and close its descriptor]\n  F --> I{bench?}\n  I -- yes --> J[sample /proc/stat until its CPUs are idle, or give up: exit 75, log skip]\n  I -- no --> K\n  J --> K[ID.json state=running, log start]\n  K --> L[run the command under taskset and, for fuzz, timeout]\n  L --> M[log end with rc; remove ID.json and ID.lock, or mark it leftover]\n```\n\n1. **Register.** Take`jobs/ID.lock`*before* writing` jobs/ID.json` . A job file whose lock nobody holds then always\nbelongs to a job that's gone. Log`queue` with the directory, git branch, CPUs, locks, load average and command\nline.\n2. **Take the locks** in the order above.\n3. **Run.** Every lock descriptor is inherited by the command and everything it starts. The locks are therefore held\nuntil the last descendant exits, and the kernel drops them however things end: crash,`SIGKILL` , closed\nterminal. There is nothing to clean up after a death. The gate's descriptor is closed first, so the command\ndoesn't inherit the gate.\n4. **End,** from an`EXIT` trap, so also on signals. Close`ID.lock` 's descriptor and try to take it back. If that\nworks, no descendant is left: remove the job's files. If not, a process the command started still holds it: the\nrecord is rewritten as`leftover` and stays. Either way, log`end` with the exit code and run time.\n\nEvery `status` call tries a non-blocking shared lock on each `jobs/ID.lock`:\n\n- **Lock free:** the job is gone. The reader renames the record to`ID.json.gone` (the rename makes sure exactly one\nconcurrent reader logs it), logs`lost` (killed without its trap running) or`clear` (a leftover whose processes\nhave now ended), and removes the files.\n- **Lock held, wrapper's PID dead:** the job is`leftover` . Its processes still run, and`fuser -v WORK_DIR/jobs/ID.lock` names them.\n\nNo 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.\n\nLocks only see jobs that take them. So once a bench holds its locks, it samples `/proc/stat` for the CPUs of its\ndomains over `WORK_BUSY_WINDOW` seconds (5). It starts only when their mean busy share is under `WORK_MAX_BUSY`\npercent (5), retrying for up to `WORK_WAIT_MIN` minutes (30). If they never get quiet it exits 75 without running\nthe command. That catches an unwrapped build, a stray script or a busy desktop app. Every bench pays at least one\nwindow (5 s) before it starts.\n\nOne 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.\n\nA `fuzz` job runs under `timeout -k 60` with a cap of `WORK_FUZZ_MAX` minutes (150; 0 for none). `timeout` puts the\ncommand in its own process group and signals the whole group: `SIGTERM` at the cap, `SIGKILL` 60 s later. The job\nends with exit 124 and a `capped` event. A process the command moved into a session of its own (`setsid`) is outside\nthat group, and stopping it is that script's job. Put a per-step cap inside long scripts too: the wrapper's cap is\nthe last line of defense, not the plan.\n\n```\nwork.zsh status          # one line per waiting, running or leftover job\nwork.zsh status --json   # {now, dir, jobs: [the job records], recent: [the last WORK_RECENT ends]}\nwork.zsh log [N]         # the last N events (20), tabulated through jq when it's installed\n```\n\n`status` in a terminal:\n\n```\nwork.zsh: jobs in /home/you/.local/state/work-lock, 2026-12-01T17:30:16+01:00, load 1.25 1.06 0.75\n  running  build \"b1\"                           2s  project (main), cpus 0-31, pid 331803\n  waiting  bench \"bench\"                        1s  project (main), cpus 0-31, pid 331825\n  waiting  build \"b2\"                           1s  project (main), cpus 0-31, pid 331842\n```\n\nA job record:\n\n```\n{\"id\":\"20261105-120000-42\",\"pid\":42,\"kind\":\"bench\",\"label\":\"print A/B\",\"state\":\"running\",\n \"checkout\":\"/home/you/src/project-second\",\"branch\":\"dev\",\"cpus\":\"0-15\",\"pinned\":1,\"locks\":\"ccd0,ccd1\",\n \"queued\":1793874000,\"started\":1793874010,\"command\":\"tools/ab.zsh a b\"}\n```\n\n| exit status | meaning | \n|---|---|\n| the command's | the job ran | \n| 75 | a bench not run: its CPUs never got quiet ( `skip` event) | \n| 124 / 137 | a `fuzz` job stopped at its cap (`capped` event) | \n| 129 / 130 / 143 | the wrapper itself got SIGHUP / SIGINT / SIGTERM | \n| 2 | usage, a bad `--cpus` or`WORK_FUZZ_MAX` | \n\n| variable | default | effect | \n|---|---|---|\n| `WORK_DIR` | `~/.local/state/work-lock` | the shared state directory | \n| `WORK_MAX_BUSY` | 5 | a bench's busy-gate threshold, mean percent; `off` skips the check | \n| `WORK_BUSY_WINDOW` | 5 | the busy gate's sample window, seconds | \n| `WORK_WAIT_MIN` | 30 | how long a bench waits for idle CPUs before exit 75 | \n| `WORK_FUZZ_MAX` | 150 | a `fuzz` job's cap, minutes; 0 for none | \n| `WORK_SPLIT` | 0 | 1: per-domain benches, and builds that pin themselves to free domains | \n| `WORK_RECENT` | 8 | how many ended jobs `status --json` lists | \n\nLog events are `queue`, `start`, `end`, `skip`, `capped`, `lost` and `clear`. Each has `t` (ISO time), `ts`\n(epoch), `ev` and `id`, plus the kind and label (for `lost` and `clear`, the whole job record under `job`). `start`\ncarries `wait_s`, `end` carries `rc`, `run_s` and `leftover`.\n\nThe 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.\n\nIn the project's `CLAUDE.md` (or the user's global one):\n\n```\n## Heavy work goes through the work lock\n- Run every build, test suite, benchmark and fuzz run as `tools/work.zsh KIND [--cpus LIST] LABEL CMD…`:\n  `bench` for anything timed, `fuzz` for long fuzz or soak runs, `build` for everything else that loads cores.\n- Compile under `build` first, then time the built binary under `bench`. Never build inside a bench job.\n- Start jobs with `run_in_background` and wait for the completion notification. Never write a polling loop, and\n  never identify a process with `pgrep -f`/` pkill -f`: they match your own shell.\n- Check `tools/work.zsh status` before a foreground build: behind a long bench it will exceed the tool timeout.\n- A queued job that doesn't start: read `status`. A `leftover` job's processes are named by\n  `fuser -v <WORK_DIR>/jobs/ID.lock`.\n- Before starting another build job of your own, read `status` and `log`: your earlier job may still be running.\n```\n\nClaude Code keeps an agent's auto-memory per project, in `~/.claude/projects/<slug>/memory/`. The slug is the\ncheckout's absolute path with `/` turned into `-`, so a second checkout of the same repository gets its own, empty\nmemory. A lesson one agent learns about the lock (check `status` before a foreground build, a helper script that\nbuilds as a side effect) would then stay with that agent.\n\nWe point the second checkout's memory at the first one's, so every agent reads and writes the same memories:\n\n```\n# before the second checkout's first session, or after merging its memories into the first's\nln -s ~/.claude/projects/-home-you-src-project/memory ~/.claude/projects/-home-you-src-project-second/memory\n```\n\n`CLAUDE.md` is shared through git anyway. The memory is for what the agents learn while working, which is where\nmost of the lessons below were first written down. Keep one fact per memory file, so that two agents rarely write\nthe same file at once; the index file is the one place they both touch.\n\nTwo small scripts (appendix B and C) and three entries in `~/.claude/settings.json`:\n\n```\n{\n  \"hooks\": {\n    \"PreToolUse\": [\n      {\n        \"matcher\": \"Bash\",\n        \"hooks\": [\n          {\n            \"type\": \"command\",\n            \"command\": \"WORK_GUARD_ROOTS=/home/you/src/project:/home/you/src/project-second zsh ~/.claude/hooks/work-guard.zsh\"\n          }\n        ]\n      }\n    ]\n  },\n  \"statusLine\": {\n    \"type\": \"command\",\n    \"command\": \"WORK_SH=/home/you/src/project/tools/work.zsh zsh ~/.claude/hooks/work-statusline.zsh\"\n  }\n}\n```\n\nThe **guard** reads the hook's JSON (`cwd`, `tool_input.command`). When the session's directory is inside one of\nthe guarded trees and the command runs a heavy `cargo` subcommand outside the wrapper, it answers with a `deny`\ndecision. The decision's reason tells the agent exactly how to wrap the command, so the agent usually retries\ncorrectly on its own. Its rule:\n\n1. A command that mentions `work.zsh` anywhere passes as a whole.\n2. Otherwise it's split into simple commands on `&&` ,`||` ,`$(` ,`;` ,`|` ,`&` , newlines, parentheses, braces\nand backticks.\n3. 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.\n4. 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.\n\nIt fails open. If `jq` is missing or anything is unexpected, the call goes through, and the busy gate remains the\nbackstop. For another toolchain, change the `heavy` list and the `cargo` match: `make`, `ninja`, `gradle`,\n`pytest`, `go test`.\n\nThe **status line** prints one line while jobs wait or run (`work ▶ bench \"parser speed\" 3m12s · … 2 waiting`) and\nnothing otherwise. It's redrawn as the session updates, not on a timer, so it can lag a little while the agent is\nidle.\n\nWe run the same guard as a Claude Code plugin in the TypeScript hooks-module form (appendix D), loaded through\n`CLAUDE_CODE_PLUGIN_DIRS` in `settings.json`'s `env`. Over the plain hooks, it adds:\n\n- 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\nred);\n- a **`/work` command** that toggles a pane: every job, a`fuser` hint under each leftover, and the last five jobs\nto end with their exit codes;\n- the **guard** as a`tool.call` hook on Bash, with the same rule. It's wrapped in`.catch(…)` so that a failure\nlets the call through.\n\nIt 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.\n\n- It reads text, not shell. A heredoc or inline script whose text puts `cargo build` at the start of a line, or\ninside backticks, is refused as if it were a build. Write such text with an editor tool, then run the script by\npath.\n- It sees only `cargo` : a heavy Python script,`hyperfine` , or a helper script that compiles as a side effect\npasses. One of our helper scripts built a fuzz target before listing its options, and loaded cores for two\nminutes beside another agent's jobs.\n- A command that merely mentions `work.zsh` (`echo work.zsh; cargo build` ) passes whole.\n- It checks the session's directory, so a session started elsewhere that `cd` s into a guarded tree isn't guarded.\n\nThe busy gate protects benchmarks from all of these. Nothing protects builds from each other, and nothing needs to.\n\n25 days on one 16-core, 32-thread, two-CCD workstation: two agents in two checkouts, plus 149 scratch trees for experiments.\n\n|  | build | bench | fuzz | \n|---|---|---|---|\n| jobs started | 4,622 | 1,948 | 315 | \n| total run time | 95.1 h | 15.8 h | 54.2 h | \n| median run | 54 s | 3 s | 400 s | \n| longest run | 3h12m | 1h19m | 1h51m | \n| 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) | \n\n- 6,891 jobs queued, up to 1,046 on the busiest day, and at most 8 running at once.\n- 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\n`fuzz` job hit its cap: the caps are insurance.\n- Five jobs were `lost` (killed without their trap) and 16 ended`leftover` ; all were cleared automatically once\ntheir processes ended.\n- The log grew to 5 MB. `status --json` greps it every 3 s per open session, which is still cheap at that size.\n\n- **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.\n- **Never wait with a poller that matches its own command line.**`until ! pgrep -f pat` matches the waiting shell\nitself and loops forever.`kill -0 $(pgrep -f pat)` polls its own PID. An empty`$(…)` inside`/proc/$(…)` makes\nthe path`/proc/` , which always exists.`pkill -f pat` kills its own shell. Wait on the background job itself, or\non a PID you hold.\n- **An agent's own builds can collide.** Builds may overlap by design, so a script that temporarily swaps a source\nfile to build an A/B baseline must not run beside another job of the same agent. Read`status` and`log` before\nstarting the next one, not just the last notification.\n- **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\nwhat it started.\n- **Background jobs started from a non-interactive shell ignore SIGINT.** Stop them with`SIGTERM` to the process\ngroup (`kill -TERM -- -PGID` ), and confirm by`/proc/*/exe` , not by command-line pattern.\n- **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.\n\n1. Put `work.zsh` (appendix A) in the repository, e.g.`tools/work.zsh` , executable.\n2. Pick one `WORK_DIR` for the machine. The default works when everyone runs as one user; for several users, a\ngroup-writable directory such as`/var/lib/work-lock` .\n3. Rename the kinds if `fuzz` doesn't fit: it means \"one at a time, fine beside builds\". Adjust`WORK_FUZZ_MAX` to a\nbit above your longest legitimate run.\n4. Wrap your benchmark scripts in `bench` , split their compile step out under`build` , and wrap CI-like scripts\nunder`build` .\n5. Add the instructions to `CLAUDE.md` , and the guard and status line (3a or 3b). Change the guard's heavy list for\nyour toolchain.\n6. With more than one checkout, symlink every other checkout's memory directory to the first one's.\n7. Leave `WORK_SPLIT` off until you've measured a bench on one cache domain with a build looping on the other.\n\nRequirements: Linux, zsh 5, util-linux (`flock`, `taskset`), coreutils `timeout`, `fuser` (psmisc) for debugging,\n`jq` for `log` and the hooks. macOS has no `flock(1)`, `/proc/stat` or `taskset`: there it needs a port (a small\n`flock(2)` helper, `host_processor_info` for the busy gate, no pinning).\n\nLimits by design:\n\n- **One machine.** The locks are local files; a fleet needs a real scheduler.\n- **Cooperative.** It stops nothing that doesn't take the lock. The guard and the busy gate narrow the gap but don't\nclose it.\n- **No priorities or preemption.** First come, first served, and a bench waits for running builds to finish rather\nthan stopping them.\n\n``` bash\n#!/usr/bin/env zsh\n# work.zsh: one machine's work lock, shared by every checkout, agent and person that runs heavy work on it, so that\n# a benchmark never runs beside other work. Linux only (flock(1), taskset(1), timeout(1), /proc, /sys).\n#   work.zsh bench|fuzz|build [--cpus LIST] LABEL CMD [ARGS…]   runs CMD as a job of that kind; exits with its status\n#   work.zsh status [--json]                                    the jobs waiting and running\n#   work.zsh log [N]                                            the last N events of the work log (20)\n# What may run beside what: a bench beside nothing; a fuzz beside builds, but not beside another fuzz; a build\n# beside builds and one fuzz. Compile under `build`, then measure under `bench`, so a compile never holds the machine.\n#   The state is in WORK_DIR (default ~/.local/state/work-lock; every user of the machine must agree on it): a lock\n#   per L3 domain (ccd0, ccd1, …: a bench takes them exclusively, the others shared), `fuzz` (one fuzz job at a time)\n#   and `gate`, which every job passes on its way in and a waiting bench holds, so that builds started after it queue\n#   behind it instead of starving it (Linux's flock doesn't favor a waiting exclusive lock). The locks are taken\n#   before CMD starts and held until this script and everything CMD started have exited (they inherit them), and the\n#   kernel releases them however they end. A job that has to wait prints what holds them and waits in flock, without\n#   polling: start it in the background and wait for it to exit.\n#   --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\n#   CPUs, unpinned. WORK_SPLIT=1, on every side, lets a bench whose CPUs lie in one domain lock only that domain, and\n#   a build that finds a domain held pin itself to the free ones: measure that a bench holds its figures beside such\n#   a build before turning it on (the domains share power, thermals and memory bandwidth).\n#   A bench, once it holds its locks, waits until the CPUs of the domains it holds average under WORK_MAX_BUSY percent\n#   busy (5) over WORK_BUSY_WINDOW seconds of /proc/stat (5), for at most WORK_WAIT_MIN minutes (30), and exits 75\n#   without running CMD if they never do; WORK_MAX_BUSY=off skips the check. It catches what the lock can't: an\n#   unwrapped build, a script, a desktop app.\n#   A fuzz job stops after WORK_FUZZ_MAX minutes (150; 0 for none): CMD and everything in its process group get\n#   SIGTERM, then SIGKILL 60 s later, and the job ends with rc 124, logged as a `capped` event. A process CMD moved\n#   to a session of its own (setsid) is its own script's to stop on that SIGTERM.\n#   The work log: WORK_DIR/jobs/ID.json names each waiting or running job, held under a lock of its own (ID.lock), so\n#   a reader tells a killed job's file from a live one by trying that lock; WORK_DIR/log.jsonl is the history (queue,\n#   start, end, skip, capped, lost, clear). A job whose work.zsh is gone while its lock is still held is \"leftover\":\n#   processes CMD started still run, and `fuser -v WORK_DIR/jobs/ID.lock` names them.\n# e.g. work.zsh build \"unit tests\" cargo test --release --no-run\n#      work.zsh bench --cpus 2 \"parser speed\" cargo test --release --test speed -- --ignored --nocapture\n#      work.zsh fuzz \"parser smoke\" cargo fuzz run parser -- -max_total_time=600\nemulate zsh\nsetopt no_unset extended_glob\nzmodload zsh/datetime\n\nusage() {\n  print -u2 \"usage: work.zsh bench|fuzz|build [--cpus LIST] LABEL CMD [ARGS…]\n       work.zsh status [--json]\n       work.zsh log [N]\"\n  exit 2\n}\ndie() { print -u2 -r -- \"work.zsh: $*\"; exit 2 }\n\nW=${WORK_DIR:-${XDG_STATE_HOME:-$HOME/.local/state}/work-lock}\nJ=$W/jobs\nmkdir -p $J || exit 1\n\n# --- CPUs and CCDs ---------------------------------------------------------------------------------------------\ncpus_expand() {   # \"0-3,8\" -> REPLY=(0 1 2 3 8)\n  local part\n  reply=()\n  for part in ${(s:,:)1}; do\n    if [[ $part == (#b)(<->)-(<->) ]]; then reply+=({$match[1]..$match[2]})\n    elif [[ $part == <-> ]]; then reply+=($part)\n    else return 1; fi\n  done\n}\ncpus_compact() {   # (0 1 2 3 8) -> REPLY=\"0-3,8\"\n  local -a out; local c a=-1 b=-1\n  for c in ${(no)@}; do\n    if (( a >= 0 && c == b + 1 )); then b=$c; continue; fi\n    (( a >= 0 )) && { (( a == b )) && out+=($a) || out+=($a-$b) }\n    a=$c b=$c\n  done\n  (( a >= 0 )) && { (( a == b )) && out+=($a) || out+=($a-$b) }\n  REPLY=${(j:,:)out}\n}\ncpus_expand $(</sys/devices/system/cpu/online); online=($reply)\ntypeset -A ccd_of\nfor c in $online; do\n  f=/sys/devices/system/cpu/cpu$c/cache/index3/id\n  [[ -r $f ]] && ccd_of[$c]=$(<$f) || ccd_of[$c]=0\ndone\nall_ccds=(${(nou)ccd_of})\nccd_cpus() {   # REPLY=(the CPUs of the CCDs given)\n  local c; local -a ds=($@); reply=()\n  for c in $online; do (( ${ds[(Ie)$ccd_of[$c]]} )) && reply+=($c); done\n}\n\n# --- JSON --------------------------------------------------------------------------------------------------------\njs() {   # REPLY = $1 as a JSON string\n  local s=${1//[[:cntrl:]]/ }\n  s=${s//\\\\/\\\\\\\\}; s=${s//\\\"/\\\\\\\"}\n  REPLY=\"\\\"$s\\\"\"\n}\ndur() {   # seconds -> 1h02m, 12m30s, 45s\n  local s=${1%.*}\n  if (( s >= 3600 )); then printf '%dh%02dm' $(( s / 3600 )) $(( s % 3600 / 60 ))\n  elif (( s >= 60 )); then printf '%dm%02ds' $(( s / 60 )) $(( s % 60 ))\n  else printf '%ds' $s; fi\n}\nload() { cut -d' ' -f1-3 /proc/loadavg }\n\n# --- the work log, read ------------------------------------------------------------------------------------------\nlogev_raw() { print -r -- \"$1\" >> $W/log.jsonl }\n# a job file's field, from its one-line JSON (strings and numbers only; the writer below is the only one)\nfield() { local f=$1 k=$2; [[ $f =~ \"\\\"$k\\\":(\\\"([^\\\"\\\\\\\\]|\\\\\\\\.)*\\\"|[-0-9.]+|true|false|null)\" ]] && REPLY=${${match[1]#\\\"}%\\\"} || REPLY= }\n\n# Lists the job files, clearing those whose job is gone: a file whose lock nobody holds is a killed job's (logged as\n# lost) or a leftover's whose processes have since ended (logged as clear). Sets live=(file…) of the live ones.\nscan() {\n  local f id st ts\n  live=()\n  for f in $J/*.json(N); do\n    id=${f:t:r}\n    if flock -n -s $J/$id.lock true 2>/dev/null; then\n      # gone; the mv makes sure one reader logs it\n      if mv -f $f $f.gone 2>/dev/null; then\n        field \"$(<$f.gone)\" state; st=$REPLY\n        js \"$id\"; ts=$EPOCHSECONDS\n        logev_raw \"{\\\"t\\\":\\\"$(date -Is)\\\",\\\"ts\\\":$ts,\\\"ev\\\":\\\"${${st:#leftover}:+lost}${${(M)st:#leftover}:+clear}\\\",\\\"id\\\":$REPLY,\\\"job\\\":$(<$f.gone)}\"\n        rm -f $f.gone $J/$id.lock\n      fi\n      continue\n    fi\n    live+=($f)\n  done\n}\n\nstatus_human() {   # one line per job, $1 the id to leave out (a waiting job's own)\n  local f j state kind label pid since started queued checkout branch cpus now=$EPOCHSECONDS\n  scan\n  for f in $live; do\n    [[ ${f:t:r} == ${1:-} ]] && continue\n    j=\"$(<$f)\"\n    field \"$j\" state; state=$REPLY; field \"$j\" kind; kind=$REPLY; field \"$j\" label; label=$REPLY\n    field \"$j\" pid; pid=$REPLY; field \"$j\" queued; queued=$REPLY; field \"$j\" started; started=$REPLY\n    field \"$j\" checkout; checkout=${REPLY:t}; field \"$j\" branch; branch=$REPLY; field \"$j\" cpus; cpus=$REPLY\n    [[ $state != leftover ]] && ! kill -0 $pid 2>/dev/null && state=leftover\n    [[ $started == (|null) ]] && since=$queued || since=$started\n    printf '  %-8s %-5s %-24s %8s  %s (%s), cpus %s, pid %s\\n' $state $kind \"\\\"$label\\\"\" \"$(dur $(( now - since )))\" \\\n      $checkout ${branch:-detached} $cpus $pid\n    [[ $state == leftover ]] && print -r -- \"           its processes still hold the lock: fuser -v $J/${f:t:r}.lock\"\n  done\n  (( $#live )) || print \"  (no jobs)\"\n}\n\nstatus_json() {\n  local f j state pid first=1\n  scan\n  print -rn -- \"{\\\"now\\\":$EPOCHSECONDS,\\\"dir\\\":\\\"$W\\\",\\\"jobs\\\":[\"\n  for f in $live; do\n    j=\"$(<$f)\"\n    field \"$j\" state; state=$REPLY; field \"$j\" pid; pid=$REPLY\n    [[ $state != leftover ]] && ! kill -0 $pid 2>/dev/null && j=${j/\\\"state\\\":\\\"$state\\\"/\\\"state\\\":\\\"leftover\\\"}\n    (( first )) || print -rn ,\n    first=0\n    print -rn -- \"$j\"\n  done\n  print -rn -- \"],\\\"recent\\\":[\"\n  if [[ -r $W/log.jsonl ]]; then\n    print -rn -- \"${(j:,:)${(f)$(grep -E '\"ev\":\"(end|skip|lost|clear)\"' $W/log.jsonl | tail -n ${WORK_RECENT:-8})}}\"\n  fi\n  print -r -- \"]}\"\n}\n\ncase ${1:-} in\n  status)\n    if [[ ${2:-} == --json ]]; then status_json; else\n      print -r -- \"work.zsh: jobs in $W, $(date -Is), load $(load)\"\n      status_human\n    fi\n    exit 0 ;;\n  log)\n    n=${2:-20}\n    [[ -r $W/log.jsonl ]] || { print \"(no work log yet)\"; exit 0 }\n    if (( $+commands[jq] )); then\n      tail -n $n $W/log.jsonl | jq -r '[.t[0:19], .ev, (.kind // .job.kind // \"\"), ((.label // .job.label // \"\") | \"\\\"\\(.)\\\"\"),\n        (if .ev == \"end\" then \"rc=\\(.rc) ran \\(.run_s)s\" + (if .leftover then \", leftover\" else \"\" end)\n         elif .ev == \"start\" then \"waited \\(.wait_s)s, cpus \\(.cpus)\" + (if .busy then \", busy \\(.busy)\" else \"\" end)\n         elif .ev == \"queue\" then \"\\(.checkout | split(\"/\") | last) (\\(.branch)), cpus \\(.cpus)\"\n         elif .ev == \"skip\" then \"not run: busy \\(.busy)\" else \"\" end)] | @tsv' | column -t -s $'\\t'\n    else\n      tail -n $n $W/log.jsonl\n    fi\n    exit 0 ;;\n  bench|fuzz|build) kind=$1; shift ;;\n  *) usage ;;\nesac\n\n# --- a job -------------------------------------------------------------------------------------------------------\ncpus_arg=\ncase ${1:-} in\n  --cpus) (( $# >= 2 )) || usage; cpus_arg=$2; shift 2 ;;\n  --cpus=*) cpus_arg=${1#--cpus=}; shift ;;\nesac\n(( $# >= 2 )) || usage\nlabel=$1\nshift\nif [[ -n $cpus_arg ]]; then\n  cpus_expand $cpus_arg || die \"--cpus $cpus_arg: not a CPU list\"\n  want=(${(nou)reply})\n  for c in $want; do (( ${online[(Ie)$c]} )) || die \"--cpus $cpus_arg: CPU $c isn't online ($(</sys/devices/system/cpu/online))\"; done\nelse\n  want=($online)\nfi\ntypeset -U mine=()\nfor c in $want; do mine+=($ccd_of[$c]); done\nsplit=${WORK_SPLIT:-0}\ncase $kind in\n  bench) (( split )) && locks=($mine) || locks=($all_ccds); mode=-x ;;\n  *)     locks=($mine); mode=-s ;;\nesac\npinned=0; [[ -n $cpus_arg ]] && pinned=1\nmax_busy=${WORK_MAX_BUSY:-5}; [[ $kind == bench ]] || max_busy=off\nwindow=${WORK_BUSY_WINDOW:-5}\nwait_min=${WORK_WAIT_MIN:-30}\n\nid=$(strftime %Y%m%d-%H%M%S $EPOCHSECONDS)-$$\nqueued=$EPOCHSECONDS\ncheckout=$PWD\nbranch=$(git branch --show-current 2>/dev/null)\njs \"$label\"; jlabel=$REPLY\njs \"${(j: :)${(q-)@}}\"; jcmd=$REPLY\njs \"$checkout\"; jcheckout=$REPLY\njs \"$branch\"; jbranch=$REPLY\n\n# the job's own lock first, then its file: a file without a held lock is always a gone job's\nexec {jfd}>$J/$id.lock || exit 1\nflock -x $jfd || exit 1\nstate=waiting started=null\nwrite_job() {\n  local cpus; cpus_compact $want; cpus=$REPLY\n  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 &&\n    mv -f $J/$id.json.tmp $J/$id.json\n}\nlogev() { logev_raw \"{\\\"t\\\":\\\"$(date -Is)\\\",\\\"ts\\\":$EPOCHSECONDS,\\\"ev\\\":\\\"$1\\\",\\\"id\\\":\\\"$id\\\",\\\"kind\\\":\\\"$kind\\\",\\\"label\\\":$jlabel${2:-}}\" }\nwrite_job\ncpus_compact $want\nlogev queue \",\\\"checkout\\\":$jcheckout,\\\"branch\\\":$jbranch,\\\"cpus\\\":\\\"$REPLY\\\",\\\"locks\\\":\\\"${(j:,:)${(@)locks/#/ccd}}\\\",\\\"load\\\":\\\"$(load)\\\",\\\"command\\\":$jcmd\"\n\ndone_logged=0 rc=1\ncleanup() {\n  local still=0 run=0\n  [[ $started != null ]] && run=$(( EPOCHSECONDS - started ))\n  rm -f -- $J/$id.json.tmp\n  # closing our descriptor releases the job's lock unless processes CMD started still hold it\n  exec {jfd}>&-\n  if ! flock -n -x $J/$id.lock true 2>/dev/null; then\n    still=1 state=leftover\n    write_job\n  else\n    rm -f -- $J/$id.json $J/$id.lock\n  fi\n  if (( ! done_logged )); then\n    logev end \",\\\"rc\\\":$rc,\\\"run_s\\\":$run,\\\"load\\\":\\\"$(load)\\\"${${still:#0}:+,\\\"leftover\\\":true}\"\n  fi\n}\ntrap 'cleanup' EXIT\ntrap 'rc=129; exit 129' HUP\ntrap 'rc=130; exit 130' INT\ntrap 'rc=143; exit 143' TERM\n\nannounced=0\nannounce() {\n  (( announced )) && return\n  announced=1\n  print -r -- \"work.zsh: $kind '$label' waits, $(date -Is); the work in $W:\"\n  status_human $id\n}\ntake() {   # take MODE FD WHAT: flock, announcing the wait if it has to\n  flock -n $1 $2 && return 0\n  announce\n  flock $1 $2\n}\n\n# one fuzz job at a time, waited for before the gate, so it doesn't hold the gate while it waits\nif [[ $kind == fuzz ]]; then\n  exec {ffd}>>$W/fuzz || exit 1\n  take -x $ffd || exit 1\nfi\nexec {gfd}>>$W/gate || exit 1\ntake -x $gfd || exit 1\ntypeset -A lfd\nfor d in $locks; do\n  exec {fd}>>$W/ccd$d || exit 1\n  lfd[$d]=$fd\ndone\nif [[ $kind == build ]] && (( split )); then\n  # a build takes the CCDs it finds free, and pins itself to them, if a bench holds the others\n  got=()\n  for d in $locks; do flock -n -s $lfd[$d] && got+=($d); done\n  if (( $#got && $#got < $#locks )); then\n    for d in ${locks:|got}; do fd=$lfd[$d]; exec {fd}>&-; unset \"lfd[$d]\"; done\n    ccd_cpus $got\n    want=(${want:*reply}) locks=($got) pinned=1\n    print -r -- \"work.zsh: build '$label' pinned to CPUs $(cpus_compact $want; print -rn $REPLY): a bench holds the other CCD\"\n  fi\nfi\nfor d in $locks; do take $mode $lfd[$d] || exit 1; done\n# leave the gate, and don't hand it to CMD\nflock -u $gfd\nexec {gfd}>&-\n(( announced )) && print -r -- \"work.zsh: $kind '$label' has its locks, $(date -Is)\"\n\n# a bench waits for quiet CPUs\nbusy=\nif [[ $max_busy != off ]]; then\n  ccd_cpus $locks; quiet=($reply)\n  sample() {   # REPLY = \"mean max\" busy percent of the CPUs in $quiet over $window seconds\n    local -A t0 i0; local -a f; local c dt di sum=0 mx=0 b n=0\n    while read -rA f; do\n      [[ $f[1] == cpu<-> ]] || continue\n      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] ))\n    done < /proc/stat\n    sleep $window\n    while read -rA f; do\n      [[ $f[1] == cpu<-> ]] || continue\n      c=${f[1]#cpu}\n      (( ${quiet[(Ie)$c]} )) || continue\n      (( 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] ))\n      (( b = dt > 0 ? 100.0 * (dt - di) / dt : 0, sum += b, n++ ))\n      (( b > mx )) && mx=$b\n    done < /proc/stat\n    printf -v REPLY '%.1f %.1f' $(( n ? sum / n : 0 )) $mx\n  }\n  deadline=$(( EPOCHSECONDS + wait_min * 60 ))\n  for (( i = 0; ; i++ )); do\n    sample\n    m=${REPLY% *}\n    busy=\"${REPLY% *}% mean, ${REPLY#* }% max\"\n    (( m < max_busy )) && break\n    if (( EPOCHSECONDS >= deadline )); then\n      print -r -- \"work.zsh: bench '$label' not run: CPUs $(cpus_compact $quiet; print -rn $REPLY) still $busy busy after $wait_min min, $(date -Is)\"\n      logev skip \",\\\"busy\\\":\\\"$busy\\\",\\\"load\\\":\\\"$(load)\\\"\"\n      done_logged=1 rc=75\n      exit 75\n    fi\n    (( i == 0 )) && print -r -- \"work.zsh: bench '$label' waits for CPUs $(cpus_compact $quiet; print -rn $REPLY) under $max_busy% busy (now $busy)\"\n  done\nfi\n\nstate=running started=$EPOCHSECONDS\nwrite_job\ncpus_compact $want; cpus=$REPLY\nlogev start \",\\\"wait_s\\\":$(( started - queued )),\\\"cpus\\\":\\\"$cpus\\\",\\\"pinned\\\":$(( pinned )),\\\"load\\\":\\\"$(load)\\\"${busy:+,\\\"busy\\\":\\\"$busy\\\"}\"\nprint -r -- \"work.zsh: $kind '$label' starts on CPUs $cpus, load $(load)${busy:+, busy $busy}\"\npre=()\n(( pinned )) && pre=(taskset -c $cpus)\ncap=0\nif [[ $kind == fuzz ]]; then\n  cap=${WORK_FUZZ_MAX:-150}\n  [[ $cap == <-> ]] || die \"WORK_FUZZ_MAX: $cap\"\n  # `timeout` runs CMD in a process group of its own and signals all of it\n  (( cap > 0 )) && pre=(timeout -k 60 $(( cap * 60 )) $pre)\nfi\n\"${pre[@]}\" \"$@\"\nrc=$?\nif (( cap > 0 && (rc == 124 || rc == 137) && EPOCHSECONDS - started >= cap * 60 )); then\n  print -r -- \"work.zsh: fuzz '$label' stopped after WORK_FUZZ_MAX=$cap min, $(date -Is)\"\n  logev capped \",\\\"max_min\\\":$cap\"\nfi\nprint -r -- \"work.zsh: $kind '$label' done, rc=$rc, $(dur $(( EPOCHSECONDS - started ))), load $(load), $(date -Is)\"\nexit $rc\nbash\n#!/usr/bin/env zsh\n# work-guard.zsh: a Claude Code PreToolUse hook for Bash. In the directories named by WORK_GUARD_ROOTS (colon\n# separated), it refuses a command that runs a heavy cargo subcommand outside work.zsh, and tells the agent how to\n# wrap it. It reads text, not shell: a reminder, not a wall. Anything unexpected lets the call through.\nemulate zsh\nsetopt extended_glob\n(( $+commands[jq] )) || exit 0\ninput=$(cat)\ncmd=$(jq -r '.tool_input.command // empty' <<<$input) || exit 0\ncwd=$(jq -r '.cwd // empty' <<<$input) || exit 0\n[[ -n $cmd ]] || exit 0\n\n# only in the guarded trees\nroots=(${(s.:.)WORK_GUARD_ROOTS:-})\ninside=0\nfor r in $roots; do [[ $cwd == $r || $cwd == $r/* ]] && inside=1; done\n(( inside )) || exit 0\n\n# a command that names the wrapper passes as a whole\n[[ $cmd == *work.zsh* ]] && exit 0\n\nheavy=(build b test t run r bench check c clippy fuzz nextest doc d install rustc miri llvm-cov xtask)\nrunners=(env time nice ionice nohup command exec chrt setsid stdbuf)\nvalued=(--manifest-path -C --config -Z --color --target-dir)\n\n# split into simple commands on && || $( ; | & newlines ( ) { } and backticks\nseps=$'\\n'\nflat=${cmd//(\\&\\&|\\|\\||\\$\\(|[\\;\\|\\&\\(\\)\\{\\}\\`])/$seps}\nfound=\nfor seg in ${(f)flat}; do\n  words=(${=seg})\n  i=1\n  while (( i <= $#words )); do\n    w=$words[i]\n    if [[ $w == [A-Za-z_][A-Za-z0-9_]#=* ]]; then (( i++ ))\n    elif (( ${runners[(Ie)$w]} )); then\n      (( i++ )); while (( i <= $#words )) && [[ $words[i] == -* ]]; do (( i++ )); done\n    elif [[ $w == taskset || $w == timeout ]]; then\n      (( i++ )); while (( i <= $#words )) && [[ $words[i] == -* ]]; do (( i++ )); done\n      (( i++ ))   # the CPU list or the duration\n    else break; fi\n  done\n  (( i <= $#words )) || continue\n  [[ $words[i] == cargo || $words[i] == */cargo ]] || continue\n  j=$(( i + 1 ))\n  while (( j <= $#words )) && [[ $words[j] == [-+]* ]]; do\n    (( ${valued[(Ie)$words[j]]} )) && (( j += 2 )) || (( j++ ))\n  done\n  (( j <= $#words )) && (( ${heavy[(Ie)$words[j]]} )) && { found=$words[j]; break }\ndone\n[[ -n $found ]] || exit 0\n\nreason=\"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.\"\njq -n --arg r \"$reason\" '{hookSpecificOutput: {hookEventName: \"PreToolUse\", permissionDecision: \"deny\", permissionDecisionReason: $r}}'\nexit 0\nbash\n#!/usr/bin/env zsh\n# work-statusline.zsh: a Claude Code status line showing the work lock's jobs, e.g.\n#   work ▶ bench \"parser speed\" 3m12s · … 2 waiting\n# WORK_SH names work.zsh. Prints nothing when no job waits or runs.\nemulate zsh\ncat >/dev/null   # the session's JSON on stdin isn't needed\ns=$(zsh ${WORK_SH:?} status --json 2>/dev/null) || exit 0\njq -r '\n  def dur: if . >= 3600 then \"\\(. / 3600 | floor)h\\(. % 3600 / 60 | floor)m\"\n           elif . >= 60 then \"\\(. / 60 | floor)m\\(. % 60)s\" else \"\\(.)s\" end;\n  .now as $now\n  | [.jobs[] | select(.state == \"running\")] as $run\n  | [.jobs[] | select(.state == \"waiting\")] as $wait\n  | [.jobs[] | select(.state == \"leftover\")] as $left\n  | if (.jobs | length) == 0 then empty else\n      \"work \"\n      + ([$run[] | \"▶ \\(.kind) \\\"\\(.label)\\\" \\($now - .started | dur)\"] | join(\" · \"))\n      + (if ($wait | length) > 0 then \" · … \\($wait | length) waiting\" else \"\" end)\n      + (if ($left | length) > 0 then \" · ! \\($left | length) leftover\" else \"\" end)\n    end' <<<$s\n```\n\nThe plugin's directory:\n\n```\nwork-lock/\n  .claude-plugin/plugin.json\n  hooks/hooks.json\n  hooks/register.tsx\n  types/index.d.ts\n  tsconfig.json          extends the types tsconfig the plugin tooling generates under .claude-plugin/types/\n```\n\n`.claude-plugin/plugin.json`:\n\n```\n{\n  \"name\": \"work-lock\",\n  \"version\": \"0.1.0\",\n  \"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\",\n  \"license\": \"MIT\",\n  \"types\": \"./types/index.d.ts\"\n}\n```\n\n`hooks/hooks.json`:\n\n```\n{ \"modules\": [\"./register.tsx\"] }\n```\n\n`types/index.d.ts`:\n\n```\n// One job of bench/work.zsh, as `work.zsh status --json` lists it (its .work/jobs/ID.json)\nexport type Job = {\n  id: string\n  pid: number\n  kind: 'bench' | 'fuzz' | 'build'\n  label: string\n  state: 'waiting' | 'running' | 'leftover'\n  checkout: string\n  branch: string\n  cpus: string\n  pinned: number\n  locks: string\n  queued: number\n  started: number | null\n  command: string\n}\n\n// One event of .work/log.jsonl: `status --json` lists the last ends (end, skip, lost, clear)\nexport type WorkEvent = {\n  t: string\n  ts: number\n  ev: string\n  id: string\n  kind?: string\n  label?: string\n  rc?: number\n  run_s?: number\n  leftover?: boolean\n  busy?: string\n  job?: Job\n}\n\nexport type Snapshot = { now: number; dir: string; jobs: Job[]; recent: WorkEvent[] }\n\ndeclare module 'claude-code' {\n  interface PluginState {\n    'work-lock': { snap: Shaped<Snapshot | null> }\n  }\n}\n```\n\n`hooks/register.tsx` (set `WORK` and `CHECKOUTS` at the top):\n\n```\n// The work lock (work.zsh) in Claude Code. In a session started in one of the guarded checkouts it\n//   - polls `work.zsh status --json` every 3 s and shows the jobs waiting and running in a band above the prompt,\n//   - opens a pane on /work (again: closes it; also Escape or its Close) with a line a job, running or waiting,\n//     and the last five to end,\n//   - refuses a Bash call that runs a heavy cargo command (build, test, run, clippy, fuzz…) outside work.zsh,\n//     since a bench can't see work that doesn't take the lock.\nimport { atom, read, update } from 'claude-code'\nimport type { Register } from 'claude-code'\n\nimport type { Job, Snapshot, WorkEvent } from '../types'\n\n// --- configure ----------------------------------------------------------------------------------------------------\n// the script, by absolute path, and the checkouts the mod acts in (a session started elsewhere is left alone)\nconst WORK = '/home/you/src/project/tools/work.zsh'\nconst CHECKOUTS = ['/home/you/src/project', '/home/you/src/project-second']\n// -------------------------------------------------------------------------------------------------------------------\n\nconst inCheckout = (dir: string) => CHECKOUTS.some(c => dir === c || dir.startsWith(c + '/'))\nconst PANE = 'work-lock'\nconst POLL_MS = 3000\nconst BAND_ROWS = 4\n// the ends the pane lists, the latest first\nconst RECENT = 5\n\nconst snap = atom({ plugin: 'work-lock', key: 'snap' } as const, null, { shape: 'snap-1' })\n\n// --- the guard ----------------------------------------------------------------------------------------------------\n\n// cargo's subcommands that compile or load every core\nconst HEAVY = new Set([\n  'build', 'b', 'test', 't', 'run', 'r', 'bench', 'check', 'c', 'clippy', 'fuzz', 'nextest', 'doc', 'd',\n  'install', 'rustc', 'miri', 'llvm-cov', 'xtask',\n])\n// words that run the command after them\nconst PREFIX = new Set(['env', 'time', 'nice', 'ionice', 'nohup', 'command', 'exec', 'chrt', 'setsid', 'stdbuf'])\n// cargo's options before the subcommand that take a value\nconst VALUED = new Set(['--manifest-path', '-C', '--config', '-Z', '--color', '--target-dir'])\n\n/** The heavy cargo subcommand a shell command runs outside the work lock, if any. */\nexport function unwrappedCargo(command: string): string | undefined {\n  if (/\\b(work|exclusive)\\.zsh\\b/.test(command)) return undefined\n  for (const segment of command.split(/&&|\\|\\||\\$\\(|[;|&\\n(){}`]/)) {\n    const words = segment.trim().split(/\\s+/).filter(word => word !== '')\n    let i = 0\n    while (i < words.length) {\n      const word = words[i]\n      if (/^[A-Za-z_][A-Za-z0-9_]*=/.test(word)) i += 1\n      else if (PREFIX.has(word)) {\n        i += 1\n        while (i < words.length && words[i].startsWith('-')) i += 1\n      } else if (word === 'taskset' || word === 'timeout') {\n        i += 1\n        while (i < words.length && words[i].startsWith('-')) i += 1\n        i += 1 // the CPU list or mask, the duration\n      } else break\n    }\n    const head = words[i]\n    if (head !== 'cargo' && !head?.endsWith('/cargo')) continue\n    let j = i + 1\n    while (j < words.length && (words[j].startsWith('+') || words[j].startsWith('-'))) {\n      j += VALUED.has(words[j]) ? 2 : 1\n    }\n    const sub = words[j]\n    if (sub !== undefined && HEAVY.has(sub)) return sub\n  }\n  return undefined\n}\n\n// --- drawing ------------------------------------------------------------------------------------------------------\n\nfunction dur(s: number): string {\n  s = Math.max(0, Math.floor(s))\n  if (s >= 3600) return `${Math.floor(s / 3600)}h${String(Math.floor((s % 3600) / 60)).padStart(2, '0')}m`\n  if (s >= 60) return `${Math.floor(s / 60)}m${String(s % 60).padStart(2, '0')}s`\n  return `${s}s`\n}\n\n// the checkout a job came from, by its last path component\nfunction where(checkout: string): string {\n  const home = CHECKOUTS.find(c => checkout === c || checkout.startsWith(c + '/')) ?? checkout\n  return home.split('/').pop() ?? home\n}\n\nconst COLOR = { running: 'success', waiting: 'warning', leftover: 'error' } as const\nconst MARK = { running: '▶', waiting: '…', leftover: '!' } as const\n\nfunction jobText(job: Job, now: number): string {\n  const since = job.started ?? job.queued\n  const state = job.state === 'running' ? '' : `${job.state} `\n  return `${job.kind} \"${job.label}\" ${state}${dur(now - since)} · ${where(job.checkout)} · cpus ${job.cpus}`\n}\n\nfunction eventText(ev: WorkEvent): string {\n  const kind = ev.kind ?? ev.job?.kind ?? ''\n  const label = ev.label ?? ev.job?.label ?? ''\n  const tail =\n    ev.ev === 'end' ? `rc=${ev.rc} ${dur(ev.run_s ?? 0)}${ev.leftover ? ', leftover' : ''}`\n    : ev.ev === 'skip' ? `not run: busy ${ev.busy ?? '?'}`\n    : ev.ev === 'lost' ? 'killed before it ended'\n    : ev.ev === 'clear' ? \"its leftovers ended\"\n    : ''\n  return `${ev.t.slice(11, 16)}  ${ev.ev.padEnd(5)} ${kind.padEnd(5)} \"${label}\"  ${tail}`\n}\n\nconst clip = (text: string, columns: number) =>\n  text.length <= columns ? text : text.slice(0, Math.max(1, columns - 1)) + '…'\n\nexport const register: Register = on => {\n  on('session.start', async ($, e, next) => {\n    const root = await $.session.cwd()\n    if (!inCheckout(root)) return next(e)\n\n    await $.command.register({ name: 'work', description: \"Show the work lock's jobs and the last to end\" })\n\n    let last = ''\n    const poll = async () => {\n      try {\n        const { exitCode, stdout } = await $.process.run(['env', `WORK_RECENT=${RECENT}`, 'zsh', WORK, 'status', '--json'], {\n          timeoutMs: 15000,\n        })\n        if (exitCode !== 0) return\n        const s = JSON.parse(stdout) as Snapshot\n        const key = JSON.stringify([s.jobs, s.recent.at(-1)?.id ?? '', s.recent.length])\n        // while jobs run their times move, so every poll redraws; otherwise only a change does\n        if (s.jobs.length === 0 && key === last) return\n        last = key\n        await update($, snap, () => s)\n      } catch {\n        // the next poll tries again\n      }\n    }\n    await poll()\n    $.clock.every(POLL_MS, () => void poll())\n\n    return next(e)\n  })\n\n  on('command.run', { command: 'work' }, async $ => {\n    if ((await $.ui.panes()).some(pane => pane.id === PANE)) {\n      await $.ui.close({ id: PANE })\n      return { text: 'Work lock pane closed.' }\n    }\n    await $.ui.open({ id: PANE, title: 'Work lock', closeOnEscape: true })\n\n    return { text: 'Work lock pane opened: /work again, Escape or its Close closes it (the full log: work.zsh log).' }\n  })\n\n  on('tool.call', { tool: 'Bash' }, async ($, e, next) => {\n    const root = await $.session.cwd()\n    const sub = inCheckout(root) ? unwrappedCargo(e.command) : undefined\n    if (sub === undefined) return next(e)\n\n    return {\n      deny:\n        `work-lock: \\` cargo ${sub}\\` loads every core, so it runs under the work lock in this checkout: ` +\n        `work.zsh build LABEL <the command> (a timing: work.zsh bench). ` +\n        `A build waits while a bench runs (work.zsh status): run it with run_in_background then.`,\n    }\n  }).catch(($, e, next) => next(e)) // a guard that fails lets the call through: it is a reminder, not a wall\n\n  on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {\n    if (e.props.hasSurvey) return next(e)\n    const s = await read($, snap)\n    if (s === null || s.jobs.length === 0) return next(e)\n\n    const { Box, Text } = $.ui.resolve(e)\n    const columns = Math.max(20, e.props.bodyColumns - 9)\n    const shown = s.jobs.slice(0, BAND_ROWS)\n\n    return (\n      <Box flexDirection=\"column\">\n        {shown.map(job => (\n          <Text>\n            <Text dimColor>work </Text>\n            <Text color={COLOR[job.state]}>{MARK[job.state]} </Text>\n            <Text>{clip(jobText(job, s.now), columns)}</Text>\n          </Text>\n        ))}\n        {s.jobs.length > shown.length && <Text dimColor>work   +{s.jobs.length - shown.length} more: /work</Text>}\n      </Box>\n    )\n  })\n\n  // 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\n  on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {\n    const { Box, Text, Button } = $.ui.resolve(e)\n    const s = await read($, snap)\n    const columns = Math.max(20, e.props.bodyColumns)\n    const close = (\n      <Button role=\"dismiss\" onPress={() => void $.ui.close({ id: PANE })}>\n        Close\n      </Button>\n    )\n    if (s === null) {\n      return (\n        <Box flexDirection=\"column\">\n          <Text dimColor>No word from work.zsh yet.</Text>\n          {close}\n        </Box>\n      )\n    }\n\n    return (\n      <Box flexDirection=\"column\">\n        {s.jobs.length === 0 && <Text dimColor>work   no job waiting or running</Text>}\n        {s.jobs.map(job => (\n          <Text>\n            <Text dimColor>work </Text>\n            <Text color={COLOR[job.state]}>{MARK[job.state]} </Text>\n            <Text>{clip(jobText(job, s.now), columns - 7)}</Text>\n          </Text>\n        ))}\n        {s.jobs\n          .filter(job => job.state === 'leftover')\n          .map(job => (\n            <Text color=\"error\">{clip(`       still held: fuser -v ${s.dir}/jobs/${job.id}.lock`, columns)}</Text>\n          ))}\n        {s.recent\n          .slice(-RECENT)\n          .reverse()\n          .map(ev => (\n            <Text dimColor={ev.ev === 'end' && ev.rc === 0}>{clip(eventText(ev), columns)}</Text>\n          ))}\n        {close}\n      </Box>\n    )\n  })\n}\n```\n\n", "url": "https://wpnews.pro/news/claude-work-lock-queue", "canonical_source": "https://gist.github.com/junkdog/91482c72a67a6243631b1a2aae08942a", "published_at": "2026-12-02 07:19:57+00:00", "updated_at": "2026-12-02 08:45:27.681506+00:00", "lang": "en", "topics": ["ai-agents", "developer-tools", "mlops", "ai-tools"], "entities": ["Claude Code", "ada"], "also_reported_by": [], "takeaway": "Route every heavy command through one flock-based wrapper tagged by kind (bench exclusive, fuzz alongside builds but not other fuzz, build overlapping) so benchmarks never share the machine with compiles, and rely on the kernel's blocking wait instead of polling loops.", "recommendation": {"advice": "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.", "playbook": "production-ops", "playbook_url": "https://wpnews.pro/playbooks/production-ops"}, "alternates": {"html": "https://wpnews.pro/news/claude-work-lock-queue", "markdown": "https://wpnews.pro/news/claude-work-lock-queue.md", "text": "https://wpnews.pro/news/claude-work-lock-queue.txt", "jsonld": "https://wpnews.pro/news/claude-work-lock-queue.jsonld"}}