Expand description
Kranz engine — orchestration core (no UI deps).
Kranz is a local mission-control harness: an orchestrator plans, fresh
Claude Code sessions implement features one at a time, independent
validator sessions judge each milestone, and git is the source of truth.
An append-only event log makes every mission resumable (kill -9 safe).
Module map (build order per plan §5 Phase 1):
- contracts:
types,events,error,backend - foundation:
paths,event_log,reducer,scrub,git_ops,config,cost,prompts,backend_mock - orchestration:
backend_claude,permissions,runner,control,digest,orchestrator
Re-exports§
pub use backend_mock::MockBackend;
Modules§
- agent_
env - Cleared-environment construction for every prompt-injectable child the
engine spawns (ticket
agent-env-clear, P1 of the 2026-07-28 hostile-workload review). - auth_
verify - Auth-preflight seam (docs/scoping/claude-cli-min-env.md; mission m-165b6f).
- backend
- The agent backend seam (plan §4 “sdk-adapter”, §8 testing strategy).
- backend_
acp - ACP (Agent Client Protocol) agent backend: spawns and supervises an external agent process speaking JSON-RPC 2.0 over NDJSON stdio (KRZ-301 — the vendor-neutrality seam: any agent that speaks ACP can drive a kranz mission role without a per-vendor CLI parser).
- backend_
claude - Real agent backend: drives the
claudeCLI headless. - backend_
codex - Codex agent backend: drives
codex exec --jsonheadless. - backend_
cursor - Cursor agent backend: drives the Cursor CLI headless
(
agent --print --output-format stream-json). - backend_
droid - Droid agent backend: drives Factory
droid exec -o jsonheadless. - backend_
kimi - Kimi Code agent backend: drives the headless
kimi -p ... --output-format stream-jsonCLI. - backend_
local - Local OpenAI-compatible HTTP backend (
f-2-1): the firstAgentBackendthat drives an in-enginereqwestclient rather than a spawned CLI subprocess. Talks to{base_url}/v1/chat/completionsin non-streaming mode. - backend_
mock - Mock agent backend — scripted sessions so the whole engine tests without model calls (plan §8: “the seam”).
- backend_
readiness - Backend readiness / quota preflight before queue drain.
- command_
exec - Bounded, process-tree-killed shell execution for contract and merge-gate
commands — extracted from
orchestrator.rsin the monolith split (pure code motion, no behavior change). These are the ONLY places the engine runs user-authored shell: contract commands need real shell semantics (sh -c/cmd /C), so argument handling, timeout kill discipline (process group on unix, Job Object on Windows), output tailing, and environment sanitization live here as one unit. - comparison_
metrics - The industry-comparison set beside the kranz-native outcomes (ticket
outcomes-comparison-metrics, KRZ-333; design:docs/scoping/governance-evidence-layer.md, scored-gates addendum). - config
- Layered mission configuration (plan §6).
- container_
egress - Non-bypassable per-host egress for Docker worker sessions.
- contract_
controls - Opt-in evidence that an approved command distinguishes a valid implementation from a particular defect. Controls are advisory; an execution failure is not evidence of rejection. The same command runs twice with a read-only checkout and writable scratch, and must report a nonzero number of behavioral checks.
- contract_
gates - Named, deterministic contract-validation gates (ticket
.kranz/tickets/contract-validation-gates.md, KRZ-327 wedge). - contract_
health - Contract/consent health — the second readiness axis the AMM whitepaper cannot see (the validator-repair-era lesson: the bites came from the contract/consent machinery — author-broken assertions, scan friction, grant stalls — not from the foundation signals the paper measures).
- contract_
lint - Pure classification + synchronous base-tree runner for command-assertion
linting at
approve_plantime (M8 tier 1, feature f-1-1). - contract_
sweep - Engine-computed out-of-contract-write sweep (M7 tier 1, feature f-1-2).
- control
- Cross-process control inbox (design.md “Cross-process control”).
- corpus_
export - Provenance-tagged training-corpus export (ticket
.kranz/tickets/training-corpus-export.md, KRZ-332 — the governance evidence layer’s flywheel feed): one JSONL stream joining the three judged-artefact sources a local model can learn from — - cost
- Token pricing and pre-mission cost estimation (plan §5 Phase 1).
- decompose
kranz decomposecore (ticket: .kranz/tickets/ticket-dag-decomposition.md): one planner turn decomposes a complex goal into a small DAG of ordinary tickets linked byblocked-byedges — reusing the existing dependency machinery (deps.rs satisfaction, cycle detection, work-time skip-on-failed- blocker) instead of inventing new orchestration. The drain then executes the DAG in dependency order under the existing claim protocol.- deps
- The
blocked-bydependency primitive: shared checks the CLI and REST approve paths both call so a ticket can’t be approved (or drafted into a cycle) while a dependency is outstanding. - digest
- Orchestrator context digest (plan §4.8).
- disk_
preflight - Pre-drain disk-footprint check (ticket
mission-build-footprint). - domain_
lint - Clean-room domain-vocabulary lint (KRZ-314; the positioning ADR’s IP
boundary —
docs/knowledge/decisions/positioning-governance-evidence-layer.md). - draft
- Non-interactive draft core (roadmap f-1-1): the sequencing behind
kranz draft, hoisted out of the CLI so any surface (CLI, REST) can drive a ticket through its planning conversation. - egress_
proxy - Userspace filtering egress proxy for
fs+netsandboxed sessions (ticketegress-grant-sandbox-instrumentation, step 3.3a — enforcement + signal). - error
- Engine error type.
- escalation_
metrics - Flight-surgeon console (ticket
.kranz/tickets/flight-surgeon-dashboard.md): escalation health metrics computed per-request from the data kranz already writes — per-missionevents.jsonlplus the optionaltraced-from-missionticket frontmatter field. Pure-fold style, mirroringcrate::outcomes/crate::contract_health: no second persisted source of truth, only functions over event slices and the ticket list. - event_
log - Append-only JSONL event log (plan §4.3) — the single source of truth.
- events
- Event envelope and event set (plan §4.3) — the resumability backbone.
- evidence_
bundle - Evidence bundle export (ticket
.kranz/tickets/evidence-bundle-export.md, KRZ-326 — the governance evidence layer’s packaging step): assemble ONE mission’s portable audit package — inputs, gate results, diffs, reviewers, escalations, cost, and the provenance chain — self-contained and suitable for handing to an auditor who has no access to the repo. - findings
- Validation-findings conversion — extracted from
orchestrator.rsin the monolith split (pure code motion, no behavior change). The §4.5 g conversion turn (MissionEngine::convert_findings) puts every finding (validator report, engine sweep, final gate) to the orchestrator: convert it to a fix feature, waive it with a one-line justification, or — forcommand-assertionfindings only — escalate it to the operator as an author-broken assertion. The fix-cycle cap (MissionEngine::fix_cycle_exhausted) and its local-tier escalation valve (MissionEngine::escalate_or_block) bound how many fix rounds a milestone gets before it blocks. - gate
- The first-class gate interface (ticket
.kranz/tickets/gate-plugin-interface.md, KRZ-311; scored-gates addendum KRZ-315). - gate_
results - Persisting gate evaluations as first-class
gate.resultevents, and resolving the artefact references those events carry (ticket.kranz/tickets/gate-results-first-class-events, KRZ-312 — the governance evidence layer’s last substrate gap before provenance-replay). - gate_
score_ flags - Gate score distribution flags (ticket
.kranz/tickets/gate-score-distribution-flags.md, KRZ-316 — the scored-gates addendum’s second half): per gate, fold the score distribution across missions and flag two smells — scores that never approach the threshold over a meaningful sample, and near-constant scores — surfaced on the outcomes report beside the rubber-stamp signal and carried into the escalation ledger fold as a summary field. - gate_
scores - Gate score series (ticket
.kranz/tickets/gate-confidence-score.md, KRZ-315 — the persistence-and-query half of scored gates): the recorded evaluation series for ONE gate identity, folded from every mission log in the repo and surfaced askranz gate-scores <gate>(text or--json). Thegate-score-distribution-flagsslice (crate::gate_score_flags, KRZ-316) folds the distribution flags over the samegate.resultevents, sharing this module’s extraction discipline and verbatim-score contract. - git_ops
- Git operations for mission branches (plan §4.4 — git is the source of truth).
- hook_
gates - Claude Code lifecycle-hook gate projection (ticket
.kranz/tickets/claude-code-hook-gate-projection.md, KRZ-302). - hook_
status - Hook-derived status signals: an OPTIONAL, non-authoritative observability
lane for CLI backends that expose lifecycle hooks (ticket
.kranz/tickets/agent-hooks-status-signals.md; the consumer backend iscrate::backend_cursor). - hooks
- External trigger core (design D-F, ticket
trigger-ci-pr-fix-mission): parse an authenticated GitHub webhook into a ticket-draft decision, dedupe by trigger identity, and write the provenance-carrying ticket. - judgement
- Judgement turns — extracted from
orchestrator.rsin the monolith split (pure code motion, no behavior change). The post-run worker judgement (§4.5 f), the final contract gate’s verdicts turn, and the cross-mission lesson capture at mission completion — all running through the shared strict-parse JSON decision turn (MissionEngine::json_decision) that the orchestrator’s unblock / dirty-tree / parallel / fix-features turns also call. - knowledge
- Ranked, byte-capped
docs/knowledge/injection for planning seeds (slice 2). - lessons
- Safe storage and rendering of repo-level lessons.
- merge
- Gated merge orchestration (roadmap M6): a human-triggered Merge action that refuses on a dirty tracked tree, runs the repo’s tracked gate suite, and advances the base to an exact, gate-tested integration commit only on green — never pushing.
- merge_
gate - Repo-configured merge-gate runner.
- merged
- Shared merge-ancestry derivation, reused by mission rows (REST
/api/missions) and the ticket projection’s Delivered/Landed split. - migrate_
state - The one-time fold of
.statussidecars into committed frontmatterstate:keys (design: ticket-state-frontmatter, rule 4) —kranz ticket migrate-state. - mission_
catalog - Mission catalog + mission hygiene — extracted from
orchestrator.rsin the monolith split (pure code motion, no behavior change). The catalog helpers edit.kranz/missions/index.mdlines (prune, list ids, attach a report link); the hygiene family (roadmap M2) retires missions (abandon_mission) and classifies mission directories forkranz clean(cleanable_class) — lifecycle helpers kept deliberately OUTSIDE the run loop, touching neither orchestrator sessions nor worker turns. - orchestrator
- Mission engine — the orchestrator loop (plan §4.5).
- outcomes
- Flight-surgeon outcomes fold: autonomy ratio, grant-latency distribution,
an escalation ledger, cost and cycle time — plus the KRZ-321/323/329
extensions (per-task-class rows, the context-reuse split, the rubber-stamp
flag, and cost per merged change), the KRZ-316 gate score distribution
flags beside the rubber-stamp signal, and the KRZ-333 industry-comparison
set (
crate::comparison_metrics) attached as a clearly-separated secondary section when the fold options pin its window — all computed per-request from the existing event log. Pure-fold style, mirroringcrate::trace_export: there is no second persisted source of truth, only a function over&[Event](the merged-change denominator adds the live ancestry probe at fold time — derived, never stored). - pack
- The pack contract (ticket
.kranz/tickets/pack-contract-gates-prompts.md, KRZ-313 series): a pack — a directory with apack.toml— declares DETERMINISTIC gates, role prompts, checklists, and artefact-store adapters that kranz validates at load and wires into the mission surfaces. - paths
- Mission data layout under the target repo (plan §4):
- permissions
- Role → permission profile mapping (plan §4.7; the table in
docs/design.mdis authoritative). - plan_
fit - Plan-time feature context-fit check (plan-feature-context-fit-check ticket): warn at approval when a feature looks bigger than one worker session’s context budget. kranz already enforces fresh-context-per-feature at run time — this moves the sizing signal to plan time, where splitting is cheap. Advisory only: a decision event and a plan.md note, never a gate (v1 is a heuristic and must not hard-block plans).
- planning
- Planning turns — extracted from
orchestrator.rsin the monolith split (pure code motion, no behavior change). The plan-request turn family: demanding the initial plan JSON and the revised plan for a running mission, the large-scope prompt policies those turns embed (considered-alternatives and research), the pre-emit validation gates a proposed (revised) plan must pass, the plan JSON Schema, and the missions-catalog index upsert. - pr_
handoff - Optional GitHub PR handoff for COMPLETE-but-unmerged missions.
- preflight
- Environment preflight (roadmap M2) — extracted from
orchestrator.rsin the monolith split (pure code motion, no behavior change). Advisory only: preflight never blocks a mission (the final contract gate stays authoritative); it surfaces missing prerequisites as a singleorchestrator.decisionat run start, andPREFLIGHT_CLEAR_SUMMARYdurably supersedes an earlier warning once a run’s probes come back clean. - prompts
- Role prompts (plan §4.6) — embedded at compile time.
- provenance
- Provenance replay (ticket
.kranz/tickets/provenance-replay.md, KRZ-325 — the governance evidence layer’s audit story): reconstruct WHY a mission’s unit passed from its event log ALONE — which gates in which order, which artefacts, which model/backend, which prompt identity, which human decisions, and the terminal outcome — as one typed, orderedProvenanceChainthat the CLI renders as a text summary or--json. - pty_
harness - Pty-driven functional validation (ticket
.kranz/tickets/pty-functional-validation.md): terminal-interactive deliverables — REPLs, TUIs, interactive CLIs — are driven by the engine through a scripted pty session, and the functional validator judges the per-step verdicts as authoritative evidence, exactly like it judges engine-run contract-command output (validator repair 3/5). - queue
- Per-repo, priority-ordered execution queue (design: docs/backlog-and-slack.md §3).
- reducer
- Pure, deterministic fold of the event log into
MissionState. - report_
render - Markdown renderers for the mission artifacts —
plan.md,research.md,revised-plan.md, andreport.md— extracted fromorchestrator.rsin the monolith split (pure code motion, no behavior change). Everything here is pure and deterministic given its inputs (no wall-clock reads): the orchestrator computes estimates and timestamps and passes them in. - review_
artifact - Review-artifact missions (KRZ-349, design D-G/D-K).
- reviewer_
independence - Approval-pinned review policy, evaluated against resolved dispatch identity.
- routing
- The backend routing table (ticket
backend-routing-abstraction, KRZ-331): deterministic resolution of a ticket’s task class to an executor CAPABILITY CLASS (ExecutorTier) under the operator-configured table (RoutingConfig). - routing_
rules - Tracked routing rules (
.kranz/routing-rules.json) — the base-branch-owned FILE surface that populates the engine’s routing table (ticketrouting-rules-config, the config-surface slice of KRZ-331). - runner
- Spawn-one-session-and-stream-it plumbing (plan §4.6) shared by workers and validators, and reused for orchestrator turns in Phase C.
- sandbox
- OS sandbox profile/argv generation — Tier 2 filesystem/network containment. See docs/scoping/worker-sandboxing.md tier 2.
- sandbox_
container - Tier-3 container sandbox provider — run a worker/validator session inside a container with the declared write/egress policy. See docs/scoping/worker-sandboxing.md tier 3.
- sandbox_
windows - Windows native-containment capability probe and AppContainer/LPAC receipts.
- scrub
- Credential scrubbing and safe truncation (plan §3, roadmap M5).
- standards_
attestation - Authorized
manual-attestationchecker decisions (KRZ-346, D-F). - standards_
coverage - The Flight Rules rule coverage matrix (ticket
.kranz/tickets/flight-rules-finding-provenance.md, KRZ-343; designdocs/scoping/flight-rules-engineering-standards.md, decision D-H — “standards evidence is first-class”): one fold over the mission’s event log that joins every applicable pinned rule to the evidence that named it — gate verdicts carryingruleIds, findings carrying acrate::types::RuleCitation— and renders each rule’s disposition aspassed,failed,advisory,waived,not-evaluated, ornot-applicable, with mechanism and artefact references. - standards_
enforcement - Flight Rules checker binding and enforcement policy (KRZ-346, D-B/D-F).
- standards_
metrics - Cross-mission Flight Rules effectiveness metrics (KRZ-348, D-H/D-K).
- standards_
waiver - The Flight Rules human waiver decision (ticket
.kranz/tickets/flight-rules-waiver-decisions.md, KRZ-344; designdocs/scoping/flight-rules-engineering-standards.md, decision D-I — “waivers are narrow human decisions”): the ONE authorized exception path for a standards failure, and the fail-closed binding checks every consumer shares. - test_
capability - Runtime-gated test support: skip loudly, and fail where the capability is required, so a silent skip cannot masquerade as a pass. Runtime-gated tests: skip loudly, and fail where the capability is required.
- ticket
- Mission tickets —
.kranz/tickets/<slug>.md(design: docs/backlog-and-slack.md). - ticket_
notes - Ticket discussion notes —
.kranz/tickets/<slug>.notes.jsonl(D-BW-3, adopted from beads’ flat{author, text, created_at}comment model). - trace_
export - Derived, event-log-regenerable export of validation-PASSED worker traces
in instruction-pair form (plan §M2). Mirrors the pattern of
orchestrator::render_mission_report: a pure function over the foldedMissionStatewith no second persisted source of truth. Callingexport_validated_traces/to_jsonlagain over the same log always yields the same bytes — there is nothing to regenerate FROM except the event log itself. - types
- Core data model for Kranz missions (plan §4.2).
- validator_
integrity - Validator immutability: the TRIPWIRE half (ticket
validator-immutability-proof, security review P1 #5; snapshot follow-up incrate::validator_snapshot; mandatory containment incrate::sandbox::resolve_validator_containment, ticketvalidator-mandatory-containment). - validator_
snapshot - Copy-on-write immutable validator snapshot — the definitive fix for the
gap ticket
validator-immutability-proofleft open (and named in its “Remaining gap” section): “read-only” validator sessions ran in the mission’s REAL session checkout, so the tamper fingerprint (crate::validator_integrity) could only catch writes at session boundaries and never saw write-then-revert inside the window. - work
- Host-callable queue drain core (roadmap f-1-1): the drain/claim/skip loop
that used to live only inside
kranzCLI’scmd_work, hoisted here so any surface (CLI, REST, Slack) can drain a repo’s queue. - workspace_
container - Local-container WorkspaceProvider (ticket
.kranz/tickets/local-container-workspace.md, design D-B implementation #2 indocs/scoping/workspace-contract.md) — gives a mission an isolated RUNNABLE environment: a per-mission compose project, dynamic host ports, and contract health/readiness executed INSIDE the container network — solving the host port clashes and Docker daemon contention that bare worktrees cannot. - workspace_
contract - Tracked workspace contract (
.kranz/workspace.json) — schema + validation. - workspace_
data - Golden-data hooks (design D-D in
docs/scoping/workspace-contract.md, ticket.kranz/tickets/golden-data-hooks.md) — the optionaldatablock’sclone/migrate/reset/skewCheckcommands that provision a de-identified golden dataset into the workspace before agents run. - workspace_
gate - Workspace bootstrap + readiness gate (design D-C/D-H, ticket
.kranz/tickets/workspace-bootstrap-preflight.md) — gate helpers plus the block/lift policy. The gate’s EXECUTION moved under thecrate::workspace_providerseam (ticketworkspace-provider-seam):LocalWorktreeProvider::readinessruns the phases below via [run_gate_commands], and the run loop drives provider.provision → provider.readiness (= this gate) → workers. This module remains the single owner of the phase shapes, the decision-summary prefixes the report and workspace endpoint derive outcome lines from, and the milestone block/lift machinery. - workspace_
provider - The WorkspaceProvider seam (design D-B/D-E in
docs/scoping/workspace-contract.md, ticket.kranz/tickets/workspace-provider-seam.md) — who supplies the mission’s runnable environment, separate fromcrate::backend::AgentBackend(who drives model sessions) and fromsandbox.provider(process containment; M7). A container may one day implement both Sandbox and Workspace, but the APIs stay separate: sandbox = blast radius, workspace = bootstrap/services/readiness/previews. - workspace_
remote - Thin remote WorkspaceProvider adapter (ticket
.kranz/tickets/workspace-remote-coder-provider.md, design D-B implementation #3 indocs/scoping/workspace-contract.md) — provisions a mission workspace on a Coder-shaped substrate (or documented equivalent): create from a pinned template/image, surface preview/takeover URLs, inject secret names via the provider. kranz does NOT build a VM scheduler or cloud IDE here — the substrate owns scheduling, images, hibernation economics, and reachability.