Skip to main content

Crate kranz_engine

Crate kranz_engine 

Source
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):

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 claude CLI headless.
backend_codex
Codex agent backend: drives codex exec --json headless.
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 json headless.
backend_kimi
Kimi Code agent backend: drives the headless kimi -p ... --output-format stream-json CLI.
backend_local
Local OpenAI-compatible HTTP backend (f-2-1): the first AgentBackend that drives an in-engine reqwest client rather than a spawned CLI subprocess. Talks to {base_url}/v1/chat/completions in 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.rs in 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_plan time (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 decompose core (ticket: .kranz/tickets/ticket-dag-decomposition.md): one planner turn decomposes a complex goal into a small DAG of ordinary tickets linked by blocked-by edges — 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-by dependency 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+net sandboxed sessions (ticket egress-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-mission events.jsonl plus the optional traced-from-mission ticket frontmatter field. Pure-fold style, mirroring crate::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.rs in 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 — for command-assertion findings 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.result events, 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 as kranz gate-scores <gate> (text or --json). The gate-score-distribution-flags slice (crate::gate_score_flags, KRZ-316) folds the distribution flags over the same gate.result events, 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 is crate::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.rs in 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 .status sidecars into committed frontmatter state: keys (design: ticket-state-frontmatter, rule 4) — kranz ticket migrate-state.
mission_catalog
Mission catalog + mission hygiene — extracted from orchestrator.rs in the monolith split (pure code motion, no behavior change). The catalog helpers edit .kranz/missions/index.md lines (prune, list ids, attach a report link); the hygiene family (roadmap M2) retires missions (abandon_mission) and classifies mission directories for kranz 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, mirroring crate::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 a pack.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.md is 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.rs in 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.rs in 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 single orchestrator.decision at run start, and PREFLIGHT_CLEAR_SUMMARY durably 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, ordered ProvenanceChain that 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, and report.md — extracted from orchestrator.rs in 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 (ticket routing-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-attestation checker decisions (KRZ-346, D-F).
standards_coverage
The Flight Rules rule coverage matrix (ticket .kranz/tickets/flight-rules-finding-provenance.md, KRZ-343; design docs/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 carrying ruleIds, findings carrying a crate::types::RuleCitation — and renders each rule’s disposition as passed, failed, advisory, waived, not-evaluated, or not-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; design docs/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 folded MissionState with no second persisted source of truth. Calling export_validated_traces/to_jsonl again 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 in crate::validator_snapshot; mandatory containment in crate::sandbox::resolve_validator_containment, ticket validator-mandatory-containment).
validator_snapshot
Copy-on-write immutable validator snapshot — the definitive fix for the gap ticket validator-immutability-proof left 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 kranz CLI’s cmd_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 in docs/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 optional data block’s clone / migrate / reset / skewCheck commands 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 the crate::workspace_provider seam (ticket workspace-provider-seam): LocalWorktreeProvider::readiness runs 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 from crate::backend::AgentBackend (who drives model sessions) and from sandbox.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 in docs/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.