A label-driven autonomous ticket pipeline for any GitHub repository. Issues
labelled ready-for-agent are claimed by a coding agent in a git worktree,
gated by your own deterministic checks, reviewed by a second model, opened as a
PR, and landed on main once the gate, the reviewer, GitHub CI, and freshness
against main all agree. Anything the pipeline cannot resolve is handed back
with a ready-for-human label and the evidence attached.
It runs on your machine, on a systemd timer, with the agent CLIs you already
have. State is GitHub (labels, comments, PRs) plus a gitignored .factory/
directory; the dispatcher itself is stateless and safe to re-run.
needs-triage ──factory triage──▶ ready-for-agent ──factory dispatch──▶ agent/<n> PR ──merge stage──▶ main
│ │ │
▼ ▼ ▼
needs-info ready-for-human factory-approved
Two ways in; both end with the same factory CLI on your machine.
Have your coding agent do it: install the skill and ask the agent to set up the factory in your repo. The skill installs the CLI if it is missing, writes the config from your CI, and runs the doctor.
npx skills add mikeroysoft/factoryOr by hand. Linux, Python ≥ 3.11, git, gh (authenticated with push access), and:
- a worker agent CLI that accepts a prompt file and works in a directory
(default
omp -p;droid,codex exec,claude -p, … work the same way) - optionally, a manager agent CLI that accepts a prompt file and works in a directory
- a reviewer CLI that answers an inline prompt on stdout (default
omp -p --model anthropic/claude-fable-5-1;codex execworks the same way) - optionally, an OpenAI-compatible local model for triage (Ollama, vLLM, llama.cpp, LM Studio)
uv tool install git+https://github.com/mikeroySoft/factory@stable # stable: released channel
uv tool install git+https://github.com/mikeroySoft/factory@main # latest: tip of main
uv tool install git+https://github.com/mikeroySoft/factory@v0.4.11 # a specific releasepipx install and pip install --user take the same URLs. The repository's
default branch is main, so a bare URL installs development code. Select
@stable explicitly for the released channel or a version tag for a fixed release;
see CHANGELOG.md. TOMLKit is installed automatically for comment-preserving settings updates.
cd your-repo
factory init # .factory.toml, .gitignore, issue template, labels
$EDITOR .factory.toml # put your real test/lint commands in [[gate.check]]
git add .factory.toml .gitignore .github/ISSUE_TEMPLATE && git commit
factory doctor # tools, auth, remotes, model, dashboard port and .factory safety
factory install --dashboard # systemd user timer every 10 min + dashboard on :8765factory install enables and starts new units. On reinstall it snapshots each
unit's enabled/active state before rewriting files and running daemon-reload.
Existing stopped or disabled timers and dashboard services stay paused, even
when their unit files change; enabled, active units retain the usual restart
behavior when changed. This also applies to the optional probe and eval timers.
Install lists paused units with a systemctl --user enable --now <unit> resume
command. Use factory install --enable (with --dashboard when needed) to
explicitly enable and start all installed units.
If is-enabled fails without stdout (as on older systemd versions), install
checks LoadState to confirm a missing unit. An inconclusive query aborts before
unit files are changed, rather than treating a query failure as a fresh install.
doctor checks the configured dashboard bind address and port; install --dashboard
refuses a foreign or unidentified holder before writing units. Each factory needs
its own [repo."owner/name".dashboard] port in the host config. The preflight cannot
reserve the port until systemd starts the service: a later bind failure exits 1
with a one-line diagnostic, and the existing systemd restart policy still applies.
District drain (host-wide scheduled-pass admission). factory install puts
ExecCondition=<python> -P -m factory drain-check first in each pass service,
before triage. Exit 0 admits the whole pass; exit 1 skips it without failing the
unit. watch ignores the resulting SERVICE_RESULT=exec-condition; a skip adds
no lifecycle failure or failure-metric sample. Dashboard, triage-probe and eval
units are not gated. Timers fire normally: the drain feature never changes their
state. Hand-run triage, dispatch and gate remain ungated.
District atomically writes (same-directory temporary file + rename) and removes
${XDG_STATE_HOME:-$HOME/.local/state}/district/drain, one UTF-8 JSON object per
host user. Schema 1, with RFC 3339 UTC timestamps and unknown keys ignored:
{"schema_version": 1, "requested_by": "district apply --drain", "reason": "engine 2ad8846 -> e84004a",
"pid": 12345, "created_at": "2026-11-02T14:30:00Z", "expires_at": "2026-11-02T20:45:00Z"}expires_at is required. DRAIN_MAX_TTL is eight hours in both Factory and
District; District caps expires_at at created_at + DRAIN_MAX_TTL. Factory
decides once at pass start, using wall time and the file's mtime:
- No file: run. Stat failure: run, logging
WARN drain flag unreadable; ignoring. - Mtime more than 60 seconds in the future: run, logging
WARN drain flag mtime in the future; ignoring. - Valid JSON object and UTC
expires_at: effective expiry ismin(expires_at, mtime + DRAIN_MAX_TTL). Unreadable content, malformed JSON, non-object, missing/invalid expiry: usemtime + DRAIN_MAX_TTLand logWARN drain flag malformed. - Now at or after effective expiry: run, logging
drain flag expired at <effective_expiry>; ignoring. - Otherwise skip, logging
skipped: district drain (<reason or "malformed flag">, until <effective_expiry>). - Unexpected exceptions: log
ERRORand run, never accidentally skip.
A flag written after admission does nothing to that pass: no signals, shortened
work, or flag checks between triage, dispatch and watch. District still rechecks
busy work before swapping the engine, including hand-run work. A malformed fresh
flag blocks only until the mtime cap; district doctor diagnoses stale/malformed
flags and district drain --clear removes them. FACTORY_NOW injects RFC 3339 UTC
wall time for deterministic drain-check regression tests; leave it unset in service.
For hand-maintained launchd plists, begin the pass's shell script with this guard (Factory's installer here only renders systemd units):
factory drain-check || { echo "=== skipped: district drain"; exit 0; }
factory triage; factory dispatch; factory watchRollout: the new condition arrives through factory install, which still
re-enables an operator-stopped timer (factory#549). District deploys this through
its normal apply path (district#149); drain itself does not operate timers.
The liveness timer is opt-in. Set the systemd user service that owns the local
model in the host config, then rerun factory install:
[defaults.triage]
url = "http://127.0.0.1:11435/v1/chat/completions"
service = "rocm-serve-ornith.service"factory install then adds a per-repository two-minute timer that runs
factory triage-probe. Each run sends GET <triage base>/models with a
three-second timeout. HTTP 503 whose response says Loading model is alive;
three consecutive failures restart the configured service. Restart state and
the 15-minute cooldown are shared by repositories using the same service and
endpoint, preventing their timers from restart-looping it. Every failed probe
and restart is written to that repository's lifecycle journal. factory doctor
reports whether the liveness timer is active. Without service, factory install removes any old probe units and the manual command only reports and
journals failures; it never invokes systemctl restart.
factory doctor --json includes a fix object on actionable drift rows only:
kind: patch carries an advisory diff from the issue template to the shipped
version; kind: relocate lists host-setting key paths and destination tables;
kind: keys lists unknown configuration keys with their 1-based source lines.
Relocation payloads omit values unless explicitly requested with
factory doctor --json --reveal-fix, which adds a toml string containing the
values under their destination host tables. Treat that output as sensitive.
Doctor never applies these repairs; text output is unchanged.
Generated triage, triage-probe, dispatch and dashboard services use the interpreter
selected by host-owned, optional [install].python, or sys.executable (the interpreter running
factory install) when unset, followed by -P -m factory. Set
python = "/path/to/venv/bin/python" under [defaults.install] or
[repo."owner/name".install]; a committed [install] remains a host-setting warning.
The selected path preserves symlink identity and is rendered as one systemd
argument: control characters are rejected, and backslash, quote, $ and % are
escaped so systemd executes the validated literal path.
For a configured interpreter, doctor and a real install check the path and run
a 10-second probe from the repository working directory. Validation snapshots the
user manager environment read-only with systemctl --user show-environment,
parses its assignments, applies the PATH rendered into units, then overlays
[install].env. Failures stop installation before any mutation.
The probe loads every generated service command and reports the loaded Factory version
and location. It checks every loaded service module origin (factory,
factory.cli, factory.drain, factory.triage, factory.dispatch and factory.dashboard), with
the selected interpreter's purelib/platlib context as appropriate, rejecting
lexical origins under the repository root (cfg.root) unless within a selected
package root.
-P only prevents Python from automatically prepending the working directory:
PYTHONPATH and other explicit import sources still apply and remain
operator-controlled. Factory neither provisions the environment nor requires its
version to match the installer. install --print only renders the units; like its
other operational preflights, interpreter validation runs only for a real install.
To act on GitHub under a separate machine account, set host-owned
[install].dispatch_env (same shape as [install].env), for example
GH_CONFIG_DIR pointing at a gh config logged in as that account, plus
GIT_AUTHOR_NAME/GIT_AUTHOR_EMAIL/GIT_COMMITTER_NAME/GIT_COMMITTER_EMAIL.
Its lines are rendered only into the triage+dispatcher unit, after [install].env;
the dashboard unit keeps the human identity. The token stays in gh's store and is
never written into a unit. doctor then reports both logins (gh api user) and
fails when they are equal; unset, nothing changes. Worker and reviewer agents never
get a GitHub credential: the dispatcher drops GH_TOKEN/GITHUB_TOKEN and points
GH_CONFIG_DIR at a fresh empty directory for them. Workers only commit; the
dispatcher pushes agent/<n> with --force-with-lease=agent/<n>:<sha>, the remote
sha observed before the worker runs (or "" when absent), or the sha returned by
the previous successful push. Changes after that observation are refused (the
ticket escalates with lease_refused, worktree kept). Rewritten worker history
(e.g. a rebase) can replace commits already present at lease-read time even when
absent locally. Linear work is refused if it still omits a leased head absent
from its starting history. Starting-history state ends at the first push or
ticket exit, so it cannot affect later refresh or manager FIX pushes.
No other ref is force-pushed.
Review-request opt-in accepts requests naming either the dispatcher's or the
dashboard's login.
Then file an issue with the Agent task template (Scope / Touches / Exit
gate / Out of scope). It gets needs-triage; the next pass triages it; if it is
fully specified it becomes ready-for-agent and is picked up.
For shared, longer-lived plans, file an issue with the Initiative template
(Status / Outcome / Owner / Areas / Boundaries / Plan / Open decisions /
Success evidence / Implementation links). It gets only initiative, never
needs-triage; discussion and edits on the issue are the collaboration
surface, and factory plan reads it. Status (proposed, shaping, ready,
underway, delivered) and Owner are declared facts, never inferred from
child closure and not grants of permission. The initiative label is an
unconditional execution guard read fresh at every boundary: triage never
promotes an initiative (no model call), the dispatcher never claims one even
with --ticket, the manager never assesses or manages one, and the merge stage
never merges an agent/<n> PR whose ticket #n is an initiative. Refusals are
logged (also in --dry-run) and mutate nothing: no labels, assignees, comments
or escalation packets. A stale frontier row cannot bypass the fresh read.
The dashboard's Roadmap view and the read-only FM use the same Python
initiative, decision-routing and immutable-binding producers. The roadmap shows
declared Outcome and stage, implementation evidence, open decisions, blockers,
and accepted-versus-observed revision drift. These are different kinds of
evidence: a declared delivered stage, closed child ticket, or merged PR does
not establish delivery. Outcome success still requires owner-confirmed evidence;
the reader does not authenticate an issue-body declaration as that confirmation.
The shared list uses the dashboard's existing 15-second cache; Refresh requests
new evidence. Targeted initiative reads are collected directly.
The owner/team selector filters questions, not the canonical plans or their revisions. It is not login, assignment, permission, or a notification receipt. Selected owners, candidates, invalid declarations and unknown ownership retain the routing producer's meaning. Organization context validation does not prove team membership or notification delivery. Unknown owners remain visible as an attention gap rather than an empty work list.
Coverage is explicit: failed, partial and incomplete reads are not successful empty results. A ticket without an accepted baseline has unknown drift, not “unchanged” drift. Complete authoritative content determines revision identity, including edits beyond the 4,000-character display projection. Retained accepted evidence remains readable when the live initiative is unavailable; later edits never amend an admitted execution snapshot.
An assigned ticket with evidence of no active execution is shown as non-runnable
human takeover, not as invisible queue starvation. The exception is Factory's own
claim: a journaled claimed/pr-opened receipt with no later escalate marks the
ticket as held in Factory's review/merge pipeline, not a takeover. Incomplete runtime
evidence instead leaves execution responsibility unknown and asks for human verification.
Changing the attention filter or replying to a question cannot release it. Humans
must arrange any retry through the existing reviewed ticket/assignment/intake workflow.
The roadmap adds no mutation controls or new model call. Full accepted snapshots are kept out of shared briefing duplication; use a targeted initiative/drift read for revision evidence. Discussion and session-only FM proposals remain proposals, not accepted shared policy. The one-runner boundary and all existing holds remain in force. This implementation is not the distinct-runner/two-human live acceptance pilot tracked by programme #52 and issue #59.
An implementation ticket can opt in to an immutable initiative revision with an
Initiative: #N declaration and a fenced JSON object under either
**Plan baseline** or ## Plan baseline. The baseline object has
schema_version: 1, the integer initiative, a sections object containing
exactly Outcome, Boundaries, Plan, and Success evidence, a sha256,
the exact source_url (https://github.com/OWNER/REPO/issues/N), and a
timezone-bearing observed_at. Factory reads the complete initiative body
through the REST issue endpoint, not the bounded display projection.
For the digest, each relevant section first converts CRLF and CR line endings
to LF and strips whitespace only at the section edges; internal whitespace is
retained. Factory then hashes the UTF-8 encoding of
json.dumps(sections, sort_keys=True, ensure_ascii=False, separators=(",", ":"))
with SHA-256. The same parser and normalization drive baseline validation and
later drift, so changes beyond display limits cannot look unchanged. Changes
inside canonical non-scope sections (such as Status, Owner and Open decisions),
issue metadata, and GitHub discussion comments do not change this digest.
Only the initiative template's named headings delimit sections; free-form
subheadings within a relevant section remain part of that section and its digest.
Admission fails closed with a specific reason when a linked ticket has a
missing, malformed, ambiguous, mismatched, incomplete, deleted, or inaccessible
binding or source. A successful admission journals a schema-1 plan-bound
event with the accepted baseline and the ticket's complete title, body, and
comments. That whole accepted ticket snapshot remains the human-approved
execution contract: every retry reuses it and cannot adopt later ticket-body or
initiative revisions. A previously bound ticket cannot downgrade itself by
removing the link or baseline. Legacy tickets that have never declared an
initiative remain unchanged.
A later explicit admission records a new complete ticket snapshot without
rewriting the evidence or contract of earlier attempts.
Briefing event summaries retain revision metadata rather than duplicating the
full snapshot, so later attempts, escalations and handoff evidence keep their
context budget. The complete accepted evidence remains in the journal.
factory plan baseline N is read-only and returns a proposed object under the
schema-1 response's top-level baseline key. factory plan drift TICKET is
also read-only: it loads the latest accepted plan-bound evidence before
querying the live initiative and writes status, baseline, observed,
changed_sections, proposed_question, and attribution under the top-level
drift key. Status is unchanged, changed, or unavailable; changed results
name only the relevant sections, while unavailable results retain the accepted
snapshot and set observed to null. Attribution is always unknown, never
guessed from the current issue author when plan history is unavailable.
To rebaseline, generate a fresh proposal after the initiative edit, have a human review and replace the ticket's fenced baseline, then send that ticket through the ordinary intake workflow. Comments are discussion only: Factory has no comment command that rebaselines or expands execution authority. Once a ticket is bound, wholly unlinked work belongs in a new ticket. A currently running contract never changes in place.
Manager REWRITE may retain existing behavior only when it preserves the
accepted Initiative link and baseline exactly. SPLIT children inherit that
same binding; Factory validates the complete live source before creating any
child. A child of an unlinked parent may declare its own binding, but it must
pass the same validation. Any missing, invalid, drifted, or unavailable source
rejects the whole split before the first child reaches needs-triage; the
manager cannot supply a replacement baseline.
Preserving the binding allows the existing rewrite-and-requeue behavior; a
later admission records its own full ticket snapshot and leaves prior
plan-bound evidence intact.
GitHub issue-body writes remain last-write-wins. Refresh the issue immediately before editing and use discussion to propose revisions first. The pinned snapshot protects admitted execution; it is not concurrency control for simultaneous human edits.
For a fork that tracks an upstream, set [repo].upstream = "upstream". When
upstream main moves, the dispatcher stages a candidate in a detached worktree
(the upstream tip merged with --no-ff, or, when the tip conflicts, the newest
conflict-free prefix) and runs the host gate on it, then files one
upstream sync: issue labelled ready-for-agent with the exact merge and gate
evidence and hands the candidate to that issue's agent/<n> branch. From there
it is an ordinary ticket: a clean candidate whose staged gate passed goes
straight to the PR and review; otherwise the worker repairs it within
max_attempts/budget_min, the gate reruns after every attempt, and exhausted
attempts escalate like any ticket. The worker gets no bypass: its gate
(factory gate --upstream <tip> --upstream <staged head>, also on refresh)
ignores only protected-path hits whose content equals the dispatcher's staged
candidate's, or the upstream tip's for a path upstream itself changed; a
fork-only protected file the worker deletes, resets to upstream's version, or
edits still fails protected-paths unless a human applies
factory-protected-override. Add-only edits require
factory-add-only-override, which the manager or a human may grant.
It leak-scans the diff from the tip, so
anything the worker writes is scanned while upstream's already-public content
is not. A passing gate is rejected unless the head still contains the recorded
upstream tip. Nothing moves main before the merge stage lands the reviewed,
CI-green PR, which merges (never squashes) the upstream ancestry. One open sync
issue, worker- or human-owned, parks the stage until it closes. A persistent
conflict therefore delays the whole upstream batch: a staged prefix is not
landed on its own, and partial progress needs its own reviewed PR.
| Command | What one invocation does |
|---|---|
factory claims --supported |
Prints exactly host-claims 1 and exits 0 for District's multi-host capability check. Works offline outside a repository; bare or other arguments exit 2. |
factory triage |
Labels every needs-triage issue via the local model: ready-for-agent (with an agent brief), needs-info (with the question), ready-for-human, or wontfix-proposal (proposal comment and label; a human closes). An issue unchanged since its last triage comment is skipped. After two consecutive unparseable model decisions, it comments once, records triage_stalled, and keeps the issue for retry. --dry-run, --issue N, --replay a,b,c. |
factory triage-probe |
Sends GET <triage base>/models with a three-second timeout. A 503 Loading model response is alive. After three consecutive failures it restarts [triage].service at most once per 15 minutes; failures and restarts are lifecycle-journaled. With no service configured it reports only. |
factory dispatch |
One stateless pass: fetch and detach the main checkout at origin/<main> before .factory.toml is read (a root with tracked or untracked changes outside .factory/ exits 1 with a root_dirty dispatcher exit row naming the paths and does nothing, even when its config does not load) → upstream sync (stage a sync ticket) → merge stage (at most one PR) → review-only PR intake → manager → claim up to max_active tickets, worked concurrently → worker plan → worker → gate → PR → review → up to review_rounds bounces. --ticket N forces one issue; --dry-run prints the plan from the checkout as it is. |
factory explain N [--json] [--since ISO] |
Reads the live .factory/events.jsonl and retained events.jsonl.N.gz segments without writing. JSON mode returns {ticket,nodes,edges,loops,cost,frontier,frontier_stage,coverage}; cost totals the ticket and each retry loop has its own total. frontier_stage distinguishes gate, review, manager, human, merge eligibility, and blocker waits; merged and wontfix tickets have a null frontier. Text mode prints a compact decision tree. Legacy claimed, attempt, review, approved, merged, and escalate rows become synthesized: true nodes, while coverage names part-1 stages with no structured record. Output is bounded to the runtime projection's 1 MiB limit. |
factory manage |
First recommends directions for needs-review PRs, then needs-viability issues; then resolves untouched ready-for-human escalation packets within [manager].rounds; finally publishes one routed human handoff request per escalation whose automatic recovery is terminal (also without a manager). --dry-run lists eligible requests without inference or writes. |
factory gate |
Runs the deterministic gate in the current worktree and writes a Markdown report. Workers run it themselves; the dispatcher re-runs it as the evidence of record. |
factory watch |
Post-ship monitor from local evidence only: lifecycle exit rows with mechanism_failure (or unknown with a check_timeout reason, plus unparseable_decision after triage records its two-pass triage_stalled streak), failed factory-* user units for this repository, factory dashboard --runtime-json failures (only the reader's failure-severity journal defects, runtime_events.FAILURES; every other reader code is coverage and never filed, see runtime contract), and one escalation code repeating on ≥3 distinct tickets in the trailing 7 days (except ticket outcomes: budget, when a ticket exhausts its configured overall runtime; gate_failed, when a ticket's project gate fails; ci_failed, when a ticket PR's checks fail; pr_feedback, when a ticket PR has unresolved feedback on its head; no_change, when a worker committed nothing and wrote its handoff because its ticket was already fixed or a duplicate; and review_revise, when review still requests changes after bounded review rounds, a manager FIX, or a merge-stage refresh/rebase). A no-commit worker without a handoff stays pr_unpublished and counts. Host conditions (worker_exit:*, triage_endpoint_*, github_command_failed) remain ignored until their current uninterrupted streak spans [watch].host_failure_minutes (default 60), then file as host; a later successful pass clears the streak. A gap between failures longer than that threshold starts a new streak, since idle successes may leave no journal row. Every signal files into one engine repository, [watch].engine_repo (default mikeroySoft/factory), never into the repository it runs in. Each distinct fingerprint (sha256 of kind and reason/unit role/source, 12 hex, so one reason hitting several stages, one journal source reporting several codes, or the same host condition or unit failure in several installs is one issue; escalation:<code> for repeats) files one bug,needs-triage issue, plus host for a host condition, carrying the fingerprint, an Observed by list of installs, the triggering journal rows, the newest attempt log tail, the unit status or the runtime failures with what they point at (the offending journal line, the conflicting execution's rows, the reader's stderr; for repeats: each ticket, its prose reason and escalation packet path), the reproducing command and an "Expected behavior" section; the filing is journaled as a watch row. Before filing it lists the engine repository's open bug issues: when one already carries the fingerprint (another install filed it), the install comments its newest evidence there, at most once per 24 hours per install, and adds itself to Observed by instead of opening a duplicate. escalate rows without a code are unknown and never filed. Never refiles while that issue is open; refiles once it is closed and the signal recurs. An unassigned filing still at needs-triage or ready-for-agent closes after 24 hours without newer evidence, including after a successful pass clears a host condition. At most 5 filings or comments and 5 closures per pass. --dry-run prints what would be filed or closed without gh. factory install runs it from the pass unit's ExecStopPost=, after every dispatch, crashed or not. |
factory stats |
Ticket table: attempts, review rounds, hours to merge, escalation count, resolver attribution, minutes in ready-for-human, re-queues, and triage/review/worker prompt and completion token sums (reported prefix-cache rates listed separately). Worker tokens come from the worker's [workers.<label>.usage] log paths or, for OMP workers, the session transcript totals; a ticket whose worker reported none reads n/a (not reported), and the footer sums worker tokens over the tickets that reported them. Dollar columns appear only when some ticket has a cost; with no [prices] table the footer says so once. Reads GitHub plus events.jsonl from the dispatcher's root: the host config's [repo."owner/name"].path for --repo owner/name or the current checkout's repository, else the current checkout itself; a root without .factory/events.jsonl fails naming that path instead of printing empty rows (--escapes reads only git and GitHub). Per-ticket GitHub reads run 8 at a time with stats: N/M tickets progress on stderr (--quiet hides it). --by-worker reads only events and shows every configured worker label: first-attempt gate pass rate, all attempts (including review bounces), and known cost. Attribution uses claim labels with current worker precedence; unclaimed attempts are excluded, missing rates/cost are n/a. The dashboard Ops view shows the same worker metrics. --escapes lists candidate escaped defects, one row per closed bug issue: its fix commits (first-parent agent/<bug>: commits on origin/<main>, else the merge commit of a merged PR whose closing references include the bug), and the candidate tickets whose agent/<m>: commits git blame names for the lines the fix modified or deleted, with blamed line counts. Rows without candidates read unlinked (no fix commit), no_blamed_lines (the fix only adds lines) or no_candidates (blamed lines are not from agent commits). A fix commit missing from the clone is fetched with git fetch origin <sha>; one still missing is skipped with a stderr warning, listed in the row's skipped, makes the row skipped when every fix was, and is counted in a Skipped fixes: N footer. Regressed-by: #N lines in the bug body replace blame (source is declared, else blame). The footer reads Candidate escapes: X of Y merged agent tickets (Z%). Blame is SZZ-style and noisy: refactors give false candidates and add-only fixes give none. Read-only. --json. |
factory stats --week [--json] |
Reads the live and rotated journals over the trailing seven days and reports distinct merges, human touches, escalations by code, pooled rate numerators/denominators, and tokens by stage/model. Human touches match the release bar: each nonempty human-decision decision ID counts once across statuses and targets (including prepared-only decisions), each legacy row without an ID counts separately, and every manager HUMAN row counts. Legacy usage locality falls back only to the configured triage model id. One separate 10-second gh issue list finds ready-for-human tickets unchanged for seven days; failure leaves stuck_over_days unavailable and the command successful. |
factory stats --promotions |
Lists every merged lessons/CURATE PR (promotion-open) with its baseline and after-window efficiency_mean, compliance_mean, gate_first_pass_rate, and n, decision (open, keep, or revert), and revert branch, from events.jsonl alone. --json. |
factory learn |
Reads the last N finished tickets' event trail, reviewer findings, and escalation reasons, plus for each ticket an excerpt of its lowest-scored session (factory score rows: lowest efficiency, ties to the lowest compliance, then a gate FAIL): every call repeated back to back, the worker's final message, then every tool call whose result mentioned error/Traceback/FAIL (the call and the result's first 10 lines), at most 3,000 characters per ticket, so the cap only shortens the flagged-call list; a ticket with no score row falls back to its failing-attempt log tails. Adds the 10 most recently closed bugs with candidate escapes (factory stats --escapes); asks the local model for ≤10 repo-specific lessons; writes .factory-lessons.md with the repository SPDX identifier (NOASSERTION when unavailable; you commit it). Every worker prompt carries it. With a manager, the lessons land as an agent/lessons-<date>-t<N> chore PR (N: the newest included ticket), and the manager may add a CURATE diff, opened as agent/curate-<date>-t<N>, that turns a lesson into a gate check or regression test: AGENTS.md, CONTRIBUTING.md, .omp/skills/, add-only .factory.toml (appended [[gate.check]] tables and [gate].protected_paths entries) and files under the base ref's protected and add-only paths; never .github/, never a deleted or renamed protected or add-only file. New PRs run the attempt gate in their throwaway worktree before the push (journaled as gate bound to the head; a FAIL opens nothing); an approved legacy head with no gate row is checked once during promotion. PRs are reviewed by review_intake_pass like a needs-review PR and are merged by the merge stage (learn.promote_pass, on merge_pass_locked's PR listing) once a gate PASS and a review-result APPROVE are bound to the PR head, CI is green and no human requested changes: add factory-approved, squash merge, then journal one approved, merged, and promotion-open {pr, head, branch, baseline} with the efficiency_mean, compliance_mean, gate_first_pass_rate and n of the last 10 score rows before the merge. Every behind lessons or CURATE head is refreshed before merge, including lessons-only diffs. learn.refresh merges origin/main, gates the merged head, pushes without force, and reviews it again for a later pass. Strict-base and required-check refusals also trigger refresh, including legacy same-head merge failed: blockers for those refusals; a failed refresh is attempted only once per head, and new heads expire old blockers. Repeated blocked passes add one promotion-blocked row per PR, head, and reason. A human merge is reconciled on the next pass as merged {by: human} and opens the same measurement. A failing PR is logged and the others still merge. Once 10 attempts journaled after the merge are scored (a pre-merge attempt scored late never counts), the end-of-pass learn_pass journals promotion-keep, or promotion-revert and opens agent/revert-lessons-<pr> (same gate/review/merge path; it opens no promotion of its own) reverting the merge commit with the before/after means in its body, when efficiency_mean or gate_first_pass_rate fell by more than the population standard deviation of the baseline window (promotion.drift). One decision per promotion, never replayed; factory stats --promotions [--json] lists them. With a manager, the dispatcher also runs --last 10 itself after every 10 finished tickets, scoring those tickets' unscored attempts first (see Learning loop under Operating it). --dry-run, --last N. --promotion claim.json judges and records a keep/revert claim under the eval promotion contract. |
factory eval --profile NAME [--dry-run] |
Replays the checked-in 20-case Factory/rocm-cli worker suite twice per case in isolated local clones with each repository's normal gate and reviewer. --dry-run lists every pinned repository, ticket, base, split and the [eval] case/token/wall budget. Real runs append one eval row per case/repeat and an eval-summary with split means/noise; an accepted-main run establishes the baseline and later runs feed a regression claim to promotion.decide(). Rejected and unmerged candidate runs never replace that baseline. Budget or replay failure records not_tested without escalation. --scheduled marks the weekly drift run. |
factory score |
Scores every finished ticket's worker attempts from their persisted OMP transcripts (attempt.transcript) and journals one score row per attempt: tool_calls, edits (edit/write calls), retries (identical consecutive calls), gate_first_pass (attempt 1 with gate PASS), efficiency = 1 / (1 + retries + max(0, tool_calls - 40) / 40), and compliance, a 0–1 LLM-as-judge score from the local triage model given the ticket's Scope and Exit gate sections against the worker's final message and handoff (null, never a guess, when the model is unreachable or answers with anything but a number; judge_model names the model that answered). Already-scored attempts are skipped; a transcript missing on disk journals {"skipped": "missing"}. At most 50 attempts per run, 2 MB read per transcript. --last N limits to the newest N finished tickets; --dry-run prints without journaling. |
factory release [--dry-run] |
Converges a patch release across up to three passes: opens a release/vX.Y.Z PR after the ticket, quality-bar, main CI, and release-tier gate checks pass; squash-merges it after its CI succeeds; then annotates the merged commit, advances stable, and publishes the tag's GitHub Release with its CHANGELOG.md section as notes. This respects the required gate check on protected main; --dry-run reports the current state and next action without writing. |
factory dashboard |
Native outcome-control workspace: Overview, Outcomes, live Flow, ticket Decisions, Attention, Success, Codebase, Atlas, System/Ops and Settings, with a persistent contextual FM dock. Defaults to 0.0.0.0; APIs require the workspace access key. --json prints a passive, bounded-window Ops snapshot without journal reconciliation writes. |
| factory dashboard --runtime-json | One bounded schema 1 runtime observation using only local read-only evidence; no GitHub, model probe, journal append, lock acquisition, or state creation. Partial source failures remain structured JSON. See runtime contract. |
| factory evidence --root /path/to/main-checkout | One explicit-repository schema 1 JSON read: compact cases, selected evidence, workflow/file/PR/CI investigations, or capabilities. Fixed read-only GitHub requests and F03 local evidence; no model, action execution, or state writes. See evidence contract. |
| factory mcp | Stdio MCP server (protocol 2025-06-18) exposing the four evidence reads plus host-registry discovery, and two write tools (factory_prepare_action, factory_apply_action) that run the named human actions through prepare, then confirmation, then apply, to one locally launched MCP client, across every repository registered with a path in the host config. Each evidence tool call runs one factory evidence subprocess; no resources, prompts, or network transport. See factory mcp. |
| factory plan list / factory plan inspect N | Read-only schema 1 JSON over initiative issues: declared status/owner, parsed sections, #N implementation links (inspect also fetches each linked issue's title/state), per-issue malformed + problems (missing/invalid declared facts, sections cut at 4,000 characters, links beyond the first 20), cited sources with observed_at. list reads at most 3 pages of 100 and keeps malformed initiatives flagged per row (exit 0); a failed page, or a malformed initiative under inspect, yields coverage.status: partial and exit 1, never a mutation. |
| factory plan route N --reason <requirements\|implementation\|ci\|unknown> [--path P]... --json | Read-only schema 1 JSON naming the human who owns a decision on ticket N; nothing is assigned, labelled or commented. JSON is also the default when --json is omitted. Priority: a **Decision owner** section in the ticket body (human override, wins on every recomputation), the canonical Initiative: #N (or legacy Programme: #N) initiative's Owner, or the initiative's own Owner when routing that initiative (requirements only), [collaboration.reasons], [collaboration.components] exact repo-relative path prefixes against the given --paths (implementation only; src/auth matches src/auth/x.py, never src/authentication/), then [collaboration].fallback. route.status is selected, candidates (paths span prefixes with different owners), unassigned (reason unknown, no --path for implementation, or nothing configured) or invalid (malformed declared owner; @org/team on a user-owned repository). route.revision ties the answer to the .factory.toml commit and issue updated_at; route.provenance lists every step. Owner syntax is checked, membership is not: an unreadable repository record leaves verification: unknown. Without a [collaboration] section only ticket sources apply. |
| factory plan baseline N / factory plan drift TICKET | Read-only schema 1 JSON for proposing a complete immutable initiative baseline or comparing a ticket's latest accepted baseline with the live complete source. Results are under top-level baseline or drift; neither command edits issues, rebaselines work, or grants execution authority. |
| factory doctor / init / install | Onboarding, above. |
Skill health comes from the same persisted worker transcripts: factory score
journals each read of skill://<name> or */SKILL.md as an idempotent
skill-load, plus skill-coverage for attempts without a transcript. The weekly
stats report ranks the top five skills by SKILL.md bytes/4 times loads, includes
all load failures, and suppresses post-load error rates below 10 sessions. Rates
compare the next 10 tool results with the same call positions in sessions that did
not load that skill. factory learn always includes load failures and adds at most
three 3,000-character tagged excerpts when a skill exceeds that matched baseline's
noise.
Lessons files generated by factory learn start with an SPDX header inferred from
the repository's package metadata or conventional licence file (NOASSERTION when
neither identifies one). Promotion re-gates an approved legacy PR head once when
its journal has no gate row. Behind lessons and CURATE heads merge origin/main,
re-run the gate, refuse a changed remote head, push normally (no history rewrite),
and receive a fresh review before a later pass can merge them. Promotion also
refreshes on strict-base or required-check merge refusals (not up to date,
is expected, or GitHub's BEHIND merge state), including legacy merge failed:
blockers for those refusals at an unchanged head. A failed refresh is attempted only once per head;
a new head expires old blockers. Other merge failures still require a new head.
Blocked outcomes and approvals are journaled once per head; merged is written
only after a successful merge. A human-merged lessons PR is reconciled on the
next pass with by: human and opens the same promotion measurement.
Merge CI and advisory review readiness verify each active base-branch ruleset's
required context against check runs on the caller's captured PR head, including
its source GitHub App (integration_id). A push before the first provenance read
keeps that head pending rather than borrowing the new head's green checks.
A same-name success from another app or SHA is
not evidence. App-unpinned contexts may use legacy statuses fetched by exact head
SHA (individual status objects have no SHA field); a pinned app requires check-run
provenance even when other requirements are unpinned.
Reads are paginated; a head/base change, unreadable evidence, or GitHub's
blocked/unknown merge state keeps CI pending. Already pending or failed CI
returns without fetching additional provenance.
Behind-main and conflicting (dirty) heads remain eligible only for the existing
merge callers' refresh path, not merge; advisory readiness still reports them pending.
PR #573's successful gate
runs 125588773738
and 125588741702
both have app ID 15368 and head 7a05cbf46ff7c00f66a36c1d01a951bc92c2e464,
matching protect-main.
The refusal was strict-base freshness, not a source-app/head mismatch:
#587 records behind_by: 4
and BEHIND at diagnosis, with strict required checks enabled.
When Git uses SSH commit signing, factory doctor checks the configured signing
key against the dispatcher GitHub account and warns with unknown_key when the
key is unreadable or unregistered.
factory stats exposes each structured review round as ordered
review_findings counts in JSON and as important/nit/pre-existing triples in
the ticket table.
Ticket reviewers receive origin/<main>...<gated head>: only changes since the
branch's merge base, not reverse patches for newer main-only commits.
Risk classification, mutation selection, and the High-risk changed-file check use
the same merge-base boundary. Explicit base_ref reviews keep their direct
base..head boundary. ./snapshot remains
the exact gated head, so missing later main commits alone are not reversions;
genuine reversals in the branch diff still receive normal blocking review.
Review policy still comes from the supplied base ref (current main by default),
not the candidate. External PR intake already uses GitHub's three-dot compare.
Ticket review events and review lifecycle results record
outside_diff_findings: citations outside the supplied diff's displayed head-side
hunk ranges (old-side ranges for deleted files, adjacent anchor for pure deletions).
This counts all validated findings before the nit cap, without filtering findings
or changing verdicts; unavailable/unparsed evidence records null.
Routing from triage through merge or wontfix writes event: "decision" rows
through the same flocked, rotating journal writer as other audit events. Schema 1 has:
{
"event": "decision",
"schema_version": 1,
"decision_id": "uuid4",
"ticket": 7,
"pr": 12,
"stage": "triage|binding|admission|worker_select|claim|plan|gate|review|manager|merge|wontfix|escalate|learn|curate",
"at": "2026-10-23T10:00:00Z",
"inputs": [{"kind": "github_issue", "ref": "https://github.com/owner/repo/issues/7", "summary": "bounded text"}],
"options": [{"option": "ready-for-agent", "eligible": true, "reason": "bounded text"}],
"chosen": "ready-for-agent",
"rationale": "bounded, credential-scrubbed text",
"causes": [{"decision_id": "uuid4", "relation": "follows"}],
"cost": {"prompt_tokens": 10, "completion_tokens": 2, "cached_tokens": 4, "seconds": 0.5},
"actor": {"kind": "model", "name": "triage", "model": "local-model", "version": "0.4.5"}
}pr is present when the decision has one; cost is null when no model or
wall time applies. A cause identifies either decision_id or ticket, with
relation follows, retries, blocked_by, split_from, unblocked_by, or
overrides. Inputs are limited to 16 entries and 256 characters per value;
rationale is limited to 2,000 characters. Token-shaped credentials are removed
before append. factory explain adds time-ordered follows edges within the
ticket, cross-ticket nodes for ticket causes, and collapsible groups beginning at
retries edges. Gate records carry the gated SHA, report and duration; review
records carry required findings and model usage; manager, merge, escalation,
learning and CURATE records retain the alternatives and evidence used.
Each non-chore attempt tells the existing worker session to write a plan of at
most 30 lines covering files, order, risks, and proof. Numbered revisions under
.factory/plans/current/ preserve course changes within the attempt. After the
worker exits, the dispatcher copies every revision beside its transcript under
.factory/transcripts/<ticket>/, journals an event: "plan" row with artifact
path and SHA-256, and records a plan decision with actor worker between claim
and gate. A missing plan records plan: "missing" without failing the gate;
chore attempts record plan: "skipped" and receive no plan prompt. This adds
no worker or model launch. The reviewer receives the latest plan artifact or
status and lists changed files the plan did not name and planned proof absent
from the gate report. Plan drift is evidence, not an automatic REVISE.
Before committing worker leftovers or running the attempt gate, the dispatcher
compares known dependency lockfiles with the ticket branch's merge-base. A
lockfile edit is planned only when pyproject.toml also changed against that
merge-base or any numbered plan artifact recorded for the ticket, across all
rounds, lists that lockfile. Ticket and brief wording is not considered.
Upstream-sync tickets skip this guard so Factory never overwrites a fork's
lockfile while synchronizing upstream. For every other ticket, Factory restores
unplanned tracked lockfiles from the merge-base and removes newly introduced
ones, so a moving main or incidental verifier drift cannot alter the gated and
pushed head. Repository gate commands that use uv run pass --frozen;
preventing uv from writing uv.lock is simpler than repairing the worktree
after the authoritative gate has run.
The workspace Decisions view (/?view=decisions&ticket=N, or /decisions)
reads the selected repository through authenticated GET /api/trace?ticket=N.
It renders the same graph unchanged as a stage-ordered breadboard with labeled
relationships, retry-loop costs, a timeline replay control, fit/zoom/pan and
fullscreen viewport controls, evidence details, coverage gaps, frontier state,
cross-ticket links, and terminal outcome. Mouse wheel and keyboard controls
share the same viewport state. Controls occupy a separate row above the canvas;
retry tracks and parallel gutters stay inside its bounds, including during spring
motion. Wires retain their node attachments after viewport, replay, resize, and
node-drag changes; genuinely offscreen endpoints use SVG clipping. The view is
read-only; legacy synthesized rows remain visibly dashed.
Successful non-dry-run triage, dispatch, and watch invocations atomically
update .factory/stage-success.json with that repository's last successful pass
per installed stage. factory stats --stages --json returns the repository slug
and last_successful_pass map without GitHub reads; text mode prints the same
three stages. Evidence observe and inspect include the map and cite the local
projection. factory doctor reports the timestamps (never until a stage has
succeeded); an unreadable or malformed projection is a warning, not a silently
missing metric.
factory init writes factory-bands.toml, the committed schema-1 control-band
configuration used by factory watch. Each [[band]] selects one daily metric,
its trailing window_days, and explicit rules. A sigma rule supplies
sigma, count, and span; a same_side rule supplies count and span.
Every rule declares a tier: log writes only the watch log and journal,
diagnose additionally asks the configured local model for a read-only summary,
and act uses the existing fingerprinted watch issue filing and closure path.
Per-test act rules also set min_tickets; only distinct tickets whose recorded
diff paths do not touch the test source count toward that threshold. Act never
opens a PR and writes only bug,needs-triage issues, comments, edits, or closures
in [watch].engine_repo.
The daily metrics are gate failures divided by gate outcomes; failed gate-check
and failed-test counts keyed by check or canonical test ID; escalated tickets
divided by merged-or-escalated tickets; mean hours from the first claimed row
to merged; and mean review rounds after the first review per terminal ticket.
Failed check/test counts exclude worker executions whose recorded head has not
merged. Failures are matched to their dispatcher run so reused attempt numbers
cannot borrow a later run's merged head. Each (ticket, attempt) counts at most
once per check or test metric. Rows without a complete ticket/attempt identity,
including main and legacy rows, retain their existing per-row counting.
Days without a denominator or completed cycle are omitted from rate, duration,
and rework bands; only failed check/test count metrics record zero on quiet days.
No rule runs until the journal's first row predates the full configured window;
factory doctor reports insufficient baseline meanwhile. The built-in
configuration uses a trailing 28-day mean and population standard deviation for
one of one beyond 3 sigma, two of three beyond 2 sigma, and eight of eight on one
side of the mean.
Gate-check result rows now carry failed_tests parsed from unittest FAIL: /
ERROR: summaries, pytest FAILED summaries, and cargo libtest failure
headers, plus changed_paths when at least one test ID was parsed. Earlier
journal rows named only the failed check and pass/fail result; they did not
contain a structured, parseable test ID.
factory watch also closes an open, unassigned issue it opened, still at needs-triage
or ready-for-agent (never one handed to a human), as completed when its
newest evidence (or its filing time) is at least 24 hours old, the failure is not
happening now, and no install has commented evidence on it in the last 24 hours. An
install that only commented never closes it. Each pass closes at most five; --dry-run
reports closures without applying them.
[release] auto = true runs the release check at the start and end of each
dispatcher pass. version_file defaults to factory/__init__.py, min_tickets
to 5, and bar_min_tickets to 20. bar_floor_human_rate defaults to 0.10 and
bar_floor_first_pass to 0.90.
The annotated tag's fenced JSON records human_rate (manager HUMAN and
human-decision rows divided by distinct merged tickets, uncapped; lower is
better), first_pass (PASS journal rows among attempt-1 rows; higher is better),
and tickets. The first tag written by this behavior also records the former
distinct-ticket metric as human_ticket_rate. Windows below bar_min_tickets
retain their raw pending counts in the tag; a later release pools those counts.
Once the pooled sample reaches the minimum, each bar moves halfway toward the
95% Wilson upper bound for human rate or lower bound for first pass, without
tightening past its configured floor. A legacy tag's bar is reset once to those
floors. A tag without a fenced bar resets the comparison, and a window without
attempt-1 evidence is held rather than scored as zero. Factory requires every
bar metric to be no
worse, all completed CI statuses and check runs on origin/<main> to pass
(success, skipped, and neutral check conclusions pass), and factory gate --tier release to pass in a temporary worktree. It then bumps the patch
version, moves the current Unreleased changelog entries under the dated release
heading, pushes the factory-owned release/vX.Y.Z branch, and opens a PR. The
release PR also updates README.md's fixed-version install pin and
docs/index.html's install pin, latest-release note, and top changelog history
entry built from the new CHANGELOG.md section. Each of those four spots must
appear exactly once; otherwise Factory refuses to create the release. A later
pass updates a behind release branch from main, closes and deletes a
conflicting one for rebuilding, or squash-merges a clean PR after its CI
succeeds, respecting the required gate check on protected main. Once the
version bump is present on main, a final pass creates the annotated tag on
the first commit that introduced that version and atomically advances stable,
then publishes the GitHub Release for the tag (gh release create <tag> --verify-tag --latest, titled with the tag, notes from that version's
CHANGELOG.md section). A Release that already exists is left alone; a gh
failure is journaled as a release row with outcome publish_failed and retried
at the start of the next pass, never rolling back the tag. A release therefore
takes up to three dispatcher passes when no branch refresh
is needed. The dispatcher advances an open release PR at the start of a pass,
before it lands a ticket (every ticket edits CHANGELOG.md, which GitHub cannot
union-merge), and opens a new one only at the end of a pass. Each pass derives
its state from remote branches, remote tags, and PRs (only a pending GitHub Release is read from the journal), so crashes need no local recovery file. Temporary worktrees are removed,
and local-only or stale local tags are ignored and removed before reuse. A
completed release journals one release row with outcome released, then one
with published (or publish_failed per failed attempt). A quality-bar hold
journals one release row with outcome held; later passes suppress another
row until the bar value changes.
Routing distinguishes absent optional information from invalid declarations. A missing
ticket Decision owner section permits fallback; an empty or malformed section stops
with invalid. A missing initiative Owner section permits configured requirements
ownership and fallback, but an explicitly empty or malformed Owner stops routing.
On user-owned repositories, mixed team/login destinations remain invalid with no
selection; provenance retains the original destinations and rejected teams for
diagnosis. Unavailable verification remains unknown, never authorization.
collaboration.reasons.unknown and component prefixes that normalize to the same
key are configuration errors; --reason unknown remains a valid non-guessing request.
Every command reads .factory.toml from the main checkout, even when run
inside one of its worktrees. A dispatch pass first pins that checkout to
origin/<main> (git fetch, git checkout --detach), so .factory.toml and
.factory-lessons.md come from the committed tip, never from a local branch or
uncommitted edit; keep the root clean and land config through PRs.
Worker and manager commands receive {prompt} as a prompt-file path and {cwd}
as the worktree (or repository root); reviewers receive {prompt} as inline
text. OMP loads a prompt file only when it is prefixed with @, so use
@{prompt}: bare omp {prompt} passes the path as prompt text. Factory rejects
that bare argument for manager commands, not worker commands.
Reviewers never start in a checkout: both review lanes launch the command in a fresh
temporary directory, so project config written by a worker or PR author (OMP
.omp/extensions, Claude Code .claude/settings.json, .mcp.json) is not discovered.
Ticket review gets ./review.diff (merge base to gated head, or the explicit
re-review base) and a read-only git archive snapshot of the gated head in
./snapshot; PR review gets the diff inline. GIT_* and
GitHub credentials are stripped from the reviewer's environment.
The dispatcher supplies the issue title, body, and every comment inline as untrusted
data: the worker's accepted snapshot for plan-bound tickets, otherwise its own
gh issue view --json title,body,comments read. Reviewers use that supplied issue
section, not GitHub or the worker's transcript. Learning-proposal reviews are unchanged.
Ticket review retries snapshot, diff, launch, and unparseable-output failures up
to three times, using exponential backoff unless the provider reports
retry-after or retry-after-ms. A nonzero exit with a validated verdict is
handled as that verdict; without one, it is a tooling failure, not worker feedback.
Persistent failure records reviewer_unavailable, preserves stderr or a structured
error event in the review diagnostics and escalation packet, and consumes no
review_rounds slot or change-request feedback event.
Keep {cwd} in worker and manager commands, and configure the manager CLI in
read-only/no-tools mode: the prompt prohibits file edits, but an arbitrary
configured executable is trusted, not sandboxed by factory. The manager reads
the packet, .factory-lessons.md, and optional .factory/manager/notes.md.
Its last DECISION: header selects RETRY, REWRITE, SPLIT, ROUTE,
AUTHORIZE, FIX, CLOSE, RESOLVE, or HUMAN, followed by the decision
body. RETRY/HUMAN/RESOLVE use plain text; REWRITE uses the
complete replacement issue body. SPLIT uses a JSON array of
{title, body, blocked_by} children, with blocked_by containing 1-based
indexes of earlier children. ROUTE uses {add, remove, guidance}, with label
arrays restricted to configured worker labels (not default).
Workers can use either the legacy argv array or a [workers.<profile>] table with
command = [...], optional when, and optional transcript = "omp-session".
A text when value is manager routing guidance. when = { label = "name" }
selects the profile directly when that ticket label is present, while keeping
the profile name stable for factory stats --by-worker; otherwise the profile
name itself remains its ticket label. First configured match wins.
The transcript mode declares that the worker accepts OMP's --session-dir
option and writes compatible JSONL; Factory then captures the session for token
usage, factory score, and factory learn. Commands containing a binary named
omp keep this behavior without the key. A table may also set env = { ... };
values accept the command placeholders and apply only to that worker after
Factory restores its lifecycle context and strips GitHub credentials. A pinned
version = "..." is recorded with the claim, usage, attempt, and worker
lifecycle entry. The prompt lists routable profiles with their when rules;
neither ROUTE nor FIX accepts unlisted profiles.
Each launch resolves one worker spec (Config.worker_spec): the host wrapper,
the profile command, its model, version, environment, transcript mode and
provenance (Repository, Host repository override, Host default or
Built-in default). The built-in OMP default carries its pinned --model.
Dispatch, factory learn replays, dry runs and the settings view all use that
same value; the model shown and recorded is read from the expanded command, and
the provenance names the layer whose command is launched (a higher layer that
adds only probe or env does not change it). Before any stage, each dispatcher
and factory manage pass health-checks every configured profile. A table may set
probe = [...], a health or auth check whose argv takes {root}, {repo} and
{home}; it runs once under the host wrapper and the profile's environment,
without GitHub credentials, and exit 0 means available. Only its last 64 KiB of
output is read, and a probe past 60 s is stopped with its process group. Before
the probe, the host wrapper and the profile's own executable must each resolve
on the worker's PATH; a wrapper on PATH says nothing about the worker it runs.
The worker's PATH is the one its launch gets, including the profile's env,
both in this check and when a ticket is claimed.
The probe is the only check that proves a login, so the manager is offered only
profiles whose probe passed this pass, and factory doctor warns about each
profile without one. A profile without a probe can still launch, but its login
is unverified, and a failure seen at launch stands across passes until its probe
passes or a launch works (dispatch --ticket N after fixing the host); PATH
alone never clears it. dispatch --ticket skips the pre-pass check: an
operator's explicit ask launches and fails loudly, still classified as below. A
failing profile is not launched that pass and is not offered to the manager. A
ticket that profile owns runs on default instead, unless the profile is chosen
by a when = { label = ... } selector or default is down too. In that case the
ticket waits unclaimed (worker_unavailable). A launch that exits nonzero
without a timeout, makes no commit and leaves a clean worktree is an
infrastructure outcome when it logs an authentication failure (auth_failed)
or exits 127, the POSIX code a wrapper or launcher returns when the worker it
runs is missing (executable_missing); so is a launch whose executable vanished
after the pre-pass check. Factory records a worker-infra row, not an attempt,
so it is not a strike, never reaches the gate and does not count toward
max_attempts. It then marks the profile unavailable and relaunches the same
attempt on the fallback. With no fallback the claim is given back. Availability
changes, and a launch failure on a profile already down for another reason,
are journaled once each as worker-health rows with worker,
available, reason, fallback, source (probe or launch) and check
(probe, executable or launch: the evidence; executable never proves a
login). The attempt that ran on a fallback records fallback_from. A manager FIX
that finds no healthy worker keeps its manage row, records manage-pending
(worker, guidance, packet) and a worker_unavailable wait instead of failing,
and no human handoff is published while it waits. Once a worker can take it, a
later pass journals manage-resume and runs that same FIX without another
manager round or comment. A resume is taken up once: one that fails or is
interrupted is handed to the human. Only the latest resume's own run counts,
so a deciding pass that crashed after recording the pending FIX, or an earlier
resume that re-pended, does not hand off a FIX a later resume applied.
[review].json_mode = true similarly declares an OMP-compatible reviewer:
Factory adds or replaces --mode json and parses its JSONL verdict and usage.
It defaults to true only when the reviewer program is named omp; set it to
false to disable that default.
AUTHORIZE uses {"justification":"...","guidance":"..."} to record why an
existing add-only file must change, add factory-add-only-override, and return
the ticket to ready-for-agent. It is limited to required add-only edits or
removal of obsolete wording-only assertions, and never authorizes protected
paths. The normal gate and independent review run again. FIX uses
{"worker":"ci-fix","guidance":"..."} to run exactly one selected worker round
in the kept agent/<n> worktree for its open PR, ignoring other ticket labels.
A kept head ahead of the remote PR head is pushed first
(--force-with-lease against the recorded PR head) when it is a head a
journaled worker attempt of this ticket produced; any other kept head
escalates with refresh_head, and a refused lease with lease_refused. FIX passes
guidance and the escalation packet to the worker, re-gates, pushes only on a
gate PASS bound to the resulting commit, and independently re-reviews that
same commit. Only a zero-exit, well-formed fresh APPROVE whose remote PR head
still matches restores factory-approved; failure stays with the human. FIX
does not merge or requeue the issue.
RESOLVE is escalation-only evidence that the requested outcome is already on
the configured main branch (by commit or PR), or that the ticket duplicates
another issue. It comments before closing the issue as completed and removes
ready-for-human; an open agent/<n> PR into main with no changed files is
also commented and closed. RESOLVE fails closed for human handling when that PR
has changed files or another base, or when an agent/<n> branch without a PR is
ahead of main.
The template includes opt-in ci-fix and conflict profiles for a
human to apply in host config; the manager cannot add profiles or edit config.
Code validates the output, records a manage event before GitHub mutations, and
leaves malformed decisions with a prefixed HUMAN diagnosis. Split children enter
needs-triage; the parent keeps ready-for-human with child blocker lines.
For REWRITE and SPLIT, Factory refreshes the issue body immediately before
applying the decision. A linked rewrite must preserve its accepted Initiative
and Plan baseline exactly. Bound split children inherit that baseline, and all
linked children are validated against the complete live initiative before the
first issue is created. A validation failure consumes the recorded manager
round, creates no intake-ready child, and leaves the parent with the human.
A trailing fenced notes block replaces .factory/manager/notes.md
(gitignored, never committed, carried into every later manager prompt). The block
is optional; code refuses an empty or over-16 KB replacement, keeps the existing
file, and records the outcome in the manage event's notes field
(written, empty_rejected, oversize_rejected, or null when no block was sent).
Manager executions and ticket-lock waits use the lifecycle journal. If a GitHub
mutation fails, the execution records a terminal failure and the ticket remains
with the human; other tickets can proceed. The consumed round is not replayed,
because a partial rewrite or split may already have changed GitHub.
A human who moves an escalated ticket back to ready-for-agent (by relabeling or with
the guarded requeue_agent action) opens a new generation for it. Whichever stage
first reads the live ticket in that state (land, manager or ticket) in a pass after the
escalation's own journals one generation row with generation, intent, source (label or requeue_agent),
actor, decision and escalation_at. Every round budget counts only the rows after
it. That covers the escalation and manager rounds, frontier manager rounds,
review-bounce rounds and conflict, gate and risk requeue rounds, so the ticket gets its
full budget again. A factory release never opens a generation. The dispatcher and
manager journal each of their own releases before relabeling: conflict-requeue,
gate-requeue, risk-requeue, mutation-proof-wait, deferred review-rework, and RETRY, REWRITE,
AUTHORIZE or ROUTE manage rows. A ticket that is back in ready-for-agent and
unassigned after its latest escalation, with none of those rows after it, was released
by a human. A journal with no generation row is generation 0 and counts exactly as
before.
requeue_agent takes an optional intent. With resume (the default, and what a
plain relabel means), the branch, worktree and refresh context are kept. With fresh,
agent/<n> is recut from main at the generation's first claim, and the superseded local
and remote heads stay under create-only
refs/factory-evidence/<n>-generation-<g>-{local,remote}-<sha12> refs, so replaying an
interrupted restart never replaces them. A generation-restart row (local, remote,
base) is the receipt: later claims of the generation reuse the recut worktree instead
of recutting it, and until the generation first publishes, its push may replace exactly
the preserved remote sha and nothing else. A remote that moved after the restart is
leased as usual, so the push is refused (lease_refused) and the newer commit stays.
The claimed row records generation and base. Until the generation's first worker
attempt, the PR frontier does not re-escalate feedback that was already undelivered when
it first saw the requeue. That set is journaled as a feedback-watermark row with the
sources it covered completely. A source that was unreadable then is watermarked when
first seen complete, holding only its items no newer than the owner's release (all of
them while the release time is unknown). Any newer or edited source after its watermark
still escalates. Manager decisions stay bound to their exact head across generations.
Once automatic recovery for an escalation is terminal — the manager returned HUMAN,
its command could not run (an explicit unable to diagnose, never a fabricated
diagnosis), manager.rounds is exhausted, no manager is configured, or the escalation
loop can never act again (its decision could not be applied to GitHub, its packet is
gone, or its escalation comment was never receipted so takeover detection cannot clear
it, as for escalations recorded before this version) — factory manage
publishes one request comment for that escalation generation (<ticket>/<round>,
or <ticket>/g<generation>/<round> after an owner requeue):
a concrete question, bounded public links (PR, the recorded escalation and manager
comments), a proposed next step, the routed owner or candidates, and the step-by-step
routing rationale from factory plan route (reason ci for CI failures, otherwise
implementation with the PR's changed paths). Runner-local paths, packets and logs
never reach GitHub. While recovery is still eligible nothing is posted; routing stays
advisory (factory plan route N).
The terminal handoff phase is still attempted if an earlier manager phase fails.
That failure remains an error: publishing a handoff does not authorize the dispatcher
to continue scheduling new work.
The request @mentions a GitHub login on the initial handoff and again only when the
owner actually changes (a human sets or edits **Decision owner** in the issue body,
which wins on every later read and is never written back). Teams are mentioned only on a
verified organization repository; unassigned, invalid or unavailable routing states the
gap instead. Nobody is assigned. Publication is intent-then-receipt in
.factory/events.jsonl (handoff row before the comment, comment row with the
comment id after); a crash or failed gh between the two is reconciled from the issue
timeline before any retry, and when that lookup fails nothing is posted. GitHub
delivery of a mention is not asserted.
Explanatory text escapes mention syntax, including rejected destinations, routing
provenance and previous owners; only the current validated owner or candidates receive
native mentions.
Human-takeover detection uses only the factory's own recorded comment ids: the
escalation comment, manager comments and handoff requests are journaled as comment
receipts and ignored; any other comment, label, assignee, body edit, or an edit to a
recorded comment counts as human activity and stops the manager. Text prefixes are
never trusted. Without the current escalation's recorded comment on the timeline,
the manager fails closed: even a failed escalation post leads to a routed handoff,
not an exemption for later human label or assignee changes. A handoff receipt cannot
substitute for the missing escalation receipt on a later pass.
Manager CLOSE and RESOLVE comments are posted explicitly before closing
their respective PR or issue, with each receipt scoped to the timeline that owns
the comment. A partial close failure does not replay the consumed manager decision.
A reply is context for humans, not a retry, approval or merge command;
use the documented labels for that.
Viability asks should we pursue this direction?, before spending effort on
specification or code review. With [manager].command configured, opt in explicitly:
factory init --labels-only # provisions the vocabulary on an existing installation
gh pr edit N --add-label needs-review
gh issue edit N --add-label needs-viability
factory manage --dry-run
factory manageThe manager handles needs-review PRs before needs-viability issues, both
before escalation management. The existing dispatch pass invokes the same stage;
there is no unlabeled-backlog sweep, new service, or separate model transport.
Held requests (factory-held), closed targets, targets with conflicting pipeline
labels, and locked targets are skipped. An unconfigured manager leaves labels alone.
Each recommendation is an issue/PR comment prefixed Factory manager:, with
reasoning, source citations, and one final machine-readable line:
VERDICT: BUILD, VERDICT: DONT_BUILD, or VERDICT: DEFER.
| Target / verdict | Label transition and authority |
|---|---|
| Issue / BUILD | Remove needs-viability, add needs-triage for deeper investigation. Never directly queue implementation; a vague idea need not already pass triage's specification checks. |
| Issue / DONT_BUILD or DEFER | Remove needs-viability; leave open, propose only. No wontfix, closure, or replacement workflow label. A human decides whether to close, defer, or overrule. |
| PR / any verdict | Retain needs-review; recommend only, even BUILD. Dispatch independently runs the SHA-bound quality review before this stage; viability adds no handoff label and never approves, requests changes, merges, or closes PRs. |
needs-review is shared opt-in, not a viability-owned completion marker. Viability
records each label-add request independently of dispatch's (PR, head SHA)
review-intake record. Its advisory verdict neither completes nor vetoes review.
Viability can assess drafts; dispatch discovers only open, non-draft PRs and also accepts
a pending review request for the authenticated factory account. That alternative
review opt-in does not opt a PR into viability.
The model uses the existing evidence/briefing source helpers: bounded target description/comments, recent issues and PRs (not an exhaustive duplicate search), selected repository code and README/roadmap context, lessons and manager notes. The bundle caps source text at 64,000 bytes / 40 sources (20,000 per source), with smaller prefixes for target bodies, summaries, and files. It samples 12 recent PRs and 12 issue-endpoint rows across all states, the target's latest comment page (at most 12 entries), up to three tracked documents and three code files, and at most 30 PR changed-file summaries without diff patches. Sources name their coverage limits; missing evidence is unknown, not absence. The prompt asks for value, overlap, roadmap fit, cost/risk estimates, and the smallest useful investigation, with citations separating facts from estimates. Malformed, uncited, unknown-citation, or failed model output becomes a diagnostic DEFER; it cannot queue work.
Idempotency is per label-add timeline event, independent of escalation rounds.
Under the existing per-ticket lock, the manager rechecks the target (including
PR head) and timeline after inference; intervening human changes leave it untouched.
It records the verdict and full proposed comment in .factory/events.jsonl
(event: viability) before any GitHub mutation, then posts and consumes only
issue triggers. A second pass never repeats that request, even with needs-review
still present or after a partial/ambiguous
GitHub failure. In that case inspect the recorded comment and live state before
recovering manually; automatic replay could duplicate an already-posted comment.
Keep the local journal: this is the same single-host at-most-once boundary as
escalation management, not a distributed exactly-once service. To deliberately
reconsider, remove and re-add the opt-in label; body or PR-head edits alone do not
re-arm a recorded viability request.
Human-touch metrics are read-only; no manager behavior is required. A
ready-for-human label addition starts an escalation interval; removal ends it
and attributes the resolution to that removal's actor. Resolver logins are retained.
Open intervals accrue until now, or until closure/merge for finished tickets.
Re-queues count ready-for-agent additions after the initial queue entry, with
repeated claimed trace records as a fallback. Trace escalation counts likewise
supplement timeline counts without adding the two counts together.
Manager command failures are counted separately as manager_failures in stats
JSON and dashboard ticket human_touch data, and as manager failures in the
stats table. They do not add an escalation or consume another manager round.
Every escalate row carries a code from dispatch.ESCALATION_CODES (the
mechanical origin: gate_failed, worker_stuck, budget, ci_failed,
review_revise, reviewer_unavailable, approval_drift, …) beside the prose
reason; the stats footer and human_touch_metrics report the trailing week
escalations_by_code.
Human corrections that never escalate are counted per agent PR (agent/<n>, any
state, merged included): human_change_requests (changes-requested reviews),
human_comments (review-thread and PR conversation comments) and human_commits
(commits whose author or committer account is human). Resolutions and corrections
share one attribution rule. The actor is factory when it is a Bot or its login
is the dispatcher's authenticated login (gh api user under [install].dispatch_env).
Any other account is human. A missing account is unknown. Every action before
that login's first observed action (labels, reviews, comments, commits) is
unattributable, so the switch to a separate machine account needs no config. With
dispatch_env unset the factory shares the human's account, so nothing is
attributable. An agent PR with any unattributable action reports its three counts
as null (n/a). Interactive agent sessions and hand edits under a human account both
count as human.
The stats footer and dashboard KPIs show escalations in the trailing seven days
and the percentage of attributed resolutions performed by humans; unresolved,
unknown and unattributable resolutions are excluded from that denominator
(n/a/null when none are attributed). The stats footer also shows
Human-touched PRs: the share of merged agent PRs with any human correction,
unattributable PRs excluded. factory dashboard --json exposes
metrics.escalations_per_week, metrics.human_resolved_pct,
metrics.human_touched_pct (both 0–100), and each ticket's human_touch details.
The dashboard reads each merged agent PR's corrections once per process. It retains
its existing 100-issue, 100-PR, and 100-timeline-item query limits; stats paginates
label timelines. Correction reads stop at 50 reviews, 50 threads of 50 comments,
100 conversation comments and 100 commits per PR.
-
Triage. Runtime bugs filed by
factory watch(the issue number is in a journaledwatchrow, or the issue's author is the account triage posts as, because another install's watch routed it here; with a first-lineFingerprint:, thefactory runtime failure:title, andbuglabel) bypass the model and go directly toready-for-agentwith a reproduce-or-handoff investigation brief. Other issues first pass a deterministic lint that rejects bodies under 80 characters or without acceptance criteria (needs-infowith a specific question); the model then decides between the four labels, andwontfixis only ever proposed. With[install].dispatch_envset, triage refuses to post (exit 1, reasonidentity_mismatch) unlessghauthenticates as the login that environment selects, so a shell or unit without the dispatcher'sGH_CONFIG_DIRcannot triage under the owner's account. The dashboard's "Run LLM triage" decision runs its triage step withdispatch_envapplied, so it posts as the dispatcher. A failed GitHub login lookup instead refuses with outcomemechanism_failureand reasongithub_command_failed; connection failures are not identity mismatches. -
Schedule and claim. Eligibility first: open
ready-for-agentissues that are not initiatives, not assigned and have no openBlocked byedge; then capacity (max_activeminus held ticket locks) and the experiment slot (at most oneexperiment-labelled ticket active; production delivery gets the rest). A ticket whose Plan binding admission would refuse (ambiguous or malformed, or linked without a baseline) is held with that reason, never ranked. Within that, admission order is accepted priority: the firstNOW/NEXT/THEN/LATERline of the ticket's own pinned Plan baseline that names it, tiers in that order, then unknown priority (no baseline or no tier line), oldest ticket first within a class. After three consecutive explicit-priority claims (claimedrows carrypriority), the oldest eligible unknown-priority ticket is admitted instead only when no eligible, unclaimed NOW ticket remains. The streak carries across ordinary passes of the same active timer and engine revision, but resets after timer pause/resume (a new systemd timerInvocationID) or an engine version/commit change. Without a usable timer identity, the streak carries across passes of the same engine version/commit; a transition to or from an observable timer also resets it. Journals predating session tracking are not reused. Eachschedulingrow records itsfairness_session. Triage briefs, manager recommendations and experiment results never set priority. A pass re-reads and re-ranks the frontier before each pick, so a Plan baseline re-bound while an earlier pick was claimed is honored. Each pick with eligible work and spare capacity logs one line per frontier ticket (selected,deferred,held, each with its reason) and journals them as aschedulingrow whosecapacityis the slots left for that pick; its admissiondecisionrow names the Plan baseline sha256 it was ranked against.--dry-runlogs the same plan and writes nothing. Capacity, locks and dependencies are never overridden. The dispatcher then re-reads the issue (search-backed listings lag), assigns itself, takes a per-ticketflock, and creates the worktree.factory/wt-<n>on branchagent/<n>. Picks are ranked and claimed one at a time, in order, soclaimedrows follow pick order; once a pick'sclaimedrow is written the next pick is ranked while it works. Each ticket runs its pipeline in its own thread with its own worktree and lock, so up tomax_activetickets (counting ones already in flight when the pass started) work at once. The pass waits for all of them; a failing ticket does not stop the others, and a ranking error for the next pick does not stop tickets already claimed. Every ticket failure is logged at the end; the pass then raises its own ranking error, else the first failed pick's. On Ctrl-C each in-flight ticket runs nothing further: within one worker poll (5 s) its worker process group gets SIGTERM (SIGKILL after 10 s), its lock is released, then the pass exits. Ticketgit fetchandgit pushcommands run one at a time, and every dispatcher log line from a ticket is tagged#<n>after the[dispatch]prefix. -
Work. The worker gets the issue, its comments, standing instructions (commit incrementally, never touch
main, nevergit stash, finish withfactory gate), and — on retries — the previous gate report or the reviewer's findings. Up tomax_attemptsattempts withinbudget_min. A fresh handoff with an emptyStill unverifiedorUnverifiedsection (blank orNone.) and a clean, committed worktree is the finish signal: after expiry, the dispatcher still gates that head and proceeds through push, PR-tier gate, review and merge normally, without charging a rework round. Unfinished work and failing gate tiers still escalate. Nested headings remain part of the unverified section; only a same-level or higher-level heading ends it, so a subsection cannot hide blocking work. A worker that exits before the deadline keeps its passing gate result even when the gate itself overruns; that alone does not require the finish signal. A worker with no log output and no worktree change for[dispatch].idle_timeoutminutes is killed asstuck(a failed attempt, retried). One that committed or wrote its handoff, then stayed quiet for[dispatch].exit_graceseconds without exiting, is terminated and gated. The attempt journal row and escalation packet name the timeout that fired. If a budget-killed worker never reaches its next gate and the ticket's last gate in the current generation passed, escalation usesbudget, notgate_failed; the comment and packet namebudget_min/budget_exceededso the budget cut is identifiable for a not-a-strike owner requeue. An actual failing gate retains its existing classification. -
Gate. The configured
[gate].protected_pathsglobs from the base ref's.factory.tomlare checked against the committed worker diff first, before any checks; a hit stops the run and immediately escalates the ticket toready-for-humanwith the offending diff in the escalation packet. Include.factory.tomlin the list to protect the list itself. Globs in[gate].add_only_paths(also read from the base ref) are protected add-only: a new file passes, a modified file passes only whengit diff --numstatshows no deleted lines, and a deletion, rename, mode change, binary change, or any removed or changed line fails asadd-only. For in-place text edits, its escalation namesfactory-add-only-overrideas the clearing label. The manager may useAUTHORIZE, with an auditable justification and worker guidance, to apply that label and requeue the ticket when the ticket requires the existing add-only edit or an obsolete wording-only assertion must be removed from a retained file; a human may apply it directly. File deletions, renames, mode changes and binary changes still fail with that label and require human-onlyfactory-protected-override. Their escalations name that label instead. Iffactory-add-only-overrideis already present and protection still fails, the escalation explicitly rules out repeated managerAUTHORIZE. The add-only override does not authorize[gate].protected_paths. Onbugtickets the attempt gate also compares every existing Python test function and every Rust#[test]function (including tests insidesrc/*.rs) with the base. Deleting or changing one, including adding@unittest.skip, pytest skip/xfail, or Rust#[ignore], fails asprotected-tests; other languages retain the configured path-based add-only policy.factory-add-only-overridebypasses that function check as well, so manager authorization also works on bug tickets. Thefactory-protected-overridelabel bypasses both path and function protection; a ticket linefactory-protected-override: <reason>bypasses only function protection on bug tickets. Anupstream sync:ticket's worker otherwise gets no override; only upstream-authored content is exempt (--upstream, above). Local gate runs only (the dispatcher does not pass it):factory gate --add-only-allow <path>=<blob> --add-only-allow-base <commit>exempts exactly the named add-only files from both checks when a human supplies the reviewed blob ids. Each path must be canonical, insideadd_only_pathsand outsideprotected_paths, an in-place regular-file text edit, and both its committed blob and its working-tree bytes (git hash-object --no-filters) must equal the approved blob;<commit>must be the merge-base. Any refusal failsprotected-paths; every other add-only file and test stays protected. A bug worker must add the reproducing test in its own commit before the fix and putRepro test: <test ID>in its handoff. The test may be added during a later retry, review bounce, or manager FIX, not just the first branch commit. The dispatcher finds the earliest first-parent commit after base that adds the declared test and requires a subsequent commit. It runs the test at its introduction commit (it must fail) and at HEAD (it must pass); both results are written to the gate report and the gate decision trace. ANo repro test: <reason>line in the ticket body or an authenticated triage account'sTriage:comment records the nonempty reason and skips only this fail-before/pass-after check. Other commenters and worker handoffs cannot grant this exemption; triage comments grant no protected-path or existing-test override. Otherwise make protected changes outside the worker flow. Thenconflict-markers, your[[gate.check]]list in order, and aleak-scanrun. Checks markedexclusiveserialise on a host-wide lock. Every check has a timeout.[[gate.check]]has three tiers, selected bywhen(factory gate --tier <tier>; anything else is a config error naming the check): attempt (default) runs here, on every worker attempt; pr runs once per PR head, before review (step 5); release runs only on av*tag from thereleasejobfactory initwrites into.github/workflows/ci.yml(factory doctorwarns when release checks exist but no workflow runs--tier release). Checks of a later tier are skipped here and reportedSKIP (pr tier)/SKIP (release tier);--tier prruns only pr checks (release ones SKIP) and--tier releaseonly release checks, with no built-ins. This attempt gate is what the worker and the dispatcher run after each attempt, and what the merge-stage refresh re-runs. Repositories may opt into mechanical repairs with[gate].fixups, an array of argv arrays (for examplefixups = [["cargo", "xtask", "manifest"]]). Factory never infers commands. Before escalating the last failed worker gate (including manager FIX and review-bounce workers), it runs these commands once, in order, in the clean ticket worktree, stopping on the first failure and using the gate check timeout. If all succeed and change files, Factory commits those changes and re-runs the gate with the same flags at the new SHA. No changes, a command failure, or another failed gate leaves the normal escalation in place; the report and escalation comment state that fixups ran. An empty/absent list leaves behavior unchanged. Refresh failures get the same repair pass after their existing same-head retry; PR-tier failures get one pass per uncached head, then recheck the attempt gate before publishing and reviewing a new head. Protected-path checks still apply to every repair commit. A PR repair'sgate-fixupreceipt binds acceptance and handoff retention to the repaired head and carries forward the previous head's recorded worker completion, so a late actionable review can still defer rework to the next pass. With[dispatch].signoff = true(the default), Factory signs off merge commits at creation, including upstream sync and refresh merges. It never retrofits trailers by amending or rewriting human or other pre-existing commits. -
Review. After the attempt gate passes, the dispatcher runs the
when = "pr"checks once for the head about to be reviewed (same timeout andexclusivelock; a head is never re-run) and appends their report to the gate report; that report keeps the output of passing pr checks too (last 80 lines), so report-only checks reach the reviewer. A pr-tier FAIL goes back to the worker like aREVISE, with that report as the findings, and uses onereview_roundsslot; when the rounds run out (or the head came from a manager FIX) the ticket escalates withpr checks failed. Otherwise the reviewer runs the diff itself and gets the gate report and issue snapshot inline, including every comment (the triage brief, approved scope changes). Native-host acceptance belongs in the worker handoff's## Native-host proofsection (Head SHA: <tested commit>, results and any archive/tree digest), or in a worktree-relative proof file cited by that handoff (for exampleProof: .factory/macos-proof.txt, containingVerified source revision: <tested commit>). A plainNative-host proof:label may also introduce file citations on following lines, up to the next Markdown heading. Paths containing spaces must be quoted with backticks, single quotes or double quotes. Before each ticket review, including manager FIX and refresh reviews, the dispatcher posts the evidence to the PR and supplies the same text inline as untrusted worker evidence. Recorded proof SHAs are checked against the gated head; stale/conflicting proof shows both revisions, while absent/unbound/unsafe evidence is explicitly not supplied as current-head proof. Re-run native proof after a refresh. Reads are bounded to 256 KiB, reject symlinks, worktree escapes and NUL-containing filenames (reported as unavailable evidence rather than aborting review), and use existing credential redaction/withholding rules; excerpts are capped at 4,000 characters and comments at 20,000, with explicit truncation notices and archive/tree digests retained when present. Successful publication is journaled by head and content hash to avoid duplicate comments on same-head retries or second reviews. Failed publication is stated in the packet and retried at the next review; it introduces no human gate. A reviewer never needs to open the gitignored worktree proof file. Every finding citespath:line; a required fix also cites an acceptance criterion, a documented rule with its source, or a concrete correctness/security defect with its trigger and impact — preferences and hypothetical extensibility are optional suggestions, never requirements, and a passing gate does not excuse a defect it did not detect. Net-new abstractions beyond the brief, whether the diff introduced them or the review asks for them, need that same justification, but a missing justification alone does not block. Reviews must end with exactly one finalVERDICT: APPROVEorVERDICT: REVISEline and a valid structured findings block. A validated verdict is handled even on a nonzero exit. Malformed, multiple, non-final, and launch failures are reviewer tooling failures: Factory retries them, then escalates persistent failure asreviewer_unavailablewithout recording change-request feedback or sending work back to the worker. Each acceptedREVISEsends the findings back to the worker, flagged so only the required fixes are binding (re-gate, push, re-review), up toreview_roundstimes; then it escalates. A managerFIXfailure leaves an already-ready-for-humanticket on its existing escalation instead of posting another escalation comment or consuming another manager round.APPROVEadds thefactory-approvedlabel only while the remote PR still points to the exact commit that passed the gate and review. The successful label operation and gate/review commit are recorded in.factory/events.jsonl. The optional[review].policypath defaults toREVIEW.md. Factory reads it from the base ref, never the worker head, so add that path to[gate].protected_paths. The policy can define bug/security/spec passes, Important/Nit/Pre-existing severity, skips, andNit cap: N; without the file, the built-in rules below remain in force. Structured reviews end with a fenced JSON object containingverdictand findings (severity,pass,path,line,summary), followed by the legacyVERDICT:line. Factory counts every finding, caps published nits, and approves if and only if Important is zero. Invalid JSON fails closed; disagreement between either verdict and the counts fails closed withverdict_counts_mismatch.review-resultrecords the three counts.Risk tiers. Before these checks, Factory classifies the exact gated
origin/<main>...headdiff with the installedfactory/risk.pyrules and records ariskevent plus ariskdecision. Candidate code cannot change the rules classifying its own head, and a new head invalidates all tier evidence.Tier Deterministic paths Review path Low docs/**; Markdown exceptAGENTS.md/REVIEW.md; additions-onlytests/**;.factory-lessons.md; note files underexperiments/**; additions guarded by a newly added default-off flagSkip when = "pr"checks and run one review. AREVISEswitches the PR to the Medium loop.Medium Every path not matched by Low or High Normal pr-tier checks and bounded review loop. High .github/**;factory/release.py,promotion.py,onboard.py,templates/ci.yml;factory/dispatch.py,gate.py,manage.py,decisions.py,config.py,risk.py;.factory.toml;factory-bands.tomlNormal gate and primary review, a second reviewer on a model distinct from both the primary reviewer and worker, and blocking mutation checks on changed factory/*.pylines.Default-off code qualifies as Low only for wholly added Python module-level guards and new literal-false flag declarations, with no unguarded executable additions or existing flag bindings. Uncertain cases stay Medium.
A High PR merges without human approval when the full current-head gate (including all PR-tier checks) passes, both reviewers approve, and mutation is
PASSorSKIP (no changed factory code). Both reviewers revising uses the normal Medium loop. Concrete required REVISE findings from either reviewer, and completed surviving mutants after approval, use the normal[dispatch].review_roundsbudget, not the second-head disagreement cutoff. When the wall-clock expires after a clean finish recorded for the current attempt and head, Factory retains the findings in areview-reworkjournal row and returns the ticket to the next pass, charging one round before releasing its claim and clearingready-for-human. Charges survive pass boundaries; the next worker receives the full packet. Rework after a merge-stage refresh uses the same mechanism and budget. Protected-path blockers come from gate status rows, not quoted reviewer findings or surviving-mutant source text. Rejects, protected-path blockers and exhausted rounds still escalate. Non-actionable High disagreements retain the bounded disagreement path.[review].second_commandis a host-only override of the code default. Non-mutation PR-check failures use the ordinary gate-failure loop, not the disagreement path. Mutation runs related tests first and stops after the first failure; a surviving mutant still has to pass every discovered test. The deterministic 200-mutant sample uses the gate timeout minus 60 seconds for preparation, baseline, and mutants together. After baseline completes, each mutant getsmin(max(60, 3 * baseline), remaining / 4)seconds, withremainingfixed at baseline completion. Per-mutant timeouts count as killed, with their timeout count shown separately in summaries and gate reports, unless the cap is below baseline duration: those runs stay incomplete and cannot disprove reviewed equivalents. Workers continue with remaining mutants after such cuts. Unstarted mutants, deadline-shortened runs and timeout results returned at or after the absolute deadline are also incomplete, not survivors or blocking failures; a baseline that never passes within the deadline and tool failures still fail. Scratch workers use local shared clones with independent Git metadata and the current working files overlaid, so Git-dependent tests run without skips. Baseline and mutant subprocesses disable bytecode writes, preventing cached baseline code from masking same-size mutations in reused scratch copies. Onproof = "mutation-v1"checks, the gate recomputes committed scope from raw textual diffs (no text conversion or external diff driver), counting only Git's LF line boundaries; source inside a hunk cannot become a file header. The producer, its localfactoryimports, and its child test harness execute from the resolved trusted base in gate-owned scratch. Producer startup excludes the reviewed checkout's interpreter, site hooks and build hooks; mutation targets and test suites remain the reviewed working tree. Missing trusted producer code fails closed. Completion records must be bounded regular files: symlinks, FIFOs and devices are invalid proof, never blocking reads. When main moves during a proof run, the dispatcher retries once. Another move defers review to a later pass without worker rework, a failed PR gate or reviewer escalation. An unbound proof, head mismatch or stale proof without a base move still fails closed. This repository's mutation command loadsmutation-equivalents.jsonthrough--equivalents FILE. It is a JSON array; each reviewed entry has this shape:{ "file": "factory/example.py", "line": 1, "operator": "core/NumberReplacer", "original": "unused = 1", "mutated": "unused = 2", "argument": "Only the integer literal 1 reaches this module-level assignment; no code reads unused, so changing it to 2 cannot affect behavior.", "reviewer": "Agreeing reviewer" }fileis repository-relative andlineis the positive start line. Matching uses the exact operator and the complete removed/added source lines from the mutation diff, preserving indentation and joining multiple lines with\n; it never uses the report's truncated display text.argumentandreviewermust be nonempty single lines. Each argument must name the input domain and where it is filtered (or why no filtering is needed). The agreeing reviewer must check that assumption against the source at the gated head. A later change widening that domain reopens the mutant, even if its exact mutation identity has not changed. Matching survivors remain in the report as accepted equivalent, with the argument and reviewer, but do not block. Invalid entries fail in both blocking and report-only modes. Before selecting mutants, every entry's completeoriginalsource must still match at its recordedfile:line; rewritten, moved, deleted or unreadable source makes the entry stale and fails either mode, even with no changed mutable files. An exact reviewed mutant that was tested and killed also fails either mode. When every changed-line candidate was sampled and completed, an entry on any enumerated changed line with no matching surviving identity is also stale (including lines with zero candidates, obsolete operators or replacement text). With matching source, unchanged files or lines, sampled-out mutants, and unstarted or deadline-cut trials provide no stale evidence. The registry is in[gate].protected_paths: additions, updates and removals require the normal human-reviewed configuration/protected-override path, not an ordinary worker diff. The registry ships empty ([]); #541 adds its own reviewed entries pinned to its gated head. No survivor is pre-approved by this mechanism. The built-in OMP worker pinsopenai-codex/gpt-5.6-sol; custom worker profiles must also name a model.factory doctorwarns when any of the worker, primary-reviewer, or second-reviewer models is missing or not distinct, or when the second reviewer cannot launch.factory stats --by-riskand the dashboard report human interventions, human-wait minutes, rounds, disagreement rate, and escape rate per tier. -
Merge stage (start of the next pass). One PR per pass requires green GitHub checks, a current-main head, no human requested-changes veto, the
factory-approvedlabel, and a matching successful journal approval whose gate, review, approval, and current PR head SHAs are identical. Checks are associated with that head and rechecked after evidence evaluation; the PR head, target branch, label, and veto are then re-read immediately beforegh pr merge --match-head-commit <sha>. Missing, unbound, legacy, or stale approval evidence never merges. With[eval] schedule = true, a PR changing worker configuration/routing, standing prompts, lessons, or skills also needs aneval-summarykeepverdict bound to that exact head; a missing orrevertclaim waits without merging. Behindmain→ refresh, re-gate on this host, force-push, run a fresh independent review, post its findings, and either reapprove the resulting head, return routine refresh work to the ticket worker, or withdraw the label and escalate. A rebase (or sync-merge) conflict is routine work: the label is withdrawn, aconflict-requeuerow records the PR, head and conflicting files, and the ticket is released (unassigned,ready-for-humanremoved,ready-for-agentadded, including after a managerFIX) so the next claim runs a worker in the same worktree on the sameagent/<n>branch with a brief to rebase onto currentorigin/main, resolve the conflicts, keep the approved intent, and not widen scope. That attempt counts as a worker round; the normal gate, push (lease on the recorded PR head), independent review,review_roundsandmanager.roundsfollow, and only a fresh approval restores the label. The conflict escalates asrefresh_conflict, with the conflicting files in the packet, when it touchesgate.protected_pathswithoutfactory-protected-override, whenreview_roundsconflict requeues are already used up, or when the ticket is not open. Conflicts inadd_only_pathsgo to the worker; the gate's add-only check judges the resolution (factory-add-only-overrideor managerAUTHORIZEto rewrite existing lines). A gate failure on the clean refreshed head is re-run once before any handoff. A passing re-run continues the normal push and review path and journals both reports ingate-rerun. If the re-run also fails, agate-requeuerow records both reports, the PR diff paths, whether the failure appears unrelated to those paths, and the round; the open ticket is released to its existing worker profile on the sameagent/<n>branch. The worker brief includes both reports and the unrelated-failure assessment. This repeats for at mostreview_roundsgate requeues. A closed ticket, exhausted gate rounds, or a protected/add-only failure without its authority label escalates immediately; escalation packets retain both reports and the same diff assessment. Red CI → label removed, escalated once with the failing check names. A check cancelled after running steps is red CI. A check cancelled before any runner picked it up (no steps, no runner, or GitHub's "not acquired by Runner" annotation) is infrastructure: once its run has finished (no other check pending and GitHub reports the run completed), the run's failed jobs are rerun once (gh run rerun --failed, journaled asci-infraandci-rerun), the label stays, and the PR waits as CI pending. If the rerun is also starved, the ticket is escalated once as "CI runner unavailable" with the label kept, so a later green rerun still merges. Existing behind PRs re-earn bound evidence through that automatic refresh. An up-to-date PR carrying a pre-upgrade unbound approval is withdrawn and escalated once; use the existing managerFIXpath to re-run its worker, gate, push, and review. Do not hand-edit the journal or fabricate SHA fields. PR creation explicitly selects[repo].main(defaultmain), independently of the installed engine channel and GitHub's default branch. Approval and merge eligibility require that same PR target; existing wrong-target PRs are left untouched for operator review. Missing target evidence also fails closed.--match-head-commitatomically guards the head, not the target branch or a late human veto. Protect release branches on GitHub; the final reads alone cannot prevent a retarget after the last check. -
Escalation. Budget exceeded with unfinished work, failing gates, exhausted review rounds, genuine reviewer rejection, nothing to PR, refused
agent/<n>push, a refresh conflict that is not routine (step 6), red CI, or any dispatcher crash after the claim: the issue getsready-for-human, loses the assignee andready-for-agent, and receives a comment with the reason and the worker log path (its comment id is journaled). The worktree is kept for forensics. When no automatic manager recovery remains, one routed human handoff request follows (see Routed human handoffs). -
Manager PR frontier (when
manager.commandis configured; runs infactory manageafter landing). Every open same-repositoryagent/<n>PR targeting the configured branch is observed through the schema-1 feedback producer; onlyowner.relation = factory_issue(a same-repository closing link plus the retained claim) puts it in the frontier, never branch text. Initiatives and already-escalated tickets are left alone. Pending CI waits. Red CI, unresolved current-head feedback (changes-requested review, unresolved non-outdated thread, failed check) and inactivity beyondmanager.stale_days(default 7) escalate the ticket once through the ordinary packet, so the manager'sFIX/CLOSE/HUMANdecisions apply. Late feedback is delivered at most once per(evidence_id, source_revision)(feedback-deliveredjournal rows); partial or unavailable coverage, unknown relevance and the factory's own reviewer are never delivered.CLOSEcloses the PR when one is open and comments with the diagnosis either way; a human's issue stays open withwontfix-proposal, while a factory-createdSPLITchild closes. Withmanager.review = "all", a head that passed the gate and independent review is not labelled until the manager returnsAPPROVEfor that exact head (managerow withhead); a refreshed head needs a fresh decision and nothing is re-bound. Decisions are bounded bymanager.roundsper PR.
.factory.toml at the repository root; every key is optional. The template
written by factory init documents them all. The ones you will actually set:
The dashboard's Settings view (/#settings) edits exactly five controls:
dispatch.max_active (concurrent tickets), dispatch.budget_min (time limit
per ticket, in minutes), dispatch.max_attempts (worker and gate attempts),
dispatch.review_rounds (reviewer revision rounds), and manager.model (the
Factory Manager model). It shows each effective value and its source
(Repository, Host repository override, Host default, or Built-in default), plus
a read-only worker/reviewer/triage summary with command arguments and endpoint
credentials omitted.
Review the explicit before/after summary and choose Save changes. The
dashboard writes only changed keys to the local .factory.toml, preserving
unrelated settings and comments; changes remain uncommitted (they never commit
or push). If another process changes the configuration first, stale edits are
rejected: reload and review the latest values before saving. A saved change
leaves .factory.toml modified in the root, so every factory dispatch pass is
refused with root_dirty until the edit lands on origin/<main> through a PR
(or is reverted); it takes effect on the first pass after it lands. The selected
model applies to the next new Factory Manager request. Running work and
in-flight requests keep their captured configuration unchanged.
Clearing manager.model removes the repository override and restores the
existing host value, a legacy manager.command --model fallback, or OMP's
default model. Gate and safety policy remain file-managed.
[repo]
# upstream = "upstream" # fork workflow: sync upstream main each pass
[dispatch]
review_rounds = 1 # REVISE -> worker -> re-review cycles
# idle_timeout = 30 # minutes quiet mid-work = stuck; 0 disables
# exit_grace = 300 # seconds quiet after commit/handoff before termination; 0 disables
# cost_pattern = 'Total cost:\s*\$([0-9.]+)' # $ from the worker log (Claude Code prints this)
[workers] # ticket label/profile -> argv; {prompt} file, {cwd} worktree
default = ["omp", "-p", "--model", "openai-codex/gpt-5.6-sol", "--cwd", "{cwd}", "@{prompt}"]
chore = ["droid", "exec", "-f", "{prompt}", "--auto", "medium", "--cwd", "{cwd}"]
# A differently named OMP-compatible worker selected by a separate pilot label:
# [workers.prime]
# when = { label = "harness-pilot" }
# command = ["factory-prime-agent", "-p", "--cwd", "{cwd}", "@{prompt}", "--mode", "json"]
# transcript = "omp-session"
# version = "0.10.0"
# env = { DO_NOT_TRACK = "1", PRIME_AGENT_TELEMETRY = "0", PRIME_AGENT_CODING_AGENT_DIR = "{root}/.factory/prime-agent" }
[review]
command = ["omp", "-p", "--no-session", "--model", "anthropic/claude-fable-5-1", "{prompt}"] # {prompt} = review prompt text
# json_mode = true # required for an OMP-compatible reviewer not named `omp`
# policy = "REVIEW.md" # read from the base ref
# second_command is host-only; it overrides Factory's code default for High-risk reviews.
[manager] # optional; unset command disables it
command = ["omp", "-p", "--cwd", "{cwd}", "@{prompt}"] # {prompt} = manager prompt file
[gate]
timeout = 1200
lock = "/tmp/factory.lock"
protected_paths = [".factory.toml", "REVIEW.md", "TRACKING*"]
add_only_paths = ["tests/**"] # new files and appended lines pass; edits escalate
# fixups = [["cargo", "xtask", "manifest"]] # optional mechanical repair; no defaults
[[gate.check]]
name = "lint"
run = ["cargo", "clippy", "--workspace", "--all-targets", "--", "-D", "warnings"]
exclusive = true
[[gate.check]]
name = "tests"
run = ["cargo", "test", "--workspace"]
exclusive = true
[leak_scan]
# Default; "" disables it. `extra` terms are added to it, never replace it.
pattern = "\\.(?:corp|internal|intranet|lan)\\b|\\bconfidential\\b|\\bproprietary\\b|\\bjira\\b|\\bconfluence\\b|\\.atlassian\\.net\\b"
extra = ["\\bmyproduct\\b"] # regexes ORed onto the pattern
[triage]
url = "http://127.0.0.1:11434/v1/chat/completions"
model = "qwen3:30b"
# timeout = 60 # seconds per model request
# max_tokens = 2048 # positive output-token limit on every request
# chat_template_kwargs = { enable_thinking = false } # optional model-specific table
[journal]
max_mb = 64 # events.jsonl rolls into events.jsonl.N.gz past this size
retention = 8 # gzip segments keptTriage sends max_tokens on every model completion (default 2048; must be a
positive integer). Optional chat_template_kwargs is a JSON-compatible table
passed through unchanged, including false values and an explicitly empty table;
the key is omitted when unset. No model-specific template option is implicit.
Completion requests to the same URL are serialized across repositories, threads,
and processes for the same host user, using endpoint-keyed locks under
$XDG_STATE_HOME/factory/triage-requests (default ~/.local/state/factory/triage-requests).
All processes sharing an endpoint must use the same state home.
For a District-managed remote host, keep its request shape in the controller's
shared host config so sync_remote_config preserves it:
[hosts.ultron.defaults.triage]
max_tokens = 1024
chat_template_kwargs = { enable_thinking = false }District merges that host override into the remote [defaults.triage]; Factory
also accepts [repo."owner/name".triage] overrides. Keep these settings out of
the repository file when hosts need different request shapes.
The shared host file is $XDG_CONFIG_HOME/factory/config.toml (default
~/.config/factory/config.toml). [defaults.engine] belongs to District:
ref, sha, previous, and installed_at describe its installed engine
snapshot; target, target_ref, and resolved_at describe the target District
resolved and CI-checked for installation. At pass start, Factory compares its
installed commit with that recorded target SHA, never resolving factory_ref
or checking engine CI itself. A mismatch emits one engine-stale event per
non-dry pass, with installed_commit, target_commit, and yield_for_update.
Missing installed identity or a missing/invalid target does not establish staleness.
Other District metadata stays outside pipeline configuration; doctor accepts it
only under defaults. An engine table under a per-repository host section
still produces a host-config warning.
[engine] yield_for_update = true in .factory.toml opts a repository into
yielding when stale (default false). For the whole shared host, set:
[defaults.engine]
yield_for_update = trueThis host policy takes precedence over every repository's setting, so a repo
opt-out cannot keep the shared engine busy. A stale pass, including --ticket,
finishes land and review intake, then exits successfully without claims, manager
work, learning, or opening a release PR. Dry runs report the yield without
writing an event. Once District records the installed SHA equal to its target,
normal passes resume. After a factory_ref switch, Factory follows District's
next recorded target, not a separately computed branch head. District still
owns green-CI eligibility and the install window: pausing timers, waiting for
idle, installing, and resuming; Factory does not change services or timers.
Outcome check for #539: over the first seven days after deployment, retain the
host's engine snapshots (sha, installed_at) and compare GitHub main-merge
timestamps with the first installed snapshot containing each merge. The median
merge-to-install lag must be at most two hours. This post-deployment observation
is separate from the dispatcher regression tests.
Several hosts serving one repository.
Opt in on each machine through the shared host file. Values directly in
[repo."owner/name"] override [defaults]:
[defaults]
host_name = "tank"
triage_host = "tank"
land_host = "tank"
claim_ttl = "2h"
[repo."owner/name"]
claim_ttl = "3h"Use a distinct host_name on every host: 1–45 ASCII letters, digits, ., _,
or -, starting with a letter or digit. Set the same triage_host on all
hosts to avoid duplicate triage; other hosts exit 0 with
triage: skipped, triage host is <name> before reading issues or writing events.
Unset triage_host keeps triage enabled everywhere. claim_ttl defaults to
"2h" and accepts positive s, m, h, or d durations, including "1h30m".
factory doctor reports the effective host settings.
Set the same land_host = "tank" on both Tank and Ultron before enabling
Ultron's Factory timer. Only the matching host_name runs landing: upstream
sync, merge and behind-main refresh. Other hosts skip before any landing git/gh
calls or journal writes, including dry runs. Unset land_host keeps landing
enabled everywhere. Like triage_host, it is host-only and uses the same host
name syntax and per-repository override.
release_host works the same way: set the same release_host = "tank" on every
host and only the matching host_name runs the release step; other hosts log
release: skipped, release host is <name> before any git or gh call. Unset
release_host keeps releasing enabled everywhere.
triage_host also gates every loop whose ownership is a GitHub-wide scan or
singleton rather than a local claim: triage, review intake, manager viability
and learn. Passes whose ownership comes from this host's own journal run on
every host that has a manager, whatever triage_host says: the PR frontier
(CI-failed, late-feedback and stale escalation, and the manager.review = "all"
approval) and escalation rounds. Terminal handoffs run on every host, with or
without a manager, and act only on this host's own escalate rows. A PR claimed
only by the other host has no local claimed or escalate row, so those passes
leave it alone.
Independently, the ticket merge stage skips PRs whose elected claim belongs to
another host, even after that claim expires. It neither refreshes those branches
nor consumes local approval evidence, removes factory-approved, or escalates
them. PRs without a claim retain ordinary eligibility checks.
Before any GitHub mutation, dispatch reads gh api rate_limit and requires at
least 100 remaining in both GraphQL and REST (core). Below either floor,
or if the budget cannot be verified, it skips the whole pass (exit 0), logs the
reason and reset time when available, and journals pass-skipped with reason
github_rate_limit. Dry runs log without journaling. This is a pass-start
safety margin, not a reservation: other hosts and clients can consume the shared
account's budget after the check.
Dispatch inspects paginated repository labels at pass start. Any host:* label
requires host_name. When host_name is unset, dispatch also scans all paginated
issue comments (including closed issues) and refuses valid host claims even if
their repository labels were removed. Unreadable evidence refuses dispatch.
Named hosts do not scan repository comment history at pass start, so their
preflight cost does not grow with historical issue/PR conversations.
Doctor inspects all paginated issue comments for every host.
Valid claim comments require host_name; claim authors must match the
dispatcher GitHub login when authored by that login or a repository owner,
member, or collaborator. Outsider comments cannot establish host identity or
block dispatch. Login comparison is case-insensitive. Doctor checks the effective
dispatcher environment, including install.dispatch_env, and reports a blocking
host claims FAIL on mismatch, missing identity, or unreadable evidence.
Dispatch refuses unsafe repository host setups (exit 1), including --ticket
and dry runs. It checks the selected ticket's claim authors at admission and
after publishing a contender, closing the different-login election window.
Foreign comments never gain cleanup authority; inspect and resolve incompatible
claims before restarting.
Inside the existing per-ticket lock, dispatch adds host:<name> and a comment
whose first line is Factory claim: host=<name> nonce=<uuid> at=<iso8601>.
Only comments authored by the authenticated dispatcher account count as claims.
After fresh label/comment reads, the earliest live comment wins, ordered by
GitHub creation time and then numeric comment ID. A loser records claim_lost
and removes its own comment and label without assigning or launching a worker.
The winner assigns @me and refreshes its comment every TTL/4 while the ticket
pipeline runs. Unclaim always applies escalation/requeue labels; only the owning
host can remove an existing claim's @me, host label and comment, even after expiry.
An in-process claim must also match the elected nonce before cleanup. Tickets
assigned before host claims were enabled retain the original @me release path.
If the label/assignee edit fails, unclaim retains its comment and host label so
another host can recover the assignment after TTL expiry. Successful host-label
removals journal claim-label-removed receipts. The manager ignores those exact
labels from the authenticated dispatcher only before the recorded escalation
comment; human removals and later edits still hold automatic management.
Expired claims are admitted through the frontier only when no other hold exists.
A human assignee or an open agent/<ticket> PR with an expired claim remains a
hold after heartbeats stop, so completed work awaiting CI/review/merge is not run again.
Each heartbeat revalidates the elected host and nonce. A displaced owner stops
renewing rather than reviving an expired claim ahead of its replacement.
Every refresh requeue publishes an authenticated Factory requeue: nonce=<uuid>
issue comment with the refresh instructions, including when the owner releases
its claim. The next host can consume that context even after the claim is deleted.
Deferred actionable review rework uses the same ownership-aware release and shares
its findings, so another host can resume the existing PR after the lease expires.
Shared instructions take precedence over this host's local requeue journal. Local
risk-disagreement history carries forward only when its instructions match the
selected context; an intervening foreign requeue cannot trigger early escalation.
Escalation comments carry the same nonce marker on their second line, preserving
the escalation prefix. A later manager/human ready-for-agent relabel can resume
the expired claim's existing PR; its live heartbeat still holds admission.
Neither transition can release a later worker's claim or its completed-PR hold.
Expired ownership follows election order, not the newest raw comment: a contender
created during the winner's last live lease cannot supersede its requeue marker
just because loser cleanup failed. A claim created at or after that lease expires
starts a new election, so an old requeue cannot release newer completed work.
Assigned stale claims stay intact until a replacement wins and assigns, so admission
or claim failures cannot strand the shared @me assignment without recovery evidence.
Dispatch then rechecks the heartbeat, removes stale comments/labels without clearing
the shared assignment, and records claim-released with the old host and last heartbeat.
The elected owner revalidates its nonce before cleanup; a losing contender still
deleting its live claim cannot block retirement of old stale ownership. Owner
unclaim also retires older stale claims before deleting its own comment, so
leftover claims cannot strand a later refresh requeue or escalation/relabel.
Unassigned stale claims can be released before election. A foreign host label without
a claim comment remains a hold; inspect it before removing it.
Cleanup removes the host label before deleting its last claim comment, so a
failed label edit retains TTL recovery evidence for the next pass. Another
same-host contender keeps its label. If comment deletion fails with the comment
still present, cleanup restores the label and surfaces the error.
Hosts need synchronized clocks and current GitHub reads. This comment-based
lease is not a fencing token for a disconnected worker that outlives its TTL.
With host_name unset and no repository host evidence, ticket assignment retains
the single-host path after preflight; triage and landing remain enabled even when
triage_host or land_host is configured.
[worker_wrap] is host-only: set command under [defaults.worker_wrap] or
[repo."owner/name".worker_wrap] (per-repo wins). Its argv is prepended to
every worker launch, whichever [workers] label is selected, including labels
a repository adds. A committed .factory.toml [worker_wrap] is a load error,
so a repository cannot replace or remove it. Placeholders: {cwd}, {prompt},
{root} (main checkout), {repo} (owner/name), {home}. Unset = unchanged.
[defaults.worker_wrap]
command = ["/usr/local/bin/my-wrapper", "--worktree", "{cwd}"]This is a trusted operator-chosen executable, not a sandbox: Factory supplies
no network, credential, gate or reviewer isolation, and the wrapper inherits the
launch environment. A containing wrapper must expose the prompt (inside the
worktree) and the linked worktree's common Git directory (under {root}/.git)
at the same absolute paths.
Leak terms that must not appear in a public repository, such as codenames or
internal hostnames, go in host config: extra under [defaults.leak_scan] or
[repo."owner/name".leak_scan]. Host, per-repo host, and committed extra
lists all add to the scan; the host cannot set pattern or exclude. A leak-scan
failure lists each hit as path:line: [matched term] line.
[defaults.leak_scan]
extra = ["\\bbluefin\\b", "\\.example-corp\\.com\\b"]Each worker attempt journals one llm-usage event (stage = "worker") with
model, prompt_tokens (cached included), completion_tokens,
cached_tokens, cost, and local; anything the worker does not report is
null. local is recorded from an explicitly loopback/private triage endpoint
or by matching worker/reviewer usage to the configured local triage model id,
never by guessing from a model name. A table worker reads usage from structured
output: usage maps each field to a dotted JSON path (or an array of paths,
added) summed over the JSON lines of the attempt log that satisfy match.
Without a cost path hit, cost falls back to [dispatch] cost_pattern. When
log paths report no tokens, an omp-session transcript supplies the
OMP-compatible session totals instead. factory stats --by-worker attributes
those totals to the worker's claim label; workers with neither source remain
n/a (not reported).
[workers.claude] # Claude Code `-p --output-format json` prints one result object (paths checked on 2.1.292)
command = ["claude-worker", "--output-format", "json", "{prompt}"]
[workers.claude.usage]
match = { type = "result" }
cost = "total_cost_usd"
completion_tokens = "usage.output_tokens"
cached_tokens = "usage.cache_read_input_tokens"
prompt_tokens = ["usage.input_tokens", "usage.cache_read_input_tokens", "usage.cache_creation_input_tokens"][prices."<model>"] (host config, e.g. [defaults.prices."qwen3:30b"]) gives
USD per million prompt and completion tokens, optionally cached. factory stats and the dashboard's llm_usage use it for triage, review and worker
events that report tokens and a model but no cost (triage: [triage].model;
OMP review and OMP worker transcripts: the model id without provider). Without
an entry no dollar figure is shown. factory stats lists per-stage tokens and
dollars plus per-ticket totals. Keys are the recorded model string; values are
USD per 1,000,000 tokens, and cached (when set) bills the cached share of the
prompt instead of prompt:
[defaults.prices."claude-opus-5-5"] # every repository on this host
prompt = 15.0
completion = 75.0
cached = 1.5
[repo."acme/widgets".prices."qwen3:30b"] # one repository
prompt = 0.0
completion = 0.0Labels (needs-review, needs-viability, needs-triage, needs-info,
ready-for-agent, ready-for-human, factory-approved, chore, initiative,
experiment)
and the agent/<n> branch scheme are fixed conventions; factory init creates
the labels. needs-review opts a PR into direction viability and dispatch's review-only intake;
needs-viability opts an issue into viability before triage.
Before the manager runs, dispatch discovers open, non-draft PRs labeled
needs-review or with a pending review request for the authenticated gh account.
Contributor branch names are unrestricted. Intake writes review-intake events
with pr and head to .factory/events.jsonl, skipping already-recorded pairs
under the shared PR/issue lock. Dry runs only print eligible revisions. For each
newly admitted revision, the configured [review] command receives the diff
between the recorded base and head SHAs. Valid final VERDICT: APPROVE or
VERDICT: REVISE output publishes an approving or changes-requested GitHub review
through gh api, explicitly bound to the recorded head with commit_id.
Findings must each cite path:line; malformed output or a failed reviewer
publishes nothing. Branch advancement cannot retarget the supplied diff or review.
The same base-ref [review].policy, structured tally, nit cap, and
Important-only blocking rule apply to this lane.
Prompts exceeding 120 KiB (UTF-8, including the diff) are skipped before reviewer
execution and recorded as unknown with reason prompt_too_large; intake
continues with the next PR. The recorded revision is not automatically retried.
Dispatch records SHA-specific required-CI readiness for admitted PRs and escalates
exhausted review attempts to a human issue. This lane does not change contributor
branches or merge external PRs.
The dashboard's Ops → External PR review queue lists open, non-draft opted-in
PRs, including review-request admissions after GitHub consumes the request.
Each GitHub-linked row shows the repository-local PR number, title, author,
current head SHA, last reviewed SHA and verdict, and required-CI state with its
last observation time. CI evidence comes from dispatch's review-readiness
events, not a new CI poll; missing evidence for the current head is unknown.
The six queue states are pending review, changes requested, CI pending,
CI failed, ready, and escalated. An old approval never makes a new head
ready, and readiness is advisory—not permission to merge.
Changes requested, failed CI, escalations, and pending reviews needing human
attention also appear in Inbox, with links to GitHub rather than mutation
controls. Viewing or refreshing the queue does not change labels, reviews,
branches, or merge state.
-
Workspace (
factory dashboard): the root opens Overview. The single application follows outcomes, observed flow constraints, attention, decisions and their results. Flow contains live cases only; historical completion belongs in Success. Selected nonterminal cases, evidenced started WIP and active executions are separate counts. Missing history is unknown, not zero or an exact repository-wide WIP total. Wait durations use recorded wait identities, not an issue's last update time. Return-after-absence comparisons name their browser-local baseline and evidence coverage. System retains Ops diagnostics, dispatcher runs, tickets, gate/review evidence, worker logs, upstream state and the supported case-action menu. Codebase and Atlas are native views, not embedded pages. Settings separates browser preferences from the existing revision-checked local repository controls. The theme selector includes the configured repository stylesheet. Atlas prints reference diagrams and source links pinned to the published Codebase revision; unverified or absent source paths are identified rather than invented.Serving defaults to
0.0.0.0; use--host 127.0.0.1to restrict it to loopback. The startup checkout owns.factory/workspace-access.key(mode0600). Every browser, including loopback clients, enters the key in a masked unlock dialog. Cancel suppresses automatic prompts; Refresh selected reopens it. Read the file securely on the host; no unauthenticated HTTP endpoint discloses it. Add--allowed-host NAMEfor a trusted DNS name. Use a trusted LAN, Tailscale, or an authenticated encrypted tunnel—not public plain HTTP. The key grants the server's configured GitHub identity and local repository-setting authority; it is not a separate multi-user login or role system.The repository selector uses District's existing host registry. A registered main-checkout path wins over a same-slug startup clone, and its root is visible. Clients cannot supply roots or arbitrary service URLs. Host-admin operations remain District-owned. Rendering returns cached data immediately while bounded, admitted background readers refresh it; errors retain useful last-good evidence with timestamps and coverage. Hidden pages do not drive polling.
Ask FM opens the persistent right dock scoped to the selected case; repository chat uses repository scope. Case chat requires a matching cached inspection. It uses authenticated
omp,[manager].model(or the existing configured command's model/default), and bounded cached sources with citations. The transport has no tools and cannot apply decisions. Evidence is sent to the selected model provider; conversations remain browser-local and are not GitHub comments.Direct/Respond prepares a server-issued exact preview of supported actions. Confirming rechecks the actor and affected state, then persists intent before any effect. Retrieve the durable receipt after refresh/restart and use Check resulting state separately. Partial and uncertain results remain explicit; replay never repeats an ambiguous effect. Cancel does not execute the proposal.
/api/actis removed; authenticated prepare/apply/receipt endpoints own actions. Upstream-sync issues cannot be requeued as ordinary worker tasks. Approval is not fabricated review evidence, and cleanup cannot race an active claim. Triage executes the controller's trusted Python package, not a shadow package in the selected checkout. Cleanup coordinates with both landing and ticket claims, binds local revisions, refuses dirty worktrees, and deletes the branch only if its SHA still matches the preview (including squash-merged branches). A nonzero mutation command can still have applied an external effect: its receipt remains uncertain until separately observed; another confirmation never reruns it.Outcomes distinguish implementation/merge from owner attestations of release, installation, health and accepted usefulness. Attestations cite a source revision and evidence URL and bind to the current canonical initiative revision and its declared owner's GitHub identity. They are not machine deployment/health proof or permission to publish/install. Missing, partial, edited or superseded evidence cannot establish current acceptance.
Theme choices persist in this browser: Cyberpunk, GPUFlo, District, Factory, ROCm, Porcelain, Sandstone, Slate and Forest. Motion respects reduced-motion preferences. The completion plan records qualification and cutover separately from source implementation.
-
Spend: the Spend KPI and each ticket's attempts tab total worker+gate wall clock from
events.jsonl, plus dollars when the worker reports them (a[workers.<label>] usageprofile orcost_pattern). -
Learning loop: after a batch of tickets,
factory learn --dry-run, read the proposed lessons, thenfactory learnand commit.factory-lessons.md. Workers see it on every ticket. At the end of every dispatcher pass,factory scorescores unscored finished attempts (at most 50), independently of the learning threshold, manager availability, or open proposals. With[manager]configured, once 10 tickets have finished (latestmerged/escalaterow) since the last successfullearnevent (manual or automatic; from the journal start if none), the dispatcher decides open promotions on the scores (below), then, unless that opened a revert (learn: skipped (revert PR opened: ...); a lessons PR would conflict with it), runsfactory learn --last 10and journalslearnwithtrigger: "auto". It skips while anagent/lessons-*,agent/curate-*oragent/revert-lessons-*PR is open (learn: skipped (open lessons PR #N); the count is kept). Blocker changes journallearn-wait; the same PR blocking learn for over 24 hours journals exactly onelearn-blockedper uninterrupted wait, surfaced byfactory watch. A different PR starts a new clock; clearing the wait clears its watch signal. Without a manager, learn logslearn: skipped (no manager); scoring still runs. A failure is journaled aslearnwithstatus: "failed"and areason, never fails the pass, and keeps the count, so the next pass retries. Lessons and CURATE proposals require gate, reviewer APPROVE (posted as a GitHubCOMMENTreview since the dispatcher cannot approve its own PR;review-resultcarries the verdict), CI,factory-approved, and squash. A recordedpromotion-revertcan instead pass on its nonempty measured baseline score: the candidate's changed paths must exactly match the original promotion's, and their contents/modes must equal that merge's parent versions. This is checked against the exact candidate head, not a branch-name exemption. Such restorations need gate and CI, not reviewer APPROVE or a new worker eval; theirapprovedrow recordsrestored_scorerather than claiming a review. A human GitHubCHANGES_REQUESTEDreview still blocks every proposal, including measured restorations; factory reviewer findings posted asCOMMENTare distinct. An unmeasured or modified restoration still needs review and scheduled eval. Only same-repository heads are admitted by branch name; a fork PR namedagent/lessons-*still needsneeds-review. The guard is measurement, not a person: each non-revert merge journalspromotion-openwith the score means of the 10 attempts before it, and once 10 attempts journaled after the merge are scored the same pass journalspromotion-keeporpromotion-revert(openingagent/revert-lessons-<pr>) when efficiency or the first-pass rate fell beyond the baseline's noise (pstdev);factory stats --promotionslists the decisions. Edit or delete lessons that don't earn their keep. Claimed improvements to a prompt, skill, rubric, model, or effort follow the eval promotion contract (train/lockbox splits, repeat scores, keep/revert).[learn] evaluate = true(or one manualfactory learn --evaluate) changes proposal into a paired replay: up tomax_ticketsrecent tickets that recorded a frozen issue snapshot and pre-work revision run in isolated checkouts with the configured worker, gate and reviewer, first without and then with each lessons-file or CURATE candidate. Replay subprocesses haveGH_TOKENandGITHUB_TOKENremoved,ghuses an empty config, the clone's origin is local, and a rejectingpre-pushhook blocks ordinary pushes. The candidate is kept only when first-gate passes are no lower, review rounds and REVISE findings are no higher, and at least one metric improves. Reported usage counts towardmax_tokens; reviewers that do not report usage still run, remain bounded bymax_ticketsandbudget_min, and showtokens not reportedin the evidence. An unavailable replay or budget exhaustion recordslearn-evaluationasnot_tested, opens no PR and never escalates. Kept PR bodies include the ticket/base set, both arms, and token/dollar/wall-time cost. Both arms' reviewer prompts receive the same neutral ticket and recorded-base context, without completed evaluation results. Before publishing a kept lessons or CURATE PR, the actual candidate diff runs the normal attempt and PR-tier gates and the configured reviewer, pinned to the gated head. This separate candidate review receives the completed ticket/base set, both arms' results and costs, and judges the learning proposal rather than the incident tickets' implementation criteria. Alearn-candidate-reviewrow retains the proposal, head, verdict, findings and reported reviewer usage. Gate failure, REVISE or invalid reviewer evidence publishes nothing and does not escalate. The learn/CURATE decision record cites both replay and candidate review evidence. Approved PR bodies include the candidate review and enter the normal promotion flow: an independent head-bound PR review and green CI allow automatic merge, while a human change request vetoes it; the post-merge score window can still revert a regression. Evaluation is off by default, so existing learning behavior is unchanged. -
Frozen worker evals:
factory/eval-suite.jsonpins 20 real Factory and rocm-cli tickets: repository, issue snapshot, pre-work revision, accepted gate/reviewer outcome, acceptance criteria, manifest version, and train/lockbox split. New versions may add cases but never move an existing lockbox case out.factory eval --profile NAME --dry-runlists the suite and configured[eval]case/token/wall budget. A real run uses two repeats in sandboxed clones, the selected worker profile, and current candidate lessons, agent rules, and skills committed as the replay baseline; Factory cases retain their pinnedAGENTS.mdbecause the historical gate validates its feature map. Each case otherwise keeps its pinned gate and reviewer. Pushes and GitHub credentials remain disabled by the shared learning-replay machinery. Every case/repeat is anevalrow; the summary records first-gate pass, review rounds, REVISE findings, tokens, wall time, per-split means and population-stdev noise, the worker-context fingerprint, and captured Primescope: globalentries when present. An accepted-main run establishes the baseline; rejected and unmerged candidate runs never replace it. Later same-profile runs usepromotion.decide(objective="regression"): parity/changes within repeat noise keep, a train or lockbox drop beyond noise reverts, and any revert for a candidate head permanently blocks that head. Budget exhaustion or unavailable evidence isnot_tested, never an escalation. With[eval] schedule = true, changes to.factory.toml,.factory-lessons.md,AGENTS.md,CLAUDE.md,factory/brief.py,factory/config.py,factory/dispatch.py,factory/learn.py,factory/templates/agent_task.md, or anySKILL.mdrequire an exact-headkeeprow at merge; a missing claim reports the exactfactory evalcommand. The same setting installs a persistent weekly timer using[eval] profile; scheduled drops beyond noise setflagged: truein the journal. -
Runner preflight: before assigning a ticket (including
dispatch --ticket), reap abandonedfactory-runner-*scratch roots, then require at least 1 GiB free and 10,000 free inodes on both the repository and temporary filesystems. Filesystems reporting no inode limit skip the inode check. Low storage recordsrunner-infrawith reasonrunner_storage_low, path, resource, available, and minimum; an unreadable filesystem recordsrunner_storage_unavailable. Neither claims the ticket nor records an attempt or escalation; retry next pass. Watch treats both refusal reasons as host conditions: transient refusals are ignored; an uninterrupted streak spanning[watch].host_failure_minutesfiles with thehostlabel rather than as a Factory lifecycle defect. Reviewer, gate, and isolated GitHub-config roots hold directory flocks for their owner's lifetime. After normal exit or a crash, only confirmed live process use (cwd, open files, or inherited scratch environment) retains an unlocked root. Unknown/unreadable process visibility alone never protects it. Linux process state is parsed as bytes so non-UTF-8 process names do not interrupt cleanup. Read-only review snapshots are removable, and legacy one-day temp sweeping remains in place. -
Audit trail:
.factory/events.jsonlretains the ticket outcome events (claimed,attempt,pr-opened,review,approved,refreshed,conflict-requeue,merged,escalate,upstream-sync, andhuman-decision;gate,promotion-open,promotion-keepandpromotion-revertforfactory learnPRs) alongside versionedlifecyclerecords. See the event contract below. A ticket's history is local; no GitHub call is needed. Past[journal] max_mbthe live file rolls into gzip segments (events.jsonl.1.gz,.2.gz, … up toretention); outcome rows are never dropped, only closed-executionlifecyclerows of expired segments are. Commands that load repository configuration use its journal settings, including worker commands running from a worktree. -
Transcripts: OMP workers and table workers declaring
transcript = "omp-session"run with--session-dir .factory/transcripts/<n>/, so each attempt's compatible JSONL session stays on disk per ticket. Theattemptrow'stranscriptfield names the file (null for undeclared workers or--no-session). Worker usage,factory score, andfactory learnconsume these sessions. -
Handoff notes: each worker attempt ends by writing
.factory/wt-<n>/.factory/handoff-<n>.md(what changed, what is unverified, what next). The next attempt gets it in its prompt; an escalation quotes it in the issue comment. Independently accepted handoffs are retained outside the worktree under.factory/results/<ticket>/<accepted-head>/; see retention. -
Logs:
.factory/logs/<n>-attempt-<k>.logper worker round;.factory/wt-<n>/.factory/gate-report-<n>.mdper gate;journalctl --user -u factory-<repo>.servicefor dispatcher passes. -
Re-run one ticket by hand:
factory dispatch --ticket N(bypasses the frontier and its label checks; respects the in-flight lock). -
Stop everything:
systemctl --user disable --now factory-<repo>.timer. In-flight tickets finish their current pass; nothing new is claimed. -
Tear down a ticket: verify any accepted handoff is retained before manually removing
.factory/wt-<n>withgit worktree remove --force, deletingagent/<n>, and re-labelling the issue. Manual removal bypasses the dispatcher's retention guard.
Factory retains the full worker handoff at durable, exact-head approval and checks
retention again before merge cleanup. Worker exit zero, gate PASS, a label, or a
valid REVISE response cannot establish acceptance. Existing reviewer, configured
manager, CI, human-veto and exact-head merge safeguards are unchanged.
These are Factory product defaults, per repository, not host/session retention settings. There are no configuration overrides in this interface:
| Limit | Default |
|---|---|
| Full handoff content | 90 days from original recorded acceptance |
| Body-free provenance/status receipt | 365 days from that acceptance |
| One artifact | 256 KiB |
| One result bundle, including metadata | 1 MiB |
| Repository result archive, including temporary writes | 256 MiB |
Reads and repeated observations never renew these lifetimes. Expired content is unavailable immediately to readers; the next non-dry-run dispatcher pass removes expired payloads, then removes receipts at 365 days. Reads never prune or acquire writer locks. These limits do not rotate existing journals, logs or transcripts.
Storage is the main checkout's gitignored .factory/results/<ticket>/<accepted-head>/,
with a bounded manifest.json and, when available, raw handoff.md. The manifest
preserves accepted-head provenance, compact acceptance receipts, the first matching
attempt's observed source head (or explicit unknown), source/retained byte counts
and SHA-256 integrity, producer identity, and accepted-contract revision references.
The source head is an observation, not proof of when the handoff was authored.
Refreshing/rebasing does not silently reattribute older bytes to a new head.
A different result never silently replaces an existing record at the same head.
Only the handoff and compact provenance are retained: no transcript, worker log, prompt, configuration/environment dump, or broad discussion ingestion. Common credential forms are withheld, not silently redacted; this is not comprehensive DLP. Explicit incomplete/redacted provenance stays incomplete. Local storage is not public-safe evidence and does not authorize uploads, new provider disclosure, or permission changes.
Missing, oversized, withheld, expired, unreadable and integrity-failed sources remain explicit. Quota or archival failure does not evict unexpired results: automatic cleanup leaves the affected worktree intact and reports the reason. Post-merge cleanup is not automatically retried: resolve the reported retention condition before manual cleanup rather than deleting the sole surviving copy. A recorded missing-source result can permit cleanup because there is no handoff content to lose. This protects against worktree cleanup, not runner loss or deletion of the main checkout; it is not a backup service.
Use the kind:"result" evidence read below for a known ticket/head, even when the
ticket is outside current GitHub case-list coverage. Briefings include the newest
retained historical result without displacing earlier human constraints.
Retention and historical acceptance are evidence, never permission to resume or
rewrite scope. The worker prompt built by factory dispatch is the one
revision-aware execution consumer: when a ticket has a prior retained result, its
prompt gets a bounded ## Resume context section reporting the prior accepted
head/result and whether the admitted scope (this ticket's plan-bound baseline)
is unchanged, changed, or unavailable since that result, using only the
local plan-bound journal and the retained result -- never a worker log, prompt,
or transcript. This is descriptive only: it never rewrites the pinned scope or
the ticket, and a changed or unavailable comparison never silently authorizes
continued execution.
.factory/events.jsonl is the single append-only journal for legacy ticket
outcomes and authoritative execution evidence. When it passes [journal] max_mb
(default 64) the appender, still holding the journal flock, rewrites the live
inode in place: lifecycle rows of open executions stay live, everything else
rolls into events.jsonl.1.gz and older segments shift to .2.gz, … up to
retention (default 8). When retention decreases, existing segments are all
read until the next rotation folds non-lifecycle rows from every expired
segment into the oldest kept segment and removes the excess segments. Thus
lifecycle.read_events and journal_snapshot return every outcome row
(segments oldest first, then the live file) and dedupe, attempt counts and
spend survive rotation. All commands that load repository configuration,
including worker commands in worktrees, use its journal settings. Tail-only
readers (runtime status, briefing, evidence) read the live file alone. An
execution is one entered scope, not a ticket's entire history. A dispatcher
pass, an independent triage run with no tickets, every worker attempt, and
each later PR revisit have their own identities. Parent/child scopes may
overlap; never collapse them into the newest ticket event.
Every event: "lifecycle" row includes all these keys. null means not
applicable or not known; it is not a fabricated ticket, run, round, or result.
| Key | JSON type | Meaning |
|---|---|---|
event |
string | Always "lifecycle". |
schema_version |
integer | 1; unversioned ticket events are not lifecycle version 1. |
event_id |
string (UUID) | Stable identity of this transition. Ordinary events use UUIDv4; reconciled interruption exits use a deterministic UUIDv5 per execution. |
sequence |
integer, ≥1 | Starts at 1, increases strictly within execution_id, allocated under the journal lock. |
execution_id |
string (UUID) | One stage invocation; never reused for a retry or revisit. |
parent_execution_id |
string (UUID) or null | Immediately enclosing execution, including across instrumented subprocess launches; null for an independent root. |
root_execution_id |
string (UUID) | Root execution of this causal tree; an independent execution names itself. |
dispatcher_run_id |
string (UUID) or null | Shared by a real dispatcher pass and its descendants. An independently invoked triage or gate has null, not an invented dispatcher run. |
ticket |
integer or null | Associated issue number; dispatcher, scheduling, and no-ticket triage scopes need no issue. |
attempt |
integer or null | Existing worker-attempt numbering, inherited by its gate. Review-bounce attempts retain the existing max_attempts + bounce numbering. |
review_round |
integer or null | Initial review is 1; revision worker/gate/review scopes use bounce + 1. Initial worker/gate scopes and unrelated activity have null. |
stage |
string | Actual entered scope, listed below; not inferred from labels or artifact times. |
kind |
string | "enter", "exit", or an evidence event listed below. |
at |
string | UTC source timestamp, ISO 8601 with microseconds and Z. A reconciled exit uses the time of observation, not an estimated crash time. |
outcome |
string or null | Terminal classification on exit; null on other kinds. |
reason |
string or null | Supported terminal reason or diagnostic text, not a closed enumeration; null when no reason is known. |
process |
object or null | Owner identity sampled on entry: pid (integer), boot_id (string or null), start_ticks (integer or null), pid_namespace (string or null), uid (integer or null), state (process-state string or null), ppid (integer or null). Factory emits an object; the reader also accepts null as unavailable authority. This cached identity is not a live heartbeat. |
locks |
array of objects | Recorded exclusion evidence, possibly empty. Each object has path (absolute-path string), device (integer or null), and inode (integer or null). Null identity fields mean unavailable evidence. |
IDs and sequence numbers survive repeated reads. Sort a single execution by
sequence, use parent/root/run IDs for causality, and deduplicate by event_id.
Neither wall-clock timestamps nor physical append order establish a causal total
order across independent executions. A scope has one enter and at most one
terminal exit; an abrupt death can leave the exit absent until observation
has enough evidence to reconcile it. Extra keys and evidence kinds may be
added; consumers should ignore those they do not understand. Unsupported schema
versions are not interpreted as version 1 by the existing observer.
Linux identity fields retain their procfs values: boot UUID, field-22 start ticks,
and PID namespace link. On macOS, lifecycle and passive runtime observation share
one private backend, and only the verified receipt is read: macOS 27.2, arm64,
64-bit pointers, little-endian. Any other combination is unknown and does not
guess offsets. kern.bootsessionuuid identifies the boot. Process identity
comes from proc_pidinfo(PROC_PIDTBSDINFO) on the verified 136-byte layout;
journal start_ticks stays that start time in integer Unix seconds, and the
microsecond field is used only to compare two reads of the same process. A
runnable-to-sleeping transition does not make that identity new. A changed
parent or uid does. Context tags come from KERN_PROCARGS2 into one
KERN_ARGMAX-sized buffer (1 MiB on the verified host). A full buffer is
truncated and unknown. proc_listallpids uses byte sizes and returns a pid
count; a buffer that comes back full is retried, then incomplete. Identity
reads follow kernel order up to 4096 pids. Context reads stay capped at 256.
Processes that started after their own uid's known process-start second are
read newest first. The same second and any earlier start stay deferred, and
an unknown origin keeps that uid deferred. Another uid's start is not a
cutoff. Membership is a context tag or a start-validated ancestor. The
continuation hand is that process's pid and start. It stays eligible when the
same process is also newer than the previous read, and a deadline does not
skip it. Past either cap, or while any deferred process is unread, the scan
is incomplete. pid_namespace is "darwin".
Host IDs hash the IOKit IOPlatformUUID with the same UUIDv5 scheme as Linux
machine-id. The guarded observer never runs ps, lsof, sysctl, or
ioreg. Denied, malformed, empty, or truncated reads are unknown, not absence.
A missing recorded PID or a changed start time proves the original process dead
only when this observer can see itself. Descendant membership is a context tag
or a start-validated ancestor, not a uid and not a parent pid alone. The existing
handoff safeguard still prevents interruption when a launched descendant cannot
be ruled out. There is no non-spawning flock-owner source: attribution stays
unavailable, the owner stays null, and an open file is not ownership. The same
limit covers passive resource state and observed admission capacity. State stays
unknown, not free. With any numeric ticket lock, capacity.active is null
and capacity.complete is false, never zero. A lock directory that was listed
and contains no numeric ticket lock is zero. A retained observation is not a
fresh reading of the current lock.
| Stage | Boundary |
|---|---|
dispatcher |
One real dispatcher pass; idle passes with nothing claimed, triaged, merged, waited on or failed leave no lifecycle rows. Completion means the pass ended, not that any ticket merged. |
scheduling |
Frontier/capacity evaluation and scheduling; separate from ticket execution and merge eligibility. |
landing |
The existing nonblocking merge-lock request and, when acquired, upstream sync staging and the merge pass through actual unlock. |
ticket |
A ticket admission/invocation, including nonblocking lock request and admission re-read. Admission refusal is not worker time. Later PR passes have separate merge-eligibility executions. |
triage, triage-ticket |
Whole triage invocation and each actual ticket decision; uneventful invocations with no issues to triage leave no lifecycle rows. Standalone triage retains its own root identity and null dispatcher association. |
worker |
One worker subprocess attempt. |
gate, gate-check |
An invoked gate and each actually executed check. Skipped checks and a disabled leak scan do not enter a check scope. |
review |
One reviewer invocation, attributed to its review round. |
merge-eligibility |
Assessment/refresh of one candidate in this dispatcher pass; not a merge. |
upstream-sync |
Staging one upstream candidate in a detached worktree (merge, then a gate child when the merge is clean) and filing its sync ticket; exits completed with reason upstream_staged. Never moves main. |
merge |
Actual PR merge. Only a successful PR merge records merged. Approval alone does not. |
resource-observation, scheduling-observation |
Change-only local evidence records, not pipeline invocations. They have stable observation-scope execution/root IDs, no enter/exit, and null parent/dispatcher/ticket/attempt/round fields; execution occupancy excludes them. |
Evidence kinds retain the common keys above and add these kind-specific keys:
| Kind | Additional keys |
|---|---|
handoff |
handoff_id: UUID string, persisted before launching a child. |
child_start |
child_process: process identity object; handoff_id: UUID string or null. |
child_exit |
child_process: the recorded child identity object. |
lock_acquired, lock_released |
lock: path string; locks reflects the updated recorded set. |
check |
check: string check name. |
timeout |
command: array of argument strings; timeout_seconds: integer. |
result |
Depending on the mechanism: returncode (integer), command (argument-string array or string), timed_out (boolean), timeout_seconds (integer), check (string), passed (boolean), verdict ("APPROVE" or "REVISE"), and/or parsed (boolean). These keys are present only when that evidence was obtained. |
Ordinary exit with unreaped children |
evidence: object containing children (process identity/state objects as below). Default completed becomes unknown; a supported exception classification is retained. |
Reconciled exit |
reconciled: true; observer_process: process identity object; evidence: the observation object described below. |
outcome |
Meaning |
|---|---|
completed |
The entered operation returned normally; not a claim that a ticket or PR is complete. |
product_feedback |
Configured checks found failing code, a parsed successful reviewer requested REVISE, or triage requested information/human attention/proposed wontfix. |
project_escalation |
The existing project escalation path ran; not a broken runtime mechanism. |
approved, merged, refreshed |
The corresponding operation succeeded; these are distinct outcomes. |
not_admitted, not_eligible |
Admission re-read refused the ticket, or merge prerequisites did not allow merging. No skipped downstream scope is invented. |
mechanism_failure |
Evidence that the configured mechanism could not run, such as a missing/permission-denied executable or unavailable triage endpoint. |
unknown |
The cause is unsupported or uncertain, including unexplained worker/reviewer nonzero exits, unparsed verdicts, command/API errors, and timeouts. A timeout alone is not proof of runtime failure. |
interrupted |
A previously unterminated execution was reconciled using authoritative liveness and lock evidence. |
Reasons include configured_check_failed, conflict_markers,
leak_scan_matches, APPROVE/REVISE, check_timeout,
triage_endpoint_unavailable, no_tickets, state_changed, ci_pending,
and no_passing_ci; exceptions may instead provide diagnostic text. Reasons
are evidence, not a replacement for outcome. Existing gate exit codes,
review retry behavior, claim locks, concurrency limits, and merge prerequisites
are unchanged.
The dashboard snapshot (factory dashboard --json or authenticated
/api/snapshot?repository=<slug>) includes a bounded executions array from the
passive runtime reader: concurrent stages, no-ticket runs and local evidence remain
visible when GitHub collection fails. coverage names retained-window limits;
these are not lifetime totals. Each entry contains
execution_id, parent_execution_id, root_execution_id,
dispatcher_run_id, ticket, attempt, review_round, and stage with the
types above, plus:
state:"active","completed","failed","interrupted", or"unknown". Onlymechanism_failuremaps tofailed; product feedback/escalation and other known ordinary outcomes map tocompleted.entered_at: sourceentertimestamp;ended_at: source/observed exit timestamp or null. An exit with unknown outcome has anended_atbut is not active.outcomeandreason: terminal values or null while unterminated.events: source lifecycle rows in sequence order.evidence: normally null on ordinary terminal exits, or the partialchildrenobject above when the scope exited before reaping its children. An unterminated/reconciled observation instead has an object withprocess("alive","dead","unknown"),children(objects withprocessidentity and the samestatevalues),locks(recorded lock objects plusstate:"held","free", or"unknown"),descendants(process identities),scan_complete(boolean: process-scan readability),descendant_absence_proven(boolean: authoritative absence of surviving descendants), andpending_handoffs(UUID-string array).wait: the current known wait object plus sourceevent_idandat, or null. It is distinct from execution liveness: a live waiting process can havestate: "active"without doing check/worker work. Unknown/dead/terminal executions do not retain a current wait; their source wait rows remain historical evidence.
Observation uses the bounded runtime reader, including its process-identity, lock-evidence and descendant-coverage limitations. Inaccessible or incomplete evidence remains unknown; an old artifact or a reused PID does not prove activity. Source transitions remain distinct from the observation and its time. Dashboard reads neither acquire the lifecycle journal lock nor append interruption, recovery or scheduling-observation records. They do not change scheduling or lock ownership.
HTTP snapshots are collected off request threads with bounded process/time/output admission. A cold snapshot returns HTTP 202 with collection status; a retained snapshot returns immediately while a due refresh runs. Legacy audit/spend/worker metrics read only committed lines from a capped live-journal window and report partial coverage when archives, clipping or malformed input are omitted.
The existing ticket phase is null unless there is one unambiguous active,
non-waiting leaf among its unresolved executions. Active wrappers do not hide their child
stage; an unknown child or simultaneous independent stages prevents selecting
one. When present, phase keeps at (source entry timestamp), artifact
(legacy field name, now the authoritative stage string), and attempt
(integer or null), and adds execution_id (UUID string). Logs/reports remain
available as evidence, never as stage truth. A ticket lock still drives the
existing in-flight/admission count, not proof of a particular executing phase.
All Factory producers serialize complete UTF-8 JSON lines under a shared file flock,
flush and fsync before returning, and allocate execution ordering under that
same lock. Readers accept only newline-terminated JSON objects and skip malformed
JSON, non-object rows, and unterminated tails. On the next append an unterminated
tail is invalidated with a NUL byte and newline before the new record; even a
syntactically complete but uncommitted tail is never promoted into activity.
Old unversioned rows retain their existing event names and fields without
retrofitted IDs, stages, or liveness. New legacy ticket events emitted within
an execution also carry execution_id (UUID string) and dispatcher_run_id
(UUID string or null) as causal references; they are still not lifecycle rows.
Dashboard spend counts only legacy attempt rows;
learn excludes lifecycle rows from finished-ticket selection and evidence;
stats still uses GitHub issue/PR comments, so lifecycle exits do not double
attempt, review, or outcome counts. dispatch --dry-run and
triage --dry-run/--replay record no lifecycle activity.
Dispatcher dry-run does not create claim/merge lock files or fetch remote refs.
With an upstream configured, it reports that a real pass would fetch and
evaluate upstream rather than claiming a fresh behind/ahead count.
F02 adds evidence to the version 1 lifecycle journal, not a second telemetry stream, controller, resource broker, or lock. All rows retain the identities, sequence, source timestamps, and interruption rules above. The bounded F03 runtime CLI below reads these same producer records without persisting observations.
Known waits use kind: "wait" with a wait object:
| Key | Type and meaning |
|---|---|
reason |
Nonempty string for a known reason; absent knowledge is represented by no current wait, never guessed from elapsed duration. |
mode |
"blocking" (an actual acquisition can block), "retry_next_pass" (this pass skips), "admission" (capacity decision), or "eligibility" (observed merge prerequisite). |
resource |
Resource descriptor below, or null for non-resource waits. |
details |
Object containing only decision evidence available at that point. |
wait_end ends a blocking wait when acquisition succeeds; a request itself is
not acquisition. A terminal scope ends its current wait without claiming the
underlying prerequisite became satisfied. Nonblocking skips, capacity decisions,
and merge eligibility remain historical decision facts after their scope exits,
not indefinitely active stages.
| Reason | Existing observation point / details |
|---|---|
capacity_reached |
Admission count reached max_active; active and max_active integers. Demand does not prove dispatcher liveness. |
ticket_lock_contended |
Ticket preflight found the lock held or its nonblocking acquisition lost the race; retry next pass. |
worker_unavailable |
A frontier claim found the ticket's worker executable (executable in details) missing from the dispatcher's PATH (e.g. mid-upgrade); the ticket is left unclaimed and retried next pass instead of failing after assignment. dispatch --ticket still launches and fails loudly. |
claim_failed |
The claim command failed before assignment; the ticket is left unclaimed and retried next pass. |
merge_lock_contended |
Nonblocking landing lock miss; skip this pass, retry next pass, never convert to a blocking wait. |
exclusive_resource |
Gate observed its exclusive lock held before the unchanged blocking acquisition. |
ci_pending |
Existing pr_checks result contained pending checks; pr integer. No extra CI query or polling loop. |
no_passing_ci |
Existing result had no passing check; pr integer. The cause is unknown, not an inferred CI outage. |
scheduled_next_pass |
Local timer explicitly active, service explicitly idle, and a future next_at timestamp reported by the existing systemctl seam. |
Review revision, escalation, eligibility, execution-stage occupancy, and waits are separate facts. None of these reasons, a held resource, or elapsed time alone creates a machinery incident. Gate outcomes and CI/human-veto prerequisites are unchanged.
Resource events distinguish resource_requested, enriched lock_acquired, and
enriched lock_released. Each includes a resource descriptor. Only an actual
successful flock acquisition supplies confirmed holder evidence. Acquired and
released rows share an acquisition_id, so delayed evidence for an older holder
cannot clear a newer acquisition. Inherited F01 locks support liveness only:
children and dispatcher parents do not thereby become resource owners.
The gate subprocess acquires its exclusive lock once, immediately before the first non-skipped exclusive check, and retains it through all remaining checks. Ticket locks span the pipeline; the landing lock spans upstream sync and merge. There are no new exclusion locks, changes to acquisition order, retry policy, capacity accounting, check execution, or scheduling.
Resource descriptors and observations have this serialized contract:
| Descriptor key | Type and supported scope |
|---|---|
id |
Opaque UUID string, stable for the canonical lock pathname and supported scope; not a ticket number or dependency name. |
scope |
"repository" for ticket/merge exclusion, or "host" for the configured exclusive gate lock. |
host_id |
Opaque host identity string derived from machine identity; without machine identity, limited to the current boot. If neither authority exists, a process-local opaque fallback prevents cross-host grouping and observations remain unknown. |
repository |
Canonical journal-directory string for repository scope; null for host scope. Different repository journals do not imply shared ticket/merge exclusion. |
lock |
F01-style path, device, inode evidence for the canonical pathname. Missing inode/device is unknown authority. |
Host-scoped IDs permit grouping only observations of the same configured lock on the same supported host identity. Different lock paths are not the same GPU or dependency merely because their check names match. Canonical symlink paths coincide; hard-link aliases and independently configured paths are not automatically unified. Identity names a lock pathname, not every past inode unlinked from it. A replaced inode cannot confirm an old acquisition. A single repository's observation does not prove every factory is affected; no journal from another repository is read to guess its holder.
All three resource operation kinds add blocking (boolean: acquisition mode)
and acquisition_id (UUID string for acquired/matched released; null on
requested or an unmatched release, which cannot clear a holder).
The F01 lock path remains on acquired/released rows. The common execution,
root, parent, dispatcher, ticket, attempt, review-round, and process fields
identify the actual requester/holder; request identity is never substituted for
holder identity. wait_end.wait_event_id names the ended wait's event UUID.
| Resource observation key | Type and meaning |
|---|---|
resource |
Descriptor above. |
state, ownership |
Independent string enums described above. none is supported only by observed free state. |
owner |
Null or object with all common execution identity fields, recorded process, acquisition_id, and source acquired_at timestamp. |
requests |
Array of currently live, unterminated requesters not yet acquired/released: common execution identity fields, process, source event_id, requested_at, and blocking. A pending request is not ownership. |
evidence |
Object: lock_state (held/free/unknown), attribution (proc_locks/lsof/unavailable), holder_pids (integer array or null). Linux uses kernel FLOCK owners; macOS uses flock try-lock for availability and lsof's whole-file lock fields for owners, not merely open descriptors. Kernel PIDs alone are not confirmed execution identity. |
event_id, at |
Stable identity and source time of the last distinct local resource observation. |
observed_at |
UTC time of this local evidence collection, distinct from transition time. |
Changes are persisted as kind: "resource_observation" in the same lifecycle
journal, carrying resource, state, ownership, owner, requests, and
evidence. Observer rows have reconciled: true and the observer's process.
Acquisition/release history remains separate from current attribution.
dispatcher.schedule contains wait (the wait object above or null),
timer_active and service_active (boolean or null), event_id, at, and
observed_at with the same transition-versus-collection distinction.
Change-only kind: "scheduling_observation" rows carry wait, timer_active,
and service_active; scheduled wait details include next_at (UTC timestamp).
The full dashboard JSON adds resources. Each resource observation separates
state (held, free, unknown) from ownership (confirmed, unknown,
none). A held lock is not proof of ownership. Confirmation requires both a
live recorded process identity and matching kernel lock attribution; missing
authority, external processes, old F01-only lock rows, and attribution gaps
remain unknown. A dead recorded execution is never retained as a confirmed
current holder, even if its old lock remains held.
Resource observation timestamps describe when evidence was collected. A reconciled ownership change or free observation does not invent the exact time an unobserved process died or released its lock. Repeated unchanged observations reuse transition identity/time rather than producing repeated release/wait events.
dispatcher.timer.active and dispatcher.service_active now accept null when
local authority is unavailable. False means explicitly inactive/failed, not a
missing command, inaccessible service manager, or absent output. The additive
dispatcher.schedule records timer/service evidence and a known scheduled wait
only when confirmed; otherwise its wait is null. Timer interval configuration
and an empty frontier do not establish next-pass intention or deliberate pause.
Dashboard status/configuration display unknown and suppress unsupported
countdowns. Schedule observations never create a dispatcher-run identity.
Because the journal may contain a torn row, a tolerant local ticket query is:
python - <<'PY'
import json
from pathlib import Path
from factory.lifecycle import read_events
for row in read_events(Path(".factory/events.jsonl")):
if row.get("ticket") == 42:
print(json.dumps(row))
PYThe full factory dashboard --json / /api/snapshot observation exposes
tickets[].pr.feedback. The existing Review drawer, Inbox raw evidence, and
factory.briefing.sources_for consume this same object. Non-PR tickets have no
fabricated feedback. --runtime-json does not invoke this collector
and retains its network-free contract.
factory.feedback.collect(read, *, repository, pr, issue=None, events=(), provenance_complete=True, producer_revision=None, observed_at=None, collect_details=True) is the shared producer. read is the existing dashboard
GitHub transport, accepting endpoint for fixed REST GETs or query/variables
for GraphQL reads, plus a remaining timeout. Source exceptions become sanitized
coverage/errors without discarding independently observed facts. There is no
feedback cache, event append, model invocation, delivery, dispatch, readiness, or
approval decision. The full dashboard's pre-existing lifecycle reconciliation
remains unchanged.
Detail reads are limited to open pull requests, so closed history never
multiplies provider calls per refresh. collect_details=False reads nothing: the
schema-1 envelope still carries the caller's independently known repository/PR
identities and state, head_sha stays null, every source is unavailable with
the not_collected reason/error code, and ownership stays unverified. Review,
Inbox and briefing report that intentional noncollection explicitly; it is not an
empty, resolved, or unsupported observation, and it is distinct from an older
engine that has no feedback key at all.
The required envelope is schema_version, producer, observed_at,
observation_id, repository, pr, owner, coverage, items, and errors.
Native repository/PR IDs are retained alongside host/slug, PR number/URL/head,
state and nullable draft. Ownership needs an actual same-repository closing-issue
link plus retained Factory claim provenance; branch text and shared credentials
do not establish it. Relations are factory_issue, unverified, ambiguous,
or none. A missing key or unsupported schema is unknown, not an empty success.
Items retain native source IDs/links, source revision/update time, review/thread/
check-run IDs, nullable run attempt, source versus observed head, disposition,
author, body/truncation, location and provider name/title. Kinds are review,
review_comment, check_run, commit_status, and factory_review; all can
coexist. Review state, thread resolved/outdated state, and check status/conclusion
remain independent. Missing source SHA is never filled with the current head.
Relevance is current_head, historical, or unknown; outdated threads cannot
become current through SHA equality. Provider User attribution remains unknown
because shared credentials may belong to Factory. A Factory review requires a
valid recorded review execution result, successful parse/exit and matching target
SHA; ordinary discussion or VERDICT prose is legacy context, not that evidence.
Unavailable provider fields remain explicit nulls (including check-run update
time or run attempt when the API does not supply them).
Fixed bounds in factory/feedback.py: ITEM_LIMIT=100 per reviews, threads/
comments and checks/statuses; PAGE_LIMIT=2; BODY_LIMIT=20000 UTF-8 bytes per
body; ERROR_LIMIT=32; DETAIL_TIMEOUT=30 seconds, with initial/final head reads.
Reviews and review threads are read as bounded GraphQL connections carrying native
IDs, links, the reviewed commit and the provider's own updatedAt (an edited review
revises it; a submission time would not). Both use up to two pages; the combined
checks source reserves one page for native check runs and one for commit statuses. Nested thread comment
overflow is explicit rather than an unbounded fan-out. Provenance reuses the
existing safe, bounded 2 MB committed-event tail reader. Every source (pr,
reviews, threads, checks) reports status (complete, partial,
unavailable), nullable observed_at/reason, and truncated. A cap, malformed
response, missing SHA, failed read, or head race never establishes disappearance
or resolution. A failed final read exposes an unknown head; raced reads retain
facts and both observed heads while making relevance unknown. Truncated text
without a reliable provider update signal explicitly lacks byte-exact change
detection beyond the retained body.
Canonical JSON is UTF-8, sorted keys, compact separators and explicit nulls.
Identity strings are stripped/NFC-normalized; host/slug and SHA hex are lowercase.
Evidence IDs namespace provider, host, repository ID, PR ID, kind and source ID.
source_revision is sha256: over exactly kind, source_id, review_id,
thread_id, check_run_id, run_attempt, source_head_sha, source_updated_at,
author, body, truncated, location, disposition, summary.
observation_id hashes repository/PR native IDs, final observed head, sorted
(evidence_id, source_revision) pairs, and coverage status/truncated/reason.
Collection timestamps, URLs, relevance and presentation order are excluded.
Unchanged polls keep identity; edits/resolution/dismissal/outcome changes revise
the same source. The producer revision is a clean source-checkout Git revision,
otherwise null, never a CLI version.
Briefing appends feedback behind existing evidence and human constraints and reports omissions in its reserved coverage citation. Source text is quoted untrusted evidence, rendered through safe text helpers. No consumer may infer delivery, fixed status, merge approval or readiness from this read-only schema. B2 (#79) does not authorize #15 delivery or change its held status; acceptance requires the actual merged producer revision and a separately authorized handoff.
factory dashboard --runtime-json prints one JSON object and exits. It is a
separate local read path, not a filtered full snapshot. --json and HTTP Ops
snapshots still perform GitHub and triage availability reads, but now reuse the
passive runtime projection and never persist lifecycle reconciliation.
The runtime command accepts no server options (--host, --port, --allowed-host, --no-open)
and cannot be combined with --json. Argument errors exit 2. Fatal repository
discovery/configuration errors exit nonzero with a sanitized diagnostic on stderr
and no runtime JSON. A usable projection, including partial or wholly unavailable
runtime sources, exits 0: inspect errors and observation quality, not just exit
status. Missing GitHub credentials are irrelevant; this command never invokes
gh, remote Git operations, model probes, or network APIs.
All listed keys are required unless explicitly described as kind-specific.
Nullable values mean unknown/not applicable, never zero, stopped, or a newly
observed transition. Times are UTC ISO 8601 strings. Source times remain unchanged
on repeated reads; generated_at and observed_at are collection times, not
event freshness. Consumers must ignore additive keys and reject unsupported
schema versions rather than interpreting them as version 1.
| Top-level key | Type / meaning |
|---|---|
schema_version |
Integer, exactly 1; implemented runtime contract, independent of package version. |
generated_at |
UTC string, generation time of this projection. |
repo |
Configured owner/repository string from the main checkout. |
dispatcher |
Local service/timer/admission evidence object below. |
executions |
Independent execution objects below; overlapping stages are retained. |
resources |
Current resource evidence objects below. |
events |
Bounded deduplicated supported lifecycle records; never synthetic poll events. |
history |
Explicit retained-window coverage object below. |
errors |
At most 32 structured partial-error objects, {source, scope, code} strings. No exception text, credentials, configuration dumps, or log excerpts. |
dispatcher has nullable booleans service_active, timer_active, and paused;
nullable UTC next_at; UTC observed_at; string observation; capacity;
run_ids (sorted dispatcher-run identity strings); and latest_transition
(null or {event_id, at, execution_id, kind} from a returned enter/exit).
Latest means the last retained observed transition in journal order, not an
artifact modification. capacity has configured (integer), active (integer
or null, actual held ticket admission locks), and complete (boolean).
Stage count is not admission count. An unavailable service query is null,
not false; inactive service evidence alone does not establish unexpected stop.
paused is null because the current producer has no recorded pause intention.
No scheduled intention is inferred from a configured interval.
Each execution has the eight common F01 identity fields (dispatcher_run_id,
root_execution_id, execution_id, parent_execution_id, ticket, attempt,
review_round, stage) with their types above, plus state (active,
completed, failed, interrupted, unknown), nullable entered_at,
ended_at, outcome, reason, and wait; latest_event_id, latest_at;
observation and observed_at. wait uses the F02 object plus source event_id
and at. The events live only in the top-level array, not duplicated per scope.
An entry outside the bounded window has null entered_at and explicit partial
coverage. A missing stage is never reconstructed from logs or artifacts.
Resource/scheduling observation scopes do not become executions.
Recorded exits retain their actual source times and ordinary outcome semantics.
A locally proven interruption without a stored exit changes only the current
execution state: no event is appended, no completion UUID is manufactured, and
ended_at stays null. Direct process identity and registered children can prove
liveness. The runtime path does not scan every process environment; missing
descendant evidence remains partial/unknown, not a fabricated completion.
A known boot change can still prove interruption. Unsupported older records
never establish current execution activity.
Resources retain the F02 descriptor, state, ownership, owner, requests,
and kernel evidence types documented above, plus observation and UTC
observed_at. event_id and at are nullable: they identify a retained,
matching persisted observation, not the latest request or this poll. A current
kernel observation without such a record has no invented transition identity
or onset. Confirmation requires matching acquisition identity, inode, kernel
holder PID, and live process identity. A request, inherited lock, replaced inode,
or external holder never becomes a confirmed owner. Released/terminal holders
are removed; source request/acquisition/release events remain in events.
Repository discovery runs local git --no-optional-locks rev-parse; only when a
slug is absent does it run local git remote get-url origin. These do not fetch
or contact remotes. The normal main-checkout lookup and host/repository
merge/host_filter precedence are retained. Only runtime configuration fields
are interpreted: slug, nonnegative integer dispatch.max_active, and gate lock.
Each repository/host TOML read is capped at 256 KiB. Invalid runtime configuration
produces factory: runtime configuration unavailable or invalid, without echoing
the input. Unrelated worker/model/check settings are not evaluated.
Three allowlisted systemctl --user queries read service state, timer state,
and JSON timers. Each local command has a 0.5-second deadline, stdout strictly
below 64 KiB, discarded stderr, and at most another 0.5 seconds for reap after
kill. At most five commands run (four with an explicit slug). The D-Bus address
is forced to a local Unix socket, never an inherited TCP address. Missing tools,
unavailable units, invalid output, overflow and timeouts yield partial errors.
Only explicit ActiveState=active is true; transitional states remain unknown.
next_at requires an active timer and an explicitly returned future timestamp.
Admission scans at most 1024 directory entries and a 256 KiB kernel lock window.
The count is Linux /proc/locks only. Unreadable, incomplete, or Darwin evidence
with a numeric ticket lock returns null capacity, not a false zero. An empty
numeric listing stays zero because the directory itself was read.
System query errors use source systemctl, scope service, timer, or
schedule, and codes invalid_unit, timeout, output_limit, command_failed,
command_unavailable, unit_unavailable, transitioning, unit_failed,
invalid_state, or invalid_schedule. Admission errors use source admission,
scope repository, with missing, unreadable, unsupported_file, byte_limit,
entry_limit, changed, invalid_kernel_locks, or locks_unavailable.
locks_unavailable is the Darwin numeric-ticket-lock result: no passive flock
table, so the count is null rather than zero or a foreign kernel table. Errors
contain fixed codes only; raw stderr and arbitrary stored diagnostic text are
never returned.
The journal reader performs one pread of at most 1,048,576 bytes at the
end of the regular file, with no journal lock. It drops the first clipped line,
accepts only newline-terminated UTF-8 JSON objects of at most 16,384 bytes
(including newline), rejects nonfinite numbers/depth over 32, and returns at most
512 newest supported unique event identities. Both bounds clip the beginning,
never promote an uncommitted last line. No logs or full lifetime journal scan.
Concurrent size/mtime changes mark the read partial; it is not an atomic snapshot
across files, processes, or service queries. Ordinary local filesystem reads are
assumed responsive; byte limits do not promise recovery from a kernel-stalled
filesystem.
history has these required fields:
| Key | Type / semantics |
|---|---|
source |
String, events.jsonl. |
status |
empty for an existing zero-byte journal; available for a readable nonempty journal (even with no usable records); missing; or unreadable. |
start_at, end_at |
Nullable UTC strings: minimum/maximum returned supported source timestamps, not file age or an inferred lifetime interval. Both null when none survive. |
complete |
Boolean: the present file was fully covered without detected gaps; never a promise of exhaustive lifetime history or producer instrumentation. An empty existing file is complete with a null interval. Missing/unreadable storage is incomplete. |
truncated |
Boolean: a byte/event bound clipped the beginning. Corruption is a gap, not necessarily truncation. |
gaps |
Deduplicated fixed code strings in deterministic discovery order. |
bytes_read, byte_limit, event_limit, retained_events |
Nonnegative integers; actual journal bytes read, 1048576, 512, and returned unique event count. |
Truncation makes the execution census partial: entire still-open scopes can be outside this window. Do not interpret an empty returned execution array as proof of no work when history is partial. Retained mid-execution scopes have unknown state and null entry time unless the entry is actually retained. A corrupt or unsupported suffix may hide an exit: affected open executions become unknown, while unaffected recorded terminal facts survive. No intermediate transition, entry time, completion, or lifetime interval is inferred.
Events are returned in retained physical journal order. Within an execution,
reduce by sequence; wall clocks and append order do not impose causality across
independent scopes. Exact duplicate identities are returned once, using the first
copy in the selected window. Conflicting copies of an identity, or different
identities reusing one execution sequence, keep the first copy and mark
duplicate_conflict; consumers must not replay the conflicting copy. Execution
identity inconsistencies and missing sequences are gaps. Executions/resources
use first-retained-appearance order (configured resource descriptors are appended
when absent); requests use execution reduction order. All are deterministic for
unchanged storage/evidence. latest_event_id/latest_at use the greatest retained
execution sequence; dispatcher.latest_transition uses physical order.
Event common keys/types are F01 above. Supported kinds are enter, exit,
handoff, child_start, child_exit, check, result, timeout,
lock_acquired, lock_released, resource_requested, wait, wait_end,
resource_observation, and scheduling_observation. Kind-specific optional
fields are handoff_id, wait_event_id, acquisition_id (identity strings,
nullable where F01/F02 permits); blocking, parsed, timed_out, reconciled,
passed (booleans); returncode, timeout_seconds (integers); check (bounded
string); verdict (APPROVE/REVISE); and the documented child_process,
resource, lock, and wait. Resource observations retain their sanitized F02
state/owner/request/evidence fields. Scheduling observations retain nullable
timer_active, service_active, and wait.
Supported outcomes are completed, mechanism_failure, interrupted,
unknown, product_feedback, project_escalation, approved, merged,
refreshed, not_admitted, and not_eligible; unknown outcome strings become
null. Only known producer reason codes (including numeric worker/review/merge/push
exit reasons) survive. Arbitrary diagnostic reasons become null, including
wait.reason when unsupported. Wait details retain only nonnegative integer
active, max_active, pr, and valid UTC next_at when present. Raw commands,
exception messages, arbitrary details, and unknown extra fields are omitted.
Identity/stage strings are at most 256 characters; paths at most 4096; each event
has at most 64 recorded locks. Invalid authority is a gap, not confirmed activity.
Execution evidence is required and nullable. When present it has process
(alive/dead/unknown), children (process/state objects), locks (F01
descriptors plus held/free/unknown state), descendants (empty array: no whole
process scan), scan_complete and descendant_absence_proven (booleans), and
pending_handoffs (identity-string array). These flags do not prove absent
descendants across missing history. Observation quality is fresh, partial,
or unavailable; fresh describes current evidence collection, not a recent
source event. No age-based stale threshold is invented by Factory.
History-window completeness and current observation quality are independent:
older byte/event truncation does not degrade a fully retained later execution,
current dispatcher probes or confirmed lock ownership. A clipped execution's
missing entry, conflicting identity/sequence, ambiguous suffix or unavailable
live evidence still makes that record partial/unknown; history gaps remain
reported even when independent current observations are fresh.
Direct identity checks are cached for at most 128 PIDs, with at most 512 cached
lock stats and 128 current holder PIDs returned per resource. On Linux, probes
use 4096-byte /proc stat reads, a 64 KiB mounts read, 128-byte boot/machine
identity reads, and one /proc/locks read under 1 MiB. On Darwin, sysctl
supplies the boot-session UUID, ioreg supplies the hashed machine UUID, and
ps supplies PID/start-time identity. An absent PID is dead only after a
successful current-process visibility probe on the same boot. Resource
attribution uses lsof lock fields per resource; missing lock fields remain
unknown, never proof that a lock is free. Each Darwin command has a two-second
timeout; its captured output has no byte cap. Hitting identity/lock/holder
bounds or unavailable probes yields unknown/partial evidence. The separate
admission query has its own smaller kernel bound above. No flock is acquired,
no ownership file is rewritten, no lock/state directory is created, and no
reconciliation is persisted.
Without host identity, configured descriptors are omitted with an error rather
than assigning unrelated hosts a fabricated shared identity.
History errors use source events.jsonl, scope history or executions:
missing, unreadable, not_regular, changed_during_read, byte_limit,
event_limit, row_limit, unterminated_tail, invalid_json, invalid_record,
unsupported_record, unsupported_version, unsupported_kind,
invalid_lifecycle, duplicate_conflict, identity_conflict, sequence_gap,
missing_enter, sequence_conflict. identity_conflict compares only the fields
fixed when a scope opens (run, root, execution and parent IDs, ticket, stage); a
ticket scope advances attempt/review_round in place for its children, and the
projected execution reports the latest values. Legacy/unversioned records are explicitly
unsupported for lifecycle coverage, not an empty valid lifecycle history.
Known legacy rows cannot hide a lifecycle exit, so they do not independently
invalidate supported open scopes.
Linux source/scope pairs are proc/identity (boot_unavailable,
namespace_unavailable, process_limit, process_unavailable,
absence_unavailable) and
proc/locks/resources (locks_unavailable, holder_limit).
Darwin uses process/identity (boot_unavailable, process_limit,
process_unavailable) and lsof/resources (locks_unavailable, holder_limit)
instead of the Linux identity and lock sources. Shared pairs are
proc/executions (descendants_not_scanned),
filesystem/resources (lock_limit, not_regular, lock_unavailable,
canonical_path_unavailable) and configuration/resources
(lock_limit, invalid_scope, host_identity_unavailable). A lock file that
does not exist (not yet created, or unlinked by ticket cleanup) is not an error:
its resource reports state unknown with no lock_unavailable.
Errors are deduplicated by source/scope/code; the first 32 are retained in
deterministic discovery order, lifecycle/resource errors before service errors.
Per-source quality/history flags remain authoritative even if the error cap is
reached. Resources report unavailable authority through their own quality flags;
independent service failures do not erase them.
failures repeats the failure-severity entries of errors: events.jsonl codes only
a defect in the factory's journal writer produces (unreadable, not_regular,
invalid_json, duplicate_conflict, identity_conflict, sequence_conflict),
each with an evidence pointer (offset, the file byte offset of the offending line;
execution_id; or error, the OS error). Every other code, including any added
later until it is deliberately listed in runtime_events.FAILURES, is coverage: a
reader bound, a clipped or rotated window, or a host condition. Codes a reader bound
can also produce (row_limit, missing_enter, sequence_gap, invalid_record,
invalid_lifecycle, unsupported_*) are coverage. factory watch files only
failures.
Actual guarded CLI output from a disposable repository on the development host, with a valid empty journal and no installed matching timer/service. Only whitespace is condensed below. Resource paths/IDs are evidence from that disposable run, not deployment configuration. Empty history is distinct from unavailable services and resource authority.
{
"schema_version": 1,
"generated_at": "2026-09-05T23:15:55.985407Z",
"repo": "example/runtime",
"dispatcher": {
"service_active": null, "timer_active": null, "next_at": null, "paused": null,
"observed_at": "2026-09-05T23:15:55.985384Z", "observation": "partial",
"capacity": {"configured": 2, "active": 0, "complete": true},
"run_ids": [], "latest_transition": null
},
"executions": [],
"resources": [
{
"resource": {
"id": "a3a6cc28-abfe-5d28-b451-def8735bd090", "scope": "host",
"host_id": "96359d9e-9be6-5980-985b-650f726a8115", "repository": null,
"lock": {"path": "/tmp/tmp531zga_5/gpu.lock", "device": null, "inode": null}
},
"state": "unknown", "ownership": "unknown", "owner": null, "requests": [],
"evidence": {"lock_state": "unknown", "attribution": "unavailable", "holder_pids": null},
"event_id": null, "at": null,
"observed_at": "2026-09-05T23:15:55.975966Z", "observation": "unavailable"
},
{
"resource": {
"id": "8d670505-a426-515c-bd0f-5869cb68f3e4", "scope": "repository",
"host_id": "96359d9e-9be6-5980-985b-650f726a8115",
"repository": "/tmp/tmp531zga_5/.factory",
"lock": {"path": "/tmp/tmp531zga_5/.factory/locks/merge.lock", "device": null, "inode": null}
},
"state": "unknown", "ownership": "unknown", "owner": null, "requests": [],
"evidence": {"lock_state": "unknown", "attribution": "unavailable", "holder_pids": null},
"event_id": null, "at": null,
"observed_at": "2026-09-05T23:15:55.975966Z", "observation": "unavailable"
}
],
"events": [],
"history": {
"source": "events.jsonl", "status": "empty", "start_at": null, "end_at": null,
"complete": true, "truncated": false, "gaps": [], "bytes_read": 0,
"byte_limit": 1048576, "event_limit": 512, "retained_events": 0
},
"errors": [
{"source": "systemctl", "scope": "service", "code": "unit_unavailable"},
{"source": "systemctl", "scope": "timer", "code": "unit_unavailable"}
]
}Support is introduced by signed-off Factory F03 issue #28 implementation revision
2e9678551ad5600498bc02ae26ad5e5aacc7a05e. The package remains 0.2.0; support is
not implied by that package version, F03 acceptance, or merge alone.
On older installations an unrecognized --runtime-json option exits nonzero;
District treats that, invalid JSON, a missing schema, or an unsupported schema
as unsupported/unknown. Factory supplies no full-snapshot fallback.
Deployment and installed-host schema verification require the separately authorized operator checkpoint. District D02 remains held until that verification and its District prerequisites pass. The approximately-five-second ten-factory shared-collector measurement belongs to D02; this endpoint makes no fleet cadence or installed-host compatibility claim.
factory evidence --root <explicit-main-checkout> accepts exactly one UTF-8 JSON
object on stdin and emits exactly one JSON result on stdout. Close stdin after the
request. The source equivalent is python -B -m factory.cli evidence --root ...;
factory evidence --help prints usage rather than a JSON observation.
printf '%s\n' '{"schema_version":1,"repository":"example/widgets","op":"capabilities"}' \
| factory evidence --root /srv/widgets
printf '%s\n' '{"schema_version":1,"repository":"example/widgets","op":"investigate","kind":"checks","number":17}' \
| python -B -m factory.cli evidence --root /srv/widgetsThe root is an operator-selected main checkout, not a request field. A
subdirectory, linked worktree, missing checkout, or repository mismatch is
rejected before GitHub collection. Repository identity comes from the main
checkout's .factory.toml (repo.slug) or its GitHub origin remote, using the
bounded F03 loader. Cwd does not select scope. The normal Python package
requires TOMLKit; these reads require no Pi installation or model provider.
Every request requires exactly schema_version:1, repository:"owner/name",
op, and the additional fields below. IDs are integers in 1..9223372036854775807,
never booleans or strings. Repository slugs are at most 200 characters.
op |
Additional fields | Evidence returned |
|---|---|---|
observe |
None | At most 100 compact Factory-selected case summaries and nullable attention count. No automatic first-case inspection or dispatcher log bundle. |
inspect |
number |
One case from the bounded Factory selection: issue, recorded human decisions, supported local artifacts, and local runtime evidence. Not arbitrary issue lookup. |
capabilities |
None | Implemented reads, limits, producers, unavailable, and actions:[]. No case or GitHub collection. |
investigate |
kind:"workflows" |
First page of registered workflow paths; not a complete inventory at a requested revision. |
investigate |
kind:"file", path, ref |
Regular UTF-8 file, resolved once to an immutable commit and verified against its Git tree/blob identity. |
investigate |
kind:"result", number, head, offset |
Local retained accepted handoff for an exact 40/64-hex head. Required byte offset is 0–262144; follow next_offset for further pages. No GitHub collection. |
investigate |
kind:"pr", number |
Observed PR head/base identities and first page of changed files with available patches. Omitted or shortened patches remain unknown. |
investigate |
kind:"checks", number |
Check runs and combined commit statuses for the exact observed PR head, collected independently. |
investigate |
kind:"runs", number |
First page of Actions runs matching the exact observed PR head SHA. |
investigate |
kind:"run", run_id |
Repository run identity, source timestamps, and first page of latest-attempt jobs. |
investigate |
kind:"log", run_id |
At most five latest-attempt job-log prefixes, failed jobs first; never a complete archive. |
investigate |
kind:"roadmap" |
Shared bounded initiative roadmap and owner-attention questions; coverage and unknown states remain explicit. |
investigate |
kind:"initiative", number |
One initiative's declared plan, available revision, linked implementation evidence, blockers, questions and accepted drift evidence. |
investigate |
kind:"drift", number |
One ticket's validated retained baseline compared with the complete live initiative; preserves historical accepted evidence on live-source failure. |
investigate |
kind:"experiments" |
Retained run directories under .factory/experiments/<experiment>/<run>/; a listing is not availability. |
investigate |
kind:"experiment", experiment, run |
One retained schema-1 observation/build run: protocol revision, producer state, report fields, recorded disposition, evidence links and per-artifact availability. |
Each roadmap/initiative plan also carries experiments and next. An experiment
appears on the plan its latest run's protocol.json names as roadmap; it is an
informed_by link (blocking: false), never a blocker, and keeps the recorded
disposition beside its outcome grouping (adopt/amend accepted,
reject/no-change rejected, defer deferred, pending, else unknown). next
ranks open linked tickets by the first NOW/NEXT/THEN/LATER Plan line naming
them; a pending experiment disposition ranks with NOW. action is the best runnable
implementation, else the best decision; awaiting_decision holds only current-priority
decisions, separate from runnable, blocked (real Blocked by edges), in_flight,
held and displaced; uncertain lists incomplete evidence and run limitations.
Nothing is applied.
Experiment reads resolve only single-name directories beneath .factory/experiments
and never follow links. Run status is complete, partial (run not terminal,
artifact missing/inaccessible or source coverage incomplete), stale (an artifact no
longer matches its producer-recorded digest), inaccessible (unsafe, unreadable,
malformed or foreign record) or missing; each artifact and report evidence link
keeps its own state. source_ledger.freshness is stale once the ledger has grown
past the frozen snapshot. A completed run is producer state only: it is not
hypothesis confirmation, production acceptance or delivery, and disposition is only
what the decision owner recorded.
Retained-result reads return archive status and manifest under investigation,
with separate manifest_source_id and handoff_source_id citations. Pages contain
at most 20,000 UTF-8 bytes: a complete archive can have a truncated excerpt and a
non-null next_offset. Offsets refer to raw archived bytes; offsets inside a UTF-8
code point are refused, not silently advanced. Existing terminal-control
sanitization can change displayed text; display_sanitized marks this and
raw_artifact_sha256 identifies the original stored bytes, not a transformed
excerpt. Non-UTF-8 originals stay retained but are unavailable as text.
Missing/expired/partial content keeps a nonzero exit and explicit coverage rather
than becoming an empty successful result. No response or briefing budget is raised.
path is a repository-relative path of 1–1024 characters, with no empty, ., or
.. components, control characters, backslashes, or URL syntax (:, %, ?,
#). ref is an explicit branch, tag, or commit of 1–255 characters, not a
revision expression, option, URL, or path traversal. Whitespace, control
characters, .., @{, and operators such as ~ and ^ are rejected.
Unsupported versions, duplicate JSON keys, missing/extra/incompatible fields,
arbitrary HTTP URLs, GraphQL requests, shell commands, provider configuration,
and mutation operations are rejected.
File reads resolve immutable trees before requesting contents. Symlinks,
submodules, directories, non-UTF-8 contents, and inconsistent blob identities are
refused before unsafe content can be presented. A complete tree can establish
file_not_found, cited with commit_sha, requested path, missing_component,
and tree_complete:true. A truncated or unavailable tree cannot establish
absence. Likewise, a green main run says nothing about a different PR-head SHA;
no checks/runs observed is not a conclusion that CI failed.
These envelope fields are always present, including invalid requests:
| Field | Meaning |
|---|---|
schema_version |
Integer 1. |
ok |
Boolean; true only for a successful bounded read. |
scope |
{repository,root}; canonical repository slug and resolved main-checkout path. Each is nullable until established. |
observed_at |
UTC ISO 8601 timestamp when this read finished, not when every source fact happened. |
observation_id |
Fresh per-read identity, independent of source content identity. |
coverage |
{status,notices}. Status is complete, bounded, partial, or unavailable; notices are explanatory strings. |
sources |
Array of inspectable citations, possibly empty. Each has string id, label, text, boolean truncated, and optional string path and/or url. |
errors |
At most 64 structured {source,scope,code} objects. Empty on success. No raw command diagnostics or configuration dumps. |
Operation-specific fields appear only where applicable:
- A parsed
observerequest hascases:[]andattention_count(integer or null). A summary containsnumber,title, provider issuestate, derived pipelinestage,labels,assignees,url,updated_at, and nullablepr. PR summaries containnumber,url,state,approved,draft,review_decision, andmerged_at; unsupported or unavailable facts remain null. - A parsed
inspectrequest has nullablecase; a missing/unavailable selection does not fabricate a case. Its supported escalation packet is the producer's.factory/escalations/<number>.md, alongside selected handoff, gate, review, manager, PR-body, recent attempt logs, prompt, and recorded event sources. investigationechoes the selected kind and target fields. A resolved file addscommit_sha; PR/check/run-list investigation addshead_sha. Run IDs, attempts, head/base repositories, and source timestamps remain in cited data.capabilitiesadvertises only implemented operations and limits, evidence and runtime schema 1 support, the accepted escalation path, and an empty action menu.- Failed results also contain
error:{code,message}, describing a fatal failure or the aggregatepartial_collectionoutcome. Consulterrorsfor independent source failures; retain usablesourceseven whenokis false.
Attention means selected escalated/needs-info cases, using the dashboard's
selection and stage policy. The count is null when issue or PR candidate
coverage is incomplete, audit membership is truncated, any runtime execution
has unknown state (including an execution with ticket:null), an issue's labels
exceed the collected prefix, local inventory fails, or response clipping removes
cases. Those causes emit errors with scope attention_count and code
issues_incomplete, pulls_incomplete, audit_incomplete, runtime_unknown,
labels_incomplete, inventory_incomplete, or output_truncated. Each error's
source is the ID of a bounded diagnostic citation. Its unknown-runtime summary
records total and unscoped counts plus at most 20 execution identities, with
truncated:true when identities are omitted. Human-readable notices begin
Attention count unavailable:. Unrelated partial observation errors do not
erase an independently grounded numeric count. Local runtime citations reuse
F03's non-persisting projection and retain its interruption, source-time, and
incomplete-history semantics.
Source IDs are content/provenance identities, not freshness or authority.
Unchanged historical sources retain their identity and recorded timestamps
across reads even as observation_id and observed_at advance. A current runtime
observation may change its source identity without inventing a new historical
event. Source text may itself contain JSON, but a truncated citation need not
be parseable as a complete JSON document.
Bounds apply during reads, not just to displayed strings:
| Boundary | Ceiling |
|---|---|
| Stdin request | 4096 bytes |
| JSON response | 500,000 ASCII-encoded bytes, plus one trailing newline |
| Whole read, including waiting for stdin | 90 seconds |
| One GitHub command | 20 seconds, or the remaining whole-read deadline |
| GitHub JSON / diagnostic capture | 1 MiB stdout / 4096 bytes stderr; oversized JSON is not interpreted |
| Lists | First 100 entries, except issue/PR comments: latest page of at most 100/30; no page traversal |
| Cited source | 20,000 UTF-8 bytes |
| Run logs | Five latest-attempt prefixes; failed jobs first |
| Local inventory | At most 1024 directory entries per bounded scan |
| Runtime history | F03's 1 MiB / 512 retained-event window |
| Audit-only case membership | Latest 1 MiB of the existing audit trail; partial/unreadable membership is explicit |
| Selected case history/context | Latest 2 MB event text; existing 64,000-byte / 40-source briefing selection limits |
Comment-page selection uses the observed comment count. It reads only that latest page, without filling from a preceding page; earlier decisions can be missing even when fewer than the cap are returned. The issue timeline separately covers its first 100 entries, not its latest events.
Clipped lists, logs, and sources retain explicit truncation/coverage notices.
Failed independent sources do not discard successful sibling reads. GitHub
commands are fixed-repository, fixed-host GETs through gh, except one fixed
read-only GraphQL query (POST) for recently updated PR candidates. That query
selects the required PR fields without duplicated repository metadata; it keeps
the first-100 bound (12 for viability samples), includes open/closed/merged PRs,
and reports PR/label pagination explicitly. GraphQL errors, including errors
alongside data, remain incomplete evidence rather than proof of absence. No
caller-supplied query, mutation or page traversal is supported. Missing tools,
permissions, authentication, service failures, oversized required fields, and
timeouts remain visible under the same byte/time caps. Log control sequences
are removed before citation display.
Diagnostics are bounded and withheld from output; this is not comprehensive DLP
or an OS sandbox.
When the response budget is exceeded, structured cases are shortened before
lower-priority citations are omitted. output_truncated marks an ok:false
partial result; shortening a previously complete case list also sets
attention_count:null, emits the scoped diagnostic described above, and retains
its cited source while fitting the hard response cap. Other retained citations
keep their original text and source IDs. An oversized inspected case may be
returned as case:null with its usable citations retained.
Audit-only cases use the same selection policy as the dashboard. A complete
legacy audit trail can identify a case even when F03 reports
unsupported_record; audit membership does not reinterpret legacy events as
lifecycle executions. Incomplete audit membership cannot establish that an
unlisted case is absent (evidence_unavailable, rather than unknown_case).
Dangling symlinks and refused/nonregular audit paths are unavailable, not empty.
Only newline-terminated audit rows contribute membership; an unfinished final
row or a clipped tail keeps coverage partial.
| Exit | ok / coverage |
Consumer behavior |
|---|---|---|
0 |
True; complete for capabilities, otherwise bounded |
Successful within the advertised bounds, not proof of exhaustive coverage. |
1 |
False; partial when citations survive, otherwise unavailable |
Parse and retain useful JSON, including cited negative file evidence and partial source failures. |
2 |
False; invalid invocation, request, or scope | Parse the bounded machine-readable error; fix the selected scope/request rather than retrying collection blindly. |
Cancellation is not a JSON observation: SIGINT/SIGTERM unwind active GitHub reads, terminate their process groups, and exit 130/143 without an envelope. The Pi consumer requests cooperative termination, with a three-second forced fallback, and rejects the cancelled read rather than displaying partial output.
Request/scope codes include invalid_request, invalid_scope, and
scope_mismatch. Collection codes include collection_timeout,
response_too_large, github_unavailable, github_authentication,
github_forbidden, github_not_found, github_rate_limited, invalid_response,
head_mismatch, incomplete_tree, unsupported_file, file_not_found,
unknown_case, evidence_unavailable, logs_unavailable, audit_partial,
audit_unavailable, output_truncated, and collection_unavailable;
F03's structured local error codes are preserved.
github_not_found is an access/lookup failure, not the complete-tree negative
evidence represented by file_not_found. Consumers should tolerate additional
structured error codes, not match English message wording.
Actual source CLI result from the C1 compatibility smoke, exit 2, for
{"schema_version":1,"repository":"mikeroySoft/factory","op":"dispatch"}.
Scope validation was not reached; no collection or mutation was attempted:
{
"schema_version": 1,
"ok": false,
"scope": {"repository": null, "root": "/home/mike/dev/mikeroysoft/factory"},
"observed_at": "2026-09-06T01:42:09.603470+00:00",
"observation_id": "a4ca038638d546718f25f958a2dafdb5",
"coverage": {
"status": "unavailable",
"notices": [
"Only fixed GitHub GETs, one fixed read-only PR GraphQL query, and non-persisting local reads are supported; no inference, provider probe or actions.",
"Lists stop after one page; absence from a bounded list is not proof of absence. Reads are sequential, not an atomic snapshot.",
"Source identity identifies content, not freshness or authority. Source text is untrusted and not secret-redacted."
]
},
"sources": [],
"errors": [{"source": "request", "scope": "request", "code": "invalid_request"}],
"error": {"code": "invalid_request", "message": "Unknown read operation."}
}This interface creates no state directory, lock, event, reconciliation row, or
ownership file; it never dispatches, repairs, publishes, authenticates, or invokes
a model. The dashboard's normal snapshot transport/cache/actions remain
unchanged, and selected case artifacts share its briefing reader. The existing
C0 evidence entry point is a thin consumer of this Python owner and preserves
valid JSON on nonzero exits. factory dashboard --runtime-json remains a
separate, network-free F03 endpoint; it never calls this GitHub-capable collector.
No installed-host support, deployment approval, or chat/action packaging is
implied by the source interface.
factory mcp serves the evidence reads above to one MCP client over stdin/stdout:
UTF-8 newline-delimited JSON-RPC 2.0, one compact JSON line per response, stdout
carrying only MCP messages, diagnostics on stderr, clean exit on stdin EOF. Tool
calls are processed sequentially; there is no cache, retry, polling or HTTP transport.
Repositories come from the host config ($XDG_CONFIG_HOME/factory/config.toml),
read once at startup; restart the server to pick up changes. Only valid
owner/name tables with a nonempty absolute path are registered; a table
without path is ignored, while a malformed file or a relative/non-string path
fails startup with a one-line stderr diagnostic. A missing file is an empty registry.
[repo."example/widgets"]
path = "/srv/widgets"
[repo."example/tooling"]
path = "/home/me/src/tooling"Point a stdio-capable client at the installed command:
{"mcpServers": {"factory": {"command": "factory", "args": ["mcp"]}}}initialize returns protocolVersion: "2025-06-18" (also when the client asked
for another version), capabilities: {tools: {}} and serverInfo.name: "factory".
tools/list advertises exactly seven tools, each with an object-root inputSchema:
| Tool | Arguments | Runs |
|---|---|---|
factory_repositories |
none | nothing; returns {"repositories": [{"repository", "path"}, ...]} sorted by slug |
factory_observe |
repository |
evidence op observe |
factory_inspect |
repository, number |
evidence op inspect |
factory_investigate |
repository, kind, plus exactly that kind's fields |
evidence op investigate |
factory_capabilities |
repository |
evidence op capabilities |
factory_prepare_action |
repository, action, args |
factory.actions.prepare in-process; stores a confirmable proposal, mutates nothing |
factory_apply_action |
repository, proposal_id, confirmation |
factory.decisions.apply in-process; applies one stored proposal exactly once |
Each evidence tool resolves repository to its registered path, launches
python -P -m factory evidence --root <path> with no shell, writes one request
(schema_version: 1, the tool's op, and every caller argument unchanged) and
closes stdin. The adapter checks only its own fields: arguments must be an
object (else JSON-RPC -32602); a missing, non-string or unregistered
repository, a caller-supplied op or schema_version, or nonempty
factory_repositories arguments return a text tool result with isError: true
without launching anything. Everything else — kinds, required/extra fields, IDs,
paths, refs, the 4096-byte request cap — is validated by factory evidence, whose
exit-2 JSON comes back verbatim as isError: true.
Tool results are always {content: [{type: "text", text}], isError?}. text is
the child's stdout as written: evidence exit 0 or 1 is a normal result (exit 1
already carries coverage/errors), exit 2 sets isError: true. Spawn failure,
signal termination, other exit codes, or empty/malformed/oversized stdout become a
short isError: true message — never raw stderr or a traceback — and the server
keeps serving. JSON-RPC errors: -32700 malformed JSON, -32600 invalid envelope
(both with id: null), -32601 unknown method, -32602 bad params or unknown
tool. Valid notifications, including notifications/initialized, get no response.
factory/actions.py defines each human decision once — input schema, preconditions,
and the decisions request it compiles to — and the dashboard's Ops Attention
buttons (POST /api/decisions/prepare with {repository, action, args}) and the
two MCP tools call that same function. Nothing else composes these label edits.
| Action | args |
Preconditions | Effect |
|---|---|---|---|
requeue_agent |
number, intent? (resume or fresh), comment? |
issue open and ready-for-human; not an upstream sync: issue (routing_refused) |
add ready-for-agent, remove ready-for-human, unassign the actor; opens a ticket generation |
resolve_and_close |
number, reason (completed or not planned), comment? |
issue open | close with that reason |
add_needs_triage |
number, comment? |
issue open, no pipeline label (needs-triage, ready-for-agent, ready-for-human, needs-info), not an upstream sync: issue |
add needs-triage |
Preconditions run against the exact target the proposal binds to, so apply's
stale-target check guarantees they still held when the effect ran. Refusals are
structured {ok: false, error: {code, message}} with the same code on both paths:
unknown_action, invalid_args, precondition_failed, routing_refused, or any
decisions code. Every proposal records caller (dashboard or mcp) and
action ({name, args}); the human-decision journal rows for prepared,
started and the final status, and the receipt, carry both.
factory chat opens a conversational, read-only Factory Manager on one
explicitly named repository. It reuses the bounded schema-1 evidence interface
above (fm_observe, fm_inspect, fm_investigate, fm_capabilities,
fm_source, fm_resource, fm_sample_preview) — no shell, no edit/write, no
publication or dispatch. It never mutates anything.
The console runs on a pinned upstream Pi runtime that is an optional console dependency; ordinary Factory execution never needs Node. Install it once inside the checkout, then launch:
# One-time: install the pinned Pi runtime (Node >=22.19) into the console.
# The console lives in this factory checkout; install it there once.
npm ci --ignore-scripts --no-audit --no-fund --prefix console/app
# Open the read-only console on an explicit repository/checkout.
# --root is the managed repository's main checkout; --console defaults to
# <root>/console/app but may point at any installed console directory, so one
# installed console can serve a --root that has no console/app of its own.
factory chat --root /path/to/checkout --repository owner/name \
--console /path/to/factory/console/app
# Resume this scope's latest conversation; startup always reobserves fresh evidence.
factory chat --root /path/to/checkout --repository owner/name --continueStartup requires a Linux interactive terminal and authenticated gh. The
launcher writes only console-owned settings into an isolated console/app/.runtime
directory (default project trust never; packages, extensions, skills, prompts
and themes empty; images blocked); it never copies provider auth or ambient host
settings. No inference happens until you approve the explicit provider/model
disclosure dialog. The default provider is the local keyless Ornith endpoint;
--provider openai|openai-codex --model <id> uses Pi's native, isolated
authentication for that provider only. Scope is fixed per launch — switching
repository means exiting and relaunching with a fresh disclosure.
Conversation history is not authoritative state: every start and --continue
resume reobserves Factory, and a failed or interrupted turn marks evidence stale
and reobserves on the next turn. The console/app/check.py read-boundary smoke
and console/app/check-transport.ts transport smoke exercise the bridge without
any model call.
For shared-plan questions, use /fm investigate roadmap,
/fm investigate initiative <number>, and /fm investigate drift <ticket>,
or ask conversationally: “What decision blocks initiative #50, and why does
the proposed sequence fit its known dependencies?” The FM can read the supplied
plans and revisions, compare explicitly evidenced areas/dependencies, and propose
sequencing or plan amendments with exact source citations. Unsupported progress,
ownership, semantic overlap and outcome delivery remain unknown. It cannot publish
decisions, edit plans, or turn session-only conversation into shared policy.
skills/factory/SKILL.md teaches a coding agent to install the factory
in a repo, write tickets it can actually work, and diagnose escalations:
npx skills add mikeroysoft/factoryThe dashboard's Codebase view (/codebase) maps the configured repository
across its locally available default-branch history. Install the optional
extractor when running from this source checkout:
uv sync --extra atlas
uv run --extra atlas factory codebase
uv run --extra atlas factory dashboardTOMLKit is the only required Python dependency. The
atlas extra pins Graphify 0.9.56; code extraction runs locally, without an LLM,
network access, checking out historical revisions, or executing repository code.
- Drag the revision slider, use its arrow keys, or select Previous / Next. Pick a baseline to distinguish additions, equal-size edits, moves, and deletions.
- Select a folder area or file for callable symbols, resolved relationship diagrams, confidence labels, and source links pinned to that commit. Inferred relationships are hidden by default.
- File slots stay fixed while scrubbing. Git-detected renames preserve identity; areas remain anchored to their original folder so moving a file does not rearrange the map. Folder labels follow a whole-area rename. Size bars use physical text lines against a common scale for the loaded history.
- While the dashboard runs, its background monitor checks local refs every 30 seconds; the page also refreshes every 30 seconds. New history does not reset an older selected revision or its baseline. A failed update keeps the last completed in-memory history visible with an error.
By default this reads origin/<repo.main>, falling back to the local
<repo.main> branch, and backfills the newest 80 first-parent commits.
It does not fetch: normal dispatcher/operator fetches advance the observed
remote-tracking ref. Uncommitted changes and side-branch commits outside that
first-parent history are not shown. The page names the observed ref and snapshot
generation time; that timestamp is not a claim about remote freshness.
uv run --extra atlas factory codebase --ref origin/main --limit 200
uv run --extra atlas factory dashboard --codebase-ref origin/main --codebase-limit 200Snapshots and the generated history live in the gitignored .factory/codebase/
cache, keyed by commit and extractor version. Extraction failure does not replace
the previously published history.json. The full Git lineage is read to retain
rename identities even when the displayed history window is bounded.
Coverage is explicit, not a completeness guarantee. Unsupported files remain inventory-only; unresolved/external relationships are omitted and counted. Valid manifests without a package identity (such as a Cargo workspace root) remain inventory-only with coverage warnings. Manifest parse errors still abort publication and preserve the last good history. Symlinks, submodules, unsafe paths and vendored/runtime directories are excluded. When a previously mapped file crosses a coverage boundary, comparison marks a coverage change, not a deletion; its baseline source remains inspectable. Snapshots are bounded to 5,000 files, 1 MiB per file and 32 MiB total; exclusions appear in coverage warnings. Preprocessed Fortran is inventory-only rather than invoking host preprocessing. Shallow history is marked incomplete. Git rename detection is heuristic: a heavily rewritten move can appear as deletion/addition. The small relationship diagram shows up to four neighbors; all resolved relationships for the selection remain in the evidence list.
Design and acceptance criteria: codebase history plan.
The native dashboard Atlas (/?view=atlas, factory/workspace-tools.js) draws
the Factory pipeline reference structure and prints commit-pinned source links.
The native Codebase inspector also diagrams actual extracted file relationships.
factory/cli.py
defines the command surface; factory/config.py layers host and repository
configuration.
The ticket flow map shows every path a ticket can take: triage decisions, build, review, approval, CI, merge, escalation and manager recovery, each edge citing the code that implements it.
Atlas also renders this canonical map as an interactive ticket-flow explorer.
Select a step in the connected diagram or searchable list to follow incoming,
outgoing, and retry paths, with transition conditions and source citations.
Overview and Reset return to the full step index; all transition evidence remains
printed below. This is a fixed Factory reference, not live activity or the selected
repository's extracted architecture. The authenticated /api/ticket-flow reads
bounded, cached local documentation; it never dispatches work or locks the pipeline.
The same Markdown source is included in installed wheels. Source links are pinned
only when the reference revision is verified; otherwise links are marked unavailable.
Operator and agent guide: docs/guide/index.md.
MIT