jig-harness/jig
M12 Parallel-agent ergonomics · in your tools

M12 mappings — per-ecosystem implementations

The module invariant — deterministic per-worktree ports, a cross-worktree heavy-run lock admitted by load, with a CI bypass, branch reuse-before-create, change records of their own assembled after the merge, banned shared-state footguns, gate output shaped for an agent, and a control channel into an unattended agent, and measuring merge-conflict hotspots — is tool-independent. This file maps its mechanisms onto concrete worktree managers / agent runners, package managers, and CI providers. Replace <placeholders> with your values.

The utilities, and where they plug in

The module ships portable scripts for the mechanisms below; the rest is convention. Run the resource-lock script from a pinned Jig checkout, keeping plugin/shared/ at its relative path for the shared lock and process cleanup registry. Point one variable at the module in that checkout and build paths from it, exactly as the other modules do. The change-note commands ship inside the plugin; run them from its installed cache with the consumer repository as the working directory.

UtilityRuns whereSignal it reads
reference/port-allocator/allocate-port.tsworktree-create hook and/or the dev scriptworktree id (arg or WORKTREE_ID), range via PORT_BASE/PORT_SPAN
reference/resource-lock/with-resource-lock.tsaround heavy local gate commands (build, test, e2e)lock via LOCK_NAME/--lock; slots and admission via LOCK_SLOTS, LOCK_STATIC_SLOTS, LOCK_TARGET_UTIL, LOCK_RUN_COST, LOCK_MIN_MEM_GB; the machine to itself via --exclusive; bypass via CI/RESOURCE_LOCK_BYPASS
changelog/scripts/release.tson the integration branch after every merge, one run at a timethe repository’s changelog: configuration (notes directory, changelog, version files)
changelog/scripts/check.tsin the branch gatesthe base’s changelog: configuration, plus --base
reference/quiet-run/quiet-run.tsaround each gate command an agent runs (a test:quiet script, or a runtime hook)--name per part, --tail for the lines a green run shows
reference/worktree-namespace/namespace-for-worktree.tsthe migration or dev command, and the create hookthe worktree’s branch (arg or WORKTREE_ID), --prefix, --max-length
reference/worktree-namespace/find-stale-namespaces.tsthe owner’s reap command, before any dropthe inventory via --inventory, git worktree list --porcelain via --live, --owner, --production (required)

Worktree managers / agent runners — where the hooks wire

The create hook allocates and prints the port slot; the remove hook nudges reflection and parks the worktree’s unsent reflection findings. Both act on the worktree they run in, so each runs inside its worktree. Only the wiring point differs per tool.

ManagerCreate-hook pointRemove-hook pointNotes
plain git worktreea wrapper script/alias around git worktree adda wrapper around git worktree remove that changes into the worktree being removed, runs the remove hook there, and removes the worktree only when it succeedsgit itself has no add/remove hook event; the wrapper is the seam
HerdrJig’s Herdr plugin (tools/herdr/plugin) answers worktree.created by running .config/worktree-hooks/create inside the worktree the event names (data.worktree.path in HERDR_PLUGIN_EVENT_JSON); tools/herdr/workspace.ts open waits for it before starting an agent, and runs it itself where the plugin is not installedtools/herdr/workspace.ts remove resolves the worktree, runs .config/worktree-hooks/remove inside it and parks its reflection findings on the machine that holds it, and removes it through herdr worktree remove only when both succeedHerdr runs a plugin’s commands in the plugin’s own directory, so a create hook that read its working directory would give every worktree the same identity and port slot; worktree.removed fires after the checkout is gone, so it can only notify, never park
Orcathe Orca workspace tool’s open (the launcher’s orca provider) runs .config/worktree-hooks/create inside the new worktree once its branch is named, before the agent starts, and marks the run in the worktree’s git directory so it runs once; a worktree created in the Orca app runs Orca’s own setup hook instead (Settings → Repository, or scripts.setup in the repository’s orca.yaml), which can name the same filetools/orca/workspace.ts remove runs .config/worktree-hooks/remove inside the worktree, parks its reflection findings when the clone is on this machine, and removes it through orca worktree rm only when both succeed; Orca’s own delete runs an orca.yaml archive hook only when asked (--run-hooks) and has no other pre-remove pointOrca names a new branch after the worktree under its own prefix, so the tool renames it before the hook runs; Orca reads the branch from git and follows
Worktrunka blocking pre-start hook in the repository’s .config/wt.toml (pre-start = ".config/worktree-hooks/create"); Worktrunk runs it inside the new worktree, before any post-start hook runsa blocking pre-remove hook (pre-remove = ".config/worktree-hooks/remove") runs inside the worktree being removed, before it is deleted; its failure aborts the removal, so unsent reflection findings are parked or the worktree stays, provided the hook ranWorktrunk asks before it first runs a repository’s project hooks, and again when one changes; declining skips every project command for the operation and the removal continues, so the hook must be approved before the first removal and after each change to it, because a refusal is not a removal veto and deletes the git directory holding unsent findings; post-remove runs in the primary worktree after the checkout is gone, so it can only notify, never park
T3 Code — watcheda script in the repository’s t3.json with "runOnWorktreeCreate": true and "command": ".config/worktree-hooks/create"; T3 Code runs it inside the new worktree (with T3CODE_PROJECT_ROOT and T3CODE_WORKTREE_PATH set), which a thread has only when it runs in a worktree (the New worktree mode in the app, or t3 thread start --worktree), once the script is imported into the project’s actions (Settings → Projects → Actions), and "async": false holds the agent until the hook exitsnone: T3 Code offers no point before a worktree is removed, so a wrapper runs .config/worktree-hooks/remove inside the worktree, parks its unsent reflection findings, and removes it only when both succeed (the repository writes that wrapper, as for plain git worktree); set the project’s automatic worktree cleanup to Off, since a cleanup policy removes worktrees without the hookT3 Code runs a t3.json script only once someone imports it on each T3 Code server that opens the project, so the file is the shared declaration and the import a step each server takes; a runOnSettle script runs each time a thread is settled (moved to the finished shelf, by a person or automatically), not before a removal, and cannot veto one; worktrees isolate files, not ports or databases: the create hook’s port slot covers ports, and a per-worktree data namespace covers databases; Jig ships no T3 Code provider, and its revisit conditions are assessed below
Rex — watchedno worktree concept: a wrapper would create the worktree, run its create hook inside it, then open a Rex session in ita wrapper would run the remove hook inside the worktree, park its unsent reflection findings, and remove it only when both succeedJig ships no Rex provider; its program status and provider revisit conditions are assessed below
another workspace runtime (such as Conductor)the runtime’s post-create / workspace-setup hookthe runtime’s pre-remove / teardown hookthe runtime already brackets a session — the natural home for both
direnv / per-directory env.envrc calls allocate-port.ts on entry and exports PORTnone (no teardown event)derived ports mean no cleanup is needed
tmux / shell session per worktreeshell rc sources a per-worktree env filea shell EXIT trap prints the reflection nudgelightweight; good when there is no formal manager

Because ports are derived, the create hook is convenience, not correctness: any dev script can call allocate-port.ts directly and get the identical port without a hook having fired.

Rex: conditions for reconsidering a provider

Assessment dated 2026-11-11: Rex is a candidate workspace runtime, with no supported Jig integration. Its command line offers machine-readable output, stable identifiers, waiting, capture, input and events; its server API describes its own methods. These are useful seams for running an agent in a worktree a wrapper owns.

Reconsider a provider when each prerequisite can be checked:

  • A stable release is available; Rex is currently in beta.
  • A Linux or iOS client is in testing. The installation guide currently limits client testing to macOS; Linux availability is server-only.
  • A published licence or an open-source core establishes the terms for use.
  • Authentication goes beyond trusting how a caller reaches the server. The remote-access guide currently relies on Tailscale identity or a private connection such as an SSH socket forward while fuller authentication is planned.

The first integration would be a workspace provider for the launcher. The dispatcher’s session runtime would follow only once Jig supplies the subscription-account binding itself: Rex’s operating-system accounts do not provide the subscription-account roster and session binding the dispatcher needs (ADR-0011).

