Skip to content
insightfloPublic

About

Model-agnostic 5-layer local coding agent orchestrator with SQLite WAL EWMA Beta decision gate

Topics

Resources

Stars

2 stars

Watchers

0 watching

Forks

Repository files navigation

English · 한국어

dgate — Empirical Multi-Agent Orchestrator with 0-turn sharp routing and 0-token Sublead pipeline

0 npm dependencies Rust v2 ~3.7ms startup macOS Linux Windows 538 tests passing Node 22.6+ MIT License

Live Control · Prerequisites · Quick Start · Architecture · 0-Token Pipeline & CLI · Roster · Security · Rust v2 & GPUI

Bind any local CLI coding agents (claude · codex · devin · pi · gemini · agy · custom) across five role slots (lead · explore · coder · verifier · advisor). Tasks proven stable in local SQLite telemetry go straight to a readonly worker with 0 Lead LLM turns, while a deterministic 0-token state machine drives isolated git worktree pipelines. When subscriptions or quotas shift, swap one roster.json.

insightflo/dgate in 15 seconds
Made with GitReels


Live Control Surfaces

dgate ships three native, read-only-first observation planes sharing one local SQLite SSOT (~/.local/state/dgate/decision.db): a dual-view localhost SSE web dashboard (dg serve), a Rust ratatui TUI (dgate-tui), and an optional GPUI desktop app (dgate-gui). All screenshots below are captured directly from the real UI with sanitized repository telemetry.

1. Signal Topology (Dark Mode) — dg serve

Real-time graph mapping Lead, Sublead clusters (↳ sublead-*), parallel worktree coders, readonly explorer, independent verifier, and on-demand advisor alongside EWMA Beta Decision Gate bars (θ_sharp = 0.70), per-repo Markdown TODOs, and a persistent Inspector + Lead Console.

dg serve Dark Signal Topology view showing TODO panel, Decision Gate probability bars, 4 active worker nodes, Local Status inspector, and Lead Console

2. Factory Pipeline View (Light Mode) — dg serve

Switch top-center from Topology to Factory for a single-pass 5-stage runtime pipeline (Local Triggers → Dispatch / Coder / Verifier / Advisor / Backprop → Local Results) where active stages illuminate automatically, paired with the live OS/herdr process mapping inspector.

dg serve Light Factory Pipeline view showing 5-stage runtime pipeline, active Coder and Verifier counters, TODO checklist, and Live Mapped Processes inspector

3. Inspector Detail Views — Lead Console & Filesystem Footprint

  • Routing Detail, Audit Log & Interactive Lead Console: Inspect any node's routing probability and decision_events audit stream while steering the selected repository's Lead directly (hc read / hc send, file/image attachments, slash commands, quick-prompt chips).

dg serve Detail & Logs inspector with expanded Lead Console displaying role-colored orchestration output and verdict summary

  • Filesystem Footprint & Worker Scope Audit (발자국 / dg footprint scan): Track 15-minute host disk/RAM deltas, newly created artifacts, SQLite DB accumulation, and per-worker out-of-scope file modifications (밖 1 alert) in real time.

dg serve Filesystem Footprint inspector showing host disk and RAM meters, 15-minute file growth, DB count, and out-of-scope worker change alerts

4. Native Rust Terminal Dashboard — dgate-tui

Zero-dependency ratatui TUI (~3.7ms native startup) with hot-reloading roster.json, Decision Gate threshold markers, Sublead cluster ownership, horizontal overflow panning (←/→), and read-only DB/process polling.

dgate-tui native Rust ratatui terminal dashboard displaying Advisor, Lead, Verifier, Decision Gate bars, 4 worker cards, and decision_events logs

Control Surface Commands & TUI Keybindings
dgate-tui                                        # Native ratatui TUI (current repo; --all for all repos)
dgate-tui --demo                                 # Render built-in demo snapshot (no DB or hc needed)
dgate-tui --snapshot                             # Print static frame to stdout and exit
dg serve --port 4747 --scope-tabs 0              # Localhost SSE web dashboard (Dark Topology & Light Factory)
dg serve --port 4747 --public-origin https://dg.example.com  # Allow writes behind reverse proxy / Access
dg footprint scan                                # Filesystem footprint & worker scope audit (dg footprint show)
dg todo-location docs/roadmap.md --repo <dir>    # Register TODO path → picked up by web TODO pane
npm run dgate-gui                                # Optional GPUI 0.2.2 GPU-accelerated desktop app
Key Action
Tab / Shift+Tab Switch focused panel
← / → Select worker card (pans across +N more overflow)
Enter Open selected worker detail modal
a Toggle current repo vs. all repos scope
r · ? · q Refresh now · Help · Quit

Why dgate

  • Empirical Decision Gate (0 Lead Turns on sharp) — Computes EWMA Beta posteriors over local SQLite(WAL) telemetry to route proven low-risk tasks directly to a readonly worker (sharp) and escalate writes, high-risk tasks, or 2 consecutive errors (forced split) to the Lead.
  • 0-Token Sublead Pipeline & Readonly Pre-Scouting — Automatically runs non-overlapping tasks in parallel isolated git worktrees. When a brief lacks file:line anchors, a lightweight readonly explore worker writes .herdr/context/<fork_id>-map.md first, while dg pipeline run drives explore → coder → verifier → rework/g3 → READY_PR with zero persistent sublead LLM tokens.
  • Independent Cross-Model Verification & Physical Guardrails — Fail-closed readonly hooks (dg hook --guard), worktree caps & write-root whitelists (.herdr/limits.json), SHA-256 worktree checkpoints before deletion (exit 4 gate), and structured verdict backpropagation (dg backprop).
  • Single Rust v2 Workspace, 0 npm Dependencies — ~3.7ms native startup across macOS, Linux, and Windows (3-OS GitHub Actions CI). One npm run install:global exposes dg, dgate, dgate-tui, and dgate-gui in any repository.

Prerequisites & What Requires herdr (hc)

dgate separates local decision/observation from background worker session control. Check what you need for your adoption level:

Component Status What It Unlocks
Rust toolchain (cargo stable) + git Required Builds every binary (dg · dgate · dgate-tui · dgate-gui) and enables git worktrees & SHA-256 checkpoints.
Local Coding CLI (1+) (claude · codex · devin · pi · gemini · agy · custom) Required for AI execution Actual worker roles (lead · explore · coder · verifier · advisor). Without any CLI, --dry-run, dg route, dg stats, and --demo still run standalone.
herdr (hc CLI / herdr-app) Required for full orchestration & Lead Console Spawning/controlling background parallel workers (hc run --bg -- dg wrap ...), dg pipeline run, dg send / dg reconcile / dg reap, Sublead cluster tracking, and the interactive Lead Console (hc read / hc send / hc put) in dg serve.
Node.js 22.6+ Optional Convenience npm run scripts and npm run install:global wrapper installer (0 external npm packages).
fswatch / GEMINI_DECISION_API_KEY Optional fswatch adds live filesystem watching to dg footprint; API key enables optional shadow/on probability calibration (default DECISION_API=off, 100% free local SQLite stats).

Important

Can I use dgate without herdr (hc)?
Yes, for standalone monitoring, routing, and wrapping: dg route · dg gate · dg wrap · dg stats · dg report · dg checkpoint · dg hook --guard · dgate-tui · dg serve (OS ps process detection, local git/worktrees, TODO panel, and filesystem footprint) all work with zero hc dependency.
No, for full automated multi-worker dispatch & live Lead steering: launching parallel background workers (dg dispatch live / dg pipeline run) and steering leads from the web Lead Console require hc (herdr) on PATH (or via HC_BIN). Run npm run setup:check anytime to inspect which tools are detected.


30-Second Quick Start

git clone https://github.com/insightflo/dgate.git && cd dgate
npm run build            # cargo build --release --workspace
npm run install:global   # installs dg · dgate · dgate-tui · dgate-gui into ~/.local/bin
npm run setup:check      # read-only check of Rust, coding CLIs, hc (herdr), and roster
dg serve --port 4747     # launch localhost SSE web dashboard — or run dgate-tui / dgate-gui

Tip

Non-invasive 3-module adoption: Adopt only what you need without modifying repository files:

  1. Monitor only (dgate-tui · dg serve · dgate-gui, zero repo edits, works without hc via OS ps + SQLite)
  2. Router only (dg route · dg suggest-session, pure local SQLite telemetry, no hc needed)
  3. Full orchestrator (dg dispatch · dg pipeline · dg merge-train — requires hc + coding CLIs).

Repo hooks and contract blocks are explicit opt-in; run npm run setup (0-token wizard) to configure your roster interactively.

Standalone 3-Line Rehearsal (No hc, External CLIs, or API Keys)
./target/release/dg route --task-kind explore_read                                  # sharp/split decision (0 LLM turns)
./target/release/dg wrap --route tool_select --tool-class shell_exec -- echo hi     # watchdog-wrapped telemetry run
./target/release/dg stats --cost --timing && ./target/release/dg report             # cost/timing stats & rule candidates
./target/release/dg dispatch --task-kind multi_edit --repo . --dry-run              # safe orchestration rehearsal (:memory: DB)

Architecture

dgate Pre-Lead Decision Gate (Layer 0) and 5-Layer Orchestration Architecture

Layer Responsibility Key Contract
Layer 0 · Pre-Lead Gate dg route / dg dispatch (0 LLM turns) EWMA Beta posterior across 7 task kinds (explore_read, code_search, single_edit, etc.) → sharp or split
Layer 1 · Lead Planning, worker briefs, serial merge Records stats (HERDR_DB_WRITE=1), enforces merge_danger & --after gates
Layer 2 · Swarm / Pipeline Readonly explore + parallel git worktree coding Parallel by default for disjoint scopes; intra-wave transitions run via dg pipeline run (0 tokens)
Layer 3 · Independent Verifier Cross-model, readonly verification .herdr/verify/<fork_id>-verdict.json SSOT → dg backprop fail-closed
Layer 4 · On-Demand Advisor 3 gates: Plan (G1), 2× Error (G2), Pre-Merge (G3) Single verdict marker response, then immediate hc kill; hc rm cleanup

Note

Role Separation & Worker Execution Contract
Decision routing, gates, and dg wrap telemetry (~/.local/state/dgate/decision.db) work standalone without hc. Background session lifecycle (hc run/wait/send/kill) and live steering run on top of hc. All external workers launch via hc run --bg -- dg wrap ... (no unwrapped nohup/disown). Long autonomous runs follow docs/autonomous-run-contract.md.


Zero-Token Sublead Pipeline & CLI

dgate Zero-Token Sublead Pipeline State Machine driving explore, coder, verifier, and rework/G3 to READY_PR or exit 3 escalation

Run dgate against any local repository via --repo (full multi-PR playbook in docs/WORKFLOW.md):

dg dispatch --task-kind multi_edit --repo /path/to/your-project --dry-run
  • dg pipeline init|step|status|run — Deterministic 0-token state machine eliminating ~70% mechanical sublead transition token waste (docs/sublead-pipeline-design.md). Drives explore → coder → verifier (cross-model enforced) → rework/g3 → READY_PR from .herdr/pipelines/<run_id>.json, exiting 3 only on budget exhaustion, verdict=human, or protocol violations for a 1–2 turn escalation.
  • dg suggest-sublead — Evaluates 3-axis signals from decision.db or pre-flight --scopes <p1,p2,...> with 0 LLM calls to recommend parallel worktree partitioning (docs/sublead-design.md).
  • dg suggest-session — Decides ephemeral (1-task) vs. warm reuse (prompt cache) for coders with 0 LLM calls (verifier/advisor are always ephemeral; auto-resets on 2× consecutive failure, compaction, 5 tasks / 35 turns, or <70% first-pass rate).
  • dg merge-train — Serializes READY_PR merges under strict branch protection with CI re-check and sublead merge-blocking guards.
  • Dispatcher Gates — --brief-file <path> mechanically validates ## Standards / ## Spec / ## Merge Danger, door: one-way|two-way, and blast_radius (≤500 chars, ≤64KB UTF-8; template: docs/verifier-brief-template.md); --after <fork_id> defers dispatch until predecessor forks close.
