Skip to main content

Patch policy

The coder's output is untrusted. The only thing the host ever takes from the coder sandbox is one file, patch.diff, and it treats that file as hostile input to a parser, a path filter, a secret scan and a real git apply in a clean checkout. This page describes that pipeline (the "security core" of the factory, plan section 6.3), the protected paths, the reason codes, and how an approved patch becomes a pull request.

The pipeline is two independent layers. apps/worker/src/factory/patch.ts is a pure parser and filter with no git and no filesystem; it fails closed on anything it does not fully understand. apps/worker/src/factory/apply.ts then applies the patch with hardened git and re-checks the resulting index, which is a second check that does not trust the parser.

Pipeline​

validateAndApply(dir, patch, policy, exactSecrets) runs everything from the filter down to the manifest check, in the order shown, on a clean checkout. Any failure leaves the checkout unusable and the caller discards it. The same function runs at four points: after the coder step (runCode), when building the carried workspace for the next iteration and the review and test workspaces (workspaceTar), and again in openPr from the stored approved bytes. A rejection logs only the reason code (patch.rejected), never the offending bytes, and the next coder prompt receives only that code.

Reason codes​

PatchRejectReason (in packages/agent-types/src/factory.ts; only these, never the bytes, reach feedback or logs):

CodeRaised when
empty_patchzero bytes or no file entries (a zero-byte coder output is also reported by runCode as empty_patch)
too_largemore than 1 MiB (maxArtifactBytes)
too_many_filesmore than 200 files (maxPatchFiles)
bad_headera header line is not UTF-8, not a known form, a mode is not one of 100644, 100755, 120000, 160000, 040000, a binary block is malformed, inflates past the total bound, or a hunk line is malformed
bad_patha path is not ^[A-Za-z0-9._/@+-]{1,255}$, is absolute, ends in /, has an empty or . segment, contains .., or the header contains a git-quoted path
forbidden_pathpath is git metadata or CI configuration (list below)
protected_pathpath matches a protected glob (list below)
symlinkmode 120000 in any header (old or new)
submodulemode 160000 in any header
binarya binary patch or Binary files differ entry while patch.allowBinary is false
protected_manifest_fielda package.json change to a protected field (below)
secret_in_patchthe secret scan matched
apply_failedgit apply --check or the apply failed
index_recheck_failedthe post-apply index re-check found a link, submodule or forbidden or protected path

Precedence: a bad_path or forbidden_path verdict returns at once; protected_path and binary are collected and the worst one is returned after all files are checked.

The parser​

parsePatch reads git diff --binary output strictly. It decodes the patch as latin1 (so body bytes of any encoding survive) and checks each header line as UTF-8 separately. Header lines must match one of: diff --git a/<path> b/<path>, mode lines, index <hex>..<hex> [mode], similarity or dissimilarity index, rename or copy from or to, --- and +++ lines, GIT binary patch, or Binary files ... differ. Hunks are consumed by their line counts, so a body line can never be read as a header. Every path named anywhere (old, new, rename and copy sources) is collected and judged. Binary payloads are base85-decoded and inflated only when allowBinary is true, with an output bound per payload and a total of 4 MiB (MAX_INFLATED_BYTES = maxArtifactBytes * 4).

Forbidden and protected paths​

Matching is on the ASCII-lowercased path and also on every suffix that starts at a segment boundary, so rules apply at any depth.

Forbidden (CI definitions and git metadata; cannot be overridden except the .github allowlist below):