Also revisit reading program status as the agent’s reported state when a supported runtime exposes it: in sessions and in steer’s check that the agent still waits before sending an answer. Rex exposes status records through the terminal block’s program_status method (Lua API), reachable through block.method in its server API.

T3 Code: conditions for reconsidering a provider

Assessment dated 2026-11-18: T3 Code (MIT licence, pingdotgg/t3code) is a candidate workspace runtime, with no supported Jig integration beyond the worktree hooks above. It is a server that runs Claude Code, Codex, Cursor, OpenCode and other agents in threads, with web, desktop and phone clients. What it offers Jig’s tooling today:

  • A seam for a workspace provider: a thread can open in a worktree of its own, and the repository’s t3.json script runs the create hook there. Isolation is optional: t3 thread start runs in the project folder unless it is given --worktree <base-branch>, so a launcher would pass that flag, or parallel agents share one checkout and no create hook runs.
  • MCP thread tools for agents it did not start (t3_thread_launch, t3_thread_wait, t3_thread_read, t3_thread_list), and the same tools on the host as t3 thread start, send, show and list (outside agents).
  • A provider instance per subscription account: each Claude instance names its own CLAUDE_CONFIG_DIR (Claude provider).
  • A headless server, t3 serve, or t3 up as a background service (remote access).

Reconsider a provider when each prerequisite can be checked:

  • A stable release is available; T3 Code is at 0.1.x, with nightly prereleases.
  • It offers a hook before a worktree is removed, so the remove hook can park reflection findings without a wrapper and cleanup policies cannot bypass it.
  • Usage per subscription account is readable by a program. Its Usage → Limits view shows per-account quotas, refill windows and the provider’s reset times, which the dispatcher’s wall needs, but its documentation names no command or API that returns them, only the application’s own views and the /usage-limits composer command.
  • Jig’s plugin skills and hooks are confirmed to load in its threads, under each provider instance’s configuration directory.

The first integration would be a workspace provider for the launcher. The dispatcher’s session runtime would follow once its account usage is readable and the dispatcher’s subscription-account binding (ADR-0011) can map onto its provider instances.

Package managers — the wrong-root-install footgun

The footgun ban “no root install with the wrong package manager” is concrete per ecosystem: each manager owns a lockfile that a foreign install rewrites, breaking every sibling worktree that shares it. Detect the declared manager (derive from the lockfile present) and reject the others.

EcosystemDeclared by (lockfile)The wrong-root-install that bitesMechanizable check
Nodepnpm-lock.yaml / package-lock.json / yarn.lock / bun.lockbrunning a different manager’s install at the root rewrites/duplicates the lockfilea hook asserting the lockfile matches the declared manager before install
Pythonpoetry.lock / uv.lock / Pipfile.locka bare pip install into the shared env instead of the project’spre-commit / setup check that the project manager is used
RustCargo.lockhand-editing or a divergent cargo update at the rootreview + lockfile-drift gate
Gogo.sumgo get bumping shared module state mid-sessiongo mod verify in a gate

The general rule: derive the package manager from the repo (don’t declare it) and treat any other manager’s root install as the banned action.

Reading the host’s load, per platform

The lock admits a run beyond the first only while the machine has room for one more. What the reading rests on differs by platform:

PlatformLoadAvailable memoryEffect
Linuxthe one-minute load averageMemAvailable from /proc/meminfoload and memory both decide
macOSthe one-minute load averagenone: the system reports only its free pages, which count reclaimable caches as usedload and the slot ceiling decide
Windowsnone (the platform keeps no load average)the free memory the system reportsmemory and the slot ceiling decide

Set LOCK_RUN_COST to the parallelism of the command the lock guards (a test runner’s worker count, a build’s job count), so a run just started counts at what it will add. A lock that guards a resource only one user may have at a time (a fixed port, a shared database), rather than the machine’s capacity, keeps LOCK_SLOTS=1: a plain mutex.

CI providers — why (and how) the lock bypasses