Complete dg Subcommand Reference (28 commands)
Command Purpose
route Evaluate sharp/split decision (0 LLM turns); supports cost-aware dynamic θ_sharp via --roster/--profile
gate Gate entry posterior & forced-split check with dynamic θ_sharp
dispatch Issue fork (dispatch:true) + worker command with --brief-file & --after gates and worktree cap check
dispatch-mode --set off|strict — in strict mode, delegate_swarm wraps require a dispatch-issued --fork
wrap Wrap worker command with watchdog (--stall-ms, --stall-action kill|warn), artifact contracts, usage/cost capture, auto-retry, and atomic SSOT commit
pipeline init|step|status|run [--dry-run] [--with-explore|--skip-explore] — 0-token sublead state machine
merge-train Serial merge train with CI re-verification & sublead merge guard
serve Localhost SSE web dashboard (--port 4747, --repo, --scope-tabs, --public-origin)
footprint scan|show — filesystem disk/new-file/DB/worker out-of-scope audit
todo-location Register/show/clear <repo>/.herdr/todo-path for the web TODO panel
suggest-sublead 0-LLM 3-axis parallel partitioning & sublead recommendation
suggest-session 0-LLM ephemeral vs. warm session lifecycle & reset decision
backprop Apply verifier [FAIL] or --verdict-file structured verdict to parent fork (fail-closed)
attempt Query or bump fork generation/attempt fence (--bump-gen, DDL v2)
retro Generate redacted failure retrospective Markdown for next worker brief
checkpoint create|verify|restore — git binary patch + untracked snapshot with SHA-256 manifest
worktree worktree remove — physically blocks deletion until checkpoint verification passes (exit 4)
reconcile Reconcile finished hc terminals against open forks by exit code
settle-orphans Reconcile then settle TTL-expired orphan forks (--no-hc optional)
close / touch / record Close fork (ok|fail|rerouted), heartbeat TTL, or record manual EWMA sample
stats Read-only cost & deduplicated interval execution/wait timing (--cost, --timing, --days)
report Read-only rule candidate report (--days, --out; never mutates prompts, code, or DB)
compact Compact SQLite decision DB & roll up stats
hook --guard (fail-closed readonly & resource guard) · --collect (fail-open PostToolUse telemetry)
setup --check · --json · --repo <dir> — inspect CLI tools, hooks, and roster health
send / reap Verified hc send with retry (send) · reap idle finished terminals (reap --minutes 30)

Hot-Swappable Roster

All role-to-model bindings live outside the binary. Swap one JSON file whenever quotas or providers change:

--roster <path>  >  HERDR_ROSTER_PATH  >  <repo>/.herdr/roster.json  >  ~/.config/herdr-quad/roster.json  >  built-in (quota-saver)

Copy .herdr/roster.example.json to ~/.config/herdr-quad/roster.json:

{
  "defaultProfile": "quota-saver",
  "profiles": {
    "quota-saver": {
      "roles": {
        "lead":     { "cli": "pi", "provider": "opencodex", "model": "<lead-model>", "thinking": "max" },
        "explore":  { "cli": "pi", "provider": "opencodex", "model": "<cheap-model>", "thinking": "medium", "readonly": true },
        "coder":    { "cli": "custom", "bin": "aider", "extraArgs": ["--no-auto-commits"] },
        "verifier": { "cli": "pi", "provider": "opencodex", "model": "<verifier-model>", "thinking": "max", "readonly": true },
        "advisor":  { "cli": "pi", "provider": "opencodex", "model": "<advisor-model>", "thinking": "high", "readonly": true, "onDemand": true, "quotaBucket": "pi" }
      }
    }
  }
}
Built-in Profile Role Binding Behavior
quota-saver (default) lead, verifier, advisor on pi (advisor on-demand) Zero agy consumption
agy-quad (opt-in) lead, verifier, advisor on agy Auto-demotes to quota-saver when daily turn budget is reached
  • Partial overrides inherit built-in defaults; "cli": "custom" binds any local terminal CLI (codex, opencode, aider, etc.).
  • Optional pricing.relativeCost enables cost-aware dynamic θ_sharp = clamp((C_eff(explore)+C_switch)/(C_eff(lead)+C_switch), 0.70, 0.90).
