Skip to main content

factory-ai

Control plane for the fusion business delivery pipeline: M0 baseline (lead intake, project lifecycle, gates, approvals, readiness, append-only audit log) plus the M1 delivery loop (headless agent dispatch, artifact write-back, costs recording, outbound email drafts + acceptance). One Go binary (factory-ai) exposing a JSON-RPC 2.0 control surface over a Unix Domain Socket only (no TCP port, no listener in the registered port range).

Extracted from the private dahai80-business/business repo (the bizplane daemon) and renamed factory-ai as a standalone public repo; see docs/superpowers/specs/2026-12-02-bizplane-to-factory-ai-design.md for the extraction and rename record.

Architecture

Single process, stdlib + two pinned dependencies (modernc.org/sqlite cgo-free driver, gopkg.in/yaml.v3):

Package Responsibility
cmd/factory-ai Binary wiring: flag/env resolution, dependency construction, graceful SIGINT/SIGTERM shutdown
internal/config Config-root loader (strict YAML, unknown fields fail closed) + validation
internal/store SQLite handle (WAL, foreign keys, 5s busy timeout), embedded forward-only migrations, schema v1
internal/events Hash-chained append-only event log over the events table (sha256 prev_hash chain)
internal/tree On-disk artifact tree under the data root; every path input is containment-checked, never sanitized
internal/lead Lead intake front door: (source, external_ref) dedup, policy snapshot, raw/attachment writes, lead.created event
internal/sm State machine over the declared stage list (S0..S5 linear in M0); overlays running/paused/error/blocked, terminals active/archived/rejected/lost_bid
internal/gates Deterministic gate evaluator: G0, G1, G1b, G2, G3, G4, G5a, G5b — stable artifact row + review verdict + hash-bound approvals + delivery acceptance
internal/approvals Approval request/decide/list; decisions are hash-bound to the payload they approve
internal/readiness P1-P5 probes: config integrity (incl. the P1 email leg), project template, team binding (agent-studio teams.list), outbound dry-run render, platform source status
internal/sidecar Channel-bridge sidecar client + email poller: stdio JSON-RPC transport, respawn-on-next-use failure recovery, IMAP UID-cursor polling into lead.create
internal/connector Platform connector v1 (dormant): OAuth2 client-credentials polling against the contract REST API, per-item cursor in adapters_state, feeds readiness P5 + platform.status
internal/studioclient agent-studio run client: auth bootstrap (loopback key factory-ai-m1), cached JWT with re-login on 401, teams.run_member / teams.run_usage calls with caller-chosen deadlines
internal/dispatch Async run execution: runs row → goroutine (panic recovery, 30 min run deadline) → teams.run_member → artifact write-back to ai-XXXX/docs/ + costs recording
internal/outbound Outbound drafts: RFC-5322 email rendering to <data>/drafts/*.eml, delivery rows (sent_at NULL), acceptance recording — draft-only, no SMTP
internal/report Weekly commercial report: aggregation (per-project stage run counts + token sums + business view: approved quote price, gate counts, delivered), markdown artifact to <config-root>/reports/, red-line check (title must differ from the intake email subject), operator self-send via the sidecar
internal/rpc UDS JSON-RPC 2.0 server: newline-delimited frames, serial per connection, panic recovery, every dispatch logged
scripts/start.sh Service lifecycle start/stop/status/restart; pid + log under <dir>/logs/

Build

go build ./...                                   # compile
go build -o bin/factory-ai ./cmd/factory-ai   # produce the binary
go vet ./...                                     # static checks
gofmt -l .                                       # format check (tabs; gofmt wins)
go test ./...                                    # unit + e2e smoke tests

Run

Direct (foreground):

./bin/factory-ai --dir ~/.fusion/factory-ai  # config root defaults to <dir>/config

Service lifecycle (builds the binary if missing, daemonizes, writes pid/log to <dir>/logs/):

./scripts/start.sh start | stop | status | restart

Install (PyPI / Homebrew)

Prebuilt releases ship through two channels; both resolve the sidecar interpreter automatically:

pip install fusion-factory-ai        # per-platform wheels (command: factory-ai)
brew install dahai80/fusion-mlx/factory-ai   # Homebrew tap (tarball + venv sidecar)

The wheel's factory-ai console script execs the bundled Go binary with --dir ~/.fusion/factory-ai (override: FUSION_FACTORY_AI_DIR) and pins FUSION_FACTORY_AI_SIDECAR_PYTHON to its own interpreter. A tag push (v*) builds the tarballs and wheels via .github/workflows/release.yml and publishes the wheels to PyPI via Trusted Publishing. New releases: bump the version in packaging/pyproject.toml, push the tag, then stamp the tarball sha256s into packaging/homebrew/factory-ai.rb and update the tap formula.

Flags and environment

Flag Default Resolution order
--dir ~/.fusion/factory-ai flag > FUSION_FACTORY_AI_DIR > default
--config-root <dir>/config flag > default (scripts/start.sh passes it from FUSION_FACTORY_AI_CONFIG_ROOT when set)
--socket <dir>/factory-ai.sock flag > derived (stale socket removed on start)
--studio-sock /tmp/fusion-studio.sock flag > FUSION_STUDIO_SOCKET > default

Environment variables understood:

  • FUSION_FACTORY_AI_DIR — data root override (flag --dir wins when set)
  • FUSION_FACTORY_AI_CONFIG_ROOT — consumed by scripts/start.sh, forwarded as --config-root
  • FUSION_STUDIO_SOCKET — agent-studio UDS path override (used by the P3 readiness probe)

Shutdown: SIGTERM/SIGINT close the listener, drain the serve loop, close the store, and remove the socket file.

Config root layout

The config root (default <dir>/config) is where pipeline configuration and ai-XXXX project directories live. factory-ai reads it at startup and exits non-zero when anything required is missing or invalid (fail-closed):

<config-root>/
  req-policy.md     # requirements policy prose; must exist and be non-empty
  team.yaml         # workers: name/cli/provider_policy/model_family/work_dir;
                    # provider_policy is local-only | cloud-allowed-with-approval;
                    # optional tuning passed to the agent-studio member:
                    # label/description/model_tier (cheap|strong)/budget_tokens/
                    # max_concurrency/permission_mode/tool_allowlist/context/
                    # run_timeout_minutes (edit live via team.get/team.update)
  pipeline.yaml     # gates (type: human | review | human+review) + stages
                    # (id/role/gates/inputs/outputs/reviews); a stage role must
                    # name a declared worker; referenced gates must be declared
  sources/*.yaml    # lead sources (one file per source), kind:
                    # email | platform | upload | manual; at least one required
  ai-template/      # project scaffold template; must contain a non-empty
                    # docs/ skeleton and a deploy/ dir (checked by probe P2;
                    # project.create copies it verbatim, fail-closed when missing)
  outbound.yaml     # SMTP channel for P4 + transmit + report self-send:
                    # smtp_host/smtp_port/from/credential (credential must be a
                    # keychain ref, inline "://" values rejected); optional
                    # transmit block (enabled/credential — absent = transmit
                    # stays draft-mode) and report block (to/credential/interval
                    # — absent = report stays artifact-only)
  budget.yaml       # optional token budget caps: per_project_tokens,
                    # per_stage_tokens (map stage id -> cap); zero/absent = inert
  rates.yaml        # optional retro reference data (M3a): currency,
                    # variance_threshold_pct, roles (per-role hourly_rate/unit —
                    # recorded verbatim into the retro, never used to compute
                    # variance); zero/absent = documented defaults
  reports/          # weekly commercial report artifacts: report-<YYYY-MM-DD>.md
                    # (created by the report service, exclusive writes only)```

Strictness: YAML files are decoded with unknown-field rejection; duplicate
worker/gate/stage ids, undeclared references, and invalid enum values are
startup errors.

**The default config root ships WITHOUT these files yet.** Create them before
first start, or point `--config-root` (or `FUSION_FACTORY_AI_CONFIG_ROOT` for
`start.sh`) at a prepared directory. New `ai-XXXX` project directories are
created **in the config root** by `project.create` (next free code from
scanning existing `ai-NNNN` dirs, docs skeleton copied from `ai-template/`).

## Data root layout

Everything mutable lives under the data root (default `~/.fusion/factory-ai`,
override: `--dir` or `FUSION_FACTORY_AI_DIR`):

/ factory-ai.db # SQLite control-plane store (schema v5: leads, projects, # stage_runs, artifacts, approvals, review_results, events, # costs, adapters_state, delivery, runs, transmit_receipts, # reports + schema_migrations) factory-ai.sock # UDS listener, removed on clean shutdown logs/ # created by scripts/start.sh: factory-ai.pid, factory-ai.log leads// # raw/, attachments/ rejected// # quarantined intake payloads drafts/ # outbound email drafts: -.eml # (RFC-5322 render; transmit through the sidecar only # when enabled + credentialed, else draft-mode fallback) ```

Disaster recovery

Scripts: scripts/backup.sh, scripts/restore.sh, scripts/verify-restore.sh. A backup captures the data root as an online-consistent SQLite snapshot (VACUUM INTO, safe while the daemon runs) plus all data-root side files (leads/, drafts/, rejected/, logs/) and a full copy of the config root (pipeline/team/sources/budget yaml, req-policy.md, outbound.yaml, ai-XXXX artifact trees, reports/), sealed with manifest.sha256. The backup target must live OUTSIDE both roots (the script refuses otherwise). Duration scales with the config-root artifact-tree size — on the current deployment (~7 GB / 170k files) a backup takes about 7 minutes and a restore about 31 minutes, so a long-running restore is normal, not a hang.

The 3am sequence (same host; example paths match a default deployment):

# 1. Snapshot (daemon keeps serving; read-only against the live roots)
factory-ai/scripts/backup.sh ~/.fusion/factory-ai ~/.fusion/factory-ai/config /tmp/factory-ai-backup

# 2. Restore into FRESH roots (manifest verified before anything is placed)
factory-ai/scripts/restore.sh /tmp/factory-ai-backup /tmp/restored-data /tmp/restored-config

# 3. Prove the restore: manifest re-check + config.validate + full event
#    hash-chain replay; prints "VERIFY OK <event-count>"
factory-ai/scripts/verify-restore.sh /tmp/restored-data /tmp/restored-config /tmp/factory-ai-backup

restore.sh refuses (exit 2) when the target data root already contains factory-ai.db — an overwrite needs the explicit --allow-live flag, and even then the daemon must be stopped first (overwriting a db the daemon holds open corrupts it). To promote a restored root, stop the daemon, restore with --allow-live, run verify-restore.sh, then start the daemon again with --dir pointing at the restored roots.

Known limits (by design, spec 2026-11-30-bizplane-m3a §6a.5):

  • Same host only. Cross-host restore is out of scope: source/credentials in the config root are bare macOS keychain service-name references that do not resolve on another machine, so config re-validation is a same-host verify step.
  • agent-studio state is not captured. The backup knows nothing about the studio daemon — team registry, task board, inbox/playbook state live on the studio side. After a restore, re-register the teams (console TeamPage or create_team) and re-seed any tasks the pipeline depends on before dispatching again.
  • Post-restore smoke. Before resuming work, probe the surviving studio daemon over its UDS (teams.list must answer) and run one small dispatch through a re-registered team to confirm the restored control plane can actually reach agents — not just that its bytes verify.
  • --allow-live restores merge, not replace. A restore over an existing root overwrites only the files present in the backup; anything written after the backup (newer reports, leads, config strays) survives and neither restore.sh nor verify-restore.sh flags it, so a promote can yield a mixed-timeline root. Prefer restoring into fresh roots and swapping the daemon over.

API surface

Transport: Unix Domain Socket, newline-delimited JSON-RPC 2.0 — one request per line {"id":..., "method":"...", "params":{...}}, one response per line {"jsonrpc":"2.0","id":...,"result":...} or {"error":{"code":...,"message":...}}. Unknown methods fail with -32601; unknown or malformed params fail with -32602; handler failures land in the -32000 server range with the message intact. M0 serves one connection at a time, serially.

rpc.hello is the console skew-guard handshake; the result {"name":"factory-ai","version":"0.1.0"} is controller-binding — the console refuses business routes unless both values match.

All 36 methods (M0 + M1 + M2 + M3a + M4a + M4b + M4c):

Method Purpose
rpc.hello Skew-guard handshake (name + version binding)
lead.create Ingest one lead (dedup on source + external_ref, policy snapshot)
lead.list All leads, oldest first
lead.get One lead by id
project.create Allocate next ai-XXXX code, scaffold docs from ai-template/, insert row + event
project.list All projects, oldest first
project.get One project by id
project.transition The only mutation path into the state machine: next stage entry, terminal request (reject/lose), or archived close-out; runs the gate evaluator and surfaces the gate reason on failure
project.resume Clear the paused overlay on the project's open stage run (operator lever after a budget-cap pause); overlay only — projects.status untouched, the next dispatch stays operator-triggered
approval.request Register a hash-bound approval subject (optional project_id binding; unknown project = -32602, no row)
approval.decide Decide one approval (optional price_override string — the G1 quote price stored in the row snapshot; RPC-boundary validated, M3b)
approval.list All approvals
review.submit Record a review verdict; fails closed on model-family independence violation (no row, review.rejected event)
readiness.status Run all P1-P5 probes, open only when every item passes
readiness.probe Re-run one probe (P1..P5)
config.get Loaded configuration snapshot
config.validate Re-validate config; returns {valid} without throwing
audit.query Paginated hash-chained event stream (entity/entity_id/after_seq/limit filters)
costs.report Costs table listing + token/cost totals, optionally per project
run.dispatch Async dispatch of one stage run to agent-studio (teams.run_member under the hood); returns {run_id, task_id, status:"running"} immediately, the run completes in the background; refuses while the project's open stage run is paused (M3b)
run.list Run rows for a project (or all projects when project_id is omitted), newest first
outbound.send Render an RFC-5322 email draft for a stage artifact into <data>/drafts/ + insert a delivery row (package_hash = on-disk artifact sha256, sent_at NULL)
outbound.accept Record customer acceptance (accepted_at) on the project's delivery row
outbound.transmit Real send of the project's latest delivery through the sidecar — fail-closed order: delivery row present, not accepted, no prior receipt, G5a approval bound to the CURRENT on-disk delivery-package.md hash, recorded hash unchanged; transmit disabled/credential absent/sidecar down all fall back to {sent:false, draft_mode:true} (no error, no receipt); success records a transmit_receipts row + outbound.transmitted event
outbound.list Delivery rows (optionally per project) with receipt state
platform.status Platform connector status + detail (dormant v1: disabled when no credentials)
report.list Report ledger rows (id, generated_at, sent_at — empty until the self-send completes), newest first
report.get {id} One report row plus its stored markdown (path containment-checked against <config-root>/reports/)
retro.get {project_id} One archived project's quote-vs-actual retro ({retro}); -32000 when the project is unknown or not archived (only archived projects record a retro)
source.browse {source, limit} Per-source inbound browse: email sources list the live mailbox newest-first through the sidecar's read-only list_email (limit default 20, clamped to 1..50) with each row annotated ingested/lead_id from the lead dedup index; non-email sources serve their already-ingested leads rows (note:"queue rows"). Pure reads — no cursor/seen mutation; unknown source -32602, sidecar failure -32000 (never an empty list with a degradation note)
source.ingest {source, uid} Operator ingest of one browsed mailbox message: fetch by UID through the sidecar's read-only fetch_email, then the exact poller ingest path (shared IngestEmail helper — same lead.created event + artifact tree writes); dedup on (source, external_ref) returns the existing lead with created:false; email sources only; a message without Message-ID refuses with -32602
source.feedback {source, external_ref, decision, snapshot, ingest} Operator feedback markup of one browsed message (accept = ingest as lead, reject = ignore): upsert into the source_feedback table (UNIQUE(source, external_ref)) with a source.feedback.recorded event in the same transaction; ingest:true + accept additionally runs the ingest leg (row stands even when the ingest fails — the error names both facts); email sources only (-32602 otherwise)
source.rules.propose {source} Deterministic rule induction from the source's labeled feedback rows: subject tokens (lowercase, ≥2 chars) + full sender address + sender domain; a candidate qualifies with ≥2 accepts and 0 rejects; capped at 5 rules by matched_accept descending; fewer than 3 labeled rows returns an empty rules list (based_on carries the label counts). Read-only — nothing persists
source.rules.apply {source, rules} Persist operator-approved rules into <config-root>/sources/<source>.yaml: field ∈ `subject
outbound.config.get Read the outbound.yaml editor payload for the console P4 editor (SMTP host/port/from/username, credential + transmit block as keychain REF strings only — no secret material ever enters a response; the report block rides along read-only); a missing or unparseable outbound.yaml is a fail-visible -32000, never fabricated defaults
outbound.config.update {smtp_host, smtp_port, from, username, credential, transmit} Validate-then-atomically-rewrite outbound.yaml: port 1-65535, bare keychain credential refs (no scheme/whitespace), host+username non-empty when transmit is enabled (-32602 otherwise); the yaml.Node tree edit touches only the editable keys (comments and the report block survive verbatim), the encoded result passes the shared readiness loader BEFORE the tmp+rename, the live sidecar send config is re-applied immediately after the rename (the new SMTP account reaches transmit without a daemon restart), and failures of the re-apply or of the outbound.config.updated event append are disclosed as errors

M1 delivery loop

M1 activates the remaining legs of the pipeline: headless agent execution, artifact write-back, costs, outbound drafts and acceptance. Gate evaluation itself is untouched — M1 fills the gate inputs.

Async dispatch (run.dispatch {project_id, stage}). Validates the project/stage, creates a runs row (status running) + run.dispatched event, then executes teams.run_member in a goroutine and returns {run_id, task_id, status:"running"} immediately; clients poll run.list. Before every dispatch the team/task mapping is ensured (teams.register idempotently, task <project>-<stage>); the team registry lives in-memory on the agent-studio daemon. A second dispatch while a run is pending/running for the same project+stage fails with -32000. Each run is bounded by a 30 minute deadline, and a panicking goroutine is recovered into a run.failed row — the daemon never dies with a dispatch.

Artifact write-back + costs. After a successful run, each declared stage output is written to ai-XXXX/docs/<name>.md from the member's artifact_ref file body (fallback: result.summary), hashed from disk (sha256) into an artifacts row + artifact.recorded event. One costs row is recorded on every terminal run (ok, capped, error) from teams.run_usage tokens, and stage_runs.spent_tokens is updated. Capped and error runs record costs but write no artifacts (fail closed — the gate will honestly fail).

Outbound draft-only (outbound.send {project_id, channel, payload_ref}). Renders an RFC-5322 email draft from the stage artifact into <data>/drafts/<project>-<artifact>.eml and inserts a delivery row with sent_at NULL. No SMTP dialing in M1 (outbound.yaml creds stay placeholders; real send is the M2 channel-bridge). outbound.accept {project_id} sets accepted_at on the delivery row (operator confirms customer acceptance; double-accept is a -32000 error).

Gate bindings. The deployed pipeline.yaml now binds all gates: G0 (S0, human+review), G1/G1b (S1), G2 (S4), G3 (S3), G5a/G5b (S5); S0 reviews requirements-brief, S5 outputs include delivery-package.md. gate.failed events carry gate_id + reason in the payload, and review.submit populates reviewed_hash with the on-disk artifact sha256 at submit time. Review runs stay record-only in M1: gates consume review.submit verdicts; dispatching an actual review run is M2.

Migration 0002 (internal/store/migrations/0002_m1_dispatch.sql, forward-only) adds the runs table (id, project_id, stage, role, task_id, status, subagent_id, summary, artifact_ref, tokens_spent, error, created_at, finished_at) with an index on (project_id, stage).

Email channel (M2, channel-bridge sidecar)

Email inbound + outbound run through one Python sidecar (sidecar/channel-bridge/main.py) that wraps fusion-channel (email_imap adapter: IMAP poll + MIME parse for inbound, SMTP send for outbound). Go spawns it over stdio JSON-RPC 2.0 on first use and respawns it on the next use after a failure (the fusion-console harness sidecar pattern).

  • Outbound: outbound.transmit sends the approved delivery through the sidecar when credentials resolve (transmit credential in outbound.yaml, secret resolved sidecar-side from the macOS keychain or the scoped FUSION_FACTORY_AI_* env override — no plaintext secrets cross the IPC boundary). The send is hash-bound approval gated (fail-closed order): the delivery row must exist with no acceptance and no prior receipt; a G5a delivery-approve approval must be bound to the CURRENT on-disk delivery-package.md hash (drift after approval refuses the send); the recorded package_hash must still match the on-disk file; and the draft body that would be sent must still match the approved artifact (a hand-edited draft body refuses the send). A real send records a transmit_receipts row (delivery id, message id, param hash, sent_at) + an outbound.transmitted event in one transaction; a duplicate transmit on a receipted delivery is refused. Recipient contract: the rendered draft is always addressed To: operator@local (factory-ai never resolves the customer address itself) — before outbound.transmit a human edits the draft .eml To: header to the real recipient (the M1 "a human moves the draft" step); transmit with the un-edited placeholder (or an empty To:) refuses to send and falls back to draft mode ({sent:false, draft_mode:true}, loud log, no receipt). When transmit is disabled in outbound.yaml (no transmit: block), the credential is absent, or the sidecar is down, transmit falls back to draft mode ({sent:false, draft_mode:true} — no error, no receipt). The sent reply threads via In-Reply-To carrying the lead's inbound Message-ID. The SMTP login username is the outbound.yaml username when set, otherwise the from address (the fusion-channel adapter requires a non-empty username).
  • Inbound: when sources/email.yaml declares credential, host, username, and at least one rules entry, a poller runs every minute: IMAP poll → MIME parse → selection rules (OR-combined case-insensitive substring on subject/from/body; no rules = no polling) → message-id dedup → ingestion through the existing lead.create path (source=email, external_ref=Message-ID, raw payload + attachments in the artifact tree). Leads that already exist are skipped by the lead service's UNIQUE index. The fetch keeps a persisted per-folder UID cursor (in the sidecar poll-state file): it fetches UNSEEN UIDs greater than the cursor, oldest poll_limit first, so a burst larger than poll_limit cannot permanently starve the oldest mail (readonly IMAP selects never set \Seen, so a plain "newest N UNSEEN" window would). The cursor advances only after a fully successful batch fetch, so a crash mid-batch re-fetches that batch next cycle and the lead UNIQUE index absorbs the overlap — no mail is silently skipped in the happy path. Tradeoff (explicit, M2): each message is evaluated at least once (exactly once in the happy path) — changing the selection rules does not re-scan already-cleared history. Residual crash window (explicit, documented as accepted): a crash between the sidecar cursor advance and the Go-side lead.create commit drops that one batch.
  • Credential references are bare keychain service names (e.g. email-imap): no keychain: scheme prefix, no inline :// URL. Both sources/*.yaml and outbound.yaml validation reject anything else — the sidecar looks the secret up with security find-generic-password -s <ref> -w and the scoped FUSION_FACTORY_AI_* env override, so the ref must be the literal service name.
  • Readiness: the P1 email leg = sidecar health + an IMAP credential probe (static check, no live login). Only that leg degrades when the sidecar is down; an email source without selection rules degrades it too (fail-closed).
  • Ops: interpreter resolution is FUSION_FACTORY_AI_SIDECAR_PYTHON → the workspace .venv → python3.12/python3; script path override is FUSION_FACTORY_AI_SIDECAR_SCRIPT. Provision the keychain item with security add-generic-password -s <credential-ref> -a factory-ai -w. Sidecar deps: factory-ai/sidecar/channel-bridge/requirements.txt (fusion-channel as an editable path dependency).
  • Offline tests: pytest factory-ai/sidecar/channel-bridge/ -q (mocked IMAP/SMTP, no network).

Platform connector (M2, dormant v1)

internal/connector ships the platform lead source as deliberately dormant v1: connector code + contract tests only, no activation. When sources/platform.yaml declares kind: platform with an empty credential, the poller logs one line at startup and stays disabled — no network calls.

  • Wire-up (when activated): OAuth2 authorization-code client against the platform REST API (api_base + oauth block: client_id, authorize_url, token_url, scopes), polling on poll_interval (default 1m) with poll_limit per batch, filtered by selection.query. Items map to the lead contract: source=platform, external_ref = the platform entity id, raw payload = canonical JSON in the artifact tree. A persisted per-source cursor in adapters_state skips items at or before it; the cursor advances per item only after a successful ingest.
  • Credential-gated: filling in the config alone does NOT activate a working source — the client secret and initial refresh token are never provisioned by any v1 code path. Activation requires credential injection (keychain/env + an initial token step), a registered OAuth application, and a contract server implementing the recorded endpoint shapes.
  • Surface: platform.status returns the poller state (disabled | degraded | ok) + detail; readiness P5 ("platform source") passes as platform source dormant: ... while the source is disabled, and fails when a configured connector degrades.

Budget caps (M2)

Optional token spend caps from budget.yaml in the config root:

per_project_tokens: 5000000   # 0 / absent = no project cap
per_stage_tokens: {}          # stage id -> cap; 0 / absent = no stage cap

run.dispatch checks both caps inside the same transaction as the runs-row insert (consistent snapshot against concurrent cost writes): the project cap sums recorded tokens_in + tokens_out for the project, the stage cap sums the same for (project, stage). Exceeding either cap refuses the dispatch with the -32000 business error (budget: project cap exceeded (spent N > cap M) / budget: stage <id> cap exceeded) — no runs row is created and no agent runs. Capped and error runs still record a costs row (real spend), but write no artifacts (fail closed).

A cap trip also pauses the project's open stage run overlay (M3a: the stage_runs.state flips to paused, projects.status stays active) so operators see the blocked stage at a glance; the pause is best-effort and the -32000 refusal remains the authoritative fail-closed response. project.resume clears the pause overlay only — the next dispatch stays operator-triggered.

Multi-project concurrency (M3a)

Dispatch runs in parallel across projects and stays serial inside one dispatch: run.dispatch inserts the runs row in a single transaction (duplicate guard + budget check + event append share it) and executes the agent run in a background goroutine, so two projects dispatched together run their stages at the same time. The single-open-run index is per (project, stage), never global; one project's failure, refusal, or cap trip cannot touch another project's runs, costs, artifacts, or event chain. This is proven by the three-project S0-S5 load scenario (TestE2ELoadThreeProjects, per-project chain replay + ledger isolation asserts) and pinned by the interleaving tests in internal/dispatch/concurrency_test.go. finishRun retries the whole finish transaction on SQLITE_BUSY / BUSY_SNAPSHOT (5 attempts, linear backoff) so concurrent stage finishes never strand a running row.

Pause semantics (spec §6a.4): a budget-cap trip pauses the TASK, not the pipeline — the refusal flips the project's open stage_runs.state to paused, projects.status stays active, and other projects keep dispatching. The paused overlay fails closed on both run.dispatch (dispatch: stage <id> is paused (resume before dispatch), enforced since M3b) and project.transition ("paused runs must be resumed first"); project.resume clears the overlay only (stage back to running, stage.resumed event, no auto re-dispatch), and the refusal remains the authoritative guard until the operator raises the cap — budget.yaml is read once at startup, so the lever is: edit cap, restart the daemon, project.resume, re-dispatch.

Project-bound approvals and the G1 price (M3a)

approval.request takes an optional project_id: when present it must resolve to an existing project (-32602 otherwise, no approvals row is written) and is stored on the approvals row (migration 0006) and the approval.requested event payload; absent keeps the legacy unbound row. approval.decide takes an optional price_override string, stored in the row's channel snapshot: the operator-entered quote price captured at the G1 approval — the project's money estimate. The string is validated at the RPC boundary (M3b): a missing field leaves the row unchanged; a whitespace-only value clears the stored price; anything else must match ^\d{1,12}(\.\d{1,2})?$ after trim and parse to a value > 0, or the decide fails with -32602 invalid param: price_override (the trimmed value is what gets stored). Existing rows are not migrated. The retro reads it through LatestApprovedPrice(projectID, action) (newest approved row wins; rejected and priceless rows are skipped), so a re-approval supersedes the earlier price idempotently and the quote-vs-actual variance has a real human-entered operand.

Migrations 0003-0005 (M2)

Forward-only, embedded, applied at startup in order:

  • 0003_runs_single_open.sql — partial UNIQUE index on open (project_id, stage) runs; the storage-layer backstop of the dispatch duplicate guard.
  • 0004_transmit_receipts.sql — transmit_receipts table (delivery id, message_id, param_hash, sent_at); one receipt per delivery, the duplicate-send guard reads it.
  • 0005_reports.sql — reports table (id, path, generated_at, sent_at NULL-able) for the weekly report ledger (schema v5).

Weekly commercial report (M2)

internal/report aggregates the control plane into one human-readable weekly artifact and self-sends it to the operator.

  • Build cadence: a ticker fires every report.interval from outbound.yaml (Go duration, default 168h = weekly; first fire after one full interval). A failed or refused build is logged loudly and retried on the next tick — never fatal.
  • Aggregation: per project — internal code (ai-XXXX), the operator-set internal lead title, project status, per-stage run counts (runs table), and cost token sums (costs table).
  • Business view (M3b): one business line per project — 报价 <price> <currency> · 闸门 <approved>/<rejected> · 已交付. The price is the newest approved quote-approve price (LatestApprovedPrice) rendered verbatim with the currency label from rates.yaml (currency:; default CNY when unset); no approval renders 未报价 (never a fake 报价 0). Gate counts come from the project's decided approval rows; delivery mirrors the archived terminal state (未交付 while active). Counts are all-time (project lifetime — the build keeps no period window, stated on the Window: line of the artifact).
  • Red-line (fail-closed): the report shows the internal code + operator title only — never the raw intake email subject. Before any write, the build recovers each email lead's raw intake subject from the lead tree (<data>/leads/<id>/raw/) and refuses the whole build when a title still equals its intake subject unchanged (error names the red-line rule; no artifact, no ledger row). An unresolvable raw file is skipped with a loud log (cannot prove equality).
  • Artifact: markdown at <config-root>/reports/report-<YYYY-MM-DD>.md, written exclusively (O_EXCL — an existing report for the same day is a visible refusal, never an overwrite), plus a reports table row (id, path, generated_at, sent_at) and a report.generated event in one transaction; the file is removed if the transaction fails.
  • Self-send: sent to the operator's own fixed address (outbound.yaml report.to) through a dedicated sidecar client using report.credential (fallback: the transmit credential). It is exempt from hash-bound approvals (design ruling 3 — the recipient is the operator, not a customer). Exactly one send_email attempt (not idempotent, no retry). Sidecar down / no recipient / credentials missing → artifact-only with a loud log, sent_at stays NULL (fail-visible); success stamps sent_at + a report.sent event.
  • RPC: report.list → {reports: [{id, generated_at, sent_at}]}, report.get {id} → {id, generated_at, sent_at, markdown} (stored path containment-checked against <config-root>/reports/, fail-closed).
  • Migration 0005 adds the reports table (schema v5).

Quote-vs-actual retro (M3a)

internal/retro records what a project was quoted versus what it actually cost, without ever fabricating a number.

  • Quote price capture (G1): the operator-entered price on the approval.decide call (price_override, stored in the approvals row snapshot) is the project's money estimate. retro.BuildForProject reads it via LatestApprovedPrice(projectID, "quote-approve") — latest approval wins.
  • Variance honesty: variance = quote price vs machine-readable actuals ONLY. The money actual is SUM(est_cost) from the costs rows (recorded as stored by dispatch cost accounting). While studio issue #826 keeps subagent token actuals at zero, no money actual is recorded either, so variance_pct stays null and the markdown prints the literal line token actuals: missing (upstream #826) — never a guessed percentage.
  • rates.yaml (optional, strict-parsed): currency (default CNY), variance_threshold_pct (default 20), and per-role reference rates (roles.<role>.hourly_rate / unit). The role rates are recorded verbatim into the retro markdown as reference data and are NEVER used to compute variance. A missing file is not an error (zero config -> documented defaults); unknown fields fail startup.
  • S2 variance note: when the gate-passed transition leaves the S2 work-plan stage and the variance is computable and strictly above the threshold, one retro.note event is appended (variance, quote, actual, threshold). Not computable or at/below threshold = no event. A note failure is logged loudly but never reported as a failed transition (the transition has already committed — fail-visible, not fail-closed).
  • S5 archive artifact (fail-closed): archiving a project builds and writes <config-root>/ai-XXXX/docs/retro.md (exclusive O_EXCL write, containment-checked path) and appends retro.recorded INSIDE the archive transaction, right before the commit. A retro write failure rolls the whole archive back: the project is NOT archived, the failure is logged loudly, and no project.archived/retro.recorded events survive. If the transaction fails after the hook already wrote retro.md, the orphan file is removed best-effort (the original error is preserved), so an archive retry is never permanently blocked by the O_EXCL retro write (M3b). Rejected/lost-bid terminals never write a retro.
  • Markdown contents: internal code + operator-set internal lead title only (red-line compliant, no customer content), quote price (报价 <price> CNY), token actuals (with the missing-actuals line while #826 is open), the variance line (or not computable (missing data)), and the per-role reference-rate table verbatim.
  • RPC: retro.get {project_id} -> {retro: {project_id, code, title, quote_price, actual_cost, actual_spend{tokens_in,tokens_out}, variance_pct, generated_at}}; plain -32000 error for an unknown project or one that is not archived.

Testing

go test ./... -count=1

Unit tests cover every package; cmd/factory-ai/e2e_test.go boots the real binary against a temp data dir and exercises the full wire surface (hello, lead create/get, project create/transition through gates, approvals, review independence, readiness, audit, costs).

Design docs

  • Pipeline design spec: docs/superpowers/specs/2026-11-27-business-delivery-pipeline-design.md (fusion-console repo)
  • M0 implementation plan: docs/plans/2026-11-27-bizplane-m0-control-plane.md
  • M1 delivery-loop plan: docs/superpowers/plans/2026-11-28-bizplane-m1-delivery-loop.md (fusion-console repo)
  • M2 plan: docs/superpowers/plans/2026-11-29-bizplane-m2.md + design docs/superpowers/specs/2026-11-29-bizplane-m2-design.md Historical plan/spec docs above keep their original bizplane filenames; they live in the private source repo (and the fusion-console repo where noted), not in this repo.

Limitations (M0 + M1 + M2 + M3a + M3b)

  • Outbound without the channel-bridge sidecar (or without resolved credentials) stays draft-only: .eml renders + delivery rows, transmit falls back to draft mode (see "Email channel (M2)" above). The rendered draft always carries the operator@local placeholder To: transmit with the un-edited placeholder refuses to send — the operator hand-edits the draft .eml To: header between outbound.send and outbound.transmit.
  • After a successful transmit the draft .eml remains on disk: the next outbound.send for the same project+artifact O_EXCL-refuses until the sent draft is hand-deleted (the operator removes or archives it).
  • Review runs stay record-only in M2 as well: gates consume review.submit verdicts (M2 adds the model-family independence/self-approval block, not a real review dispatch).
  • The team registry (teams.register) is in-memory on the agent-studio daemon — re-registration after a studio daemon restart is expected and idempotent.
  • RPC serve is serial: one connection at a time, requests processed sequentially per connection (dispatch work itself runs in the background).
  • Config seeding is pending: the default config root is empty until the required files are created manually.
  • No fusion-supervisor integration: lifecycle is owned by scripts/start.sh per the spec.
  • Subagent usage/tokens are recorded as 0: the agent-studio daemon does not surface teams.run_member usage upstream, so cost rows exist but budget accounting stays inert until that is fixed upstream (agent-studio).
  • If the finishRun transaction fails, the runs row stays running and the duplicate guard blocks re-dispatch for that project+stage until manual cleanup — the failure is logged loudly (verified in final review).
  • The daemon-supplied run artifact_ref is read without path containment (local-first threat model: the studio daemon runs as the same user).
  • The terminal project state is archived; a delivered transition is rejected fail-closed.

M3b hardening (report business view + fail-closed fixes)

M3b (branch feat/bizplane-m1) ships the weekly-report business view (see "Business view (M3b)" under the weekly report above) plus three fail-closed hardening fixes:

  • Paused-stage dispatch refusal: run.dispatch refuses when the project's open stage run carries the paused overlay (-32000, dispatch: stage <id> is paused (resume before dispatch)) — the resume-then-dispatch order is enforced at the RPC boundary, closing the M3a gap where dispatch alone bypassed the pause.
  • Orphan retro cleanup: if the archive transaction fails after the retro hook already wrote retro.md, the orphan file is removed best-effort (the original archive error is preserved), so an archive retry is never permanently blocked by the O_EXCL retro write.
  • price_override validation: approval.decide validates the price at the RPC boundary — shape ^\d{1,12}(\.\d{1,2})?$ after trim and it must parse to a value > 0, else -32602 invalid param: price_override; a whitespace-only value clears the stored price, a missing field leaves it unchanged (see "Project-bound approvals and the G1 price" above).

Source browse (M4a, per-source tabs)

M4a (branch feat/bizplane-m1) opens the operator-facing inbound surface behind the fusion-console S0 source-browse tabs: while a project is running the operator can inspect the real mailbox and consciously pull a message into the pipeline. Two RPCs, both backed by the channel-bridge sidecar's new read-only methods (list_email / fetch_email — pure IMAP reads; the persisted poller UID cursor and the \Seen flags are never touched):

  • source.browse {source, limit}: email sources list the live mailbox newest-first (limit default 20, clamped to 1..50) with each row annotated ingested/lead_id from the lead dedup index; non-email sources serve their already-ingested leads rows. The listing is unfiltered — selection rules gate only the poller, not the operator's view.
  • source.ingest {source, uid}: fetch one browsed message by UID and run it through the exact poller ingest path (shared IngestEmail helper — same lead.created event and artifact-tree writes); dedup on (source, external_ref) returns the existing lead with created:false.

Fail-closed: unknown source or a non-email source in source.ingest is -32602, a sidecar failure is -32000 — a browse never degrades to an empty list with a degradation note. The rpc Service gains SetMailbox wiring (the same sidecar client instance the poller uses) and both methods fail closed until it is set. Console side (separate repo): per-source browse tabs with an ingest action and an ingested badge on already-ingested rows.

Feedback markup and rule induction (M4b)

M4b closes the selection loop: the operator's reject/accept decisions on browsed messages become training data for the poller's selection rules — no LLM in the loop, induction is deterministic.

  • source.feedback (migration 0008, source_feedback table): one upsert per (source, external_ref) — the last decision wins; the snapshot (subject/from/excerpt) is stored with the row so induction never needs to re-fetch the mailbox. ingest:true + accept chains the regular ingest leg; if that leg fails the feedback row stands and the error discloses both facts.
  • source.rules.propose: pure function over the labeled rows. Candidates are subject tokens (unicode letter/digit runs, ≥2 chars, lowercased), the full sender address, and the sender domain. A candidate qualifies when it appears in ≥2 accepts and 0 rejects; the top 5 by matched accepts are returned. Under 3 labeled rows (inductionMinLabels) the proposal is empty — no cold-start guessing.
  • source.rules.apply: writes the approved rules into the source's yaml through a yaml.Node tree edit that replaces only the rules key (comments and unrelated keys survive verbatim; empty rules render rules: []), then reloads that single source in memory (config.LoadSource) — the poller picks the rules up without a daemon restart.

Console side (separate repo): 忽略 button per browsed row (reject feedback with the row snapshot), and a rules-proposal card above the email list (fetches propose on every browse refresh, apply button posts the rules back and reloads the pipeline config).

Metadata

Release files for fusion-factory-ai 0.1.2

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Built distributions (wheels)

Table of built distributions (wheels) for fusion-factory-ai 0.1.2
File Actions
fusion_factory_ai-0.1.2-cp310-abi3-manylinux2014_x86_64.whl CPython 3.10 abi3 Linux glibc 2.17+ x86-64 Details for fusion_factory_ai-0.1.2-cp310-abi3-manylinux2014_x86_64.whl
fusion_factory_ai-0.1.2-cp310-abi3-manylinux2014_aarch64.whl CPython 3.10 abi3 Linux glibc 2.17+ ARM64 Details for fusion_factory_ai-0.1.2-cp310-abi3-manylinux2014_aarch64.whl
fusion_factory_ai-0.1.2-cp310-abi3-macosx_11_0_arm64.whl CPython 3.10 abi3 macOS 11.0+ ARM64 Details for fusion_factory_ai-0.1.2-cp310-abi3-macosx_11_0_arm64.whl
fusion_factory_ai-0.1.2-cp310-abi3-macosx_10_15_x86_64.whl CPython 3.10 abi3 macOS 10.15+ x86-64 Details for fusion_factory_ai-0.1.2-cp310-abi3-macosx_10_15_x86_64.whl

Total release size: 40.7 MB

Release files / fusion_factory_ai-0.1.2-cp310-abi3-manylinux2014_x86_64.whl

Download URL fusion_factory_ai-0.1.2-cp310-abi3-manylinux2014_x86_64.whl
Size 10.5 MB
Tags CPython 3.10 Linux glibc 2.17+ x86-64 abi3
SHA-256 checksum
How to use checksums
cc1082103b2099af65a874716450c66b3ac04b76375d3dc0579f74c77a56c89b
BLAKE2b-256 checksum
How to use checksums
c282c3f0d31e4ffce77118d349b6648db1e11ce27c468fe1d51e402fb4958eba
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Dec 3, 2026.

Transparency log

Release files / fusion_factory_ai-0.1.2-cp310-abi3-manylinux2014_aarch64.whl

Download URL fusion_factory_ai-0.1.2-cp310-abi3-manylinux2014_aarch64.whl
Size 9.7 MB
Tags CPython 3.10 Linux glibc 2.17+ ARM64 abi3
SHA-256 checksum
How to use checksums
d18747637c5e8903a5109d94513b259b7ac27bcdafe828f3c58116016805120f
BLAKE2b-256 checksum
How to use checksums
4d7c4fbcb8077864276548a0213d825e88bcaec7bdfa3e18f8c4e5f280942095
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Dec 3, 2026.

Transparency log

Release files / fusion_factory_ai-0.1.2-cp310-abi3-macosx_11_0_arm64.whl

Download URL fusion_factory_ai-0.1.2-cp310-abi3-macosx_11_0_arm64.whl
Size 10.0 MB
Tags CPython 3.10 abi3 macOS 11.0+ ARM64
SHA-256 checksum
How to use checksums
3b9e78a081aa54d7ef3aee97b6702f25b358b449292485cc9b03d2f094e64756
BLAKE2b-256 checksum
How to use checksums
1422e6f065f8d7a9cb9927995539c1f9843974256e97a94b1d045b093a19e7d9
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Dec 3, 2026.

Transparency log

Release files / fusion_factory_ai-0.1.2-cp310-abi3-macosx_10_15_x86_64.whl

Download URL fusion_factory_ai-0.1.2-cp310-abi3-macosx_10_15_x86_64.whl
Size 10.5 MB
Tags CPython 3.10 abi3 macOS 10.15+ x86-64
SHA-256 checksum
How to use checksums
f2ce7b860f4630f16804a09298c1176f43a2092354b33e2d9715d3025dbcb9af
BLAKE2b-256 checksum
How to use checksums
893a16974f990b734f034e1c65f2a621bef829bcd382701586607cd1a8cceaa4
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Dec 3, 2026.

Transparency log

Security for fusion-factory-ai 0.1.2

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

All 4 files in this release have been uploaded with provenance metadata.

Select from 4 files

Attestation for fusion_factory_ai-0.1.2-cp310-abi3-manylinux2014_x86_64.whl

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Dec 3, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page