Skip to main content

Gates and approvals

A gate is a point where the workflow stops and waits for a human decision. The factory has two gates, factory.plan and factory.pr. A decision binds to exactly the bytes the approver saw through a digest, Postgres alone decides whether a decision is valid, and the Temporal signal that follows only wakes the workflow.

The two gates​

GateCovers artifactPresent whenOpened by
factory.planthe newest plan artifactthe repo policy's gates contains factory.planopenGate after runPlan
factory.prthe newest patch artifactalways (effectiveGates forces it; a policy cannot remove it)openGate after an accepted iteration

The default repo policy is gates: ['factory.pr']. The status while waiting is awaiting_plan_approval or awaiting_pr_approval.

The gate digest​

The digest binds an approval to a job, repo, base commit and artifact:

gateDigest = sha256( utf8( "af-gate-v1\n" + gate + "\n" + jobId + "\n" + repo + "\n"
+ baseSha + "\n" + artifactSha256 + "\n" ) )

gateDigestInput (packages/agent-types/src/factory.ts) validates every field before building the string (gate enum, UUID job id, catesworks/<name> repo, 40-hex base SHA, 64-hex artifact digest), because a field holding a newline would make two inputs collide. The worker computes the digest in openGate; it stores it in factory_jobs.pending_digest.

FactoryJobView.pendingGate exposes {gate, gateDigest, artifactId, artifactSha256, expiresAt}, and the view carries repo and baseSha, so a caller can recompute the digest independently from the artifact bytes (GET /v1/factory/jobs/:id/artifacts/:kind returns the bytes, with x-artifact-sha256 and x-artifact-redacted; if redaction changed the text, its bytes no longer hash to the digest, and the approver can tell). The digest is always over the stored, unredacted bytes.

Opening a gate​

PgFactoryStore.openGate is one UPDATE that succeeds only on an open job with no cancel request and no other pending gate. It sets status = awaiting_<gate>, pending_gate, pending_digest, pending_artifact_id and gate_expires_at = now() + ttl. The check constraint factory_jobs_pending_gate_valid guarantees the four pending columns are all null or all set, and only while the status is an awaiting_* value. The TTL is FACTORY_APPROVAL_TTL_MS (default 72 hours, from 1000 ms up to 7 days).

Deciding a gate​

consumeApproval runs in one transaction with SELECT ... FOR UPDATE on the job row and checks, in order:

CheckRefusal reasonHTTP
job exists (and id is a UUID)not_found404
status equals the awaiting status of the gatenot_awaiting409
pending_gate equals the gateno_pending_gate409
pending_digest equals the submitted digestdigest_mismatch409
now() < gate_expires_atexpired409

On success it inserts the factory_approvals row (gate, digest, approver, decision, consumed_at = now()) and clears the pending columns. The unique partial index factory_approvals_one_consumed on (job_id, gate) where consumed_at IS NOT NULL makes a second decision for the same gate impossible. Both approve and reject consume the gate.

If the signal cannot be delivered (Temporal down or out of budget), the decision is already in Postgres and the API answers 200 with signalled: false; the workflow also reads Postgres when its gate timer fires.

Workflow side​

The signal handler sets a flag only when the signal's gate equals the gate currently waited on; the loop then calls readDecision. A signal never carries a decision, so a forged or replayed signal can only cause one extra read (a warning gate.signal_without_decision is logged when the read returns none).

expireGate is a single UPDATE that clears the pending columns and sets status = 'failed', error_code = 'approval_expired', closed_at = now() only if pending_gate = <gate> and closed_at IS NULL. It returns true only when no approval consumed the gate first. After a false return the workflow reads the decision once more, so an approval that won the race with the timer is honoured.

Re-derivation at openPr (approval-to-push TOCTOU)​