RuleDetail
.git or .agentforge as any path segmentforbidden at any depth
any basename starting .gitforbidden, except .gitignore (so .gitattributes, .gitmodules and other .git* files are out)
.github/workflows/**forbidden regardless of policy
azure-pipelines*.yml, azure-pipelines*.yaml, .azuredevops/**, .gitlab-ci.yml, .circleci/**, jenkinsfile, .agentforge/**forbidden
.github/** at the repo rootforbidden unless a glob in the repo policy's patch.githubAllow matches
.github as a non-root segmentforbidden

Protected (files that run code in CI or on a maintainer's machine when the PR is checked out; defaults plus the policy's patch.protected globs, which add to and never replace the defaults):

pnpm-lock.yaml, package-lock.json, yarn.lock, .npmrc, pnpm-workspace.yaml, .nvmrc, .pnpmfile.cjs, .yarnrc.yml, .yarn/**, .husky/**, .envrc, .vscode/**, .idea/**, .devcontainer/**, Dockerfile*, docker-compose*.yml, Makefile, .tool-versions, lefthook*.yml, .pre-commit-config.yaml, CODEOWNERS, docs/CODEOWNERS.

Globs: ** matches any characters including /, * matches within one segment, ? one non-slash character.

A passing test step is a coder-influenced signal: the coder may edit tests, fixtures and test config; only lifecycle scripts in package.json are protected by default. To pin tests, list their globs (for example the test directory and the test runner config) in patch.protected; a patch touching them is then rejected protected_path.

The package.json manifest check​

After the apply, for every changed file whose basename is package.json (any depth), the host JSON-parses the content at HEAD and in the index (no code runs) and compares a fingerprint of: the scripts preinstall, install, postinstall, prepare, prepublish, prepack, postpack; the top-level keys pnpm, packageManager, overrides, resolutions; and every top-level key whose name matches dependencies (case-insensitive, so dependencies, devDependencies, peerDependencies and so on). Any difference is protected_manifest_field. A missing base manifest is treated as an empty object; an unparseable manifest after the patch fails closed.

Secret scan​

patchHasSecret scans the whole patch as UTF-8 and as latin1, plus every decoded binary payload. It matches any of these, and reports only the code:

PatternNotes
sk-ant- followed by key charactersAnthropic key shape
afj_ plus a 43-character suffixgateway job token
sk-, pk-, rk- followed by 16 or more key charactersgeneric provider keys
the word Bearer followed by a token (case-insensitive)bearer values
ghp_, gho_, ghu_, ghs_, ghr_ followed by 20 or more characters; github_pat_ followed by 20 or moreGitHub tokens of any length
AKIA plus 16 uppercase alphanumericsAWS access key id
a PEM private key header (five dashes, BEGIN, optional algorithm words, PRIVATE KEY, five dashes)
HAWKEYE-CANARY- plus 8 or more hex characters or dashes (case-insensitive)canary pattern
api_key, api-key, apikey, secret, token, password (with an optional word suffix) assigned a quoted literal of 16 or more characters with Shannon entropy of at least 3.5 bits per characterthe generic rule is deliberately narrow
exact match of any token the worker minted for this job (read, PR, push), of at least 8 characters

The generic assignment rule differs from the agent-core redaction set, which rewrites any value after token = and similar. The scan keeps the narrow form because the broad one rejected honest code such as const token = getToken(). The consequence, recorded in the source and the P3-4 findings: a patch line that the redaction would still rewrite (for example password = hunter2) can pass the scan, so the artifact view may return redacted text that no longer hashes to the stored digest. The API says so with x-artifact-redacted: true, and the gate digest is always over the stored bytes. Split or encoded secrets evade the scan; the human gate is the control.

Host git hardening​

The host never runs repository code: no package manager, no hooks, no filters. Every host git call goes through runGit:

  • A fixed subcommand allowlist (GIT_SUBCOMMANDS): clone, fetch, archive, init, add, commit, apply, diff, push, rev-parse, cat-file, ls-remote, write-tree, and merge-base (added for CodeCrucible's prepare-workspace step). Any other subcommand throws.
  • A clean environment: only PATH, an empty temporary HOME, GIT_CONFIG_NOSYSTEM=1, GIT_CONFIG_GLOBAL=/dev/null, GIT_TERMINAL_PROMPT=0, GIT_ASKPASS=/bin/false, LC_ALL=C, plus per-call extras (the auth header and author/committer values, never in argv).
  • Hardening config on every call: core.hooksPath=/dev/null, core.symlinks=false, core.fsmonitor=false, core.protectHFS=true, core.protectNTFS=true, core.ignorecase=false, commit.gpgsign=false, core.quotePath=true; clone and fetch add --no-recurse-submodules.
  • Per-operation protocol flags: local operations (apply, commit, archive, add, diff) set protocol.allow=never. The https transport (real remote) sets protocol.allow=never, protocol.https.allow=always, http.followRedirects=false, so the auth header is never sent to a redirect target. The test transports (file-test, http-test) exist for the local fakes only.
  • Timeout 120 s by default (300 s for clone-sized work), SIGKILL on expiry.
  • Version floor: assertGitFloor refuses to start with git below 2.50.1, which covers the case-insensitive-filesystem CVE class (CVE-2024-32002) and CVE-2025-48384.
  • Clone: git clone -q --template= --revision=<sha> (no hook templates), only for a 40-hex SHA.

After the apply, recheckIndex runs git diff --cached --raw -z --no-renames HEAD and returns index_recheck_failed for a mode 120000 or 160000 on either side, any path that pathVerdict flags, or a line it cannot parse.

The out file​

The runner leaves exactly one file in /workspace/.agentforge/out/ per factory profile (plan.md, patch.diff, review.json; see Sandbox roles). The keeper runs tar -c -C /workspace/.agentforge/out --no-recursion -- <name> and pickOneFile reads the stream, which is attacker-influenced. It accepts only if all hold:

  • the whole stream is at most maxBytes + 64 KiB of overhead;
  • exactly one tar entry, a regular file (type 0), named exactly the expected name (a leading ./ is tolerated), with size at most maxBytes; a second entry of any kind refuses the archive;
  • the archive ends with two zero blocks (a single block or none means a cut stream);
  • the keeper's tar process exited 0 (exit is awaited; a well-formed prefix of a failed tar is discarded).

maxBytes is 1 MiB for patch.diff, 64 KiB for plan.md and 16 KiB for review.json. Anything else is artifact_invalid. Nothing is written to disk. The review file must also pass the ReviewVerdict schema (verdict is approve or changes_requested, notes at most 8192 characters); invalid output becomes changes_requested host-side.

From approved patch to pull request​

After the factory.pr approval, openPr publishes through the GitHost seam (GitHubAppHost in production, LocalGitHost plus a fake API in tests).

Rules:

  • Two GitHub Apps. App permissions apply App-wide, so a single App with write access could write every organisation repository if its key leaked. agentforge-read-pr has contents:read, pull_requests:write, metadata:read and is installed on the organisation with selected repositories equal to the allowlisted repos and their forks. agentforge-push has contents:write only and is installed only on the forks. A stolen read-PR key cannot push to any repo; a stolen push key reaches only forks.
  • Per-job tokens. An App JWT (RS256, iat backdated 60 s, exp 540 s after now) is exchanged for installation tokens scoped to the single target repo: read (contents:read, base), pr (pull_requests:write and contents:read, base and fork) and push (contents:write, fork). Tokens live in worker memory for one activity, never in Temporal payloads, database rows, logs or any sandbox. Git auth uses a per-invocation http.extraheader in the environment, never argv and never .git/config.
  • Fork only. The fork is <FACTORY_FORK_OWNER>/<name><FACTORY_FORK_SUFFIX> (suffix default -fork); startup refuses a fork name equal to any allowlisted base repo. PRs come only from the fork with head agentforge/<jobId>; same-repo branches are never used.
  • No force-push. pushBranch returns exists only when the remote branch already holds the deterministic commit; a different SHA is BranchConflict, which fails the job internal_error.
  • Deterministic commit. Author and committer AgentForge with a fixed invalid-domain address, date equal to the job's created_at, message agentforge: job <jobId>, so the same tree yields the same SHA and a retry after the PR was created finds and reuses it.
  • Closed PRs. A closed PR for the head fails the job pr_closed_by_human; it is never reopened or recreated.
  • PR base is the constant main in the activity (PR_BASE); the base branch is not stored per job. This is noted in the source as a known limitation.
  • Fork CI must run without secrets and require maintainer approval; the patch filter additionally rejects any .github/** change by default. An audit script (scripts/audit-prt.sh) must be run on every allowlisted repo before it is added to FACTORY_REPOS.

Operational detail and the GitHub setup runbook are in docs/deploy-factory.md and on Deploy runbooks.

Unverified and not wired​

  • FactoryRepoPolicy.patch.allowNonAscii exists in the schema (default false), but PatchPolicy in patch.ts has no such field and the path regex is ASCII only, so the flag has no effect in the code I read.
  • The GitHub path (GitHubAppHost) is exercised in CI only against a fake API; a live check against real GitHub is documented as an attempt with findings, and the fork layout is UNVERIFIED in docs/deploy-factory.md.
  • The residual risks recorded in the plan stand: split or encoded secrets evade the scan, and the human approver who checks the branch out runs on a workstation the worker does not control (the protected defaults and the fixed PR warning are the controls).

Sources​

  • apps/worker/src/factory/patch.ts (parsePatch, filterPatch, pathVerdict, DEFAULT_PROTECTED, FORBIDDEN)
  • apps/worker/src/factory/apply.ts (runGit, GIT_SUBCOMMANDS, validateAndApply, recheckIndex, manifestFieldsChanged, commitIndex, assertGitFloor)
  • apps/worker/src/factory/secrets.ts (containsSecret, patchHasSecret)
  • apps/worker/src/factory/outfile.ts (pickOneFile)
  • apps/worker/src/factory/git-host.ts (GitHost, publishPr, cloneVia, pushVia), apps/worker/src/factory/github-app.ts
  • apps/worker/src/factory/activities.ts (workspaceTar, runCode, openPr, PR_BASE, toPatchPolicy)
  • packages/agent-types/src/factory.ts (PatchRejectReason, FactoryRepoPolicy, ReviewVerdict, FACTORY_LIMITS)
  • docs/deploy-factory.md, .omc/plans/p3-software-factory.md (sections 6.3 to 6.5)