
dicklesworthstone/frankenterm
Developer toolsSwarm-native terminal platform for AI coding agents: real-time pane capture, change-point pattern detection, transactional policy-gated automation, a JSON/MCP robot API, and a fail-closed operating...
Overview
The retained 200-pane figures are synthetic benchmark-lane results, not a qualified native or target-class operating envelope. 97 workspace crates, 19 sub-crates carved out of the core, 540 core-library modules, 1421634+ lines of Rust, 64657+ test annotations across 1051 integration test files. Counts are auto-stamped by scripts/stamp-readme-counts.sh and drift fast. See Maintainers: how counts stay honest at the bottom for the exact recipe. Developer checks use the live worktree by default; release snapshots use --source=head so unrelated dirty files cannot alter the attested counts. The installer verifies the DSR-published checksum and minisign signature, then publishes ft, the mux server, the PTY guardian, and (on Apple-Silicon macOS) a verified FrankenTerm.app candidate as one manifest-bound generation.
README
ft — FrankenTerm
What’s here
| If you’re… | Start with |
|---|---|
| Trying it out | 10-Minute Tour → Commands → Robot Mode |
| Building a meta-agent | Robot Mode → Sample Mission/Tx Contracts → Operating Envelope |
| Operating at scale | Capacity Planning → Operator Playbook → Troubleshooting |
| Understanding how it works | Architecture → System Components → Deep Dives |
| Auditing the claims | Trust & Attestation → Threat Model → Formal Methods |
| Reading the algorithms | Algorithm & Data Structure Catalog → Pattern Engine → Cx Cancellation Model |
A swarm-native terminal platform designed to observe, control, and audit large fleets of concurrent AI coding agents. The retained 200-pane figures are synthetic benchmark-lane results, not a qualified native or target-class operating envelope. 97 workspace crates, 19 sub-crates carved out of the core, 540 core-library modules, 1421634+ lines of Rust, 64657+ test annotations across 1051 integration test files.
Counts are auto-stamped by scripts/stamp-readme-counts.sh and drift fast. See Maintainers: how counts stay honest at the bottom for the exact recipe. Developer checks use the live worktree by default; release snapshots use --source=head so unrelated dirty files cannot alter the attested counts.
TL;DR
The Problem. Running large AI coding swarms across ad-hoc terminal panes is chaos. When you’re driving 50–200 Claude Code / Codex / Gemini agents at once, a single undetected rate limit wastes hours of compute. A stuck agent silently burns tokens. An auth failure goes unnoticed for thirty minutes. You have no search across agent output, no audit trail, no way for one AI to safely control another, and no way to know whether your swarm is operating inside or outside its safe envelope.
The Solution. ft is a full terminal platform for agent swarms with deep observability, deterministic eventing, policy-gated automation, machine-native control surfaces (Robot Mode + MCP), and a fail-closed operating-envelope contract. It captures bounded terminal-output deltas across observed panes and records explicit gaps whenever continuity cannot be established, detects state transitions via multi-pattern matching plus Bayesian change-point detection, triggers transactional workflows in response, and exposes those surfaces through a JSON API built for AI-to-AI orchestration. The closest analogy is Kubernetes for terminal-based AI agents: observe, detect, react, audit, and refuse admission outside the envelope justified by the telemetry and evidence currently available. That envelope is deliberately narrower than the eventual 200-pane target while target-class proof remains blocked.
Runtime model. Cx-aware async on asupersync, with project-owned
structured-task and cancellation conventions. Direct tokio usage is
banned at the dependency level via cargo-deny and at the type level via
the RuntimeProof sealed trait. The runtime_async module is the canonical
first-party async API; its implementation layer and explicitly audited
integration seams may still name pinned asupersync types directly. The
dual-runtime era is over. Cancellation responsiveness is an operation-level contract: a wait
must checkpoint its Cx or explicitly race a cancellation signal; merely
holding a Cx does not make every suspended primitive wake on cancellation.
If you’d rather see commands than prose, jump straight to the 10-Minute Tour below.
10-Minute Tour
A guided walkthrough from “I cloned this” to “I have an AI driving an AI.” Each step builds on the previous one.
1 · Install + verify (1 minute)
curl -fsSL https://raw.githubusercontent.com/Dicklesworthstone/frankenterm/main/install.sh | bash
# An idle first install should report activation=current. If it is pending,
# use the printed absolute "Candidate CLI" path without changing live authority:
/absolute/candidate/generation/ft --version
/absolute/candidate/generation/ft doctor
The installer selects one DSR release generation and verifies its checksum and
minisign signature before publication. It automatically activates a first
process-family generation only when two bounded censuses report the host idle
and the stable paths pass --version plus ft doctor --json. It never treats a
standalone ft binary as a complete installation. ft talks to a live
FrankenTerm/WezTerm-fork mux. Native vendored builds can use the direct pooled
mux protocol; compatibility configurations may instead require the external
wezterm CLI in PATH. ft doctor reports the available backend
prerequisites. If you need a source build or optional features (mcp, web,
distributed, semantic-search, ftui), see Installation
below. Do not substitute the stable ft path for the printed candidate path
unless the installer receipt explicitly says the generation is current.
2 · See the fleet (1 minute, no daemon yet)
ft robot state gives an AI-readable snapshot of every pane the mux can see, without starting a long-running daemon. This is the call a meta-agent makes when it wants a one-shot view. The full RobotResponse envelope wraps every response with ok, data, elapsed_ms, version, now, and schema_version (the MCP transport adds mcp_version on top of that); data for the state endpoint is a bare array of pane records (truncated below for clarity):
$ ft robot state
{
"ok": true,
"data": [
{"pane_id": 0, "title": "claude-code", "domain": "local", "cwd": "/project"},
{"pane_id": 1, "title": "codex", "domain": "local", "cwd": "/project"},
{"pane_id": 2, "title": "build", "domain": "local", "cwd": "/project"}
],
"elapsed_ms": 4,
"version": "0.2.0",
"now": 1747371642000,
"schema_version": 1
}
For AI-to-AI use, add --format toon to swap the JSON encoder for the lower-token TOON serialization. Exact savings depend on payload shape; pass --stats and the CLI prints estimated JSON and TOON token counts and the savings percentage to stderr.
3 · Start observing (2 minutes)
Now start the watcher so capture, pattern detection, and workflow execution kick in. Run it in the foreground for the tour:
ft watch --foreground
# (leave this running; new terminal for the next steps)
In a second shell, peek at what the watcher is seeing. ft robot events returns an EventsData envelope that wraps the event list with filter + count metadata:
$ ft status # human-readable fleet overview
$ ft robot events --limit 5 # recent pattern-triggered detections
{
"ok": true,
"data": {
"events": [
{
"id": 1247,
"pane_id": 1,
"rule_id": "codex.usage.reached",
"pack_id": "builtin:core",
"event_type": "detection",
"severity": "warn",
"confidence": 0.95,
"captured_at": 1747371642000
}
],
"total_count": 1,
"limit": 5,
"unhandled_only": false
},
"elapsed_ms": 3,
"version": "0.2.0",
"now": 1747371643000,
"schema_version": 1
}
The watcher’s pattern engine has already noticed pane 1 hit a rate limit; the event is queued for any registered workflow handler to react.
4 · React safely (2 minutes — send + wait-for + policy gate)
Send a /compact to the stuck codex pane, but block until the recovery confirms. The default send path stays fast and only returns the policy-gated injection result plus optional wait-for data. Add --verify-submit or --submit-level when the caller needs a durable submit receipt persisted with the audit row under its idempotency_key:
$ ft robot send 1 "/compact" --verify-submit --wait-for "compaction complete" --timeout-secs 30
{
"ok": true,
"data": {
"pane_id": 1,
"injection": { /* wire-level injection record */ },
"wait_for": {
"pane_id": 1,
"pattern": "compaction complete",
"matched": true,
"elapsed_ms": 4823,
"polls": 96,
"is_regex": false
},
"submit": {
"state": "submitted",
"guarantee_level": "submitted",
"guarantee_met": true,
"attempts": 1,
"evidence_rule_ids": ["policy.allow"],
"elapsed_ms": 4829,
"polls": 96,
"idempotency_key": "rk:0123456789abcdef"
}
},
"elapsed_ms": 4829,
"version": "0.2.0",
"now": 1747371646829,
"schema_version": 1
}
Notice three things: (1) ft robot send is policy-gated — if you try to send something that violates a policy rule, you get a structured RequireApproval envelope with an 8-char approval code, not a silent error. (2) --wait-for is condition-based, not sleep-based — it polls until the pattern shows up or the timeout fires. (3) The response is structured JSON the calling agent can route on. Prompt-active evidence comes from OSC 133 markers emitted by the pane’s shell: until you run ft setup shell (bash, zsh, or fish; idempotent, --dry-run to preview) in the shells you want to drive, an untrusted caller’s first send to a pane returns RequireApproval with rule policy.prompt_unknown rather than ok: true. The running watcher reads those markers live from the mux’s semantic zones, so keep ft watch up: with no watcher, pane state is unknown and the send returns robot.approval_error asking you to start it. Agent TUIs publish no prompt markers, so for Codex and Claude Code the watcher reads the screen instead: an idle input composer counts as prompt evidence (agent_ready:codex, agent_ready:claude_code), while a working agent (esc to interrupt) or any menu, confirmation or folder-trust prompt is treated as a running command and the send is denied. Other agents (Gemini today) and unrecognized screens keep the approval path.
When ok=false, the error fields live at the top level of the envelope (not nested under error):
{
"ok": false,
"error": "Action requires approval",
"error_code": "robot.require_approval",
"hint": "Run: ft approve AB12CD34",
"elapsed_ms": 1,
"version": "0.2.0",
"now": 1747371646830,
"schema_version": 1
}
5 · Search the past (1 minute)
Every byte of pane output the watcher captured is FTS5-indexed. ft robot search returns a SearchData wrapping the result list:
$ ft robot search "error: compilation failed" --limit 3
{
"ok": true,
"data": {
"query": "error: compilation failed",
"results": [
{
"segment_id": 41827,
"pane_id": 1,
"seq": 5821,
"captured_at": 1747370104000,
"score": 1.2845,
"snippet": " --> services/billing/pricing.rs:142:12\n error: compilation failed: type mismatch"
}
],
"total_hits": 1,
"limit": 3,
"mode": "lexical"
},
"elapsed_ms": 7,
"version": "0.2.0",
"now": 1747371700000,
"schema_version": 1
}
Add --mode hybrid for semantic-ranked results; hits then carry semantic_score and fusion_rank fields alongside score.
6 · Orchestrate transactionally (2 minutes — mission + tx)
For multi-pane operations that need rollback semantics, use the Tx engine:
$ ft tx plan --contract-file deploy-staging.json # validate the contract
$ ft tx run # prepare + commit, with auto-compensation on failure
$ ft tx show --include-contract # full receipt with per-step audit
For a free-text operator goal that respects the safety envelope:
$ ft mission objective-plan --objective "spawn 5 codex panes for the pricing refactor"
This invokes the read-only objective planner. It ranks the objective against the scope you pass and a capacity posture you supply (--capacity-posture admit|defer|pause|unknown, default admit); it does not read the live operating envelope itself, so check ft swarm envelope first and pass the posture it implies. See Sample Mission and Tx Contracts for the JSON shapes.
7 · Verify the release attestation (1 minute)
Every load-bearing claim links to a signed artifact slot. The CLI re-hashes every artifact from disk, recomputes the canonical signing payload, checks the recorded .sigstore file hash + size, and verifies the Sigstore signature. Exits 0 on full pass, non-zero on any failure.
ft attestation verify docs/attestations/.json # human-readable verdict
ft attestation verify docs/attestations/.json --json # machine-readable verdict
ft attestation show docs/attestations/.json # pretty-print without re-verifying
ft attestation is a thin Rust wrapper over scripts/attestation-verify.sh; third parties without the ft binary can run the script directly.
Where to go next
- Robot Mode (JSON API) — the full call contract AI agents use to drive other AI agents
- Operating Envelope — the fail-closed safety surface that gates new pane admission
- Commands — every
ftsubcommand with examples - Bundled Demo Scenarios — side-effect-free onboarding/regression fixtures with retained artifacts
- Configuration —
ft.tomlreference for tuning poll intervals, retention, redaction tiers - Operator Playbook — what to do when things break
Read/query interfaces (ft get-text, ft search, ft robot get-text, ft robot search, and MCP wa.get_text / wa.search) are policy-evaluated and redact secret material in returned text/snippets — you won’t accidentally leak a JWT into a notification or an event payload.
Why use ft?
Now that you’ve seen it run, here’s the full capability surface:
| Capability | What it does |
|---|---|
| Full Observability | Captures terminal output across panes with low-latency delta extraction; sub-50 ms lag is the benchmark-lane target (attestation)[^ft-attest-perf-headline][^ft-attest-lindley] |
| Multi-Agent Detection | Aho-Corasick multi-pattern engine + Bloom prefilter + BOCPD change-point detection. Native rule packs for Codex, Claude Code, and Gemini |
| Event-Driven Automation | Workflows trigger on detected patterns with per-workflow trigger-policy allowlists (ft-j0ufc), never on sleep loops |
| Robot Mode API | JSON / TOON envelopes optimized for AI-to-AI control[^ft-attest-robot-contracts] |
| Lexical + Hybrid Search | SQLite FTS5 plus a hash-embedding semantic lane fused with RRF; lexical, semantic, and hybrid modes across captured output |
| Operating Envelope Contract | ft.operating_envelope.v1 planner module decides whether new pane work is admitted based on system pressure; fails closed when telemetry is missing |
| Policy Engine | 14-subsystem policy framework with per-subsystem health verdicts, capability gates, rate limiting, audit trails, and approval tokens |
| Transactional Mission Orchestration | Prepare/commit/compensate lifecycle, idempotency ledger, deterministic replay, kill switches, capacity-aware objective planner |
| Tiered Scrollback | Three-tier memory management (hot/warm/cold) with a worst-of fleet memory controller; 200-pane capacity and memory figures are benchmark-lane results, not a target-class or live-session guarantee[^ft-attest-perf-headline] |
| Incident Bundles | Crash and swarm-incident bundles with recent events, stored pane state, DB metadata, config, git state, and a beads coordination snapshot |
| Replay & Forensics | Capture, replay, and diff decision graphs for post-incident analysis and regression testing |
| Distributed Mode | Optional agent-to-aggregator streaming with per-agent dedup, versioned wire protocol, and stale-session pruning[^ft-attest-distributed-threat] |
| Reality-check + Attestation | Maps claims to artifacts or explicit deferred slots in docs/attestations/manifest.json. Inspect bundle integrity with ft attestation verify; publisher authentication requires a trusted release policy |
[^ft-attest-perf-headline]: Verified via the populated perf/headline-claims attestation slot in docs/attestations/manifest.json; this covers benchmark-lane capture latency, Bloom prefilter speedup, and pane/memory capacity rows. Target-class caveats remain governed by their linked artifacts and the fail-closed swarm-capacity-envelope adjunct.
[^ft-attest-lindley]: Deferred: the perf/lindley-bounds capture-path latency proof is assigned to ft-7h5da.10.2; the manifest currently contains no accepted artifact for this slot.
[^ft-attest-robot-contracts]: Verified via the populated proofs/robot-contracts attestation slot for JSON/TOON control-plane envelope contracts.
[^ft-attest-distributed-threat]: Verified via the populated security/distributed-threat-model attestation slot for distributed wire-protocol safety review and diff-fuzz coverage.
What “swarm-native” actually means
The phrase has a concrete meaning here:
- The minimum-useful-unit is the fleet, not the pane. Every primary subsystem (storage, search, policy, workflows, mission, tx, distributed) models fleets rather than a single-pane-only world. The architecture targets dozens to hundreds of panes; the upper end remains a benchmark target until live and target-class qualification closes.
- Fleet pressure is a first-class signal. The operating envelope, fleet memory controller, and backpressure tiers compose pressure across the entire fleet, not per-pane in isolation. A single hot pane can throttle the rest of the fleet’s poll cadence; a healthy fleet runs at full speed.
- One AI can drive another safely. Robot Mode, MCP, and the policy gate exist specifically so AI agents can control other AI agents without writing brittle text-parsing glue. The JSON envelopes are the contract.
- Coordination primitives are built in. Beads issue tracking, Agent Mail file reservations, work claim queues (
ft robot work), and tx idempotency ledgers exist because swarm work needs coordination, not just observation. - Failure isolation is per-pane, but recovery is per-fleet. A stuck pane doesn’t take down the watcher. An auth failure on one agent doesn’t pause the other 49. But the fleet memory controller throttles uniformly when pressure is real.
Who is this for?
- Anyone running 2+ AI coding agents in parallel and tired of writing bash glue to coordinate them
- Anyone building meta-agents (one AI driving N specialized AIs) who needs a structured control plane
- Operators targeting large swarms (50–200+ panes) who need fleet-wide observability, memory bounds, and capacity admission and can honor the current provisional capacity envelope
- Anyone who has to audit what an AI did in a terminal session after the fact
- Anyone who has lost work to a rate limit they didn’t notice for 30 minutes
- Anyone who wants their multi-agent infrastructure to fail closed rather than silently degrade
Supported Surface Matrix
Honest status of every shipped surface, without migration-era hand-waving.
| Surface | Status | Notes |
|---|---|---|
| Watch / status / triage / doctor / reproduce | Supported | Native operator surfaces; ft doctor, ft status --health, and ft triage are the first-run and incident entrypoints |
| Search / events / audit / workflows / mission / tx | Supported | Backed by local storage, policy, and workflow subsystems |
| Robot mode | Supported | All core families: state, get-text, send, wait-for, search, events, rules, workflow, agents, accounts, reservations, mission, tx, health, proof status, approve, checkpoint, context, work, fleet, profile, connector, kill-switch (persisted operator switch with scoped fence receipts; docs/robot-contracts/kill-switch.md). NTM-gap fallback retired. Caveats: the agents family is gated behind the (default-on) agent-detection feature — a --no-default-features build returns robot.feature_not_available for it (see the Compile-Time Feature Matrix); the connector family’s non-dry-run uninstall/rollback are approval-blocked pending the robot approval-token gate (see docs/robot-contracts/connector.md) |
| Operating envelope | Supported | ft.operating_envelope.v1 planner contract + golden fixtures; fails closed on missing or critical-pressure telemetry |
| Mission objective planner | Supported | Read-only objective planner; the capacity posture is caller-supplied (--capacity-posture), not read from the operating envelope (ft-auy2g) |
| Incident bundles | Partial | ft reproduce export collects recent events, stored pane rows, DB metadata, config, git state and the beads snapshot; audit tail included, process tree opt-in (--process-sample); GPU, render and BSU/ESU collectors are not on the production path |
| Session persistence | Capture/inspect/export supported; restore execution unavailable | Snapshot save/list/inspect/pane-membership diff/delete, ft session doctor, ft session dump, and read-only ft session list-durable / export-durable ship. The live dump is a private, redacted, checksummed export of live pane text plus bounded topology metadata; the durable export reads the committed cold-scrollback prefix for one stable pane UUID. Neither is a process checkpoint or executable restore image. ft snapshot restore and robot checkpoint rollback accept metadata-only --dry-run descriptor/status reporting, but every non-dry invocation fails closed before database resolution, process discovery, subprocess launch, or mux mutation. Production does not currently restore panes, processes, hot viewport, mux domains, window/workspace placement, durable tab order, stable active-tab identity, or full appearance. |
| Reality-check + attestation | Supported | ft attestation verify / show ship as a thin Rust wrapper over scripts/attestation-verify.sh. Signed bundles live in docs/attestations/ |
| Deferred proof queue | Supported with fail-closed proof prerequisite | ft proof queue/status/replay/attach and ft robot proof status expose source-landed proof intents. Replay executes only through remote-required RCH when admission is explicitly admitted; local Cargo is never substituted. Release-slot evidence stays under docs/attestations/proofs/deferred-proof-replay.json; current W8.2 remote proof remains blocked on RCH admission. |
| Web API / SSE | Supported (web feature, on by default) |
/health, /panes, /events, /search, /stream/events, /stream/deltas |
| Browser fleet viewer | Preview: read-only, local or HTTPS proxy | ft web --ui-dir serves a FrankenTUI WASM viewer of panes and live detections at /ui/ (Browser fleet viewer). Operator-token sign-in protects HTTP reads and live streams; FT_WEB_HTTPS_ORIGIN enables exact-origin authentication behind a trusted HTTPS proxy. Live tailnet qualification, terminal attach and DSR-packaged assets remain under ft-browser-frankenterm-7z4il |
| Distributed mode | Supported (distributed feature, on by default) |
Remote panes persist into the same DB and surface through status/search/state; live get-text for distributed panes is intentionally unavailable |
| MCP server | Supported (mcp feature, on by default) |
stdio tool surface; per-family Robot parity is scoped in docs/robot-contracts/mcp-robot-surface-matrix.md |
| Semantic search | Supported (hash embeddings) | Hybrid mode fuses FTS5 with a built-in FNV-1a hash-embedding lane via RRF; fastembed/ML models and a Tantivy index are not on the production path |
| Browser auth tooling | Feature-gated (on by default) | ft auth is real; it needs the browser feature (in default builds) and a usable browser stack on the host |
| GUI (FrankenTerm.app) | Supported on macOS | Native macOS bundle; live render-state plumbing, BSU/ESU sync-output, classified drag handlers, command-palette domain labels |
Design Philosophy
1. Passive-First Architecture
The default observation loop does not send pane input, but it is not
side-effect-free: ft watch owns persistence lifecycle work, including schema
migration, capture writes, and retention pruning. With --auto-handle, matched
events can also enter policy-gated workflow actions. Input, workflow,
mission, and transaction effects remain separately gated and auditable; do not
treat starting a watcher as a passive offline diagnostic.
2. Event-Driven, Not Time-Based
No sleep(5) loops hoping the agent is ready. Every wait is condition-based: wait for a pattern match, wait for pane idle, wait for an external signal. Deterministic, not probabilistic. ft robot wait-for blocks until a specific pattern appears in pane output, not until a timer expires.
3. Delta Extraction Over Full Capture
Instead of repeatedly persisting entire scrollback buffers, ft uses a bounded 1 MiB overlap window to extract only new content. The larger default can match retained prefixes after realistic scrolls without turning routine polls into false full-snapshot gaps. When overlap still cannot be established (terminal reset, scrollback clear, or a shift beyond the bound), the discontinuity is recorded as an explicit event rather than silently dropped.
4. Single-Writer Integrity
A filesystem lock (via fs2) ensures only one watcher can write to the database. No corruption from concurrent mutations. Graceful fallback for read-only introspection. The lock metadata records PID and start time for diagnostics.
5. Agent-First Interface
Robot Mode returns structured JSON with consistent schemas. Every response includes ok, data, error, elapsed_ms, and version. TOON (Token-Optimized Object Notation) is the lower-token machine format; payload shape controls savings, and the benchmark substrate lives at docs/perf-ledger/toon-encoding.md. The format is built for machines to parse, not humans to read.
6. Transactional Safety
Multi-pane operations use a prepare/commit/compensate lifecycle borrowed from distributed transaction protocols. If a commit step fails, compensation rolls back the committed steps. Kill switches and pause controls provide emergency intervention. Every transition emits an observability event with a reason code and decision path.
7. Defense in Depth for Memory
The fleet memory controller synthesizes pressure signals from three independent subsystems: pipeline backpressure (queue depths), system memory utilization, and per-pane memory budgets. These feed a unified 4-tier pressure model (Normal, Elevated, Critical, Emergency) with asymmetric hysteresis that escalates fast and de-escalates slow. During incidents, operators use the resource-pressure cockpit contract to separate rust_heap, mmap_file_backed, sqlite_page_cache, graphics_media, scrollback_cache, child_processes, and unknown resident memory before calling anything a leak.
8. Fail Closed on Missing Telemetry
The operating envelope, network-pressure selector, process-snapshot pipeline, and RCH critical-pressure gate all refuse to advance when their measurement source is absent or unhealthy. A swarm controller that doesn’t know what state the system is in must not pretend to know. This is enforced at the call sites of every component that consumes pressure or health telemetry.
9. Layered via Extraction
Layering is enforced through sub-crate extraction, not just discipline. frankenterm-core has 19 sibling sub-crates carved out. Core imports shared leaf types; cluster crates such as ARS, replay, search, and fleet depend on core and shared leaves. Cargo rejects cycles among normal and build dependencies; dev-dependency cycles allow core’s tests to exercise extracted clusters.
10. Reality-Check Discipline
Every headline claim is meant to link to a signed attestation slot. The quarterly /reality-check-for-project discipline produces a bridge plan, a substrate of proof slots, and a per-release bundle. The current round (ft-xxfwy, opened 2026-09-01) closes the entry ramp first: a signed installable release, ft attaching to the running FrankenTerm.app, a live-agent proof of the observe → detect → react → audit loop, and the first real signed bundle. See docs/reality-check-bridge-plan-2026-09-01.md; the earlier rounds are docs/reality-check-bridge-plan.md (2026-04-30) and docs/reality-check-bridge-plan-2026-05-12.md (ft-tf6g3).
Glossary of Terms
Terminology used throughout this document and the codebase. Reading these once saves grepping later.
| Term | Meaning |
|---|---|
| Mux | The terminal multiplexer process. ft talks to the WezTerm/FrankenTerm mux. |
| Domain | A backend that hosts panes — local, SSH:, tmux:, or a custom domain. Each pane has one. |
| Window / Tab / Pane | Mux topology unit, in increasing granularity. A window holds tabs; a tab holds panes. |
| Session | An ft concept: a coherent run of the watcher with persistent identity. Sessions outlive individual mux restarts. |
| Snapshot | A point-in-time capture of the mux topology + per-pane state, persisted to the DB. |
| Checkpoint | A persisted session-progress marker; checkpoints accumulate within a session. |
| Backup | A portable archive of the entire ft database, separate from snapshots. |
| Capture | The act of reading current scrollback from a pane and persisting any new bytes. |
| Delta | The new bytes a capture produced after the bounded 1 MiB overlap match. |
| Gap | Captured discontinuity (the previous tail didn’t match anywhere in the new capture). Recorded as an event. |
| Rule | A pattern with stable ID, anchor strings, regex, severity, and agent type. |
| Rule pack | A versioned collection of rules; the default is builtin:core. |
| Detection | A rule firing on captured text; emitted as an event with the originating pane_id and rule_id. |
| Event | A typed message on the event bus — detections, gaps, lifecycle changes, system events. |
| Workflow | A registered handler that runs in response to detected events (or on demand). |
| Mission | A planned multi-pane operation with a contract, lifecycle state machine, and audit trail. |
| Tx (transaction) | The execution engine for missions; prepare → commit → compensate with idempotency receipts. |
| Operating envelope | The fail-closed admission contract that decides whether new pane/workflow work is safe right now. |
| Profile | A reusable pane specification (agent + cwd + env + session settings). |
| Persona | Behavioral defaults a profile inherits (skill mix, prompt preludes, tool palette). Planned: defined as a type, not yet loadable from ft. |
| Fleet template | A composition of profiles with counts and dependencies. Planned: defined as a type, not yet loadable from ft. |
| Reservation | An advisory lease on a pane (or file path) preventing concurrent edits. |
| Approval token | A one-shot, scope-pinned 8-char code that lets a specific action through the policy gate. |
| Robot Mode | The JSON / TOON API surface AI agents use to drive ft. |
| TOON | Token-Optimized Object Notation — a compact tree serialization for AI-to-AI envelopes. |
| Cx | asupersync’s cancellation context; propagates cancel signals through structured concurrency. |
| RuntimeProof | A sealed trait that makes tokio::* types refuse to compile in bounded API surfaces. |
| Aggregator | In distributed mode, the host running ft watch with the listener; it receives streams from ft distributed agent peers. |
| Cockpit | The resource-pressure cockpit contract; classifies resident memory before any “leak” claim. |
| Reality-check | The quarterly discipline that produces a bridge plan + substrate + signed per-release attestation bundle. |
| Bead | A unit of tracked work in beads_rust (br); IDs prefix ft-* for this project. |
| PDU | Protocol Data Unit — the codec layer’s wire message envelope between mux client and mux server. |
Safety Guarantees
- Observe vs act split: the default
ft watchloop does not send pane input, but it does own local persistence effects such as schema migration, capture writes, and retention pruning. Input and--auto-handleworkflow actions remain separately policy-gated and auditable. - No silent gaps: capture gaps are recorded explicitly and surfaced in events/diagnostics.
- Policy-gated sending:
ft sendand workflows enforce prompt/alt-screen checks, rate limits, and approvals. - Policy-gated reads:
get-text/searchsurfaces enforce policy checks and return redacted text payloads. - Transactional operations:
ft tx runuses prepare/commit/compensate phases with idempotency guards and deterministic replay. - Approval tokens: allow-once approval codes scoped to specific action + pane + fingerprint combinations.
- Secret redaction: captured output is redacted before being returned through any API surface, with configurable sensitivity tiers (T1/T2/T3) and retention policies. Token redactor coverage was expanded in 2026-05 to include JWT, GitLab, Twilio, SendGrid, and Datadog patterns.
- Workflow trigger-policy allowlists (ft-j0ufc): high-trust workflows declare allowlisted source panes to prevent low-trust panes from triggering them via output injection.
- Public-field bypass class eliminated: ~6 audit findings closed where
pubstruct fields let callers bypass clamping or validation. Constructors/builders now own the invariants forErasureShard,CircuitBreaker::Config,QuantileBudgetMs,ArrivalCurve,ServiceCurve,ApprovalScope/AuditContext,ScaleFactor, andAxisValue. - Rubber-stamp
is_safe()class eliminated: ~17 audit findings closed whereis_safe()returnedtrueon cold start or before measurements were recorded. Every release-gateis_safenow requires evidence before reporting safe. - Attestation bundles:
docs/attestations/records artifact hashes and deferred claims. Bundle integrity, publisher authentication under a trusted policy, and the DSR release artifact signatures are separate checks; a development bundle is not proof of a published release.
Trust & Attestation
Latest reality-check drumbeat: docs/reports/reality-check-2026-11-20.md (2026-11-20). Fourth full pass (RC4): docs/reality-check-bridge-plan-2026-11-20.md, epic ft-mgy5t2 (four-surface truth, cross-platform release-channel split, attestation --strict-deferred unblock, and proof-closeout convergence). Predecessors: 2026-04-30 (RC1), 2026-05-12 (ft-tf6g3, RC2), and 2026-09-01 (ft-xxfwy, RC3).
The canonical manifest is docs/attestations/manifest.json; each slot maps a claim category to its producing-bead artifact, and the per-release bundle signs those slot hashes.
The README claim-to-slot map identifies populated artifacts and explicitly deferred proofs:
| README claim | Manifest slot | Producing bead |
|---|---|---|
| Capture latency benchmark lane | perf/headline-claims |
ft-syqcz.3 |
| Deferred: capture-path Lindley / min-plus bound | perf/lindley-bounds |
ft-7h5da.10.2 |
| Bloom prefilter search speedup | perf/headline-claims |
ft-syqcz.3 |
| 200-pane capacity and memory-budget benchmark lane | perf/headline-claims |
ft-syqcz.3 |
| Robot JSON/TOON envelope contract | proofs/robot-contracts |
ft-0elb9 |
| Scoped remote operating-envelope read-only admission proof; target-class capacity remains unproven | proofs/robot-contracts |
ft-booek.7 |
| Redactor coverage matrix | security/redactor-coverage |
ft-x0666.2 |
| Distributed wire-protocol safety | security/distributed-threat-model |
ft-x0666.3 |
runtime_async Loom model |
proofs/loom-runtime-async |
ft-e87u6.12 |
RuntimeProof sealed-trait guard |
proofs/runtime-proof-trait |
ft-i2eni.1 |
| Transaction kill-switch proof | proofs/tx-killswitch |
ft-tf6g3.12 |
The operating-envelope contract (ft.operating_envelope.v1) remains deferred
under the proofs/robot-contracts manifest category to ft-booek.7.
Its retained artifact records scoped remote contract tests and development bundle
verification; final artifact and bundle qualification remain pending. The slot does not
prove target-class production capacity while the target-class resource-cockpit
artifact remains skipped_not_proven. The
renderer SLO suite is still tracked under ft-tf6g3
for inclusion in a future bundle. The optional proofs/rehearsal-score slot
hashes the rehearsal-score golden matrix so blocked, skipped, degraded,
missing-evidence, and fixture-only score rows stay visible; it is not a
production support claim unless the cited receipt criterion has proven evidence.
Verify a release attestation bundle in one command, offline, without trusting GitHub or any registry:
ft attestation verify docs/attestations/.json
The CLI re-derives every artifact’s SHA-256 from disk, recomputes the canonical signing payload, checks the recorded .sigstore file hash and size, and verifies the Sigstore signature. Exits 0 on full pass; non-zero on any failure. For machine-readable output:
ft attestation verify docs/attestations/.json --json
ft attestation show docs/attestations/.json
Use --strict-required on verify to fail when the bundle’s required_categories list does not match the canonical manifest. The release gate is meant to run the shell verifier with --strict-deferred so tagged releases cannot ship intentionally deferred slots; wiring that check into the DSR quality gate is tracked under ft-xxfwy.15. At this revision the only bundle in the tree is docs/attestations/0.0.0-dev.json (dev channel, signature.method: unsigned); no tagged release has shipped a signed bundle yet, so `` in the examples above is a placeholder until the first one lands.
The ft attestation family is a thin Rust wrapper over scripts/attestation-verify.sh; third parties without an ft binary can run the script directly with the same arguments. For Sigstore signing identity, Fulcio/Rekor trust-root details, and manual cosign verify-blob commands, see docs/attestations/SIGNING.md. For the per-release closure procedure (when to run, how to file regressions on hash mismatch), see docs/release/attestation-checklist.md.
How ft Compares
| Feature | ft | WezTerm | Zellij | Ghostty |
|---|---|---|---|---|
| Swarm-native orchestration | Built in; 200-pane scale is benchmark-lane only, pending target qualification | External glue required | External glue required | External glue required |
| Event-driven automation | Built-in workflows + policy gate | Not native | Not native | Not native |
| Machine API for agents | Robot Mode + MCP + TOON | None | None | None |
| Operating-envelope safety | Native fail-closed contract | None | None | None |
| Cross-session capture + inspection | Built-in snapshots + sessions; automated restore/restart execution is unavailable | Partial / manual | Session-centric, not swarm-centric | Minimal |
| Agent-safe control plane | 14-subsystem policy diagnostics surface | Not native | Not native | Not native |
| Transactional multi-pane ops | Prepare/commit/compensate + idempotency ledger | None | None | None |
| Full-text search over output | FTS5 + hybrid (RRF) modes | None | None | None |
| Memory management at scale | Three-tier scrollback + fleet controller | Single tier | Single tier | Single tier |
| Replay and forensics | Decision graph + diff + provenance | None | None | None |
| Reality-check attestation bundles | Sigstore-signed slot manifest | None | None | None |
| Incident bundles | Events, pane rows, DB/config/git state, beads snapshot | None | None | None |
| Async runtime contract | asupersync, Cx-first, project-audited cancellation, tokio banned |
tokio (no Cx model) |
smol (no Cx model) |
none of these project-specific contracts |
| Unsafe code | Forbidden in CLI/core; audited native/FFI exceptions | unsafe present | unsafe present | unsafe present |
When to use ft:
- Running 2+ AI coding agents that need coordination
- Building automation that reacts to terminal output
- Debugging multi-agent workflows with full observability
- Operating agent swarms with memory and backpressure control, while treating the published 50–200-pane figures as provisional benchmark bounds until the target-class gate passes
- Anywhere a swarm controller needs attestable safety bounds
When ft might not be ideal:
- Single-shell / single-agent usage where orchestration is unnecessary
- Environments that only need a lightweight interactive terminal and no swarm control plane
- Use cases that require driving a different mux backend (tmux, Zellij, kitty) — by design,
ftruns on its own in-tree terminal engine, not an abstraction over arbitrary multiplexers
Real-World Scenarios
These are the workloads ft was built for. Each scenario describes the operator pain without ft, then how the platform addresses it.
Scenario 1 — Detect and recover from rate limits across a 50-pane swarm
Without ft: You’re driving 50 Codex/Claude Code panes in parallel. One agent hits its usage limit and silently stops making progress. You don’t notice for 30 minutes. The other 49 agents continue burning tokens until they hit their limits.
With ft: the native rule packs recognize supported usage-limit output and record the originating pane_id and rule_id. Provider wording changes and unknown forms still require detection updates; the 50-pane journey needs target-class qualification. Two approaches:
# A) Let the built-in workflow handle it (preferred)
ft watch --foreground --auto-handle # registers handle_usage_limits, handle_compaction, …
# B) Inspect detected events before choosing a provider-specific recovery
ft robot --format json events --unhandled --limit 50 | \
jq -c '.data.events[] | {id, pane_id, rule_id}'
# Wait for literal output on one pane (this does not subscribe to a rule ID)
ft robot wait-for 7 "Usage limit" --timeout-secs 3600
ft robot wait-for takes a single pane_id and a substring (or regex with --regex). For fleet-wide reactions, inspect ft robot events --unhandled or use --auto-handle. Context compaction does not reset an account quota. A custom consumer must deduplicate and acknowledge events after an observed outcome, and pause when recovery needs operator approval. Workflow sends pass the same policy gate as ft robot send: they go through when the pane shows prompt evidence (OSC 133 from an integrated shell, or a recognized Codex / Claude Code composer at rest) and stop at an approval request or a denial otherwise, so a busy agent or an open menu is never typed into.
Scenario 2 — Coordinate a multi-pane mission with safe rollback
Without ft: You need to run a 5-step refactor across 4 panes (e.g., “pane 1 rewrites tests, panes 2–4 update implementations in parallel, then pane 1 verifies”). You wire this with bash, shell sleeps, and prayer. When step 3 fails halfway, you have no way to roll back the partial work.
With ft:
ft mission plan --mission-file refactor.json # validate the contract
ft mission status # see the dispatch summary
ft tx run --contract-file refactor-tx.json # prepare + commit deterministically
# if a step fails mid-commit, ft tx automatically runs compensation
ft tx show --include-contract # see the receipt + per-step audit
The tx engine uses prepare/commit/compensate phases with an idempotency ledger. Compensation can fail, and an interrupted external effect can remain indeterminate; inspect the receipt before retrying. Mission planning and lifecycle metadata do not yet drive or cancel running agent tasks (ft-majms, ft-xxfwy.48). This scenario remains a product goal until that driver and crash/recovery path are qualified.
Scenario 3 — Reconstruct what an agent did six hours ago
Without ft: A coding agent did something destructive at 02:14 AM and you find out at 08:00. The terminal scrollback rolled. The pane process exited. You have no record.
With ft: captured pane deltas are redacted and stored in SQLite with FTS5 indexing. Capture gaps, truncation, retention, and periods without a running watcher limit the history; it is not a byte-perfect record of all terminal activity. Policy audit records cover instrumented action and denial paths; the supported-surface audit tracks the remaining coverage gaps.
# Search captured output for the timeframe (--since takes epoch ms)
SIX_HOURS_AGO_MS=$(( $(date +%s) * 1000 - 6 * 3600 * 1000 ))
ft search "the suspicious string" --pane 7 --since $SIX_HOURS_AGO_MS
# `ft history` accepts human-readable since strings
ft history --pane 7 --since "6 hours ago"
ft history --pane 7 --since "2026-05-16T02:00:00" --until "2026-05-16T03:00:00"
# Check the audit trail for actions ft itself took (--since takes epoch ms)
ft audit --pane 7 --since $SIX_HOURS_AGO_MS
# Pull a long tail of the pane's current buffer (audit history covers the rest)
ft robot get-text 7 --tail 5000
Scenario 4 — Stand up a fresh swarm host with a known-safe envelope
Without ft: You provision a new VPS, install your CLI tools, kick off 100 agents, and the box OOMs at 87. You have no model of what “safe” capacity is for this hardware.
With ft: The operating-envelope planner evaluates available pressure snapshots and configured bounds. Admission is a model decision, not a hardware safety guarantee. Target-class resource evidence remains unproven, and authenticated receipt consumption is tracked in ft-7h5da.10.4.4. Inspect the evidence state and limiting inputs before starting a large fleet.
ft swarm envelope # current admission verdict and the limiting inputs
ft mission objective-plan --objective "spawn 100 codex panes" --strictness strict \
--capacity-posture defer
# objective-plan does not read the envelope; pass the posture the envelope implies
Scenario 5 — Drive one AI by another, safely
Without ft: You want Claude Code (the meta-agent) to control 10 specialist Codex panes. You build glue with tmux send-keys, regex parsing of scrollback, and brittle sleep loops. Three weeks later you have a 2000-line Python script with seven race conditions.
With ft: The meta-agent runs ft robot --format toon state for fleet snapshots, ft robot wait-for for condition-based blocking, ft robot send for input (with policy gates), and ft robot search for cross-pane retrieval. Every call returns a structured envelope. The meta-agent never sees raw scrollback unless it explicitly asks.
# Snapshot every pane the mux can see (use TOON to save tokens)
ft robot --format toon state
# Wait for a specific condition on a single pane
ft robot wait-for 7 "Press Enter to continue" --timeout-secs 600
ft robot send 7 "" # respond
# Pull unhandled events across the fleet, react per rule_id
ft robot --format json events --unhandled --limit 50 | \
jq -c '.data.events[]' | while read -r e; do
rule=$(echo "$e" | jq -r .rule_id); pane=$(echo "$e" | jq -r .pane_id)
case "$rule" in
*.usage.reached) printf 'Review provider recovery for pane %s\n' "$pane" ;;
*.approval_needed) printf 'Operator approval required for pane %s\n' "$pane" ;;
esac
done
Scenario 6 — Investigate a crash without losing context
Without ft: A pane crashes. You have a core file maybe, scrollback definitely gone, no way to correlate with the other panes’ state at the moment of failure.
With ft:
ft reproduce export --kind crash --out /tmp/incident
# Bundle includes: recent events, audit tail, stored pane/mux rows, SQLite metadata,
# redacted config, git status, latest crash report, beads coordination snapshot
# (add --process-sample for a redacted process-tree snapshot)
Live collectors snapshot the world at the moment of failure. The bundle is portable; you can attach it to a bug report and a reviewer can reconstruct the incident without the original host.
Why FrankenTerm Owns Its Terminal Engine
FrankenTerm runs on its own terminal engine — a fully vendored, in-tree fork of WezTerm’s mux/termwiz/term crates that the project now owns and has diverged, not a live dependency on upstream WezTerm and not an abstraction layer over arbitrary terminal multiplexers. The terminal-emulation core began as a WezTerm fork; everything built on top of it — the watcher capture loop, the pattern/change-point engine, Robot Mode + MCP, missions and transactions, the policy gate, and the operating-envelope contract — is FrankenTerm’s own. This section explains why that engine is vendored and owned rather than wrapped, and how upstream fixes are still harvested.
The decision
The vendored frankenterm// workspace members are first-class. There are currently 42 top-level vendored crate directories and 55 Cargo workspace members when nested derive/lua crates are included. No “implementation boundary” exists between ft and “the mux”; the in-process mux session API is the MuxInterface trait, and the audit under docs/proposals/ft-zoxxq-mux-boundary-truth.md (7,803 LOC examined, 31 importers, 192 concrete-type refs, 0 trait-object consumers) confirmed that nobody actually treats the boundary as polymorphic.
Why not abstract over both WezTerm and (say) Zellij?
- Mux semantics aren’t interchangeable. WezTerm’s pane lifecycle, scrollback model, alt-screen handling, and PDU schema are concretely different from Zellij’s or tmux’s. Pretending otherwise produces an abstraction that’s a worst-of-all-worlds compromise.
- The asupersync runtime contract is tighter than upstream WezTerm assumes.
ftowns its own async story (Cx-first propagation, structured task ownership, and audited cancellation checkpoints/races). Reusing the vendored crates means we can (and do) patch them when their runtime assumptions don’t fit ours. - Test/proof surfaces are easier on owned code. RuntimeProof, the
asupersync_test!macro, the Loom model, and the cargo-deny tokio ban only work because we control the entire dependency graph. - Bundle identity matters. FrankenTerm.app is a distinct macOS bundle (separate bundle ID, separate icon, separate update channel). Side-by-side install with upstream WezTerm is intentional.
Weekly upstream backport workflow
We never blindly merge upstream WezTerm. Upstream is treated as a read-only patch source:
- Find the upstream baseline from
frankenterm/PROVENANCE.json(divergence_point.subjectrecords the imported WezTerm commit). - Fetch upstream into a read-only tracking ref.
- Build an inventory of upstream commits since the baseline, grouped by subsystem:
term,termwiz,window,config,mux,pty,font,ssh,codec, GUI, mux-server. - Prioritize security, crash, data-loss, terminal-correctness, macOS/windowing, PTY, SSH, and font fixes before cosmetic changes.
- For each accepted upstream commit, port the smallest coherent slice manually into the renamed FrankenTerm paths (no regex-based code rewrites). Include the upstream SHA in the commit body as
Upstream-WezTerm:. - Validate package-scoped first (e.g.,
cargo check -p mux --lib), then broader workspace checks. - Update provenance/backport notes at the end of each batch.
Good backports feel like FrankenTerm-native fixes with traceable upstream provenance, not like a partial re-import of WezTerm.
Installation
Via install script (curl | bash)
The one-liner installs a prebuilt ft binary (no Rust toolchain required) and, on Apple-Silicon macOS, the FrankenTerm.app GUI bundle:
curl -fsSL https://raw.githubusercontent.com/Dicklesworthstone/frankenterm/main/install.sh | bash
# Force a fresh fetch past any CDN cache:
curl -fsSL "https://raw.githubusercontent.com/Dicklesworthstone/frankenterm/main/install.sh?$(date +%s)" | bash
What it does:
- Downloads one DSR-published release generation for your platform, verifies its SHA-256 checksum and repository-pinned minisign signature, and stages the manifest-bound
ft, mux-server, and PTY-guardian process family under~/.local/bin(override with--dest DIR, or--systemfor/usr/local/bin). - Requires
minisignfor release verification (brew install minisignon macOS); the installer checks this before downloading any release artifact. - On macOS arm64, it also stages and proves the matching FrankenTerm.app (the GUI terminal emulator, bundled
ft, mux server, and PTY guardian) at/Applications(or~/Applicationswhen/Applicationsisn’t writable). Until cross-launcher lifetime serialization and PTY handoff are production-proven, the verified app remains at its generation-specific candidate path and the live app bundle is unchanged. It does not restart the Dock or add a Dock tile. Skip it with--no-app, force it with--with-app, or relocate it with--app-dest DIR. - Falls back to a from-source build when no prebuilt asset matches your platform (Intel Mac, uncommon targets).
| Flag | Effect |
|---|---|
--version vX.Y.Z |
Install a specific release (default: latest) |
--dest DIR / --system |
CLI install location (~/.local/bin default; /usr/local/bin with sudo) |
--easy-mode |
Append ~/.local/bin to PATH in your shell rc files |
--with-font |
Also install the bundled Pragmasevka Nerd Font |
--no-app / --with-app / --app-dest DIR |
macOS GUI-app control (skip / force / relocate) |
--from-source |
Build from source instead of downloading (needs Rust + git) |
--offline TARBALL |
Install from a local tarball; no network |
--activate-if-idle |
After publishing an upgrade, promote it only when the bounded process census remains inactive at the activation boundary. First installs use this safe-idle path by default. Active or ambiguous hosts retain the verified candidate without changing authority. |
--activate ID --idle-host-confirmed |
Promote the published candidate generation ID (printed in the install receipt) to the current authority so ft, the mux server, and the PTY guardian resolve on PATH. It takes the permanent installer lock, requires explicit idle-host confirmation, repeats the process census, commits the shared selector last, runs stable-path readiness plus ft doctor --json, and restores the exact prior authority if readiness fails. This is an idle maintenance operation, not live-pane handoff. |
--no-verify |
Skip the DSR minisign signature check only; SHA-256 remains mandatory (testing only) |
--verify |
Run the published generation’s ft doctor --json by immutable path; fail installation verification on a non-zero exit or malformed/oversized JSON. A passing pending-candidate self-test does not activate it. |
The bundled GUI app is ad-hoc signed (not Developer-ID notarized). A curl/terminal-placed bundle isn’t Gatekeeper-quarantined, so it launches normally; if you instead fetch the .app asset through a browser, clear the quarantine flag with xattr -dr com.apple.quarantine /Applications/FrankenTerm.app before first launch.
On the first launch that uses the canonical frankenterm data and cache
namespaces, FrankenTerm transactionally reconstructs only validated,
FrankenTerm-owned window state and remembered-domain authority from the former
wezterm data leaf. It never bulk-copies that directory and never deletes old
evidence. Rebuildable cache and update metadata start fresh. Plugins, REPL
history, recent commands, recent emoji, unknown files, and other
ownership-ambiguous state remain untouched only in the legacy leaf so a
side-by-side WezTerm installation cannot be imported or overwritten.
Why direct cargo install is not an installation path
Installing only the ft Cargo binary can silently combine a new CLI with an
older mux server, PTY guardian, or GUI bundle. That is not a supported
FrankenTerm installation. Use the release installer above for a coherent,
signed generation. Use the next section only to build an uninstalled checkout
for development.
Build a checkout from source
git clone https://github.com/Dicklesworthstone/frankenterm.git
cd frankenterm
bash scripts/install-hooks.sh
RCH_REQUIRE_REMOTE=1 RCH_NO_SELF_HEALING=1 rch --no-self-healing exec -- \
env CARGO_TARGET_DIR=/tmp/ft-readme-release-interactive \
cargo build --locked --profile release-interactive \
-p frankenterm --bin ft \
-p frankenterm-mux-server --bin frankenterm-mux-server \
-p frankenterm-pty-guardian --bin frankenterm-pty-guardian
This builds an uninstalled candidate process family on the selected RCH worker.
The command requests /tmp/ft-readme-release-interactive as CARGO_TARGET_DIR;
RCH can remap it to a worker-scoped build directory. Consult the RCH transcript
and artifact receipt for actual remote and retrieved local paths. Do not
copy only ft over a live
installation: the CLI, mux server, and PTY guardian are an atomic family with a
shared build identity, manifest, and selector. On Apple-Silicon macOS, build the
complete four-role app bundle (GUI plus that process family) with
scripts/create-macos-bundle.sh; the script uses the repository’s strict RCH
source-fencing contract and emits FrankenTerm.app plus its component manifest.
To install a published release from source rather than merely build a checkout, use the installer path so the complete family is sealed and verified:
curl -fsSL https://raw.githubusercontent.com/Dicklesworthstone/frankenterm/main/install.sh \
| bash -s -- --from-source
With optional features
# MCP server support
cargo build -p frankenterm --profile release-interactive --features mcp
# Web API with SSE event/delta streaming
cargo build -p frankenterm --profile release-interactive --features web
# Distributed mode (agent streaming)
cargo build -p frankenterm --profile release-interactive --features distributed
# Semantic search (ML embeddings)
cargo build -p frankenterm --profile release-interactive --features semantic-search
# TUI dashboard (FrankenTUI backend)
cargo build -p frankenterm --profile release-interactive --features ftui
# Legacy ratatui parity oracle for development/regression checks
cargo build -p frankenterm --features tui-oracle
# Everything
cargo build -p frankenterm --profile release-interactive --all-features
Requirements
- Rust nightly (Rust 2024 edition; see
rust-toolchain.toml) - A reachable FrankenTerm/WezTerm-fork mux endpoint for pane discovery, live read/write, and snapshot capture. The direct pooled mux protocol is the preferred path; the external WezTerm CLI is an eligible compatibility fallback, not a universal prerequisite.
- SQLite (bundled via
rusqlite— no system dependency)
Setup & First-Run Checklist
For setting up a new host (font, daemon, persistent config). For learning the tool, see the 10-Minute Tour above.
1. Run setup (recommended)
ft setup
ft setup font --apply # Pragmasevka Nerd Font (auto-installs on normal usage)
FT_SKIP_BUNDLED_FONT_INSTALL=1 ft status # opt out of automatic font install
2. Verify first-run health
ft doctor
ft status --health
wezterm cli list
3. Start the watcher
ft watch # daemonized
ft -v watch --foreground # foreground for debugging
4. Check status
ft status # human-readable
ft robot state # JSON
5. Search captured output
ft search "error" # full-text search (alias: ft query)
ft events # recent detections
ft events annotate 123 --note "Investigating"
ft events triage 123 --state investigating
ft events label 123 --add urgent
ft robot search "compilation failed" --limit 20
6. React to events
ft robot wait-for 0 "Usage limit"
ft robot send 0 "/compact"
7. Stream live updates (web feature)
ft web # start local server
curl -N http://127.0.0.1:9999/stream/events
curl -N "http://127.0.0.1:9999/stream/events?channel=detections&pane_id=7&max_hz=25"
curl -N "http://127.0.0.1:9999/stream/deltas?pane_id=7&max_hz=50"
/stream/eventsdelivers persisted detections in database ID order astext/event-stream. Fresh subscriptions start at an atomic database checkpoint; reconnects resume from the last received checkpoint or detection cursor. EventBus notifications wake storage reads promptly, and periodic reads recover detections whose notifications were lost. Lifecycle and diagnostic signals remain best-effort live events; bus overflow produces an explicitlagframe./stream/deltasstreams redacted pane output deltas and gap markers from storage.max_hzbounds fan-out rate;pane_idnarrows to one pane;channelacceptsall,deltas,detections, orsignals.
Commands
Watcher management
ft watch # start watcher in background
ft watch --foreground # run in foreground
ft watch --auto-handle # enable auto workflows
ft stop # stop running watcher
Pane inspection
ft status # overview of observed panes
ft status --health # health view with operator next steps
ft show # detailed pane info for a live pane
ft get-text # recent output from pane
Pane actions
ft send "" # send input (policy-gated)
ft send "" --dry-run # preview without executing
ft send "" --wait-for "ok" # verify via wait-for
ft send "" --no-paste --no-newline
# Default = the text as one bracketed paste, then a typed Enter that submits it
# (agent composers and shell prompts alike). --no-paste types the characters
# instead; --no-newline leaves out the Enter. The receipt reports the mode as "no_paste".
Search
ft search "" # full-text search
ft search "" --pane 0
ft search "" --limit 50
Explainability
ft why --list # list explanation templates
ft why deny.alt_screen # explain a common policy denial
ft why FT-1001 # explain the error code an error message names
Attention console
ft attention ranks what needs an operator or agent next, without changing
anything. Without --input it reads live sources:
- the watcher’s operating envelope;
- policy denials and approval holds from the last 24 hours of the audit log;
- verified-submit profile drift;
- unhandled warning and critical detection events;
- operator pane holds;
- watcher crash bundles from the last day;
- a failed or compensating mission transaction.
Each item carries its reasons, a safe next action and a mute key. MCP
wa.attention with live: true reads the same database sources, but not the
watcher envelope, crash bundles or the transaction contract. The JSON contract is in
docs/robot-contracts/attention-router.md.
ft attention status # scored snapshot and source health
ft attention next # the highest-priority safe next action
ft attention explain # why the next item ranks first
ft robot attention next # the same, as a robot envelope
ft mute add # stop one item resurfacing (the key is in its summary)
Workflows
ft workflow list
ft workflow run handle_usage_limits --pane 0
ft workflow run handle_usage_limits --pane 0 --dry-run
ft workflow status -v
Security model: source-pane trust scope (ft-j0ufc). Workflows fire when a detection pattern matches a pane’s output. By default any pane may fire any workflow. That default is convenient when every pane is operated by the same trust principal and dangerous when a low-trust pane shares a runtime with a high-trust pane. Workflows that act on high-trust panes should declare an allowlist via Workflow::trigger_policy():
fn trigger_policy(&self) -> WorkflowTriggerPolicy {
WorkflowTriggerPolicy::allowlist([trusted_pane_id])
}
The runner enforces the allowlist before any lock, audit row, or engine state is created; refused triggers surface as WorkflowStartResult::SourcePaneNotTrusted and the originating source_pane_id is recorded on the workflow’s persisted trigger context for post-incident forensics. The default policy (allow_all()) preserves pre-ft-j0ufc behavior.
Mission & Tx control
ft mission plan # validate mission contract + compute hash
ft mission run # advance lifecycle into execution
ft mission status # lifecycle + assignment summary
ft mission explain # legal lifecycle transitions
ft mission pause # canonical lifecycle transitions
ft mission resume
ft mission abort
ft mission objective-plan --objective "" # read-only objective planner (ft-auy2g)
ft tx plan # validate tx contract + summarize lifecycle
ft tx run # prepare + commit, deterministically
ft tx run --fail-step tx-step:commit
ft tx rollback # compensation for committed steps
ft tx show --include-contract # receipts and full tx payload
The mission objective planner reads the requested objective and a caller-supplied capacity posture (--capacity-posture, default admit), ranks the candidate work, and prints a deterministic plan artifact. It does not query the operating envelope (ft swarm envelope does), and planning is side-effect-free: nothing is spawned, sent, or stored. See Operating Envelope below.
Rules
ft rules list # list detection rules
ft rules test "Usage limit reached" # test text against rules
ft rules show codex.usage.reached # show rule details
ft robot rules lint --fixtures --strict # validate the pack (naming + regex safety + fixture coverage)
Audit & approvals
ft approve AB12CD34 --dry-run # check approval status
ft audit --limit 50 --pane 3 # filter audit history
ft audit --decision deny # only denied decisions
Diagnostics
ft triage # summarize issues (health/crashes/events)
ft diag bundle --output /tmp/ft-diag # collect diagnostic bundle
ft reproduce export --kind crash # export latest crash bundle
ft doctor # environment health check
ft doctor --json # machine-readable diagnostics
ft proof-doctor --bead -- # check a proof command's RCH-required shape (does not run it)
Attestation
ft attestation verify docs/attestations/.json
ft attestation verify docs/attestations/.json --json
ft attestation verify docs/attestations/.json --strict-required
ft attestation show docs/attestations/.json
Bundled demo scenarios
ft demo is the side-effect-free onboarding and regression surface for the
bundled demo-lab fixtures. It validates the manifest-backed scenarios
(quickstart, usage_limit, and compaction) and reports retained artifact
links and follow-up simulation commands without sending input to live panes,
repairing Agent Mail, mutating RCH workers, or claiming production-capacity
proof.
ft demo # list available demos
ft demo quickstart # validate one demo scenario
ft demo quickstart --format json # machine-readable JSON
ft demo quickstart --format toon # machine-readable TOON
ft demo quickstart --manifest fixtures/demo-lab/manifest.v1.json
ft simulate validate fixtures/demo-lab/scenarios/quickstart.yaml --json
ft simulate run fixtures/demo-lab/scenarios/quickstart.yaml --speed 1
The retained artifacts live under fixtures/demo-lab/ and are indexed in
docs/demo-scenarios.md. They prove deterministic
fixture and CLI/simulation command contracts only; they do not prove remote
Cargo, target-class capacity, live-pane mutation, or production-scale behavior.
Web API (feature-gated)
Run ft web (the web feature is in default builds) to expose a local HTTP surface on 127.0.0.1:9999 by default. Builds before 2026-11 used port 8000. Set [tuning.web] default_port in ft.toml, or pass --port, to choose another.
ft web
curl http://127.0.0.1:9999/health
curl http://127.0.0.1:9999/panes
curl -N http://127.0.0.1:9999/stream/events
curl -N "http://127.0.0.1:9999/stream/deltas?pane_id=3&max_hz=50"
Streaming query parameters: pane_id filters to one pane; max_hz caps delivery rate for backpressure control; /stream/events also accepts channel=all|deltas|detections|signals. Streaming responses use schema ft.stream.v1, send keepalive comments when idle, emit lag frames when a slow client misses events, and redact secret material before emission.
/stream/events reads persisted detections from the database in ascending ID order. Standalone ft web also tails the watcher’s database every 250 ms to publish prompt wakeups; ft watch --web [--web-port N] receives wakeups directly from its watcher. Periodic storage reads repair missing wakeups in either mode, including when FT_WEB_STORAGE_TAIL=0 disables the standalone tail. The all and detections channels require event storage. The signals and deltas channels carry best-effort live bus traffic without durable resume cursors; /stream/deltas is the separate storage-backed output endpoint.
The first ready frame establishes an accepted durable checkpoint and includes its cursor in both data.cursor and the SSE id field. Each persisted detection then carries its own cursor. Browser EventSource reconnects send the most recently received value as Last-Event-ID; other clients can supply that exact value in the header or the cursor query parameter:
curl -N -H "Last-Event-ID: $CURSOR" \
"http://127.0.0.1:9999/stream/events?channel=detections&pane_id=7"
Treat these values as opaque tokens. Their versioned form is event-v1::all: or event-v1::pane::, where the epoch binds the cursor to the database’s retention history. Keep the same pane filter when resuming. Numeric legacy IDs and since_id bootstrap requests are rejected; begin a fresh subscription without a cursor to deliberately start at the current tail. A nonempty Last-Event-ID takes precedence over a URL cursor. Invalid tokens fail before streaming, and an expired cursor, changed database epoch, or unprovable retention interval produces an explicit discontinuity instead of silently resetting the position. Lifecycle, lag, and error frames do not overwrite the durable checkpoint. Delivery is at least once across reconnects; clients should deduplicate by cursor when necessary.
Browser fleet viewer (preview)
ft web --ui-dir (or FT_WEB_UI_DIR, or ft watch --web --web-ui-dir ) also serves a read-only fleet viewer at /ui/: a FrankenTUI model compiled to WebAssembly, painted by the FrankenTerm WebGPU renderer from frankentui. It lists the recorded panes, shows recent and live detections from /stream/events, and marks the stream live, connecting or offline with the age of its data. Keys: 1/2 switch views, j/k move, r refetches, and Tab leaves the viewer for the page’s buttons. It never writes to a pane.
RCH_CARGO_WRAPPER_BYPASS=1 scripts/build-browser-ui.sh /tmp/ft-ui # needs the wasm32 target and wasm-bindgen 0.2.128
ft web --ui-dir /tmp/ft-ui/site # then open http://127.0.0.1:9999/ui/
The build script fetches the renderer’s last source revision from the frankentui repository, checks the archive’s SHA-256, and builds it with the dependency lock vendored in crates/frankenterm-browser-ui/renderer.lock. The package’s manifest.json records every file’s SHA-256. At startup ft web reads exactly those files, checks each digest, and serves them from memory: a tampered or incomplete package stops startup, and no request path reaches the filesystem. The page carries a same-origin Content-Security-Policy. Browsers without WebGPU use the fleet viewer’s native text view. tests/e2e/test_browser_fleet_viewer.sh drives a real headless Chrome against a viewer fed by the headless capture-and-detect smoke.
To require local browser sign-in, set an environment variable to a randomly generated access token of 32–256 visible ASCII characters, then pass its name to either server entry point:
ft web --ui-dir /tmp/ft-ui/site --auth-token-env FT_BROWSER_TOKEN
ft watch --web --web-ui-dir /tmp/ft-ui/site --web-auth-token-env FT_BROWSER_TOKEN
The viewer checks /auth/status before starting any data requests. Sign-in exchanges the operator token for an opaque HttpOnly, SameSite=Strict cookie; the token is never placed in a URL or browser storage. Sessions expire after one hour, with at most 16 concurrent sessions. Sign-out revokes that session, stops its stream producers, and clears the viewer, pane output and history results. Restarting the server revokes all sessions. Each session has an independent nonsecret epoch that binds reads and stream reconnects to the original viewer; a changed session starts with a fresh model and cursor. Health, session status and UI assets stay public; data routes and OpenAPI require a valid session.
Authentication is opt-in. Without FT_WEB_HTTPS_ORIGIN, either token flag limits Host and Origin checks to the actual loopback listener address and port. Sessions stay bound to the exact origin used at sign-in.
For authenticated access from your other devices through Tailscale Serve, or another trusted HTTPS reverse proxy, set FT_WEB_HTTPS_ORIGIN to the browser’s exact canonical HTTPS origin. Use a lower-case hostname and omit a trailing slash, path, query, fragment, credentials and the default :443 port. A non-default HTTPS port is allowed. The setting requires the existing token flag; missing authentication or an invalid origin stops startup before the listener binds.
# FT_BROWSER_TOKEN contains your randomly generated 32–256 character access token.
# Replace this example origin with your machine's actual Tailscale HTTPS origin.
export FT_WEB_HTTPS_ORIGIN='https://this-machine.your-tailnet.ts.net'
ft web --ui-dir /tmp/ft-ui/site --auth-token-env FT_BROWSER_TOKEN &
tailscale serve --bg http://127.0.0.1:9999
tailscale serve status
# Open https://this-machine.your-tailnet.ts.net/ui/ and sign in.
tailscale serve --https=443 off # stop sharing
The same setting applies to ft watch --web --web-auth-token-env FT_BROWSER_TOKEN. In HTTPS mode the startup announcement names the browser origin and the internal HTTP proxy upstream. The listener remains loopback-only: the proxy must terminate HTTPS and preserve the original Host and Origin headers. Forwarded headers and Tailscale identity headers never establish application authority. Sign-in and sign-out cookies include Secure; sign-out and expiry retain the same live-stream revocation and session-epoch fencing as local mode. Use the configured HTTPS URL in this mode, because local HTTP aliases are refused.
This is one operator’s read-only session authority over the existing data routes, not per-user or per-pane sharing. Tailnet access rules control who can reach the sign-in page; the operator token is still required to read captured output, history and live streams. Omitting both token authentication and FT_WEB_HTTPS_ORIGIN preserves the unauthenticated local mode. Do not forward that mode when application sign-in is required, and do not use tailscale funnel to publish the viewer to the internet.
The backend socket tests exercise authenticated proxy requests and stream revocation; they do not establish live TLS/Tailscale or device qualification. The pinned HTTP substrate still collapses duplicate raw header lines and does not provide a cancellation deadline for a blocked socket write; those transport requirements remain part of ft-xxfwy.55.3. Live tailnet qualification, terminal attach, controller leases and DSR packaging remain open in the browser campaign.
ft web runs no capture pipeline of its own. Its storage tail follows newly persisted events rows written by the watcher and republishes wakeups on its in-process bus. Subscriptions always obtain detection content and ordering from storage, so a delayed or reordered wakeup cannot skip an earlier row. The tail starts after existing history; explicit subscription cursors control replay. Embedders that publish to the same bus in-process can disable the extra wakeup tail with WebServerConfig::with_storage_event_tail(false).
Session persistence
ft snapshot save # persist a bounded mux metadata projection
ft snapshot list # list recent snapshots
ft snapshot inspect # inspect snapshot contents
ft snapshot diff # compare pane-ID membership only
ft snapshot restore --dry-run # metadata-only descriptor/status report
ft session list --limit 50 --offset 0 # bounded page of saved sessions
ft session show --limit 50 --offset 0 # bounded checkpoint page
ft session doctor # health check for session persistence
ft session acknowledge-cleanup --force # resume retention after an interrupted cleanup attempt that doctor reports
ft session dump # private, checksummed live pane-content/topology export
ft session verify-dump # offline schema/checksum/private-file verification
ft session list-durable # discover continuously persisted cold-scrollback panes
ft session export-durable # read-only export of one 32-hex durable pane ID
ft session recover # export a complete orphan transcript; never write it to a PTY
ft session recover --allow-partial # explicitly retain a reported partial salvage
ft session discard --force # remove only the leased data leaf; retain its lock inode
ft watch # start the persistence/observation lifecycle; may prune retained data
ft session dump lists the currently visible mux panes, reads each through the
bounded read-only mux API, then lists the topology again. It redacts pane text
and metadata, records per-pane SHA-256 digests, and writes a mode-0600 JSON
envelope under
~/.local/share/ft/mux-dumps/ by default. It refuses to overwrite a path,
rejects symlinked path components, fsyncs both the artifact and its containing
directory, verifies the persisted handle, and returns failure for a pane-read
error or changed topology fingerprint unless --allow-partial is explicit.
ft session verify-dump revalidates the private regular-file shape,
schema, complete-publication marker, payload and artifact checksums, per-pane
text checksums and byte/line counts, aggregate limits, summary counters,
completeness, and the explicit non-restorable capability claims without
contacting a mux.
This is a pre-upgrade/crash-forensics safety artifact. It preserves observable
redacted text and bounded topology metadata. Pane text is captured sequentially,
not as one atomic point-in-time terminal snapshot; the schema says so explicitly.
It does not preserve live PTY file descriptors, process memory, shell/editor
internal state, terminal parser/render state, or running-agent continuity.
On mux servers, cold rows evicted from the hot terminal viewport are also persisted continuously under a stable pane UUID with checksummed styled-line records and crash-recoverable sequence authority. A rejected cold write retains the row in memory instead of silently dropping it. This protects scrollback, but it still does not make the current mux process replaceable: PTY and child ownership must move into the documented guardian before live upgrades can preserve running processes.
ft session list-durable validates and lists those per-pane manifests without
opening their content logs for write. ft session export-durable performs
a bounded, read-only snapshot of the committed log prefix, rejects checksum,
identity, sequence, privacy, replacement-race, and resource-limit failures,
decodes the styled rows with the bounded codec, reapplies current redaction,
and creates a new private synchronized transcript without overwriting a prior
artifact. A final torn record is reported and excluded because it was never
durability-acknowledged. This export is historical output, never PTY input, and
is not an executable process checkpoint.
ft session recover is intentionally export-only. Historical terminal output
is output, not shell input: recovery never creates or splits a live pane and
never sends archive bytes through a PTY input channel. It preserves the
header-declared source-completeness result and refuses to publish an incomplete
source or a transcript with skipped records unless --allow-partial is
explicit. An authorized partial artifact reports complete: false and the
finite terminal reason; it is never promoted to a complete recovery. ft session discard --force holds the same recovery lease through descriptor- and
identity-checked unlink plus parent-directory synchronization. It deliberately
retains the private lock inode so a competing writer cannot create a second
flock authority while the operation is retiring.
Note: list-orphans, recover, and discard operate on the flat per-pane
mmap scrollback files under ~/.local/share/ft/scrollback/. No production
capture path writes those files today (the per-pane mmap writer is reserved,
see config.rs), so on a normal install these commands find nothing. Durable
cold scrollback from the mux server is read with list-durable /
export-durable instead.
All three flat-mmap orphan commands accept the same explicit recovery envelope:
--max-directory-entries, --max-file-bytes, --max-records,
--max-replay-chunks, --max-payload-bytes, and
--max-transcript-bytes. Defaults stay conservative. Operators who configured
a larger valid writer capacity can opt in up to the finite hard ceilings rather
than having that file become impossible to inspect or discard. Invalid limits
and operational scan/read/write/discard failures remain bounded and redacted in
JSON/TOON output and exit with status 2.
ft snapshot restore --dry-run reads a bounded checkpoint descriptor and
prints a metadata-only descriptor/status report. It does not load a full restorable projection and
is not evidence that execution would succeed. Every non-dry snapshot restore,
on every platform, returns a finite unavailable diagnostic before database
resolution, process discovery, subprocess launch, or mux mutation. Robot
checkpoint rollback has the same boundary: dry-run planning only, with
non-dry execution returning robot.feature_not_available.
The executable layout restorer remains library/test substrate. That substrate can exercise a limited windows/tabs/splits/local-CWD projection and honor an explicit per-tab active-pane identifier when one is actually present, but the current pane-list-derived snapshot does not preserve durable tab order or a stable active-tab identity. It also does not establish mux-domain identity, workspace/window placement, historical scrollback, render state, process or agent continuity, titles, exact geometry, or full appearance.
ft restart execution is likewise deliberately unavailable: it fails closed
before locks, capture, process discovery, signals, spawning, or mux mutation
until one authenticated mux endpoint can be bound to an exact process
incarnation and verified relaunch receipt. The production ft watch startup
path runs the unclean-session detector and logs what it finds, but it does not
prompt or restore. Use snapshot/session commands for evidence inspection and
make any recovery changes manually.
The top-level [session] configuration table is entirely unsupported and is
rejected, including the retired session.restore_max_lines key. The retired
[snapshots.process_relaunch] table is also rejected; no production relaunch
or scrollback-replay setting exists.
Configuration
ft config show
ft config validate
ft config set
ft config export # TOML or JSON
For the full command matrix (human + robot + MCP), see docs/cli-reference.md. For the evidence model behind these support claims, see docs/ft-xbnl0-verification-contract.md. For GUI onboarding and WezTerm migration, see docs/frankenterm-gui-user-guide.md.
Robot Mode (JSON API)
The ft robot subcommand provides machine-optimized output for AI agents. Always use --format toon for token-efficient output when piping results to another AI.
Output formats
| Flag | Format | Use case |
|---|---|---|
--format json |
JSON | Default, easy parsing |
--format toon |
TOON | Lower-token AI-to-AI envelopes |
--stats |
Stats on stderr | Token-savings visibility |
Environment variables
| Variable | Purpose |
|---|---|
FT_OUTPUT_FORMAT |
Default format (json or toon) |
TOON_DEFAULT_FORMAT |
Fallback default format |
FT_WORKSPACE |
Workspace root directory |
FT_ROBOT_FAIL_ON_ERROR |
1 makes ft robot exit with status 1 when it printed an ok: false envelope (default: exit 0, the envelope is the result), so ft robot wait-for 0 Done && next stops on a timeout or refusal |
Precedence: CLI flag > FT_OUTPUT_FORMAT > TOON_DEFAULT_FORMAT > json
Implementation status
| Family | Actions | Status |
|---|---|---|
ft robot state |
current pane state | shipped |
ft robot get-text |
single / batch / all pane output | shipped |
ft robot send |
send text (with policy gate) | shipped |
ft robot wait-for |
pattern trigger | shipped |
ft robot search |
lexical / semantic / hybrid | shipped |
ft robot events |
recent detection events | shipped |
ft robot approve |
approve gated action | shipped |
ft robot agent-mail-outbox |
retained fallback outbox entries + replay state | shipped (read-only fixture/queued-entry surface; not live delivery proof) |
ft robot checkpoint |
save / list / show / delete / rollback | shipped for save/list/show/delete; rollback is metadata-only with --dry-run, while non-dry rollback fails closed until an authenticated, incarnation-pinned mux execution contract exists |
ft robot context |
status / rotate / history | shipped (native SQLite registry; rotation receipts are durable; raw context content is not stored) |
ft robot work |
claim / release / complete / list / ready / assign | shipped (native SQLite work_claims queue) |
ft robot fleet |
status / scale / rebalance / agents | shipped (live scale/rebalance plans, dry-run receipts, durable non-dry-run receipt replay, typed mutation/error receipts) |
ft robot profile |
list / show / validate / apply | shipped (read paths + dry-run apply + mux-backed non-dry-run apply with durable receipts) |
State & discovery
ft robot state # JSON
ft robot --format toon state # compact TOON
ft robot --format toon --stats state # with token stats on stderr
ft robot state --include-text --tail 20 # pane metadata + per-pane tail output
Response envelope:
{
"ok": true,
"data": [
{"pane_id": 0, "title": "claude-code", "domain": "local", "cwd": "/project"}
]
}
ft robot state serializes data as a bare PaneState array. The --include-text variant wraps the array in an object:
{
"ok": true,
"data": {
"panes": [{"pane_id": 0, "title": "claude-code", "domain": "local"}],
"tail_lines": 200,
"escapes_included": false,
"pane_text": { "0": "…tail…" }
}
}
Reading pane content
ft robot get-text 0 # recent output
ft robot get-text 0 --tail 50 # last N lines
ft robot get-text 0 --escapes # include escape sequences
ft robot get-text --panes 0,1,2 --tail 20 # batch
ft robot get-text --all --tail 10 # all active panes
Sending input
ft robot send 1 "/compact" # paste, then a typed Enter submits it
ft robot send 2 "make test" --no-paste # type the characters instead of pasting
ft robot send 1 "dangerous command" --dry-run # preview without executing
ft robot send 1 "y" --wait-for "confirmed" # send and wait for confirmation
ft robot send 1 "/compact" --verify-submit # return submitted-level SubmitReceipt
ft robot send 1 "/compact" --submit-level working # require working/output evidence
Pattern waiting
ft robot wait-for 0 "Usage limit" --timeout-secs 3600
ft robot wait-for 0 "Done" --timeout-secs 60
Deferred proof queue
ft proof queue --bead ft-w8 --kind test --package frankenterm-core -- RCH_REQUIRE_REMOTE=1 RCH_NO_SELF_HEALING=1 rch --no-self-healing exec -- env CARGO_TARGET_DIR=/tmp/ft-w8-target cargo test -p frankenterm-core --lib proof_intent
ft proof status --format json
ft proof replay --admission-state admitted --dry-run
ft robot proof status
The queue is a fail-closed proof-debt surface. Status and dry-run replay explain what would run; live replay refuses stale source hashes and never replaces a remote-required RCH proof with local Cargo.
Search
ft robot search "error: compilation failed"
ft robot search "rate limit" --pane 0
ft robot search "warning" --limit 5
ft robot search "compilation failed" --mode hybrid
Events
ft robot events --limit 10
ft robot events --pane 0
ft robot events --rule-id "codex.usage.reached" # exact rule id match
ft robot events --unhandled
Agent Mail outage outbox
ft robot agent-mail-outbox
ft robot --format toon agent-mail-outbox --entry fixtures/agent-mail-outage-spool/valid/agent-mail-unavailable.json
ft robot agent-mail-outbox reads retained fallback outbox fixtures and
additional queued-entry JSON files. It is for outage review and replay
planning, not live service repair: queued entries, dry-run-ok rows, and fixture
replay logs are not Agent Mail delivery proof until a replay receipt records a
delivered message id. The command is read-only and never restarts, repairs, or
reconstructs the shared Agent Mail service.
Profile management (ft-hac7w)
The ft robot profile family is the ship-first proof of the robot-contract methodology (BR-RC-ROBOT-CONTRACT.1). Its contract doctrine (idempotency rules, failure semantics, side-effect surface, concurrency contract) is the canonical example for every other robot family. See docs/robot-contracts/profile.md.
ft robot profile list
ft robot profile list --role agent
ft robot profile list --tag claude-code
ft robot profile show codex_ws
ft robot profile apply codex_ws --count 3
ft robot profile apply codex_ws --count 3 --dry-run
ft robot profile validate codex_ws
ft robot profile create codex_ws --role agent --command codex --cwd . \
--tag codex --env OPENAI_LOG=warn --bootstrap "/status" # persist a profile so apply can spawn it
Profiles live in the agent_profiles table and are created with ft robot profile create (nothing else defines them; the name must be unique).
Family contract:
| Action | Idempotency | Failure semantics | Side effects |
|---|---|---|---|
list |
Idempotent | MustNotPartiallyMutate | read-only |
show |
Idempotent | MustNotPartiallyMutate | read-only |
apply |
Receipt-based replay for the same request | Live compensation can fail; inspect rollback and per-pane effects | tables: agent_profiles; mux: spawns count panes |
validate |
Idempotent | MustNotPartiallyMutate | read-only |
create |
Not idempotent: a repeated name fails with robot.profile.already_exists and changes nothing |
MustNotPartiallyMutate | tables: agent_profiles (one row) |
Concurrency: the model’s intended contract is serialization per profile name. Live requests also share mux capacity and mutation state; cross-process serialization, retries, and compensation require their own proof. A saved idempotency receipt does not make arbitrary concurrent external effects atomic.
$ ft robot --format json profile apply codex_ws --count 3
{
"ok": true,
"data": {
"profile_name": "codex_ws",
"panes_spawned": [10, 11, 12],
"dry_run": false,
"requested_agents": 3,
"spawned_agents": 3,
"skipped_existing_agents": 0,
"idempotency_key": "",
"mutation_idempotency_key": "",
"rollback_status": "succeeded",
"idempotent_replay": false,
"mutation_receipt": { "...": "full fleet mutation receipt" }
},
"elapsed_ms": 37
}
Error handling
Robot mode returns structured errors using the flat envelope shape (error, error_code, and hint are sibling top-level fields, not nested):
{
"ok": false,
"error": "Pane 99 not found",
"error_code": "robot.pane_not_found",
"hint": "Use 'ft robot state' to list available panes",
"elapsed_ms": 1,
"version": "0.2.0",
"now": 1747371700000,
"schema_version": 1
}
Error codes include robot.pane_not_found, robot.timeout, robot.wezterm_not_running, robot.mux_version_skew (the CLI and the running FrankenTerm.app are from different releases; the hint names both codec generations), robot.policy_denied, robot.require_approval, robot.storage_error, robot.feature_not_available, robot.fleet.inventory_unavailable, robot.profile.spawn_failed, and the full robot.fleet.* typed envelope family.
MCP (Model Context Protocol)
cargo build --profile release-interactive --features mcp
ft mcp serve # MCP server over stdio
MCP covers a subset of Robot Mode (plus MCP-only mission lifecycle and steer-plan tools); docs/robot-contracts/mcp-robot-surface-matrix.md lists which families are mirrored, partial, or robot-only. See docs/mcp-api-spec.md for the tool list and docs/json-schema/ for response schemas.
Configuration
Configuration is discovered in canonical precedence order:
- Explicit
--configCLI option - Workspace-local configuration via
FT_WORKSPACE($FT_WORKSPACE/.ft/config.toml,$FT_WORKSPACE/.ft/ft.toml, or$FT_WORKSPACE/ft.toml) - Current working directory (
./.ft/config.toml,./.ft/ft.toml, or./ft.toml) - Platform default configuration (
~/Library/Application Support/ft/ft.tomlon macOS; elsewhere, Windows included,$XDG_CONFIG_HOME/ft/ft.tomlor else~/.config/ft/ft.tomlunder the home directory)
[general]
log_level = "info" # trace, debug, info, warn, error
log_format = "pretty" # pretty (human) or json (machine)
data_dir = "~/.local/share/ft"
[ingest]
poll_interval_ms = 200
[ingest.panes]
include = []
[[ingest.panes.exclude]]
id = "exclude_htop"
title = "htop"
[[ingest.panes.exclude]]
id = "exclude_vim"
title = "vim"
[ingest.priorities]
default_priority = 100
[[ingest.priorities.rules]]
id = "critical_codex"
priority = 10
title = "codex"
[ingest.budgets]
max_captures_per_sec = 0 # 0 = unlimited
max_bytes_per_sec = 0
[storage]
writer_queue_size = 100
retention_days = 30
[gc]
enabled = true
interval_seconds = 3600
vacuum_threshold = 0.20 # Advise explicit VACUUM when >20% pages are free
log_report = true
[vendored]
mux_socket_path = "~/.local/share/wezterm/default.sock"
[vendored.mux_pool]
max_connections = 64
idle_timeout_seconds = 60
acquire_timeout_seconds = 10
pipeline_depth = 32
pipeline_timeout_ms = 5000
max_frame_bytes = 4194304
max_outbound_codec_bytes = 1073741824
max_outbound_in_flight_requests = 256
compression = "auto"
[vendored.sharding]
enabled = false
socket_paths = ["/tmp/ft-shard-0.sock", "/tmp/ft-shard-1.sock"]
assignment = { strategy = "round_robin" }
[backup.scheduled]
enabled = false
schedule = "daily" # hourly, daily, weekly, or 5-field cron
retention_days = 30
max_backups = 10
destination = "~/.local/share/ft/backups"
[patterns]
packs = ["builtin:core"] # Claude Code, Codex, Gemini, terminal runtime events
[workflows]
enabled = ["handle_compaction"] # empty = all built-in workflows
max_concurrent = 10
[safety]
require_prompt_active = true # needs OSC 133 prompt markers in the pane's shell: run `ft setup shell` (bash/zsh/fish, idempotent)
block_alt_screen = true
rate_limit_per_pane = 30
rate_limit_global = 100
[safety.redaction]
enabled = true # T1/T2/T3 sensitivity tiers
[agent_detection]
enabled = true
active_output_threshold_ms = 5000 # Output within 5s → Active (green)
thinking_silence_ms = 5000 # Input sent, no output for 5s → Thinking (yellow)
stuck_silence_ms = 30000 # No output for 30s after input → Stuck (red)
idle_silence_ms = 60000 # No activity for 60s → Idle (gray)
Operator-tunable runtime constants live under [tuning] sections such as [tuning.runtime], [tuning.patterns], and [tuning.search]. See docs/tuning-reference.md for every key, default, unit, validation guard, and provisional starting ranges for 10-pane, 50-pane, and 200±pane benchmark workloads. Those ranges are not target-class certification.
Environment variables
| Variable | Purpose |
|---|---|
FT_OUTPUT_FORMAT |
Default format (json or toon) |
TOON_DEFAULT_FORMAT |
Fallback default format |
FT_WORKSPACE |
Workspace root directory |
FT_SKIP_BUNDLED_FONT_INSTALL |
Skip automatic font install |
Architecture
┌───────────────────────────────────────────────────────────────────────┐
│ ft Swarm Runtime Core │
│ Session Graph │ Pane Registry │ State Store │ Control Plane │
│ Mission Orchestrator │ Fleet Memory Controller │ Tx Engine │
│ Operating-Envelope Planner │ Mission Objective Planner │
└───────────────────────────────────────────────────────────────────────┘
│
asupersync runtime (Cx-first cancellation contract)
▼
┌───────────────────────────────────────────────────────────────────────┐
│ Ingest + Normalization Pipeline │
│ Discovery → Delta Extraction → Fingerprinting → Observation Filter │
│ SIMD Scan → Pattern Trigger (AC + Bloom) → zstd Compression │
└───────────────────────────────────────────────────────────────────────┘
│
▼
┌───────────────────────────────────────────────────────────────────────┐
│ Storage Layer (SQLite + FTS5 + embeddings) │
│ output_segments │ events │ workflow_executions │ audit_actions │
│ approval_tokens │ session_checkpoints │ mux_pane_state │
│ policy_denied_audit (v24+) │ work_claims │ profiles_applied_log │
└───────────────────────────────────────────────────────────────────────┘
│
┌──────────────┼──────────────┐
▼ ▼ ▼
┌───────────┐ ┌───────────┐ ┌───────────┐
│ Pattern │ │ Event │ │ Workflow │
│ Engine │ │ Bus │ │ Engine │
│ (detect) │ │ (fanout) │ │ (execute) │
└───────────┘ └───────────┘ └───────────┘
│ │ │
└──────────────┼──────────────┘
▼
┌───────────────────────────────────────────────────────────────────────┐
│ Policy Engine (14 health checks) │
│ Capability Gates │ Rate Limiting │ Audit Trail │ Approval Tokens │
│ Secret Redaction (T1/T2/T3) │ Backpressure Tiers │ Circuit Breakers │
│ Source-Pane Trust Scope (ft-j0ufc) │
└───────────────────────────────────────────────────────────────────────┘
│
┌──────────────┼──────────────┐
▼ ▼ ▼
┌──────────────────────┐ ┌──────────────┐ ┌───────────────────────┐
│ Robot Mode API │ │ MCP Server │ │ Distributed Streamer │
│ JSON / TOON │ │ (stdio) │ │ (wire protocol v1) │
└──────────────────────┘ └──────────────┘ └───────────────────────┘
│
▼
┌───────────────────────────────────────────────────────────────────────┐
│ Attestation & Incident Plumbing │
│ Sigstore-signed bundles │ Live crash + incident-bundle collectors │
│ Beads coordination snapshot │ Reality-check drumbeat │
└───────────────────────────────────────────────────────────────────────┘
Workspace Structure
frankenterm/ # 97 workspace members (auto-stamped)
├── Cargo.toml
├── crates/
│ ├── frankenterm/ # CLI binary (ft)
│ ├── frankenterm-core/ # Core library — 540 top-level modules, 1421634 LOC
│ │ ├── src/
│ │ │ ├── runtime.rs # Observation runtime orchestration
│ │ │ ├── runtime_async.rs # Canonical asupersync wrapper API surface
│ │ │ ├── ingest.rs # Pane discovery + delta extraction
│ │ │ ├── patterns.rs # Pattern detection engine
│ │ │ ├── events.rs # Event bus and detection fanout
│ │ │ ├── storage/ # SQLite + FTS5 (schema version: see storage/schema_ddl.rs::SCHEMA_VERSION)
│ │ │ ├── policy.rs # Safety / access control
│ │ │ ├── redactor.rs # Secret redaction (T1/T2/T3 tiers)
│ │ │ ├── plan.rs # Mission + Tx types
│ │ │ ├── workflows/ # Workflow engine + handlers + lock
│ │ │ ├── search/ # Lexical / semantic / hybrid + daemon
│ │ │ ├── connector_*.rs # Connector fabric (14 modules)
│ │ │ ├── scrollback_tiers.rs # Three-tier scrollback storage
│ │ │ ├── simd_scan.rs # Newline + ANSI density metrics (BOCPD features)
│ │ │ ├── wire_protocol.rs # Distributed messaging
│ │ │ ├── operating_envelope.rs # ft.operating_envelope.v1 planner
│ │ │ ├── incident_bundle.rs # Live incident-bundle collectors
│ │ │ ├── mission_objective_plan.rs # Capacity-aware objective planner
│ │ │ └── … # 500+ additional modules
│ │ ├── tests/ # 1051 Rust test files, 64657+ test annotations
│ │ └── benches/ # 119 Criterion bench files
│ │
│ ├── frankenterm-core-ars/ # ARS (Adaptive/Autonomous Reflex System)
│ ├── frankenterm-core-tantivy/ # Lexical search stack
│ ├── frankenterm-core-replay/ # Replay subsystem
│ ├── frankenterm-core-fleet/ # Fleet dashboard
│ ├── frankenterm-core-connectors/ # Connector boundary
│ ├── frankenterm-core-mcp/ # MCP type boundary
│ ├── frankenterm-core-test-macros/ # #[lab_runtime_test] proc macros
│ │
│ │ # ── 12 leaf type crates (no first-party deps but one) ──
│ ├── frankenterm-core-resource-types/
│ ├── frankenterm-core-error-types/
│ ├── frankenterm-core-config-types/
│ ├── frankenterm-core-policy-types/
│ ├── frankenterm-core-replay-types/
│ ├── frankenterm-core-telemetry-types/
│ ├── frankenterm-core-cass-types/
│ ├── frankenterm-core-caut-types/
│ ├── frankenterm-core-connector-types/
│ ├── frankenterm-core-audit-types/
│ ├── frankenterm-core-atlas-pack-types/
│ ├── frankenterm-core-x11-resize-types/
│ │
│ ├── frankenterm-flight-recorder/ # Bounded cross-layer interaction tracing
│ ├── frankenterm-gui/ # GUI binary crate (FrankenTerm.app; OpenGL default, opt-in Native Metal)
│ ├── frankenterm-renderer-metal/ # Native Apple Silicon Metal renderer (opt-in: `front_end = "Metal"`)
│ ├── frankenterm-mux-server/ # Headless mux server binary
│ ├── frankenterm-mux-server-impl/ # Shared mux-server implementation
│ ├── frankenterm-pty-guardian/ # Crash-resilient PTY guardian & lease holder
│ ├── frankenterm-browser-ui/ # Browser FrankenTerm WASM fleet viewer/terminal UI
│ ├── frankenterm-terminal-wire/ # Binary wire protocol for browser/remote terminal streaming
│ ├── frankenterm-machines/ # Host/machine inventory & air-gapped workspace model
│ ├── frankenterm-mobile-attach/ # Native iOS / mobile SSH+mux attach substrate
│ ├── frankenterm-mobile-mux/ # Mobile mux client bridge (`ft mobile`)
│ ├── frankenterm-redactor/ # Shared secret redactor library
│ ├── frankenterm-sigpipe/ # Recoverable panic & SIGPIPE quarantine contract
│ ├── frankenterm-build-identity/ # Build/commit/generation provenance stamps
│ ├── frankenterm-alloc/ # Allocator + telemetry support (jemalloc)
│ ├── frankenterm-topo/ # Workspace topology + cycle detection
│ ├── ft-perf-gate/ # Statistical regression gating (SPRT, conformal, KL)
│ └── ft-test-log/ # Centralized test-logging convention
├── apps/ # Native Apple companion surfaces
│ ├── ios/ # Native iOS FrankenTerm app (SwiftUI, App Store approved 1.0)
│ ├── apple/ # Shared Swift `FrankenTermKit` (`FTAG`/`FTQR1` encrypted QR + HPKE)
│ └── macos/FrankenTermExport/ # Notarized Mac companion exporter (`FrankenTerm-Exporter.dmg`)
├── lints/ # Custom compiler lints (`cx_propagation/`, `cache_gpu_handle/`)
├── frankenterm/ # In-tree vendored FrankenTerm crates (ex-WezTerm; see `Cargo.toml` workspace members)
│ ├── codec/ config/ mux/ pty/ term/ termwiz/ ssh/ scripting/
│ ├── font/ window/ client/ surface/ …
│ ├── deps-freetype/ deps-harfbuzz/ deps-fontconfig/
│ ├── env-bootstrap/ tabout/ gui-subcommands/ toast-notification/ open-url/
│ └── lua-api-crates/{termwiz-funcs,mux-lua,url-funcs}/
├── fuzz/ # 52 fuzz targets
├── docs/ # 549 Markdown documentation files
├── tests/e2e/ # 305 shell E2E scripts
└── fixtures/ # Test fixtures (including operating-envelope goldens)
Sub-crate extraction invariants
- Leaf type crates (
*-types) declare no first-party dependencies, with one exception:frankenterm-core-audit-typesdepends onfrankenterm-core-replay-types. - Cluster sub-crates (
*-ars,*-tantivy,*-replay,*-fleet) depend onfrankenterm-coreand, where needed, shared leaf types. - Core imports shared leaves, including the feature-gated MCP type crate. The connector boundary imports connector types, not core.
- Normal/build dependency cycles are forbidden. Dev-dependency cycles let core tests exercise the extracted clusters.
- See
docs/proposals/ft-l3tfo-cold-build-measurements.mdfor the cold-build ADR.
Key algorithms and techniques
| Subsystem | Algorithm / technique | Purpose |
|---|---|---|
| Delta extraction | Bounded 1 MiB overlap matching with gap semantics | Efficient incremental capture without persisting full-buffer re-reads |
| Pattern detection | Aho-Corasick multi-pattern + anchor filtering + Bloom prefilter | Fast multi-agent pattern matching with probabilistic pre-rejection |
| Search | FTS5 lexical + hash-embedding semantic lane | Lexical, semantic, and hybrid modes via RRF fusion |
| Change-point detection | BOCPD (Bayesian Online Change-Point Detection) | Catch novel failure modes regex patterns miss |
| Backpressure | Four-tier model (Green/Yellow/Red/Black) with queue-depth gauges | Prevent OOM and cascading latency under load |
| Fleet memory | Worst-of tier synthesis with asymmetric hysteresis | Coordinated fleet-wide pressure response; 200-pane qualification remains pending |
| Scrollback | Hot (RAM) → Warm (zstd compressed) → Cold (evicted) tiering | Memory-efficient scrollback for large pane counts |
| Tx execution | Prepare/commit/compensate with idempotency ledger | Safe multi-pane transactional operations |
| Operating envelope | Side-effect-free planner over RCH + network + process pressure | Refuse admission when telemetry missing / critical |
| Mission objectives | Capacity-aware planner with golden corpus harness | Safe swarm orchestration under operating-envelope constraints |
| Retry | Exponential backoff with jitter + circuit breaker integration | Robust I/O error handling without retry storms |
| Latency analysis | Min-plus algebra (network calculus) + Lindley equation | Formal worst-case delay and backlog bounds |
| Graph analysis | Dijkstra + Bellman-Ford + Floyd-Warshall | Agent routing and dependency chain analysis |
| Decision replay | Normalized DAG + causal edges + diff engine | Post-incident forensics and regression testing |
| Content dedup | SHA-256 content hashing + FNV-1a fast hash + XOR filter | Prevent duplicate indexing in search pipeline |
| Quiescence detection | Composable gauge + activity tracker with atomic CAS | Wait for system to settle before taking action |
Data flow
- Discovery — enumerate pane/session resources via active backend adapters
- Capture — stream output and state deltas from adapters / runtime hooks
- Delta — compare with the previous capture using the bounded 1 MiB overlap window
- Store — append new segments to SQLite with FTS5 indexing
- Detect — run pattern engine (anchored + Bloom-prefiltered + BOCPD) against new content
- Event — broadcast detections to event bus subscribers
- Admit — operating-envelope planner decides whether new pane/workflow work is safe
- Workflow — execute registered workflows on matching events (with trigger-policy allowlists)
- Policy — gate all actions through capability and rate-limit checks
- API — expose everything via Robot Mode JSON, MCP, web/SSE, and distributed streamer
System Components and Responsibilities
ft is composed of cleanly-separated subsystems. Each owns a specific responsibility surface; cross-subsystem communication goes through typed event-bus messages, the policy gate, or the storage layer, never direct mutation.
| Component | Owns | Talks to | Doesn’t do |
|---|---|---|---|
Ingest pipeline (ingest.rs) |
Pane discovery, delta extraction, gap detection, overlap matching | Storage (write), Event bus (deltas) | Pattern detection, policy decisions, sending input |
Pattern engine (patterns.rs) |
Rule packs, Bloom prefilter, anchor evaluation, regex execution, BOCPD | Event bus (detections), Storage (read-only) | Sending input, mutating panes |
Event bus (events.rs) |
Bounded broadcast of typed events, fanout to subscribers, backpressure | All subscribers | Persistence (subscribers persist if needed) |
Storage (storage/) |
SQLite schema + migrations, FTS5 indexing, single-writer lock, page-stat advisories + explicit VACUUM, backup/restore | All readers | Pattern matching, workflow execution |
Search (search/) |
Lexical (FTS5), semantic (embeddings), hybrid (RRF fusion), index daemon | Storage (read), embedder daemon | Pattern matching, workflow execution |
Policy engine (policy.rs) |
Capability gates, rate limits, approval tokens, audit trail writes, secret redaction | Storage (audit writes), Event bus (denials) | Direct pane I/O |
Workflow engine (workflows/) |
Engine + runner + lock + handlers + trigger-policy allowlists | Event bus (subscribe to triggers), Policy gate, Pane I/O | Pattern detection |
Mission engine (plan.rs, mission_objective_plan.rs, mcp_missions.rs) |
Mission contracts, lifecycle state machine, dispatch, objective planner | Policy gate, Workflow engine, Storage | Pane discovery |
Tx engine (plan.rs::TxReceipt + prepared_plans table + workflow_action_plans table) |
Prepare/commit/compensate, idempotency ledger, kill switches | Mission engine, Policy gate, Storage | Pattern detection |
Operating envelope (operating_envelope.rs) |
Admission decisions, fail-closed verdicts, telemetry composition | Mission engine (consumer), Diagnostics | Spawning panes, sending input |
Connector fabric (connector_*.rs) |
Inbound/outbound bridges, mesh routing, capability envelopes, host runtime | Event bus, Policy gate, External systems | Storage management, pane I/O |
Robot/MCP surface (robot_*.rs, mcp*.rs) |
JSON/TOON envelope contracts, MCP tool registration, request routing | All read+action subsystems through their public APIs | Direct storage I/O |
Distributed streamer (wire_protocol.rs, distributed.rs) |
Versioned envelopes, per-agent dedup, stale-session pruning, TLS | Storage (write-through for remote panes), Event bus | Local pane discovery |
GUI (frankenterm-gui) |
Window/font/render-state, BSU/ESU drain, classified drag handlers, command palette | Storage (read), Event bus, Scripting | Pattern detection, policy |
Mux server (frankenterm-mux-server) |
Headless mux, federation, command transport, durable state checkpoints | PTY layer, codec layer | Pattern detection, policy |
Attestation (CLI + scripts/attestation-verify.sh) |
Bundle verification, Sigstore signature checks, manifest hash recomputation | Filesystem (read-only) | Anything mutating |
Sub-crate boundaries explained
| Sub-crate | What lives there | Why it’s separated |
|---|---|---|
frankenterm-core-ars |
Adaptive/Autonomous Reflex System (15 modules) — drift detection, evidence ledger, blast radius, regime analysis | Heavy ML/statistics surface that shouldn’t be in everyone’s compile graph |
frankenterm-core-tantivy |
Full Tantivy lexical search stack (~16k LOC) | Tantivy is a heavy dep; sub-crating it lets frankenterm-core test paths skip it |
frankenterm-core-replay |
Replay + replay-assessment harness (~40k LOC) | Determinism testing has its own dep set (proptest, criterion) |
frankenterm-core-fleet |
Fleet dashboard | Will host multi-host coordination; partial extraction in progress |
frankenterm-core-connectors |
Connector type boundary | Reuses connector types without importing the core runtime |
frankenterm-core-mcp |
MCP type boundary | MCP integration is feature-gated; types live in their own crate so consumers can depend on schemas without dragging in the server |
frankenterm-core-test-macros |
#[lab_runtime_test] proc macros |
Proc-macros must live in their own crate by Cargo decree |
frankenterm-core-*-types (12 leaves) |
Data-only types (errors, configs, telemetry, audit, etc.) | Zero first-party deps; importable from anywhere without cycles |
Dependency rules (enforced by the build, not just by convention)
- Core imports shared type crates. The normal dependency direction for extracted implementation clusters is cluster → core; core’s dev-dependencies can exercise those clusters in tests.
- Leaf type crates declare no first-party deps. They depend only on external libs (serde, etc.), except that
frankenterm-core-audit-typesusesfrankenterm-core-replay-types. - Implementation clusters depend on core and shared leaves. MCP and connector type boundaries have narrower dependency graphs; the
frankenterm-core-*prefix alone does not identify a cluster. tokioban at thecargo-denylayer fails the build if any first-partyCargo.tomldeclarestokiodirectly.- Cycle detection runs in the release gate (
scripts/release-gates.sh, DSR quality) viacargo-deny+ the workspace-topology crate (frankenterm-topo).
Practical consequence: distinguish data-only leaves from implementation clusters when following imports. The Cargo manifests identify the actual normal, optional, and dev-dependency edges.
Operating Envelope
The operating envelope contract is the system’s answer to “is it safe to do more work right now?”
Contract: ft.operating_envelope.v1 (see docs/robot-contracts/operating-envelope.md and the JSON schema at docs/json-schema/ft-operating-envelope.json).
Inputs (each fails closed when missing):
- RCH (remote compilation helper) cluster pressure
- System network pressure (recently fail-closed when telemetry source is missing)
- Process snapshots (recently fail-closed)
- Fleet memory pressure tier (from the worst-of synthesis described in §7 of Design Philosophy)
- SQLite write queue depth + GC budget
Outputs:
- An admission verdict per (pane class, count) pair
- A typed envelope status object for the operator runbook (
ft.operating_envelope.v1) - A side-effect-free plan that the mission objective planner consumes
Failure semantics (reason codes from operating_envelope.rs):
- Missing or stale telemetry → reason
telemetry.stale/capacity.stale; the planner denies admission rather than guessing - Critical pressure on any input → reasons
capacity.red(critical) orcapacity.black(emergency); planner emitsenvelope.shed(andcapacity.pressure_shed) - Target-class artifact missing or
skipped_not_proven→ reasoncapacity.target_class_unproven; high-scale claims are held back - All required sources healthy → reason
envelope.all_required_sources_available; verdict isenvelope.admitwith the admitted (pane class, count) tuple - Tier classification flows through
capacity.greenfor headroom-available healthy state
This is the surface that protects swarms from accidentally being driven outside their proven operating range. See docs/operator-runbook.md for the operator-facing recovery procedures (ft-booek.6).
Mission Objective Planner
ft mission objective-plan --objective "" \
--strictness {advisory|normal|strict} \
--capacity-posture {admit|defer|pause|unknown} \
--target-bead # optional Beads candidate
--owned-path [,...] # for dirty-overlap checks
--dirty-path [,...] # caller-observed dirty state
ft mission objective-plan invokes the capacity-aware mission objective planner (ft-auy2g). Inputs and behavior:
- Takes a free-text
--objectivestring (operator’s stated goal). No JSON contract is required. - Takes the capacity posture from the caller (
--capacity-posture, defaultadmit) together with the supplied scope (owned paths, candidate bead, dirty paths). It does not query the operating envelope; runft swarm envelopefor the live verdict and pass the posture it implies. - Builds a read-only plan, ranking a candidate as ready work when a
--target-beadis supplied or--candidate-id/--candidate-titledescribe one. - Prints a deterministic plan artifact (golden-fixture-comparable). Nothing is persisted; keep the output if you need a record.
The planner is side-effect-free: objective-plan never spawns panes or sends input, and --execute is rejected. Execution is a separate ft mission run step (which operates on a mission contract file at .ft/mission/active.json by default, see Sample Mission and Tx Contracts); today it advances the mission lifecycle only and does not dispatch into panes (ft-majms, ft-xxfwy.48).
Incident Bundles
When something goes wrong (a crash, a stuck pane, a fleet-wide degradation), ft packages what it knows into an incident bundle. ft reproduce export runs as its own process, so sources that only a running watcher publishes (tailer health, resource pressure, live robot state) are recorded as unavailable rather than invented.
Collected today:
- Recent events (last 50)
- Pane/mux state from stored pane rows (not a live mux query)
- SQLite metadata (journal mode, size, schema version, row counts)
- Redacted config, git status, and the latest crash report
- Audit-trail tail: recent policy decisions and results from
audit_actions(no free-text summaries) - Process tree: a bounded, redacted
pssnapshot when you pass--process-sample - Beads coordination snapshot from
.beads/issues.jsonl(ft-tkkqx)
Not yet on the production path: GPU state, render-state snapshots, SynchronizedOutput (BSU/ESU) drain telemetry, and WAL checkpoint detail.
Producer side: the swarm wire protocol carries publish-side bundle source notifications (ft-9sy9e family) so distributed incidents include each participating agent’s local view.
Consumer side: ft reproduce export --kind crash --out DIR exports the latest crash bundle for external forensic tools; ft robot incidents autopsy compiles a redacted post-mortem from a flight-recorder source set.
Replay side: ft robot incidents list/show/explain/replay reads persisted
flight-recorder source sets and classifies proof evidence without mutating
panes, Beads, RCH, Agent Mail, or git. Use
docs/operator-runbook.md#2d-flight-recorder-incident-replay-runbook
for source failures, RCH infrastructure blocks, dirty-tree contamination,
policy denials, communication outages, operator cancellations, and
proof-incomplete closeouts.
Substrate Audit Discipline
The codebase is swept by family rather than by spot. Each family is a defect class with a known pattern; the discipline is that every audit closes every member of the family it touches.
| Family | What it looks like | Example fixes |
|---|---|---|
| Public-field bypass | pub struct field lets callers bypass clamping, NaN-rejection, or invariants |
ErasureShard, CircuitBreaker::Config, QuantileBudgetMs, ArrivalCurve/ServiceCurve, ApprovalScope, ScaleFactor, AxisValue |
Rubber-stamp is_safe() |
Release-gate is_safe() returns true on cold start or before any measurement is recorded |
display_pipeline_ci_matrix (CRITICAL release-gate forgery), gpu_regression_fuzz_report, redactor_coverage_matrix, iterm2_osc_1337, 7 cold-start doctor snapshots, others |
| Sanitization gap | Input sanitizer accepts DEL / C1 / argv-flag injection / path traversal | restore_process (DEL + C1 + CSI), kitty_graphics_alt_text (HIGH bypass), browser::sanitize_path_component, cass argv flag injection |
| NaN / unbounded input | Float input not validated against NaN / NEG_INFINITY / unbounded ranges |
chaos, recorder_replay::ReplayConfig, VirtualClock, bench_stats::empirical_bernstein_ci, disk_pressure::EwmaEstimator |
| Privacy bypass | Optional redaction field can be skipped via direct access | scrollback_cold_tier::ChunkMetadata.redaction, incident_bundle::truncate_file_content, truncate_excerpt |
| Redactor coverage | Token family not in the redactor pattern set | Added JWT, GitLab, Twilio, SendGrid, Datadog patterns |
| State-machine defects | Transitions accept impossible / inconsistent input | pane_groups, triple_buffer_watchdog, sync_output_watchdog, frame_budget::SustainedBurstHarness |
| Docstring overpromise | Docstring claims behavior the implementation doesn’t honor | OSC 52 docstring honesty (ft-uea9o) |
See docs/audit-checklist.md for the per-substrate audit checklist and the bead-keyed exemplars.
Deep Dive: Bayesian Regime Detection (BOCPD)
Regex patterns catch known failure modes. But what about novel failures that nobody wrote a pattern for? ft includes a Bayesian Online Change-Point Detection (BOCPD) engine that detects statistical regime changes in pane output:
- Infinite loops producing repetitive output at unusual cadence
- Output quality degradation (token ratio shifts, response length changes)
- Novel failure modes that don’t match any existing pattern
- Subtle behavioral drift over multi-hour agent sessions
The BOCPD module maintains a posterior distribution over possible “run lengths” (how long the current regime has lasted). When the posterior probability of a regime change exceeds a configurable threshold, a change-point event is emitted. This triggers a context snapshot that captures the execution environment (CWD, env vars, process info, shell state) at microsecond precision.
The workspace also carries ARS (Autonomous Reflex System) modules in frankenterm-core-ars for drift detection, evidence ledgers, blast-radius estimation, secret scanning, and compile-time regime analysis. They are implemented and tested but not wired into any live path yet: no production code consults them, so they scan, intercept, and gate nothing today (ft-7p0qz).
Deep Dive: Probabilistic Data Structures
Several subsystems use space-efficient probabilistic data structures to avoid costly exact lookups:
Bloom Filter (Pattern Engine). Before evaluating regex patterns against captured text, the pattern engine checks a Bloom filter seeded with the anchor strings from each rule. If the Bloom filter rejects, the text cannot possibly match, and the full regex evaluation is skipped. This reduces CPU cost by 10–100× for rule packs with dozens of patterns, since most text chunks match zero rules.
XOR Filter (Search Dedup). The search indexing pipeline uses XOR filters for space-efficient content-hash membership testing. An XOR filter uses approximately 1.23 * n * fingerprint_bytes to represent a set of n items, which is more compact than Bloom filters at equivalent false-positive rates. XOR filters are static (built once from a known set), and that fits the dedup use case where the known-hash set changes infrequently.
FNV-1a Hash (Fast Content Fingerprinting). For real-time dedup decisions where SHA-256 is too expensive, the pipeline uses FNV-1a (64-bit, non-cryptographic) as a fast fingerprint. FNV-1a processes one byte per cycle and is deterministic across platforms.
Deep Dive: Session Persistence and Restore
The session-restoration library/test substrate can identify sessions that did
not shut down cleanly (shutdown_clean = 0), load a checkpoint, and exercise a
restore state machine:
Database → SessionCandidate → RestoreDecision → LayoutRestorer → RestoreSummary
Production ft watch startup runs that detector and logs its result; it does
not prompt for or execute a restore. The human snapshot-restore and
robot-rollback commands provide bounded metadata-only dry-runs; all non-dry
execution is unavailable.
The checkpoint schema can record:
- A deterministic topology snapshot derived from numeric window/tab/pane IDs; schema v1 does not preserve user tab order or stable active-tab identity
- Per-pane terminal metadata such as dimensions, cursor position, title, and alt-screen flag, plus CWD when supplied by the bridge
- Optional foreground-process, scrollback-reference, agent, and redacted environment fields
The production PaneInfo projection currently populates terminal metadata and
CWD; optional process/agent/environment schema fields must not be mistaken for
evidence that those values or their continuity were captured.
The library/test layout substrate can create new panes and map old pane IDs to new ones for a limited projection. It does not preserve durable tab order, stable active-tab identity, mux domains, workspace/window placement, or full appearance. It never replays historical output through PTY input or restarts captured processes; those processes receive finite manual dispositions. Its same-session durable intent/outcome/lifecycle chain records mappings and keeps interrupted or partial attempts unclean for explicit reconciliation instead of silently retrying unknown external effects. No production CLI reaches this execution path today.
Scheduled backups use the SQLite online backup API for consistent snapshots. Backup archives include the database binary, a JSON manifest with SHA-256 checksums, and optional SQL text dumps. Retention and rotation are configurable by day count and maximum backup count, with 5-field cron scheduling support.
Deep Dive: Disaster Recovery Drills
The disaster_recovery_drills module provides structured, repeatable DR drill scenarios that exercise the backup/restore pipeline and measure RTO/RPO compliance. Each drill scenario specifies:
- RTO target (Recovery Time Objective): maximum acceptable time to restore service
- RPO target (Recovery Point Objective): maximum acceptable data loss window
- Completeness threshold: minimum fraction of panes that must be restored successfully
Drills produce scored reports with pass/fail/degraded verdicts and per-metric breakdowns. The verdict logic uses asymmetric scoring: completeness failures are always “Fail,” but missing one RTO/RPO target while meeting completeness produces “Degraded” rather than outright failure.
ContinuityReport was hardened in 2026-05 so that an empty report reports Unknown rather than Healthy — a release-gate forgery class that previously slipped through the rubber-stamp is_safe() sweep (ft-38rxl).
Deep Dive: Connection Pool and Circuit Breaker
The mux connection pool reduces overhead by reusing persistent connections to the WezTerm mux server. Key design choices:
- Semaphore-based concurrency. A
Semaphore(viaruntime_async) limits concurrent connections. Eachacquirereturns a guard that holds a permit; dropping the guard releases the slot. This prevents pool starvation even when operations fail. - Recovery with retry. On transient/recoverable errors, the pool discards the failed connection (guard drop releases the semaphore) and retries with a new connection using configurable backoff. The connection is intentionally not returned to the pool after an error since its state may be corrupted.
- Circuit breaker integration. After exhausting retries, failure is reported to a circuit breaker state machine. When the circuit opens (too many recent failures), subsequent operations fail immediately rather than waiting for timeouts. The circuit transitions through Closed → Open → Half-Open → Closed states with configurable cooldown periods.
The retry layer supports exponential backoff with random jitter (uniform ±10% by default) and per-use-case policies (WezTerm CLI: 3 attempts / 100 ms initial; database writes: 5 attempts / 50 ms initial). ft watch webhook delivery uses its own bounded policy: 5 attempts, 1 s initial delay doubling to a 4 s cap, retrying only transport errors, 408, 429 and 5xx.
The circuit-breaker Config had its pub fields tightened (ft-l5z7z) so callers can no longer bypass clamping; see the Substrate Audit Discipline section for the broader public-field bypass family closure.
Deep Dive: Pattern Engine Architecture
The pattern engine is a four-stage filter chain optimized for the common case (most text matches zero rules):
text chunk
│
▼
┌────────────────────────────────────────────┐
│ Stage 1: Bloom prefilter │ ← reject 80–95% of chunks
│ (anchor strings from every rule) │
└────────────────────────────────────────────┘
│ pass
▼
┌────────────────────────────────────────────┐
│ Stage 2: Aho-Corasick anchor match │ ← exact anchor confirmation
│ (single-pass over the buffer) │
└────────────────────────────────────────────┘
│ candidate rules
▼
┌────────────────────────────────────────────┐
│ Stage 3: Regex evaluation (fancy_regex) │ ← only on candidates
│ (per-rule, with timeout guards) │
└────────────────────────────────────────────┘
│ matches
▼
┌────────────────────────────────────────────┐
│ Stage 4: Dedup context + severity scoring │ ← suppress duplicate triggers
└────────────────────────────────────────────┘
│
▼ emit DetectionEvent → event bus
Why this chain is fast
- Bloom prefilter rejects most chunks for zero cost. A pack with 100 rules has 100–500 anchor strings; the Bloom filter computes ~8 hashes per chunk and rejects when none match.
- Aho-Corasick is O(n) in chunk length regardless of pattern count. Anchors are exact substrings, so AC is the right tool; regexes are deferred to candidates only.
- Regex evaluation is per-rule, with timeout guards. The substrate audit closed the regex-ReDoS class via
ft robot rules lint --strict, which warns on nested wildcards, excessive length (>500 chars), and consecutive spaces. - Dedup context prevents the same trigger from firing twice when output is repeated within a configurable window (the rate-limit retry-duration regex was recently tightened to anchor near rate-limit markers, reducing false positives; see CHANGELOG 2026-04-26).
Cross-chunk subtlety
Aho-Corasick’s LeftmostFirst non-overlapping mode is not composable across chunk boundaries. Earlier bytes consume match positions, preventing later patterns from matching. The live production engine — PatternEngine::detect_with_context (patterns.rs), driven per pane segment from runtime.rs — solves this with a bounded tail re-scan: each new segment is prepended with DetectionContext::tail_buffer (capped at PatternsTuning::DEFAULT_MAX_TAIL_SIZE_BYTES, 2 KiB) and only that overlap is re-scanned, with the common no-match case rejected up front by the Bloom quick_reject before Aho-Corasick runs at all (segments are themselves capped at IngestTuning::DEFAULT_MAX_PERSIST_SEGMENT_BYTES, 64 KiB).
Rule pack composition
A “rule pack” is a versioned, named collection of detection rules. The default pack is builtin:core (Codex + Claude Code + Gemini + terminal runtime events). Custom packs are TOML files discovered in /patterns/ (override with [patterns] user_packs_dir) and in the workspace’s .ft/patterns/, or listed explicitly as file:/path/to/pack.toml in [patterns] packs. Each rule has:
id(stable, machine-readable, prefix-namespaced; e.g.,codex.usage.reached)agent_type(codex / claude_code / gemini / wezterm / unknown; must align with theidprefix)event_typeanddescriptionanchors(Bloom-prefilter + AC input; short literal strings the rule needs to see)regex(optional; confirms the match, only run if anchors fire)severity(info / warning / critical)
Linter checks
ft robot rules lint --fixtures --strict enforces:
- Naming — IDs start with
codex.,claude_code.,gemini., orwezterm. - Agent-type alignment — Rule ID prefix matches its
agent_typefield - Regex safety — warns on nested wildcards (potential ReDoS), excessive length (>500 chars), consecutive spaces
- Fixture coverage — every rule has at least one corpus fixture
Deep Dive: Search Modes — Lexical, Semantic, Hybrid
ft search, ft robot search, and MCP wa.search share three retrieval modes.
Set the workspace default in ft.toml:
[search]
mode = "hybrid"
An explicit --mode (or MCP mode argument) overrides this setting, including
--mode lexical when the configured default is hybrid. Without a configured
mode, search uses lexical retrieval. The config value fts5 also selects
lexical retrieval; unsupported values such as two-tier are rejected.
| Mode | Backend | Best for | Latency target |
|---|---|---|---|
lexical (unconfigured default) |
SQLite FTS5 | Known strings, exact errors, identifiers | <10 ms |
semantic |
FNV-1a hash embeddings (fnv1a-hash-128) |
Token-overlap similarity on reworded queries; not true paraphrase understanding | vector scan over stored embeddings |
hybrid |
RRF fusion of lexical + semantic | Best of both; recommended when in doubt | lexical + semantic + fusion overhead |
Lexical (FTS5 + Tantivy)
SQLite FTS5 indexes captured output at write time. A Tantivy secondary index exists as a separate crate but is not populated on the production path.
Semantic (hash embeddings)
Every appended segment also gets a 128-dimension FNV-1a hash embedding (fnv1a-hash-128) stored alongside it. Queries are embedded the same way and matched by vector similarity. This is a lexical-flavored semantic lane, not an ML model; fastembed and the embedder daemon are not on the production path.
It sits behind the semantic-search feature, which the ft binary enables by default; without it, semantic and hybrid modes return lexical-only results.
Hybrid (RRF fusion)
Hybrid mode runs both backends in parallel and fuses results with Reciprocal Rank Fusion (RRF):
score(doc) = sum over backends of 1 / (k + rank_in_backend(doc))
k defaults to 60 (the canonical RRF constant). Hybrid mode is the recommended default when you don’t know in advance whether a query is best served by exact matching or by the looser token-overlap recall of the hash-embedding lane. The cost is roughly lexical_latency + semantic_latency + small fusion overhead.
Future-query recall caveat
The current recall bound for semantic search on held-out data is a vacuous PAC-Bayes bound until production query data is collected (derivation, artifact). Treat semantic recall claims as benchmark-substrate only, not production-data-validated, until the bound is non-vacuous.
Deep Dive: Policy Engine
The policy engine sits between every action and its target. Its job: turn a request like “send `` to pane 7” into a decision: Allow, Deny, or RequireApproval.
Decision pipeline
ActionRequest
│
▼
┌────────────────────────────────────────────┐
│ Capability gate │ ← does the caller have this capability?
└────────────────────────────────────────────┘
│
▼
┌────────────────────────────────────────────┐
│ Surface check (alt-screen, prompt-active) │ ← is the target in a state that accepts input?
└────────────────────────────────────────────┘
│
▼
┌────────────────────────────────────────────┐
│ Rate limit (per-pane + global) │ ← have we exceeded the rate budget?
└────────────────────────────────────────────┘
│
▼
┌────────────────────────────────────────────┐
│ Approval gate (if required by policy) │ ← does this action need explicit human consent?
└────────────────────────────────────────────┘
│
▼
┌────────────────────────────────────────────┐
│ Redactor (for read-path responses) │ ← strip secrets before returning text
└────────────────────────────────────────────┘
│
▼ Decision { Allow | Deny(reason) | RequireApproval(token) }
Audit writes
Every Deny / RequireApproval decision from the MCP gate helpers is persisted to the policy_denied_audit table (storage schema v24+). The wiring is in mcp_tools.rs::persist_mcp_policy_denial_async; the matrix at docs/security/policy-denial-audit-wiring-matrix.md catalogs which surfaces are wired.
Approval tokens
When the policy returns RequireApproval, it emits an 8-character approval code. The token is scoped to a specific (action, pane_id, fingerprint) triple; a code issued for sending /compact to pane 7 cannot be reused to send /compact to pane 9 or to send /clear to pane 7.
ft robot send 7 "rm -rf ~/important" # returns RequireApproval with code AB12CD34
ft approve AB12CD34 # operator approves
ft robot send 7 "rm -rf ~/important" # now succeeds; token is one-shot
Secret redaction
Every outbound pane-content read path (ft get-text, ft search, ft robot get-text, ft robot search, MCP wa.get_text/wa.search, web SSE /stream/deltas) routes through the Redactor. Configurable T1/T2/T3 sensitivity tiers control aggressiveness; the docs/security/redactor-coverage.json attestation slot catalogs which token families are covered. The 2026-05 expansion (ft-8nd26) added JWT, GitLab, Twilio, SendGrid, and Datadog patterns to the default ruleset.
Policy surfaces and subsystem diagnostics
The policy framework recognizes a small set of PolicySurface variants — Mux, Swarm, Robot, Connector, Workflow, Mcp, Ipc, Unknown — on every decision, so audit rows record which subsystem originated the request. Around those surfaces, the framework exposes a wider set of diagnostic subsystems (capability passport, command guard, approval flow, rate limiter, redactor, audit writer, etc.) — ft doctor --json reports per-subsystem health verdicts, and ft proof-doctor checks whether an intended proof command has the RCH-required shape before it is run. Those doctor rows describe a fresh engine, not the running watcher’s counters. The operator kill-switch tier is persisted; quarantines, the in-memory audit chain, and pending approvals remain process-local. A trip receipt identifies the integrated owner and does not prove settlement of previously admitted remote work. See the kill-switch contract for per-effect refresh and fence semantics. Failures are typed and routed back through the same error-code taxonomy as the rest of robot mode.
Deep Dive: Workflow Engine
A workflow is a registered handler that triggers on detected patterns. The engine runs them safely:
Components
- Engine (
workflows/engine.rs) — the orchestrator. Registers handlers, listens to the event bus, dispatches matching events to handlers. - Runner (
workflows/runner.rs) — runs a single workflow execution. Persists state toworkflow_executions. Enforces timeout + cancellation. - Lock (
workflows/lock.rs) — per-pane workflow lock. Prevents two workflows from racing each other on the same pane.LockManagerHealthtelemetry surface (ft-rai3h) tracks lock acquisition latency, hold time, and contention. - Handlers (
workflows/handlers.rs) — built-in workflow implementations (HandleCompaction,HandleUsageLimits,HandleAuthRequired,HandleOnErrorCassSearch, others; see the Built-in Workflow Handler Catalog for the full list). - Traits (
workflows/traits.rs) — theWorkflowtrait every handler implements. Required methods:name(),description(),handles(detection),steps(),execute_step(ctx, step_idx); defaulted ones includetrigger_event_types(),supported_agent_types()andtrigger_policy()(defaults toallow_all).
Trigger-policy allowlists (ft-j0ufc)
Workflows that act on high-trust panes can declare an allowlist:
fn trigger_policy(&self) -> WorkflowTriggerPolicy {
WorkflowTriggerPolicy::allowlist([trusted_pane_id])
}
The runner enforces the allowlist before any lock, audit row, or engine state is created. Refused triggers surface as WorkflowStartResult::SourcePaneNotTrusted and the originating source_pane_id is recorded for post-incident forensics. This closes the privilege-amplification class where a low-trust pane’s output could fire a high-trust workflow whose actions land on a different pane.
Workflow lifecycle
TriggerEvent → trigger_policy check
│
▼ pass
acquire pane lock
│
▼
persist WorkflowExecution(state=Started)
│
▼
handler.execute(ctx)
│
┌────┼────┐
▼ ▼ ▼
Success Failure Cancel
│ │ │
└────┼────┘
▼
persist WorkflowExecution(state=Final)
│
▼ emit WorkflowCompleted event
release pane lock
Idempotency
A workflow can declare itself idempotent. The engine then deduplicates triggers within a configurable window, so the same (pane_id, rule_id) event firing twice in 100 ms only runs the handler once.
Deep Dive: Transactional Mission Execution
Multi-pane operations use a prepare/commit/compensate lifecycle borrowed from distributed transaction protocols.
Lifecycle
TxContract
│
▼
┌────────────────────────────────────────────┐
│ PREPARE │
│ - validate preconditions (policy, liveness)│
│ - reserve resources (pane reservations) │
│ - obtain approval tokens if required │
│ - persist PrepareReceipt │
└────────────────────────────────────────────┘
│ success
▼
┌────────────────────────────────────────────┐
│ COMMIT │
│ - execute steps in dependency order │
│ - persist per-step receipt │
│ - on failure: stop and trigger compensate │
└────────────────────────────────────────────┘
│ success
▼ done
or, on failure:
┌────────────────────────────────────────────┐
│ COMPENSATE │
│ - run compensating action for each │
│ committed step in reverse order │
│ - persist CompensationReceipt │
└────────────────────────────────────────────┘
│
▼ TxOutcome
Idempotency ledger
Every step execution is recorded with a content-hash idempotency key. If a tx crashes mid-flight and is resumed, steps whose receipts already exist are skipped. This makes tx safe to retry after operator-host crashes, network partitions, or operator Ctrl-C.
Kill switches
The mission engine exposes a kill-switch enum (MissionKillSwitchLevel in plan.rs) with three levels:
- Off — default; mission proceeds normally
- SafeMode — restrict the mission to non-mutating / read-only steps; operator can still resume
- HardStop — abort immediately; compensation runs for any committed steps
The transition graph is enforced as a state machine; illegal transitions return a typed error. The TLA+ model for the kill-switch invariants is the proofs/tx-killswitch attestation slot (ft-tf6g3.12). Adjacent enums govern the broader execution model: KillSwitchAction in tx_killswitch_model.rs and FleetKillSwitch in robot_fleet_state_machine.rs.
Failure injection
ft tx run --fail-step tx-step:commit triggers an injected failure at the named step. This is how compensation paths are exercised in tests and in operator dry-runs.
Deep Dive: Fleet Memory Controller
The fleet memory controller synthesizes pressure from three independent subsystems into a single 4-tier model that drives uniform action across the system.
Inputs
- Pipeline backpressure — the capture queue and the storage-writer queue depths against their capacities (the same rows the resource cockpit’s
queue_backpressuredomain reports). - System memory utilization — process RSS / total RAM, with platform-specific source (
sysctlon macOS,/proc/meminfoon Linux). - Per-pane memory budgets — each pane’s resident scrollback as the mux reports it (warm resident bytes plus in-memory rows), against
[fleet_scrollback] per_pane_budget_bytes.
Synthesis: worst-of
The controller takes the worst tier across the three inputs. If pipeline backpressure is Green but per-pane budget is Red, the synthesized tier is Red. A single hot signal must always escalate.
4-tier pressure model
| Tier | Meaning | Action |
|---|---|---|
| Normal | All inputs healthy | None |
| Elevated | One input is yellow | Idle panes may back off to a 4x longer poll ceiling; active panes keep their poll rate |
| Critical | Any input is red | Idle panes are paused (a 16x longer poll ceiling), plus ft watch asks the mux to move the most pressured panes’ warm scrollback to the cold tier (mux codec 67+; older muxes log a recommendation) |
| Emergency | Any input is black | Idle panes are paused (16x ceiling); warm scrollback is evicted on every pane |
Pausing an idle pane stretches its poll ceiling rather than stopping capture: its next poll captures what it printed meanwhile (a burst larger than the capture window becomes an explicit gap segment, as at any poll rate), and a pane that starts printing returns to the fast poll floor at once.
ft watch also evaluates the global admission controller every health tick
for a standard new agent spawn: capture/write queue fullness and measured
failure rate, the compound fleet tier, the mux warm-tier budget, and measured
p95 stage latencies against their budgets. The verdict (admit, defer, degrade,
or shed, with reason codes; missing evidence is reported, never guessed) is
published in the resource cockpit’s resource_admission domain in
ft doctor --json. ft robot profile apply and a scaling-up
ft robot fleet scale consult it before spawning: a fresh shed verdict
refuses the spawn (robot.admission_shed; override with --force-admission),
and every other verdict, including unavailable when no
watcher answers or its snapshot is older than 90 s, proceeds and is reported
in the response’s admission field.
Asymmetric hysteresis
Escalation is fast: any input crossing into a hotter tier escalates immediately. De-escalation is slow: the controller requires N consecutive samples of the cooler state before stepping down a tier. This prevents flapping when an input oscillates near a tier boundary.
Cockpit data
During incidents, the resource-pressure cockpit contract gives operators the residency breakdown: rust_heap, mmap_file_backed, sqlite_page_cache, graphics_media, scrollback_cache, child_processes, unknown. Before calling anything a “leak,” operators classify the residency source. The cockpit also exposes action_receipts — what mitigations have already been attempted and their outcomes.
Deep Dive: Three-Tier Scrollback
In a simple sizing model, 200 panes retaining roughly 20 MB of uncompressed
backbuffer each consume about 4 GB before other process costs. That is an
illustrative calculation, not a measured comparison against every stock
terminal. ft keeps scrollback in three tiers and migrates lines between them
based on access patterns and pressure.
Tier transitions
new line
│
▼
┌──────────┐
│ HOT │ VecDeque in RAM, ~200 bytes/line
│ (last N) │
└──────────┘
│ aged out (configurable: line count, time)
▼
┌──────────┐
│ WARM │ zstd-compressed in RAM, ~40 bytes/line (~5:1 ratio typical)
│ (mid-age)│ Decompressed on demand
└──────────┘
│ evicted (configurable: pressure tier, age)
▼
┌──────────┐
│ COLD │ Persisted in SQLite output_segments
│ (queryable on demand) │
└──────────┘
Hot tier
A bounded VecDeque of decoded terminal lines. Direct indexing for renderer paint; O(1) push to the head. Tier boundary is configurable (default: most recent N lines, with N depending on pane priority).
Warm tier
Block-compressed (zstd) older lines. Compression block size is tuned so a single block is roughly the size of a screenful. Decompression is on-demand: a request for line 5000 decompresses only the block containing that line, not the entire warm tier.
Cold tier
When a line is evicted from warm (under Critical/Emergency pressure or aged past the warm threshold), it is dropped from RAM. Within the configured durable-retention window, the line remains queryable via the output_segments table (which is the canonical source of truth) and via FTS5 search; age, count, or storage-size retention may later prune it.
Why this layout
- Renderer hot path stays fast. The renderer only reads from the hot tier.
- Tier eviction does not create an immediate search gap. Lines that leave RAM remain searchable in SQLite until the configured durable-retention policy prunes them.
- Memory scales sublinearly with scrollback depth. Adding 10× more scrollback doesn’t add 10× RAM.
Deep Dive: Distributed Wire Protocol
Distributed mode lets remote hosts stream pane state into an aggregator. The wire protocol is designed defensively: every input is validated, dedup’d, and bounded.
Envelope schema
Every message is wrapped in a versioned envelope (crates/frankenterm-core/src/wire_protocol.rs):
pub const PROTOCOL_VERSION: u32 = 1;
pub struct WireEnvelope {
pub version: u32, // protocol version for compat checking
pub seq: u64, // monotonically increasing per sender (ordering + dedup)
pub sender: String, // sender identity (hostname or agent id)
pub sent_at_ms: i64, // epoch-ms timestamp; informational only
pub payload: WirePayload,// typed variants: pane meta, deltas, gaps, detections, …
}
Defenses
- Versioning —
versionis the first field; mismatch is a typed rejection. - Sender identity validation — at session start, the agent authenticates (token or mTLS); subsequent envelopes are rejected if
senderdoesn’t match the authenticated identity. - Per-sender sequence-number dedup — if
seqis repeated or arrives out of order, the envelope is rejected. Prevents replay attacks and accidental double-delivery. - Bounded message size — enforced at the codec layer via
WireProtocolTuning::DEFAULT_MAX_MESSAGE_SIZE. Larger payloads are rejected before allocation. - Stale-session pruning — sessions with no activity for
DEFAULT_AGENT_STALE_AFTER_MS(5 min default) are pruned by the aggregator. - Local receipt-clock decisions — the aggregator never uses remote clocks for liveness or ordering decisions. The
sent_at_msfield is informational only; capacity eviction and stale-session pruning are local decisions. - TLS recommended for non-loopback binds —
[distributed]config supports TLS; tokens from files / env vars (avoid inline).ft doctor --jsonverifies effective security state.
Safety review
The full safety review and diff-fuzz coverage live in docs/security/distributed-threat-model.md, the producer for the security/distributed-threat-model attestation slot.
Deep Dive: RuntimeProof Sealed Trait
The “no tokio” rule is enforced at three layers: dependency (cargo-deny), test (CI checks), and type (RuntimeProof sealed trait).
The mechanism
// In runtime_proof.rs (sketch)
mod sealed {
pub trait Sealed {}
}
pub trait RuntimeProof: sealed::Sealed { /* … */ }
// asupersync types implement RuntimeProof
impl sealed::Sealed for asupersync::sync::Mutex {}
impl RuntimeProof for asupersync::sync::Mutex { /* … */ }
// tokio types DO NOT implement RuntimeProof
// (and cannot, because Sealed is in a private module)
What it does
Any API surface that bounds its generic parameter by RuntimeProof cannot accept tokio::sync::* types. Those types don’t implement the sealed trait, and they cannot implement it because the Sealed super-trait lives in a private module. Adding an impl Sealed for tokio::* line elsewhere in the workspace fails to compile.
Why this matters
The two looser enforcement layers (cargo-deny, CI test grep) catch direct declarations of tokio. But what if a transitive dep re-exports tokio::sync::Mutex under a different name? Or what if someone writes a generic adapter that erases the runtime origin? The sealed trait catches these at the type level. The build refuses to even compile code that tries to smuggle tokio types into a RuntimeProof-bounded API.
The soundness argument
The Sealed super-trait is modeled in docs/proofs/runtime-proof-soundness.lean and checked by scripts/check-runtime-proof-soundness.sh. The proof argues: (1) Sealed is in a private module; (2) no external code can construct an impl Sealed for T; (3) therefore no external T can implement RuntimeProof; (4) therefore any RuntimeProof-bounded API rejects all non-allowlisted runtime types.
This is the proofs/runtime-proof-trait attestation slot (ft-i2eni.1).
Deep Dive: Attestation Bundle Format
A release attestation bundle is a content-addressed, Sigstore-signed JSON file under docs/attestations/.json. Its job: prove that every load-bearing README/AGENTS claim is backed by a hash-verified artifact.
Bundle structure
Top-level shape per the live bundles under docs/attestations/:
{
"schema_version": "1.0.0",
"generated_at": "2026-05-17T03:47:27Z",
"generator": { "name": "...", "version": "..." },
"release": { "channel": "...", "tag": "...", "version": "..." },
"git": { "branch": "...", "commit": "", "tree": "..." },
"required_categories": ["perf/headline-claims", "security/redactor-coverage", "..."],
"artifacts": [
{
"category": "perf/headline-claims",
"description": "...",
"media_type": "application/json",
"path": "docs/perf/headline-claims.json",
"produced_by_bead": "ft-syqcz.3",
"proof_categories": ["..."],
"sha256": "",
"size_bytes": 12345
}
],
"confidence_summary": { "best_confidence_by_category": {}, "records": [], "schema_path": "...", "schema_version": "..." },
"taxonomy_coverage": { "below_threshold_count": 0, "category_counts": {}, "delta_from_prior_release": {}, "schema_version": "...", "taxonomy_path": "...", "uncategorized_artifact_count": 0 },
"deferred_slots": [],
"retractions": [],
"signature": { "canonical_sha256": "", "method": "...", "reason": "..." }
}
Verify flow
ft attestation verify docs/attestations/.json
This:
- Re-derives every
artifacts[].sha256by reading the artifact from disk and hashing it - Recomputes the canonical signing payload (deterministic serialization of the slots + metadata)
- Verifies that
signature.canonical_sha256matches the recomputed hash - Verifies that the
.sigstorefile’s hash + size match the recorded values - Verifies the Sigstore signature against the canonical payload using the Fulcio cert + Rekor entry
Exits 0 on full pass, non-zero on any failure. --json mode emits a machine-readable verdict envelope. --strict-required adds a check that required_categories matches the canonical manifest exactly (catches under-declaration).
Signing identity
Sigstore keyless signing via Fulcio + Rekor. The signing identity, trust roots, and cosign verify-blob recipes live in docs/attestations/SIGNING.md. The closure procedure (when to run, how to file regressions on hash mismatch) lives in docs/release/attestation-checklist.md.
Retraction
When a shipped slot turns out to be wrong, the bundle is not edited. Instead, a retraction is recorded:
ft attestation retract --bundle docs/attestations/.json --slot proofs/tx-killswitch \
--rationale-file why.txt --retracted-by-release
ft attestation retractions --bundle docs/attestations/.json --json
Retractions are append-only and visible to anyone who verifies the bundle; this is the bundle-retraction substrate (ft-tf6g3.41).
Deep Dive: The Watcher Capture Loop
ft watch runs the main capture loop that produces every byte of observed data. Understanding the loop is essential to understanding what ft is doing while it’s “doing nothing visible.”
Per-tick stages
┌────────────────────────────────────┐
│ tick start (~poll_interval_ms) │
└────────────────────────────────────┘
│
▼
┌──────────────────────────────────────────────────────────────────────┐
│ 1. Discovery — call into the mux, list current panes │
│ - Detect new panes, retired panes, identity changes │
│ - Update pane registry + bookmarks │
└──────────────────────────────────────────────────────────────────────┘
│
▼
┌──────────────────────────────────────────────────────────────────────┐
│ 2. Round-robin scheduling among equal-priority panes │
│ - Honor [ingest.priorities] overrides │
│ - Respect per-pane / per-fleet capture budgets │
└──────────────────────────────────────────────────────────────────────┘
│
▼
┌──────────────────────────────────────────────────────────────────────┐
│ 3. Capture — pull current scrollback from each pane (concurrent) │
│ - Bounded by [ingest.max_concurrent_captures] │
│ - Uses native push events when the bridge is available; │
│ falls back to poll otherwise │
└──────────────────────────────────────────────────────────────────────┘
│
▼
┌──────────────────────────────────────────────────────────────────────┐
│ 4. Delta extraction — bounded 1 MiB overlap vs. last capture │
│ - On match: append the new tail to the segment buffer │
│ - On miss: emit explicit Gap event (never silent) │
└──────────────────────────────────────────────────────────────────────┘
│
▼
┌──────────────────────────────────────────────────────────────────────┐
│ 5. Scan pipeline — SIMD metrics → AC trigger → zstd compression │
└──────────────────────────────────────────────────────────────────────┘
│
▼
┌──────────────────────────────────────────────────────────────────────┐
│ 6. Persist — append to output_segments + FTS5 + hash embedding │
│ - Goes through the single-writer queue with batched commits │
└──────────────────────────────────────────────────────────────────────┘
│
▼
┌──────────────────────────────────────────────────────────────────────┐
│ 7. Detect — pattern engine evaluates new content (BOCPD parallel) │
└──────────────────────────────────────────────────────────────────────┘
│
▼
┌──────────────────────────────────────────────────────────────────────┐
│ 8. Event fanout — broadcast detections to EventBus subscribers │
│ (workflow engine, web/SSE streamer, distributed streamer, …) │
└──────────────────────────────────────────────────────────────────────┘
│
▼
┌──────────────────────────────────────────────────────────────────────┐
│ 9. Maintenance — GC compaction (cooldown'd), backup window check, │
│ pressure-tier re-evaluation, watchdog heartbeat │
└──────────────────────────────────────────────────────────────────────┘
│
▼ tick end
Provisional tick-budget bands
- 10-pane fleet: the current planning default is ~200 ms.
- 50-pane fleet: evaluate a tighter poll interval only while the measured pressure tier stays Normal; consider per-pane priority bumps for hot panes.
- 200±pane target: treat native push events and fleet-pressure throttling as required design assumptions, then qualify the exact host and workload before deployment.
These are starting hypotheses for measurement, not release-qualified latency or capacity guarantees.
When the loop throttles
- Elevated tier — idle panes back off to a 4x longer poll ceiling.
- Critical tier — idle panes are paused (16x poll ceiling; capture continues at that cadence), and the watcher evicts the targeted panes’ warm scrollback on the mux (codec 67+).
- Emergency tier — idle panes are paused; warm scrollback is evicted on every pane.
ft robot profile applyandft robot fleet scalerefuse spawns only on a freshshedadmission verdict.
What the loop never does
- It never sends input to a pane. That always goes through the policy gate via
ft send/ robot send / workflow handlers. - It never retries forever against an unreachable mux. The circuit breaker eventually opens; doctor reports the failure.
- It never invents data when capture fails. Gaps are recorded as explicit events.
Deep Dive: Storage Schema and Migration Strategy
ft stores everything in a single SQLite database. The schema is versioned and migrations are tracked.
Current schema version
The current version is v51. The authoritative source is
storage/schema_ddl.rs::SCHEMA_VERSION;
documentation must follow that constant rather than becoming an independent
version authority.
Core tables
| Table | Purpose |
|---|---|
output_segments |
Append-only captured-output deltas with FTS5 index. The canonical source of truth for everything searchable. |
events |
Detection + system events with categorical filters (rule_id, severity, handled flag, pane_id). |
audit_actions |
Every action that went through the policy gate (allow / deny / approve / rate-limited / failed). |
policy_denied_audit (schema v24+) |
Every Deny / RequireApproval decision from MCP gate helpers — see docs/security/policy-denial-audit-wiring-matrix.md. |
approval_tokens |
Approval codes + scope (action, pane, fingerprint), with one-shot semantics. |
workflow_executions |
Per-execution state and lifecycle for every workflow run. |
pane_reservations |
Cross-process pane-edit reservations (advisory leases). |
work_claims |
Native SQLite work-queue backing ft robot work claim / complete / list / ready. |
pane_contexts + context_rotations |
Native context registry for ft robot context status / rotate / history. |
agent_profiles + profiles_applied_log |
Profile definitions + per-apply receipts. |
session_checkpoints + mux_pane_state |
Session persistence (snapshots, restore IDs). |
prepared_plans + workflow_action_plans |
Tx prepare-phase state and pre-planned action records. Mission and Tx contracts themselves live as JSON files at .ft/mission/active.json and .ft/mission/tx-active.json; tx receipts (TxReceipt) are typed values persisted into those workspace contracts. |
mux_sessions + agent_sessions + panes |
Live mux/session/pane registry. |
notification_history + event_labels + event_notes + event_mutes |
Notification dedup history and event annotation. |
output_gaps + segment_embeddings + fts_index_state + fts_pane_progress |
Capture gaps, semantic embeddings, FTS5 index health. |
saved_searches + pane_bookmarks + accounts + action_undo + secret_scan_reports + usage_metrics + maintenance_log |
Operator-facing surfaces (saved queries, bookmarks, accounts, undo log, secret-scan reports, usage metrics, bounded operational advisories, and retained cleanup receipts). |
ft_meta |
Single-row table holding schema_version, min_compatible_ft, created_by_ft. |
Why SQLite specifically
- No system dep. rusqlite bundles SQLite; no install step.
- In-process I/O. No IPC overhead between
ftand the store. - WAL mode lets multiple readers proceed while a single writer commits.
- FTS5 is built-in and battle-tested.
- Online backup API gives us consistent snapshots without stop-the-world.
- Schema migrations are versioned + tracked + reversible (forensic_migration + rollback_execution support).
Single-writer integrity
A filesystem lock (fs2) ensures at most one watcher writes. The lock metadata records PID and start time. Read-only consumers (e.g., ft robot state from a second shell) acquire a shared lock and proceed without blocking the writer.
GC and VACUUM
The [gc] config controls periodic page-stat reporting. The cycle (configurable, default hourly) checks the free-page ratio and advises an explicit operator-run VACUUM when more than vacuum_threshold (default 20%) of pages are free. It never runs a full VACUUM automatically because that database rewrite can monopolize FrankenTerm’s single writer during a large active session. Each cycle emits a bounded advisory report (log_report = true by default); global retention deletes only old cache_gc and fleet_scrollback_coordinator advisories in finite FIFO batches while preserving cleanup receipts and unknown maintenance classes.
Schema migration safety
- Forward migrations are deterministic and idempotent. The migration engine in
crates/frankenterm-core/src/storage/migrations.rsapplies versioned steps;ft db migrate --statusshows the plan,ft db migrate --dry-runpreviews,ft db migrateapplies, and--totargets a specific revision. - Health checks are available via
ft db check(integrity + FTS + WAL + schema verdicts inauto/plain/json). - Repair is available via
ft db repair(FTS rebuild, WAL checkpoint, vacuum);--dry-runpreviews before executing. - Compatibility window.
ft_meta.min_compatible_ftrecords the minimumftversion that can read the current schema. A binary older than that refuses to open the DB rather than corrupting it.
Deep Dive: Recorder and Replay
Beyond delta capture, ft has a separate recorder subsystem that produces high-fidelity execution traces, and a replay harness that runs those traces back deterministically. Together they enable post-incident reconstruction and regression testing.
Recorder
- Append-log backend (current shipped default) — newline-delimited JSON events appended to a per-session log file.
- frankensqlite backend (rollout/test only; live bootstrap pending): a structured-row backend for tighter querying.
- The recorder owns its own invariants checker (
recorder_invariants.rs) and audit surface (recorder_audit.rs); the migration story (recorder_migration.rs) handles upgrading old session logs into the current event schema.
Replay
The replay subsystem is its own crate (frankenterm-core-replay, ~40k LOC, 31 source files). It accepts a recorded session and produces:
- A normalized event DAG (decision graph with causal edges)
- A virtual-clock harness so timing-dependent steps can be replayed deterministically
- A diff engine that compares two replays, useful for catching nondeterminism in workflow handlers
- A replay-assessment scorer that produces pass / fail / degraded verdicts per scenario
What replay catches
- Nondeterministic workflow handlers — handlers that read the wall clock, generate random IDs without a seeded RNG, or depend on iteration order over a
HashMap. - Off-by-N in event causality — events that should be downstream of a trigger but get persisted out of order under load.
- Regressions in policy decisions — a recorded session can be replayed against a newer policy ruleset to see whether previously-allowed actions are now blocked (or vice versa).
Replay invariants
- The
VirtualClockvalidator rejects NaN andNEG_INFINITYfor time inputs (br-ft-p2xmz / br-ft-gldyy, see CHANGELOG). ReplayConfig::validaterejects non-finite numeric inputs at the boundary.- Replays are byte-equal across machines when the recorded session is byte-equal; this is the project’s definition of replay determinism.
Deep Dive: Connector Fabric
The connector subsystem lets ft talk to external systems (issue trackers, monitoring, secret stores, log aggregators, custom internal services) through a unified bridge model.
Pieces (14 connector_*.rs modules in frankenterm-core/src/)
connector_sdk— the contract every connector implements. Versioned capability envelopes, request/response schemas, error taxonomy.connector_registry— name-keyed registry of installed connectors, with version pinning.connector_lifecycle— install / start / stop / restart / drain semantics.connector_host_runtime— the connector host model plus an HTTP delivery client that runs inside the watcher when[safety.connector_transport]is configured (no separate host process).connector_inbound_bridge— converts external signals (e.g., a webhook from PagerDuty) into typedftevents.connector_outbound_bridge— converts typedftevents (e.g., a critical detection) into external calls (e.g., a Slack post).connector_mesh— multi-host routing across a fleet offtaggregators.connector_governor— rate limits, capability gating, credential management.connector_credential_broker— short-lived credential issuance.connector_data_classification— tags data flowing through with sensitivity tier before redaction.connector_reliability— circuit breaker + retry budget per connector.connector_event_model— typed event variants the bridges produce/consume.connector_bundles— packaged connector definitions for distribution.connector_testbed— synthetic providers for tests; the only place mock connectors should live (the mock-finder discipline ratifies this).
Capability envelopes
Every connector declares its capabilities: what actions it can invoke, what state it can read, what events it can stream. The default envelope includes Invoke, ReadState, StreamEvents. Capabilities are enforced at the policy layer; a connector that didn’t declare StreamEvents cannot subscribe to the event bus even if its code tries to.
Certification probe pipeline
A certification probe pipeline (connector_sdk.rs) models this flow:
- Validate the connector binary signature
- Run the capability round-trip evidence harness (the connector reports its capabilities; the host verifies them)
- Record the result
- Refuse to start the connector if certification fails
It is exercised by the SDK simulator and tests only: ft robot connector install does not run it yet, and there is no certification table.
Mock-finder discipline
Mock connectors live only in connector_testbed.rs by design. The mock-finder sweep (per-substrate audit family) automatically detects production-stub regressions; the latest sweep on the connector cluster verified 14 connector_*.rs files clean. (See MEMORY note connector-cluster-mock-finder-sweep-2026-04-26 — referenced as ft-z4wvi + ft-6scm7 sweep follow-ups.)
Deep Dive: Agent Profiles, Personas, and Fleet Templates
A profile is a reusable specification of a pane: which agent (codex / claude_code / gemini), what cwd, what env overrides, what session settings, what tools it can use. Profiles let you say “spawn 3 of codex_ws” without re-stating the details every time.
Three-level composition
| Level | What it specifies | Example |
|---|---|---|
| Persona | Behavioral defaults (skill mix, prompt preludes, tool palette) | codex_engineer, claude_reviewer |
| Profile | Concrete pane spec (persona + cwd + env + session settings) | codex_ws (codex_engineer + workspace cwd) |
| Fleet template | A composition of profiles (counts + dependencies) | swarm_5x_codex_1x_claude |
Registry
Profiles persist in agent_profiles (DB-backed). ft robot profile list enumerates them; ft robot profile show shows the full definition. ft robot profile validate validates the definition without spawning.
Apply semantics (idempotent on identical input)
ft robot profile apply codex_ws --count 3 is idempotent on (name, count, env_overrides, dry_run). Re-running with identical inputs returns the same plan + same idempotency key. The mutation receipt is persisted to profiles_applied_log for replay.
Non-dry-run apply spawns panes through the mux bridge with rollback on mid-apply failure. The full contract (including idempotency rules, failure semantics, side-effect surface, and concurrency contract) is the canonical example for the broader robot-contract methodology (docs/robot-contracts/profile.md).
Why profile-driven spawning?
- Reproducibility. Two operators running
ft robot profile apply codex_ws --count 3get the same fleet shape. - Audit. The applied-log records who applied what when, with the content hash as the idempotency key.
- Composability (planned). Personas and fleet templates exist as types (
session_profiles.rs) but cannot yet be loaded or applied fromft; profiles are created withft robot profile createand applied directly.
Deep Dive: The Cx Cancellation Model
Cx is asupersync’s capability and cancellation context. When FrankenTerm
threads it explicitly through a call graph, it preserves typed cancellation,
deadline, budget, and capability state at each audited operation boundary.
What Cx is
A Cx is a token-bearing scope. When you spawn a child task with the canonical
spawn_with_cx wrapper, the child inherits the exact context and effective
capability mask. Cancellation becomes observable through explicit checkpoints
and operation-specific races. Budget-aware sleeps, timeouts, receives, and
locks do not all share identical direct-cancellation wake behavior, so each
wrapper documents its own contract.
What this buys us
- Monotone cancellation authority. Explicit child tasks inherit the
parent’s
Cxand effective capability restrictions. Lifetime enforcement still requires owned handles or aJoinSet; aCxby itself does not forcibly terminate a detached future. - Budget-aware primitives with explicit direct-cancel handling. The pinned
asupersync
budget_sleep/budget_timeoutprimitives honor theCxbudget deadline, but do not register a direct-cancellation wake. Callers that need prompt cancellation checkpoint before/after bounded waits or race an explicit cancellation signal, then classify timeout and cancellation from the typed context state. - Auditable shutdown. When the operator hits Ctrl-C, the root
Cxrequests cancellation and owned top-level handles are drained under a bounded budget. Shutdown reports when acknowledgement or independently delegated/blocking work remains unproven instead of claiming that no operation can survive.
Pre-cancel vs mid-flight semantics
asupersync’s recv/acquire primitives observe pre-cancel cleanly but not mid-flight by default; a recv that’s already past the cancellation check at the moment cancel arrives will complete its current iteration. The project standard for mid-flight cancel responsiveness is the select-race pattern: race the awaited operation against cx.cancelled(). See docs/proofs/runtime-async-cancel-traces.md (Mazurkiewicz cancel-trace classes) for the formal model.
Cancellation is not a circuit-breaker failure
Error::Cancelled is explicitly exempted from circuit-breaker failure counts (ft-gc4hz). Cancelling a request because the operator hit Ctrl-C is not a sign that the downstream system is unhealthy; treating it as one would open the circuit on every clean shutdown.
Deep Dive: Error Taxonomy
Every ft error is a typed envelope with a stable code, a human-readable message, and an optional actionable hint. The taxonomy is operator-readable and machine-routable.
Code prefixes
| Prefix | Meaning |
|---|---|
robot.* |
Robot Mode surface errors (most common; one per failure mode) |
policy.* |
Policy decision errors (deny, require_approval) |
mission.* |
Mission lifecycle errors |
tx.* |
Tx prepare/commit/compensate errors |
envelope.* |
Operating-envelope admission verdicts |
storage.* |
DB / FTS5 / migration errors |
wezterm.* |
Mux backend errors (subset of robot.wezterm_*) |
cass.* |
Cross-Agent Session Search errors |
caut.* |
Errors from the caut account-usage CLI wrapper |
connector.* |
Connector fabric errors |
Categories (ErrorCategory)
Each code is classified into a category for routing, one per code range: Wezterm (1xxx), Storage (2xxx), Pattern (3xxx), Policy (4xxx), Workflow (5xxx), Network (6xxx), Config (7xxx), and Internal (9xxx). Categories enable bulk policy decisions (e.g., “retry every Network error, alert on every Internal”).
Retryability
Each code has a is_retryable() verdict. Examples of retryable codes: robot.wezterm_not_running, robot.timeout, robot.cass_timeout, robot.rate_limited, robot.circuit_open, robot.tx_lock_failed, robot.tx_in_progress. Non-retryable codes include pane-not-found (the pane really doesn’t exist; retrying won’t help) and policy-denied (deny is a decision, not a transient).
Actionable hints
The hint_for(code) -> Option registry maps codes to operator suggestions. When a caller doesn’t set a site-specific hint, the central registry provides a fallback. Unknown codes return None — callers are not allowed to fabricate generic hints; an absent hint is the signal that the code needs an entry in the registry. The registry is allocation-free (&'static str).
This pattern (ft-tzolj) closed the class of error responses that shipped hint: None and left operators to look up the code in external docs.
Deep Dive: Resource Pressure Cockpit
When operators see “high memory,” the cockpit contract demands they classify the residency source first. The contract is at docs/resource-pressure-cockpit-contract.md.
Residency classes
| Class | What it counts | Where it usually lives |
|---|---|---|
rust_heap |
Heap allocations of the watcher itself | jemalloc stats |
mmap_file_backed |
mmap’d file regions | SQLite + Tantivy index files |
sqlite_page_cache |
SQLite’s page cache | Tunable via PRAGMA cache_size |
graphics_media |
GPU buffers, texture atlases | Only on GUI builds |
scrollback_cache |
Hot + warm scrollback tiers | Per-pane budgets |
child_processes |
Spawned mux/pty processes | OS process accounting |
unknown |
Everything else | Should always be near-zero; non-zero is a yellow flag |
Action receipts
Each cockpit response includes action_receipts — what mitigations have already been attempted and their outcomes. Operators check these before claiming a mitigation “actually ran.” This prevents the classic incident-response anti-pattern of “tried X, didn’t help, but we never confirmed X actually ran.”
Conformance artifact
The resource-cockpit conformance lane is the e2e script tests/e2e/test_ft_rz0eb_4_resource_cockpit_conformance.sh (retained remote-reduced conformance artifact: tests/e2e/artifacts/goal-line/ft-rz0eb.4/resource_cockpit_conformance/20260513T172634Z/summary.json). Target-class proof is governed by docs/perf/target-class-hardware.md and is currently skipped_not_proven.
Deep Dive: Mux Server Federation
frankenterm-mux-server is the headless mux daemon. frankenterm-mux-server-impl houses the shared implementation. Together they enable federated multi-host setups where one operator runs the GUI / Robot Mode and remote hosts run the mux + agents.
Federation primitives
- Command transport — typed scope + kind enums (
CommandScope,CommandKind), with deduplication on the wire (CommandDeduplicator) to avoid double-execution under retry. - Topology orchestrator — layout templates + template registry; the orchestrator decides where to place new panes based on the registered topology spec.
- In-process federation checkpoints —
DurableStateManagerkeeps bounded lifecycle-registry checkpoints and optional topology in memory for rollback and diff operations. It can encode/decode checkpoint JSON, but no production disk writer/loader is wired, and it does not preserve terminal bytes, PTYs, or child processes. - Federation router — outbound mux events are routed to the right federated participant; inbound events are stamped with origin metadata.
Why a separate headless server
Some operators want to run ft watch and ft robot from a laptop while the agent fleet lives on a beefier remote box. The headless mux server provides the mux + PTY layer remotely; ft on the laptop talks to it over a connection (loopback in the local case; TLS-secured in the remote case).
Operator topology
Operator workstation Remote agent host
┌──────────────────────────────┐ ┌────────────────────────────┐
│ ft (GUI / Robot Mode) │ ◄──────────── │ frankenterm-mux-server │
│ ft watch (capture/store) │ loopback / │ agent panes (codex/cc/…) │
│ SQLite + FTS5 + Tantivy │ TLS │ pty layer │
└──────────────────────────────┘ └────────────────────────────┘
For wider topologies (one operator, many remote hosts), see Secure Distributed Mode.
Deep Dive: Native Event Bridge (push mode)
The default capture mode is poll: ft watch queries the mux for pane state every poll_interval_ms. A complementary push mode is available when the native event bridge is wired up.
What push mode does
The native event bridge subscribes to OS-level signals from the mux/GUI process: pane lifecycle events (created, exited, focus changed), PTY events (output ready), and visibility events. When a signal arrives, the watcher captures the affected pane immediately rather than waiting for the next poll tick.
Why this matters at scale
- A 200-pane fleet polling every 200 ms generates 1000 mux queries/sec just for discovery. Push mode collapses that to ~zero for idle panes.
- Latency from “agent produces output” to “ft has captured it” drops from ~half the poll interval to ~bridge round-trip + extraction time.
- Capture is more accurate: poll-mode can miss bursts that started and finished within a poll window; push-mode catches them.
Implementation
native_events.rs houses the bridge. It forwards native events to the runtime over an asupersync mpsc channel. The emitter side lives in the GUI / mux process and ships through the codec layer. The receiver side in ft watch subscribes per-pane.
Fallback
When the native event bridge is unavailable (running against an older mux, or against a backend that doesn’t expose push signals), the watcher transparently falls back to poll mode. ft doctor --json reports the effective bridge state.
Deep Dive: WASM Extension Surface (type substrate; runtime not yet wired)
ft has a typed extension contract surface in extensions.rs designed for out-of-process WASM execution via wasmtime (component-model, async, std). The wasmtime runtime itself is not yet wired in the current shipped build — the source explicitly notes: “The actual WASM runtime (wasmtime) is a future addition; these types…” The substrate is in place so the ABI freezes early; the live execution path is pending.
Why ship the types first
- Letting the contract shape stabilize while implementation evolves means external authors can start writing against it.
- Replay determinism, fuel budgets, and policy-gating story can be designed before the runtime arrives.
extensions.rslives infrankenterm-coreand is compiled into every build; it holds contract types only, with no runtime behind them.
Intended capabilities (when wired)
- Custom detection rules (compiled regex or richer logic)
- Custom workflow handlers
- Custom search rewriters
Intended constraints
- No filesystem or network access outside host-mediated APIs
- No cross-extension state access
- No policy-gate bypass
- wasmtime fuel-budget enforcement so runaway extensions can’t lock up the host
When tracking issue: the WASM execution path is part of the broader extension-system roadmap; this README will be updated when wasmtime is wired and a working example ships.
Deep Dive: Notification Pipeline
When detections fire, ft watch can notify operators through desktop notifications, email, and webhooks.
Backends
| Channel | File | When to use |
|---|---|---|
| Desktop notification | desktop_notify.rs |
Interactive operator on a workstation |
email_notify.rs |
SMTP delivery with required STARTTLS, implicit TLS, or an explicitly configured unauthenticated plaintext relay | |
| Webhook | webhook.rs |
Integrate with PagerDuty / Slack / custom routers |
| Prometheus alert | via the metrics surface | Existing alerting infra |
| In-app events | event bus | Other ft surfaces (web/SSE, MCP, robot events) |
Email delivery
Configure an SMTP relay, then use ft notify test --channel email --format json
to exercise the same filtering, redaction, and transport used by the watcher:
[notifications]
enabled = true
[notifications.email]
enabled = true
smtp_host = "smtp.example.com"
smtp_port = 587
tls = "start_tls"
username = "[email protected]"
password = "replace-with-your-app-password"
from = "[email protected]"
to = ["[email protected]"]
subject_prefix = "[ft]"
timeout_secs = 10
ft watch --notify-via email selects email alone; multiple --notify-via
selections can enable other channels alongside it. Channel selection preserves
the configured SMTP credentials and validates the configuration before startup.
For implicit TLS, set tls = "tls" and the relay’s SMTPS port (usually 465).
tls = "none" is limited to relays without credentials. STARTTLS is mandatory
when selected: a relay that cannot upgrade is rejected before authentication.
TLS verifies the server certificate and hostname using public WebPKI roots.
SMTP authentication supports PLAIN and LOGIN over TLS. A transaction accepts at
most 32 recipients and has one total timeout of 1–120 seconds. All recipients
must be accepted before the message body is submitted. Success means the relay
acknowledged the completed DATA command; it does not establish inbox delivery.
Connection loss or cancellation after DATA begins is reported as
email.delivery_indeterminate. Email does not retry automatically, since an
uncertain acknowledgement may follow a successfully accepted message.
Alert manager (alerts.rs)
ft watch can monitor recorded API costs, token usage, rate-limit counts, and an explicitly selected account’s remaining balance. Alerts are opt-in and require an observed pane ID. Cost, token and rate-limit rules total that pane’s recorded metrics over a rolling day, week, or 30-day month; an optional agent_type filter narrows the total. These rules reject account_id, because recorded pane usage carries no account.
[alerts]
enabled = true
check_interval_secs = 60
repeat_after_secs = 1800
[[alerts.rules]]
id = "agent-token-budget"
pane_id = 7
metric = "token_usage"
threshold = 1000000
period = "day"
[[alerts.rules]]
id = "account-balance"
pane_id = 7
metric = "account_balance"
threshold = 20.0
period = "day"
service = "anthropic"
account_id = "my-account"
Use cost, token_usage, or rate_limit_frequency for upper limits: levels start at 50%, 75%, 90%, and 100% of the configured threshold. account_balance monitors a minimum percentage, requires both service and account_id, and uses the selected pane as its notification target. Missing account data, data older than 15 minutes, unobserved panes, and oversized metric windows are reported
Install
This server does not publish a one-line install command.
Open the repository installation guide New to MCP? Start with the mcpskill.org guide →