A CI runner already gives each job its own isolated machine, so the cross-worktree lock has nothing to bound there and the wait would be pure added latency. with-resource-lock.ts therefore runs the command unlocked when it sees a CI signal. Most providers set CI=true automatically, so the bypass is usually zero-config; the column below is the signal to rely on (or set RESOURCE_LOCK_BYPASS=1 explicitly).

ProviderAuto-set signalNote
GitHub ActionsCI=truealso GITHUB_ACTIONS=true; the default CI is enough
GitLab CICI=truealso GITLAB_CI=true
BuildkiteCI=trueone agent per job — already isolated
JenkinsCI not guaranteedset RESOURCE_LOCK_BYPASS=1 (or CI=1) in the job env

Locally, leave heavy commands wrapped:

sh
LOCK_RUN_COST=4 bun with-resource-lock.ts --lock test -- pnpm test   # admitted by the machine's load

In CI, run them unwrapped or wrapped — either way the bypass makes them run immediately:

yaml
# GitHub Actions — CI=true is already set, so even a wrapped command runs at once
- run: pnpm test

The lock is the same mechanism M1 points to for heavy pre-push gates; a repo that adopts both wraps its heavy gate once and gets the cross-worktree bound locally and the isolation-based bypass in CI for free.

Per-worktree data namespaces

The name comes from reference/worktree-namespace/; the create writes the owner and the expiry beside it; the reaper reads them back into the decision script’s inventory and drops what it lists, after the report. The drop decides each name again under a per-name lock the create also holds, from a fresh census, because a worktree can come back on the same branch between the report and the drop (the reference’s drop step). The same shape on every database: only the commands differ.

DatabaseCreate, with owner and expiryInventory for the reaperDrop
PostgreSQLCREATE SCHEMA "$NS"; COMMENT ON SCHEMA "$NS" IS '{"owner":"$USER","expires_at":"<ISO 8601>"}'; the migration runner sets search_path to the namespace, and production (the public schema, no prefix) needs an explicit opt-in flagSELECT jsonb_agg(jsonb_build_object('name', n.nspname) || coalesce(obj_description(n.oid, 'pg_namespace')::jsonb, '{}'::jsonb)) FROM pg_namespace nDROP SCHEMA "$NS" CASCADE
MySQL / MariaDBCREATE DATABASE $NS; owner and expiry in a worktree_namespaces table, since a database carries no commentSELECT name, owner, expires_at FROM worktree_namespaces joined with SHOW DATABASESDROP DATABASE $NS
MongoDBa database per worktree, owner and expiry as a document in a namespaces collection of an admin databasethat collection, joined with listDatabasesdb.dropDatabase() on the namespace
A branching database host (Neon, PlanetScale)a branch per worktree, named by the script, with the host’s expiry or a tag for owner and expirythe host’s branch listthe host’s delete-branch call
SQLitea file per worktree under a gitignored directory, owner and expiry in a sidecar .jsonthe directory listingdelete the file and its sidecar
Redis / Valkeya key prefix per worktree rather than a database; owner and expiry in a hash under the prefixSCAN by the prefix, reading the hashUNLINK the keys under the prefix

A production target is refused in the migration runner (the empty prefix needs an explicit flag), in the reaper (--production <name> is never a candidate), and wherever the drop runs, so no single mistake reaches it.

Control channels

The invariant: an unattended agent is reached through a closed set of directives that code enforces and that fail closed, plus notes that only advise. The mechanisms an agent runner already has cover part of that; the table says which part.

MechanismBinding directivesAdvisory notesFails closedNote
drive-pr’s drive mailboxhold-push, pause, stop, each with its resumeyes, read by choice with mailbox.ts checkyes: an unreadable inbox or directive holds the push and stops the loopthe reference; two append-only files under the worktree’s .context/drive-mailbox/
A process signal (SIGKILL)termination only, immediately rather than at a safe pointnonot applicablethe hard kill the channel exists to avoid needing
A runner’s message to a running subagent (Claude Code’s SendMessage)none: the message enters the agent’s context, and the agent decidesyesnosuits a subagent in the same session; give it nothing it must obey
Typing into the agent’s terminal (tmux send-keys)noneyes, but as if the person typed itnofree text with the force of a person’s instruction, which is what keeping notes advisory prevents

A runner’s own messaging covers the notes; the directives need code at the agent’s checkpoints, whichever runner starts it.

The reference’s layout: two append-only files in the worktree’s scratch directory (.context/drive-mailbox/), an inbox any sender appends to and an outbox only the agent writes, recording what it has read and answered. Each append takes a lock, so concurrent senders never interleave a line. A hold sent while the push’s own pre-push hooks run lands after the push’s first check; running push-hold-recheck.ts as the last pre-push hook command closes that window (drive-pr README § Push hold).

Change notes — per ecosystem

The invariant: no pull request edits a file every pull request edits. Each change adds a note of its own, and one run at a time on the integration branch writes the notes into the changelog and moves the version. The tools that do it (the plugin’s changelog skill, Changesets, towncrier, scriv, changie), the ones that generate the changelog from commits instead, and how the release reaches a protected branch are in M16’s mappings, with the rest of the release practice.

One neighbouring approach removes the conflicts without notes, and is not enough: a union merge driver (CHANGELOG.md merge=union in .gitattributes) lets git keep both sides of a local merge, but places lines without knowing the changelog’s sections, does nothing for the version, and GitHub’s mergeability check does not use it: the pull request still shows as conflicting.

Agent-facing gate output

The invariant: a gate speaks to an agent in a condensed voice on green and in full on red, keeps its own exit status, and prints one verdict line per part. Two seams carry it: the runner’s own flags, and a wrapper the repository or the agent runtime applies. The wrapper is reference/quiet-run/; the flags below condense less than it does, but cost nothing to adopt.

Runner flags

RunnerQuieter on greenOn redTrap
go test (no -v)one ok / FAIL line per package: the verdict-per-part shape, built ina failing package prints its output in full-v turns every test into a line again
pytest-q (or -qq), --tb=shortfailures keep their tracebackan argument that matches nothing must fail the run, not report that no tests ran: the wrapper’s shell sets its no-match option (failglob) for that reason
vitest--reporter=dotfailures print in full under every reporter--silent drops the tests’ own console output, which is often the diagnostic
Jest--reporters=summarythe same--silent, the same
bun testno condensing flag: wrap it——
cargo test-qfailures print in full—
Biome--reporter=summarythe summary lists each failing rule—
ESLint——--quiet hides warnings, not success noise: with a ratchet counting warnings (M1) it hides what the ratchet counts
tscprints nothing on success alreadyerrors only—
Turborepo--output-logs=errors-only: a task’s log only when it failsthe failing tasks’ logswithout --continue, the first failure stops the rest, and their missing verdicts mean did not run; with it, every part runs and gets its line

The pipe trap

bun test | tail -n 30 exits with tail’s status, so the suite’s failure is gone before anything reads it. set -o pipefail keeps the failing status in bash and zsh, but it is off by default and a hook’s shell is not always the agent’s; the wrapper captures the status from the command itself and needs no shell option.

Agent-runtime hooks

A runtime that can rewrite a command before it runs applies the wrapper automatically; where it cannot, the quiet package script named in the instruction file is the seam, and the agent runs it by convention.

RuntimeSeamContract
Claude Codea PreToolUse hook on the Bash toolreads the tool call as JSON on standard input (tool_input.command), replies with hookSpecificOutput.updatedInput.command holding the rewritten command; it must not reply with a permission decision, since a rewrite is not a review of the command, and the rewritten call goes through the normal permission flow
any runtimethe quiet script (test:quiet, lint:quiet) the instruction file namesthe agent runs it by convention; no rewrite

The hook’s safety model fails towards showing more, never towards hiding a failure:

  • it rewrites only a command that, trimmed, is a plain invocation of a known runner (an allowlist of exact prefixes, each followed by a space or the end), and the check for shell punctuation runs before the prefix match, so a rewrite can never start a second command;
  • anything with a pipe, a redirect, a subshell, a quote, a newline or a background run passes through untouched, and so does an inspection flag (--help, a dry run, a collection-only run, a coverage or durations report, a watch or debugger mode): those outputs are the payload, and a tail of them would be wrong, not merely short;
  • the rewritten command captures the exit status from the runner itself and bounds what it captures;
  • a cancellation prints what was captured before re-raising the signal, so a run killed by the tool’s own timeout leaves its diagnostics behind;
  • the shell the wrapper hands the command to fails an argument that matches nothing (failglob), so a mistyped test path cannot pass as “no tests ran”.