An approval authorises specific bytes, not a checkout on disk. openPr re-derives everything from the approved bytes immediately before publishing:

  1. Refuse with disabled if the kill switch is set.
  2. Read the consumed decision for the factory.pr gate and digest; require approve.
  3. Load the patch artifact by id from Postgres; require kind patch.
  4. Verify sha256(bytes) equals the stored artifact digest, and that recomputing the gate digest from (gate, jobId, repo, baseSha, actual artifact digest) equals the digest the approver signed. Any mismatch returns internal_error with no push (pr.rederive_mismatch is logged).
  5. Preflight the GitHub host (push App cannot reach the base; fork is a fork of the base), set status opening_pr.
  6. Re-clone baseSha into a fresh directory, run the whole host validation and apply again on the approved bytes (Patch policy), commit with fixed identity and date, and publish.

The pull request title and body come from a fixed template: job id, the submitting client, the approving client, the gate digest, the patch digest, and a fixed warning that the change was written by an AI agent, that scripts, editor tasks and hooks must not be run before review, and that a passing test step is a signal the coder could influence unless the repo policy's patch.protected globs cover tests. No model text is included.

Roles and visibility​

CapabilityWhoEnforcement
submit a jobAPI clients in FACTORY_CLIENTSroute handler (403 otherwise)
read a job, its events and artifactsthe submitting client, and every client in FACTORY_APPROVERSscope(c): submitters are scoped to their own client id, approvers see all
decide a gateclients in FACTORY_APPROVERSroute handler (403 and no signal otherwise)
cancel a jobthe owning client, or an approverDELETE uses the same scope
propose an approval from inside a sandboxnobodythe sandbox has no route to the API or Temporal

API_KEYS is a flat client-to-key map with no scopes; FACTORY_CLIENTS and FACTORY_APPROVERS are comma lists of client ids, each of which must exist in API_KEYS or the API refuses to start. Approver identity is the API client id. A real user identity for approvers (the roadmap's Zitadel identity) is not built.

Four-eyes: not built​

The plan (section 6.6) describes a four-eyes rule (submitter must differ from approver) as a policy flag, default off for a solo developer. In code:

  • FactoryRepoPolicy.approvals.fourEyes exists in the policy schema with default false (packages/agent-types/src/factory.ts).
  • Nothing reads it. A search of apps and packages finds the name only in the schema and its test. consumeApproval records approver but never compares it with factory_jobs.client, and the API does not load the per-repo policy files (the worker loads them from FACTORY_POLICY_DIR).
  • A client listed in both FACTORY_CLIENTS and FACTORY_APPROVERS can therefore submit and approve its own job today.

To obtain separation today, use disjoint client lists. The flag is a placeholder for a future check; setting it to true has no effect in the code I read. Unverified: any enforcement outside the files above.

Contradictions with the plan​

  • The plan says approver identity is "shown in the job view". FactoryJobView has no approver field; the approver appears in the stored factory_approvals.approver and in the PR body. Code wins.
  • The plan says the approval route enforces four-eyes when the policy flag is set. Code does not (above).

Not verified​

Approval flow was exercised locally only (fake git remote, scripted model). The Zitadel approver identity, a real GitHub PR and the live gate TTL behaviour are not verified (docs/deploy-factory.md).

Sources​

  • packages/agent-types/src/factory.ts (FactoryGate, ApprovalRequest, PendingGate, gateDigestInput, effectiveGates, FactoryRepoPolicy)
  • packages/agent-workflows/src/workflows/factory.ts (gate(), approvalRecorded handler)
  • packages/agent-workflows/src/workflows/factory-shared.ts (APPROVAL_SIGNAL, GateOpened, Decision)
  • apps/worker/src/factory/activities.ts (openGate, readDecision, expireGate, openPr)
  • apps/api/src/factory.ts (approvals route, scope, isApprover)
  • packages/db/src/factory.ts (openGate, consumeApproval, readDecision, expireGate), packages/db/src/schema.ts (factoryApprovals, factory_jobs_pending_gate_valid)
  • .omc/plans/p3-software-factory.md (sections 5.2, 6.6)