trk
A local issue tracker and agent launcher in one Rust binary. Each project has its own SQLite
database in .trk/; humans use the CLI, agents work through a per-issue MCP server, and trk run [ID] starts
an agent session on one issue through a named launcher profile (Herdr, hc, or tmux). See Design and state machine for the model.
An issue has a title, a description, notes, a priority, a required type (from [issues] default_type, initially code-change), and one of four states:
open → claimed → closed
→ waiting → closed its check passed, or a human closed it
→ claimed failed check, human CLI resume, or eligible same-session chat resume
→ open no live session, wake delivery failed, or a human reopened it
A session ends by closing the issue or leaving it waiting: the work is done once something
outside the session happens (a merge, a review, a decision). A waiting issue may carry a shell
command; trk check runs those commands until each one passes, fails, or says “not yet”.
Quick start
cd ~/src/orch && trk install # .trk/ with the database and config; ids are orch-…
trk create "Add claim leases" -d "Crashed agents must release their claims." -p P1
trk create "Enable leases in prod" --blocked-by orch-4kq
trk ready # open, with every blocker closed
trk claim orch-4kq # open → claimed; records the worktree
trk note orch-4kq "Sweep runs at the start of every write"
trk close orch-4kq -m "Merged in 9f2c1e0" # or leave it waiting, below
trk log orch-4kq
Use trk create "Fix the bug" -d "Reproduction details" --run to create an issue and
immediately launch its agent, equivalent to trk run <new-ID> with default routing
and launcher settings. It returns the run result (JSON data.issue is the new ID).
--run cannot be combined with --dry-run. If launching fails, the issue stays saved;
the error identifies it so you can fix the cause and retry with trk run <ID>.
Every command takes --json (or --format pretty|json|jsonl). Scripts should always pass --json;
JSON output is the versioned API (schema_version: 4), and errors use the same envelope with a
stable code, a hint, and exit codes 1–5.
Pretty output colors priorities consistently (P0 red, P1 yellow, P2 cyan, P3 dim) and states
(open green, claimed yellow, waiting cyan, closed dim green). Full issue details (trk show and
other commands displaying an issue) use bold cyan IDs and section headings, green ready indicators,
and yellow blocked and check-due indicators. Metadata, timestamps, and field labels
are dimmed; description and note bodies retain their existing rendering. Labels and state glyphs
remain present without color. ANSI styling is enabled only for pretty output on a terminal;
NO_COLOR or --no-color disables it, and piped output is unstyled. JSON and JSONL output never
contain ANSI styling.
Queries and saved views
trk list QUERY and trk ready QUERY query the current project’s database, not
other projects. ready adds the readiness filter to the same query language.
Quote the query so your shell does not interpret operators, spaces, or globs.
trk list 'state!=closed'
trk ready 'priority<=P1'
trk list 'state in (open,claimed) type=code-change'
trk list 'claimed-by=me'
trk list 'claimed-by=agent:*'
trk list 'blocks=orch-m1 state!=closed'
trk list 'closed>-7d reason=done'
trk list 'text~"feature flag"'
Syntax
Terms are joined by implicit AND. Prefix a term with NOT or ! to negate it.
Use name in (a,b,c) to match any listed value for one field; there is no general
OR operator or grouping syntax.
name=value name!=value name<value name<=value name>value name>=value
name~value
name in (a,b,c)
NOT term !term
ready blocked due stale-lease
| Field | Meaning |
|---|---|
id, title, state, priority, type, reason | Issue ID, authored fields, state, or close reason (done, abandoned) |
claimed-by, created-by | Claimant or creator actor |
created, updated, closed, next-check | Timestamps |
text | Full-text search over titles, descriptions, and notes |
blocks, blocked-by | Issues on either side of a dependency edge |
| Flag | Matches |
|---|---|
ready | Open issues with every blocker closed |
blocked | Nonclosed issues with at least one nonclosed blocker |
due | Waiting issues with a check due now |
stale-lease | Claims whose lease has expired; reading does not sweep them |
Values can be words or quoted strings. Unquoted me resolves to the acting actor.
Times accept now, relative durations such as -7d, -12h, and +30m, dates
such as 2026-11-01 (midnight UTC), or RFC 3339 timestamps.
For ordinary text fields, = and != accept SQLite globs (*, ?, [...]),
and ~ matches a glob or, without glob characters, a substring. For text, use
text~"feature flag" for a full-text phrase. Dependency fields resolve issue IDs,
including unique suffixes, rather than matching arbitrary strings.
Output and ordering
Both commands default to priority, then oldest creation time, then ID.
--sort accepts comma-separated keys; prefix a key with - for descending order.
Keys are id, state, title, priority, type, created, updated, closed,
claimed-by, lease, and next-check. ID breaks remaining ties.
trk list 'state=waiting' --sort next-check
trk list 'state!=closed' --sort priority,-updated --limit 20
trk ready --fields id,priority,type,title --json
--fields chooses pretty-table columns or JSON object keys. --limit caps the
number of issues. See JSON API and errors for output formats.
Saved views
Define named views in project or user config.toml:
[views.mine]
query = "claimed-by=me"
[views.waiting]
query = "state=waiting"
fields = ["id", "priority", "waiting", "next-check", "title"]
sort = "next-check"
Run trk list @mine or trk list '@waiting priority<=P1'. Extra terms narrow the
view; explicit --fields, --sort, and --limit override its defaults. Settings
follow the normal configuration layers.
Installation and upgrades
Install and upgrade
Beta compatibility
trk is beta. The JSON envelope, identified by schema_version, and its error codes
are intended to be stable, as are the MCP tool names. Treat schema_version as
the JSON API version, not the application version or the SQLite schema version.
Config keys, seed prompts, the database schema across trk versions, and the Herdr
mod may change without notice. Keep backups of .trk/ before upgrading; do not
assume an older binary can open a database migrated by a newer one.
See the changelog for release changes and the release steps for version and tag details.
Installation
./install.sh
This builds a release binary and installs it to ~/.cargo/bin/trk. It also refreshes
the Herdr mod if already installed.
trk keeps no global database; an optional user configuration can be shared across projects.
Set up each project:
cd ~/src/orch && trk install
trk install creates .trk/ in the project root (by default, the primary git checkout
root): the database, the default config with every setting written out, and a .gitignore
that keeps all of it out of git. To install a project in a monorepo subdirectory, run
trk --dir .trk install from that subdirectory. It also installs the agent skill (see below).
Commands find the project from its subdirectories and corresponding paths in git worktrees.
Other project commands fail with not_installed until it has been installed.
Choose the configuration seed with these install options:
trk install --list-presets # local and github; no installation or writes
trk install --preset local # implicit default: land locally by verified merge
trk install --preset github # open a GitHub PR and wait for its merge
trk install --from /path/to/team-seed # use only this directory's files, recursively
trk install --minimal # project settings only; inherit shared user resources
The built-in seed/ directory is embedded recursively at build time, so adding or changing
a seed file is picked up by the next build without maintaining a file list. Common files
(config.toml, prompts/_rules.md.j2, and prompts/briefing.md.j2) live at the seed root;
default_type.txt supplies the built-in fallback but is not installed.
Both presets install the same implementer, researcher and operator agents and the
change, bug, research and ops types, plus their shared instruction prompts
and both landing recipes. change is the default and uses an implementer
worktree; bug uses the same agent/worktree with guidance to reproduce first,
record the root cause in a note, and add a regression test. research uses the
researcher without a worktree. ops uses the operator without a worktree for
running-service operations; it has no type guidance or landing recipe. Its
instructions require before/after evidence, notes before state-changing commands,
and direct in-session approval for destructive or irreversible actions, not wait.
Repository fixes become follow-up change issues. The operator has full shell
access and a commented MCP example for project cloud/observability extensions,
with none enabled by default. It closes with the operation’s outcome and record.
The installer also supplies the built-in .gitignore.
Preset landing.txt metadata selects merge for local or pr for github and
is not installed. A preset’s files replace common files at matching paths.
local has no review or approval gate: [check] verify is its sole verification
gate, and an empty value skips verification, not the merge. Set it explicitly for
your project. github requires GitHub CLI (gh) installed and authenticated;
installation warns when gh is missing. Authenticate with gh auth login before use.
--from DIR instead copies a fully resolved install layout directly into .trk/, including
nested and binary files, with no built-in fallback or preset selection. Only regular files
and directories are accepted; symlinks and special entries are rejected. Supply your own
.gitignore if wanted. A presets/ directory inside a custom source is ordinary content.
--from, --preset, and --minimal cannot be combined.
--minimal is unchanged: it writes no agents, types, or prompts and relies on the user layer.
--list-presets cannot be combined with install modifiers. Listing works outside a project;
its JSON data is {"presets":["github","local"]}.
Only config.toml substitutes install-time markers: {{EMAIL_LINE}} becomes the human email
setting (or a commented example), {{PREFIX}} becomes --prefix or the detected project
prefix, {{DEFAULT_TYPE}} becomes the built-in default issue type, and {{BASE}} becomes
the TOML-quoted detected base branch. The unquoted {{LANDING}} marker becomes the
TOML-quoted landing value selected by the preset; --from defaults it to "merge".
Other files are copied unchanged, including template markers.
Upgrading existing projects
Finish active sessions and back up .trk/ before upgrading. After changing or pulling
this checkout, run ./install.sh again, then select trk install --preset local or
trk install --preset github in each project (or retain its custom --from or
shared-config --minimal installation). trk does not remember the selection.
Installation applies schema migrations, refreshes the agent skill, adds missing files,
keeps existing configuration files, and lists files that differ from the seed.
For config.toml, only harness-profile differences count as drift, not project identity
or formatting. --force rewrites supplied files but still does not prune other files.
To adopt the new built-in types and landing workflow:
- Install the chosen preset to add
types/change.tomland the other missing resources. Existingcode-change,review, andreviewerdefinitions/prompts and existing issues are preserved; installation does not rename issue types. - After
types/change.tomlexists, manually set[issues] default_type = "change"in.trk/config.toml. Existingdefault_typeis kept until you change it. - Manually choose
[run] landing = "merge"for local or"pr"for GitHub, since the existing config is kept. Set[check] verifyto the desired local verification command; an empty value skips verification and there is no local approval gate. - Keep legacy definitions until their issues are migrated with
trk edit <ID> --type changeor an appropriate custom equivalent. Consider blocker dependencies and any review obligations before changing types; migration does not remove those dependencies. Remove legacy reviewer/review prompts and agents only when no remaining types, issues, or templates use them.
This repository’s own .trk/ is existing, untracked project state: use the same
procedure locally rather than editing it as part of a source upgrade.
trk --version prints the package version and build commit, for example
trk 0.1.0 (<commit>); see release steps.
Running agent sessions keep the binary they started with.
Active sessions during upgrades
Finish active sessions before a schema-changing upgrade. Running MCP servers keep the binary they started with; replacing the executable does not upgrade them.
If an older server encounters a newer schema, it returns newer_database with the database
path, database_version (SQLite user_version) and supported_version. These are not the
JSON envelope’s schema_version. The database is not downgraded or reset.
Preserve uncommitted work and handoff text, install a compatible trk, and restart the
harness’s MCP connection with that executable and the original project directory, issue
and actor. Call get_task after reconnecting. Restarting does not claim an issue or bypass
dependency/ownership checks; if the claim has expired, preserve the handoff for the human.
Waiting, checks, and resume
Waiting and trk check
# Merge your branch only after verifying the merged result in the issue worktree.
local_check=$(cat <<'CHECK'
cd "$TRK_WORKTREE" || exit 1
git merge --no-edit "$TRK_BASE" || { git merge --abort 2>/dev/null; exit 1; }
if [ -n "$TRK_VERIFY" ]; then
sh -c "$TRK_VERIFY" || exit 1
fi
cd "$TRK_REPO" || exit 1
[ "$(git branch --show-current)" = "$TRK_BASE" ] || exit 1
git merge --ff-only "$TRK_BRANCH" || exit 1
CHECK
)
trk wait orch-4kq -r "verify and merge into base branch" -c "$local_check"
# Done once the PR is merged; wake for conflicts or failed head-commit CI.
# gh's built-in jq filter reads the head commit's check runs and statuses.
pr_check=$(cat <<'CHECK'
result=$(gh pr view 12 --json state,baseRefName,mergeable,headRefOid,statusCheckRollup --jq '
if .state == "MERGED" then "merged"
elif .state == "CLOSED" then "PR closed without merging"
elif .mergeable == "CONFLICTING" then "PR conflicts with base branch \(.baseRefName)"
else
.headRefOid as $head |
[.statusCheckRollup[]? |
select(
(.__typename == "CheckRun" and .status == "COMPLETED" and
(.conclusion | IN("FAILURE", "TIMED_OUT", "CANCELLED", "ACTION_REQUIRED", "STARTUP_FAILURE", "STALE"))) or
(.__typename == "StatusContext" and (.state | IN("FAILURE", "ERROR")))
) |
"\(.name // .context): \(.conclusion // .state) \(.detailsUrl // .targetUrl // "")"
] |
if length > 0 then "CI failed on head \($head):\n" + join("\n")
else "waiting" end
end
') || exit "$?"
case "$result" in
merged) exit 0 ;;
waiting) exit 75 ;;
*) printf "%s\n" "$result"; exit 1 ;;
esac
CHECK
)
trk wait orch-4kq -r "PR 12 merged" --every 10m -c "$pr_check"
# Waiting on a person: no check. A human can close, resume the live session, or reopen.
trk wait orch-4kq -r "SQLite or Dolt?"
trk check # run the checks that are due, one at a time
trk check --watch # keep doing that; leave it running in a spare terminal
trk check orch-4kq # run one now
trk check --dry-run # preview checks and eligible cleanup without changing anything
trk check --no-gc # run checks without automatic cleanup (also works with --watch)
trk list state=waiting # what is waiting, on what, and when it is checked next
Human-readable check output, including --watch, uses cyan issue IDs and activity/waiting
labels, green successes, yellow warnings/skips, and red failures. Status text and glyphs
remain visible without color. Styling follows the CLI’s terminal detection: NO_COLOR
(even empty), --no-color, or redirected stdout disables it. JSON/JSONL remain unstyled;
--watch retains its human-readable progress stream even with a JSON format selected.
Previewed shell commands and paths are not colored.
Without a check, the human can close the issue if nothing remains, reopen it for a new
session, run trk resume <ID> -m "<your decision>" to continue the live waiting
session, or reply in that same session’s chat for the agent to report through MCP
resume when chat resume is enabled (the default; see below).
The no-check MCP wait result includes the CLI command with the real issue id.
When [wait] chat_resume = false, the session must say plainly that a chat reply alone
will not continue the work and end its chat question with that exact command.
If the human replies only in chat while chat resume is disabled, the session repeats
the command rather than only recording a note.
After each non-ID pass, trk check automatically sweeps all eligible closed-as-done
issues, including manual closes, under the same queue lock and safety gates as trk gc.
Abandoned issues are excluded. [check] gc = true and gc_grace = "1h" are the defaults,
also when those keys are missing. The grace is a minimum age since closure, not a cleanup
deadline: cleanup waits for a later pass and may skip unsafe resources. trk check ID
never sweeps; --no-gc disables sweeping for the whole run or watch session.
--dry-run previews cleanup without removals or cleanup notes. Cleanup errors are advisory
and do not change check outcomes or exit status. JSON includes optional data.gc with
dry_run, manual-GC-shaped issues, and optional errors strings, omitted when there
are no eligible issues or errors. Pretty output shows one line per issue with removals;
skips and their reasons are shown once per issue per run, rather than on every watch pass.
Human-authorized resume
A human can continue the original live waiting session, with or without a check:
trk resume orch-4kq -m "Use SQLite; continue the implementation" --json
-m is required and must contain non-whitespace text. Resume restores the latest waiting
session’s actor, worktree, host, agent and terminal in a fresh claim with a new lease before
sending the message, so its MCP lifecycle tools work again once its MCP connection is
running (restart it if dormant). It never launches a replacement.
Human resume neither consumes nor resets the automatic wake_count or [check] max_wakes
budget. The timeline records the human’s authorization, message and delivery outcome.
Success data contains issue, actor, terminal, claim, resumed_from, message and
delivered: true: this confirms launcher delivery, not that the agent read, acted on or
completed the request. trk send only delivers text; it does not restore a waiting claim.
CLI resume refuses agent actors with not_permitted; agents must request human
authorization for this path, never impersonate a human. Empty messages return bad_args.
A busy check queue returns invalid_state: retry after it finishes; do not clear its lock.
A gone or unknown terminal/session (including a remote or unknown host), missing
terminal or missing send configuration also returns invalid_state. A human can instead run
trk reopen orch-4kq -m "Restart with the decision" then trk run orch-4kq.
If delivery fails after restoration, resume returns
nonzero internal, releases only that exact restored claim to open and records a failure
note without overriding subsequent session actions. Inspect trk show before recovery.
Same-session chat resume
For a wait without a check, the same waiting session can call its MCP resume
tool after an actual unmarked human replies in that session’s chat. It supplies the reply
verbatim as message, then continues only after success. [wait] chat_resume = true
is the default, including in existing configs; set it to false in .trk/config.toml
to require human CLI resume instead.
This records the agent’s report, not human authorization. The agent-attributed
resume_chat event stores the original message, prior claim and restored claim;
an agent-attributed note says Session reported a human reply in chat: followed by
the reply. Whitespace-only messages are refused, but accepted text is stored verbatim.
The transaction requires the latest waiting claim to belong to that same agent,
the issue still to be waiting with no active claim, and no check. It restores the
same session’s metadata with a fresh lease, without terminal probing or delivery.
It preserves wake_count.
Only an actual human chat reply qualifies. Notes, tool results, check output and agent-generated text do not. Tracker terminal deliveries are wrapped as:
[trk-delivery source=<source> actor=<actor>]
<body>
[/trk-delivery]
Sources include trk-send, check-wake, human-resume, check-notification and
briefing when relevant. Marked text never counts, even when it quotes a human.
trk send cannot authorize or trigger chat resume.
A checked wait always refuses MCP resume with not_permitted and a hint to ask
for human trk resume, protecting [check] max_wakes from a chat-resume bypass.
Human CLI resume remains available with or without a check; it is the distinct
human-authorized path described above.
List and ready tables show each issue’s type after priority. Filter either command with
type=review (or type=research / type=code-change); use --sort type to order by type:
trk list type=review --sort type
trk ready type=research --sort type
The check runs with sh -c in the worktree the issue was claimed in, or the primary
repository root when the claim has no worktree (the project root outside git), with
TRK_ISSUE, TRK_WORKTREE, TRK_REPO (the primary checkout, unset outside git),
TRK_BRANCH, TRK_BASE (the resolved base branch) and TRK_VERIFY ([check] verify,
default empty) set. Its exit code decides:
| Exit | Meaning | Result |
|---|---|---|
| 0 | pass (PR merged) | the issue closes as done |
| 75 | not yet (CI pending, awaiting review, unresolved threads, approved but not merged, unknown mergeability) | still waiting; checked again after --every (default [check] interval, 5m) |
| anything else, or a timeout | error (base-branch conflict, failed head-commit CI, closed without merging, or query/authentication failure) | wake the original live session, otherwise reopen; record the command’s output in a note |
The PR states above describe the example, not built-in PR handling. The agent opens
the PR and waits; trk closes the issue when it merges. The agent fixes reported
base-branch conflicts and failed head-commit CI unattended. Review threads and
merging belong to the human unless they ask the agent to handle them.
The check names the conflicting base or prints failed jobs and their URLs. It
does not block on CI or review. Checks must be non-interactive, non-blocking
(no --watch) and safe to repeat.
Configure [check] verify in .trk/config.toml as an opaque shell command, for example
verify = "npm ci && npm test". It is also available to prompt templates as {{ verify }}.
The local recipe merges the current base into the issue worktree, aborts merge conflicts,
then runs the command there if nonempty. Any verification failure (including exit 75)
fails the check and leaves the primary checkout untouched. Only the verified result is
fast-forwarded into the primary checkout after checking its branch. Empty verification
skips only the command. This local gate applies only when the issue type uses an issue
worktree and branch; a type opting out has no issue branch to merge or test. The PR recipe is unchanged.
Include dependency setup in the command if the worktree needs it. Verification uses the
whole check’s [check] timeout (default 10m) and holds the serialized queue; choose a fast
subset or increase the timeout for slow suites.
A failed check restores the original session’s claim with a fresh lease when its terminal
is confirmed live on the claim’s known local host, its pinned launcher provides send,
and its wake count is below [check] max_wakes. MCP liveness is not a prerequisite.
The cap defaults to 5; 0 disables waking.
Each restored claim increments the session’s persistent count, even if sending fails.
Entering or updating wait preserves it. A fresh explicit claim (including --steal)
resets it to zero; repeating a claim as its current owner does not.
The session receives wake N of M, the output and a prompt to fix only what the
check reported, then end the new work cycle, normally with the same wait. Its
MCP tools work again once its MCP connection is running; restart a dormant connection
first. If the same failure keeps returning, it should hand_back with the evidence
instead of repeating indefinitely. While waiting, it can still add notes and
receive requests from the human.
If the cap is reached, the issue reopens with a note saying wake cap of M reached
and retaining the check output. A gone session or failed send also reopens the issue.
trk show displays a wakes line for a nonzero count while claimed or waiting;
issue JSON includes top-level wake_count only in those cases.
trk check --json distinguishes woken from failed (reopened); both include output.
trk interprets only the check’s exit code, not PRs or CI.
A passing check still best-effort sends an informational message that the issue is closed. Exit 75 does not notify or restore a claim.
With the Herdr driver, a passing check also best-effort prepends [closed]
to the current name of the space containing the original waiting session’s exact
terminal, keeping the marker visible even when a long title is truncated. User
renames and embedded literal [closed] text are preserved. An existing leading
marker is not duplicated; old trailing [closed] markers are moved to the front.
This does not require a live agent or successful notification; missing UI/spaces
or rename failures never change the check result. Failed and retrying checks leave
titles unchanged.
trk check detects replacement of its executable, including same-version builds.
It finishes the active check, records the outcome and stops its remaining process
group, then releases the queue lock and re-executes the installed binary with the
original arguments and environment. Replacement is checked before each queued
issue and while idle in --watch; no manual watcher restart is needed. Before
re-executing, it logs an executable-update notice and the binary path to stderr,
leaving JSON stdout unchanged. One-shot results survive the restart, and completed
checks (including exit 75 with --all or an explicit ID) are not replayed within
that pass. Already-printed watch results
are not printed again. A temporarily missing executable is retried until it returns;
an exec failure reports an error without undoing recorded outcomes.
Three properties follow from that:
- A waiting issue still blocks. What depends on it becomes ready when the work has landed, not when the session stopped.
- Checks are a merge queue. Only one
trk checkruns at a time and it runs checks one after another, so two sessions never merge into the base branch at once. - Failures come back as work. A failed check wakes its live session to fix it; otherwise
the issue reopens and the next session reads the output in the notes. A command that
is missing or times out (
[check] timeout, 10m) fails rather than waiting forever.
trk check owns each check’s process group as well as the queue lock. On shell exit,
timeout, SIGINT, SIGTERM or SIGHUP, it stops remaining group members (SIGTERM, then
SIGKILL after two seconds) and reaps the shell before releasing ownership. Interrupting
the runner stops the pass/watch loop and leaves the interrupted issue waiting without
recording a partial result. Checks must not detach from their process group.
After SIGKILL or a runner crash, a new runner reports busy while the previous runner
or any live member of its recorded group survives. Once both are gone, it recovers
automatically; zombie processes do not block recovery. trk whoami shows
check_running.pid, .host and .pgid. A different/unknown host or unavailable
process information prevents automatic takeover. Inspect/stop surviving checks on
the owning host before retrying; never delete the lock while a check can still run.
A check is written by an agent and runs later, unattended, as you. trk show always prints it in
full, and trk check --dry-run shows the queue before anything runs.
Agent sessions and skill
Agent sessions
trk run # start the highest-priority ready issue
trk run orch-4kq # claim as agent:<harness>:<uuid>, create the worktree, start in hc
trk runs # active and waiting sessions: terminal/session and separate MCP liveness
trk dashboard # live full-screen overview of all of this; ? lists the keys
trk attach orch-4kq # take over the terminal
trk note orch-4kq --to-agent "Also update the docs" # delivered with the agent's next tool result
trk send orch-4kq "Wrap up and finish" # typed into the session
trk reap # release active claims whose local terminal is confirmed gone, with a note
trk run orch-4kq --dry-run # print the launch spec; claims nothing
trk run orch-4kq --model provider/model --dry-run # one-run model override and resolved argv
trk agent preview implementer --issue orch-4kq # instructions, briefing, tool schemas
An issue can carry links to what its work produced: a pull request, a preview, a document.
A session adds one with its link tool (the seed PR landing recipe asks for PR #<number>), and
you can with trk link orch-4kq https://… -l "PR #12"; trk unlink removes it. trk only stores
and shows them: the first link appears on the issue’s row in the dashboard, where l opens it
in the browser, and the details list them all. In Herdr the links are clickable.
In the dashboard, select a waiting / needs-you issue and press v to Resume the
original session, including when it has no check. Enter a nonempty continuation message
(for example, SSH unlocked; continue) and press Enter; Esc cancels without changes.
Resume runs in the background; success confirms claim restoration and instruction delivery,
not completion by the agent. The row refreshes from the database on success or error.
s Send delivers text only and never restores ownership; x Close and o Reopen
remain separate actions. ? lists the keys. If Resume fails, inspect the error and current
state; restore session access and retry, or reopen and run a replacement as described above.
Omitting the ID selects the first ready issue, ordered by priority (P0–P3), then oldest
creation time, then ID, matching trk ready. If there are no ready issues, the command
returns an error without launching a session. trk run --dry-run previews the selection.
The agent for a run is --agent (a one-off override), else the issue type’s agent mapping.
The seed types are change (default) and bug → implementer, research →
researcher, and ops → operator.
Use trk create ... --type ops, trk edit <ID> --type research, and trk list 'type=ops'.
Each .trk/types/<name>.toml may set worktree = true (the default when omitted)
or worktree = false. This is a type-only setting, not an agent or harness setting;
--agent does not override it. change and bug use worktrees, while the research
and ops seeds set it to false. With true, the worktree is
.trk/worktrees/<ID> on a branch named after the issue. New issue branches start at
the resolved [run] base; existing issue branches are reused, so a later session
on the same issue finds the earlier work. The worktree contains the whole repository;
the session starts at the project’s relative path inside it (for example,
<worktree>/services/api for a project at repo/services/api). Claims record the
worktree root, and checks use that root as TRK_WORKTREE, with the primary checkout
root as TRK_REPO. With false, the session runs in the primary project root,
creates neither branch nor worktree, and records no worktree path in its claim.
trk show --json routing and trk run --dry-run --json expose the resolved worktree boolean.
The operator performs work on a running service (deploy, rollback, migration,
credential rotation or incident investigation), not a repository change to land.
It records the initial state, notes every state-changing command before execution,
and verifies and records the result. Before destructive or irreversible work it
asks the user in the session and proceeds only on their authorizing answer; this
approval does not use trk wait. Repository code/config fixes are filed as
follow-up change issues instead of edited. The operator closes with the outcome
and evidence; its instructions include shared tracker rules but no landing recipe.
The harness is --harness, else the first installed harness the agent prefers (see Configuration).
The seed config prefers omp running openai-codex/gpt-6-luna.
Model precedence is --model, then the agent’s model for the selected harness, then
the profile’s model. With none set, the harness chooses its own default.
The MCP server (trk mcp --issue … --actor … --agent …, started by the harness) serves exactly one
issue with eight tools: get_task, add_note, link, report_followup, hand_back, close,
wait and resume.
It renews the claim’s lease while it runs. The briefing carries the issue’s description and every
note, which is how an issue that came back from a failed check explains itself.
Leaving an issue waiting releases the claim, not the terminal. While the issue stays
waiting, the actor of its latest claim released with reason waiting can still call
add_note, link and report_followup, and receive --to-agent notes with its next tool result.
It cannot call wait, close or hand_back again without a claim. trk send and
trk attach use that waiting session’s terminal when there is no active claim; an
active claim always takes precedence, even if it has no terminal. trk runs marks
waiting sessions with state: "waiting" (their displayed lease is historical), and
trk reap skips them. Closing, reopening or claiming the issue for a replacement ends
the old session’s access.
For a no-check wait with [wait] chat_resume enabled (default), that same session
may report an actual unmarked human reply through MCP resume to restore its
claim and continue. This is agent-reported continuation, not human CLI authorization.
Checked waits and disabled chat resume require the human CLI path instead.
Session liveness comes from the recorded terminal, not the MCP process. A recorded
launcher profile, a known claim host matching this machine and a nonblank terminal
are required; otherwise liveness is unknown. Unnamed historical or non-launcher claims
cannot use launcher-based attach, send, CLI resume or automatic wakes;
trk never assigns them today’s launcher. The Herdr driver discovers exact terminals;
other profiles use optional exists argv: exit 0 means live, a nonzero exit means gone,
and command errors or a
missing/empty operation mean unknown. Unknown sessions are neither automatically
woken nor CLI-resumed or reaped; a failed check instead reopens. Wakes and CLI
resume require the pinned profile’s send. MCP chat resume does not probe terminal liveness.
[launcher] send_delay waits before the initial briefing (default 5 seconds).
All sends—briefings, trk send, resume, and check wakes/notifications—use
send_retries total attempts (default 10; 0 means one attempt), with
send_retry_delay seconds between failed attempts (default 3).
Every delivery is wrapped in [trk-delivery source=<source> actor=<actor>]
and [/trk-delivery]; the actor is quoted and escaped. Such text never counts
as a human chat reply for MCP resume, even if a human invoked trk send.
trk runs and the dashboard distinguish terminal/session liveness from MCP liveness.
A live terminal with a stopped MCP server is dormant, not a dead session; it can
receive a wake or human-authorized resume. Restart its MCP connection with the same
identity to use tools again. trk reap leaves dormant and unknown sessions alone.
Lease renewal stops while MCP is stopped, however: active claims can still expire
through the normal lease sweep. Terminal liveness does not prevent expiry.
Agent skill
trk install also installs a skill (from skills/trk/, embedded in the
binary) that teaches your interactive agent sessions to use the trk CLI at .agents/skills/trk.
Configure links for other harnesses explicitly. trk whoami reports whether the installed
copy matches the binary; run trk install again to refresh it.
Configure its locations in .trk/config.toml:
[skill]
path = ".agents/skills/trk" # "" disables skill installation
links = [".claude/skills/trk"] # [] disables symlink creation
Paths are relative to the project root (absolute paths also work). Any number of links
can point to the installed directory. Installation, git excludes, tracked-path warnings,
and whoami follow this section; a disabled skill reports "disabled" and adds no excludes
or warnings. Changing the section does not remove previously installed files, links, or excludes.
Install JSON reports symlinks in skill.links as {path, linked} entries.
Sessions started by trk run should reach trk only through their MCP server. That is
why the skill is kept out of git with .git/info/exclude: the worktrees trk run creates do not
contain it, so those sessions do not see it. trk install and trk run warn when a repository
tracks the skill anyway; the omp profile also hides it with a per-session --config overlay
(skills.ignoredSkills: [trk]), and the skill itself tells an agent that has trk MCP tools to stop.
Launcher profiles
Launcher profiles
[launcher] use tries named profiles in order and selects the first available one.
When writing a built-in config, trk install probes Herdr’s UI, hc ls and
tmux -V, then keeps available profiles in that order, including tmux automatically.
All three profile definitions remain in the config. An available argv must succeed;
without it a profile is usable (the Herdr driver probes its UI). No available profile
is an error before claiming or starting a session; the hint lists profiles tried and
suggests installing a launcher, editing [launcher] use, or trk run --fg.
The selected name is recorded on the claim, and attach/focus, send, resume, checks and
GC keep using that profile even after use changes. Keep profiles needed by historical
sessions in the config.
Profiles accept optional available, start, attach, send, exists, focus,
close and rename argv arrays. Missing operations are skipped. Entries remain
separate arguments, with substitutions {name} (session address), {cwd},
{shell_command} (launch command including directory and environment), {text}
and {title}. Start’s first stdout line replaces the generated session name;
empty stdout retains it. Stderr is diagnostics, never a session address.
The tmux seed requests a stable session ID so rename does not break later operations.
Retry settings on [launcher] apply to profiles unless overridden there.
Each profile can set name = "trk-{id}", name_max = 32 and
name_chars = "a-z0-9_-" (the defaults). Templates accept {id} (full issue ID),
{prefix}, {project} (project-root directory name), {agent} and {type}.
Use, for example, name = "{project}-{id}" to distinguish projects sharing a prefix.
Names are ASCII-lowercased, characters outside name_chars become -, and the
result is limited to name_max characters. Character sets accept inclusive ranges
and literal characters; a trailing - is literal. Changing naming rules does not
rename existing sessions: later operations use the address recorded on the claim.
driver = "herdr" supplies Herdr’s start, exists, focus, close and rename defaults;
the seed’s attach and send still use hc. Each run opens a new Herdr space named
with the issue title and rooted in the launch directory, leaving the launching space
and tabs intact. JSON includes the actual terminal address and placement (visible
or failed). Observation timeout warns without ending the session. An uncertain
creation response retains the claim and never starts a duplicate session. When
Herdr is unavailable, selection tries the next profile in [launcher] use.
Configuration and harnesses
Configuration
Project state stays in .trk/ at its root, written by trk install:
.trk/ (found from the working directory; $TRK_DIR / --dir override it)
.gitignore "*": nothing here is tracked until you edit it
trk.db the database
config.toml user, issue id prefix, leases, check interval and timeout, worktrees,
launcher templates, harness profiles, saved views
agents/*.toml instructions, briefing, other MCP servers, harness preferences
types/*.toml name, description, agent routing, optional guidance
prompts/*.j2 MiniJinja templates
worktrees/<ID>/ git worktrees made by `trk run` ([run] worktrees)
sessions/<uuid>/ per-session files
checks/ logs of running checks
Settings resolve in order: built-in defaults < user < project. The optional user
directory is $TRK_USER_DIR, otherwise $XDG_CONFIG_HOME/trk, otherwise ~/.config/trk.
It has the same configuration layout: config.toml, agents/, types/, and prompts/;
no database or session state is stored there. A missing user directory changes nothing.
trk whoami shows the resolved user directory.
config.toml merges per key: tables merge recursively, arrays and scalar values replace
the lower layer. Named [harness.<name>] profiles and [views.<name>] views therefore
inherit unspecified keys. Project [user] identity and [issues] prefix take precedence;
when absent they can inherit from the user layer. Built-in defaults fill absent settings,
but do not supply agent/type/template files or harness profiles.
Launcher operations are optional. Omitted skill settings use .agents/skills/trk without links.
[issues] prefix names new issues (<prefix>-<base32>); normal installation writes the
directory name, or trk install --prefix NAME. Changing it later only affects new issues.
[issues] default_type selects the type for CLI and editor creation and MCP follow-ups
when no explicit type is supplied; trk whoami reports it. The default is change.
Set it to your project’s type name (for example,
default_type = "task" with types/task.toml) before removing or renaming the seed type.
Agents, types, and prompts resolve by filename, project first, then user, without
merging file contents. Template {% include "prompts/_rules.md.j2" %} uses the same
search order, even when the including template comes from the other layer.
The MCP server uses these same layers when started with TRK_DIR.
Normal trk install still writes complete project settings and all seed files.
Those project copies override shared settings; remove individual keys/files to inherit.
For a new project using shared configuration, use trk install --minimal: it writes
only project identity, issue prefix and base branch, plus the database, ignore file and
CLI skill. Populate the user directory with the shared profiles, agents, types and prompts
first. Minimal installation does not delete existing project resources.
[run] base selects the base branch, for example:
[run]
base = "develop"
landing = "merge"
When writing a new config, trk install detects the branch named by origin/HEAD,
then the current branch of the primary checkout, and finally falls back to main.
When base is omitted, runtime uses the same repository detection. An explicit base
takes precedence. Waiting checks receive the resolved branch as TRK_BASE; instruction
and briefing prompt templates can use {{ base }}.
[run] landing selects prompts/_landing.<value>.md.j2. The seed provides "merge"
for verified local landing into the base branch in the primary checkout, and "pr"
for opening a GitHub pull request against that branch and waiting on its merge.
New configs select "merge" with the implicit local preset or "pr" with
--preset github. Existing configs are preserved: switching presets does not change
their landing setting. Only the implementer includes the selected recipe; researchers
and operators receive the generic tracker rules. Local landing has no review or approval gate:
[check] verify is the sole verification gate, and an empty value skips verification
while still merging. GitHub landing requires installed, authenticated gh; install
warns if it is missing.
To add another workflow, create a template such as .trk/prompts/_landing.gitlab.md.j2
and set landing = "gitlab"—no code change or edit to shared rules is needed.
trk agent check reports a configured landing value with no matching template.
| Check setting | Default, also when omitted | Meaning |
|---|---|---|
[check] gc | true | Automatically sweep closed-as-done resources after non-ID passes; --no-gc overrides it for a run/watch |
[check] gc_grace | "1h" | Minimum age since closure for automatic cleanup, not a deadline |
There is no schema to apply: states, the close reasons (done, abandoned), priorities and the
one dependency kind (blocks) are fixed. Agents and prompts are read when a session starts;
trk agent check validates them. trk agents, trk agent check, and trk run --dry-run
report the project/user origins of agents, types and templates.
Type guidance
Both presets install change (the default) and bug, routed to implementer with
issue worktrees, research routed to researcher, and ops routed to operator,
both without worktrees. ops has no guidance snippet: service-operation rules
live in the operator instructions. The operator has full shell access through
builtin_tools = "default" and a commented cloud/observability [[mcp]] example
in agents/operator.toml; no extra MCP servers are enabled.
The built-in bug guidance requires reproducing first, a root-cause note, and a
regression test. A type can add task-specific instructions without another agent:
name = "bug"
description = "Fix a defect"
agent = "implementer"
guidance = """
Reproduce the defect in {{ project.name }} before changing code.
Add a regression test for the reported behavior.
Explain the root cause and verify the fix.
"""
guidance is optional inline TOML text rendered as MiniJinja with the same context
as agent instructions (see the context table below). For a reusable external snippet,
use guidance = '{% include "prompts/_bug.md.j2" %}' instead. Includes use the same
project-first, then user template loader. Type files resolve as whole files: a project
types/bug.toml replaces the user copy, including its guidance; fields do not merge.
The rendered snippet is appended automatically to agent instructions under
## Type guidance, including when instructions are folded into the briefing.
trk run --agent NAME changes the agent, not the issue’s type or its guidance.
Omitting guidance preserves the previous prompt output without an extra heading.
Use trk agent preview <agent> --issue ID or trk run ID --dry-run --json to inspect
the rendered instructions. Preview, dry-run and trk agent check report guidance
provenance as types/<name>.toml#guidance resolved to the type file, alongside any
included templates. trk agent check validates guidance syntax, rendering and includes
for every actual routed type; a broken snippet is an error, not ignored.
Set the default harness preference once in either layer’s config.toml:
[harness]
prefer = ["omp", "claude-code"]
Agents inherit this list unless their own [harness] prefer is present. An explicit
prefer = [] disables the inherited ordering; --harness overrides selection.
Seed agents inherit the preference from the project config rather than repeating it.
New built-in configs detect commands on PATH and keep installed harnesses in this
order: omp, claude-code (claude), codex, opencode, pi. Install reports both
launcher and harness detection and warns if either list is empty. All harness profiles
remain available for explicit selection. Later installs preserve existing configs and
preferences unless --force is given; --from sources and --minimal shared-config
installs do not filter preferences.
Agents can choose models and add arguments without duplicating harness profiles:
# .trk/agents/implementer.toml
[harness]
prefer = ["omp", "claude-code"]
model = { omp = "provider/implementer-model", claude-code = "implementer-model" }
args = { omp = ["--thinking", "high"] }
harness.model also accepts a string, applying it to every harness. A missing entry
in a model table falls back to the profile default. harness.args is a table of
harness names to argument lists; only the selected harness’s list is used.
Agent harness.builtin_tools levels are open-ended: default is reserved and adds
no restriction arguments; any other name (for example no-network or plan-only)
must be defined by at least one profile’s builtin_tools.<level> argument list.
An empty list explicitly declares support without extra arguments.
trk agent check reports undefined levels with the available names and warns
when a preferred harness lacks a level. trk run refuses to launch when the
selected profile lacks it, including explicit --harness selections; it no
longer silently launches unrestricted. Define the level’s enforcement flags in
that profile or select a profile that supports it.
Claude Code permissions
The seed uses --permission-mode dontAsk with --allowedTools for Bash, Edit,
Write, NotebookEdit and the exact trk MCP tools exposed to that session. Other
operations that need approval are denied rather than prompting; extra agent MCP
servers are not automatically approved. This avoids depending on the user’s
permission mode or a model-specific auto classifier, without using
--dangerously-skip-permissions.
This is still broad authority: Bash can execute arbitrary programs with your
account’s access. On the verified Claude Code version, dontAsk also skips the
first-use workspace trust dialog. Launch only in repositories you trust; use an
isolated environment for untrusted code. Narrow the Bash allow rules in your
project profile if its commands can be enumerated, accepting that other commands
will be denied. Existing installations keep their profile; copy the Claude Code
section from seed/config.toml to adopt these changes.
Claude’s read-only level exposes Read/Grep/Glob plus ToolSearch; none exposes
only ToolSearch, not file, shell or delegation tools. ToolSearch is a deliberate
discovery-only exception: with literal --tools "", Claude 2.1.331 can start its
first turn without any MCP tools and cannot call get_task or wait. Both
restricted levels retain discovery of the agent’s trk MCP tools without relying
on a delayed launcher briefing (which --fg does not send automatically).
These levels restrict built-ins, not MCP side effects or shell checks submitted
through wait; they are not filesystem sandboxes.
Models and launch arguments
# .trk/config.toml
[harness.omp]
command = "omp"
args = ["--config", "{{ session_dir }}/omp.yml", "{builtin_tools_args}", "{model_args}", "{agent_args}", "{{ briefing }}"]
model = "openai-codex/gpt-6-luna"
model_args = ["--model", "{{ model }}"]
model is optional; model_args defaults to an empty list and is inserted only
when a model resolves. Set model_args to the harness’s model-selection flags.
All seeded profiles provide it; only omp sets a default model.
{{ model }} expands to the resolved model (or an empty string if unset) in profile
arguments, environment and files, and agent arguments.
Standalone args elements {builtin_tools_args}, {model_args}, and {agent_args}
expand in place to zero or more argv entries. Place them before a subcommand or
after -- as the harness requires.
Each group without a marker goes before the first argument
using briefing, or at the end when none does. Unmarked groups retain the order
of built-in tool restrictions, model arguments, then agent arguments.
Arguments remain separate argv entries; they are not shell-split.
trk run --dry-run --json includes the resolved model (or null) and argv.
trk agents shows effective models per profile; its JSON includes the agent’s
configured model, effective models by harness (null means harness default),
and extra args.
Agent instructions, type guidance and briefings are MiniJinja templates with the same
context in trk run, the MCP server and trk agent preview:
| Variable | Value |
|---|---|
issue | Issue object, including dependencies and derived fields; briefings also include notes |
project.name, project.root, project.prefix | Project root directory name, root path (not the session worktree), and configured issue ID prefix |
type.name, type.description | Resolved types/<type>.toml metadata, even with an agent override |
config.check.interval, config.check.timeout, config.check.max_wakes | Configured check durations and numeric wake cap |
config.wait.chat_resume | Boolean enabling same-session chat resume for waits without a check (default true) |
config.claims.agent_lease, config.run.worktrees | Configured lease duration and worktree directory |
config.run.landing | Landing recipe name, used by the implementer’s dynamic template include |
agent.name, agent.description | Selected agent metadata |
tools | List of available tools, each with name and description |
worktree, actor, harness | Session worktree path, actor and harness name; worktree/harness may be null |
base | Resolved [run] base branch |
fold_instructions, instructions | Whether instructions are folded into the briefing, and their rendered text (otherwise null) |
Durations and config.run.worktrees retain their configured strings (for example 5m
and .trk/worktrees), without path expansion. Example: {{ project.name }}: {{ type.description }}; wake cap {{ config.check.max_wakes }}.
trk agent check renders each actual routed type, including its guidance, with a
sample issue and its resolved agent. It also retains the representative agent render
with sample issue/type/project values (project root /tmp/project, type change
with description Sample type description), using the project’s configured settings.
The wait tool advertises the configured check interval and wake cap; with
max_wakes = 0, failures reopen the issue instead of waking the session.
Seed waiting rules render these settings from the template context. Tool descriptions
cover the check mechanism only; branch landing and pull-request policy live in the
instruction templates, where projects can change them.
[wait] chat_resume = true is the default, including when [wait] is omitted.
Set chat_resume = false under [wait] in .trk/config.toml to require human
CLI resume instead of allowing the waiting agent to report an actual human chat
reply. This applies only to no-check waits; checked waits always refuse MCP chat
resume, preserving the automatic [check] max_wakes defense. Both chat and human
CLI resume preserve wake_count. See waiting and checks.
Harness profiles in config.toml use a separate MiniJinja context. Every command,
argument, environment value, file path/content and optional argument is
rendered once; substituted values are never expanded recursively.
| Variable | Value |
|---|---|
name, issue, actor, agent, harness | Terminal name, issue ID, actor, agent name and harness name (strings) |
model | Resolved model string, or an empty string when unset |
cwd, worktree, session_dir | Launch directory, worktree (falls back to cwd) and session scratch directory |
briefing, briefing_file, instructions, instructions_file | Rendered prompt text and corresponding file paths |
mcp_json_file, trk_command | Generic pretty MCP JSON file path and trk executable path |
trk_args, trk_env, trk_tools | trk MCP argument list, environment map and available trk tool names |
mcp_servers | Server list, trk first; each has name, command, args and env |
Server environments already expand ${env:NAME} from trk’s environment.
Use {{ value | tojson }} for compact JSON without HTML escaping and
{{ value | toml }} for inline TOML (quoted strings, comma-space-separated arrays,
and tables such as {key = value}). MiniJinja loops, expressions and built-in
map/join filters let each profile define its MCP dialect in configuration;
mcp_json_file always points to the generic pretty JSON, not a harness dialect.
The seed profiles include generic MCP and OpenCode examples.
The Codex seed emits individual overrides for trk and every agent [[mcp]]
server, without replacing other servers configured in Codex. args_json renders
a JSON array of strings prepended to the static args; this allows loops to
generate a variable number of flags without shell splitting:
[harness.codex]
command = "codex"
args_json = '''[
{% for server in mcp_servers %}
{% if not loop.first %},{% endif %}
{% for field in ["command", "args", "env"] %}
{% if not loop.first %},{% endif %}
"-c", {{ ("mcp_servers." ~ server.name ~ "." ~ field ~ "=" ~ (server[field] | toml)) | tojson }}
{% endfor %}
{% endfor %}
]'''
args = ["{builtin_tools_args}", "{model_args}", "{agent_args}", "{{ briefing }}"]
model_args = ["--model", "{{ model }}"]
builtin_tools = { read-only = ["--sandbox", "read-only"] }
trk install reports config.toml in differ when its harness profiles differ
from the seed, ignoring project identity and formatting. Existing config is kept
unless --force is explicitly requested; copy the profile above to update Codex
without replacing project settings.
Launcher templates retain their existing single-brace syntax.
There is no cross-project view: trk list, trk runs and trk check --watch act on the
project of the working directory, so each project needs its own trk check --watch.
Herdr dashboard
Herdr panel
In the Herdr app, the dashboard is also a native panel: a Herdr mod (from
herdr/mods/trk/, embedded in the binary). It reads
trk dashboard --json, the snapshot the terminal dashboard draws, and every button runs trk
itself, so both behave the same. Herdr labels the mod and new dashboard tabs trk dashboard.
The panel header shows the project name without a trk prefix.
trk herdr open # the panel for this project, as a tab in this Herdr space
trk herdr open --split right # beside this terminal's pane instead (or: down)
Each issue row and detail header shows a colored type badge, including code-change.
Built-in types use consistent theme colors; custom types get a stable color from their name.
The type text stays readable in the theme’s foreground color, with a full-name tooltip.
Issue IDs and type labels use shared, left-aligned columns across all dashboard sections.
Titles wrap in the remaining width. Working-session spinners prefix the title, aligned with
its first line; links and other statuses stay below, with no empty row for spinner-only issues.
Column widths adapt to the list pane when resized; long IDs and custom type names wrap instead of being clipped.
That is the whole setup. Herdr mods are machine-wide and a space shows one once a pane or tab
there holds it, so open does both steps: it installs or refreshes the mod when needed, then
opens the panel in the space this terminal is in (outside Herdr: the space whose folder is the
project, or --space <id>). The panel is pinned to this project and stays in that space, across
restarts, until you close it in Herdr. Opening again goes to the panel that is there. Spaces
where you never open it are untouched.
trk herdr install [--layout] # only the mod; --layout adds the sidebar and split layouts
trk herdr uninstall # remove the mod and layouts unless you edited them
- For a trk dashboard button above Settings in Herdr’s sidebar:
run
trk herdr install --layout, thenherdr-app do layout.switch --name main-trk. The button opens the dashboard for the shown space, or focuses its existing trk panel. Unpinned panels follow that space’s first terminal with a live folder, in tab order—not keyboard focus or the space’s original creation folder. With no live folder, they use the space folder. A collapsed sidebar shows just the icon.main-trkis a personal copy of Herdr’s layout; the shippedmainlayout is untouched. Switch back withherdr-app do layout.switch --name main. ./install.shandtrk installrefresh an installed mod, so it never lags the binary; neither installs it. The mod folder is trk’s and is rewritten; the layouts are yours once written.- The
trklayout (herdr-app do layout.switch --name trk) shows issues on the left and the selected issue’s live session on the right. It follows the shown space’s project. - Issues are grouped as in the dashboard. A session whose agent Herdr reports as blocked moves to Needs you; a working one shows a spinner. New needs-you issues post a toast, and the Dock badge counts them across the projects shown.
- Select an issue for its description, notes and timeline, and to go to or peek at its session,
run it, send text, resume, check now, add notes, change priority, unclaim, reopen or close.
Destructive buttons ask for a second click. Edit opens
trk editin a pane below. At widths of 720px or more, the list and details start at an equal 50/50 split; drag the divider to resize them. Each scrolls independently. Herdr keeps the split across repaints, issue selection, and hiding/reopening details in that window. Below 720px, details appear inline below the selected row. Hide details (orEsc) closes the details pane so the issue list fills the panel. Click an issue or pressEnterto reopen details;j/kkeep them hidden while browsing. - Click an issue ID in the list or detail header to copy it to the clipboard. The status line confirms the copy; selection and detail visibility stay unchanged.
- With the panel focused:
j/kmove,Enteropens,agoes to the session,ppeeks,ssends,m/Mnote (to the agent),vresumes,xcloses,ccreates,lopens the issue’s first link. Link chips on a row and in the details open in the browser on click. trk.newandtrk.refreshare mod commands forkeys.json, for example"global": { "ctrl-shift-i": "trk.new" }. They reach a shown copy of the panel.- By hand:
herdr-app do tab.new --mod trk --props '{"folder": "/path/to/project"}'. Withoutfoldera copy follows the shown space;"select": "<id>"opens it on an issue. Run the panel’s location regressions withnode --experimental-vm-modules --test herdr/mods/trk/main.test.mjs.
Cleanup
Cleaning up closed issues
Closing retains the session, worktree and branch; use explicit garbage collection after work has landed:
trk gc --dry-run --json # preview all closed-as-done issues
trk gc orch-4kq --json # clean up one issue
trk gc --older-than 7d --abandoned --json # include abandoned issues closed over a week ago
trk gc [ID...] [--legacy-hc] [--dry-run] [--abandoned] [--older-than DURATION] [--json] defaults to
closed-as-done issues; --abandoned also includes abandoned issues. It never collects open,
claimed or waiting issues, and serializes cleanup with the check queue and lifecycle writes.
All historical claims are considered, but only resources on this host are eligible.
Sessions use each historical claim’s pinned launcher, never today’s selection order.
Terminals without a recorded launcher profile are normally skipped, including during
trk check --watch sweeps; their independently owned Git resources remain eligible.
GC invokes the profile’s optional close operation; Herdr finds the exact recorded
terminal and closes its containing space, protecting your current space and other issues’ active or
waiting sessions. Legacy claims recording the primary checkout as their working directory
do not establish ownership of a disposable worktree or branch; their sessions remain
eligible, and they do not block cleanup of actual issue worktrees recorded by other claims.
Already-missing worktree paths are reported as absent, even outside today’s configured
directory. Existing worktrees are removed only below the configured worktree directory,
never the primary checkout or current worktree. Git worktree removal is not forced;
branch deletion uses git branch -d in the primary checkout, only for the issue-ID branch
and only after all recorded issue worktrees are removed or absent. Dirty or locked
worktrees, unmerged branches, existing outside-directory worktrees and other unsafe or
refused targets are reported as skipped. A missing directory’s remaining Git registration
can still prevent branch deletion; GC does not force or prune it.
Runs without a recorded issue worktree have no worktree or branch resources for GC to
collect; their recorded sessions remain eligible for normal session cleanup.
Recovering historical hc sessions
For historical claims with a NULL or empty launcher profile, explicitly select issue IDs
and opt in only after independently verifying that the sessions came from hc:
trk gc orch-4kq --legacy-hc --dry-run --json
trk gc orch-4kq --legacy-hc --json
--legacy-hc requires at least one explicit issue ID. It asserts independently verified
provenance; terminal spelling, aliases and today’s default launcher are not evidence.
It never selects a launcher profile or changes cleanup for claims with a named profile.
All normal eligibility, host and resource-safety gates remain in force. Your current
HC_TERMINAL_ID and other issues’ active or waiting terminal identities are protected.
Recovery inventories sessions with hc ls --all --json, matching only the exact recorded
address, never an alias or name. A valid inventory without that address proves absence;
an unavailable, failed or malformed inventory does not. For a present address,
hc get ADDRESS --json must confirm the exact address, a finished state, and the claim’s
working directory (or project root when none was recorded). Its argv must contain the
exact TRK_ACTOR=<actor> word for that claim; shell command strings are split on ASCII
whitespace for this check. Only a finished session with matching identity is removed,
using hc rm ADDRESS --json. Live, ambiguous, mismatched or unavailable sessions are
skipped; recovery never kills a live session.
A successful real removal or proven absence appends a structured, GC-only note receipt:
gc_session: {claim: ID, terminal: ADDRESS, host: HOST, backend: "hc"}.
The receipt is bound to that historical claim; its original launcher and all other claim
data remain unchanged. Later ordinary GC and check sweeps consult the receipt and recheck
hc, allowing an absent session to be reported without repeating the missing-profile
warning. A receipt is not proof of continued absence or a general launcher override.
Failed or skipped recovery writes no receipt, and dry runs neither mutate resources nor
write notes.
JSON uses the normal envelope with data: {dry_run, issues}. Each issue has id and
session, worktree, branch outcomes with status (removed, absent, skipped) and
reason. Session and worktree outcomes also have items, identifying each terminal /
space or path with its own status and reason. Dry runs write no notes and remove
nothing: planned removals use removed with a would remove ... reason and
dry_run: true. Real removals append caller-attributed notes; rerunning when resources
are already absent adds no cleanup notes, except for the first successful legacy-hc
recovery receipt described above.
Design and state model
trk is a local issue tracker and agent launcher in one Rust binary. Each project
owns a SQLite database in .trk/; there is no global issue registry. Humans use
the CLI and dashboards. Sessions launched for an issue use its per-issue MCP
server, so their tracker context and tools stay focused on that issue.
An agent is instructions plus tools; a harness runs the agent; a launcher provides its terminal/session. Types route issues to agents, choose whether a run uses an issue worktree, and may supply optional task-specific guidance. They do not introduce different state machines or custom issue fields.
Goals and boundaries
- Keep the model small: four states, one blocker relationship, attributed claims.
- Keep project state local and configuration portable, without registering projects.
- Preserve the history of decisions and handoffs as append-only events.
- Treat completion as delivered work: landed repository changes, an answered research question, or a verified service operation with a record. Awaiting merge, review or a decision is waiting, not done. Waiting still blocks dependent work.
- Return failed checks as actionable work, with evidence, rather than silently retrying errors forever.
- Share domain rules across CLI, MCP and the check runner through
trk-core.
There are no configurable workflows, issue hierarchies, network synchronization, networked multi-user service or web issue editor. Types do not require evidence on close: completion requirements belong in instructions and checks, not a built-in review/CI model. External status is read by checks when needed, not mirrored into issue fields. Checks and agent identities are not security sandboxes.
Type guidance is optional inline MiniJinja text in types/<name>.toml, rendered
with the agent instruction context and appended under ## Type guidance. It can
include shared prompt templates rather than duplicating agent definitions. An
explicit --agent override changes the selected agent but retains the issue type’s
guidance. Absent guidance leaves existing prompt output unchanged.
Types resolve project-over-user as whole files, not merged fields; included templates
use that same project-first search order. Guidance provenance identifies the resolved
type file as types/<name>.toml#guidance and records included templates. Agent check
validates every routed type with a sample issue in addition to its representative
agent context; preview and run dry-run expose the rendered result and sources.
See type guidance for configuration examples.
Both install presets (local and github) seed change and bug through
implementer in issue worktrees, research through researcher without a
worktree, and ops through operator without a worktree or type guidance.
Operations cover deploys, rollbacks, migrations, credential rotation and incident
investigation on running services. The operator has default built-in tools
(full shell), shared tracker rules and no landing recipe. Projects can add cloud
or observability MCP servers; none are enabled in the seed.
The operations contract lives in the operator instructions: establish and note
current state, note each state-changing command before running it, then verify
and note evidence. Destructive or irreversible actions require asking the user
in the session and proceeding only on their authorizing answer, not a trk wait.
Repository code/config fixes become follow-up change issues rather than edits.
The deliverable is the operation plus its record; close records the outcome.
Issues, readiness and blockers
An issue has a required title, Markdown description, priority (P0 urgent through
P3 low; default P2), and required routing type (configured default, otherwise
change). Notes are history events, not a mutable description extension.
The system owns state, close reason, waiting metadata, authorship and timestamps.
IDs have the form <prefix>-<random lowercase base32 suffix>. New suffixes start
at three characters and lengthen on collisions. The prefix is configurable;
changing it does not rename existing issues. Unique ID/suffix prefixes may be
used in the CLI; ambiguous matches fail rather than selecting an issue arbitrarily.
Links are issue-owned HTTP(S) pointers with optional single-line labels of at most
40 characters. Their URL is the key: adding it again updates its label. Links
survive claims, waiting and reopening. trk stores and displays them but does not
fetch their targets or interpret pull requests.
A blocks B is the only dependency: B is ready only when A is closed. The graph
must be acyclic, including no self-edges. Readiness means open and every blocker
closed; both done and abandoned satisfy that condition. Priority ranks eligible
work and cannot bypass blockers. The default ready/list order is priority, creation
time, then ID; explicit or saved-view sorting may override it.
Reviews, decisions and milestones are ordinary issues with descriptions and blocker edges. A follow-up records its originating issue in the create event; it is not a parent/child hierarchy or an implicit blocker.
States and transitions
| State | Meaning |
|---|---|
open | Unclaimed; eligible for claiming only when ready |
claimed | Exactly one active claim |
waiting | No active claim; waiting on a check or a person |
closed | Finished with reason done or abandoned and a closing timestamp |
| From | To | Cause |
|---|---|---|
open | claimed | Claim a ready issue |
claimed | open | Unclaim, agent hand-back, lease expiry, or reap of a confirmed-gone local session |
claimed | waiting | Claimant waits with a reason, check, or both |
claimed | closed | Claimant closes as done or abandoned |
open or waiting | closed | Human closes without an active claim |
waiting | waiting | Check returns 75, or a human replaces its waiting settings |
waiting | claimed | Failed check restores its eligible live session, a human authorizes CLI resume, or the same waiting agent reports an actual human chat reply through MCP resume for an enabled no-check wait |
waiting | open | Failed check cannot wake its session, or restored-claim delivery fails |
waiting or closed | open | Human reopens |
A human can force another actor’s claimed issue through claimant-restricted
operations; the override is recorded. Stealing a claim replaces its owner without
changing claimed state. Reopening clears closure/waiting metadata; closing clears
waiting metadata. Closing an issue does not delete it.
Waiting is not ownership
Entering waiting releases the claim with reason waiting. A check is initially
due immediately and subsequently scheduled at its interval. No check means the
issue waits for a human rather than polling. The exit-code contract is deliberately
small:
- 0: close as
done. - 75: remain waiting and schedule another check; no history event or
updated_atchange is generated. - Anything else, including timeout: record the failure and output tail, then restore the original eligible session or reopen the issue.
Automatic restoration requires a confirmed-live terminal on the known local claim host, the original pinned launcher’s send operation, and remaining automatic wake budget. Terminal liveness is separate from MCP liveness: a dormant MCP connection does not make a terminal dead, but must reconnect with the same identity before using tools. Unknown or remote liveness does not authorize restoration.
A restored claim has a fresh lease and preserves actor, worktree, host, agent,
terminal and launcher. Automatic restoration increments persistent wake_count,
even if message delivery fails. Waiting preserves the count; a fresh explicit
claim, including stealing, resets it; an idempotent claim by its owner does not.
Human-authorized CLI resume and agent-reported chat resume neither increment nor reset it. Failed delivery releases
only the exact restored claim, never a replacement claim or subsequent session
state. Successful delivery is not proof that an agent read or executed a request.
See Waiting and checks for scheduling, wake limits, human CLI resume, same-session chat resume, failure recovery and landing recipes.
Actors, claims and permissions
Actors are human:<email> or agent:<harness>:<session-id>. The agent session ID
is everything after the second colon, kept verbatim; trk run mints a UUID before
launch. An agent may record the human it acts on behalf of. CLI actor selection
uses --as, then TRK_ACTOR, then configured human identity.
Claim creation and the transition to claimed are atomic. A partial unique index
permits at most one active claim per issue, and core maintains the stronger
invariant: an issue is claimed if and only if it has an active claim. Claims
retain their actor, timestamps, optional lease, worktree/host and session routing
metadata after release. Release reasons are closed, waiting, unclaimed,
expired and stolen.
Agent claims have a default 30-minute lease; human claims have none by default. Explicit renewal, the running MCP server and claimant writes renew leases. Expired leases are swept at the start of write transactions, releasing their claims and reopening issues without a lease daemon. A live terminal does not prevent lease expiry when MCP renewal stops.
Core enforces agent authorization for the CLI as well as MCP:
- Ordinary issue edits and lifecycle actions require the agent’s active claim.
- A waiting session is the latest claim’s actor only while the issue remains
waiting and that claim was released as
waiting. It has no lease or ownership. - Its remaining access is notes, links and follow-up creation, plus receiving messages. It cannot close, wait again or hand back without a restored claim.
- Closing, reopening or replacement ownership ends the old waiting session’s access.
- Follow-ups may be created only from the agent’s active or waiting session. Dependency edits require an active claim on at least one endpoint.
- Only a human may authorize CLI resume. For a no-check wait with
[wait] chat_resumeenabled (default), the same waiting agent may instead report an actual unmarked human chat reply, verbatim, through MCPresume. That report restores its claim; it is attributed to the agent, not recorded as human authorization. - Chat resume transactionally requires the issue still waiting, no active claim, no check, and the latest waiting claim belonging to the caller. It restores the original metadata with a fresh lease, without terminal probing or delivery.
- Checked waits and disabled chat resume refuse this path with
not_permittedand the humantrk resumehint; chat resume cannot bypass[check] max_wakes. Agents must not impersonate a human or treat tracker deliveries as chat replies.
Actor identifiers are attribution and application policy, not authenticated operating-system identities. A harness that can reach the database or select a human identity is not hard-isolated by these rules. Hard isolation requires an execution environment where the database is inaccessible. See Agent sessions for the MCP interface and session lifecycle.
History
Domain changes and notes append attributed, UTC-timestamped event rows. Notes
use op = 'note'; correcting one appends a new note with amends pointing to the
previous note. SQLite triggers reject event updates/deletes and issue deletion.
This is an application-level append-only record, not cryptographic tamper evidence
against someone controlling the database file.
Lifecycle events include creation, edits, claims/releases, waiting, check outcomes,
closure, reopening and dependency changes. Link changes use set events. Passing
or failing checks record an outcome and the transition they cause; exit 75 only
updates scheduling metadata to avoid flooding history. Failed checks retain the
command and the last 4 KiB of output in a note for the next work cycle.
Chat continuation records a distinct resume_chat event with
{message, resumed_from, claim} and an agent-attributed note beginning
Session reported a human reply in chat:. The required message must be nonempty
after trimming but is stored verbatim. Human CLI resume retains separate human
authorization and delivery records, distinguishable in trk show and the dashboard.
Architecture and storage
trk-core owns domain rules and the Store write path. trk-cli implements human
interfaces, project resolution, launch orchestration and the check runner;
trk-agent defines and executes agent tools and renders launch instructions;
trk-mcp exposes a per-issue server and renews its claim. See
Development for the crate layout and contributor commands.
Project .trk/ contains trk.db, configuration/resources, worktrees, session
scratch files and check logs. Optional user configuration has no issue database or
session state. Settings merge built-in defaults < user < project; agent, type
and prompt files resolve project-first then user by filename without merging
contents. See Configuration for paths and precedence details.
Project discovery uses explicit --dir/TRK_DIR first. Otherwise it searches
ancestors for .trk/trk.db within the current checkout. In a linked worktree it
also searches the corresponding path and ancestors in the primary checkout, so
nested projects resolve correctly. The fallback is the primary Git checkout root,
or the current directory outside Git. Normal commands require an installed database
and configuration; they never implicitly create a new project database.
Launched MCP sessions and checks receive TRK_DIR to preserve project identity.
Transactions and check ownership
- Connections use WAL,
synchronous=NORMAL, foreign keys and a five-second busy timeout. Reads use deferred transactions. - A core write runs in one
BEGIN IMMEDIATEtransaction: register the actor, sweep expired leases, validate permissions/invariants, mutate rows and append events, then commit. Failure rolls it back; core dry-run writes also roll back. - Checks execute outside database transactions. Queue locking, durable process-group registration and result recording are separate transactions. A spawned shell cannot execute its check until its group has been durably registered.
- The queue serializes checks, including merges. Shell exit, timeout and runner interruption stop remaining group members and reap the shell before releasing ownership. Cleanup failure retains the lock; interruption leaves the issue waiting without recording a partial check outcome.
- Crash recovery takes over only when the same-host runner and its live group members are gone. Unknown ownership fails closed. Checks must not detach from their process group.
- Results validate the waiting command and lifecycle revision before changing an issue. Stale results cannot overwrite a newer wait or ownership change.
- Commands can run again after a crash between execution and result recording: checks must be non-interactive and repeat-safe, not assume exactly-once execution.
Migrations apply on open using SQLite user_version; a database newer than the
executable is refused, not downgraded or reset. Running MCP servers require an
explicit compatible restart after an upgrade. Backups use VACUUM INTO for a
consistent copy.
Data model
The baseline schema and subsequent migrations define the current database:
| Table | Purpose |
|---|---|
harness, actor | Actor identities, delegation and session metadata |
issue | Authored fields, lifecycle/waiting metadata, timestamps and wake count |
dep | Directed blocker edges (src blocks dst) |
link | Current issue URLs and labels; changes remain in events |
claim | All claims, including released claims and pinned launcher identity |
event | Append-only attributed history with JSON payloads |
inbox | Delivery bookkeeping for notes addressed to a session |
check_lock | Serialized queue owner and active process group |
search | FTS5 index of titles, descriptions and notes |
Views expose note, active_claim, issue_view (with claimant/lease) and ready.
SQLite enforces foreign keys, valid states/priorities/reasons, closure consistency,
one active claim, valid event JSON and append-only history. Core additionally
enforces transitions, claim/state equivalence, authorization and acyclic blockers.
Not every invariant is a database constraint: direct SQL writes are not a supported
alternative to core operations.
Trust boundary
Checks are shell commands, potentially written by an agent and executed later,
unattended, with the invoking user’s privileges. They run outside any sandbox the
harness may have used. Process-group ownership prevents overlapping managed
checks; it does not sandbox commands or protect files and credentials. trk check
runs only when started by the user; inspect the full command in trk show or the
queue with trk check --dry-run before execution.
Project and user configuration are trusted executable inputs, including launcher
commands and templates; there is no separate trust gate between those layers.
External-service credentials, permissions, query failures and status interpretation
belong to the check command. trk interprets its exit code, not PR, CI or review
semantics.
MCP contract
Agent sessions use MCP; human sessions and scripts use the CLI JSON API. The harness starts the stdio server for the session:
trk mcp --issue orch-4kq --actor agent:omp:23e60544-0aa7-4c7c-bf2f-99b5da8c56ee --agent implementer
The server serves exactly one issue, resolved when it starts. No tool accepts an
issue ID, and there is no general search, arbitrary issue editing, or shell tool.
report_followup can create another issue in the same project’s database, but does
not switch the session to it. See agent sessions for launching and
session identity, and configuration for agent definitions.
Tool catalogue
The fixed catalogue has eight tools. All input schemas are objects with
additionalProperties: false; required text arguments must be nonblank.
An omitted optional argument uses the default described below.
| Tool | Required arguments | Optional arguments | Effect |
|---|---|---|---|
get_task | None ({}) | None | Read the issue, notes, dependencies and resolved routing. |
add_note | body: string, markdown | None | Append a note to the issue’s memory. |
link | url: string, absolute HTTP(S) URL | label: string, at most 40 characters | Attach a link; using the same URL updates its label. Omitting the label leaves the URL as its display text, including when replacing an existing label. |
report_followup | title: string; description: string | priority: P0, P1, P2 or P3 (default P2); type: configured issue type (default [issues] default_type); blocks_this: boolean (default false) | Create a follow-up and append its ID and title as a note on this issue. If blocks_this is true, the new issue blocks this one; hand back if you cannot proceed. |
hand_back | note: string, explaining what remains and why | None | Release the claim and return the issue to open. |
close | reason: done or abandoned; note: string, the outcome | None | Close the issue and release the claim. |
wait | reason: string, what must happen next | check: string, a shell command; interval: duration string such as 2m, 1h or 1d (default [check] interval) | Enter waiting and release the claim. Without a check, wait for a human decision. |
resume | message: string, the actual unmarked human chat reply, verbatim and nonblank | None | Restore this same waiting agent’s claim for a no-check wait when [wait] chat_resume is enabled (default). Records an agent report, not human authorization. |
The server populates report_followup.type’s schema enum and description from the
project’s installed type definitions. Discover the current schemas with MCP
tools/list; do not assume every project uses the seed types.
trk agent preview <agent> --issue <ID> also shows the session’s tools.
Without a check, wait returns a message containing the issue-specific command
trk resume <ID> -m "<your decision>". The human can close the issue if nothing
remains, reopen it for a replacement session, or use that command to continue the
live waiting session. With chat resume enabled, the same session can instead
report an actual unmarked human chat reply through MCP resume and continue only
after success. When chat resume is disabled, the session must end its question
with the real CLI command and state that a chat reply alone will not continue the
work; on a chat-only answer, repeat the command rather than only adding a note.
A check runs unattended with sh -c in the recorded worktree/project directory.
It receives TRK_ISSUE, TRK_WORKTREE, TRK_REPO, TRK_BRANCH, TRK_BASE and
TRK_VERIFY. Exit 0 closes as done; exit 75 schedules another attempt; other exits
or timeouts record a failure note and either wake the eligible live session with
its claim restored, or reopen for a replacement. Waking is bounded by
[check] max_wakes; setting it to 0 disables automatic wakes. A check must be
noninteractive and safe to repeat. See waiting and checks
for the environment, scheduling, wake conditions and landing recipes.
Permissions and ownership
An agent definition may narrow the catalogue with trk_tools.include:
[trk_tools]
include = ["get_task", "add_note", "report_followup", "hand_back"]
An absent or empty include list selects all eight tools. Entries match names with
* globs; @all selects the entire catalogue. This only narrows access: it cannot
add tools or override ownership checks. A filtered-out tool is unavailable even
when the session owns the claim.
For agent actors, lifecycle writes require the session’s active claim.
get_task is readable without a claim when included. After wait, the actor of
the latest claim released with reason waiting retains these capabilities while
the issue remains waiting:
- Read the task.
- Call
add_note,linkandreport_followup, if included. - Receive inbox messages, if inbox delivery is enabled.
- Report an actual human chat reply through
resume, if included and the wait has no check with[wait] chat_resumeenabled.
It cannot call wait, close or hand_back again without a restored claim.
Closing, reopening or claiming the issue for a replacement ends this waiting
exception. After close or hand_back, further writes are refused. Human CLI resume,
an automatic failure wake, or eligible same-session MCP chat resume can restore
ownership. A chat message alone does not restore it: MCP resume must succeed.
Agents must not impersonate a human or use CLI resume autonomously.
Chat resume requires the latest waiting claim to belong to the caller, the issue
still waiting, no active claim and no check. It restores the same metadata and a
fresh lease without terminal liveness checks or a launcher send, preserving
wake_count. Checked waits and [wait] chat_resume = false return not_permitted
with the human CLI resume hint. Empty/whitespace-only messages return bad_args.
The original message is stored verbatim in an agent-attributed resume_chat event
and note, never as human authorization. See chat continuation.
Text wrapped in [trk-delivery source=<source> actor=<actor>] and
[/trk-delivery] is tracker-delivered text, never an eligible human chat reply,
even when its actor is human or it quotes a human. This includes trk-send,
check-wake, human-resume, check-notification and briefing deliveries.
Notes, tool results, check output and agent-generated text do not qualify either.
While the MCP server runs, it renews only its own active, leased claim. A waiting session holds no claim and does not renew its old lease. If MCP stops, renewal stops even if the terminal stays alive; normal lease expiry still applies.
Tool results and errors
Tool results contain a text content block whose text is a JSON object. Inspect the
MCP tool result’s isError flag: the payload is not the CLI’s versioned
{ok, schema_version, data} envelope, and success shapes differ by tool.
| Tool | Successful JSON payload |
|---|---|
get_task | The full issue object, including deps, notes and routing; see issue JSON. |
add_note | {"ok":true,"result":{"note":42},"task":{...}}; note is the appended note’s sequence number. |
link | {"ok":true,"result":{"linked":"https://example.com/pr/12","changed":true},"task":{...}}; changed is false if nothing changed. |
report_followup | {"ok":true,"result":{"created":"orch-9xa","blocks_this":false},"task":{...}}. |
hand_back | {"handed_back":"orch-4kq","message":"..."}. |
close | {"closed":"orch-4kq","reason":"done","message":"..."}. |
wait | {"waiting":"orch-4kq","reason":"PR 12 merged","message":"..."}. |
resume | {"ok":true,"result":{"resumed":"orch-4kq","claim":{...},"message":"..."},"task":{...}}; claim is the restored claim. |
Here task is a compact snapshot with id, state, claimed (boolean) and
blocked_by (IDs). wait, close and hand_back return their direct
acknowledgement, not this snapshot. Do not require a top-level ok key on every successful tool result.
Domain failures normally set the MCP error flag and return:
{
"ok": false,
"error": {
"code": "not_permitted",
"message": "...",
"issue": "orch-4kq",
"hint": "..."
}
}
Error codes and optional detail fields use the core error vocabulary.
An unknown/unavailable tool or a failure opening the store instead returns the
error object directly (code, message, optional hint/details), still with the
MCP error flag. Transport/internal task failures can be MCP protocol errors.
A failed tool call does not terminate the stdio server or yield a CLI exit code.
Server startup failures go to stderr and exit 1; stdout belongs to MCP.
Task resource and inbox
The server advertises trk://task with MIME type application/json. Reading it
returns the issue with dependencies and notes, without a claim requirement. It
is independent of trk_tools.include, and is not byte-for-byte identical to
get_task: the tool adds routing, and only tool calls deliver inbox messages.
Unknown resource URIs return an MCP resource-not-found error.
With inbox = true in the agent definition, a human’s
trk note <ID> --to-agent "message" is attached once as messages_for_you to the
owning active or waiting session’s next processed tool result, including a domain
error result. Each message has seq, from, at and body. Delivery marks it
consumed; the note remains in the issue history. Old or unrelated sessions cannot
consume it. Unknown tool calls and store-open failures return before inbox
processing, and resource reads do not consume messages.
Implementation: tool schemas, tool execution, and MCP transport and ownership.
CLI JSON and exit protocol
Use --json for scripts. It is shorthand for --format json and takes precedence
if both options are present. --format pretty|json|jsonl can also be set through
TRK_FORMAT; without either option, stdout being a terminal selects pretty,
otherwise JSON. JSON and JSONL do not contain ANSI styling. Pretty output is a
view of the same command result, not a separate query.
This chapter covers ordinary CLI command results. The MCP server owns
its stdio transport and does not use this envelope. trk check --watch prints
human-readable progress lines as checks finish, even with a JSON format selected;
use a single trk check --json pass for machine-readable results.
Envelope and version
A successful --json command writes one JSON document to stdout:
{
"ok": true,
"schema_version": 4,
"data": [
{"id": "orch-4kq", "state": "open", "type": "code-change"}
]
}
This example could be produced by
trk list --fields id,state,type --json. The current output schema version is
4, independent of the installed binary’s version or the SQLite migration
version. Within an output schema version, keys are only added; removing or
renaming keys requires a version bump. Version 3 replaced the old issue agent
field with required type; version 4 removed issue project and repo because a
database contains one project. Consumers should tolerate additional keys, test
ok, and handle optional fields rather than infer success from the data shape.
The type of data depends on the command:
| Command/result | JSON data |
|---|---|
list, ready | Array of issue objects, or projected objects when --fields is set. Empty results are []. |
show <ID> | One issue object. |
show <ID> <ID>... | Array of issue objects. |
log <ID> | Array of timeline events, including notes, in sequence order. |
check (one pass) | Object with busy, results, and optional holder or gc; see below. |
| Other commands | The command’s typed object/array. Even commands silent in pretty mode can return JSON data. |
--fields changes object keys as well as pretty table columns. Saved views can
also supply fields. For example, --fields id,claimed-by,ready emits exactly
those keys, using null where the selected value is unavailable. Field aliases
include status → state, reason → close_reason, created/updated/closed
→ their _at timestamps, claimed-by → claim.actor, lease →
claim.lease_until, ready/due/blocked-by → the corresponding derived
fields, and check/next-check → the corresponding waiting fields. See
queries for filtering and configuration for views.
JSONL
--format jsonl writes compact, unwrapped JSON values rather than the versioned
success envelope:
listandready: one issue (or--fieldsprojection) per line. No matches produce no stdout.log: one timeline event per line. Each event hasseq,issue_id,actor,at,opandpayload; notes are events withop: "note"and their text inpayload.body.- Other results: one line containing the command’s whole
datavalue. In particular,show A B --format jsonlemits one array, not one issue per line.
JSONL success values have no ok or schema_version wrapper. On failure the
renderer instead writes the same pretty-printed, potentially multiline error
envelope as JSON mode. Check the process exit status before treating stdout as
a stream of successful rows.
trk list 'state!=closed' --fields id,state,type --format jsonl
trk log orch-4kq --format jsonl
trk show orch-4kq --json | jq '.data.derived'
Issue objects
The normal issue representation contains:
| Fields | Meaning |
|---|---|
id, title, description, priority, type | Authored identity and content; priorities are P0–P3, and type is required. |
state, close_reason | State is open, claimed, waiting or closed; close reason is done, abandoned or null. |
waiting | Null unless waiting. Otherwise an object with reason, check, interval (seconds), next_check_at, last_check_at, last_check_exit and cwd; individual values can be null. A human wait has no check. |
claim | Active claim or null. Contains actor, on_behalf_of, claimed_at, lease_until, worktree, host, agent, terminal, and optional pinned launcher. A waiting session’s released claim is not an active claim. |
deps | When requested, blocked_by and blocks arrays of {id, title, state, priority}. List/ready and ordinary show include dependencies. |
derived | Computed read-time state: ready, blocked_by (unclosed blocker IDs), due, and unblocks_higher_priority (objects with id and priority). When blockers exist, also progress: {total, closed}, including closed blockers in the total. |
created_by, created_at, updated_at, closed_at | Authorship and timestamps; closed_at is null before closure. |
Additional fields depend on context:
linksappears only when nonempty; each entry hasurland an optionallabel.wake_countappears when positive and the issue is waiting or claimed.show --with notes,events,claimsadds the requested arrays (--with alladds all three). Notes haveseq,actor,at,body,amends,to_agent. Events use the timeline shape above. Historical claims addreleased_atandrelease_reasonto the claim shape.showaddsroutingfor a known issue type, including the resolved worktree policy. MCPget_taskincludes notes, dependencies and its session’s routing.
Timestamps are RFC 3339 UTC with second precision, such as
2026-11-21T18:02:11Z; relative times are a pretty-output presentation only.
Derived fields are not stored. See sessions for claim metadata and
waiting and checks for waiting state.
Check results
A normal single trk check --json pass returns data shaped like:
{
"busy": false,
"results": [
{
"issue": "orch-4kq",
"title": "Add claim leases",
"result": "retry",
"exit": 75,
"timed_out": false,
"duration_ms": 12,
"state": "waiting",
"next_check_at": "2026-11-21T18:07:11Z"
}
]
}
result | Outcome |
|---|---|
passed | The check exited 0 without timing out; the issue closed as done. |
retry | The check exited 75 without timing out; the issue stays waiting and another check is scheduled. |
failed | The check failed, timed out or could not run, and the issue reopened rather than waking its previous session. |
woken | A failed check restored the waiting session’s claim and delivered the wake message. |
skipped | Concurrent changes made the result inapplicable, so trk did not apply it; this can also occur during wake recovery. |
Each normal result includes issue, title, result, exit, timed_out,
duration_ms, state and next_check_at. exit can be null if the command was
killed or could not start. failed and woken also include output (combined
stdout and stderr with trailing whitespace trimmed). state and next_check_at
are the issue’s values read after processing, not a promise that another actor
will not subsequently change them.
--dry-run instead returns result entries with result: "would_run", issue,
title, check, reason, cwd and problem; it does not run commands.
A busy queue is a successful result with busy: true, holder and results, not
a busy error. Optional gc describes the advisory cleanup sweep and its errors.
A failed check is also a result, not a command error: a completed pass exits
0 even if it reports failed, woken, or cleanup errors. Errors such as an
invalid explicit issue/check request still use the error protocol below.
Errors and process exits
After CLI argument parsing, command errors in JSON and JSONL modes are written to stdout with the same schema version:
{
"ok": false,
"schema_version": 4,
"error": {
"code": "blocked",
"message": "orch-9xa is blocked by orch-4kq",
"issue": "orch-9xa",
"blocked_by": ["orch-4kq"],
"hint": "close its blockers first, or remove the edge with `trk dep rm`"
}
}
code and message identify the error. issue and hint are optional, and
code-specific detail keys (for example blocked_by, claimant, candidates,
allowed or problems) are merged into the error object. Do not assume that
every failure supplies a hint or issue ID.
| Exit | Meaning | Error codes |
|---|---|---|
| 0 | Successful command/result | No error code. |
| 1 | Internal or compatibility error | internal, db_corrupt, newer_database |
| 2 | Usage error | bad_args, bad_query |
| 3 | Not found | not_found, ambiguous_id, not_installed |
| 4 | Validation failure | invalid_field, invalid_state, cycle, config_invalid |
| 5 | Conflict or ownership restriction | claimed_by_other, not_claimant, blocked, busy, not_permitted |
Argument-parser errors occur before the renderer exists: unknown options,
missing required CLI arguments and invalid option values use the parser’s
stderr text and exit 2, even with --json. Help/version output is also not a JSON
envelope. Pretty-mode command errors go to stderr. Warnings and diagnostics can
appear on stderr separately from a valid stdout JSON document; keep the streams
separate. The MCP server has its own tool error behavior.
Implementation: renderer, read models, check runner, and error codes.
Development
For development: cargo build, cargo test --workspace --locked, and cargo lint.
cargo lint runs cargo clippy --workspace --all-targets -- -D warnings, rejecting
compiler and Clippy warnings in every workspace target, including tests and examples.
Keep build outputs local to each issue worktree; do not point CARGO_TARGET_DIR
or --target-dir at the primary checkout. Seed-dependent tests materialize the
installer’s embedded defaults in temporary directories, so their binaries also
work after the checkout they were compiled in has been removed.
GitHub Actions runs the workspace tests, lint, and Herdr mod tests on
ubuntu-latest and macos-latest for pushes and pull requests. CI reads the Rust
toolchain version from workspace.package.rust-version in Cargo.toml and uses
Node.js 24 for node --experimental-vm-modules --test herdr/mods/trk/main.test.mjs.
Releasing 0.1.0
The first public release is 0.1.0 (beta). A human performs the release after
the release changes have landed on main; agents must not create or push the tag.
-
In the release checkout, ensure
mainis up to date and the working tree is clean. Confirmworkspace.package.versioninCargo.tomlis0.1.0. -
Review CHANGELOG.md, replace the pending release date with the actual release date, and commit and land that change before tagging.
-
Run
cargo test --workspace --locked,cargo lint, andnode --experimental-vm-modules --test herdr/mods/trk/main.test.mjson the release commit. Resolve failures before proceeding. -
Finish any active trk sessions before running
./install.sh, thentrk --version. A Git checkout build printstrk 0.1.0 (<commit>), where<commit>is the build’s abbreviated Git commit (requested at 10 characters, longer if needed for uniqueness). Check that it matches the release commit. Without Git metadata, it printstrk 0.1.0. The version comes from Cargo plus the build commit, not the tag name. -
Human only: create an annotated tag on that tested commit and push it:
git tag -a v0.1.0 -m "trk 0.1.0" git push origin v0.1.0
Before installing the release, users should finish active sessions and follow the upgrade procedure.
Layout
| Crate | Role |
|---|---|
trk-core | The state machine, claims and leases, the waiting queue, query language, Store (the only writer) |
trk-agent | Agent definitions, the eight trk tools and their executor, prompt rendering, harness profiles, launch spec |
trk-mcp | The per-issue MCP server (rmcp, single-threaded Tokio) |
trk-cli | The trk binary, rendering, trk check, trk run and the launcher templates |
seed/ holds the default configuration, embedded into the binary for trk install.
herdr/ holds the Herdr mod and layout, embedded the same way.
Notes on the implementation
- Harness names: the Claude Code profile is
claude-code, matchingagent:claude-code:<id>. A harness is registered the first time one of its sessions acts. - omp (verified live): reads
<worktree>/.omp/mcp.jsonand shows MCP server instructions to the model, so no folding is needed. Its--toolsflag hides MCP tools that are not listed, so profiles use a MiniJinja loop overtrk_toolsto prefix each tool name withmcp__trk_. It keepswriteavailable even with a restricted--toolslist, sobuiltin_tools = "read-only"is not fully enforced there. - Claude Code (verified live on 2026-11-24, version 2.1.331,
--model sonnet, resolved to Sonnet 5.5): tested in throwaway Git repositories throughtrk installandtrk run, with Herdr/hcterminals. The original profile stopped at workspace trust; after approval its default auto mode did not prompt for MCP or Bash. The explicit-permission profile started in a fresh repository without manual input, received MCP server instructions, calledget_task/add_note/wait, created and edited a file, committed in its issue worktree, and landed throughtrk checkusing the seed merge recipe. Failed-check wake andtrk sendacknowledgements were verified.read-onlyandnonewere also exercised live. - Unverified harness profiles: the Codex, OpenCode and pi profiles were not run live.
- Session liveness comes from the local claim’s terminal via its pinned launcher’s
existsoperation or Herdr driver. MCP pid, host and exit metadata inactor.metareport MCP status separately, not session death. trk checklock: a row holding the pid and host of the running pass. A holder whose process is gone on this machine is replaced; a holder on another host is never replaced automatically.TRK_NOWfixes the clock, for tests.
Building the manual
The manual is built with
mdBook. Install the version pinned in
.github/workflows/pages.yml, then build or preview from the repository root:
cargo install mdbook --version 0.5.4 --locked
mdbook build
mdbook serve --open
book.toml uses docs/ as its source and docs/SUMMARY.md as its navigation.
Add new chapters to the summary; generated HTML goes in the ignored book/
directory. Use relative links between chapters and absolute GitHub URLs for
repository files outside docs/, so links work both in source and on Pages.
The Manual workflow builds pull requests, pushes to main, and manual runs.
Only builds on main deploy, using the github-pages environment. A repository
administrator must enable Settings → Pages → Build and deployment → Source:
GitHub Actions before the first deployment. No deployment branch or token
secret is required; the deploy job uses the workflow’s Pages and OIDC permissions.