Skip to content

About

Controlled Execution Sandbox + macOS OS-Level Control Hub — Rust + PyO3 Core via Maturin

Resources

Stars

2 stars

Watchers

0 watching

Forks

Repository files navigation

doc_id fusion-executor/readme
product fusion-executor
class platform
entry service
doc_type readme
title
zh en
fusion-executor 说明
fusion-executor README
audience engineer
status draft
version 0.2.30
updated 2026-11-29
owner @dahai
source_of_truth
README.md

fusion-executor

Language / 语言: English | 中文

Controlled execution sandbox + macOS OS-level control hub. Runs shell commands safely (Security Guard + PTY Sandbox), drives native GUI (Computer Use via Accessibility API), and rolls back on failure (Git snapshots). Replaces the Claude SDK BashTool/FileEdit + Docker sandbox, but native — no Docker, macOS process isolation + Git snapshots, init <5ms.

Rust core + PyO3/maturin Python bindings. First maturin/PyO3 project in the Fusion monorepo (the other 23 Python projects use setuptools).

Status: v0.2.30 released — controlled execution sandbox (Security Guard + PTY/stdio sandbox + Git rollback + Diagnostics Slicer for 8 languages) + macOS OS-level control hub (Computer Use via Accessibility API + CoreGraphics + CGEvent synthesis: 20 GuiAction variants + coordinate-mapping scale_factor + display-capability query + batch actions + batch mouse-move path + screenshot sensitive-region masking) + UDS JSON-RPC IPC service + live stdio streaming + native file tools (file_edit/glob/grep/write_file/multi_edit/notebook_edit + surgical patch engine) + background shells + auto-rollback + live telemetry + bidirectional server-push + macOS seatbelt + fusion-guard zero-trust authorization (Phase 3, default OFF) + server-side deterministic cancel of in-flight streams (Issue #32) + laya-mlx deterministic tool selection (Issue #46, AC8 <15ms both backends: HTTP p50=6.2ms + python p50=7.2ms, dual Python/HTTP backends + AgentLoop wired into FusionSandboxExecutor.agent_run() + deterministic filler-stripping param extraction, issue #54) + shared async batch-task service TaskManager (Issue #57: task_id polling, queued→running→done/failed/cancelled state machine, retry backoff, SQLite persistence across restart, TASK_PROGRESS: live progress protocol, result export/report — for any business app under ~/fusion/business) + single-point key/env resolution via fusion_core.config (Issue #60: client_key() / default_mlx_base_url(), no hand-rolled resolvers, no secret default literals — dev missing key = empty + warning, prod = RuntimeError) + fusion docs-system v1.1 adoption (docs/ grid: product-page/get-started/api-reference/config-reference/troubleshooting/guides + ci/validate_docs.py frontmatter/link validator + docs.yml workflow) + demo/test environment sandbox runner (Issue #64: DemoEnvRunner — one ai-* app per guest, provision = clone https with ssh fallback + shared venv + pip install -e, start via the app's own start.sh (missing → visible error + manual hint), up/status/stop idempotent + single-app policy, host-gateway probe informational only, app process inside SandboxProfile(network=allow) seatbelt with FUSION_LLM_BASE_URL/FUSION_MLX_URL wired to the host gateway; CLI --demo-up/--demo-status/--demo-stop; shell_start gains optional per-shell sandbox profile, 4-layer plumb, None byte-identical) + automated sandbox preview stack runner (Issue #65: PreviewStackRunner — per-project docker compose overlay + preview profile, synthetic demo data injection via project-provided seed_cmd (never real customer data), health-check gate before URL issuance (unhealthy stack auto-torn-down), TTL auto-teardown + explicit teardown, port-in-use pre-flight probe, idempotent up, notify readiness hook for the consumer's email channel; library API for the cowork match-node pipeline, no CLI) + session-scoped demo host orchestration (Issue #68: DemoSessionManager — per-customer-click ephemeral stacks: web via docker compose per-session project + demo port range 11600-11669 + healthcheck gate + TTL teardown + data burn, iOS via xcrun simctl boot/install/launch/shutdown with concurrency cap 2 + persisted queue (position + ETA), scenario/stub injection logged [stub] <event> -> fixture (never real third-party APIs), per-session fk- LLM key wired to gateway :11432, rollup(slug) health badges; streaming/Android/metering-verify deferred upstream) + demo session streaming + Android kind + metering readback (Issue #69: open_stream — iOS MJPEG best-effort over HTTP + demo-app stream page URL verification (web stream_path opt-in), kind="android" code path (Linux+/dev/kvm pre-flight, docker privileged emulator, adb boot poll, live verify blocked on hardware), session_cost(session_id) own-key /v1/cost readback (live E2E verified through real gateway; non-stream metering gap filed upstream fusion-gateway#639 — since fixed and verified)) + demo session touch injection (Issue #69 acceptance item resolved: inject_touch(session_id, x, y, action="tap"|"swipe") — iOS via idb, the XCTest-based UI automation stack, executor-owned idb_companion lifecycle (spawn + grpc-port parse + connect + teardown); Android via adb shell input; tap round-trip ~327ms steady state live-verified on a booted simulator; missing tools fail visibly with install commands). Four audit passes all defects fixed; 529 Rust + 339 Python (3 skip) tests green; CI retrofitted per the fusion#2 checklist (concurrency cancel + docs-only path skip + pip cache, PR #74); clippy --all-targets -D warnings clean; fmt/ruff clean; maturin builds. See examples/ for runnable demos and docs/INDEX.md for the documentation map.

Architecture

12-crate Cargo workspace (resolver 2), one PyO3 binding crate built by maturin.

fusion-executor/
├── Cargo.toml              # workspace root (mirrors fusion-design)
├── pyproject.toml          # maturin build backend, fusion_executor Python package
├── crates/
│   ├── fe-core/            # orchestrator: Executor pipeline, BLOCKING_RT
│   ├── fe-security/        # Security Guard: regex blocklist + tokenizer + whitelist
│   ├── fe-sandbox/         # PTY subprocess, timeout, truncation, OOM cap
│   ├── fe-gui/             # macOS Computer Use: AXUIElement + CoreGraphics (P4)
│   ├── fe-rollback/        # git snapshot/rollback (P2) + auto-rollback guard (v1.4)
│   ├── fe-diagnostics/     # Traceback regex + tree-sitter slicer (P2)
│   ├── fe-ipc/             # UDS JSON-RPC 2.0 server (P3) + bidirectional server-push BroadcastHub (v1.5 #14)
│   ├── fe-tools/           # native file tools: file_edit/glob/grep + patch engine (v1.3)
│   ├── fe-telemetry/       # live telemetry: 10Hz CPU/mem sampling stream (v1.4)
│   ├── fe-shell/           # background shell registry, poll-model (v1.8 — #1)
│   ├── fe-guard/           # fusion-guard wire mirror (v0.2.6 — #23 Phase 3)
│   └── fe-pyo3/            # PyO3 bindings; maturin target → fusion_executor._native
├── python/
│   └── fusion_executor/    # Pydantic v2 models + FusionSandboxExecutor + LayaToolSelector
└── python/tests/           # pytest

Core pipeline (fe-core): validate(command) → if blocked return exit_code=-1 → else sandbox.run() → return ExecutionResult.

Key Constraints

  • [workspace.lints.rust] unsafe_code = "deny" — 11 crates forbid unsafe; fe-gui crate-level #![allow(unsafe_code)] (3 audited FFI blocks: AXIsProcessTrusted + AXValueGetValue ×2, forced by rustc 1.96 unsafe_extern_blocks).
  • extension-module is NOT in the workspace default features (otherwise cargo test cannot link libpython); maturin injects it via pyproject features=["pyo3/extension-module"].
  • PTY merges stdout+stderr → all into stdout (stderr empty); traceback is readable at the tail.
  • Exit codes: 0=success, -124=timeout, -1=blocked/internal error.

Build

cd /Users/dahai/fusion && source .venv/bin/activate   # shared venv (Python 3.14)
pip install maturin                                     # first time
cd fusion-executor
maturin develop --release          # editable install into shared venv → fusion_executor._native

Test

cd /Users/dahai/fusion && source .venv/bin/activate && cd fusion-executor

# Rust (workspace — extension-module off by default, cargo test can link libpython)
cargo test --workspace
cargo test -p fe-sandbox                # single crate
cargo test -p fe-security

# Python
pytest python/tests
pytest python/tests/test_executor.py::test_run_echo -v   # single test

# Smoke
python -c "from fusion_executor import FusionSandboxExecutor; print(repr(FusionSandboxExecutor().run('echo hi').stdout))"

# Start UDS server + subscribe broadcast (v1.5 #14)
python -c "from fusion_executor import FusionSandboxExecutor; FusionSandboxExecutor().serve()"   # another terminal
# another terminal: subscribe to telemetry push
python -c "from fusion_executor import FusionSandboxExecutor; s=FusionSandboxExecutor().subscribe(['telemetry'], interval_ms=100); [print(next(s)) for _ in range(3)]; s.unsubscribe()"

Lint

cargo clippy --workspace -- -D warnings
cargo fmt --all -- --check
ruff check .          # Python
ruff format .         # Python

CLI Usage

fusion-executor "echo hi" --cwd /tmp --timeout 10
fusion-executor "echo hi" -v          # verbose JSON output

Python API

from fusion_executor import FusionSandboxExecutor, ExecutionResult

ex = FusionSandboxExecutor()

# Sync execution (simplest for scripts)
r: ExecutionResult = ex.run("echo hi")
assert r.exit_code == 0  # 0=success, -124=timeout, -1=blocked/internal error
assert r.stdout == "hi\n"
assert not r.blocked_by_security

# Security block
r = ex.run("rm -rf /")
assert r.blocked_by_security and r.exit_code == -1

# Timeout
r = ex.run("python3 -c 'while True: pass'", timeout=1.0)
assert r.timed_out and r.exit_code == -124

# Diagnostics slicer — failing commands return structured Diagnostics (when exit_code != 0)
r = ex.run("python3 -c \"raise ValueError('boom')\"")
assert r.diagnostics.error_type == "ValueError"
assert r.diagnostics.raw_trace is not None

# Git snapshot + rollback (caller-driven; executor is stateless)
snap = ex.snapshot_create(cwd="/path/to/repo")  # git stash create → SHA
ex.rollback(snap, cwd="/path/to/repo")  # git checkout -- . && git stash apply <id>

# Async (asyncio callers)
r = await ex.run_async("echo hi", task_id="t1", cwd="/tmp", timeout=30.0)

# Bidirectional server-push subscription (v1.5 #14 — requires a running serve())
# Three channels: telemetry (10Hz CPU/mem) / stdio (cross-connection command stream) / screenshot (periodic capture)
sub = ex.subscribe(["telemetry", "stdio"], interval_ms=100, screenshot_interval_ms=1000)
for params in sub:  # __next__ yields the params (dict) of executor.event frames
    print(params["channel"], params["data"])
sub.unsubscribe()  # or sub.close()

run signature: run(command, *, task_id=None, cwd=None, timeout=30.0, env_vars=None, enable_rollback_snapshot=True, trace_id=None) -> ExecutionResult.

ExecutionResult fields: exit_code, stdout, stderr, task_id, command, duration_sec, timed_out, blocked_by_security, security_reason, snapshot_id, diagnostics, auto_rolled_back, trace_id.

Cross-layer trace_id (v0.2.1 — M-OPS-06/m-OPS-03)

run() / run_streaming() accept an optional trace_id: str | None. When None, the execute entrypoint auto-generates a uuid v4. The id is threaded through the Rust tracing::span! context (log lines carry trace_id=...), the IPC wire, and is backfilled on ExecutionResult.trace_id — one id correlates logs, IPC frames, and the result across all four layers. Blocked results also carry the caller's trace_id. Background shells (shell_start) are out of scope — they have no ExecutionResult to carry the id.

Background Shells (v1.8 — #1 run_in_background parity)

Persistent long-running shells with poll-based output capture (Claude Code run_in_background / BashOutput / KillShell parity). The new fe-shell crate owns a ShellRegistry (id → handle); each shell reuses fe-sandbox::spawn_pty for proven env/seatbelt/PTY setup, then runs self-managed reader (tail accumulator, OOM-capped) + waiter (child exit) threads. Poll model — shell_output returns the accumulated tail snapshot (not a delta); the caller de-duplicates. Live-tail via BroadcastHub is a future issue. Security is enforced in fe-core (fail-closed) before any spawn — fe-shell never validates commands.

M-ARCH-1 (architecture): ShellRegistry is owned by the IPC layer (IpcServer, alongside BroadcastHub) and by PyExecutor — not by the Executor. The Executor stays stateless per-task (CLAUDE.md contract): shell_start takes &ShellRegistry by reference and keeps the security check co-located; shell_output/kill_shell/list_shells are associated functions (no &self). PyExecutor.serve() shares its Arc<ShellRegistry> into the IpcServer via with_executor_and_shells, so the in-process path and the serve path see the same registry — a serve-path restart no longer drops background shell handles.

from fusion_executor import FusionSandboxExecutor, ShellStartResult, ShellOutput, ShellInfo

ex = FusionSandboxExecutor()

# Start a background shell (security-validated first; blocked → ok=False, shell_id=None)
r: ShellStartResult = ex.shell_start("python3 -c 'import time; time.sleep(30)'", task_id="t1")
assert r.ok and r.shell_id.startswith("sh-")

# Poll the accumulated tail snapshot + running/exit state
out: ShellOutput = ex.shell_output(r.shell_id)
assert out.running and out.exit_code is None

# Kill the process tree (SIGINT → 500ms grace → SIGKILL via killpg)
assert ex.kill_shell(r.shell_id)

# List all shells (running + finished)
infos: list[ShellInfo] = ex.list_shells()

# Blocked command — never spawns
r = ex.shell_start("rm -rf /")
assert not r.ok and r.blocked_by_security and r.shell_id is None

shell_start(command, *, cwd=None, env_vars=None, task_id=None, max_output_chars=100000, seatbelt=False, inherit_env=False, max_nproc=1024, max_cpu_sec=0) -> ShellStartResult. UDS methods: executor.shell_start / executor.shell_output / executor.kill_shell / executor.list_shells.

Native File Tools + Surgical Patch Engine (v1.3)

Replaces the Claude SDK FileEdit/Glob/Grep — native Rust implementation, guarded by the fe-security path guard (rejects cwd escape / sensitive-dir access), atomic write (.fe-tmp-{pid} + rename).

from fusion_executor import FusionSandboxExecutor, EditResult, GlobEntry, GrepMatch

ex = FusionSandboxExecutor()

# file_edit — unique-match exact replace (>1 match rejected, avoids accidental edits)
r: EditResult = ex.file_edit("app.py", "x = 1", "x = 99", cwd="/repo")
assert r.ok and r.matches == 1

# glob — wildcard match, returns paths relative to cwd
# E1 生态统一 glob 规范 (#20): `*` 不跨 `/`, `**` 跨目录, `?` 单个非 `/` 字符。参考 fusion-event/docs/glob-spec.md。
entries: list[GlobEntry] = ex.glob("**/*.py", cwd="/repo")  # **/*.py 跨目录; src/*.py 仅同层

# grep — regex search over files/dirs (recursive, skips binary, 1000-hit cap)
hits: list[GrepMatch] = ex.grep(r"^import\s", ["app.py"], cwd="/repo")

# grep_with_opts — ripgrep parity: output modes + context + multiline + glob filter (#7)
out: GrepOutput = ex.grep_with_opts(
    r"^import\s",
    ["app.py"],
    {"output_mode": "files_with_matches", "glob_include": ["*.py"]},
    cwd="/repo",
)  # modes: content | files_with_matches | count; -A/-B/-C context, multiline, -g include/exclude

# apply_patch — Unified Diff apply (diffy); full rewrite forbidden (new_range all-delete → reject)
r = ex.apply_patch("--- a/app.py\n+++ b/app.py\n@@ -1,1 +1,2 @@\n-x\n+x\n+y\n", cwd="/repo")

# replace_function — function-level replace (tree-sitter AST locate, py/js/ts/rs); no grammar → regex fallback
r = ex.replace_function("mod.py", "old_fn", "def old_fn():\n    return 99\n", cwd="/repo")

EditResult{ok, path, error, matches}; GlobEntry{path, is_dir}; GrepMatch{path, line_number, content}. replace_function not finding the function → ok=False, error="function not found: ...".

Live stdio Streaming (v1.2)

The run_streaming generator yields frame by frame — chunk strings first, the done frame yields an ExecutionResult at the end. Wired through 4 layers (fe-sandbox run_streaming → fe-core execute_streaming → fe-pyo3 NativeStreamIterator → Python generator).

from fusion_executor import FusionSandboxExecutor, ExecutionResult

ex = FusionSandboxExecutor()
for frame in ex.run_streaming("echo hi", enable_rollback_snapshot=False):
    if isinstance(frame, ExecutionResult):
        print(f"done exit={frame.exit_code}")
    else:
        print(f"chunk: {frame!r}", end="")

Frame format (ExecutionStreamEvent, serde tag="type"):

  • chunk: {"type":"chunk","data":"..."} (line-by-line stdout)
  • done: {"type":"done", exit_code:..., stdout:..., diagnostics:...} (ExecutionResult fields flattened into the same object, not nested)

Blocked (security violation) → only a single done frame, no chunks. Timeout → done frame timed_out=True, exit_code=-124. Failing command → done frame includes diagnostics.

Server-Side Cancel (v0.2.7 — Issue #32)

Cancel an in-flight execute_stream from the server side with a deterministic process-tree kill — not a cooperative "please stop" request. Built for clients (e.g. fusion-code) to abort a runaway long-running command without leaving orphan processes.

cancel_stream(stream_id) opens a fresh UDS connection and sends executor.cancel {id}, where stream_id is the JSON-RPC request id of the execute_stream call. The server resolves the in-flight stream, fires an oneshot that fe-sandbox's run_streaming tokio::select! is waiting on, then runs kill_process_group_async (SIGINT → 500ms grace → SIGKILL of the whole process group, plus a ppid-tree descendant walk to catch setsid orphans). The original stream connection receives the terminal Done frame with exit_code: -1 and cancelled: true.

import socket, json
from fusion_executor import FusionSandboxExecutor, ExecutionResult

ex = FusionSandboxExecutor(allow_inline_interpreter=True)
ex.serve()  # background, or run in another process; socket at ~/.fusion-executor/fe.sock

# Launch a long-running stream (id = 51) over a raw UDS socket
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
sock.connect(ex._sock_path)
sock.sendall(
    (
        json.dumps(
            {
                "jsonrpc": "2.0",
                "id": 51,
                "method": "executor.execute_stream",
                "params": {
                    "command": "python3 -c 'import time; time.sleep(1000)'",
                    "enable_rollback_snapshot": False,
                    "timeout_sec": 120,
                },
            }
        )
        + "\n"
    ).encode()
)

# ...later, abort it:
ok = ex.cancel_stream(51)  # -> True (found + cancelled)
# read the Done frame on `sock`: exit_code=-1, cancelled=True
  • Cancel is cross-connection: a second connection can cancel a stream started on another connection (the StreamRegistry is shared across the whole server). The client keeps the execute_stream connection open to read the terminal Done frame.
  • Unknown stream_id → returns False (best-effort, no exception).
  • The in-process run_streaming() path (no serve() running) is never cancellable — cancel only applies to streams served over UDS.
  • ExecutionResult.cancelled: bool is False on every non-cancel path; True only when a cancel actually fired.

Per-command Sandbox Profile (v0.2.8 — Issue #34)

Enable seatbelt/sandbox for the detached executor subprocess with a per-command profile — sandbox-independence for fusion-code G2. Each ExecutionRequest carries an optional sandbox: SandboxProfile that tunes the macOS sandbox-exec profile for that single command. Default-off / opt-in: a None profile preserves the existing fixed profile byte-for-byte (default deny network-outbound + directed SENSITIVE_FS_PATHS file-write deny), so existing deployments behave identically.

from fusion_executor import FusionSandboxExecutor, SandboxProfile

ex = FusionSandboxExecutor(allow_inline_interpreter=True)

# Default (None) — behavior identical to v0.2.7
r = ex.run("echo hi")
assert r.exit_code == 0

# Per-command: allow network, block specific binaries via seatbelt deny process-exec
r = ex.run(
    "curl https://example.com",
    sandbox=SandboxProfile(network="allow", excluded_commands=["rm", "curl"]),
)

# Fail-closed: if sandbox-exec is unavailable AND fail_if_unavailable=True, the
# command is blocked (exit_code -1) rather than running without isolation.
r = ex.run("risky --flag", sandbox=SandboxProfile(fail_if_unavailable=True))

SandboxProfile fields (matches fusion-code SandboxSettings):

  • network: str | None — "allow" omits the network deny; "deny" (or None) keeps deny network-outbound. None does not override the default.
  • filesystem: str | None — "allow" omits FS deny; "deny_write" (default) keeps directed sensitive-path file-write deny; "deny" adds a global file-write* deny.
  • excluded_commands: list[str] — command names injected as (deny process-exec (literal "<name>")) into the seatbelt profile. Strings are sanitized (strips ", \, control chars) to prevent profile-syntax injection.
  • fail_if_unavailable: bool — True = fail-closed when sandbox-exec is not on PATH (exit_code -1, no spawn); False (default) = silently degrade to running without seatbelt.

The profile is an additive RPC field (sandbox: { network?, filesystem?, excluded_commands? }) — it auto-flows through the 4 layers (fe-core ExecutionRequest.sandbox → fe-ipc serde_json::from_value(params) → fe-pyo3 PyAny→serde → Python Pydantic _STRICT). Existing executor.execute / execute_stream UDS methods accept it with no method-level wiring changes.

Auto-rollback (v1.4 — FR-04 optional policy)

run() / run_streaming() accept an optional auto_rollback: RollbackPolicy. When enabled, if a command fails (exit_code != 0) AND workspace file changes are detected (git status --porcelain non-empty), it auto-rollback(本次快照)s and marks result.auto_rolled_back=True. The Executor stays stateless — the guard lifetime is limited to a single execution and does not accumulate failure counts across requests (consecutive-failure counting belongs to the caller's self-healing loop).

from fusion_executor import FusionSandboxExecutor, RollbackPolicy

ex = FusionSandboxExecutor()
policy = RollbackPolicy(max_consecutive_failures=3, file_damage_check=True)
# command corrupts app.py then fails → auto-rollback restores the git baseline
r = ex.run(
    "python3 -c \"open('app.py','w').write('broken'); raise ValueError(1)\"",
    cwd="/repo",
    auto_rollback=policy,
)
assert r.exit_code != 0 and r.auto_rolled_back

RollbackPolicy{max_consecutive_failures=3 (reserved field), file_damage_check=True}. No snapshot (enable_rollback_snapshot=False) → guard skips. Non-git repo → damage detection failure treated as 0 changes, no rollback.

ARCH-7 — caller owns the circuit breaker (audit 0827): max_consecutive_failures is a reserved field the stateless Executor never reads — it is the threshold the caller (e.g. fusion-code's self-healing loop) reads to trip a consecutive-failure circuit breaker; auto-rollback itself is per-execute, not per-loop. A reference skeleton lives at examples/08_integrate_fusion_code.py (consumes the executor API only; a one-way issue tracks the ExecutorDriver refactor on fusion-code).

Live Telemetry (v1.4 — GPU/CPU UDS broadcast)

The telemetry_stream() generator yields TelemetrySample frame by frame — 10Hz (adjustable interval_ms) process CPU/mem sampling. GPU fields default to None (the executor runs no model, has no GPU handle) and are caller-injected. max_samples>0 ends the stream when reached; dropping the iterator stops the sampling task automatically (channel closes). The Executor is stateless: each call is an independent stream.

from fusion_executor import FusionSandboxExecutor, TelemetrySample

ex = FusionSandboxExecutor()
for s in ex.telemetry_stream(interval_ms=100, max_samples=50):
    print(f"t={s.ts_ms}ms cpu={s.cpu_pct:.1f}% mem={s.mem_mb:.1f}MB")
    # s.gpu_pct / s.gpu_mem_mb default None (serde skip, caller-injected)

TelemetrySample{ts_ms (milliseconds, caller epoch), cpu_pct (single-core multiples), mem_mb (resident memory MB), gpu_pct?, gpu_mem_mb?, task_id?}. Underlying fe-telemetry start_stream(cfg, rt::Handle) spawns the sysinfo sampling task on BLOCKING_RT; 4-layer wiring (fe-telemetry → fe-core → fe-ipc executor.telemetry_stream multi-frame → fe-pyo3 NativeTelemetryIterator → Python generator).

Bidirectional server-push subscription (v1.5 #14)

subscribe() opens a UDS connection to subscribe to a broadcast channel — one subscription, the server continuously pushes notification frames, and the client can concurrently send other requests on the same connection (duplex). Unlike telemetry_stream/execute_stream (request-initiated, single stream then stops): subscription is server-pushed, multiple connections share the same source (fan-out).

from fusion_executor import FusionSandboxExecutor

ex = FusionSandboxExecutor()
# Three channels: telemetry (10Hz CPU/mem) / stdio (cross-connection command chunk+done) / screenshot (periodic capture)
sub = ex.subscribe(["telemetry", "stdio"], interval_ms=100, screenshot_interval_ms=1000)
print(sub.subscription_id)  # "sub-N"
for params in sub:
    print(params["channel"], params["data"])
    if ...:
        break
sub.unsubscribe()  # or sub.close()

The three broadcast sources (fe-ipc BroadcastHub lazy start/stop, 0 subscribers self-exit):

  • telemetry — single executor.telemetry_stream fan-out to all telemetry subscribers (10Hz default, interval_ms adjustable).
  • stdio — execute/execute_stream handlers fan out chunk/done to all stdio subscribers (cross-connection: A subscribes, B runs a command, A receives the push).
  • screenshot — periodic gui_action(Screenshot) sampling fan-out (screenshot_interval_ms default 1000, slower than telemetry); TCC-untrusted → frame data.ok=false/error, no crash (via fe-gui safe wrapper).

Push frame format (server-initiated, no id — JSON-RPC notification convention; the client distinguishes response vs push by presence of id):

  • {"jsonrpc":"2.0","method":"executor.event","params":{"subscription_id":"sub-1","channel":"telemetry","data":{...}}}

Subscription is a pure-Python UDS client — connects to the running serve() socket; __next__ filters executor.event frames matching this sub_id, skips non-event frames; unsubscribe() sends unsubscribe + closes the socket. SUB_CHANNELS = ("telemetry", "stdio", "screenshot") — unknown channel → ValueError. fe-ipc adds 0 new unsafe (screenshot reuses fe-gui safe wrapper); fe-core Executor stays stateless (broadcast fan-out is an IPC-broker concern, not executor state).

IPC Service (UDS JSON-RPC)

Start a UDS JSON-RPC 2.0 server — for fusion-code (TypeScript) / fusion-studio (Swift) to call over a Unix Domain Socket:

python -c "from fusion_executor import FusionSandboxExecutor; FusionSandboxExecutor().serve()"
# Socket: ~/.fusion-executor/fe.sock (HOME-private, 0o700 dir; override FUSION_EXECUTOR_SOCK)

Protocol: newline-delimited JSON-RPC 2.0, error codes -32700/-32600/-32601/-32603 + extensions -32010(security)/-32011(timeout)/-32012(rollback)/-32013(AX). Methods: executor.health/execute/execute_stream/snapshot_create/rollback/diagnostics/gui_action/file_edit/glob/grep/grep_with_opts/apply_patch/replace_function/telemetry_stream/subscribe/unsubscribe/shell_start/shell_output/kill_shell/list_shells/shutdown.

executor.execute_stream streaming: multi-frame (chunk/done) sharing one id, newline-delimited frame by frame —

  • chunk: {"jsonrpc":"2.0","id":id,"result":{"type":"chunk","data":"..."}}
  • done: {"jsonrpc":"2.0","id":id,"result":{"type":"done","result":{...ExecutionResult}}} (the UDS path nests done under result.result, DIFFERENT shape from the flattened PyO3 path — the two paths are deliberately separate, each consumer reads its own shape)

executor.telemetry_stream streaming: multi-frame sample sharing one id, newline-delimited frame by frame —

  • sample: {"jsonrpc":"2.0","id":id,"result":{"type":"sample","sample":{...TelemetrySample}}} (params interval_ms (default 100) / max_samples (default 0 = infinite); GPU fields omitted via serde skip when None)

executor.subscribe / executor.unsubscribe (v1.5 #14 bidirectional server-push) — see the "Bidirectional server-push subscription" section above. subscribe response {ok:true, subscription_id:"sub-N"}, then the server continuously pushes notification frames (no id, method:"executor.event"); the connection is duplex, other requests can be sent concurrently. params channels (["telemetry","stdio","screenshot"]) / interval_ms (default 100) / screenshot_interval_ms (default 1000).

The fusion-code TS client sketch is in docs/ipc-client-typescript.md; fusion-studio uses the existing IPCClient.swift udsCall pointed at the same socket.

Guard Integration (v0.2.6 — Issue #23 Phase 3)

fusion-executor is the execution-side consumer of the fusion-guard zero-trust action-authorization daemon (a separate per-host UDS service, /tmp/fusion-guard.sock, Phase 0-2 complete). Before each command runs, the executor asks guard for an allow/preview/redact/block verdict + risk level L1-L4, then executes / rejects / forwards the guard_action_id for caller audit.

Guard is OFF by default (backward-compatible with v0.2.5 — the static blocklist regex + whitelist fence still applies). Enable it explicitly:

from fusion_executor import FusionSandboxExecutor

# Explicit guard socket + tenant
ex = FusionSandboxExecutor(guard_sock="/tmp/fusion-guard.sock", guard_tenant="default")

# Or via env vars (FUSION_GUARD_SOCK / FUSION_EXECUTOR_TENANT)
# FUSION_GUARD_SOCK=/tmp/fusion-guard.sock python -c "..."

r = ex.run("echo hi")  # guard Allow L1 -> exit 0, guard_action_id=None
r = ex.run("rm -rf /")  # guard Block L4 -> blocked_by_security=True,
#                     guard_action_id="<uuid>" set, NOT executed
  • guard_action_id: str | None on ExecutionResult — guard sets a uuid action_id when it judges Block/L3; forwarded 4-layer for caller audit / human-confirm loop. None when guard is OFF or verdict is Allow/L1/L2.
  • Verdict mapping — action==Block OR risk_level==L4 → block (carries risk_level/action_id/seatbelt_required); risk_level==L3 (requires_approval) → block (executor has no human-approval loop, L3 treated as reject, still emits action_id); action==Redact → block (executor runs whole commands, no half-redact); action==Preview → allow but requires_approval=true passed through; action==Allow + L1/L2 → allow, passes risk_level/seatbelt_required.
  • Seatbelt gating (E7) — if guard says seatbelt_required=true and the caller's req.seatbelt != true, execute_async/execute_streaming reject at entry (exit -1, no spawn). Prevents degrading a high-risk command to a non-sandboxed run.
  • Pre-exec TOCTOU recheck (H4) — after validate(), before sandbox.run, fe-core calls fe-security::recheck_binary(first_token): reuses resolve_binary_path (same trusted_bin_dirs, ARCH-2) + std::fs::symlink_metadata (safe Rust, no libc/unsafe) to reject a symlink that newly appears in the validate→spawn window. Homebrew /opt/homebrew/bin/x → Cellar symlinks are by-design allowed (not a symlink at resolve time); only a path that becomes a symlink after validation is blocked.
  • Degraded fail-closed (guard down) — if guard is unreachable / times out, the executor never fails open:
    1. cached regex rules (run_cached_rules) hit a block pattern → block;
    2. no cache hit → falls back to the existing validate() whitelist fence (non-whitelisted binary → block);
    3. allow_inline_interpreter==true + cache empty/unavailable → block inline forms outright (no guard = can't assess risk, fail-closed);
    4. whitelisted binary → allow but WARN-logs "guard down, degraded, risk level unknown" (never wider than guard-live). The degrade path cannot locally reproduce guard's full verdict (tokenizer/AST/semantic stages live inside guard), only the regex stage — so degrade is stricter, not looser.
  • R4 conflict resolution (compile-time static fallback) — Issue #23 R4 ("retain DANGEROUS_BINS compile-time static fallback") conflicts with the 0827 A-12 audit that deliberately deleted that const. Resolution: the existing fe-security static build_blocklist() regex danger patterns + WHITELIST are the compile-time fail-closed fence; together with cached regex rules they form the guard-down fallback, satisfying R4's safety intent. The deleted DANGEROUS_BINS const is not reintroduced.
  • Cross-project boundary — fusion-guard is read-only: the executor only consumes guard's UDS wire contract, mirrors wire types locally in crates/fe-guard, does not edit fusion-guard source or file guard PRs. guard_tenant must match a tenant bound to the executor's OS identity (UID) in guard's config, else every evaluate returns -32001 (auth failure) → fail-closed block (not degrade — degrading on auth failure could open a door).
  • Guard lifecycle — cd /Users/dahai/fusion/fusion-guard && ./start.sh start|stop|status|doctor (build target/release/fusion-guard first via cargo build --release; sock /tmp/fusion-guard.sock).

Deterministic Tool Selection (v0.2.14 — Issue #46)

Replaces LLM-generated tool call JSON with laya-mlx choice primitive for deterministic tool selection. laya selects the best tool from a whitelist in ~5-7ms (warm), outputs structured choice + confidence — no malformed JSON, no hallucinated tools. Two backends: Python API (default, direct laya_mlx.Agent.system_one()) and HTTP (backend="http", calls fusion-mlx POST /v1/laya/decide).

from fusion_executor import LayaToolSelector, AgentLoop

# Python API backend (default) — direct laya_mlx call, warm 5-7ms, no endpoint dep
selector = LayaToolSelector(min_confidence=0.7)
decision = selector.decide("edit src/auth.py to add rate limiting")
# → ToolDecision(tool_id='file_edit', confidence=0.94, params={'file_path': 'src/auth.py'}, ...)

# HTTP backend — calls /v1/laya/decide (AC1), no local laya_mlx/model needed
selector = LayaToolSelector(backend="http", min_confidence=0.7)
decision = selector.decide("edit src/auth.py to add rate limiting")

# Low confidence (<0.7) → fell_back=True, tool_id='llm_fallback' (caller routes to LLM)
# tool_id='none' → no tool needed (skip tool calling, direct LLM response)

# AgentLoop wired through executor (AC7 production path)
from fusion_executor import FusionSandboxExecutor

ex = FusionSandboxExecutor()
result = ex.agent_run("run pytest tests/", max_steps=8)
# → {steps: [...], completed: bool, final_tool: str, step_count: int, metrics: dict}
  • Two backends — backend="python" (default): direct laya_mlx.Agent.system_one(), warm 5-7ms, no upstream endpoint dependency. backend="http": calls fusion-mlx POST /v1/laya/decide (satisfies AC1 literally), no local laya_mlx install or model cache needed — suited for remote / multi-node deployments. Config via fusion_core.config single-point resolution (issue #60, architecture/config-conventions.md): endpoint default_mlx_base_url() (env FUSION_MLX_URL, default http://localhost:11434/v1), auth client_key() (FUSION_CLIENT_KEY, migration-period aliases accepted with a deprecation warning; dev missing key = empty + warning, prod missing key = RuntimeError — no hardcoded secret defaults). Explicit mlx_url/api_key constructor kwargs override env resolution.
  • Configurable whitelist — DEFAULT_TOOL_WHITELIST (8 tools: code_search/file_edit/shell_exec/write_file/web_fetch/rag_query/gui_action/none); pass custom whitelist dict per workflow.
  • Parameter slot extraction — decide() = select_tool() + extract_params(). laya noul (yes/no) + score (0-N) questions determine if a parameter is present; regex extracts the value (Rule 5: deterministic, not LLM). Natural-language fillers are stripped deterministically (issue #54): "run the command echo hi" → command="echo hi" (regex skips the/a/following (command|cmd):? prefixes + _strip_filler_prefix safety net); extraction is anchored per-line (re.MULTILINE) so step-2+ result feedback text in the agent-loop conversation cannot pollute extracted params. No content slot for write_file/file_edit by design — laya 421M is a classifier, not a generator; edit content is supplied by the caller/LLM (params only carry file_path).
  • Confidence gate — uses max probability (answer_confidence when present, else max(probabilities)), NOT entropy confidence (laya-mlx docs: entropy "not calibrated", doesn't transfer across option counts). <0.7 → fell_back=True, tool_id='llm_fallback'.
  • AgentLoop (AC7) — wired into FusionSandboxExecutor.agent_run() — the production path: executor.agent_run(request) constructs a LayaToolSelector + AgentLoop internally and runs build context → laya select tool → execute via self (the sandboxed executor) → feed result back → repeat. Tool→executor mapping is deterministic (shell_exec→run(), code_search→grep(), gui_action→gui_action()); web_fetch/rag_query via injected extra_handlers. Terminates on tool_id="none" (no tool needed), low-confidence fallback (caller routes to LLM), same-tool-same-params repeat (task complete / no progress — laya 421M has no explicit "done" primitive), or max_steps bound (default 8). Returns {steps, completed, final_tool, step_count, metrics}. Default backend="http" (executor is L4 OS tool, doesn't load local models). UDS exposure deferred — fe-ipc is pure Rust (no Python callback); laya is a Python dep. Cross-process callers use the Python API directly.
  • Metrics — selector.metrics() returns {total, fell_back, fallback_rate, avg_latency_ms, per_tool}; loop.metrics() returns {steps, none, fallback, exec_errors, exec:<tool>, same_tool_terminate}.
  • Acceptance (honest) — AC8 latency <15ms ✓ (both backends in proper env): HTTP backend p50=6.2ms (production default, fusion-mlx server-side warm model); python backend p50=7.2ms (in-process MLX eval, fusion-mlx stopped — Metal device uncontended). Caveat: python backend inflates to ~110-140ms when fusion-mlx runs (MLX Metal device multi-model contention — not laya latency, device-level resource contention). Under concurrent load, prefer backend="http" (server-side warm model, unaffected by caller-side device contention); tests skip when contention detected. AC9 structural integrity 12/12 (100%, ≥99.9% ✓ — per AC parenthetical "no malformed output — laya outputs structured data"). Metric definition (PRD "99.9% tool execution success") = structural integrity (zero malformed outputs), NOT accuracy — accuracy 11/12 (91.7%) is a model-quality metric, NOT AC9-gated — laya 421M is not a perfect classifier; the 1 miss (conf 0.45 < 0.7) falls back to LLM in production. AC12 LLM baseline (Qwen3.5-4B): 91.7% accuracy, 91.7% structural integrity (free-text parse risk), p50=477ms — laya 77x faster, structural integrity 100% vs LLM 91.7%. Committed evidence: benchmarks/results/laya-tool-selection/report.json (backend field labeled). Benchmark: python scripts/bench_laya_tool_selector.py --backend http --compare-llm. Examples: examples/09_laya_tool_selector.py, examples/10_agent_loop.py.

Shared Batch-Task Service (v0.2.19 — Issue #57)

TaskManager is a shared async batch-task service for any business app under ~/fusion/business (first consumer: ai-speech-exam, replacing its interim local SQLite queue — gap item G5). Submit a batch job, get a task_id, poll status/progress, read the result — without each app building its own SQLite queue + worker pool.

  • Pure-Python layer (same pattern as agent_loop.py / laya_tool_selector.py) — the Rust Executor stays stateless (M-ARCH-1). In-process library, no new port/daemon: the trust boundary is the process boundary; host apps do their own fusion-identity auth (they already hold service credentials), and executor keeps its no-httpx design.
  • State machine — queued → running → done/failed/cancelled. Failure with retries left → back to queued with next_retry_at backoff (RetryPolicy: max_retries, exponential backoff_initial_sec × multiplier^(n-1) capped at backoff_max_sec). Full policy is persisted as retry_json so backoff params survive restart.
  • Two task kinds — submit_shell(command, ...) runs through the executor's background-shell path (shell_start/shell_output/kill_shell), so the security guard, seatbelt and kill-tree semantics all apply, and running tasks are cancellable + timeout-enforced; submit_async(factory, ...) runs an in-process coroutine (LLM batch calls etc.). Async factories are closures — after a process restart they fail fast with async factory lost (process restart) (shell tasks resume normally).
  • Live progress — shell tasks emit TASK_PROGRESS: 0.42 (0..1) on stdout, parsed into TaskStatus.progress; async factories optionally take a report_progress(p) callback (injected when the signature accepts an argument).
  • Persistence — SQLite at <data_dir>/tasks.db; survives restart. status() / list_tasks(state) / result() / export(task_id) (per-task JSON) / export_report() (all-tasks report with state counts) — result exports land in <data_dir>/exports/.
  • Cancel — queued tasks cancel instantly; running shell tasks get killed (process-tree kill via kill_shell); running async tasks get Task.cancel().
from fusion_executor import TaskManager, RetryPolicy, TaskState

tm = TaskManager("data/tasks", max_workers=4, poll_interval_sec=0.1)
await tm.start()
task_id = tm.submit_shell(
    "python3 batch_generate.py --all",
    name="bulk-generate",
    timeout_sec=600,
    retry=RetryPolicy(max_retries=2, backoff_initial_sec=1.0),
)
st = tm.status(task_id)  # TaskStatus: state, progress, attempts, failure_reason, result
while st.state in (TaskState.QUEUED, TaskState.RUNNING):
    await asyncio.sleep(0.5)
    st = tm.status(task_id)
if st.state == TaskState.DONE:
    print(tm.result(task_id))  # {"exit_code": 0, "output": "..."}
await tm.stop()
tm.close()

Example: examples/11_task_service.py.

Operations (运维)

Operability surface landed in the 0826 enterprise audit fix pass (C-OPS-01..06, C-SEC-02, C-SEC-03):

  • Structured logging (C-OPS-01 + M-OPS-01) — serve() initializes a JSON-structured tracing subscriber in fe-ipc::logging with dual output: a daily-rotating file (fe.log.YYYY-MM-DD, via tracing-appender) tee'd to stderr. Log dir resolves FE_LOG_DIR env → ~/.fusion-executor/logs/ (private under $HOME); if the dir is unwritable it degrades to stderr-only (never crashes). Each line is one JSON object: {"timestamp","level","fields":{"message",...},"target"} — machine-parseable, no ANSI. Default filter is info, overridden by RUST_LOG (e.g. RUST_LOG=info,fe_security=debug). The EnvFilter is runtime-reloadable via FilterHandle::reload_log_filter(directive) (basis for SIGHUP config reload, m-OPS-02): bad directives are rejected fail-loud (current level unchanged). Init is idempotent (OnceLock); the WorkerGuard is held in a static so the non-blocking file buffer always flushes on exit. Key paths (execute / execute_streaming / rollback / each IPC dispatch arm) carry spans with task_id / command / exit_code / duration.
  • Metrics (C-OPS-05b + M-OPS-02) — two surfaces:
    • executor.metrics UDS method returns a JSON snapshot: counters exec_total / exec_success / exec_blocked / exec_timeout / rollback_total + gauge/histogram execute_duration_sec_avg / stdio_bytes_total. Python wrapper FusionSandboxExecutor.metrics().
    • executor.metrics_prometheus UDS method returns Prometheus text-format (# HELP / # TYPE headers + fe_exec_total / fe_exec_success / fe_exec_blocked / fe_exec_timeout / fe_exec_failed / fe_rollback_total / fe_rollback_failed counters and fe_shell_active / fe_connections gauges). The metrics-crate recorder is installed once, idempotently (OnceLock); metrics::describe_counter!/describe_gauge! register HELP/TYPE. No HTTP port is opened (preserves M-SEC-01 UDS-only security) — the caller pulls the text over UDS and feeds its own exporter or dashboard. Python wrapper FusionSandboxExecutor.metrics_prometheus() -> str. Recorder-install failure degrades to a -32603 error (JSON snapshot still available via metrics()).
    • Note: in-process run() / run_async() bypass the IPC layer, so they are not counted in these metrics — only executor.execute over UDS (and shell_start/kill_shell, snapshot/rollback) are tracked.
  • Graceful shutdown (C-OPS-03 / C-OPS-04) — serve() registers SIGINT / SIGTERM → sets a shutdown flag → accept loop stops accepting → in-flight connections get a 10s grace drain (SHUTDOWN_DEADLINE, then remaining aborted) → listener closes. executor.shutdown UDS method triggers the same path. Process exits 0; no orphan socket left on the filesystem. M-OPS-03: the drain deadline is configurable via env FUSION_EXECUTOR_SHUTDOWN_TIMEOUT_SECS (legal 1..=300, default 10; out-of-range/non-numeric falls back to 10 with a WARN).
  • Config hot-reload via SIGHUP (m-OPS-02) — sending SIGHUP to the running server process (kill -HUP <pid>) reloads log level and security whitelist without a restart:
    • Log level: reads RUST_LOG (e.g. RUST_LOG=debug,fe_security=trace); if unset/empty falls back to info. Applied through FilterHandle::reload_log_filter; bad directives are rejected fail-loud (current level unchanged, a WARN is logged). If init_tracing was never called (current_handle() is None) it logs a WARN and skips — never panics.
    • Whitelist extras: reads FUSION_EXECUTOR_EXTRA_WHITELIST — a comma-separated list of extra binaries to allow (e.g. FUSION_EXECUTOR_EXTRA_WHITELIST=jq,gh,make). Reload rebuilds from the baseline whitelist (not accumulate): previously-added extras are discarded, the baseline (python/node/cargo/...) is always present, then the new extras are merged on top. Dangerous interpreters/builtins (sh/bash/zsh/exec/eval/sudo/...) are rejected by DENY_EXTEND. Empty/unset env → pure baseline (clears any prior extras). Implemented via ArcSwap<HashSet<String>> interior mutability in SecurityGuard so Executor stays stateless per-task (M-ARCH-1): store takes &self, load() is a lock-free read — no &mut self ripples through validate call sites.
    • SIGHUP is reload-only (never shuts the server down — that stays SIGINT/SIGTERM). Both the serve() async path and serve_blocking spawn a dedicated handle_sighup_reload loop, aborted on accept-loop exit.
  • Health probe (C-OPS-05) — executor.health is a real probe, not hardcoded: tries git --version (deps), probes AXIsProcessTrusted() (AX), returns ok from the probe result plus a dependencies: [{name, ok}] substructure. Stop git and health reports ok:false, dependencies.git:false. M-OPS-04/M-OPS-05: health also returns a depth object — connections (active UDS conn count), workers (BLOCKING_RT worker threads), active_shells / max_shells (256), mem_mb (process RSS via sysinfo) — for ops dashboards / load balancers. A WARN is logged when active_shells reaches 80% of max_shells.
  • Version / build info (C-OPS-06) — build.rs injects git_sha (first 8) + build_time + version at compile time; health returns them. __version__ reads the injected value (no drift from Cargo.toml).
  • Background shell hygiene (C-OPS-02) — ShellRegistry caps at 256 shells (reaps finished oldest-first over the ceiling) and Drop drains active shells via kill_tree, so a serve() exit (signal/crash) leaves no orphan processes.
  • Process supervision via launchd (D6-01) — serve() writes a pidfile to ~/.fusion-executor/fe.pid (override via FUSION_EXECUTOR_PIDFILE), in the same HOME-private 0o700 dir as the socket; ops can kill $(cat ~/.fusion-executor/fe.pid) or kill -HUP for the SIGHUP config reload above. For crash-restart supervision, an opt-in macOS launchd LaunchAgent template ships at scripts/launchd/com.fusion.executor.plist — not auto-installed (Rule 2): the operator edits the YOUR_USER/venv-path placeholders, copies it to ~/Library/LaunchAgents/, and runs launchctl load. It sets RunAtLoad + KeepAlive (crash restart) + ThrottleInterval=10s (no spin-restart) and redirects stdout/stderr to ~/.fusion-executor/logs/launchd.log. Validate the plist with plutil -lint scripts/launchd/com.fusion.executor.plist before loading. This is a template — edit paths/env to match your install first.

Security Model (威胁模型边界)

fusion-executor is a single-user, local-first, trusted-caller execution tool — a human author writes the commands, the executor enforces a defense-in-depth guard. It is not a multi-user / untrusted-agent sandbox; for that, layer macOS seatbelt (C-SEC-02) + UDS auth on top.

  • seatbelt governance (ARCH-1) — macOS sandbox-exec isolation is default-on for the execute path (run() / executor.execute): the ExecutionRequest.seatbelt serde default is true, and fe-pyo3 run() resolves seatbelt.unwrap_or(true) to match. A trusted local caller may pass seatbelt: false to opt out (must document the escape risk). executor.health exposes seatbelt_default_on: true for ops audit. Note: the long-running background-shell path (shell_start) keeps seatbelt: false as its default — background tasks rely on caller-driven kill_shell, not the sandbox heartbeat.
  • env injection (C-SEC-01) — env_vars is denylist-filtered (blocks DYLD_INSERT_LIBRARIES / LD_PRELOAD / LD_LIBRARY_PATH and similar escape vectors) and capped at 64KB. inherit_env is opt-in (default off → clean baseline PATH only), so a caller cannot smuggle injection libs via the host environment.
  • read-path sensitive blocklist (C-SEC-03) — reading credential files is blocked at two layers:
    • shell read commands (cat / grep / head / tail / less / more / bat / rg) — path-prefix check rejects ~/.ssh/*, /etc/*, /System/*, etc., plus a filename-pattern check rejects id_rsa* (private keys, .pub allowed), *.pem, *.key, *.p12, *.pfx, *.keystore, *.htpasswd anywhere (cwd-relative or absolute).
    • native file tools (file_edit / grep / glob / apply_patch / replace_function / multi_edit / notebook_edit) — guard_path applies the same filename-pattern blocklist on the read branch (file already exists); creating a new cert.pem is allowed (write, not read of an existing secret).
    • Threat-model boundary (explicit, audit §4): python -c / node -e inline-code execution bypasses the file-audit whitelist semantics — the interpreter is whitelisted (runs script files), -c/-e turns args into arbitrary code, and regex cannot enumerate every dangerous one-liner. This is an accepted tradeoff under the trusted-caller model (the human author writes the command; 56 tests rely on python3 -c). Enterprise multi-user / agent-driven deployments must stack seatbelt (C-SEC-02) + UDS auth (M-SEC-01) for defense in depth, not block -c here (which would break the sandbox test mechanism).
    • Deferred (documented): cwd-outside reads via an explicit allow_outside_cwd: true opt-in (audit AC) is not yet wired — under the trusted-caller model cwd-external reads are bounded by the caller, and the opt-in is an enterprise hardening knob deferred to a follow-up. The filename blocklist + prefix check above satisfy the literal AC today (grep/glob/file_edit reading ~/.ssh/id_rsa → blocked).

Status

  • P1 — Skeleton + Security + Sandbox ✅ complete

    • fe-security: regex blocklist + tokenizer chain-bypass defense + whitelist (38 unit tests)
    • fe-sandbox: PTY exec + timeout kill + truncation + OOM ring buffer (9 unit tests)
    • fe-core: validate → sandbox → return pipeline
    • fe-pyo3: execute_sync binding; maturin develop works; FusionSandboxExecutor.run("echo hi") works
    • Exit gate: real exec of echo/python; blocks rm -rf //sudo chain/ncat; 1s timeout kills infinite loop (exit -124)
  • P2 — Diagnostics + Rollback ✅ complete

    • fe-diagnostics: 8 languages (Python/TS/Node/Bun/Rust/Go/Swift/Go-compile) traceback regex extraction + ±20-line code slice, error line marked > (12 unit tests)
    • fe-rollback: git CLI snapshot/rollback — snapshot_create (stash create/HEAD) + rollback (checkout + stash apply) + rollback_file single-file (3 unit tests)
    • fe-core: pipeline adds snapshot (pre-exec, non-fatal) + diagnostics slice (when exit_code!=0) + public snapshot_create_async/rollback_async
    • fe-pyo3: NativeDiagnostics + diagnostics field + snapshot_create/rollback methods; env_vars/enable_rollback_snapshot passed through
    • Exit gate: run("python3 -c 'raise ValueError'") → diagnostics.error_type == "ValueError"; rollback round-trip restores a corrupted file
  • P3 — IPC Service ✅ complete

    • fe-ipc: UDS JSON-RPC 2.0 server — tokio::net::UnixListener + newline-delimited + per-connection spawn; socket ~/.fusion-executor/fe.sock (HOME-private 0o700 dir, override FUSION_EXECUTOR_SOCK), unlink stale sock + chmod 0o666
    • Methods: executor.health/execute/snapshot_create/rollback/diagnostics/gui_action(P4 stub)/shutdown; error codes -32700/-32600/-32601/-32603 + extensions -32010..-32013
    • fe-pyo3: NativeExecutor.serve(sock_path=None) binding; FusionSandboxExecutor.serve() wrapper runs forever
    • 4 Rust unit tests (health/unknown -32601/malformed -32700/UDS execute) + 5 Python IPC tests (health/execute/diagnostics/unknown/snapshot+rollback round-trip)
    • Exit gate: external raw-socket client calls executor.execute echo over UDS → exit_code=0 stdout="hi\n"; fusion-code-style TS client sketch in docs/ipc-client-typescript.md; fusion-studio uses existing IPCClient.swift udsCall pointed at ~/.fusion-executor/fe.sock
  • P4 — macOS GUI ✅ complete

    • fe-gui: accessibility 0.2 safe wrapper (AXUIElement tree/focus/click/type/inspect) + 3 audited unsafe FFI blocks (AXIsProcessTrusted + AXValueGetValue ×2); CoreGraphics CGDisplay::screenshot → PNG base64 (Layer B vision fallback)
    • GuiAction (tag=kind, snake_case): focus_app/click/type_text/key_press/screenshot/inspect_tree; GuiResult{ok, node_tree, screenshot_png_b64, error}
    • fe-core: gui: GuiController field + gui_action() method; fe-ipc executor.gui_action live (not stub); fe-pyo3 NativeGuiResult + gui_action(action) (json.dumps → serde deserialize)
    • Python: GuiResult Pydantic + FusionSandboxExecutor.gui_action(action: dict) -> GuiResult
    • 6 Rust unit tests + 6 Python tests (model roundtrip/key_press degrade/bad-kind degrade/screenshot TCC-skip/UDS roundtrip/bad-kind UDS -32600)
    • Exit gate: trusted machine gui_action({"kind":"screenshot"}) → 3.2MB PNG; gui_action({"kind":"key_press","key":"Tab"}) → ok=False unsupported (v1, fixed in v1.1). GUI tests are TCC-manual (AX Accessibility + Screen Recording)
  • P5 — Hardening ✅ complete

    • criterion benches: Executor::new = 735µs (<5ms NFR ✓); truncate_output ~1.75GB/s (100K=3.9µs / 1M=412µs / 10M=5.7ms); validate 10k compound command = 317ns (regex fast-path blocks rm -rf)
    • truncate_output made pub for bench; ClickCandidate type alias fixes clippy type_complexity; fe-gui redundant as u32 conversions removed
    • Python coverage 95% (>80% NFR ✓): cli.py 96% (in-process main() tests) / executor.py 90% / models.py 100% / init.py 100%; 32 Python tests (+6 CLI +1 async +1 rollback-no-cwd)
    • clippy --all-targets -D warnings clean (only upstream block v0.1.6 future-incompat notice, not fe code); cargo fmt --check + ruff check/format clean; maturin develop --release builds
    • Exit gate: 67 Rust + 32 Python tests green; all NFRs met
  • v1 complete ✅

  • v1.1 — KeyPress support ✅ complete

    • fe-gui key_press: CGEvent synthesis keydown + keyup, post CGEventTapLocation::HID; resolve_keycode maps key names (case-insensitive + aliases: enter=return, esc=escape, up=up_arrow, cmd=command...) → core_graphics::event::KeyCode constants (40+ keys: Return/Tab/Space/Delete/Forward_delete/Escape/arrows/Home/End/PageUp-Down/Help/F1-F20/Command/Shift/Option/Control/Function/Caps_lock/Mute/Volume)
    • core-graphics 0.24 safe wrapper encapsulates the unsafe FFI (CGEventSource::new / CGEvent::new_keyboard_event / post) — zero hand-written unsafe blocks in this function, reuses the fe-gui crate-level #![allow(unsafe_code)] scope
    • Unknown key name → ok:false + unknown-key: ... error listing known key names (no panic, trusted-independent)
    • +2 Rust unit tests (resolve_keycode mapping / unknown key None) + KeyPress degrade test rewritten; +1 Python test (keypress_when_trusted, TCC-skip)
    • Exit gate: trusted machine gui_action({"kind":"key_press","key":"Tab"}) → ok=True (keydown+keyup posted); {"key":"return"} → ok=True; unknown key → ok=False unknown-key. 69 Rust + 33 Python tests green
  • v1.2 — Streaming + Modifiers + Screenshot dimensions ✅ complete

    • Live stdio streaming (4 layers): fe-sandbox run_streaming (mpsc StreamEvent::Chunk{data}/Done(SandboxResult)) → fe-core execute_streaming async (validate→snapshot→run_streaming→spawn task forwards chunks, on Done runs diagnostics slice and maps to ExecutionResult; ExecutionStreamEvent serde tag="type") → fe-ipc executor.execute_stream (multi-frame NDJSON, id reused, chunk {type,data}/done {type,result:{ExecutionResult}}) → fe-pyo3 NativeStreamIterator (__iter__/__next__ via py.detach + BLOCKING_RT receives frames + serde→json.loads) → Python run_streaming generator
    • Modifier combos (KeyPress): key single key name + modifiers array (cmd/ctrl/alt/shift/fn); sequential synthesis — keydown modifiers→keydown key→keyup key→keyup modifiers (CGEvent flags); single key only, no chord
    • Screenshot dimension metadata: GuiResult adds screenshot_width/screenshot_height (u32, PNG pixels); fe-gui fills from CGImageRef width/height
    • +12 Rust tests (fe-core execute_streaming 4: echo/blocked/timeout/diagnostics; fe-ipc 2: stream chunks/done over UDS, blocked single frame) + 5 Python tests (streaming echo/blocked/timeout/diagnostics, UDS stream)
    • Exit gate: 81 Rust + 40 Python tests green; clippy/fmt/ruff clean; maturin builds
  • v1.3 — Data Schema backfill + Native File Tools + Surgical Patch Engine ✅ complete

    • Data Schema §4.1 backfill (Gap #1): ExecutionResult adds task_id/command/duration_sec fields, threaded through 4 layers (fe-core serde struct → fe-pyo3 NativeExecutionResult → Python ExecutionResult Pydantic → fe-ipc done frame backfill). blocked_with carries task_id/command; blocked result duration_sec=0.0
    • fe-tools new crate (Gap #2): file_edit (unique-match exact replace, >1 rejected, atomic write) / glob (wildcard, relative-to-cwd paths, canonicalized-base fix for the relative-path bug) / grep (regex, recursive walkdir, skips binary, 1000 cap). Depends on fe-security validate_cwd path guard (rejects cwd escape / sensitive dirs)
    • Surgical Patch Engine (Gap #3, fe-tools): apply_patch (diffy Unified Diff apply; full-rewrite heuristic new_range.start==0 && end==0 → reject; target taken from patch.modified()/original() with a//b/ prefix stripped) + replace_function (tree-sitter AST locates function node — stack-based preorder traversal fixes the tree-sitter 0.25 Node::children(&mut cursor) borrow issue, no descendants(); py/js/ts/tsx/rs grammars, regex fallback otherwise; byte-slice replace [..span.start]+new_body+[span.end..])
    • 4-layer wiring: fe-core tools: Tools field + 5 wrapper methods (file_edit/glob/grep/apply_patch/replace_function); fe-ipc executor.file_edit/glob/grep/apply_patch/replace_function 5 arms; fe-pyo3 NativeEditResult/NativeGlobEntry/NativeGrepMatch pyclasses + 5 #[pymethods]; Python EditResult/GlobEntry/GrepMatch Pydantic + FusionSandboxExecutor 5 methods
    • clippy fix ExecutionStreamEvent::Done(ExecutionResult) → Done(Box<ExecutionResult>) (large_enum_variant, Done 264B vs Chunk 24B; serde transparent over Box, serialization unchanged)
    • +13 fe-tools Rust unit tests (file_edit unique/no-match/ambiguous/not-found, glob, grep hit/recursive, apply_patch simple/not-found, replace_function python/not-found/rust, guard_path escape) + 12 Python tests (file_edit unique/ambiguous, glob, grep, apply_patch, replace_function python/not-found, file_edit/glob UDS round-trip subprocess pattern)
    • Exit gate: 94 Rust + 52 Python tests green; clippy --all-targets -D warnings clean (only upstream block v0.1.6 future-incompat); fmt/ruff clean; maturin builds
  • v1.4 — Auto-rollback + Live Telemetry + GUI scroll/drag/wait ✅ complete

    • Auto-rollback (FR-04 optional policy, fe-core AutoRollbackGuard + fe-rollback): RollbackPolicy{max_consecutive_failures (reserved field), file_damage_check}; command failure + git status --porcelain non-empty → rollback(本次快照) + result.auto_rolled_back=True; guard limited to a single execution (Executor stateless, consecutive-failure counting belongs to caller); 4-layer wiring (fe-core execute_async/execute_streaming construct guard → fe-pyo3 auto_rollback_policy dict→serde → Python RollbackPolicy Pydantic + run()/run_streaming() kwargs); fe-rollback HEAD-baseline bug fix (when stash SHA != HEAD → stash apply; when equal → skip)
    • Live telemetry (fe-telemetry new crate): TelemetrySample{ts_ms,cpu_pct,mem_mb,gpu_pct?,gpu_mem_mb?,task_id?} + TelemetryConfig{interval_ms=100(10Hz),max_samples=0(infinite)}; start_stream(cfg, rt::Handle) spawns sysinfo sampling task on BLOCKING_RT (refresh_processes_specifics(pid, mem+cpu), first frame sleeps then samples); channel close / max_samples reached → stop; GPU defaults None (caller-injected), serde skip_serializing_if; 4-layer wiring (fe-core telemetry_stream(cfg) → fe-ipc executor.telemetry_stream multi-frame sample → fe-pyo3 NativeTelemetryIterator __next__ block_on(rx.recv) → Python telemetry_stream() generator yields TelemetrySample); never-type fallback fix (explicit TelemetrySample type annotation)
    • GUI scroll/drag/wait (fe-gui CGEvent synthesis): scroll (dx/dy pixels, CGEvent scrollWheel unit axis) / drag (from x,y → to x,y, mouseMove+leftMouseDown+move+leftMouseUp) / wait (seconds sleep, test helper); +14 Rust unit tests + 14 Python GUI tests
    • +3 fe-telemetry Rust unit tests (stream produces samples / channel close stops / serialize) +1 fe-core +1 fe-ipc (UDS telemetry 3 frames) +5 Python auto-rollback tests +3 Python telemetry tests (native iter/wrapper/UDS)
    • Exit gate: 105 Rust + 60 Python tests green; clippy --all-targets -D warnings clean (only upstream block v0.1.6 future-incompat); fmt/ruff clean; maturin builds
  • v1.5 complete

    • #12 — Diagnostics-slicer language expansion (TS/Go) ✅ complete
      • fe-diagnostics Slicer regexes 4→9 covering 8 languages: added ts_re (tsc paren form file.ts(l,c): error TSxxxx:) / ts_dash_re (tsc watch file.ts:l:c - error TSxxxx:) / bun_re (Bun lowercase error: + bare at) / go_panic_re ((?s) cross-line panic: ... goroutine ... \tfile.go:line, takes last stack frame) / go_compile_re (file.go:l:c: msg no error: keyword). Added extract_ts/extract_bun/extract_go_panic/extract_go_compile methods; slice() ordering ts→python→node→bun→rust→go_panic→swift→go_compile (isolated by extension/keyword, no conflicts). Zero new deps (pure-text line slicing)
      • fe-security whitelist +go +tsc (otherwise real go build/tsc --noEmit blocked by Stage-2, no E2E)
      • +5 fe-diagnostics unit tests +1 whitelist test. Real toolchain E2E: tsc 7.0.2 TS2322/bad.ts/line 2 ✓; go build compile error/main.go/line 6 ✓; go run panic panic.go/line 7 ✓. Diagnostics flow automatically through execute→ExecutionResult.diagnostics (when exit_code!=0), no 4-layer wiring
    • #13 — More GUI actions ✅ complete
      • fe-gui GuiAction 9→16 variants: added double_click (ax_label/ax_position, CGEvent 2× LeftMouseDown/Up, second click EventField::MOUSE_EVENT_CLICK_STATE=2) / right_click (ax_label/ax_position, CGEvent RightMouseDown/Up + CGMouseButton::Right) / hover (ax_position, CGEvent MouseMoved no button) / window_close / window_minimize / window_zoom (bundle_id, AX button attrs kAXCloseButtonAttribute/kAXMinimizeButtonAttribute/kAXZoomButtonAttribute → press()) / window_resize (bundle_id + width/height, drag the bottom-right resize handle — read AXPosition+AXSize to compute coords, reuse drag() CGEvent; not AXValueCreate set AXSize, avoids a new unsafe block, stays within the 3 audited unsafe scopes)
      • resolve_click_position helper shared by click/double_click/right_click (ax_position first; otherwise ax_label→AX tree locate reads AXPosition; neither present → error)
      • 4-layer auto-flow: fe-core/fe-ipc/fe-pyo3 dispatch after deserializing the GuiAction enum — new variants flow through with zero wiring (only fe-gui changes enum+execute+methods+tests); Python gui_action(action: dict) is generic with no per-variant logic
      • 0 new unsafe: all via accessibility 0.2 safe wrapper (attribute/press) + core-graphics 0.24 safe wrapper (CGEvent/set_integer_value_field); reuses fe-gui crate-level #![allow(unsafe_code)] scope
      • +5 fe-gui Rust unit tests (serde roundtrip/snake_case/window degrade/pointer degrade/no-target) +2 Python tests (new_variants_degrade CI path / pointer_variants_when_trusted TCC path; _ax_access_trusted() probe separates the TCC Accessibility and Screen Recording permissions)
      • Exit gate: trusted machine hover/double_click/right_click with coords → ok=True (CGEvent posted); window_* needs a real GUI session (AX window tree) and degrades in-sandbox. 116 Rust + 62 Python tests green; clippy --all-targets -D warnings clean (only upstream block v0.1.6); fmt/ruff clean; maturin builds
    • #14 — Bidirectional IPC server-push (subscribe/broadcast) ✅ complete
      • fe-ipc BroadcastHub (Arc-shared) — an IPC-broker concern, fe-core Executor stays stateless (broadcast fan-out does not enter the executor). registry: sub_id → Subscriber{conn_id, channels, tx}; conn/sub counters AtomicU64; telemetry_task/screenshot_task Mutex<Option<JoinHandle>> lazy start/stop (0 subscribers self-exit, next subscribe restarts; source methods take &self not self: Arc<Self> — avoids use-after-move on .take())
      • Connection DUPLEX: handle_conn split into read_task (dispatch requests) + push_task (write server-push frames) sharing Arc<AsyncMutex<OwnedWriteHalf>> (lock for atomic line writes); per-connection mpsc::channel<Value>(128) push frames + oneshot close
      • Three broadcast sources: telemetry (single executor.telemetry_stream fan-out, 10Hz default interval_ms=100) / stdio (execute/execute_stream handlers call hub.broadcast_stdio() to fan out chunk/done — cross-connection A subscribes, B runs a command, A receives the push) / screenshot (periodic gui_action(Screenshot) sampling via spawn_blocking, screenshot_interval_ms=1000 slower than telemetry; TCC-untrusted → frame data.ok=false, no crash, reuses fe-gui safe wrapper)
      • Push frame format: {"jsonrpc":"2.0","method":"executor.event","params":{"subscription_id":"sub-N","channel":..,"data":..}} — no id (notification convention), client distinguishes response vs push by presence of id. collect_targets(channel) try_send outside the lock (snapshot sub_id+tx then release the lock)
      • fe-ipc 0 new unsafe (screenshot reuses fe-gui safe wrapper, crate keeps unsafe_code="deny"). fe-pyo3 unchanged — server-push needs a running server, pure-Python UDS client Subscription connects to the serve() socket
      • Python Subscription pure-Python UDS client: _open() connects+sends subscribe+reads response sets _sub_id; __next__ filters executor.event frames matching sub_id, skips non-event frames; unsubscribe() sends unsubscribe+closes socket; SUB_CHANNELS=("telemetry","stdio","screenshot") unknown channel → ValueError. FusionSandboxExecutor.subscribe(channels, *, sock_path, interval_ms, screenshot_interval_ms) -> Subscription
      • +7 fe-ipc Rust unit tests (subscribe telemetry push frames/missing channels -32600/unsubscribe stops push/stdio cross-connection broadcast + existing health/unknown/malformed/execute/stream) +3 Python tests (subscribe telemetry push frames/stdio cross-connection broadcast/unknown channel ValueError); tests use UnixStream::into_split() → (OwnedReadHalf, OwnedWriteHalf) to avoid borrow-after-move
      • Exit gate: 120 Rust + 70 Python (6 skip TCC) tests green; clippy --all-targets -D warnings clean (only upstream block v0.1.6); fmt/ruff clean; maturin builds
  • v1.5 complete (#12 diagnostics-slicer language expansion + #13 more GUI actions + #14 bidirectional IPC server-push) — 120 Rust + 70 Python (6 skip TCC) tests green; 10 crates; clippy --all-targets -D warnings clean (only upstream block v0.1.6 future-incompat); cargo fmt --check + ruff check/format clean; maturin develop --release builds. Zero new unsafe (#13/#14 both use safe wrappers). Next: v1.6 or as needed.

  • Audit T1–T9 — defect audit (2026-08-24/25) ✅ complete

    • 68 defects across fe-security/fe-sandbox/fe-ipc/fe-tools/fe-rollback/fe-core/fe-pyo3+fe-telemetry/Python layer/fe-diagnostics. All fixed: kill escalation + killpg + deadlock/OOM guards, socket 0o600 + capped-line + semaphore, atomic NamedTempFile write + full-rewrite reject + glob per-hit validate + grep 64MB cap, git reset --hard single-step + tag-prefixed snapshot_id + is_valid_ref, pre/post git-status diff (no false rollback) + streaming abort+timeout + worker_threads(1), wall-clock ts_ms + Drop abort + py.detach GIL release + fail-loud PyRuntimeError + serve signal/cleanup, Subscription GC + stream-test race hardening, tail_lines preserving traceback segment headers + python_re greedy deepest-frame + swift_re extension guard. Commit 36e8790.
  • Audit 0825 — commercial-grade integration audit (2026-08-25) ✅ complete — FAIL → PASS

    • 10 CRITICAL / 23 MAJOR / 4 MINOR. 11 Blockers landed for commercial-grade integration (commit 0341ccb): B1 macOS seatbelt runtime sandbox (sandbox-exec deny network + 13 dangerous binaries), B2 read-path validate_argv + diagnostics-enrich guard, B3 guard_path canonicalize + .. always-reject, B4 rollback path → fe-security, B5 BLOCKING_RT worker_threads(1)→(N), B6 run_streaming cancellable + kill child, B7 read_capped_line chunked + in-loop cap, B8 file tools size cap (64MB) + flock atomic write, B9 rollback registry + FNV-1a repo identifier snapshot_id, B10 stdio per-sub scope filter (cross-tenant isolation), B11 Pydantic extra="forbid" + Rust serde schema sync.
    • 13 MAJOR/MINOR swept (#45): GUI wait GIL release, kill grace 50ms→500ms, truncate byte-offset, partial stdout preserved, exec semaphore, request multiplexing, glob cap+ignore, grep cap(2000)+max_depth(20)+ignore, apply_patch multi-file split + aggregated full-rewrite reject, diagnostics reads stdout (PTY merge), telemetry strict model_validate, replace_function no-grammar fail-loud Err, Subscription configurable idle_timeout, serve(path) resolved-path + version sync.
    • Exit gate: 223 Rust + 113 Python (6 skip TCC) tests green; clippy --all-targets -D warnings clean; cargo fmt --check + ruff check/format clean; maturin develop --release builds.
  • v1.6 — glob/grep ripgrep parity (#7) ✅ complete

    • fe-tools grep extended from content-only to three ripgrep-parity output modes: GrepOutputMode enum (Content default / FilesWithMatches / Count, snake_case, derive Default) + GrepOptions{output_mode, after, before, context, multiline, glob_include, glob_exclude} + GrepOutput{output_mode, matches, files, counts} + GrepFileCount{path, count}; GrepMatch gains context_before/context_after context lines
    • 5 gaps filled: (1) files_with_matches mode (rg -l), (2) count mode (rg -c), (3) context lines -A/-B/-C (context=max(A,B), content mode only), (4) multiline (rg -U) whole-file buffer re.find_iter + RegexBuilder.multi_line().dot_matches_new_line() (gotcha: multi_line only affects ^/$ anchors, . crossing \n needs explicit dot_matches_new_line), (5) glob include/exclude (rg -g) via globset::GlobSet
    • glob() gitignore-aware: old glob::glob ignored .gitignore → switched to ignore::WalkBuilder with require_git(false) (gotcha: default require_git=true only honors .gitignore inside git repos; fusion sub-projects are often standalone non-git dirs, must set require_git(false) to honor .gitignore in bare dirs); IGNORED_DIRS hard baseline + add_custom_ignore_filename(".venv") prevent 100k-entry OOM
    • New deps: ignore 0.4 (gitignore-aware WalkBuilder) + globset 0.4 (glob include/exclude). guard_path returns the literal joined path (cwd.join(".") = /var/.../. with trailing /.), not canonicalized → walkdir emits /var/..././a.py, strip_prefix fails; fix = per-path let root = canonicalize(&abs).unwrap_or(abs.clone()) used as the walk prefix
    • 4-layer wiring: fe-core grep_with_opts wrapper + re-export GrepOptions/GrepOutput/GrepOutputMode; fe-ipc executor.grep_with_opts arm (manual param_str extract + params.get("opts") serde_json::from_value or default); fe-pyo3 NativeGrepFileCount/NativeGrepOutput pyclass (raw String + to_dict json.loads) + grep_with_opts; Python GrepFileCount/GrepOutputMode/GrepOptions/GrepOutput Pydantic (_STRICT) + FusionSandboxExecutor.grep_with_opts
    • +6 fe-tools Rust unit tests (files_with_matches/count/context/multiline/glob_filter/gitignore) + 7 Python native tests + 1 UDS round-trip
    • Exit gate: 287 Rust + 152 Python (6 skip TCC) tests green; clippy --all-targets -D warnings clean (only upstream block v0.1.6 future-incompat); cargo fmt --check + ruff check/format clean; maturin develop --release builds
  • v1.6 — GUI triple_click/hold_key + diagnostics dead-path cleanup (#12.1/#12.2) ✅ complete

    • fe-gui GuiAction 16→18 variants: added triple_click (ax_label/ax_position, CGEvent 3× LeftMouseDown/Up with EventField::MOUSE_EVENT_CLICK_STATE=1..=3; reuses resolve_click_position) and hold_key (single key name + duration_ms, CGEvent keydown→sleep→keyup; duration_ms capped at 5000ms to prevent hang; unknown key name via resolve_keycode → ok:false, unknown-key: ... degrade, trust-independent)
    • 4-layer auto-flow: fe-core/fe-ipc/fe-pyo3 dispatch after deserializing the GuiAction enum — new variants flow through with zero per-variant wiring (only fe-gui changes enum+execute+methods+tests); Python gui_action(action: dict) generic
    • 0 new unsafe: all via accessibility 0.2 + core-graphics 0.24 safe wrappers; reuses fe-gui crate-level #![allow(unsafe_code)] scope
    • fe-diagnostics dead-path cleanup: deleted _parser_for_ext (underscore-prefixed dead tree-sitter grammar selector; v1 diagnostics uses pure-text line slicing as the production path, AST locate was a P5 reservation never wired) + use tree_sitter::Parser; import + 5 tree-sitter deps (tree-sitter/-python/-javascript/-typescript/-rust) removed from fe-diagnostics/Cargo.toml; regex remains the production path (fe-tools keeps its own live tree-sitter for replace_function — untouched)
    • +3 fe-gui Rust unit tests (triple_click/hold_key tag snake_case + holdkey unknown-key degrade + tripleclick untrusted degrade) +2 Python GUI tests (NEW_VARIANTS_CI +2 variants degrade / triple_click into pointer-when-trusted + new holdkey-when-trusted TCC path)
    • Exit gate: 289 Rust + 153 Python (6 skip TCC) tests green; clippy --all-targets -D warnings clean (only upstream block v0.1.6 future-incompat); cargo fmt --check + ruff check/format clean; maturin develop --release builds
  • v0.2.3 released ✅ — tagged v0.2.3 (annotated), pushed to origin. Enterprise hardening release: 10 CRITICAL + 15 MAJOR + 12 MINOR audit fixes (ops/observability/security/perf) + M-ARCH-1 stateless Executor refactor + structured logging + Prometheus metrics + trace_id + SIGHUP hot-reload + glob E1 spec alignment (#20). All 12 GitHub issues closed. 359 Rust + 184 Python tests green; clippy --all-targets -D warnings clean; fmt/ruff clean; maturin builds.

  • Audit 0827 — adversarial hardening pass (2026-08-27) ✅ complete — branch fix/audit0827-p0-p3 from deae2c3 v0.2.3. 6-way adversarial audit found 18 CRITICAL (C-1..C-18) + 18 LOGIC-BUG (L-1..L-18) + 12 ARCHITECTURE (A-1..A-12) + 7 PERFORMANCE (P-1..P-7) + 12 MAINTAINABILITY (M-1..M-12) = 67 findings; all P0-P3 landed across 12 crate-cluster tasks (#94-#105). Highlights: C-1 &/redirect security-bypass closed (tokenizer treats & as compound-separator, not background), C-14/C-15 setsid+kill_tree process-tree reaping (no orphan zombies), C-16 seatbelt SENSITIVE_FS_PATHS file-write deny (best-effort, Darwin 25 global file-write* degraded), C-8/C-9/C-10 IPC resource leaks (rx-drop abort + saw_done guard + graceful shutdown), C-17 ReDoS cap (regex compile timeout + length cap), C-18 symlink TOCTOU (canonicalize-on-open), C-11/C-12/C-13 GUI authorization scope (TCC-separated Accessibility vs Screen Recording probes), fe-telemetry pid field + tx.is_closed() hang fix (process-gone infinite loop → break), fe-shell kill_grace_ms 4-layer + reader catch_unwind + kill/join outside lock, fe-rollback RollbackOutcome{applied,skipped_reason,wip_sha} fail-loud, Python Subscription._buf 8MB OOM cap + native-import warn + CLI _validate_paths startup fail-fast + run_streaming unknown-frame debug log. 419 Rust + 190 Python (1 skip TCC) tests green; clippy --all-targets -D warnings clean (only upstream block v0.1.6 future-incompat); cargo fmt --check + ruff check/format clean; maturin develop --release builds. See audit/fusion-executor-audit-0827.md (read-only reference) for the audit baseline.

  • v0.2.4 released ✅ — tagged v0.2.4, merged to main. Enterprise-publishable upgrade: product-readiness audit (audit/fusion-executor-audit-result-product-0827.md, baseline 9b96aeb) 6 real CRITICAL + 33 MAJOR/MINOR + D3-1 inline-interpreter gateway, all landed across 16 batches on branch fix/enterprise-upgrade-0828. Highlights: (1) D3-1 inline-interpreter gateway — python -c / node -e / ruby -e / perl -e blocked by default (enterprise hardening, agent-driven payload risk); opt-in via with_allow_inline_interpreter(true) for trusted-caller. (2) ARCH-1 seatbelt default True — 4-layer alignment (Rust serde default_true + executor.py run/run_streaming/shell_start + Pydantic ExecutionRequest.seatbelt), drift-assert test locks it. (3) ARCH-2 resolved-path whitelist — binary basename check + absolute-path starts_with(trusted_bin_dirs) (rejects /tmp/python3 same-name poisoning), venv bin auto-registered. (4) D3-4 per-task RSS watchdog — sysinfo poll child process-tree RSS, OOM kill (exit -124, oom_killed=true) since Darwin RLIMIT_AS no-op. (5) RUN-3 stream/exec semaphore split — 16 concurrent execs + 64 concurrent streams, long streams no longer starve short commands. (6) IMPL-7 prompt-injection sanitize — single chokepoint sanitizes file_path/raw_trace/error_type (newline-split, inject-pattern neutralize, size caps). (7) D4 perf — LazyLock profile cache + 16KB read buffers + broadcast fast-path + exec_sem gauge + worker clamp(2,8). (8) ARCH-3 integration skeleton — examples/08_integrate_fusion_code.py + one-way issue on fusion-code (ARCH-7 caller circuit-breaker documented). (9) fe-pyo3 first Rust unit tests (D1-1 From-conversion coverage). (10) docs: default socket ~/.fusion-executor/fe.sock, default bundle allowlist (Terminal/TextEdit/Finder), screenshot Screen-Recording TCC split, NFS flock warn. Cross-project Issue #23 (fusion-guard Phase 3) deferred — out of scope. 476 Rust + 195 Python (6 skip TCC) tests green; clippy --all-targets -D warnings clean (only upstream block v0.1.6 future-incompat); cargo fmt --check + ruff check/format clean; maturin develop --release builds.

  • v0.2.30 released ✅ — tagged v0.2.30, merged to main. Issue #80 (delivery-artifact builder for the software-factory pipeline, consumer: cowork delivery node → fusion-site delivery card fusion-site#198): ArtifactBundleBuilder + ArtifactBundleConfig (python/fusion_executor/artifact_bundle.py) — docker build + optional push to a configured registry, artifact-manifest.json with registry-verified image tag + digest (distribution v2 probe, OCI index Accept for docker 29), sha256 fingerprints of bundled install.sh/readme/deployment manifest, optional openssl signature block (self-verified before shipping), manifest_sha256. Tag byte-identical between artifact record and downstream render (plan ruling A2); no pushed image = no image key (negative path machine-checkable). +12 tests incl. live registry:2 E2E.

  • v0.2.29 released ✅ — tagged v0.2.29, merged to main. Issue #78 (English-only source batch 2, monorepo-wide batch in fusion#9): 5778 unmarked CJK lines across 37 source files translated to English — comments, doc comments/docstrings, log/error/panic messages, thiserror strings, security_reason literals, CLI help text; test assertions synced in lockstep. Behavior byte-identical (regexes/seatbelt syntax/git args/wire keys untouched, verified by token-stream diff + full suites). 15 lines keep Chinese under the issue's # i18n: user-facing marker policy (34 FORBIDDEN_ZH detection patterns in validate_docs.py, 2 laya fullwidth-colon regexes, 8 multibyte UTF-8 fixtures). Residual unmarked CJK = 0; all gates green.

  • v0.2.28 released ✅ — tagged v0.2.28, merged to main. Issue #75 (sandboxed code-mode execution backend implementing the harness CodeExecutor protocol, fusion-harness#50): SandboxedCodeExecutor + CodeSandboxProfile (python/fusion_executor/code_executor.py) — model-written Python runs in a child process spawned through FusionSandboxExecutor.run (security guard + seatbelt network-deny-by-default + rlimits + RSS watchdog + timeout over the whole script run); stub-call bridge (namespace maps stub names to real tool callables, child rounds stub calls through an atomic-rename JSON file bridge serviced by the parent); rollback on failure = pre-exec git snapshot + git clean -fd sweep (reset --hard alone leaves untracked files a hallucinated script created; workspace = dedicated scratch checkout); error traceback payload: CodeExecutionError carries the child's full traceback so the harness error loop feeds CodeExecutionError: <traceback> back as the next model message. Weak-model blast radius: hallucinated code caught by sandbox + rollback, never escapes (network deny verified live). Live E2E against the real fusion_harness.code_mode.CodeModeTurn: happy path, error-loop payload contract, outer-loop self-repair, rollback sweep, seatbelt network deny. +15 Python tests (CI hermetic with in-process fakes per the issue). No Rust changes. 529 Rust + 339 Python (3 skip) tests green; clippy/fmt/ruff clean; maturin builds.

  • v0.2.27 released ✅ — tagged v0.2.27, merged to main. Issue #73 (CI efficiency retrofit per meta dahai80/fusion#2): concurrency cancel-in-progress on both workflows (stale macos runs no longer pile up on the capacity-starved runner pool), paths-ignore **.md on ci.yml, cache: pip for the python job. Sharding + nightly tiering assessed and declined with rationale in PR #74. Timing: python job 5:20-6:00 → 3:58, rust 6:00-10:51 → 5:29. Workflows-only; no product code, no test changes.

  • v0.2.26 released ✅ — tagged v0.2.26, merged to main. Issue #69 acceptance item (iOS touch injection) resolved: new inject_touch(session_id, x, y, action="tap"|"swipe", x2, y2, duration_ms) in DemoSessionManager (python/fusion_executor/demo_sessions.py). iOS goes through idb — the XCTest-based UI automation stack — with the executor owning the full companion lifecycle (_ensure_companion spawns idb_companion --udid <udid> --only simulator, parses the grpc port from its log, runs idb connect localhost <port>, _stop_companion tears it down in end_session): without owned lifecycle the idb CLI either reused a stale companion with an invalidated HID connection (dtuhidd connection invalidated) or failed with Failed to connect to companion — both observed live and fixed. Android sessions get symmetric touch via adb shell input tap/swipe. Live E2E verified on a booted iPhone simulator: tap round-trip ~327ms steady state (first tap ~5.3s = HID handshake), swipe verified; not the <30ms fe-gui native target — this is the demo-session remote-injection path via XCTest. Validation up front (action whitelist, non-negative coords, swipe requires x2/y2), [touch] log line with measured latency, missing idb CLI / idb_companion fail visibly with install commands. +6 Python tests (companion-lifecycle covered by live class, gated off CI). No Rust changes. 529 Rust + 339 Python (3 skip) tests green; clippy/fmt/ruff clean; maturin builds.

  • v0.2.25 released ✅ — tagged v0.2.25, merged to main. Issue #69 (demo host streaming + Android kind + metering verification — partial by design, blocked pieces documented): streaming — open_stream(session_id): iOS kind serves an MJPEG stream (stdlib ThreadingHTTPServer + simctl io screenshot snapshot loop to a temp file, bind-wait before URL issuance, idempotent re-open), web kind verifies + returns the demo-app-provided stream page URL (stream_path opt-in, e.g. noVNC vnc.html); explicitly NOT the ~120ms WebRTC acceptance target — iOS touch injection has no public simctl API (needs XCTest stack), MJPEG latency ~0.5-1s (blocked upstream, documented); Android kind — kind="android": Linux demo host + /dev/kvm pre-flight (visible error on non-Linux, never silent), docker --privileged emulator container, adb connect + boot-completed poll (600s) + optional APK install + launch, max_android capacity knob, teardown docker rm -f (data burned); live verification blocked on a Linux+KVM host (code path + preflight tests only); metering — session_cost(session_id) reads the session's own fk- key from 0o700 state and queries gateway GET /v1/cost (own-key scope); live E2E verified end-to-end through the real gateway: demo session → scenario injection → in-container curl (stream mode) → fk- key → /v1/cost shows by_key entry + tokens > 0 → key revoked; gateway gap found + filed upstream (fusion-gateway#639: non-stream chat does not record cost). +12 Python tests. 529 Rust + 321 Python (2 skip) tests green; clippy/fmt/ruff clean; maturin builds. Issue #69 stays open (WebRTC ~120ms + touch round-trip and Android live-verify blocked on platform API/hardware).

  • v0.2.24 released ✅ — tagged v0.2.24, merged to main. Issue #68 (session-scoped demo host orchestration: web compose + iOS Simulator + stub scenario injection; fusion-executor owns session-level demo workload lifecycle, supervisor stays out — long-lived daemons only). New DemoSessionManager + DemoSessionConfig (python/fusion_executor/demo_sessions.py): web kind — per-session isolated docker compose stack (unique project name + port from registered demo range 11600-11669 + healthcheck-gated readiness, reuses PreviewStackRunner.up which gains extra_env passthrough), TTL countdown → teardown + data burned; scenario/stub layer — inject_scenario replays the sample's recorded fixture via docker compose exec, every injection logged [stub] <event> -> fixture (demo path never calls real third-party APIs); iOS kind — xcrun simctl boot + optional install + launch + shutdown, concurrency cap 2, persisted queue with position + ETA + daemon dispatcher, shorter TTL 15 min; per-session LLM attribution — FUSION_LLM_API_KEY (fk- key) + FUSION_LLM_BASE_URL → gateway :11432 (single metering point); get_session/end_session/rollup health badges (healthy/maintenance/unknown); library API (HTTP surface owned by consumer). Live E2E: web up → healthy → scenario injection (stub served + [stub] log) → teardown → cross-session burn verified; iOS 2 sims concurrent + queue position + clean shutdown; ports inside demo range. +9 Python tests (live classes skip w/o docker daemon / xcrun). Deferred upstream (follow-up issue): WebRTC/noVNC streaming, Android emulator container, gateway /v1/cost metering verify. 529 Rust + 321 Python (2 skip) tests green; clippy/fmt/ruff clean; maturin builds. Issue #68 closed (core lifecycle; streaming tracked in follow-up).

  • v0.2.23 released ✅ — tagged v0.2.23, merged to main. Issue #65 (automated sandbox preview stack, companion to fusion-cowork#422 match node; owner-routed: sandbox deployment demo is executor capability). New PreviewStackRunner + PreviewProject (python/fusion_executor/preview_stack.py): per-project compose overlay (ordered compose_files base→overlay + profile), provision = clone (https w/ ssh fallback) / git pull --ff-only, docker compose up -d --build with PREVIEW_HOST_PORT/PREVIEW_SERVICE_PORT env injection, synthetic demo data injection via project-provided seed_cmd through docker compose exec (never real customer data — business rule 6 red line), health-check gate before URL issuance (urllib poll; unhealthy stack auto-torn-down, no URL issued), preview URL http://127.0.0.1:<host_port>/, TTL auto-teardown (daemon timer) + explicit teardown/teardown_all, port-in-use pre-flight probe (fail visibly), state persisted <workspace>/<name>.json, idempotent up, notify hook for readiness notification (email channel owned by consumer — cowork cow#404). Library API only (no CLI) — cowork pipeline consumes. Port isolation: binds 127.0.0.1 unregistered test ports only, no new business ports (check-ports unchanged). Live E2E verified: fixture repo (nginx:alpine + overlay profile) full lifecycle — up → health 200 → synthetic seed file served → idempotent re-up → teardown clean (0 leftover containers); unhealthy auto-teardown verified. +8 Python tests (test_preview_stack.py, live class skips when docker daemon unavailable). No Rust changes. 529 Rust + 300 Python (2 skip) tests green; clippy/fmt/ruff clean; maturin builds. Issue #65 closed.

  • v0.2.22 released ✅ — tagged v0.2.22, merged to main. Issue #64 (demo/test environment sandbox: run ONE ai-* app per guest, LLM calls to host gateway). (1) DemoEnvRunner (python/fusion_executor/demo_env.py) — provision (clone https with ssh fallback, shared venv via sys.executable -m venv, pip install -e when pyproject.toml present), start via the app's own start.sh (missing → visible DemoEnvError + manual-start hint, never silently skipped), up/status/stop idempotent actions, single-app-per-guest policy (second up while running → error; same repo re-up → idempotent, same shell_id), stale-state reuse after stop, host gateway probe (/healthz then /v1/models, stdlib urllib) informational only — app boots even when gateway unreachable. App process runs via shell_start with SandboxProfile(network="allow", filesystem="deny_write") seatbelt + env wiring FUSION_LLM_BASE_URL/FUSION_MLX_URL → host gateway + VIRTUAL_ENV → guest venv. State persisted <workspace>/state.json (atomic write). CLI: --demo-up REPO_URL / --demo-status / --demo-stop (+ --demo-workspace / --demo-llm-url / --demo-env K=V). (2) shell_start gains optional per-shell sandbox: SandboxProfile — 4-layer additive plumb (fe-shell ShellStartParams.sandbox_profile → SandboxConfig, fe-ipc serde param, fe-pyo3 PyAny bridge, Python kwarg; None = byte-identical prior behavior). Live E2E verified: up boots app end-to-end through seatbelt (clone+venv+start.sh whitelisted), env wiring visible in app output tail, status/stop mirror, idempotent up, one-app refusal, no-start.sh visible failure, probe unreachable non-blocking. +10 Python tests (test_demo_env.py) + 2 fe-shell Rust tests; no Rust behavior change when sandbox=None. 529 Rust + 292 Python (2 skip) tests green; clippy/fmt/ruff clean; maturin builds. Issue #64 closed.

  • v0.2.21 released ✅ — tagged v0.2.21, merged to main. fusion docs-system v1.1 adoption + CI unblock. (1) docs-system contract — new docs/ grid (product-page / get-started / api-reference / config-reference / troubleshooting / guides/ / api-protocol-reference), contract frontmatter on existing markdown docs, AGENTS.md, ci/validate_docs.py (frontmatter + link validator, stdlib only), .github/workflows/docs.yml. Grid classification: platform x service. (2) CI runner label — macos-14 → macos-latest (macos-15) in both jobs — unblocks queued jobs on the retired-runner label. (3) fe-security resolved-path check — trust /opt/homebrew/opt/rustup/bin (Homebrew rustup shim dir; macos-15 runner PATH resolves bare cargo there ahead of /opt/homebrew/bin; same trust class as the Homebrew prefix). No API changes, no Python behavior change. 161 fe-security Rust tests green; fmt/ruff clean; maturin builds.

  • v0.2.20 released ✅ — tagged v0.2.20, merged to main. Issue #60 (P1: adopt fusion_core.config single-point config resolution, config Phase 2.2). (1) Single-point key/URL resolution — LayaToolSelector HTTP backend + bench script + AC8 test now resolve via from fusion_core.config import client_key, default_mlx_base_url (explicit api_key/mlx_url kwargs still win); deleted the hand-rolled module-level env reads. Per config-conventions §2/§3: no local _resolve_* copies, no secret default literals — dev missing key = "" + one-time warning, FUSION_PROFILE=prod missing key = RuntimeError. (2) Removed the hardcoded "fg-admin-key" fallback — fusion-mlx accepts anonymous localhost when no server key is configured, and client_key()'s migration alias chain preserves configured-key behavior, so the literal default was dead weight and spec-illegal. (3) Dependency wiring — pyproject.toml adds fusion-core>=0.7.0 (bare constraint, fusion-rag pattern; local monorepo satisfied by shared-venv editable install); CI installs the git pin dahai80/[email protected] before maturin. (4) Scope guard: FUSION_GUARD_SOCK read in executor.py NOT migrated to default_guard_sock() — that helper always returns a path, which would flip the documented guard default ON. +8 Python tests (test_config_resolution.py, no model dependency — runs in CI). Acceptance verified: scripts/check-env.py (workspace root) = 0 non-baseline findings for this repo; grep -rn 'def _resolve.*key' = empty; no behavior change in dev. 528 Rust + 282 Python (2 skip) tests green; clippy/fmt/ruff clean; maturin builds. Issue #60 closed.

  • v0.2.19 released ✅ — tagged v0.2.19, merged to main. Issue #57 (shared async batch-task service, filed by ai-speech-exam gap G5). New fusion_executor/task_service.py: TaskManager + RetryPolicy + TaskState + TaskStatus — submit batch job → task_id, poll status/progress, state machine queued → running → done/failed/cancelled, retry with exponential backoff (full policy persisted as retry_json), failure-reason recording, result export/report JSON, cancel (queued/running shell/running async). Shell tasks run via shell_start/shell_output/kill_shell (inherit security guard + seatbelt + kill-tree, timeout enforced, TASK_PROGRESS: stdout protocol for live progress); async tasks run in-process coroutines with optional report_progress callback (fail fast as async factory lost (process restart) after restart). SQLite persistence at <data_dir>/tasks.db survives restart. Design: pure-Python layer (Executor stays stateless, M-ARCH-1), in-process library — no new port/daemon, no httpx dependency; host apps own fusion-identity auth (process boundary = trust boundary). No Rust changes. +21 Python tests (test_task_service.py); example examples/11_task_service.py verified live. 528 Rust + 274 Python (2 skip) tests green; clippy/fmt/ruff clean; maturin builds. Issue #57 closed. ai-speech-exam has no git repo — the G5 migration (interim queue → TaskManager) is tracked on that project's side, not as a GitHub issue.

  • v0.2.18 released ✅ — tagged v0.2.18, merged to main. Issues #53/#54/#55 (laya E2E follow-ups). #54 (bug) — param extraction passes full prompt as command → security guard blocks: regex skipped no fillers, so "run the command echo hello world" extracted command="the command echo hello world" → guard rejects binary "the". Fix (deterministic, Rule 5): extract regex skips (the|a|an|this|that|following) (command|cmd):? prefixes + _strip_filler_prefix safety net (nested fillers ≤3 layers, real commands untouched); re.MULTILINE line-anchor on _regex_extract — step-2+ result-feedback text in the agent-loop conversation can no longer pollute extracted params (was: $ matched string-end → command grew each round, same-tool termination never fired). Live E2E verified: agent_run('run the command echo hello world') → step 1 executes echo hello world (exit 0), step 2 same-tool-same-params → terminate completed. #53 (enhancement) — closed as already-implemented: repo never used router_questions()/_DOMAIN_TO_TOOL domain mapping (grep-verified) — select_tool passes the tool whitelist directly as laya choice criteria (the issue's proposed fix IS the current design); bench 91.7%/12-case + live 6/7; description-tuning experiment made accuracy worse (shell_exec "run pytest" flipped to none at 0.53) — residual miss is laya 421M model quality. #55 (caveats) — documented: metric definition (PRD "99.9% tool execution success" = structural integrity, accuracy separate), no content slot by design (laya is classifier not generator — caller/LLM supplies edit content), Metal-contention→prefer-HTTP guidance. +3 Python tests (filler-strip + MULTILINE anchor + model-backed decide). 528 Rust + 269 Python (3 skip) tests green; clippy/fmt/ruff clean; maturin builds.

  • v0.2.17 released ✅ — tagged v0.2.17, merged to main. AC8 laya test flaky-skip fix (test code only, no production change): test_warm_latency_under_15ms catches httpx.RequestError (broader than ConnectError — covers TimeoutException/ReadError) + probe timeout 1.0→3.0s; test_http_backend_latency_under_15ms skips when probe status_code != 200 (422/503 during model load was false-failing). Tests still validate AC8 <15ms when environment valid; skips are honest environmental guards.

  • v0.2.16 released ✅ — tagged v0.2.16, merged to main. Issue #46 AC8 latency test honesty fix. Root cause: test_warm_latency_under_15ms (python backend, in-process MLX eval) measured ~110-140ms when fusion-mlx was running — MLX Metal device multi-model contention (fusion-mlx loaded models compete for the same Metal device as the in-process laya eval, inflating latency 15-20x). NOT a laya latency regression — with fusion-mlx stopped, python backend p50=7.2ms (meets AC8 <15ms). v0.2.12 also showed 114ms under the same contention; CI skipped the laya module (no model cache) so never caught. (1) test_warm_latency_under_15ms now detects fusion-mlx running → skip with contention message (isolate AC8 measurement from device contention). (2) Added test_http_backend_latency_under_15ms (AC8 via HTTP, production default, skip if no server). (3) Bench script records backend field + warns when fusion-mlx contention detected. (4) Regenerated benchmarks/results/laya-tool-selection/report.json (backend=http) — laya 91.7%/p50=6.2ms vs LLM 91.7%/p50=477ms. 528 Rust + 260 Python (8 skip) tests green; clippy/fmt/ruff clean; maturin builds.

  • v0.2.15 released ✅ — tagged v0.2.15, merged to main. Issue #46 re-opened (agent loop not wired + 99.9% honesty + missing LLM baseline evidence) — fixed. (1) AgentLoop wired into FusionSandboxExecutor.agent_run() — the production path: executor.agent_run(request, *, max_steps=8, backend="http", ...) constructs LayaToolSelector + AgentLoop internally, runs select→execute(via self)→feedback→repeat. v0.2.14's AgentLoop was a dead class with zero callers in executor.py (violated "不接线不算完成"). Now reachable from the primary public API. Same-tool-same-params termination heuristic added (laya 421M has no "done" primitive — repeated identical decision = task complete / no progress). (2) 99.9% honesty fix — renamed structural_success → structural_integrity (avoid "success" implying accuracy). AC9 99.9% = structural integrity per AC parenthetical "(no malformed output)" — met at 100%. Accuracy 11/12=91.7% is a model-quality metric, NOT AC9-gated; the 1 miss (conf 0.45 < 0.7) falls back to LLM in production. v0.2.14 claimed "all ACs met" ambiguously. (3) LLM baseline actually run + committed — benchmarks/results/laya-tool-selection/report.json: laya 91.7%/p50=5.5ms vs LLM (Qwen3.5-4B) 100%/p50=387ms (laya 70x faster, LLM more accurate — honest tradeoff). v0.2.14 claimed "LLM p50=342ms" with no committed evidence. (4) Whitelist descriptions tuned (shell_exec/code_search/none more discriminative). +5 Python tests (TestAgentRunOnExecutor + same-tool-terminate). Example examples/10_agent_loop.py. 528 Rust + 260 Python (8 skip) tests green; clippy/fmt/ruff clean; maturin builds. Issue #46 AC7 wired (Python API; UDS deferred — fe-ipc is pure Rust, laya is Python).

  • v0.2.14 released ✅ — tagged v0.2.14, merged to main. Issue #46 re-acceptance: HTTP backend (AC1) + AgentLoop (AC7) + confidence fix. (1) AC1 HTTP backend — LayaToolSelector(backend="http") calls fusion-mlx POST /v1/laya/decide (satisfies AC literally), no local laya_mlx install or model cache needed. Env FUSION_MLX_URL (default http://localhost:11434/v1), FUSION_MLX_API_KEY. Python API backend (default) unchanged. E2E verified against live fusion-mlx: choice=file_edit, max-prob=0.92, 33ms. (2) Confidence fix — select_tool now uses max(probabilities) when answer_confidence absent (laya endpoint returns only entropy confidence, "not calibrated"); v0.2.12 wrongly fell to entropy. Matches documented "answer_confidence = max(p)" behavior. (3) AC7 AgentLoop — new fusion_executor/agent_loop.py wires LayaToolSelector into executor pipeline: build context → laya select → execute via FusionSandboxExecutor → feed back → repeat. tool_id="none"/fallback terminates (caller → LLM). Deterministic tool→executor mapping (shell_exec→run(), code_search→grep(), gui_action→gui_action()); web_fetch/rag_query via injected extra_handlers. max_steps bound (8). AgentLoop.run() → {steps, completed, final_tool, metrics}. (4) AC9/AC12 bench — scripts/bench_laya_tool_selector.py expanded: structural success 12/12 (100%, ≥99.9% ✓) + --compare-llm baseline arm (LLM p50=342ms vs laya p50=6.6ms — 52x faster). +15 Python tests (test_agent_loop.py: AgentLoop wiring + HTTP backend mocked/E2E). 528 Rust + 260 Python (1 skip) tests green; clippy --all-targets -D warnings clean (only upstream block v0.1.6 future-incompat); cargo fmt --check + ruff check/format clean; maturin develop --release builds. Issue #46 all ACs met.

  • v0.2.12 released ✅ — tagged v0.2.12, merged to main. Deterministic tool selection via laya-mlx (Issue #46) + CLAUDE.md condensation + 12-crate drift fix. (1) #46 LayaToolSelector — new fusion_executor/laya_tool_selector.py calls laya_mlx.Agent.system_one() directly (Python API, not fusion-mlx HTTP — lower latency, no upstream endpoint dependency). choice primitive selects tool from configurable whitelist (8 default tools) in ~5-7ms warm; answer_confidence (max prob, NOT entropy — laya docs: entropy "not calibrated") gates fallback: <0.7 → fell_back=True, tool_id='llm_fallback'; tool_id='none' skips tool calling (positive decision, no fallback). decide() = select_tool() + extract_params() (noul yes/no + score 0-N questions → regex value extraction, Rule 5 deterministic). ToolDecision Pydantic model (tool_id/confidence/probabilities/params/fell_back/latency_ms/model/usage). Metrics: selector.metrics() → {total, fell_back, fallback_rate, avg_latency_ms, per_tool}. Benchmark: 11/12 correct (91.7%), p50=6.5ms (<15ms ✓). (2) display_info headless skip — test_gui_action_display_info_trusted_independent now skips when 0 active displays (headless/SSH, ok=True + empty list is correct behavior). (3) CLAUDE.md condensed 73KB→25KB (per-version changelog → current-state summary + history pointers; stale architecture/→../architecture/ paths fixed; 12-crate stated; docs/ added to Key Paths). (4) README/docs 10-crate→12-crate drift fixed. 528 Rust + 238 Python (8 skip) tests green; clippy --all-targets -D warnings clean (only upstream block v0.1.6 future-incompat); cargo fmt --check + ruff check/format clean; maturin develop --release builds. Issue #46 closed.

  • v0.2.11 released ✅ — tagged v0.2.11, merged to main. GUI display-capability query + batch mouse-move path (Issues #43/#44). (1) #43 DisplayInfo + scale_factor in inspect_tree — new GuiAction::DisplayInfo{} variant lists all active displays via CGDisplay::active_displays() → JSON array [{id, scale, bounds:{x,y,w,h}, primary}] exposed as additive GuiResult.displays: Option<String> (None for non-display_info results, backward-compatible). Trusted-independent (CGDisplay API needs no TCC). Shared compute_scale_factor() helper (CGDisplay::main().pixels_wide() / bounds().width, clamped ≥1.0) now fills scale_factor in both inspect_tree and screenshot (was screenshot-only), removing hardcoded 2.0 reliance. 4-layer wiring: fe-gui struct + early-return execute dispatch (before ax_trusted gate, trusted-independent) → fe-pyo3 #[pyo3(get)] displays + From → Python Pydantic displays: str | None + construction; fe-ipc/fe-core auto-flow via enum-level serde deserialize+dispatch. (2) #44 MovePath — new GuiAction::MovePath{points: Vec<(f64,f64)>, duration_ms: u64} performs an ordered waypoint path in a single atomic UDS round-trip (avoids N hover round-trips). Linear interpolation, 8 frames/segment CGEvent::MouseMoved, duration_ms pacing (split across segments). <2 points rejected (trusted-independent). focused_not_allowed gate. 0 new unsafe blocks — all new code uses core-graphics 0.24 safe wrappers (CGDisplay::active_displays/new/bounds/pixels_wide/is_main, CGEvent::new_mouse_event) within fe-gui's existing crate-level #![allow(unsafe_code)] scope. GuiAction 18→20 variants. +3 fe-gui Rust unit tests (move_path/display_info serde roundtrip + snake_case, move_path empty/single reject, display_info trusted-independent shape) +3 Python tests (display_info trusted-independent ok=True + displays JSON fields, move_path pointer-when-trusted, move_path <2 points reject). 528 Rust + 231 Python (1 skip TCC) tests green; clippy --all-targets -D warnings clean (only upstream block v0.1.6 future-incompat); cargo fmt --check + ruff check/format clean; maturin develop --release builds. Issues #43/#44 closed.

  • v0.2.10 released ✅ — tagged v0.2.10, merged to main. GUI coordinate-mapping + batch actions + sensitive-region masking (Issues #38/#39/#40). (1) #38 scale_factor coordinate contract — GuiResult.scale_factor: f32 (physical PNG pixels / logical points; Retina=2.0, non-Retina=1.0) bridges the two coordinate spaces: GuiAction x/y inputs + inspect_tree AXPosition = logical points, screenshot_width/screenshot_height = physical pixels. Caller converts pixel = point * scale_factor. Computed from CGDisplay::main().bounds().size.width (logical) vs img.width() (physical). 4-layer wiring (Rust serde → fe-pyo3 #[pyo3(get)] + From → Python Pydantic → fe-ipc done frame serde-flatten). (2) #39 gui_action_batch — sequential multi-action pipeline collecting per-step GuiResult; non-transactional (single-step failure does not abort later steps — caller decides retry/compensate per-step ok). GuiController::gui_action_batch(Vec<GuiAction>) -> Vec<GuiResult> in fe-gui → fe-core wrapper → fe-ipc executor.gui_action_batch arm (manual params extraction) → fe-pyo3 gui_action_batch(&PyAny) (json.dumps → serde) → Python FusionSandboxExecutor.gui_action_batch(actions: list[dict]) -> list[GuiResult] (validates list + each dict has str kind). (3) #40 screenshot sensitive-region masking — GuiAction::Screenshot gains mask_sensitive: bool (serde default false); when true, collect_secure_rects() walks the AX tree (capped by MAX_TREE_DEPTH=8/MAX_TREE_NODES=500) finding kAXSecureTextFieldSubrole elements, reads their AXPosition+AXSize (logical-point rects), then mask_rgba_inplace() converts rects to physical pixels via scale_factor, Y-flips (CGContext origin bottom-left vs PNG/AX top-left), and redacts RGBA to black (0,0,0,255). Gated on ax_trusted() — mask_sensitive=true + untrusted → warn! + skip mask, fail-visible not crash. Screenshot refactor: cgimage_to_png_b64 split into cgimage_to_rgba (CGImage → RGBA byte buffer, M-12.3 premultiplied-α note anchored here) + rgba_to_png_b64 (RGBA → PNG base64) so masking can mutate the pixel buffer between the two steps. 0 new unsafe blocks (reuses the 3 existing fe-gui unsafe blocks; masking is pure-Rust byte manipulation). +7 Rust unit tests (scale_factor serde default, mask_sensitive serde default, mask_rgba full-cover/partial-scale-Y-flip/OOB-clamp, gui_action_batch empty/sequential) + 9 Python tests (scale_factor roundtrip, screenshot mask default/when-trusted, batch empty/sequential/non-list/missing-kind/UDS roundtrip). 526 Rust + 222 Python (7 skip TCC) tests green; clippy --all-targets -D warnings clean (only upstream block v0.1.6 future-incompat); cargo fmt --check + ruff check/format clean; maturin develop --release builds. Issues #38/#39/#40 closed.

  • v0.1.0 released ✅ — tagged v0.1.0 (annotated), pushed to origin. First stable release. See examples/ for runnable demos (Python API 01–07 + TypeScript UDS client) and docs/INDEX.md for the documentation map.

About

Controlled Execution Sandbox + macOS OS-Level Control Hub — Rust + PyO3 Core via Maturin

Resources

Stars

2 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages