FrankenTerm

Architecture

1,051 words5 min read7 subsectionsFrom the README at ft 0.15.21

On this page7
Workspace StructureSub-crate extraction invariantsKey algorithms and techniquesData flowSystem Components and ResponsibilitiesSub-crate boundaries explainedDependency rules (enforced by the build, not just by convention)
┌───────────────────────────────────────────────────────────────────────┐
│                       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/                              # <!--count:workspace_members-->97<!--/count--> workspace members (auto-stamped)
├── Cargo.toml
├── crates/
│   ├── frankenterm/                      # CLI binary (ft)
│   ├── frankenterm-core/                 # Core library — <!--count:core_top_level_modules-->540<!--/count--> top-level modules, <!--count:core_loc-->1421634<!--/count--> 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/                        # <!--count:core_rust_test_files-->1051<!--/count--> Rust test files, <!--count:test_count-->64657<!--/count-->+ test annotations
│   │   └── benches/                      # <!--count:criterion_bench_files-->119<!--/count--> 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/                                 # <!--count:fuzz_targets-->52<!--/count--> fuzz targets
├── docs/                                 # <!--count:doc_markdown_files-->549<!--/count--> Markdown documentation files
├── tests/e2e/                            # <!--count:e2e_scripts-->305<!--/count--> 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-types depends on frankenterm-core-replay-types.
  • Cluster sub-crates (*-ars, *-tantivy, *-replay, *-fleet) depend on frankenterm-core and, 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.md for 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

  1. Discovery — enumerate pane/session resources via active backend adapters
  2. Capture — stream output and state deltas from adapters / runtime hooks
  3. Delta — compare with the previous capture using the bounded 1 MiB overlap window
  4. Store — append new segments to SQLite with FTS5 indexing
  5. Detect — run pattern engine (anchored + Bloom-prefiltered + BOCPD) against new content
  6. Event — broadcast detections to event bus subscribers
  7. Admit — operating-envelope planner decides whether new pane/workflow work is safe
  8. Workflow — execute registered workflows on matching events (with trigger-policy allowlists)
  9. Policy — gate all actions through capability and rate-limit checks
  10. 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)

  1. 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.
  2. Leaf type crates declare no first-party deps. They depend only on external libs (serde, etc.), except that frankenterm-core-audit-types uses frankenterm-core-replay-types.
  3. 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.
  4. tokio ban at the cargo-deny layer fails the build if any first-party Cargo.toml declares tokio directly.
  5. Cycle detection runs in the release gate (scripts/release-gates.sh, DSR quality) via cargo-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.