Measuring merge conflicts

The invariant: a repository working in parallel measures where its merges conflict, and each hotspot is removed at its cause or kept by a recorded decision. This works across ecosystems because the evidence is in git.

Run the plugin command from its installed cache, with the repository as the working directory (<skill-dir> is the installed resolve-conflicts skill):

sh
bun <skill-dir>/scripts/history.ts --days 30 --json > <scratch>/merge-conflicts.json
SourceWhat it observesLimit to retain with the report
git replay (history.ts)reachable merge commits, their conflicted paths and region causes; the Conflicts resolved: commit section adds decisions and reasonsrequires git 2.43 or later (2.45 in a partial clone); never fetches; shallow boundaries can hide merges; squashed branches and rebase stops may leave no replayable merge
clone-local live record (resolve-conflicts)resolutions of merges, rebases, cherry-picks and reverts, including time and whether drive-pr started themevents live in git’s common directory and cover this clone only; no event does not mean no conflict
the repository’s M11 event pipelinethe same conflict events sent through its own emittercoverage depends on where that emitter runs; see M11

The replay does not read the live record. The replay JSON schema is merge-conflicts/v1. Keep the window, scope, skipped merges and cause-accuracy statement with the path rankings. The threshold is resolve_conflicts.hotspot_min_merges (default 3). Choose a remedy from the reported cause: derive counts, move release versions after the merge, or keep entries in separate files; an overlapping change still needs a decision about the work itself. Record the hotspot’s cause, remedy or keep decision, reason and revisit condition in the repository’s learning loop. With Jig’s reflection on, bun <skill-dir>/../reflect/scripts/reflect.ts hotspots <scratch>/merge-conflicts.json notes each hotspot as a reflection finding whose class is its cause; the reflection’s escalation and review then record the remedy, or a keep decision: a dismissal whose reason says the cause is kept on purpose and names the condition for revisiting it. Compare like windows after the change rather than treating an empty or partial report as proof that the cause is gone.

Machine resource collection schedules

The invariant is a daily report and a weekly collection, with explicit executable paths and environment. The installed plugin copy owns the command; a worktree checkout cannot host a job that may remove that checkout. jig install gc previews the repository bounds and installs on confirmation (--yes); the first install, before the plugin’s jig command is on PATH, runs from the installed copy as bun --no-env-file --config=<plugin>/gc/bunfig.toml <plugin>/jig.ts install. See the command for its configuration, proof requirements and rollout limits.

Platform schedulerInstalled file or entryCadenceSee the last runRemove
macOS launchd~/Library/LaunchAgents/dev.jig.gc.plistStartCalendarInterval.Hour, from machine gc.hourjig status gc; launchctl print gui/<uid>/dev.jig.gc; collection receiptsjig uninstall gc --machine --yes
Linux systemd user timer~/.config/systemd/user/jig-gc.service and jig-gc.timerOnCalendar, from machine gc.hourjig status gc; systemctl --user status jig-gc.timer; journalctl --user -u jig-gc.service; receiptsjig uninstall gc --machine --yes
cron fallbackCurrent user’s crontab, marked # jig-gcDaily hour field from machine gc.hourjig status gc; collection receipts; scheduler’s own mail or logsjig uninstall gc --machine --yes

The command chooses collection on machine gc.collect_day or under gc.min_free_bytes pressure; other daily runs report. Removing one repository keeps the job while another repository or machine-level kind remains.

Worktree collection through a workspace runtime: Orca is the runtime supported so far. It applies on a machine whose gc.orca.command names Orca; the runtime’s agent registry stands in for the opener’s lock, an agent that has not finished or an unreadable registry keeps the worktree, and the removal goes through Orca. See the Orca binding.

Source: modules/M12-parallel-agent-ergonomics/mappings.md