Environment Variables Reference (11 vars)
Variable Purpose
DGATE_DB_PATH SQLite decision DB path (default ~/.local/state/dgate/decision.db; legacy aliases supported)
HERDR_ROSTER_PATH Override roster.json path
PI_BIN / HERDR_PI_BIN Override pi binary path
AGY_BIN / DEVIN_BIN / HC_BIN / CLAUDE_BIN / CODEX_BIN Override individual CLI executable paths
HERDR_AGY_TURN_BUDGET Daily agy turn budget (default 20 — auto-demotes profile when exceeded)
DECISION_API off (default, 0 network) · shadow (parallel eval, local unchanged) · on (cold-start basis:prior only)
GEMINI_DECISION_API_KEY Decision API key — sent strictly via x-goog-api-key header (never URL ?key=); degrades to off if absent
DECISION_API_BASE_URL Endpoint override (default https://generativelanguage.googleapis.com)
DECISION_API_MODEL Model override (default gemini-decision-1)
DECISION_API_TIMEOUT_MS Timeout ms (default 3000, clamped 50–30000)
DGATE_MAX_WORKTREES Override worktree cap (default 5, or per-repo .herdr/limits.json)

[!CAUTION] Never commit API keys to this repository. Inject credentials exclusively via environment variables; .env* files are excluded by .gitignore.


Security & Isolation

Defense Layer Mechanism
Resource Guard (Pre-Block) dg hook --guard caps git worktree add (default 5, .herdr/limits.json maxWorktrees / DGATE_MAX_WORKTREES) and blocks shell writes outside configured writeRoots (sample: docs/limits.sample.json).
Fail-Closed Readonly Guard .agents/hooks.json blocks writes, delegation, dangerous flags (--dangerously-skip-permissions), and control-char injection for HERDR_READONLY=1 workers (denies on guard error).
Fail-Open Telemetry PostToolUse collection errors never block worker execution.
Readonly Tool Pinning pi explore workers automatically receive --tools read,grep,find,ls --exclude-tools edit,write.
Session & Dry-Run Isolation Session names validated against ^[a-z0-9_-]{1,32}$ + 6-hex suffix; --dry-run runs on an in-memory :memory: SQLite DB.
Deep Dive: Lifecycle Watchdog, Fail-Closed Verdict, DDL v2, Checkpoints & Secret Redaction
  • Execution Lifecycle & dg wrap Watchdog — Runs workers in a detached process group, commits outcomes atomically (commitWrapOutcome) with --expected-gen/--expected-attempt fencing, enforces artifact contracts (--require-artifact, --require-nonempty), monitors stalls (--stall-ms 300s, --stall-action kill|warn), harvests per-CLI token/cost usage (pi, devin, agy, claude, codex + optional pricing.json, sample: docs/pricing.sample.json), auto-retries transient failures (--retry, default 1, excludes stall/timeout), and classifies 11 FailureCause types while isolating config_error/interrupted from EWMA pollution.
  • Fail-Closed Verdict & dg retro — .herdr/verify/<fork_id>-verdict.json (schema_version: 1, pass|rework|fail|human, P0|P1|P2|info) enforces schema, fork_id/HEAD binding, and contradiction checks via dg backprop (invalid/stale/replay/human parks at waiting_human with exit 3). dg retro emits redacted retrospectives for retry briefs.
  • DDL v2 & Deduplicated Timing — Auto-migrates v1 DBs via VACUUM INTO backup + single transaction (PRAGMA user_version = 2), adding fork_intervals so dg stats --timing unions overlapping parallel worker spans cleanly.
  • Git-Native Worktree Checkpoints & dg report — dg checkpoint create|verify|restore snapshots binary diffs + untracked files (12 MiB cap) with SHA-256 manifests; dg worktree remove physically cannot delete without verified checkpoint (exit 4, no bypass flag). dg report runs strictly read-only (PRAGMA query_only).
  • 3-Layer Secret Defense — Header-only API auth (x-goog-api-key), sanitized child environments (--sanitize-env strips *_API_KEY|_TOKEN|_SECRET|_PASSWORD|_PRIVATE_KEY), and global redactSecrets scrubbing across logs, snippets, verdicts, and retros.

Rust v2 Workspace & Optional GPUI App

Rust v2 is the sole implementation of dgate (Node v1 removed; see docs/v2-ssot-migration.md). Headless CLI builds never compile GUI crates:

default-members = ["crates/dgate-core", "crates/dgate-cli"]
  • cargo build --release builds native target/release/dg and target/release/dgate (~3.7ms startup, macOS · Linux · Windows).
  • Optional GPUI Desktop App (crates/dgate-gui): GPU-accelerated native control app built on gpui 0.2.2 (macOS · Windows) featuring per-repo tabs, resizable panels, 5-role live telemetry, Sublead clusters, Decision Gate bars, and two-step confirmed worker stop (npm run gui:build / npm run dgate-gui).

Verification

Suite Count Command
Rust Workspace (core · cli · e2e · tui · gui) 528 tests cargo test --workspace
Global Installer Contract (wrappers · idempotency · win32) 10 tests node --test tests/install-global.test.ts

Run all 538 tests in one command with npm test.


License & Credits

  • License — MIT License (independent Rust v2 codebase; third-party Cargo crates retain their respective permissive licenses).
  • Visual Layout Inspiration — Early TUI topology concepts were visually inspired by leecg39/Gemini_trick; all dgate v2 Rust code, Decision Gate logic, rosters, and web/GPUI dashboards are independently implemented.
  • Guardrail Inspiration — Execution guardrails, checkpoints, and telemetry patterns inspired by Tencent/LoopForge (analysis: docs/loopforge-references.md).
  • Optional Companion Skills (under their respective licenses): mistology · NeverStuck · todo-flow · Effort-Router

About

Model-agnostic 5-layer local coding agent orchestrator with SQLite WAL EWMA Beta decision gate

Topics

Resources

Stars

2 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages