How the Foundry is built
How the Foundry is built and why. For how to use it, see the user guide; for the format of flows, FLOW_AUTHORING.md; for the reasons behind many of these choices, LESSONS_LEARNED.md.
- 1. What it is
- 2. Design principles
- 3. The parts
- 4. Flows and the engine
- 5. Agents and models
- 6. The queue
- 7. Watchers: from GitHub issue to merged code
- 8. The two pipelines
- 9. Branches: gitflow
- 10. What happens next
- 11. Accounts, roles and repositories
- 12. Safety
- 13. Data on disk
- 14. The server and its restarts
- 15. The web interface
- 16. Tests
- 17. Self-repair
- 18. Where it is going
1. What it is#
An AI coding factory that runs on one machine. Work is described as flows: YAML pipelines of agent steps (Claude Code or Codex), shell steps, approvals and branches. The Foundry runs them headlessly against git repositories — from a task someone types, or automatically from GitHub.
Its main use: put one label on a GitHub issue, and the Foundry asks the open questions, plans, codes, tests, reviews and merges the story, asking a person only when it has to.

Node.js and TypeScript (ESM), no web framework, no database. About 15,000 lines of source and 2,100 tests.
2. Design principles#
- Facts by code, judgement by agents. Whatever can be checked by a shell step (tests pass, size is under the limit, the branch is clean, no secret is pushed) is checked by a shell step. Agents plan, write and review.
- A person only where a person is needed. A risk score decides; questions are asked up front; everything else continues by itself, at once.
- Always say what happens next. Every story and run has one plain sentence: who acts next and what they do.
- Runs are isolated and resumable. Each run has its own folder and its own copy of the code. Any run can be continued from the step where it stopped.
- State lives in files and on GitHub. No database. A run is a folder; the queue is a file; the backlog and its status are GitHub issues and labels.
- Safe by default. Protected branches, a secret scan, budgets, read-only tools for reviewers, permissions enforced on the server.
- Text from outside is data. Issue text, comments and step output never become part of a shell command.
- Small parts, no magic. Plain modules, plain JavaScript in the browser, flows generated from shared blocks.
3. The parts#
flowchart LR
subgraph People
B[Browser]
C[Command line: scf]
end
subgraph Foundry["Foundry server (one Node.js process)"]
API[HTTP API + permissions]
W[Watchers]
Q[Scheduler / queue]
E[Engine]
N[Next step, Your turn, board, health]
end
subgraph Outside
GH[(GitHub: issues, labels, branches)]
A1[Claude Code CLI]
A2[Codex CLI]
L[Local models]
end
D[(Data folder: runs, queue, accounts, config)]
B --> API
C --> E
API --> Q
API --> N
W -->|every few minutes| GH
W --> Q
Q --> E
E -->|agent steps| A1
E -->|agent steps| A2
A1 -.-> L
E -->|shell steps: git, gh, tests| GH
E --> D
Q --> D
N --> D
| Folder | What it holds |
|---|---|
src/engine/ | Runs a flow: steps, jumps, budgets, guards, resume |
src/steps/ | The step runners: Claude Code, Codex, shell |
src/agents/ | Choosing agent, provider and model; limits, retries, sign-out |
src/flow/ | The flow format (schema), loading, blocks, publishing to users |
src/queue/ | Scheduler, watchers, dependencies between issues, status comments |
src/stories/ | The story store: one interface for a repository's stories and pull requests, GitHub behind it |
src/server/ | HTTP API, permissions, board, health, Your turn |
src/auth/, src/credentials/ | Accounts, sessions, repositories per user, stored tokens |
src/next-step.ts, src/words.ts, src/errors.ts | The one vocabulary: what happens next, status words, explained errors |
ui/ | The web interface: plain JavaScript modules |
flows/, blocks/, scripts/build-flows.mjs | The shipped flows, the block library, and the generator |
tools/ | Helper programs that flows call |
The story store (#734)#
src/stories/store.ts defines StoryStore: everything the Foundry does with a repository's stories
(issues) and change requests (pull requests). storeFor(repo) returns the store of a repository, one
instance per repository string. Today it is always GitHubStore (src/stories/github-store.ts), which
wraps the functions of src/github.ts with the same arguments and timeouts, and calls gh directly
where no such function exists. The data types (Issue, RestIssue, Comment, UpsertResult) stay
in src/github.ts; the store reuses them.
- No session in the store. A store keeps no
ghsession. Each call runs in the caller's session (withGhEnv), as before. - Inputs are checked first. Issue numbers, pull request references, commit SHAs and list sizes are
checked before
ghruns, so they cannot becomeghoptions or API paths. - The synchronous part.
tools/waits-forrunsghitself, synchronously, so it cannot await the store.store.sync(run)returns aSyncStories(get,list,setBody) bound to the caller's runner (aGhCall). A confirmed not-found givesundefined; a malformed answer or anothergherror throws. The body ofsetBodygoes on stdin. - The status marker is unchanged.
upsertStatusCommentstill finds the Foundry's comment by<!-- claude-factory status -->;BOT_MARKER,BOT_MARKERSandSTATUS_MARKERare not changed. - Every story call goes through the store. The guard,
tests/story-store-guard.test.ts, scanssrc/,blocks/,tools/andscripts/build-flows.mjsfor story calls (gh issue,gh pr,gh apion issues, pulls, labels, check runs, or the issue-state GraphQL). Outsidesrc/stories/github-store.tsandsrc/github.tsthere is no story call: the allowlist in that test is empty (#739). The helper scripts intools/(create-split,split-family,post-questions,decide-questions.mjs,daily-branch,issue-digest) loaddist/stories/store.jsand usestoreFor(repo).sync(gh), with the sameghrunner andFACTORY_GH_BINas before. A new story call goes into the store, never into a file. - A caller that owns its process.
openChangeWithtakes a runner: the store builds thegharguments and the broker starts the process, with its exact environment, pinned secrets and limits. - Flow steps use
tools/story. The built-in blocks that read or write a run's story callnode "$FACTORY_TOOLS/story"(#737) instead ofgh. Change-request (pull request) steps and the inline steps of the built-in flows use it too (#738):open-pr,merge,ciandpr-commentscall itspr-…subcommands. The tool loadsdist/stories/store.js, so a step reaches the store through one helper, and bodies go through stdin, never a shell argument. Where gh's output or exit status must reach the step whole (pr-open,pr-merge,pr-checks,pr-checkout), the store runs gh withghInherit(src/github.ts): gh writes straight to the step's stdout and stderr, and the exit status is gh's (a signal gives 128 plus its number). Every other call goes throughgh(). - A local store for a project without GitHub (#764).
LocalStore(src/stories/local-store.ts,new LocalStore(dir, repo)) implements the sameStoryStore. A story is a file in<dir>/.scf/stories/(the format ofsrc/stories/story-file.ts).src/stories/local-map.tsscans the folder and maps the files toRestIssue,IssueandComment. Every call reads the files again, so a hand edit is seen at the next call. Numbers come fromnext-number, or one above the highest number found when it is missing; a number is never reused, becausenext-numberis written before a story is created. A write takes the lock.scf/stories/.lock, created exclusively with the holder's PID and a token. A lock whose holder is gone, or that is older than 5 s without a readable holder, is taken over under a guard file (.lock.takeover). Waiting has a limit (10 s by default). A write goes to a temp file and is then renamed (writeAtomic). A file that cannot be read is never dropped or overwritten: lists show it as a story titled "cannot be read" with the reason in its body,getreports it, and a write to it fails. Pull request methods fail with "Pull requests are not available for a local project".storeForstill returnsGitHubStorefor every repository. The shared contract suite (tests/story-store-contract.ts) runs against both stores. - The flow steps on a local store (#765).
LocalStoreimplements thestep…methods ofStoryStoreandsync(run). The texts are built insrc/stories/local-text.tsfrom aStoryView(toView()inlocal-map.ts, the ghissue view --jsonshape), not by running the jq programs ofgithub-store.ts. Every comment has a stable id:nextCommentId()gives the next one above the highest used, andcomment_topin the front matter keeps a removed comment's id from being given out again. Writes from the synchronous part usewithStoryLockSync()(story-lock.ts), which blocks while it waits for the lock, sosyncis for a tool process only. Both paths share one write body (applyChange()).
The public package (#780)#
The package @melomar-it/scf-core has one public entry, src/index.ts, and package.json
exports lists only ".", so a deep import into dist/ fails. index.ts re-exports each name by
hand, with no export *, so adding or removing a public name is a visible edit. The build writes
.d.ts files (declaration: true in tsconfig.build.json), so consumers get the types.
tests/public-api.test.ts compares the real exports (values by kind, types from the text of
index.ts) with tests/public-api.snapshot.json, and apiChange decides whether a change needs a
minor or a major bump. PLUGIN_API_VERSION is checked against the snapshot. The publish workflow
runs on v*.*.* tags, checks that the tag matches package.json, and before npm publish imports the
package by name. scripts/release-notes.mjs writes the Plugin API: line. The public surface and
the promise are in PLUGIN_API.md.
Plugins from config (#781)#
src/plugins/load.ts loads the plugins: list of config.yaml once, in startServer, after the
config is checked and before the queue and the watchers are built. loadPlugins resolves each
module (a package name through import.meta.resolve, an absolute path as it is), checks that its
real path is not inside a runs folder or a repository (blockedDirs), imports it under a 30 s
deadline, and calls register(api) under the same deadline. The first failure throws a
PluginLoadError that names the module; startServer logs it and rethrows, so there is no
half-started server. api is frozen and holds version (PLUGIN_API_VERSION) and a copy of
options; the plugin points are added to it by the parts after this one.
The registry (ApiContext.plugins) is read-only after start. pluginProblems combines the problems
recorded at runtime with a check of the file: when config.yaml now lists other plugins than the
loaded ones, or cannot be read, the health line shows it. PUT /api/config refuses a plugins key
(400), and a save without the key keeps the stored list (withStoredPlugins), so the settings page
cannot change it. The settings inventory lists plugins.* as exceptions: the file is the only place to set them.
Identity provider (#833)#
A plugin may supply one identity provider (api.identityProvider({ resolve }), plugin API 0.4). The
provider owns sign-in, role and workspace; the Foundry keeps a mirror record per account in users.json
(source: "provider", optional workspace) so the places that call getUser(id) keep working, and the
scheduler's account check does not cancel the queued work of an unknown account.
src/auth/identity.tsis the slot, the 5 s deadline with anAbortSignal, the 8-call cap and the strict answer check (zod,.strict()). It imports only zod andworkspaces/list.ts, soplugins/load.tscan use it without a cycle. It reports fixed reasons only.src/server/identity-session.tscopies the request without the session cookie, and signs in or rechecks. Reads of the stores happen after the provider answers, so a change made meanwhile wins.src/auth/provider-users.tswrites the mirror record under the auth lock. A recheck takes no lock when nothing changed and never creates a record.src/server/api-auth.tsasks the provider on every API call of a provider session (requireSession), andGET /api/sessionsigns in. While a provider is active, sessions of local accounts do not count, and password sign-in, setup and password routes are refused.- Provider accounts have no password;
src/auth/users.tsrefuses the password and profile actions withprovider-account(409) and leaves local admins alone inhasAdminandisLastAdmin. src/server/workspace-scope.tsgives a provider user its one workspace;src/server/server.tschecks authentication after the plugins register, so a provider-only install may listen on a non-local address.
Workspaces (#816)#
A workspace is a team. Each repository record, each watcher's runs and each queue entry belongs to exactly one
workspace; a run without a repository is in default. src/workspaces/list.ts holds the schema of the list
(WorkspaceListSchema, used by ConfigSchema as workspaces, so a bad entry stops the config from being read),
the id rule (WORKSPACE_ID_RE, default reserved) and the one supplier slot that api.workspaces(store) takes
(supplyWorkspaces()). The file imports only zod, so config.ts, usage/schema.ts and plugins/load.ts can
use it without an import cycle.
src/workspaces/index.ts answers the lookups and never throws: workspacesOf(userId) (an account may be in
several workspaces; none gives default), workspaceOfRepo(id), workspaceOfRun(runId), limitsOf(id) and
knownWorkspace(id). currentWorkspaces() reads the plugin's list when one supplies it (a list that fails the
check, or a list() that throws or returns a promise, is empty and is reported once), else the list of
config.yaml. workspaceForJob() looks the repository up by its name, and by the owner when several accounts
have a record of it.
The workspace is decided once, when the scheduler queues a job (Scheduler.workspaceFor()), from the variables
the run will use (freezeRunVars() freezes them at the same time). It is stored on QueuedJob and passed to
runFlow as workspace, and run.json keeps it only when it is not default, so older runs and installs
read as before. The flow's own workspace setting (empty, repository, …) says where a run checks out code and
plays no part here. Usage events take the run's workspace (common() in usage/events.ts), and the schema
refuses an empty value.
The Settings page has no control for the list yet (workspaces.* are in settings/exceptions.ts).
setRepoWorkspace() in auth/repos.ts is the only writer of the record field, behind the admin route
PUT /api/admin/repos/:id/workspace. authPlan() and transferRepo() keep the field, so a change of sign-in
or an owner change does not move a repository.
Workspace limits and fair share (#819)#
The limits are enforced by the scheduler (src/queue/scheduler.ts), not by a second picker. default and evals
(localTest) have no workspace limits, and the scheduler never asks for them.
- Holds in
limitOf(). After the account limits,wsHold()returnsworkspacewhen the workspace hasmax_concurrentactive jobs (chores count too), orworkspace_budgetwhen its monthly spend is atmonthly_budget_usd. The budget counts only whencost_limitsis on. A held job gets the samelimitmarking as an account hold, so the status text comes fromwords.ts(user_limitwithworkspace: true). - Spend.
spentThisMonthByWorkspace()insrc/engine/state.tssums the cost of the runs of the workspace whosestartedAtis in the current UTC month. It reads every run file (no early exit at an older run) and caches each file's value by mtime and size, so a run that is still writing is read again. - Month rollover. A held budget has no event that ends it, because nothing runs while it holds. A timer
(
monthTimer) re-runspump()at the next UTC month start (at most every 12 hours). It is stopped when no budget holds a job, and inclose()anddrain(). - Round robin. Story starts pick the workspace with the oldest
lastStartOfWorkspaceentry, using the samestartSeqcounter as owner fairness. Inside that workspace the order is unchanged: the priority block first, then the group with fewest active runs, then queue order.behindPriorityonly counts priority jobs of the same workspace. With one workspace the turn never changes the order. - Test slots. The scheduler does not count test slots.
workspaceSlotEnv()(src/workspaces/index.ts) gives shell and agent stepsFACTORY_WORKSPACEandFACTORY_WORKSPACE_TEST_SLOTS(empty when the workspace has no limit);src/release/host.tsforwards the same two variables to release builds.tools/test-slottakes a slot in<slots-dir>/workspaces/<id>/slot-Nbefore the machine slot, and the order (workspace, then machine) is fixed so two waiters cannot each hold one and wait for the other. The id is checked against^[a-z0-9][a-z0-9-]{0,39}$before it is used in a path. A workspace limit is never skipped: when the slot does not come free, the command is not run and the tool exits 75. A slot folder holdspid(the holder's pid only, written through a rename) andstart(the holder's start time,ps -o lstart=in UTC). A slot is taken over when its pid is not a positive whole number, when it has no pid and is older than 30 s, when the holder is gone, or when the pid now has another start time (reused). A slot that cannot be read, or has no or an emptystartwhile its holder is alive, stays held. A takeover runs underslot-N.lock.<n>(newest generation only, 30 s stale limit), and a holder removes a slot only while itspidis still its own (#1029).
Workspace folders (#824)#
Runs and area locks of a workspace other than default live under <data>/workspaces/<id>/ (runs/, locks/).
default keeps <data>/runs and <data>/locks; nothing is migrated. The runs folder stays the anchor: runsDir
is still the one folder the callers pass around, and workspaceDir() derives the container from its parent
(dirname(runsDir)). src/engine/state.ts holds the helpers: workspaceDirsIn() lists the workspace folders
(real folders with a valid id; links and files are skipped), workspaceRunsDir() and allRunsDirs() give the
runs folders (<data>/runs first, so it wins a duplicate id), runDirOf() and listAllRunIds() find a run in
any of them, and runIdTaken() checks a supplied id. workspaceDir() and workspaceRunsDir() refuse a bad id
and a workspaces/<id>, runs or locks link that leaves the data folder. src/home.ts has workspaceHome().
- Ids are reserved, not checked and written. A new run takes its id with
mkdirwithoutrecursive, so an existing folder is an error and a run is never overwritten. The same check covers a supplied id and two creations at once. - Locks.
lockRoot(ws)andallLockRoots()(src/engine/running.ts) give a workspace run<data>/workspaces/<id>/locks, set asSCF_LOCK_DIRandFACTORY_LOCK_DIRfor its steps (src/engine/execute.ts,src/agents/run.ts). The monitor's area locks use the key prefixworkspaces/<id>/. - Sandbox.
src/engine/os-sandbox.tsallows the workspace's lock folder and denies the default runs root, the workspace container derived fromrunsDir, and the plugin exclusions. This holds for a custom--runs-diroutside the home, data and temporary folders. - Sweeps, budgets and clean.
sweepRunning,sweepStaleRunning, the server's sign-in-folder sweep,migrateDataHome(src/home-migrate.ts),clean(src/clean.ts) and the daily budgets (spentToday,spentTodayBy,spentTodayByProject) read every folder.adoptRuns(src/auth/run-owner.ts) adopts ownerless runs in both layouts and still skips refinement runs. - Removed workspaces are read-only. A workspace that is no longer in
config.yaml(knownWorkspace()) fails a new run or a resume withWORKSPACE_REMOVED(Scheduler, both at queueing and inrunFlow).Scheduler.answerthrowsAnswerRefused;setArchivedreturns"removed", whichapi-runs.tssends as 409; park and clear-park return false. The check runs before the saved run is written, so a refused operation leaves it unchanged. Cancel and explicit clean still work; the runs stay listed. - Watcher.
src/queue/watcher.tsno longer creates a run folder for its "planned" log lines. It keeps them in memory and writes them once the run exists, so a restart before that loses them.
Known gaps for part 2 (#818). These still read one runs folder and see only <data>/runs: scf ops, evidence
(evidence and delivery verify), analyst/cli, ops/usage.ts and ops/flaky.ts. Runs of other workspaces are
invisible to them until a later change covers them. lifecycle-cli and release-cli read every runs folder since #825.
Workspace skills folders (#825)#
A workspace other than default has its own administrator skills folder, <data>/workspaces/<id>/skills/.
workspaceSkillsDir(ws, data?) (src/home.ts) gives it for a valid id other than default, and <data>/skills for
default, no workspace or an invalid id. workspaceSkillsFolderIn() (src/engine/state.ts) builds the path and
throws when a workspaces/<id> or skills link leaves the data folder.
- Registry.
DiscoverOptions.skillsDirreplaces the first source, the data-folder root, inbuildSources()(src/skills/registry.ts). The release store,skills.roots, the built-in skills and the repository stay install-wide, and so do the pins (skills.lock.json), the lifecycle record and the release manifests. The cache ofcachedSkillRegistryAt()keys on the home, the repository and the skills folder, and holds up to 16 registries (MAX_CACHED) instead of one. - Callers. A run uses the registry of its own workspace in the skill catalogue (
src/agents/run.ts), the skill lock and draft list (src/engine/skill-lock.ts), the plan check (src/skills/run-plan.ts), the run page's skill view (src/server/api-runs.ts) and the allowance (src/server/api-skills.ts).scf skillstakes--workspace <id>forlist,pinandlifecycle(src/skills/cli.ts);allow-runtakes none. - Finding a run.
chosenRunDirs()(src/skills/lifecycle-cli.ts) maps each run id of every runs folder (allRunsDirs()) to one folder. The first folder with arun.jsonwins, as inrunDirOf(); a folder with only a skill lock counts only when no folder has arun.jsonfor that id.runsLocking()(used when a lifecycle state changes) andreleaseList()(src/skills/release-cli.ts) use it, so a team's run is listed. - Allowance.
applyAllowance()takes a registry per workspace.runWorkspace()reads the workspace from the run'srun.jsonand usesdefaultwhen it is missing or invalid. A run that is not found is checked against thedefaultregistry and answersno-run; the allowance never falls through to another folder's lock. - Tests.
tests/workspace-skills.test.ts(folders, link check, cache, run lookup, allowance, CLI flags) andtests/workspace-skills-run.test.ts(a team run with its skill, the run page, an allowance through the team registry, the catalogue).
4. Flows and the engine#
A flow is a list of steps. A step has a type:
| Type | What it does |
|---|---|
claude | An agent step: a prompt, a model, allowed tools. Runs on Claude Code or Codex |
shell | A command. Its output and exit code decide the path |
approval | Stops and waits for a person |
parallel | Runs several steps at the same time |
flow | Runs another flow as one step |
The path through a flow is decided by each step's result: on_success, on_failure,
routes (a pattern in the output picks the next step), pass_if, and the reserved targets
next, end, fail and stop. max_visits limits loops such as test → fix → test.
jump_only steps run only when another step sends the run there.
A run is a folder with run.json (status, history of steps, variables, cost), a log per
step, a readable transcript per agent step, and the workspace. The flow definition is stored
with the run, so a resume behaves the same even if the flow changed meanwhile.
Run states: running, waiting (for a person), stopped (paused, can continue),
succeeded, failed, cancelled.
Workspaces. worktree (a git worktree on its own branch), empty (the flow clones what it
needs — used by the GitHub flows) or inplace.
Passing information. A step's output is available to later steps as a template value and as
an environment variable ($FACTORY_OUT_<STEP>); flow variables as $FACTORY_VAR_<NAME>. This
is how untrusted text travels: as environment variables, never pasted into a command.
Shipped flows are generated. scripts/build-flows.mjs builds flows/*.yaml from shared
pieces (plan phase, test-and-fix loop, review loop, merge). The YAML files are never edited by
hand.
The skill path#
Skills reach an agent in a fixed order. Each stage has its own module:
- Profile and catalogue:
src/skills/repo-profile.ts,catalogue.tsandrun-catalogue.ts. - Import evaluation (
src/skills/evaluate-cli.ts, read throughstaged-cli.ts):scf skills selections evaluaterunsevaluateSourceSkillson a staged import and the selections. It is offline and writes nothing; no run reads it. - Collisions (
collisions.ts, rules incollision-rules.ts): pure classification and merge of normalized skills; reached fromrun-catalogue.tsonly through its optionalcandidatedependency, which no run supplies yet. - Canonical selection (
canonical.ts, rules incanonical-rules.ts, facts incanonical-facts.ts): pure choice of one winner per exclusive capability, in the precedence order ofCANONICAL_LEVELS; reached fromrun-catalogue.tsonly through its optionalcanonicaldependency, which no run supplies yet. - Reviewed frontend profiles (
frontend-rules.ts, data only;frontend-connector.ts, pure functions): used bysource-evaluation.tsonly for a source whose repository has a profile. Selection happens before normalization, and the profile is authoritative: its capabilities, technologies and category replace the upstream ones, and ascopeis refused. A folder is reviewed only by a digest in its own rule, added by a code change. - Source evaluation (
source-skill-evaluation.ts, re-exported bysource-evaluation.ts, Azure markers inprovider-rules.ts): pure per-skill verdict of an imported source (selection, licence, undeclared provider needs, overlaps, provider rule); no run calls it yet. - Licence review (
licence-review.ts): the digest covers the whole licence evidence that can apply to the staged folders (every licence and notice file above or inside them, with its hash or problem), not only the attribution of the promoted skills. A change to a rootLICENSEtherefore needs a new review even when every skill keeps its own licence. Promotion reads it throughlicenceReviewProblem. - Provider assumptions (
provider-assumptions.ts): a pure, declarative scan of a skill's declared tools,compatibilityand instructions for Claude, MCP and Anthropic API references. It is recorded inSkillProvenance.providerand never grants a tool or blocks a skill. - Source profiles (
src/skills/source-profiles.ts): pure parser and safe reader ofskill-source-profiles.yaml, read only byscf skills profiles check; no run reads it yet. - Skill lifecycle (
lifecycle.ts, commands inlifecycle-cli.ts): the recordskill-lifecycle.jsonlin the data folder is append-only JSON lines, one transition or run allowance each, withseqcounting from 1. The reader replays every line through the same rules as the writer (lifecycleTransitionProblem: no same-state change, nothing leavesrevoked; an allowance only for a quarantined key). A line that is invalid, has an unknown field, has aseqgap or afromthat does not match, a symbolic link, or a file over 4 MiB makes the read fail closed; the reason never holds the file content or the path. Writes take the data-folder lock (openAppendLocked) and check the size under it, so a write that would pass 4 MiB is refused withfulland nothing is written.effectiveLifecyclemerges the local status with the revocations of approved release manifests: a release revocation wins, and it carries no allowances. The registry (registry.ts) keeps the non-active statuses (lifecycle) and the release revocations (revoked) separately frombyKey. A registry with an unreadable record has alifecycleproblem, and then every id is refused withineligible. Selection (resolve.ts) refuses quarantined, retired and revoked versions with reason codeineligible, with no fallback to another version of the same id. Run locks (run-lock.ts) apply the policy to versions that are already locked: revoked always stops, quarantined stops unless the run is allowed, and the other states only add notes (runSkillLockNotes, written bysrc/engine/skill-lock.ts). The admin routes inapi-skills.tscall the same apply functions as the command line, withwaitMs: 0, and clear the registry cache after a write. - Evaluation gate (
evaluation.ts, thresholds inevaluation-rules.ts): pure verdict of a candidate from its evaluation record; see "Evaluation gate" below. No run calls it yet. - Import review (
import-review.ts, rules inimport-review-rules.ts, command inreview-cli.ts): pure report of a staged import against the registered skills (licence, attribution, scan, collisions, category); reads only, promotes nothing. - Request:
src/skills/request.ts; the gates arerisk_gateandpost_plan, and the check is the tooltools/skill-request. - Check after the gate:
planRunSkills,startRunSkillsandrecheckRunSkillsinsrc/skills/run-plan.ts, withresolve.tsandassessSkillsinunresolved.ts. - Plan record and carry:
src/skills/plan-record.tsandcarryRunSkillsinsrc/engine/plan-carry.ts. - Lock:
ensureSkillLockinsrc/engine/skill-lock.tsandsrc/skills/run-lock.ts. - Session:
skillSessioninsrc/engine/skill-lock.ts,src/skills/payload.tsandsrc/agents/run.ts. - Run page:
src/server/skill-view.tsandui/run-skills.js.
Design rules:
- The resolver and the policy are pure modules: same input, same answer.
- Nothing is written to the workspace, so no skill file appears in a diff.
- Messages are built from validated fields, never from request text.

Approvals in the data folder (#798)#
Part 2a of #775 lets the server record approvals itself, in skill-approvals.json in the data folder (src/skills/approvals.ts):
- Store. Schema 1, per source id: the repository key, an optional approved commit (
ref) and the releases (catalogue, version, digest, and optionalkeyandsignature). The file is at most 256 KiB and at most 200 sources and 100 releases per source. It is written atomically with mode 0600, under theskill-approvals.lockfile. A read never throws: a missing file isnone; a link, a special file, a bad schema or an over-size file isunreadable. A write over the size limit is refused (too-large) and keeps the old bytes. - Merge point.
approvedReleases(rel)is the only place where the config list and the stored list meet. The same digest in both is one entry (the config entry wins). Two different digests for one catalogue and version drop both and report a conflict. The registry,release list/verifyand the approval code all call it, so they see one list. - Refusal. A root whose release is in conflict is refused (
root-refused) before theallow_unreleasedcheck, for store and administrator roots alike. An unreadable store is a problem; the config entries still load. - Ref overlay.
readSourcesreplacesref.approvedwith the stored commit for an enabledupdate.autosource of the same repository key (withApprovedRefs). The default reads the data folder;{ approvals: false }returns the raw file.update --dueand release publish overlay the entries they use.update-cliedits the raw file, so its "changed on origin" check compares the raw entry (existingRaw), and a stored commit is never a false change. - Automatic approval.
approveAutoRelease(src/skills/auto-approve.ts) is the entry point for part 2b. It checks the source (first-party, enabled,update.auto), the stored release and its verification, and that every package comes from the source's repository with first-party trust. It refuses a conflict with config or store. Whenskills.releases.keysis set it signs withskills.releases.auto_key(the key must matchkeys[id]). Its order is fixed: the audit line is prepared under the audit lock first (a failure refuses and changes nothing); then the store entry is written; then the audit line is appended. If the append fails after the write, the result isapprovedwith a note, and the store entry is the durable record. A rollback is not done, because it would be riskier than the note. - Not in this part. The automatic update chain (#799, below) is the first production caller of
approveAutoReleaseandrecordApprovedRef. Retention of automatic releases (removing old folders under a lock, with run-lock checks) is a later part and is not here; no release is deleted by this change.
Automatic update (#799)#
Part 2b of #775 turns a due update of a first-party source with update.auto into a release and an approval, with no pull request. The chain is autoUpdate() in src/skill-import/update-auto.ts, called by updateSource (update-cli.ts) for a due run of such a source. Every other run keeps the review pull request.
- Order. Fetch the commit of
ref.track; stage it (stageSource, quarantine only); run the gates per skill and the evaluation suite of the catalogue, when it has one; publish the release; approve it withapproveAutoRelease; record the commit withrecordApprovedRef. Each step writes oneskill-auto-updateaudit line. Nothing waits for the network after the publish. - Gates without review files.
src/skills/release-publish.tssplits the oldbuildReleaseloop intogateReleaseSkills()(per skill, returns the passed skills and the failures with a gate name) andfinishRelease()(builds the manifest and the release).buildReleasekeeps its committed-review path and its results; the automatic path needs noskill-releases.yamlorskill-sources.yamlreview file. The chain builds its gate input insrc/skills/auto-release.ts(buildAutoRelease()), which reads the approved releases of the data folder. - Partial release. A skill that fails a gate is left out. The release holds the others, and the failures are recorded, so one bad skill never stops the source. A source where every skill fails releases nothing (
blocked). - Versions.
autoSkillVersion()insrc/skills/auto-version.tsis pure: no approved base gives1.0.0(or a higher declared version); the same digest as the base keeps the version; a higher declared version wins; a changed file list is a minor bump, changed text a patch bump.bumpMinorandbumpPatchdrop a prerelease part. The base is the newest approved release that holds the skill. A pinned version is never edited; a change gets a new version. - Catalogue. The catalogue id is the source id; the version is
1.0.<n>, one above the highest1.0.<k>in the release store or in the approvals (nextAutoVersion,AUTO_VERSION_RE). A stored release with the same id, version and different bytes refuses the publish. - Record.
src/skills/auto-updates.tswritesskill-auto-updates.json(schema 1, mode 0600, atomic, under a lock). Per source:at,commit,result(released,unchanged,blockedorfailed), an optionalreleaseand the failed skills. A failed skill hasskill,gateandmessage, wheremessagemust equal the fixed sentence of its gate (GATE_MESSAGES). The record holds no upstream text. Read never throws; an unreadable file isunreadable. - Concurrency. One chain per source at a time:
autoUpdate()takesskill-auto-update-<id>.lockin the data folder without waiting.recordApprovedReftakes the stored commit it expects; a commit changed meanwhile givesstaleand the run stops with aPROBLEM, though the release stays approved. - Failures. A fetch failure writes an audit line and a
PROBLEM, no release and no record. The sweeper (src/server/skill-update-sweep.ts, actormonitor) turns thePROBLEMinto a monitor finding, as for review sources. - Not here. The route and the Skills card for the record are part 3 (2c). The record is the input for those issues.
Evaluation gate#
A candidate skill is promoted only on one verdict from its evaluation record (src/skills/evaluation.ts, #501):
- Record.
EvaluationRecord(schema: 1) holds the candidate, the suite digest and scenario inputs, the runtime, the time, the scores of every sample per dimension, findings and evidence. Its digest hashes a header line and canonical lines, so key order does not change it. A credential-like text anywhere in the record is refused. - Dimensions.
selection,instructions,conflicts,contextandtools. The four offline ones are always mandatory;instructionsis mandatory only when the suite says so. A suite can make a threshold stricter, never looser. - Verdict.
evaluationGatepasses only when every mandatory dimension meets its threshold, the safety gate (promotionBlockers) has no blocker and the licence isallowed. Each failure has a reason code. - Modes.
newuses absolute thresholds.upgradealso requires that no score is lower than the baseline (the record of the current canonical version) by more than the sample spread or 0.1.duplicatecompares two candidates for one capability and names the clearly better one, or reports no clear difference. - Outcome.
evaluationOutcometurns the result into thepassedorfailedvalue ofCanonicalCandidate.evaluation.
The gate reads no clock, file, process or network, and gives the same answer for the same input in any order. Running suites and storing records is a later step.
Agent runs of the scenarios (#536)#
scf skills score <source> --agent (src/skill-eval/score.ts, runner in src/skill-eval/run.ts, packages in package.ts, fixtures in fixture.ts) runs each instructions scenario with a Claude agent. Each run is one arm of the flow built in memory: workspace: empty, skills explicit, and the steps fixture (a clone of the snapshot), work and check, all boxed. It is not a flow file.
- The user's run is reused. The temporary data folder has no user entry for its owner, so
userAccounttreats the run as a user's run and fails closed. That turns on the OS sandbox, the short environment, step isolation and the private agent home (sandboxedRun,shortEnvRun,stepIsolated,agentHomeEnv) without a change to the engine. The evaluation adds only what a user's run lacks: the evaluation limit below, and adontAskwork step with the tools of its scenario policy. - One process-wide folder switch.
switchDataFoldersetsFACTORY_HOME,SCF_HOME,FACTORY_LOCK_DIRandSCF_LOCK_DIRto the temporary folder. The four are needed because the sandbox, the running-job and monitor code each read a different one first. It also setsFACTORY_NO_NOTIFY=1andFACTORY_NO_FAILURE_MODEL=1, and clearsSCF_STEP_ENV_PASSandFACTORY_STEP_ENV_PASS.serverPassList(src/engine/short-env.ts) is always applied, so the environment of a run holds only the model key. Everything is restored infinally. The real data folder gets only the evaluation record, and itsskills.lock.jsonandskills/stay byte for byte the same. - Arms run one after another. The candidate is written as a Foundry package with
idas theSKILL.mdname, and its digest is kept as evidenceagent-package. A baseline is copied unchanged and its digest is checked. Each arm has its ownskills.lock.json, so no arm sees another arm's skill. The arm folder is removed when the arm ends. - Paired baselines. Each of the (at most four) baselines from
gateChecksruns the same number of times as the candidate, with the same suite. Its offline score is made too. The results go into the candidate'sagentblock, so the gate compares the pair in one record. This is needed because addinginstructionschanges the suite digest, which makes every stored baseline record of an older suite mismatch.gateImportandcompareBaselinetherefore prefer the paired baseline. - Limits. While a run is in progress, the evaluation limit (#534) holds: outbound TCP only to the model's port, the real data folder unreadable, and only the scenario's tools. The network is therefore not host-limited, and the record says so (
agent.network). - Stop and cleanup. Each job has a deadline: fixture 120 s, work
timeout_sec, check 300 s. On SIGINT, SIGTERM or an error, every job is cancelled and awaited before the folders are removed and the environment restored. Then the run printsPROBLEM the evaluation was interruptedand writes no record, so a record is never written from a partly run arm. - Refusals first. Before anything is made, a run is refused when the sandbox is missing or switched off, the suite has no
instructions, the agent is not Claude, the model key is missing, or a fixture's hash differs from the suite digest's (evaluationSuiteDigestcovers profile findings only, so instruction fixtures get their own content hash). - Shared code.
scoreImportinsrc/skills/evaluate-cli.tsis split intoprepareScoringandwriteScores, so the offline and agent paths write the same record.skillsCommandgets the runner asagentScore, sosrc/skills/cli.tsstarts no process; a guard test forbids a dynamicimport()there.
Skill effect (#456)#
scf skills effect (src/skills/effect.ts for the pure logic, src/skill-eval/effect.ts for the run, store in evaluation-store.ts) asks whether a skill changes an agent's result on the sample tasks. It reuses the runner of #536: each offered instructions scenario runs repeat times with the skill and repeat times without it, on the same model, in the same sandbox. The user guide says how to run it (Measure the effect of a skill).
- Measurement. The outcome is the pass rate of the scenario check, counted per run. Tokens and time are recorded and reported, and they do not enter the verdict.
- Why not review findings. A reviewer session per run would double the cost. The reviewer is itself a model that can be swayed by the skill it reviews, and there is no fixed scale to compare runs on.
- Why not fix rounds. The evaluation flow has one work step. Fix rounds exist only in full flows, and they are capped, so they would mostly measure the reviewer.
- Rule. A two-sided Fisher exact test on the pass counts of the two arms (
EFFECT_RULE: p ≤ 0.05 and |difference| ≥ 0.2). The result ishelpsorharmswhen both hold, otherwiseno-measurable-effect. A skill that is not offered in any scenario, or is never loaded in the with arm, isnever-selected. The test is exact rather than a normal approximation, and each arm is capped at 200 runs (EFFECT_LIMITS), which bounds the computation. - Sample size. With fewer than 4 runs per arm no result can be significant: 3/3 against 0/3 gives p = 0.1. The recommended size is 5 scenarios ×
repeat4 = 20 runs per arm, which detects 0.9 against 0.5 (18/20 against 10/20, p ≈ 0.014) but not 0.8 against 0.5 (16/20 against 10/20, p ≈ 0.096). - Cost.
sessions ≈ offered × repeat × 2, and tokens ≈ sessions × T, where T is the tokens of one session. Estimate: T ≈ 40k, so about 1.6 M tokens per skill at the recommended size. This is an estimate, not a measured value. - Both arms always run. When any scenario is offered, both arms run in full, even if the with arm never loads the skill. The arms therefore always have equal repetitions; the only run-free case is that no scenario is offered.
- Records. One file per run of the command:
skill-effects/<id>/<digest hex>/effect--<sequence>.json,schema: 1. The writer uses the store's shared publish step, so a file is written once and is never replaced. The readerreadNewestEffectchecks the newest file with the full record parser, which recomputes the verdict, enforces the run limits and scans the text for credentials. It never falls back to an older file.effectStatemaps the newest record of a skill and digest tohelps,no-effect,harms,not-measuredorinvalid; the list (scf skills) shows it. - Promotion (#543).
effectPromotion(read, decisions, id, digest)insrc/skills/effect.tsis the one rule ofscf skills gateandscf skills promote check. It returns{ verdict, code?, decision? }:harms(effect-harms) and an invalid record (effect-invalid) always fail;no-effect(effect-no-effect) and no record (effect-not-measured) fail unless an owner decision matches the skill, the digest and the kind. The decisions are theeffect_decisionslist ofskill-evaluations.yaml, parsed with the same owner, date and note checks as the evaluations (src/skills/suite-records.ts). The codes are not evaluation reason codes, sojudgeItems,release publishand the evaluation records do not change. Known gap:release publishdoes not apply the rule yet. - Sample tasks. The owner-written
instructionssection of the suite. The example set is inevals/skill-effect/kafka/. Files shipped inside upstream skills are not used as tasks. - What
scf evallacks.scf evalalready supportsrepeat(up to 20) and runs the repetitions, so this is not missing. What it does not have: an automatic comparison with and without a skill, the statistical verdict, loading a staged candidate (it runs flows × models only), and storage against a skill digest.
Skill gaps (#776)#
The Foundry asks for a missing skill by opening an issue in the skill library, and the skill-write flow (#774) picks it up. The parts are split so the signals stay testable without GitHub:
- Signals (
src/skills/gap-signals.ts, pure).gapSignals()reads the runs, the monitor's findings and the registry, and returns one signal per topic. The four kinds areunknown(a plan'sskillPlan.unresolvedwith codeunknown, skipped when the skill is active now),technology(a technology the profile recorded inskillCatalogue.technologieswith high or medium confidence, thatskillCoversTechnology()finds uncovered now),review(a[high]or[medium]line of a review step's output, classified by the fixedREVIEW_KINDStable; 3 runs in 14 days) andfailure(a failed test step, or a fix step visited 3 times; 3 runs in 14 days, or one run, or an opensame-step-failingordevelop-redfinding). Only signals with a known technology in their repository can befailure. Windows and thresholds are constants (GAP_WINDOWS,GAP_THRESHOLDS). Only validated tokens leave the module (topics, run ids, kinds, versions, repository names). Topics are checked againstSKILL_ID_RE. - Duplicates and limits (
src/skills/gap-issues.ts, pure).gapIssuesOf()reads the marker from the issue bodies. An open issue blocks its topic; a closed one blocks it forREOPEN_DAYS(30) after its closing time, and a closed issue without a closing time blocks it (fail closed).planGapIssues()appliesmax_openover all open marked issues andmax_per_dayover the ones created in the last 24 hours. Both counts come from GitHub's list, not from the ledger. - Issue text.
gapIssueText()builds the titleSkill gap: <topic>and a body from fixed sections (what to teach, evidence, sample tasks), with the marker last. The evidence names the repository the signal is about and nothing from another repository. - Sweeper (
src/server/skill-gap-sweep.ts).skillGapSweeper()runs an hourly timer instartServerand a kick when a run stops for skills. The steps are: read the signals from at most 500 runs updated in 30 days; list the library's issues (a cut list opens nothing); create the label if missing and the issues; write the ledger (skill-gaps.json, one repository, written by a temporary file and a rename); link the runs that stopped for anunknownskill that has a ledger entry. Its sign-in is the administrator's record of the library (kind: skill-library, not a user's record); it runs withwithGhEnvand is disposed after each tick. Ticks do not overlap, andstop()ends a tick before it writes the ledger or links a run. - Linking and resume.
withGapLink()insrc/skills/run-plan.tsadds the link when a plan is checked, and the sweeper adds it later. The link isrun.skillGap(topic, issue, url) and the sentenceSkill gap issue: <url>in the stop reason.isSkillGapStop()is a stop with a link whose unknown skills can clear.isPaused()counts it as paused, so the waiting list shows it as waiting. The watcher resumes it only whenskillGapReady()finds every unknown skill in the registry, the watcher is not paused and the run's code area is free. The sweep never resumes a run. - Ledger. The ledger holds the marked issues of one repository (
readGapLedger()returns an empty ledger for another repository). It is a cache for links only: a missing or broken ledger links nothing, and the next tick rebuilds it from GitHub. - Record of a run.
runSkillCatalogue()stores the technologies the profile showed (at most 10, observations only, never coverage) on the step's catalogue record. That is the only input of thetechnologysignal that the run does not already have.
The tests run without GitHub: the signals and the limits are pure functions, and the sweeper takes fakes for the runs, the findings, the sign-in and the store.
Skill improvement (#777)#
A library skill that does not help gets an issue to improve it. It reuses the gap parts (#776): the sweeper, the marker check and the limits.
- Signals (
src/skills/improve.ts, pure).improveSignals()returns one signal per library name from three inputs:effectImproveSignals()(the newest effect record of each installedid@versionisno-measurable-effectorharms),reviewImproveSignals()(the same review finding kind in 3 or more distinct runs of 14 days, counting only the exact installed versions the coder loaded) andquarantineImproveSignals(). The library names come from the authoring source's selections and from the names the ledger keeps (libraryinskill-gaps.json, written whenskill-writepublishes, seepublishedLibrarySkills()). - Issues (
src/skills/gap-issues.ts).gapIssuesOf()reads both markers and setskind(gaporimprove). The topic of an improve issue isimprove:<name>, so the duplicate and reopen rules are the same.planGapIssues()is generic over the signal type and counts both kinds formax_openandmax_per_day.improveIssueText()builds the titleImprove skill <name>. - Publish rule (
improveDecision()). The new version must have verdicthelpswith runs. An old version with no runs on the scenarios lets the new one stand alone; otherwise both must have the same number of runs with the skill and the new one must pass at least as many. Anything unreadable does not publish. - Flow (
tools/skill-improve,scripts/build-flows.mjs). Theskill-writeflow reads the target from the issue (improveTarget()), measures the old version fromgit archiveof the base, compares the twoEFFECTlines withskill-improve compare, and counts the failed tries withimproveFailures()(Foundry comments with askill-improve-failedmarker, plus the current run). The second failure runsscf skills lifecycle <key> deprecatedonly whenimproveStateOf()reads the version asactive, and addsFactory_needs_info.
The tests run without GitHub or a model: tests/skill-improve.test.ts calls the pure functions, and the flow tests use the fake scf.
Evidence formats#
src/evidence/ defines two formats for what a run did (#134). The engine writes the events (#135,
see "The evidence stream" below). Both are extra files in the run folder, so run.json stays as it is.
EvidenceEvent: one line ofruns/<run-id>/evidence.jsonl. Every event hasversion,id,seq(its place in the stream, from 0),runId,timeand atype: eight for the run (run.created,run.queued,run.started,run.stopped,run.resumed,run.cancelled,run.failed,run.completed) and eight for a step (step.started,step.routed,step.retried,step.denied,step.approved,step.failed,step.completed), withstep.profiled(the tool profile of one try, see "Tool profiles") from version 3, andpolicy.decidedfrom version 2 (a decision of a policy pack at a boundary, see "Policy hooks in observe mode"), andrepo.operationfrom version 4 (one repository operation of the broker, see "Repository broker"), andcontext.bundledfrom version 5 (the context bundle of the run was written, or making it failed, see "Writing a run's bundle"), and from version 6 the reason codecontext.uncited(see "Policy hooks in observe mode"), and from version 8 the optionallocalTest: trueonrun.created(a run started with--local-test; the schema accepts onlytrue, and the migration 7 → 8 only sets the version), and from version 10 the eventrun.autonomy(the level of the run, the repository's level when there is one, and the flow's; see "Autonomy levels"), and from version 11 the optionalresumed: trueonrun.autonomy(a resume that found another level than the stored one; the migration 10 → 11 only sets the version).run.autonomycomes right afterrun.created.prevHashandhashcome together and are for the hash chain.RunEvidence:runs/<run-id>/evidence.json, the manifest of a run that ended (succeeded,failedorcancelled): the flow and its hash, the event file with its count and last hash, base and final commit, models, policies, approvals, test results, files, the diff and the pull request. OnlyfinalizedAtdepends on when it was written.- Identities (
identity.ts): step, model, tool, policy, approval, test result, commit, pull request, and who acted (an account id, the command line, a watcher or the Foundry). - No secrets by shape. There is no free text: only short one-line names, ids and codes. Every object refuses unknown fields. A tool has a name and no arguments; an account has an id and no name; a pull-request address has no sign-in data, query or fragment.
- Files are named, not copied. An
ArtifactRefis a path inside the run folder (relative, no..), its SHA-256, its size, andrequired(false: the file may be removed later). - Versions.
parseEvidenceEventandparseRunEvidencelook atversionfirst. A higher version than this Foundry writes is refused with one sentence that says so; a lower one goes through the steps inEVENT_MIGRATIONSorMANIFEST_MIGRATIONSand is then checked. A new field means a new version and a step.readRunEvidencegivesabsentfor a run without a manifest (every run made before this), and never throws.
Autonomy levels#
src/governance/ keeps how far each repository and each flow may go (#643). The module split is:
autonomy.tsis pure: the four levels in order (observe,plan-only,guarded-write,delivery-handoff),lowerLevel, the run'sRunAutonomyschema,autonomyOfRun(a run without the field reads asdelivery-handoff, an invalid one asobserve) and the log line. It imports only zod.autonomy-store.tsreads and writesautonomy.json: one map of repository ids and one of flow names, each entry with a level,since,byand an optional reason. Lookups useObject.hasOwn, so keys such as__proto__are safe. A missing file is an empty store. A file that is a link, larger than 1 MiB, not JSON or not valid is aStoreError. A write runs under the data-folder lock (withAuthLock), validates the whole store and its size first, then replaces the file with onewriteAtomic(a temporary file and one rename). A refused write leaves the file as it was.run-autonomy.tsworks out a run's level when it starts and records it. It never throws. The evidence event is written before the log lines, so a failing logger cannot drop it.
The defaults are in autonomy.ts: no entry is delivery-handoff, and a repository connected through the API
gets guarded-write. addRepo writes that entry through its beforeSave hook, under its own lock, before it
saves repos.json; the API passes it in api-repos.ts, so auth/ does not import the store. A repository of an
existing install (moved from config.yaml) gets no entry.
The level is read when runFlow starts, and again on each resume (runAutonomyOnResume, which uses the same
runAutonomyAtStart); the new level is stored in run.json before drive and autonomyStop read it. A resume with another
level writes run.autonomy with resumed: true. A resume with no change writes nothing new. If a
store cannot be read at that point, the run counts as observe (the fail-closed choice), and the log says so.
The level is enforced where each action starts, not in the prompt:
autonomy-rules.tsholds the rule table (which action needs which level) andpullRequestRefusal. It imports onlynode:modules, becausetools/storyandtools/daily-branchload it fromdist/inside a container.agents/run.tsrefuses a writing agent step beforeagent.writeis asked, so no agent starts.engine/execute.tsrefuses arepo_accessshell step before any credential is looked up.autonomyStopwrites thestep.deniedevent withautonomy.deniedand returns the step failure; it does not stop the run.repo-broker.tschecks each operation against the same table (statusis always allowed).- A run below
delivery-handoffgetsFACTORY_NO_PUSHset to its level.guards.tsinstalls the pre-push hook for it, and the hook refuses every push, deletes included, and writes a refusal line to the push log.recordStepreads that log after the step and fails the step, sogit push || truecannot hide a refusal. - For Docker steps, the hook folder is mounted read-only and the push-log folder writable, only when the flag is set. Agent sandboxes keep the push-log folder writable, also in read-only sessions.
The promotion gate (#645) is in src/governance/gate.ts. promotionGate gets its data through GateDeps
(the runs, the eval coverage, the findings and the monitor's last check), so the file imports nothing from
src/server/. The route api-autonomy.ts builds the deps once per request: runs are narrowed by repository or
flow first, read through the shared outcome facts cache, and the loop yields to the event loop between runs.
Each check returns a value and a threshold, or a plain reason when its data is missing; passed is the AND of the
four evidence checks, and approval is always "pending" until part 4 fills it in.
Automatic demotion (#647) is in src/governance/auto-demote.ts. The monitor calls it after mergeFindings has
saved the findings: markAutoDemotions marks only the findings that are new in this check (fresh), and only
those that demote (AUTO_DEMOTE_DETECTORS names the major detectors; any critical one counts). Each marked
finding carries autoDemote.left, the keys still to lower (repos:<id> or flows:<name>). runAutoDemotions
takes one key out of left and saves the findings before it calls demoteLevel with by: "monitor". So a crash
loses one demotion and never repeats one, and a failure on one record leaves the others alone. The findings
that carry an open autoDemote are kept when the 500-finding cap evicts. Monitor.applyAutoDemotions runs after
the save, never throws, and does not wait for the autonomy lock. Turned off, it empties left and saves.
Policy contracts#
src/policy/ defines what a policy is, what it is asked and what it answers (#141). Nothing in the
engine asks a policy yet; the stories after it do. The folder has no side effects: schemas, version
numbers and pure functions.
PolicyPack: one version of one policy.versionis the version of the format.policyis theidof the pack and theversionits author gave the contents: the same pair evidence carries as its policy identity.modeisobserve(decisions are only recorded) orenforce.rulesare read from the first to the last;defaultOutcome(allowordeny) decides when no rule applies.- A rule has an
id, theboundariesit is about,when, anoutcomeand areasonCode. From version 2 it may also have its ownmode(observeorenforce). A decision takes themodeof the rule that decided, or the pack'smodewhen the rule has none;policy.input-incompleteof a rule takes that rule's mode, andpolicy.no-rule-matchedtakes the pack's mode.whenhas at most one condition per fact, and all of them must hold:inornotInwith patterns for a text (*stands for any characters, nothing else is special),inornotInwith fixed values for a choice,anyInfor the changed paths,overfor a number (more than, never equal),trueorfalsefor a flag. PolicyInput:version,boundary,runIdandfacts. The boundaries arerun.start,step.before,step.after,repository.access,agent.write,push,approval.consume,context.selectandrun.complete. The facts are a closed list (FactsSchema): repository, branch, flow, step, tool, workspace, owner role, credential, changed paths, secrets found, output bytes, elapsed time, step, run and daily cost, six flags, the context facts ofcontext.select(contextSources,contextBytes,contextOmittedandcontextClassification, the most private class of the sources), andcontextUncitedatstep.after(a count from 0 to 3 of the plan's sections with no citation, see "Policy hooks in observe mode"). All are optional and none is free text. A caller gives what it knows and never a guess.POLICY_INPUT_VERSIONis 3 from thecontextUncitedchange (2 from thecontext.selectchange).PolicyDecision:version,policy,packSha256,mode,boundary,inputSha256,outcome,reasonCode,ruleandevaluatedAt. The outcomes areallow,warn,require_approvalanddeny. The input itself is not kept, only its hash. The hashes are the SHA-256 of the canonical JSON (keys sorted, no spaces).- Reason codes are a closed list (
src/policy/reasons.ts), each with one sentence. A code is never renamed, reused or removed; a new meaning gets a new code. Codes for rules:branch.protected,branch.hotfix-exception,secret.detected,path.forbidden,output.limit-exceeded,timeout.exceeded,budget.step-exceeded,budget.run-exceeded,budget.daily-exceeded,sandbox.required,workspace.admin-only,repository.not-allowed,credential.scope-exceeded,identity.missing,tool.not-allowed,issue.closed,flow.retired,approval.required,exception.granted,context.limit-exceeded,context.sources-omitted,context.classification-exceeded,context.uncited. Codes only the evaluation gives:policy.no-rule-matched,policy.input-incomplete,policy.invalid,policy.unavailable. The code only the break-glass gives:policy.break-glass(awarninenforcemode, see "Break-glass" below). evaluatePolicy(pack, input, evaluatedAt)gives one decision and is deterministic: no file, network, model, clock or randomness; the caller gives the time. A rule that does not name the boundary of the input is passed over. The first rule whose conditions all hold decides. A rule that needs a fact the input does not have cannot be judged: the answer isdenywithpolicy.input-incomplete. An exception (such as the hotfix merge) is a rule before the rule it is an exception to. Bad data decides nothing: the pack, the input and the time are checked first and aPolicySchemaErrornames the fields that are wrong.- Evidence.
policyIdentityOf(decision)is the policy identity of #134, andpolicyDenial(decision, tool?)is thedenialof astep.deniedevent: only fordenyinenforcemode. Every reason code fits the evidence format. - Versions. Each contract has its own number in
version.ts. A record with another version is refused with one sentence. Every object refuses unknown fields, so a new field means a new version. The pack format is version 2 (POLICY_PACK_VERSION).parsePolicyPackalso reads version 1, withPolicyPackV1Schema(no rulemode, so amodeon a rule of a version 1 pack is refused). A version 1 pack is read and hashed as written, never rewritten to version 2, so itspolicyPackSha256does not change. Any other version is refused. The decision format (POLICY_DECISION_VERSION) did not change: itsmodealready existed. - Enforce is refused at load time.
parsePolicyPackacceptsenforceon a pack or a rule, since a pack built in memory may use it.loadOne(loadPolicyPacks) and the last-known-good restore refuse a pack in which the pack or any rule is inenforce(enforceProbleminpolicy-hooks.ts).
Policy hooks in observe mode#
src/engine/policy-hooks.ts asks the configured policy packs at the boundaries of a run (#142). It
is the only place the engine calls src/policy/; src/engine/policy-store.ts holds the last-known-good copies and the restore. A decision changes a run in one case only: fail closed
(below), which an active break-glass can turn into a recorded warn (see "Break-glass"). Otherwise packs run in observe mode.
- Where the questions come from. The engine asks, so a flow cannot leave a boundary out:
runner.tsasksrun.start,repository.access(before a workspace is made),approval.consumeandrun.complete(only when the run succeeded);run-context.tsaskscontext.selectonce the bundle is written (see "Writing a run's bundle");execute.tsasksstep.beforeandstep.afterfor every visit of a step throughbeginStepandrecordStep, andrepository.accessfor a step in the repository's checkout;agents/run.tsasksagent.writebefore a write-capable agent step. Built-in and custom flows take the same path. - Packs are a snapshot (new run).
loadRunPacks(summary, config)reads the packs once, beforerunPolicyinrunFlow.runPolicytakes that list (preloaded) and looks each id up in it; an id that is not in the list becomespolicy.unavailable, so a mandatory pack fails closed and is never read a second time. The promotion gate takes the same list (GateInput.policyPacks) and iterates it without the baseline, so it checks exactly the packs that run. Both sides build the ids withrunPackIds, so they cannot drift. A resumed run (resumeRun) has no promotion check and reads the packs again, so a tightened mandatory pack stays in force. - Pushes.
pushis asked once for each push a step makes. The pre-push hook (guards.ts) appends<branch>\t<remote url>\t<secrets found>\t<identity>to the file inFACTORY_PUSH_LOG. The count is empty when the scan did not finish, and the identity is1or0(whether git can find a committer identity). Two-field lines from older hooks still read.drainPushLogreads and removes the file when the step ends, and reads only a plain file of at most 64 KiB and 100 pushes. A count that is not 1 to 9 digits and an identity that is not1or0are left out. The repository of a push is set only when its remote is a GitHub address. The hook never fails a push. The count and the identity are observations only: a step can write to this file too, so they never drive a guard. - The push gap. The hook is added only when something needs it: a protected branch, the secret scan,
or configured packs (
protectedBranchEnv(…, observe)). A run with both guards off and no packs keeps the hook out, so its pushes are not observed.RunPolicy.observesPushessays whether the hook is there, and the baseline'spushrules are asked only then. - Facts.
baseFactsgives the run's repository, flow, workspace and owner;runPolicyaddsshippedFlowfromisShippedFlow(guards.ts: true only for an unchanged built-in flow of that name, false on any error), so it reaches every boundary. Each boundary adds its own.policyFactskeeps only the values that pass their schema inFactsSchema; a value that does not is left out, never changed. The repository is lower case, and the placeholderowner/repois no fact. - Packs.
loadPolicyPacksreads<data folder>/policies/<id>.jsonwithO_NOFOLLOWandO_NONBLOCK, only as a plain file of at most 1 MiB. A pack that is missing, linked, not a file, unreadable, invalid, for another policy id, or inenforcemode becomes aLoadedPackwith apolicy.unavailableorpolicy.invalidproblem. Its detail never names a path or file content. - Last-known-good.
saveLastKnownGood(called byrunPolicyfor each mandatory overlay that loaded) writespolicies/last-known-good/<id>.jsonwith{ version, id, savedAt, policyPackSha256, pack }. The folder is 0700 and the file 0600, written by a random temp file and onerename. It never throws: a failure is one!log line.restorePolicy(policy-store.ts, underwithAuthLock, always ondataHome()) reads the copy withreadPolicyFile, checks the id,mode: observe, the stored SHA-256 and the size of the compact JSON, and refuses a link, a folder, a changed copy or a valid current file without--force. It keeps the replaced entry as<id>.json.replaced-<time>(never overwritten), replaces the active file with onerename(the temp file is written withwx, and removed on failure), and writespolicy-restoreto the audit log. The SHA-256 is not a signature. The command ispolicy-cli.ts. - Layers and precedence.
src/policy/compose.ts(pure) gives the layersmandatory(the baseline and the admin'spolicy.mandatoryoverlays),repository(policy.repositoriesfor the run'sowner/name, matched in lower case) andoptional(policy.packs).layeredPackIdskeeps an id only in the first layer that names it.combineDecisionspicks the most restrictive outcome; a tie goes to the higher layer, and a tie inside one layer to the first pack. So a repository pack cannot relax a baseline deny, and the answer does not depend on the order of the lists. - Baseline controls.
baselineControls(config, run)(baseline.ts, pure) readsprotected_branchesandsecret_scanthe way the pre-push hook does: entries are split on space, tab and new line, and empty entries and duplicates are dropped. A pattern the evaluator cannot match exactly (? [ ] \, other spaces, control characters, over 255 characters) goes toleftOut, never to a looser rule. Therepositoryis kept only when the facts schema accepts it.baselinePack(version, controls)puts the protected branches in chunks ofMAX_PATTERNS(100) rules,branch-protected,branch-protected-2, …; the hotfix exception chunks come first, then the deny chunks, so no pattern is dropped. Rule order isbranch-hotfix-exception(only for the shipped hotfix flow),branch-protected,secret-detected(only when the scan is on),identity-missing,repository-not-allowed(only with a known repository), the sandbox and workspace rules, andcredential-scope-exceeded. The branch rules come first because the hook checks the branch before it scans: a push refused for a protected branch has no secret count, sosecret-detectedmust not decide it.repository-not-allowedcomes after the secret and identity rules, so every push decided by them keeps its decision. Forbidden paths (forbidden_paths, #631) are taken as written, and theirpathsrules come last, after the limit rules, so no earlier rule's index changes. The hotfix exception is only allowed forissue-gitflow/push_mainwithshippedFlow: true, and is safe withhotfix_to_mainoff becausepush_mainexits before pushing unlessFACTORY_HOTFIX=on. Scan off: the hook never gives a count, so the secret rule is not in the pack; no zero count is invented. - Unknown push repository.
runBaselinealso buildspushWithoutRepository(the same pack without the repository rule).RunPolicy.decideuses it atpushonly when the input has norepository. Such a decision records that pack's hash. The repository is never guessed. - Plan citations fact.
stepContextUncited(src/engine/context-index.ts, called fromrecordStepinexecute.ts) givescontextUncitedatstep.afteronly for a top-levelclaudestep whose prompt has{{context.index}}, whose output has aPLAN_STATUS: READYline, and whose run has a readablecontext.json. The count comes fromplanCitations(src/context/citations.ts): the Requirements, Constraints and Acceptance criteria sections that are missing or cite no id the step's role may consume (mayConsume, roleskill_role ?? "coder"). The baseline rulecontext-uncited(CONTEXT_UNCITED_RULE, observe,warn) is last, so a limit or path deny still wins.runBaselinebuildsstepWithoutCitations, the same pack without that rule;RunPolicy.decideuses it atstep.afterwhen the input has nocontextUncitedfact, so other steps never getinput-incompletethere. - Step without sandbox fact. The
sandbox-requiredrule also applies atstep.before(SANDBOX_STEP_RULE), andrunBaselinebuildsstepWithoutSandbox: the same pack with the rule only atagent.write.RunPolicy.decideuses it atstep.beforeonly when the input has nosandboxedfact, which is every step that is not a shell step (shellSandboxed,src/engine/step-facts.ts, returns undefined for those). So a claude step or an approval step never gets a baselineinput-incompletethere. For a shell step it is(OS sandbox on and short environment) or (the step has a Docker image), matchingboxedand the Docker path ofexecute.ts; a refused sandbox counts as not on. - Changed paths (#631).
pathsis worked out only when a usable pack needs it (RunPolicy.needsFact, atstep.after), so runs without path rules do no git work.src/engine/diff.ts(changedPaths,checkoutRoot,runChangedPaths,ensurePathsBase) runs git async, with the cancel signal and a 30 s budget.changedPathsuses a private bare git folder in a temporary folder, with the workspace's objects as alternates and the workspace as work tree:read-treeof HEAD, a check that every blob of HEAD and the base is present,add -A, thendiff --cached --name-only base. It takes the union with the same diff of the workspace's own index, which is read and never written (--cached,GIT_OPTIONAL_LOCKS=0), so a crafted index can only add paths or make the result incomplete. Calls have no lazy fetch (GIT_NO_LAZY_FETCH=1,GIT_ALLOW_PROTOCOLempty,-c protocol.allow=never), so a promisor config cannot run a command; a missing object is undefined. Output is-z, each path is checked withisSafeRelativePath, and more than 5000 paths is undefined.checkoutRootaccepts the root of the workdir's repository only when it is the workdir or an ancestor of it; an empty workspace never searches upward. ThepathsTrackedflag (set on new runs) gates every mode: older runs get no git call andinput-incomplete. The base for an empty workspace is HEAD after the first step that left a checkout (pathsBaseSha), read once and memoised per summary (ensurePathsBase);baseShais ignored there. Any failure after.gitexists setspathsBaseLost, persisted, andresumeRunsets it for a checkout without a base. The base never moves forward.runChangedPathsnever throws. - Construction failure.
baselineEntry(version, controls)returns aLayeredPack. If the baseline cannot be built (too many rules or a bad version), it is apolicy.invalidmandatory entry, so the fail-closed path of "Fail closed" applies at privileged boundaries. There is no silent fallback to a weaker pack.BASELINE_PACK(the four legacy rules) is still the pack of the build without run controls. - Limit rules (#630).
limitRules(baseline.ts) adds, aftercredential-scope-exceeded, the observe rulesoutput-limit-exceeded(warn,outputBytes),timeout-exceededandtimeout-exceeded-2… (deny,elapsedMs),budget-step-exceeded(deny,stepCostUsd),budget-run-exceeded(deny,runCostUsd) andbudget-daily-exceeded(deny,dailyCostUsd). Each is only atstep.after.policy-limits.tsbuilds the groups fromstepLimits(flow, depth, config): steps with the same value share one group, in order of first appearance, and the groups are chunked byMAX_PATTERNS(100) rules, so-1,-2, … The output group usesstepMaxOutput ?? DEFAULT_MAX_OUTPUT(20,000) for every shell step; claude steps have no output rule. Timeouts cover claude and shell steps; budgets cover claude steps and needcost_limits !== false. Values that are not finite positive numbers, and ids that are too long or not plain tokens, are dropped inlimitRules. The run-wide budget rules come fromflow.limits.max_cost_usdanddaily_budget_usd. A rule is only added when its limit is in effect, so the rule ids of a run without limits are the same as before.- Cap.
runBaselinethrowsPolicySchemaErrorwhen the baseline would have more thanMAX_RULES(500) rules;baselineEntryturns that intopolicy.invalidwith that detail, so the fail-closed path applies. About 490 distinct limit values are needed to reach it. - Scopes.
RunPolicy.subFlow(parent, flow, depth)(called byexecute.tsafter a sub-flow's scope is built; it never throws) builds the sub-flow's baseline from the root controls with that flow's limits, and stores it under the parent step id.at()asksscopedPacks(packs, entry)at every boundary of a step whoseparentis set. The scoped entry replaces the root baseline, but a root that is invalid is kept, so a failed root never becomes a valid scope. A sub-flow that fails is logged once (! policy foundry.baseline: sub-flow …) and denies its privileged steps. A scope with no registration uses a fallback baseline with no per-step limits. The hash is per scope and is recorded with each decision. - Meter.
ProcessMeter(process.ts) holdsms(from spawn toclose, after stdio is drained) andprintedBytes(the UTF-8 bytes of the kept output). It is set on every exit path: a normal close, a timeout, a spawnerror, a failed log write and a rejected call. The caller owns it, so the values survive a rejected promise.runAgentStepclears it before each attempt, so only the final attempt is recorded. - Bytes and characters. The output rule counts bytes, so with non-ASCII output a warning can come before the
engine's character cut. Limits use
over(strictly greater); a value exactly at its limit gives no rule. - Missing facts.
stepCostUsdandoutputBytesare always given atstep.after. The missing-fact check (input-incomplete) runs first, so a rule that needs a fact the step did not produce is not silently skipped.dailyCostUsdis given only when a daily budget is in effect (Engine.dailyCostUsd, read in atry; on a throw it is absent).
- Cap.
- Baseline.
src/policy/baseline.tsbuildsfoundry.baseline. The Foundry owns it: its version is the package version, and admins can only add overlays. It is always in the list of packs, so a run always asks it. The file's only read ispackage.json, once, for that version; it is the one file read insrc/policy/. A bad or missing version becomesunknown. - Decisions.
RunPolicy.atasks every pack, in layer order, and returns{decisions, combined}, wherecombinedis the winning decision. Each one is logged as· policy <id> <version> [<layer>] · <boundary>: <outcome> (<reason>), with· winson the combined decision when there is more than one pack, and recorded as apolicy.decidedevent (RunRecorder.policyDecided). A pack that cannot be evaluated is recorded aspolicy.invalidwithunknownas version, and the log says so. A decision that cannot be recorded either marks the evidence incomplete (RunRecorder.incomplete). No method throws into the engine. - Fail closed (#614).
privilegedBoundary(boundary, facts)is true foragent.write,approval.consumeandrepository.accesswith themachineorrepositorycredential. A pack in themandatorylayer that cannot be loaded (policy.unavailable/policy.invalid) or evaluated getsmode: "enforce"at a privileged boundary, fromdecide/noPack: the decision isdenywith versionunknownand nopackSha256.atthen setsdeniedon the answer (PolicyDenied: the reason fromdeniedReason, the decision and itspolicyDenial). If even the decision cannot be built (for example a bad id),deniedhas the reason only, andfail()marks the evidence incomplete. Nothing throws. The other layers and boundaries stayobserve.refuseByPolicy(execute.ts) is the one place that acts ondenied: it setsaccessFailed(soon_failureis not followed), recordsRunRecorder.stepDenied(step.deniedwith kindpolicy) when there is a decision, and logs the reason. The shell step checks beforepushLogForand the bot token; the agent checks atrepository.accessand before each writing session; the approval checks atapproval.consumeand records nostep.approved.RunPolicy.mandatoryUnusablestops the run from fetching the bot token up front. No push check is needed:pushis not privileged, and the sign-in was already refused atrepository.access. - Break-glass (#626).
runPolicypassesRunPolicya reader,() => activeBreakGlass(home ?? dataHome())(breakGlassoption; the default() => undefinedfails closed).RunPolicy.outage(id, decision, boundary)is called for each mandatory pack's decision, indecideand in thecatchpath ofat. It acts only on anenforcedenywithpolicy.unavailableorpolicy.invalid, and only when the run has a recorder. Then the reader is asked; a throw orundefinedkeeps the denial. The replacement iswarnwithpolicy.break-glass, the same policy id, versionunknown, the input hash of the denial, and no pack hash or rule.atkeeps it only afterreporthas recorded it:RunRecorder.policyDecidedreturns whether the event was written (puttoo). If it was not, the original denial stands,deniedis set and the log says so. Rule decisions, the other layers and the other boundaries never call the reader. The run log line is! policy: break-glass active until …, and the policy line ends with— break-glass: the step goes on.PolicyDecisionSchemaacceptspolicy.break-glassonly withoutcome: "warn"andmode: "enforce", andNO_RULE_REASONSandNO_PACK_REASONSinclude it. The decision version is unchanged, so an older build refuses a run that has it.breakGlassWatch(log, now)(policy-break-glass.ts) is the server's watch: it runs at startup and every 60 s on an unref'd timer, logs while a record is active (first check, a newstartedAt, every 15 minutes), writes theexpiredline throughendExpiredBreakGlasson expiry and logs when the record is gone. It never throws. Counting break-glass decisions in the SLO input (slo-input.ts) is not done yet. - Enforced rules (#728).
policy.enforce(BaselineRuleIds) makes the listed baseline rules decide inenforcemode (controls.enforce,RunPolicy.enforcedAt). Their denials setdeniedat the boundaries they guard, andrefuseByPolicyacts on it atstep.beforeandstep.after(execute.ts, also in the parallel branch and the approval branch ofrunner.ts), whilerefuseRunByPolicyacts atrun.start(runFlowanddrive, which also covers a resume).completeRun(runner.ts) turns a succeeded result into a failed one on arun.completedenial.beginStepreturns thestep.beforeanswer, so a refused step runs no command and noapproval.consumeis asked.recordStepasksstep.afterright after the first save and beforeevidence.stepEnded, the delivery checks and the push decisions. On a denial it setsokfalse,errorandaccessFailed, dropsheldandlimited, updatesscope.ctx.stepsand saves again; the checkout is not rolled back.pushis not in the enforced set: it is recorded only. An unusable baseline denies the enforced rules' boundaries (outageScope), with the samedeniedpath. Break-glass never covers these. - Evidence.
policy.decidedhas the decision and the step for every boundary about a step. It has no step forrun.startandrun.complete, nor forrepository.accesswhen it is asked for the run's workspace. The event is inEVIDENCE_EVENT_TYPES;EVIDENCE_EVENT_VERSIONis 2 for it. - Explanations and repeats (#145).
src/policy/explain.ts(pure) turns a recorded decision into plain text at display time, so the evidence format is unchanged. Every sentence comes from a closed list: the reason text (reasons.ts) andNEXT_ACTIONS, picked bynextActionCodefrom the outcome, mode, reason code and the policy id (the baseline is told apart from other packs forpolicy.unavailableandpolicy.invalid). The engine'slogDecision(policy-hooks.ts) writes the decision line for each answer. TheWhy: … What to do: …line follows the first answer of a key (policy id and version, layer, boundary, outcome, reason code, mode and rule); a repeat carries· seen N times, first at …, now …. The key counts inRunPolicy.seenfor one start of the run (at most 1,000 keys; past the cap a key is not counted).policyDecisionsOf(evidence-view.ts) reads thepolicy.decidedevents throughreadEvidenceChainand folds them withgroupPolicyDecisions: groups of at most 100 (the rest counted inomittedGroups), up to 10 step names each, andcompletefalse when the chain, the tail, the incomplete marker or the verifier says the events are not whole. A user's answer leaves outruleandpackSha256;user-view.tsrebuilds the log lines of a user the same way (only the known shapes pass, and a line that does not match is left out).ui/run-evidence.jsshows the list. - Baseline always asked, files only when configured. With no packs in any list,
runPolicystill returns aRunPolicythat asks the baseline at every boundary. It reads no file (loadPolicyPacksruns only for listed ids). Without packs the hook is added only for a guard, so pushes are observed only when a guard or a pack needs the hook. The engine'spolicyis set for every run it starts (execute.ts).
Context bundle#
src/context/ defines the format that says what a run was given to read, and where each piece came
from (#151), and the selector that makes one (#152, see "Context selection" below). Issue runs get
a bundle before their first agent step (see "Writing a run's bundle"). The stories after it give the
sources to the agents read-only (#153) and show them (#154). It is an extra file in the run folder,
runs/<run-id>/context.json, so run.json stays as it is.
ContextBundle:version,runId,createdAt, the onerepositoryand commit it is about, abudget,policies,sourcesandomitted.A source has an
id, akind, auri, arevision,content(file, SHA-256, size in bytes),owners, aclassification,retrievedAt,freshness, aselectionreason andconsumers. Every field is required, exceptfoundryon anissue-comment:foundry: trueis set only for a comment the Foundry wrote (see "Issue files" below). A bundle without the field still reads, soCONTEXT_BUNDLE_VERSIONstays 1.Kinds and addresses (a closed list,
uri.ts):repository-file(repo:<path>),issue(issue:<number>),issue-comment(issue:<number>/comment/<id>) andrefinement-notes(refinement:<session id>). An address has no host, no folder of the machine, no query and no fragment, and only one spelling. Theidiss-plus 16 hex characters of the SHA-256 of the address, so the same source has the same id in every run.Revision. A repository file has the full commit, and it must be the commit of the bundle. The other kinds have a
version: the time of their last change, as their origin reports it.Text is stored apart. The bundle holds no source text.
content.pathis a file undercontext/in the run folder;sha256andbytesare of exactly that file.Policy is named, not carried.
policiesholds id and version only. No source kind is a policy, so source text is always data and never an instruction.Owners are host handles (
@user,@organisation/team), never an e-mail address or a name. An empty list means no owner is known.Classification:
public,internal,confidential,restricted, from least to most private (classificationAtMost).Freshness:
maxAgeSecondsafterretrievedAt, ornullfor a copy that does not go stale (staleAt,isStale; the caller gives the time).Selection reason: a code, not a sentence:
task,instructions,ownership,api-schema,discovery(with therulethat found the file) orrefinement. Each kind takes only its own reasons.Consumers: the roles that may be given the source (
planner,coder,reviewer,tester), at least one (mayConsume).Budget:
maxSources,maxSourceBytesandmaxTotalBytes. A bundle over its own budget is not valid.max_source_bytesmay not be abovemax_total_bytes(thecontext:settings check this before a bundle is made; seesrc/context/settings.ts).Omitted: an expected source that is not in the bundle, with one reason:
missing,stale,ambiguous,over-budget,classification,generated(the repository marks the file as made by a program) orunsupported(not a regular text file: a link, a submodule or a binary file).Hash.
serializeContextBundlechecks the bundle and writes it in one fixed form (lists and fields in a fixed order), so the same bundle always gives the same bytes.hashContextBundleis the SHA-256 of that text.contextBundleRefgives the evidenceArtifactRefforcontext.json(kindother, required), which is how evidence names the bundle by its hash;contextSourceRefdoes the same for the text of one source.hashContextSourcesis one hash over the sources only, the same in every run for the same repository state and task.Versions and old runs.
parseContextBundlelooks atversionfirst, with the same rules as evidence: a higher version is refused with one sentence, a lower one goes throughCONTEXT_MIGRATIONS.readContextBundlegivesabsentfor a run without the file (every run made before this), and never throws. Error messages name fields, never values.The view (#154, part 1).
GET /api/runs/:id/contextanswers the bundle as a view (src/server/context-view.ts,runContextView). It readscontext.jsononce, with a size limit, and never throws.stateisavailable,absent(no file, as for every run before the bundle) orunreadable(with a fixed reason and a code). The view has the bundle's hash, the sources' hash, the creation time, the commit, the budget, one entry per source (kind, label, revision, selection,retrievedAt, freshness at the time of the request, classification, owners,sha256andbytes) and one per left-out source (status and next action). It never holds source text or the path of a stored text. Statuses and next actions are closed lists in the same file, so the wording is in one place. A user's answer is built from a list of fields: no address, id or owners for any entry, and only kind, classification, selection and freshness for a confidential or restricted source. The admin view hasuriandid. The UI (ui/run-sources.js) only draws the answer and exports it unchanged.
Context selection#
selectContext (src/context/select.ts) makes a bundle and the text of its sources from one
repository at one commit and the inputs of a task (#152). It is a function: no model, no network
and no clock (the caller gives now). The same repository state and task give the same sources and
hashes (hashContextSources). The engine calls it for issue runs (see "Writing a run's bundle");
giving the bundle to the agents is #153.
Inputs. A snapshot of the repository, the task (the issue text, its comments and the accepted refinement notes, all fetched by the caller; and the paths the task is about), a budget, the policy profile (id and version, which goes into
policiesand is never a source), and optionally the rules to run, a classification, the most private classification allowed, the consumers and how long a fetched input stays fresh.Only the declared commit.
openRepositoryAt(folder, commit)(repository.ts) reads through git only:ls-treeof the full commit id, thencat-fileby the object id from that list. The working tree is never read, so a changed, new or left-over file cannot get in. Reading has an optionaldeadlineMs(an absolute time, with the clocknow): every git call,cat-fileincluded, gets the smaller of its own timeout and the time left, and with no time left it throwstimeoutwithout starting git. Without a deadline the clock is never read. The folder must be the repository itself (a repository above it is not used), a branch, a tag or a short id is refused, and git runs without the caller'sGIT_*variables, without user or system settings and without fetching missing objects. A link is listed as a link and never followed; its text is not read either. A path that is not a safe relative path is never looked at.Rules, in this fixed order (
CONTEXT_RULES; the id is written toselection.rule):Rule Picks When it is not there task-issuethe issue text nothing refinement-notesthe accepted refinement notes nothing root-instructionsAGENTS.mdandCLAUDE.mdin the rootboth missing, when there is neithernested-instructionsAGENTS.mdandCLAUDE.mdin every folder above a path the task namesnothing ownership-filethe first of .github/CODEOWNERS,CODEOWNERS,docs/CODEOWNERS.github/CODEOWNERSismissingtask-commentsthe comments on the issue, oldest first nothing named-in-taskfiles the task names: the paths the caller gives, and paths of the commit spelled out in the task text a path the caller gave is missingapi-schema-filesopenapi,swaggerandasyncapifiles (.json,.yaml,.yml),schema.graphql(s),*.proto,*.graphql(s),*.avsc,*.openapi.*; nearest to the root first; not innode_modules,vendor,third_party,dist,build,target,outor a folder that starts with a dotnothing root-readmeREADME.mdin the rootmissingAn address is decided by the first rule that finds it.
Checks per file, the cheap ones first: not in the commit (
missing); a link or a submodule (unsupported); too private (classification); markedlinguist-generatedin.gitattributes(generated; the nearest.gitattributesthat speaks about the path decides); does not fit the budget (over-budget, known from the size in the list, so the file is not read); not UTF-8 text (unsupported); a comment in its first five lines says "Generated by", "@generated", "DO NOT EDIT", "automatically generated" or "auto-generated" (generated, as inflows/*.yaml).Budget. The order of the rules is the order of importance. Candidates are taken in that order; one that is larger than
maxSourceBytes, or does not fit what is left ofmaxSourcesandmaxTotalBytes, is left out asover-budgetand the next one is tried. So what a later rule found is left out first, and a small file may still fit after a large one did not.Owners come from the ownership file, and only when that file is in the bundle: the last line that matches a path decides, as on the host. Only handles are kept; an e-mail address cannot be written in a bundle and is counted, not kept. Patterns are matched part by part with a table, never as a regular expression, so a hostile pattern cannot stall the selector (
patterns.ts).Diagnostics. What a bundle has no field for is returned next to it as a code and a number: owners that are not handles, unsafe paths in the task, paths of the commit that were never looked at, a
.gitattributesfile that could not be read, and omissions above the 1000 a bundle lists.Writing (
store.ts):writeContextBundle(folder, bundle, texts)checks every text against its hash, then writescontext/<source id>per source andcontext.jsonlast, and returns the evidenceArtifactRef. It never replaces a file: a folder that already hascontext.jsonorcontext/is refused. Every file is made withopenSync(…, "wx", 0o600)and recorded at once, and every folder right after itsmkdirSync. If anything fails, the store walks that record in reverse and removes each entry (rmSyncfor a file,rmdirSyncfor a folder), never recursively, each in its owntry; then it throwswrite-failed. Files and folders it did not make survive, so a foreign file planted insidecontext/mid-write keeps its folder.
Issue files#
pull_ticket (blocks/pull-ticket.yaml) writes three files in the run folder, each removed when its
fetch fails: issue.json, issue-comments.jsonl and issue-foundry-comments.json, a JSON array of
the ids (safe integers ≥ 1) of the comments the Foundry wrote. A comment counts as the Foundry's when
GitHub says the account that runs the Foundry wrote it (viewerDidAuthor) and its body has
<!-- claude-factory or <!-- spaghetti-code-foundry. The printed issue text uses the same rule: such
a comment is headed --- comment by <login> (Foundry):. Any other line that starts with
--- comment by in an issue or comment body is quoted as > --- comment by, so no body can fake the
header.
readIssueFiles (src/context/issue-files.ts) reads the list with the same strict rules. A comment in
the list gets foundry: true. A missing, unreadable or invalid list marks nothing and the bundle is
still built (the planner then sees no Foundry comments). renderContextIndex shows a marked comment
with | by: Foundry. The index never holds comment text.
Writing a run's bundle#
src/engine/run-context.ts makes the bundle of an issue run (#707). The runner calls
contextBeforeStep(engine) for every top-level step that is not a shell or an approval step, between
the max_visits check and the ▶ line, so the bundle is written before the first agent step. The
hook does nothing unless contextPending holds: a top-level pull_ticket shell step that runs
issue.json, an ok pull_ticket record, no claude, parallel or flow record at any depth, and
none of context.attempt, context.json or context/ in the run folder (checked with lstat).
So custom flows and runs that already took an agent step get no bundle, and no log line.
- Attempt marker.
context.attemptis created first, withwxand mode 0400. It is never removed, so a run has one attempt, also after a resume or a restart. If it cannot be made, the result ismarker-failed. - Commit rule. The bundle is about the workspace's
HEAD^{commit}, read bygitHeadwith a clean environment,GIT_OPTIONAL_LOCKS=0,core.hooksPath=/dev/nullandcore.fsmonitor=false. The answer must be a 40 or 64 hex id; no commit givesrepository-no-commit. The working tree is never read. - Deadline. One deadline, now + 30 s (
CONTEXT_DEADLINE_MS), is shared bygitHead, the repository reads and the selection.gitHeadtakes the smaller of 10 s and the time left. After selection, a deadline that has passed givestimeoutand nothing is stored. A bundle that is stored and locked after the deadline is removed the same way. retrievedAt. The issue sources take thestartedAtof the latest ok top-levelpull_ticketrecord. A resumed run that fetched the ticket again is therefore judged by its newest fetch, not by the first one, sotask_max_age_secondsdoes not drop a fresh issue as stale.- Store and locking.
writeContextBundlewrites the files.lockRunContextthen sets files to 0400 and folders to 0500, deepest first; it walks withlstat, opens withO_NOFOLLOWand changes the mode withfchmodSync. If locking fails, the bundle's own paths are removed, never recursively.unlockRunContextsets the folders back to 0700, top-down, and never throws.scf cleancalls it before the purge removes the run folder. - Sandbox. The OS sandbox denies writes to
context.json,context.attemptandcontext/, in the normal and the read-only variant (src/engine/os-sandbox.ts). - Log.
contextBeforeSteplogs exactly one line, with no path and no value, and never throws. It returnsskippedwhen the hook does not apply. - Evidence (#638). Right after the write (or the failure),
contextBeforeStepcallsRunRecorder.contextBundled, which records onecontext.bundledevent. A written bundle givesoutcome: "written"withbundle(contextBundleRef, thecontext.jsonfile),sourcesSha256(hashContextSources), thelimits(ContextBudgetSchema),sources,bytesandomitted, a count for every omission reason (zero included). A failed selection givesoutcome: "failed"with only the fixedfailurecode fromRUN_CONTEXT_CODES. The schema refuses the other fields for each outcome.finalize.tsputscontext.jsoninto the manifest's files, soverifyEvidencechecks it by its hash like every other file: a changedcontext.jsonisfile-changed. - Policy (#638). For a written bundle, the hook then asks
context.selectwithcontextSelectFacts: the source count, the byte total (contextTotalBytes), the left-out count and the highest classification of the sources (left out when there are none). The decision is recorded as apolicy.decidedevent with no step, likerun.start. A failed selection is not asked. The engine does not act on the answer: the run goes on whatever the decision is, also inenforcemode. The fail-closed rules (privilegedBoundary) do not cover this boundary. - Old runs. A run without the event verifies as before;
EVENT_MIGRATIONS4 → 5 only sets the version.
Tool profiles#
src/tool-profile/ defines what an agent session may do with which tools, and what an agent program
can be made to hold of that (#146). Every agent step works out one profile before an agent starts
(#148; see "Run time" below). The folder has no side effects: schemas, version numbers and pure functions.
ToolProfile:version(of the format),profile(idandversionof the contents) andgrants. It names no agent program. It is closed: a kind, an operation or a target that no grant names is refused, and a profile without grants allows nothing.- Kinds and operations are closed lists.
files(the agent's own file tools):read,write.shell:run.git:status,clone,fetch,branch,commit,push.github:issue.read,issue.write,pull-request.read,pull-request.write,pull-request.merge,checks.read.web(the agent's own web tools):fetch,search.mcp:call.builtin(any other tool the agent program brings):call. A new kind or operation is a new version. - A grant names one kind, its
operationsand itstargets, and declares all of:dataClassification(public,internal,confidential,restricted: the most sensitive data a call may handle),credential(none,repository,machine: the list of the policy contracts),timeoutMs,maxConcurrentandoutputCapBytes(for one call;nullmeans no limit of its own), andapproval(noneorrequired). Ashellgrant also hassandbox:filesystem(read-only,workspace-write,unrestricted) andnetwork(none,unrestricted) for the commands it starts. Nothing is optional and nothing has a default. One operation of a kind is in one grant only, so two operations can have different targets or conditions. - Targets are patterns in which
*stands for any characters and nothing else is special. Each kind has its own form: a path forfiles(relative: in the workspace; starting with/: on the machine;/*is every file), a command line forshell,owner/nameforgitandgithub, a host name forweb,server/toolformcp, a tool name forbuiltin. A command line that joins or redirects commands (;,&,|,<,>, a backquote,$() is only allowed by the target*: a pattern is text, not a parser. checkToolCall(profile, call)answersallow,require_approvalordenyfor one kind, operation and target. A refusal has the policy reason codetool.not-allowed, orrepository.not-allowedfor a repository that is not a target; approval hasapproval.required.toolCallDenialgives thedenialof astep.deniedevidence event, with the tool namekind.operation(such asgit.push).- Hash and reference.
normalizeToolProfilegives the one canonical form (grants, operations and targets in a fixed order).toolProfileSha256is the SHA-256 of its canonical JSON, so the order a profile was written in does not count.toolProfileRefgivesid,versionandsha256: what a run keeps of the profile it resolved: everystep.profiledevent carries it. - Least privilege.
toolProfileExcess(a, b)lists every point whereaallows more thanb;isAtMostAsPermissiveis true when there is none.resolveToolProfile(identity, profiles)gives what all profiles allow under the strictest condition of any: an operation stays only when every profile grants it, a target only when every profile allows all of it, and of each condition the lowest is taken. Targets that overlap in part are dropped, never widened. The result does not depend on the order of the profiles. AdapterCapabilities:version,agent, and for every kind how the agent reaches it (own-toolsor, forgitandgithub,shell) and the controls the adapter can hold:deny-kind,limit-operations,limit-targets,require-approval,timeout,concurrency,output-cap; and the sandbox levels it can hold. A control that is not listed is not held.unenforceable(profile, capabilities)lists what a profile restricts that the adapter cannot hold, so a later story can refuse the profile or hold the rest another way (the sandbox of a user's run, a broker).- The two adapters today (
adapters.ts). Claude Code can deny a kind and limit operations and targets for files, the shell, web, MCP and its other tools, and can hold commands to the workspace. Codex has no list of allowed tools: it can switch off writing files and MCP servers and has three sandbox levels, and nothing else. Neither holds the network of a command, approval or a limit per call. For both, Git and GitHub are commands like any other: while an agent has a shell, a repository operation cannot be held by the adapter. - Flows of today.
legacyToolProfile(settings)turns the tool settings of an agent step (permission mode,allowed_tools, sandbox, the sandbox of a user's run, no tools, MCP servers, sign-in) into a generated profile with the idgenerated.flow-settings. It follows the same rules assessionToolsinsrc/skills/tool-policy.ts, and a test keeps the two equal. A rule it cannot express grants nothing and is returned inunmapped. No setting of today grants a Git or GitHub operation, a limit per call or approval, so the generated profile has none. - Skills.
tool_profilein a skill'sskill.yamlstays what it is: what a skill needs, in three words (shell, network, filesystem). AToolProfileis what a session is given.skillCapabilitiesOf(profile)puts a profile in those three words andmeetsSkillToolProfilecompares the two. The skill check itself is not changed. - Versions and errors. Each contract has its own number in
version.ts. A record with another version is refused with one sentence. AToolProfileSchemaErrorhas a code and the fields that are wrong, and never repeats a value of the record. - Run time (#148). An agent step resolves its profile once, before an agent is picked
(
resolveStepProfileinsrc/agents/tool-gate.ts), from the settings the step gets: the same inputs aslegacyToolProfile. The profile is then checked again for each try (gateTarget), so a retry or a fallback gets the same profile. A profile passed asRunOptions.toolProfileis read withdeclaredToolProfile, copied withsnapshotToolProfileand saved inrun.jsonastoolProfile, which resume reads. Likeowner, it is trusted server state: a changed or deleted saved profile is not detected, but eachstep.profiledevent carries its hash, so a change shows in the evidence. A saved profile that is no longer valid is refused on every step. - Refusal and partial. A declared profile is refused before an agent is picked when the
settings allow more than it (
toolSession, and again after mapping withmappedExcess). Each try then asksadapterFitwhether the agent holds it: rules with no meaning in a profile, data classes belowrestricted, controls the agent cannot hold, and the personal setup a session would load all refuse. The settings cannot say the data class or the network of a command, so those are not checked against them. A Codex shell command under its own workspace sandbox with no network isheldby that sandbox, not a gap; that relies on the network assumption of #147. A generated profile is never refused: what the agent cannot hold ispartialand only recorded. - The mapping only narrows.
mapSessionSettingsgives the sandboxes a session really runs with. Claude's sandbox is never switched on, because it would auto-allow Bash; Codex's sandbox is only made stricter, never wider. A generated profile maps to today's settings unchanged. - Diagnostics. A refusal or a log line uses only fixed words, error codes, counts and the first
12 characters of the hash. Profile ids, versions, rules, Zod messages and exception texts are never
echoed, so a profile cannot make a line look like a limit, an outage or a sign-in error to the
classifiers in
targets.ts.
Repository broker#
src/engine/repo-broker.ts and src/engine/repo-request.ts (#633, part 1 of 3 of #149) carry out
one repository operation on the server: clone, fetch, branch, commit, push,
pull-request and status (REPO_OPERATIONS). This part is a library only: no agent calls it yet,
so a run's behaviour does not change.
- Request.
RepoRequestSchemais strict and discriminated onop. Unknown fields are refused. Branch names followgit check-ref-format --branch(checked in code, at most 255 characters); a commit message or PR body is 1–5000 characters with no NUL; a title is 1–256 characters on one line. A request may name arepository(owner/name) on any operation, but never a URL or remote. The named repository is never the target: one other than the run's is refused (other-repository, see Refusals). - Target. Always the run's
github_repovariable, resolved on the server. The URL is the stored sign-in's (repoAccess), otherwisehttps://github.com/<owner>/<name>.git. A missing or placeholder repository is refused (no-target). - Checks, in order (
brokerRequest(ctx, request, grant)): 1. validate the request; 2. the target; 3. the tool profile (checkToolCallwith the repository as target); 4. pick the credential; 5. the workspace's git settings; 6. the commit identity; 7. policy; 8. run the operation; 9. record onerepo.operationevent. The result is{ outcome: "done" | "failed" | "refused", refusal?, output, pullRequest? }. - Refusals (
REPO_REFUSALS):invalid-request,no-target,not-in-profile,approval-required,deploy-key,no-credential,unsafe-git-settings,policy,not-empty,other-repository. A profiledenyorrequire_approvalalso recordsstep.deniedthroughtoolCallDenial. A policy denial goes throughrefuseByPolicy. - Another repository (
otherRepository, step 2b, before the profile): a request whoserepositorydiffers from the run's (compared in lower case) asksrepository.accesswith that repository as therepositoryfact, is refused asother-repositorywhatever the grant, and recordsrepo.operationrefused. An enforced deny from that question goes throughrefuseByPolicyfirst. No process starts and no credential is picked. The baseline rulerepository-not-allowedguardspushandrepository.access. - Credential. The narrowest one available, never wider than the grant's
credential:none: no sign-in.repository: only the repository's own stored sign-in. A GitHub App gives a fresh installation token limited to the repository and to the operation's permissions (APP_PERMISSIONS):contents: readfor clone and fetch,contents: writefor push,pull_requests: writefor a pull request. A stored token is used as it is. A deploy key is refused (deploy-key). No stored sign-in is refused (no-credential).machine: the repository's stored sign-in first. Only for a run that is not isolated does it fall back to the bot: a repository-limitedconfig.github_apptoken with the same permissions, otherwisebot.gh_token_env.- Local operations (
branch,commit,status) never get a credential. installationTokenInfotakes an optionalpermissions, sent in the request and part of the cache key.appTokenAccesspasses it on.
- Processes. Every
gitandghprocess runs with an argument list, never through a shell. Network operations getrepoTokenEnv: HTTPS only, no terminal or credential-manager prompts,GH_PROMPT_DISABLED=1, and a new emptyGH_CONFIG_DIRremoved infinally. Without a credential they get the same settings with no helper. A user's run usesshortEnv. The commit identity is the run's own (stepIsolation(...).who, otherwise the identity names).- clone:
git clone -q -- <url> ., only into an empty folder. - fetch:
git fetch --no-tags --no-recurse-submodules -- <url> +refs/heads/<b|*>:refs/remotes/origin/<b|*>. - push:
git push --recurse-submodules=no -- <url> HEAD:refs/heads/<branch>. Never forced. - pull request:
gh pr create --repo <repo> --head … --base … --title …, with--draftif asked and the body on stdin (--body-file -). - commit:
git add -A, thengit commit -q --no-gpg-sign -m <message>. With nothing staged it isdonewith "nothing to commit". - branch:
git checkout -q -B <name> [origin/<from>]. status:git status --porcelain=v1 --branch.
- clone:
- Git settings. Before an operation in an existing checkout,
git config --list --nullruns withGIT_CONFIG_GLOBAL=/dev/null,GIT_CONFIG_NOSYSTEM=1andGIT_CONFIG_COUNT=0. A key outsideALLOWED_GIT_SETTINGSrefuses the operation. The allowlist iscore.{repositoryformatversion, filemode, bare, logallrefupdates, ignorecase, precomposeunicode, symlinks},remote.origin.{url,fetch},branch.<name>.{remote,merge}anduser.{name,email}. So an agent-writtenhttp.proxy,http.sslVerify,include.*,url.*.insteadOf,filter.*orcore.fsmonitorcannot redirect traffic or read a token. The engine's ownGIT_CONFIG_*entries (core.hooksPath, so the pre-push hook still runs) come first, and the credential settings come after them. - Policy. Before the operation the engine asks
repository.access(tool,credential,isolated). A push also askspush(withbranchandcommitIdentity). Adenyrefuses withpolicy.RunPolicy.repository()is not called, so the step's own push facts do not change. - Output. Never holds a token. The issued token is redacted as
runShellredacts its pinned secrets, and stderr is scanned with the token and key guards. The output is cut to the grant'soutputCapBytes. - Evidence.
repo.operation(evidence version 4):step,operation(orunknown),repository?,branch?,credential,policy?(the combined outcome when policy was asked),outcome,refusal?(exactly when the outcome isrefused) andpullRequest?(only a done pull request).RunRecorder.repoOperation()writes it. Telemetry maps it totool.calledwith outcomeok,failedordenied, and causepolicyortoolwhen refused. A done push also emitsdelivery.push_attempted.
The evidence stream#
Every run appends its events to runs/<run-id>/evidence.jsonl (#135).
- Where it is written.
src/evidence/record.ts(RunRecorder) turns what the engine already has into events;src/evidence/stream.ts(EvidenceStream) writes them. The calls are at the edges of the engine:runFlow,resumeRun,finishandcancelWaitingRunfor the run; the loop,recordStep, the parallel step and the model loop ofrunAgentStepfor the steps. The scheduler passes who asked, when the job was queued and who cancelled. No prompt reads or writes evidence. - Order.
run.queuedcomes first when the run came through the queue (a new run has no folder while it waits, so the event is written at the start with the time it was queued), thenrun.createdandrun.started. A resume addsrun.queued(when queued) andrun.resumed. Every visit of a step isstep.started, then what happened in it, thenstep.completedorstep.failed. Thestep.afterquestion is asked before that end event (#728): itspolicy.decided, and astep.deniedwhen it denies, come beforestep.completedorstep.failed, and the event shows the result after the denial (failed). The delivery checks and push decisions come after the end event. A run that waits for approval or pauses ends withrun.stopped; the approval step itself starts when the decision is there. - One writer, one line. An event is one
writeof one line to a file opened for append. The writes of a run come one after the other, also when parallel steps end together.seqis the place in the file and the id follows from it (ev-000007), so both are stable. - Checked before written. Every event goes through
EvidenceEventSchema. There is no free text: a refused tool is its name, a model is three labels, a log is a path with its SHA-256 and size (required: true). Reasons, notes, outputs and errors are not recorded. - Never in the way. No call throws. The first problem (the file cannot be written, an event is not valid, the file holds a line that is not an event of this run) is written once to the live log, and the stream stops. It never goes on after a hole, and a stream that stopped has no end event, so such a run cannot count as verified later.
- Restart. The file is read when the first event of a start is written, and again when its size is not what this process left (another process wrote). Whole lines are never changed. A last line without a line end is a write that was cut off: a whole event gets its line end, a piece is removed.
- Not followed, not waited for. The file is opened without following a link and without waiting for a pipe, and only a plain file is used. The OS sandbox of a user's run denies writes to both evidence files.
- Privacy.
appendhides stored secrets in the texts of an event with the redactor ofcredentials/redact.ts(secretRedactor, onestatwhile the store is unchanged) and checks the finished line once more; a store that cannot be read, or a line that would still hold a secret, stops the stream like any other problem.finalizeRunEvidencechecks the whole stream and the manifest text the same way and writes no manifest otherwise. There is no second redaction system. - Retention.
cleanRuns(src/clean.ts) removes the evidence of a run it keeps only whenevidenceOlderThanDaysis given, and then all four files, manifest first. It never removes a log and keeps the evidence, so a kept run is either verifiable or has no evidence. - API.
GET /api/runs/:id/evidence(ruleown,src/server/evidence-view.ts) builds its answer fromverifyRunEvidenceand the manifest on each call and never throws; it sends references, not file content, and a user's answer leaves out models, policies and account ids and goes throughhidePaths. It adds nothing to the engine. A user's answer also leaves out the rule and the pack hash of each policy decision (policyDecisions, see "Policy hooks in observe mode"). - Stopped means stopped. The first problem also leaves an empty mark,
evidence.incomplete, in the run folder. While it is there no start of the run continues the stream and the run gets no manifest (#136). Nothing removes it. - What is derived. A shell step whose id has the word
testortestsis a test run. The pull request of a run is known only when the run was started for one (vars.pr). A target without a model name is recorded as modeldefault. A cancel or resume nobody is named for is the Foundry's (system).
The hash chain and the manifest#
The events of a run are a hash chain, and a run that ends gets a manifest (#136).
Canonical form (src/evidence/canonical.ts). One text for one value, the rules of RFC 8785:
- An object is
{, its members,}. A member is"name":value; members are in the order of their names, compared by UTF-16 code unit, with,between them. A member without a value is left out. - An array is
[, its values in their own order with,between them,]. - A string is in double quotes.
"is\",\is\\. The control characters U+0000 to U+001F are\b,\t,\n,\f,\ror\u00xx(lower-case hex); a lone surrogate is\udxxx. Every other character is written as itself. Nothing is normalized. - A number is written as JavaScript writes it (
12,-3,0.5); evidence only has whole numbers.true,falseandnullare these words. There is no space or line break. - The text is UTF-8 when it is hashed or written.
The hash of an event is the SHA-256 (64 lower-case hex characters) of the canonical form of the
whole event without its hash field. prevHash is part of it: null for the first event, the
hash of the event before for every other. It is taken over the event as it is written, never
over one that was brought to a newer version. tests/evidence-chain.test.ts holds fixed texts and
hashes; they change only together with the event version.
A stream is a chain (readEvidenceChain in chain.ts) when every line is a JSON object in
canonical form, byte for byte; is a valid event with seq equal to its place, the run id of the
stream and an id no earlier line has; has prevHash equal to the hash of the line before; and
has the hash of its own content. The first line that is not is named with one of eight faults
(not-json, not-canonical, unsupported-version, invalid, order, unchained, link,
hash). The writer checks the chain before it adds to a file it did not write itself, and does
not continue a file that is not a chain. Someone who can rewrite a line and every line after it
gets a chain again, with another last hash: that is why the manifest holds the last hash.
The manifest (finalize.ts). When a run reaches succeeded, failed or cancelled
(finish and cancelWaitingRun, right after the end event), evidence.json is written:
| Field | From |
|---|---|
status, finishedAt | the last event (run.completed, run.failed, run.cancelled) and its time |
startedAt | the time of run.created |
flow | run.created, and the SHA-256 of the canonical form of flowDef in run.json |
events | evidence.jsonl, the number of events, the hash of the last one |
git | base from run.started, final from run.completed |
models, policies | every model a step was given to or ran on, every policy that refused something: each once |
approvals, tests | every decision at an approval step and every test run, oldest first |
artifacts | every log, transcript and report the step events name, each path once (named twice: as named last) |
diff | evidence.diff, made at this moment: git diff <base> <final> with stored secrets hidden; required: false |
pullRequest | run.completed |
- Deterministic. The same events and files give the same manifest. The one field that depends
on time is
finalizedAt: the moment of writing, and never beforefinishedAt. The diff is made again each time, from the two commits; it is left out when git fails, takes more than 15 seconds or gives more than 20 MB. - Only for the end the run is at. A resume removes
evidence.jsonandevidence.diffbefore its first event; the events stay and the chain goes on. The next end writes a new manifest. The earlier end is still in the chain. - A failure is visible. Finalizing never throws and never changes the run. When it cannot be
done (the stream is not a chain, does not end with the end of the run, ends in another status,
has the
evidence.incompletemark, or the file cannot be written), any manifest that is there is removed and the live log says so once. A run without a manifest is not a verified run. - Runs that started before evidence. A resumed older run gets events from the resume on, but
no manifest: its stream does not begin with
run.created. - No secrets. The manifest is checked with
RunEvidenceSchemabefore it is written: ids, names, hashes, commit ids and one pull-request address. Files are written beside their place and moved over it, mode0600.
Verifying evidence#
src/evidence/verify.ts checks the evidence of a run (#137). verifyEvidence is pure: it gets the
texts of the manifest and the event file, the flow definition, and a function that looks at one
file. verifyRunEvidence(runDir, runId) reads them from a run folder. scf evidence verify
<run-id> (src/evidence/cli.ts) prints the result. No model, no network, no server, and nothing
is written.
The checks run in this order, and the first one that fails ends the run of checks (the later ones
are skipped):
| Check | Passes when | Failure codes |
|---|---|---|
manifest | evidence.json is a valid manifest of a version this Foundry reads and of this run, and there is no evidence.incomplete mark | incomplete, manifest-unreadable, manifest-version, manifest-run |
events | evidence.jsonl is a plain file that ends with a whole line | events-missing, events-unreadable, events-cut |
chain | every line is canonical, a valid event of a readable version, at its place, linked to the line before, with its own hash | chain- + the fault of readEvidenceChain, with the line |
terminal | the number of events and the hash of the last one are those of the manifest | events-added, events-removed, terminal-hash |
content | the manifest built again from the events is the same manifest | manifest-changed |
flow | the canonical hash of flowDef in run.json is the flow hash of the manifest | flow-missing, flow-changed |
files | every named file is a plain file of the run folder with the same SHA-256 and size | file-missing, file-changed, file-unreadable |
- Result (
VerifyResult, version 1):status,verified,explanation(one or two short sentences),failure(the first one:check,code,message,lineorpath),checks,manifest(the SHA-256 of the file, its status and time),events(count and last hash),files(each withstate:ok,changed,missing,unreadable) andmissingOptional. - Four outcomes.
verified;failed;not-finalized(an unbroken chain but no manifest: the run has not ended, or finalizing failed);absent(no evidence at all: a run from before evidence). Onlyverifiedsetsverified: true. - Required and optional. A missing file with
required: truefails. A missing file withrequired: falseis listed inmissingOptionaland does not fail. A changed file fails either way. All files are looked at, so the result shows every state; the failure is the first. - Files stay in the run folder. A file is read without following a link; a link anywhere on
its path, a folder or a pipe is
unreadable. Messages name lines and paths inside the run folder, never content. - What it cannot see. The manifest is the anchor: someone who can rewrite the events, the manifest and the files together gets evidence that verifies. The result gives the manifest's SHA-256 so it can be kept somewhere else (the delivery contract, #162).
- Fixtures.
tests/fixtures/evidence-runs.tswrites four runs from fixed content, with its own canonical form and hashes: valid, a changed event, a missing file, and an old run without evidence.
Delivery contract#
src/delivery/ defines the delivery contract (#649, part 1 of 2 of #162, part of #133): a versioned,
signed statement of what a pull request was handed over with, fixed at one moment. This part is a
library only: only types, schemas and pure functions. Nothing in a run writes a contract yet.
- Contract (
DeliveryContractSchema,schema.ts): version 1, strict, every object refuses unknown fields. It holdsrunId,sequence(1, 2, …),supersedes(the SHA-256 of the previous contract; set exactly whensequenceis above 1),repository,pullRequest,commit(sha,branch),dependencyLock(each lock file at the commit with its path and SHA-256, and one SHA-256 of that list; an empty list when there is none),ciWorkflows(each file under.github/workflows/with its git blob id),requiredChecks,evidence(path,count,terminalHashof the chain at that moment),artifacts(name and optional SHA-256),provenance(required) andstopConditions. - Stop conditions. A fixed list in version 1, in this order:
commit-changed,lock-changed,workflow-changed,required-check-failed(a required check is missing or did not pass),evidence-unverified,signature-unverified,superseded. The schema refuses any other list. - Order. Every list is sorted by UTF-16 code unit and holds each key once; the schema refuses an unsorted or repeated list. The lock hash must be the hash of the lock files.
- Build (
buildDeliveryContract(facts),contract.ts): pure. It uses no clock, no file and no randomness, sorts the lists itself, copies only the known fields and throwsDeliveryContractError(with the path and message of each issue) for bad facts. The same facts in any order give the same bytes. - Bytes and digest.
deliveryContractTextiscanonicalJsonof the contract.contractDigestis the SHA-256 of those UTF-8 bytes. A verifier also refuses a text that is not in this canonical form. - Signature (
sshsig.ts): the OpenSSHSSHSIGformat, in plain Node (no dependency, no child process): Ed25519, SHA-512, the namespacescf-delivery-contract, armoured output.signDeliveryContractsigns the text.ssh-keygen -Y verifyaccepts what is written here, and the tests check that (skipped when/usr/bin/ssh-keygenis missing).readSigningKey(text)reads one unencrypted Ed25519 key, in OpenSSH form or as a PKCS#8 PEM. An encrypted key, an RSA, EC or DSA key, or anything else is refused with a reason.publicKeyLine(key)givesssh-ed25519 AAAA….verifySshSignature(message, armoured, publicKeyLine, namespace)never throws. It checks the signature against the key inside it first, then against the trusted key.publicKeyFingerprint(line)givesSHA256:and the unpadded base64 of the SHA-256 of the key blob, asssh-keygen -lshows it. It isundefinedfor anything but a validssh-ed25519line.
- Verify (
verifyDeliveryContract(text, sigText, publicKey, eventsText?)): never throws. It returns the first fault in this order:unreadable(not JSON, not an object, not canonical, or not valid),wrong-version,signature-missing,signature-bad,wrong-key, andevidence-head-mismatch(only when the events are given). The head check reads the firstcountevents of the chain and passes when the event atcount - 1has the contract'sterminalHash, so events added later do not break it. A passing result carries the contract and its digest. - Validator (
tools/delivery-validate/validate.mjs, #671, part 1 of 2 of #667): a CI job checks a contract against the checked-out commit. It is one plain Node ESM script that imports onlynode:modules, so it needs nonpm ciand nodist/.scf delivery validate(src/delivery/cli.ts) runs the same script and gives the same stdout, stderr and exit code.- Copied rules. The script cannot load
src/, so it copiescanonicalJson,sha256Hex, the field helpers ofidentity.ts,DeliveryContractSchema(ascontractProblems),verifySshSignaturewith its reader and key parsing, anddecodeBase64Exactanded25519PublicKey.node:cryptoverifydoes the cryptography. A comment at the top says to change both copies. The parity test runs the script andverifyDeliveryContracton the same contract, signature and key (good and tampered fixtures, each re-canonicalised and re-signed so one fault is present) and compares the verdict and the fault. - Check order.
contract,signature,commit,locks,workflows,checks,evidence,comment. Ifcontractorsignaturestops, the later checks areskippedand git is not run. - Fault → condition.
unreadable,wrong-version,signature-missing,signature-badandwrong-keystop withsignature-unverified. A HEAD that is notcommit.shagivescommit-changed. A lock that is changed, missing or not a blob giveslock-changed. A workflow that is added, removed or changed givesworkflow-changed. A required check that is missing or notsuccessgivesrequired-check-failed. With--events, a chain that fails the library's checks, or whose event atcount - 1lacksevidence.terminalHash, givesevidence-unverifiedwithevidence-head-mismatch. A valid chain of this run that holdslocalTestgivesevidence-unverifiedwith the faultlocal-test(deliveryEvidenceProbleminsrc/delivery/contract.ts, the same rule as the Foundry's own check). A broken chain that holds the marker still givesevidence-head-mismatch. With--comment, a digest that differs givessuperseded, and an evidence hash that differs fromevidence.terminalHashgivesevidence-unverified. - Evidence chain (
--events, #672). The script reads only the firstcountlines of the events file (256 MiB at most) and checks them in the order ofreadEvidenceChain: each line is a canonical JSON object; the version is upgraded as inupgradeEvidence(a version above the script's pinnedEVIDENCE_EVENT_VERSIONis refused); the fullEvidenceEventSchemaholds, with every refinement;seq,runIdand a uniqueidare right; the hash andprevHashlink and the content hash match. Lines aftercountdo not matter. The script reads the marker from the same chain:readChainsetslocalTestonly after a line has fully verified, andcheckEvidencestops withlocal-testafter the terminal-hash comparison. The version is 1.1.0, because a verdict changed. The schema copy is one marked section of the script, andtests/delivery-validate-events.test.tsis the drift guard: it reads the script's constants, compares them with the library's enums, and builds one valid event per type and enum value. A new event type, enum value or version fails that test until the script is updated. - git. Read-only calls through
execFilewith argument arrays, never a shell. HEAD is resolved once and used for every lookup.GIT_LITERAL_PATHSPECS=1makes a path in the contract a literal path. The locks usels-tree -z --full-treeandcat-file blob; the workflows usels-tree -r -zon.github/workflows/, so subfolders count and other files are ignored. A git failure, or a--repothat is not a repository, is a read error (exit 2) with git's first line, cleaned. - Output. One line per check:
<check>: ok,<check>: stop <condition>: <reason>or<check>: skipped (<why>).--jsonprints{version, result, digest, checks}. Control characters in reasons become?. An error message never repeats file content. Askippedcheck is not a pass. - Inputs. Options are parsed in strict mode.
--public-keyis a key line or a file (16 KiB at most). Text files are 1 MiB at most.--checksis a JSON list of{name, conclusion}(a conclusion may benull); duplicates must all besuccess.--commentmust hold exactly one marker line:<!-- claude-factory delivery-contract digest=<64 hex> evidence=<64 hex> -->(CRLF allowed). Part 2 of #667 writes this marker, so the format is fixed. - No writes. The script never writes a file, and never fixes or regenerates a contract.
- Not yet. No run writes the comment yet, so the validator is used only where a CI job runs it.
- Copied rules. The script cannot load
- PR comment (
src/delivery/comment.ts, #697). A library that builds and reads the comment that carries a signed contract on a pull request. Nothing posts it yet.- Layout. A first line (
reportFirst("info")forokandunsigned; a "what you need to do" line forstop), a### Delivery contractheading, a status line (**Verified.**,**Not verified.**for an unsigned contract, or**Stopped:** `<condition>` — <reason>), bullets for the run, sequence, digest, commit, branch, evidence count and terminal hash, and the key fingerprint orunsigned. Then up to 50 check lines (more get an "and N more" line), a<details>block with the contract and the signature, and the markers as the last two lines. - Two markers. The validator marker
<!-- claude-factory delivery-contract digest=… evidence=… -->is the onevalidate.mjs --commentreads (VALIDATOR_MARKER_REmatches itsMARKER). The delivery marker<!-- <product> delivery-contract run=<id> -->is always the last line, and only the Foundry writes it.isDeliveryCommentaccepts it only as the last line (LF or CRLF), so a quoted or mid-body copy does not count. - One comment per pull request.
upsertStatusCommentwithon: "pr"andmatch: isDeliveryCommentfinds any run's delivery marker, so a later run edits the same comment and the others are left alone.on("issue"by default, or"pr") picks the comment list and the posting call (prComments,commentOnPullRequest).matchpicks which comments count (isStatusCommentby default). - Contract and signature blocks.
json scf-delivery-contractholds the canonical text andtext scf-delivery-signaturethe signature. Each fence is longer than any backtick run in its content, so the content cannot close it. - Safe text. Reasons and check lines go through
safeLine: secrets are taken out (scrub, which throws when it cannot be sure), white space is folded,<and>become‹and›, backticks become', mentions are neutralised, and the result is at most 300 characters with the ellipsis counted. Nothing is deleted, so no delimiter can be rebuilt. The signed contract bytes are never changed: a contract with a secret in a string field is refused. - Too long. Above 60 000 characters the details block is replaced by a pointer to
delivery/contract-<n>.jsonin the run folder. - Reading.
readDeliveryCommentreturns the contract, signature, digest and evidence from a body. It never throws, and a body with two validator markers gives no digest or evidence. - Checks.
deliveryCommentBodythrows when the run id is bad, the contract fails its schema, the digest is not the digest of the text, or the signature is not in SSH-signature form.
- Layout. A first line (
- Writing (#657, part 3 of 4 of #650).
src/delivery/write.tsandsrc/delivery/git-facts.ts. - Writing (#657, part 3 of 4 of #650).
src/delivery/write.tsandsrc/delivery/git-facts.ts.- Local tests.
write()refuses a local-test run in two places: at step 0, when the input sayslocalTest(from the run summary, so no folder is made), and after the chain check, when the events have the marker (a run whoserun.jsonlost the key). Both log the fixed line fromDELIVERY_WRITE_FAULTS.localTestand write nothing. The refusal is logged once per top-level step after the pull request exists, sodeliveryAfterStepstays stateless. - Trigger.
deliveryAfterStepruns fromrecordStep(execute.ts) after the step outputs are read, for top-level steps only. It needsoutputs.pull_requestto be a pull request of the run's repository (parsePullRequestUrl, case-insensitive) and a workdir that exists. It never throws. - Live settings.
Engine.deliverySettingsis read at each call. The scheduler fills it from its live config getter, so a settings change applies from the next step.deliveryRequirementsgives the global values, and a repository entry overrides only the fields it sets. - Bounded git reads.
readCommitFactsuses synchronous git withcleanEnv,GIT_NO_REPLACE_OBJECTS=1,GIT_NO_LAZY_FETCH=1andSAFE_OPTIONS, under one deadline (10 s by default). It throwsCommitFactsErroron a detached HEAD, too many lock or workflow files, too many bytes, a timeout or a missing object.ls-tree -rreads the commit, and the blobs come in onecat-file --batch.reusewith the same commit skips git. Messages never show git's output or paths. - Evidence. The count and terminal hash come from
evidence.jsonlthroughreadEvidenceChain. A missing, broken, truncated-tail or incomplete chain (evidenceIncomplete) writes nothing. A previous contract must still match the chain (evidenceHeadProblem). - Comparison rule. The facts are compared with the latest contract, leaving out
version,runId,sequence,supersedesandevidence. If they are equal, nothing new is numbered, and only a missing or stalecontract.jsoncopy is put back. - Storage.
<run>/delivery/is created with mode 0700 only when it is absent.contract-<n>.jsonand.sigare created withwxand mode 0600, so they are written once. The latest copy is replaced by renaming a temporary file. An unsigned contract removescontract.json.sig. A failed write removes the files it created. - Key folder. The signing key must resolve (real path) inside
<data>/delivery-keys. Otherwise nothing is written. Key files are read with a size limit and no link following. - Errors. Every fs error becomes one fixed line from
DELIVERY_WRITE_FAULTS, with no path and no system message.
- Local tests.
- Verifier (#658, part 4 of 4 of #650).
src/delivery/run-verify.ts.verifyRunDelivery(runDir, runId, publicKey)never throws and only reads. It reads each file as raw bytes with a size limit and no link following, and decodes it as strict UTF-8, so a changed byte cannot decode to the signed text. It checks the folder (plain, only contract files), the numbering, the signatures against the trusted key,supersedes, the latest copy, theevidence.incompletemarker and the evidence chain up to each contract'scount(throughdeliveryEvidenceProblem, which also giveslocal-testfor a marked chain, signed or not). The first failure ends the check with onefaultand a relative path. The result isverified,failed,unsignedornone, anddeliveryVerifyExitCodemaps it to 0, 1 or 2 (none gives 2). Events after the last contract are allowed.deliveryCommandhandlesverifyandpublic-key; the key comes from--public-key(readPublicKeyFile) or from the configured signing key (readConfiguredSigningKey). Nothing in the server, the UI or CI calls it yet. - Not yet. No server or UI reads a contract. Making CI stop on a missing contract, and the stop conditions in a run, are the next part of #162.
- Tests.
tests/delivery-contract.test.ts(order, golden text, every byte of the text, the order of faults, the head check) andtests/delivery-sshsig.test.ts(round trips, every character of the signature, refused keys, the realssh-keygen). Both are unit tests: no server, no git, no run.
Handoff (#698)#
src/delivery/handoff.ts and tools/delivery-handoff run the handoff step of release-daily (after
checks). The step checks the run's latest contract, keeps one delivery comment on the release pull request and
then marks the pull request ready or draft. handoffCommand(args, io, deps?, env) never throws; the tool sets
process.exitCode and does not call process.exit.
- Trust. The public key comes only from the engine environment (
stepEnvinsrc/engine/execute.tssetsFACTORY_DELIVERY_PUBLIC_KEYandSCF_DELIVERY_PUBLIC_KEYfromdeliveryKeyEnv). It is""by default and-for a key that cannot be used; aFACTORY_DELIVERY_PUBLIC_KEYinprocess.envis overwritten. The private key never reaches a step. A sandboxed step cannot write<run>/delivery/, so the contract the handoff reads is the one the engine wrote. - Without a key the handoff prints
HANDOFF: skipped (…)and exits 0. With a key but no usable input or no pull request it printsHANDOFF: stop …and exits 1; gh is not called in either case. - After-step write.
deliveryAfterStepstill runs afterhandoff. It writes a contract only when a stated fact changed (writeContract,write.ts), and the handoff changes none. A test (tests/delivery-write.test.ts) holds that nocontract-<n>.jsonis added, even when the remote head has moved. The step is not special-cased inrecordStep. - Draft while checking. With a key, the step makes the pull request a draft before the check and marks it ready
only after
HANDOFF: ok. A killed step (timeout or cancel) therefore fails closed. Without a key nothing is made a draft first, so unsigned installs keep today's behaviour. A failed draft or ready call is reported; the ready call fails the step. - Verdict.
checkHandoffruns the checks in this order:signature(parseSshSignature, the trusted key,verifyDeliveryContract),superseded(a newercontract-<n>.json, another.sigcopy, or another repository, pull request or run id),commit(remoteHeadviagit ls-remote origin refs/heads/<branch>, thenreadCommitFacts),locksandworkflows(compared with the contract's hashes and blob ids, sorted withcompareCodeUnits),checks(waitForChecks, then the validator's rule), andevidence(the bounded read ofevidence.jsonlanddeliveryEvidenceProblem). The first stop wins; with none the verdict isok. Without a signing key there is no signature check, so thekey === ""branch reads the run's events itself: a valid chain of this run with the marker stopsevidence-unverified(local-test) instead of returningunsigned. An unreadable file or an unmarked chain still returnsunsigned. - Head re-read. If the check runs were polled more than once and the commit check passed,
remoteHeadis read again. A changed, missing or unreadable head is acommit-changedstop. The window that remains is the seconds between that read andgh pr ready; the CI validator is the hard check for it. - Waiting.
waitForCheckspollscheckRunseveryCHECKS_POLL_MS(15 s) until every required name has a completed run, or one required check has finished without success. It returns the last good read when the deadline would pass before the next poll, and{ok:false}when there was none.checksWaitSecreadsFACTORY_DELIVERY_CHECKS_WAIT_SEC(integer 0 to 3600, otherwise 600). Only the first 100 check runs are read; a required check beyond them counts as missing, which fails closed.sleepandnoware injected. - Output. Every reason and
whygoes throughsafeLine(comment.ts, the secret scrub) before it is cut toHANDOFF_TEXT_MAX(300) characters, and control characters become?. Scrubbing comes before the cut, so a cut cannot leave half a token unrecognised. If the scrub throws, the text is the fixedthe reason cannot be shown. - Comment. Unless the result is
none,deliveryCommentBodybuilds the body; when it throwsDeliveryCommentErrorthe body is built again without the contract, andupsertStatusCommentwithon: "pr"andisDeliveryCommentas the match edits the one delivery comment in place. An identical body is not patched (upsertStatusCommentcompares it). Failures printdelivery comment: could not be updatedand keep the verdict; gh output is never printed. - Flow.
release_pronly printsPR:andTITLE:. Thehandoffstep hasrepo_access: trueandtimeout_sec: 1800. The ready mark (without--undo) comes after the handoff in the step's shell script; a test checks that order. - Rejected. A handoff in the engine would need a new step kind. Running
validate.mjscannot read the remote head or poll the check runs.--draftongh pr createfails on private repos on free plans. - Tests.
tests/delivery-handoff.test.ts(every stop, the head re-read, the wait with a fake clock, the scrub, and the in-process command against a fakeghand a bareorigin),tests/delivery-write.test.ts(deliverySigningKey,deliveryKeyEnv, the no-write after-step case),tests/untrusted-output.test.ts(stepEnv) andtests/gitflow.test.ts(the step order and flow checks).
Telemetry#
src/telemetry/ writes one value-free event for each lifecycle fact of a run, to a local daily file (#584,
part 1 of 3 of #155). It is a second, smaller view of what the evidence already records; it does not replace
the evidence and nothing depends on it.
- Envelope.
envelope.tsdefinesTelemetryEventSchema:version2 (TELEMETRY_VERSION), a strict object withid,time,kindandnamerequired, and optional labels that reuse the identity schemas ofevidence/identity.ts,evidence/schema.tsandpolicy/schema.ts. The kind and name must match (run,step,model,policy,tool,delivery,pull_request,watcher). There is no free-text field, and unknown fields are refused. Version 2 adds therun.measuredname and themeasuresobject (see below);measuresis present exactly forrun.measured. The id isev:<run>:<evidence id>(with:prfor the pull request ofrun.completed) ortm:<32 hex>. - From evidence.
telemetryFromEvidencemaps every evidence body to at least one draft; it never throws. A line that was written gives the evidence id andseq; a body that was not written (the stream has stopped) gets a randomtm:id and noevidence.RunRecorder.puttakes one time for both the append and the telemetry, so the two agree.watcherRefgives the watcher part of an event. - Live events (#585, part 2 of 3 of #155). Events with no evidence line are written by
emitLiveTelemetry(kind, name, fields)intelemetry.ts. It gets a newtm:id and the time now, returns at once when telemetry is off, and never throws. Itsnameis typed againstTELEMETRY_NAMES[kind], so a wrong kind/name pair fails the build. Sources:delivery.push_attempted(recordStep, from the push log),tool.called(onToolofrunClaude, Claude Code only, name only),watcher.checked/watcher.failed/watcher.queued(Watcher) andpull_request.feedback(Watcher.submitfor a PR). Each label (repository, branch, tool name, actor) is checked with its own schema and left out when it fails, so one bad label does not drop the event. - Measures (#612, part 1 of 2 of #156).
src/monitor/measures.tsholdsMEASURES, the catalogue of 12 measures. Each entry has aname, aunit, anowner(adminorrepository owner, a role and never an account) and adecision(the detector or the setting it informs). A test fails when an entry lacks an owner or a decision.measureRun(run, events)is pure: it reads no files, calls no AI and never throws. Per step it gives duration, retries, tokens, cost, denials, context size and tool latency. Per run it gives queue time (run.queuedto the firstrun.started), stops and resumes, approval latency (approvalstep.startedor the stop at the approval, tostep.approvedorstep.denied), policy outcomes (one count per outcome, andpolicy.unavailable/policy.invalidtogether) and the pull-request result. A missing source leaves its measure out.readRunEvents(runDir, runId)readsevidence.jsonlloosely: an unreadable line is skipped.emitRunMeasured(run)writes onerun.measuredevent after evidence finalization infinish,cancelWaitingRunandcancelStoppedRun. Itsmeasuresobject isTelemetryMeasuresSchema: numbers ≥ 0 only, all optional, strict. It is the sums and maxima of the steps and the run's own numbers. OTLP flattens these numbers on its own.- Tool latency.
runClaudetimes each call from itstool_useto itstool_result(streamMeter, whole ms).onTool(name, durationMs)sendstool.calledwithdurationMswhen the result arrives. A call that never gets a result is sent at the end of the session without it.StepRecord.toolsholdscalls,totalMsandmaxMs. - Context size.
StepRecord.contextTokensis the largest input of one model turn (input, cache read and cache creation tokens from theusageof each assistant message). Claude steps only; Codex has none. - Retries. Tool times and context size are kept over all tries of an agent step, so a retry never hides an earlier, slower call or larger context.
- Tool latency.
- Outcomes (#617, part 1 of 4 of #157).
src/outcomes.tsholdsOUTCOME_DEFINITIONS, the ten outcome measures, andcomputeOutcomes(runs, facts, window), which is pure and never throws (on an error or a bad window every measure isnull).src/outcome-facts.tsturns one run's events into small facts (outcomeFactsOf, pure).OutcomeFactsCachereadsevidence.jsonlfor them. Each definition has a decision sentence and the detector or setting it informs.- Delivered. A run is delivered when it succeeded and a
pushpolicy decision has an outcome other thandeny. So merge rate is "pushed work": a merge done by hand on GitHub is not seen. Observe mode is literal: an observeddenyatpushis not a delivery, unless another decision at that push allows it. - Window. Runs count by
finishedAtin[from, to). Work items count by the end of their first delivery (the earliest ended, delivering, evidenced run of the item). Issue-to-PR time starts at the earliestrun.queued(or start) of the item's runs up to that delivery. Rework counts delivered items with a later run on the same item that ends beforeto. Returning users compare the owners of the window with the owners of the previous window. - Exclusions. Refinement runs are excluded everywhere and are never open. Open runs (not ended, started in the
window) only count in
open. Runs whose evidence is missing, too old, too large or a link are excluded from the measures that need evidence; cost, resumes and returning users do not need it. - Unit of
excluded. Always runs, never work items, so the counts can be compared across measures. A run that is excluded for two reasons counts once. - Pairing. Every speed (
ms) and cost (usd) measure listspairedWithmeasures from the quality, rework, policy and user categories, so that a faster or cheaper result is always read with its effect on quality. A test checks this for every catalogue entry. - Cache limits.
OutcomeFactsCacheholds 2000 finished entries (the least recently used goes first). A run is read only when it has settled (SETTLE_MS, 2 minutes afterfinishedAt), at most once per run folder, run id andupdatedAt, and calls that come while the read runs share it. The read uses the same guards as the SLO input: no links (O_NOFOLLOW) and no file overMAX_EVIDENCE_BYTES(16 MiB). The cache keeps the facts, never the events. The manifest and the incomplete marker are checked on every call, so a late file shows up. - Owners. The definition texts and the owners are a proposal, reviewed by the owner in the pull request.
- Delivered. A run is delivered when it succeeded and a
- Push log. The pre-push hook already appends
<branch>\t<remote url>toFACTORY_PUSH_LOGbefore its checks, so a refused push is logged too.pushLogForreturns that file also when telemetry is on and the protected-branch or secret-scan hook is installed. Hook installation is unchanged on purpose:core.hooksPathreplaces the repository's own git hooks, so turning it on for telemetry would change every run in every repository. - Privacy.
privacy.ts(privateTelemetry) runs three checks, all closed.idandrunIdmust not change underscrub(identity). Each redactable label is checked on its own with the stored credentials andhelp.sensitive_patterns; a label that changes is removed and listed inredacted. The canonical line is checked once more, reading the credential store again; an unreadable store drops the event (privacy). - Local file.
local.tswrites<data folder>/telemetry/events-YYYY-MM-DD.jsonl(UTC day) withO_APPEND,O_NOFOLLOWandO_NONBLOCK. The folder is made 0700 and the file 0600, loose modes are tightened, and a link or a path owned by another user is refused.sweepTelemetry(keepDays)removes only old plain files namedevents-<day>.jsonl, never through a linked folder. The sweep runs each time the writer opens a file. - Hub.
telemetry.tsholds the state:configureTelemetry(config, { log })readstelemetryandhelp.sensitive_patterns; alogreplaces the current one, and without one the earlier is kept.emitTelemetryvalidates, checks and writes each event, and never throws. A drop is counted and each reason (invalid,privacy,identity,write) is logged once, in fixed words, throughDROP_WORDS.resetTelemetryis for tests. - Wiring.
runFlowandresumeRuncallconfigureTelemetryright after the config is loaded;scf watchdoes it right afterloadConfig()(with its log line); the server does it afterreadConfig()and on every reload. Withtelemetry.local: falsenothing is opened and no folder is made. - OTLP exporter (#586, part 3 of #155).
otlp.tssends the same events as OTLP/HTTP JSON logs. It is made only whentelemetry.otlp.enabledis true and has an endpoint, and it gets only events that passed the schema and the privacy check, so it adds no new field.otlpLogsRequestmaps each event to a log record: the time as a string of nanoseconds,traceId= the first 32 hex characters of SHA-256 of the run id (the same for every event of a run),scf.*attributes flattened from the event, and WARN forfailedordenied. - Why no SDK. The OpenTelemetry SDK would add dependencies, its own timers and process listeners, and a
global state that the hub cannot control. A request of a few lines of JSON with
fetchis enough for the one signal we send, and every rule below stays in our code and our tests. - Exporter.
OtlpExporterkeeps a queue of at mostOTLP_QUEUE_MAX(1000) events; when it is full the oldest is dropped and counted asfailed. A batch is sent atOTLP_BATCH(50) events, or by an unref'd 2 s timer for a short batch. Flushes are serialized: one request at a time, each withredirect: "error",content-type: application/jsonand anAbortSignal.timeout(timeout_ms). There is no retry. Each response body is released, and a request that throws or returns a non-2xx status counts asfailed. The exporter never throws and holds no process listener. - Log lines. The first failure of a period logs one
!line; the first success after it logs one·line. The text is fixed (OTLP_WORDS), so no value appears in it. - Hub.
telemetry.tskeeps one exporter for the current config. It is made on the first event. It is kept while the endpoint, the timeout and the enabled state are unchanged, and it is retired (closed, not dropped) when one of them changes.fetchis injected throughconfigureTelemetry(config, { fetch }), and the hub countsexportedandfailedintelemetryStats(). A callback of an exporter from before aresetTelemetry()does nothing, so old requests cannot change the new counts or the log. - Shutdown.
closeTelemetry(ms = 3000)closes the local file, asks the exporter to send what is queued and waits at mostms. It waits for every exporter that is closing, also when called twice, and an event that arrives while it waits is sent if time is left. After the limit the queue is dropped and counted, and a request in flight is aborted.exitAfterTelemetry(code)runs it once per process, then waits until stdout and stderr have handed their buffered output to the OS (flushed(stream); a closed or broken stream does not wait), and then exits with the code. Without that wait a large--jsonanswer on a pipe was cut off at 128 KB; the CLI uses it in themainhandlers, thewatchinterrupts and theservesignal handlers (after the updater stops), andserver.close()callscloseTelemetry()before the HTTP server closes. - Not yet. Endpoint authentication and a Settings control (see
settings/exceptions.ts). The synchronous restart insrc/supervise.ts(process.exitafter the restart) does not go throughexitAfterTelemetry, so the last unsent batch can be lost there. This is a follow-up.
5. Agents and models#
An agent step names what it needs (a model, an effort level, allowed tools); the Foundry decides where it runs.
- Two agent programs: Claude Code and Codex, both run headlessly as child processes.
- Model specs such as
sonnet,codex:gpt-5,ollama:qwen3-coder; routing rules can send steps to other models, with fallbacks. - Roles in the shipped flows: a strong model plans, a different vendor's model reviews the plan and the code, a fast model writes the code. A reviewer from another vendor finds more than a model reviewing itself.
- Reviewers are read-only. Coding agents get edit tools and the project's build tools.
- Failures are sorted into: a usage limit (pause, try again later), signed out (pause until the user signs in), a passing capacity problem (retry after 1 and 3 minutes), or a real failure.
- A clean environment. Variables of the session that started the server are removed before an agent starts; secrets are never placed in an agent's environment.
Run priority (#747)#
Every process of a run goes through spawnTarget() in src/steps/process.ts, its one spawn point. The
ProcessOptions.priority field (from governor.priority, passed by the shell, Claude, Codex and broker
callers) puts the command behind /usr/bin/nice -n <delta> and /usr/sbin/taskpolicy -c <qos>, in that
order and outside any sandbox-exec profile, so the wrappers cannot be refused by a profile. Both
exec the command: the pid and the process group stay the same, so cancel, timeout and group kill reach
the real process. low is nice 5 and utility; background is nice 15 and background. The nice
delta is computed from os.getPriority(0), so a priority is never raised. priorityMachine() trial-runs
each tool once per process (cached) and uses only the ones that work; a command that cannot be found is
started unwrapped, and a wrapper that fails to start before the command ran falls back to the plain
start (WrapperStartError). The server process is never wrapped.
While busy mode holds (busyHolds() in src/ops/busy.ts), runProcess() starts a process that has a priority at background, through busyPriority(). The check runs at each start, so a switch on or off applies to the next process. A running process is never renice'd: without root rights a lowered process cannot be raised again. The hand switch is governor/busy.json, and its cap (busy) in governor/caps.json is written by syncBusyCap(): the server calls it at start, then every 60 seconds (BUSY_RENEW_MS), and it is cleared when the switch ends. The cap always has an end (4 minutes, or the switch's own end if sooner), so a stopped server cannot hold runs down. The governor's program check (governorBusyApps(), in src/ops/cli.ts) owns the busy-apps cap, and a reading whose names could not be read leaves that cap alone.
6. The queue#
One scheduler for all runs:
- A fixed number of slots (
concurrency). - Locks: a flow can ask for one run at a time per repository.
- Fair use: with
userLimitsandstartedTodayset (the server passeseffectiveLimits), a user never has more runs active thanmaxConcurrent, and new runs wait oncemaxRunsPerDayare started today.pump()picks the next job: priority block first, then the owner with the fewest active runs, then the owner whose last start is oldest (kept in memory), then queue order, and re-evaluates after every start. Jobs without an owner are not limited and form one group. Resumes count formaxConcurrentonly. Today's count comes fromsrc/queue/usage.ts(run briefs, by run id) plus runs started in the current pump.queue()marks waiting entries withlimit(concurrentorper_day); the status kinduser_limitshows it without numbers, andqueue-stalledignores such jobs. The CLI and evals pass no options, so they have no limits. - A persistent queue file, so queued work survives a restart.
- Runs that were active when the server stopped are marked interrupted and continued.
- When a run ends, the watchers of its repository check at once, so the next story does not wait for the next interval.
Code areas. A plan lists the areas of the code it will change. Before coding, the run claims
them with tools/area-lock. If another run holds one, the run steps aside: it stops and
frees its slot, and continues when the holding run has stopped working. Documents, Markdown
files and whole test folders are not locked.
7. Watchers: from GitHub issue to merged code#
A watcher checks GitHub on an interval and starts runs. Sources: issues with a label, review comments on the Foundry's pull requests, a red build, or a schedule.
flowchart TD
I[Issue gets the build label] --> P{New batch?}
P -->|yes| QF[epic-questions: ask what only the owner can decide]
QF -->|questions| NI[Label: needs info]
NI -->|answer or /defaults| D
QF -->|no questions| D
P -->|no| D{Depends on open stories?}
D -->|yes| WAIT[Waits; the app says for what]
D -->|no| S[Start a run of the flow]
S --> R{Result}
R -->|succeeded| DONE[Label: done; issue closed when merged]
R -->|waiting for a person| WA[Label: waiting; shown under Your turn]
R -->|paused: limit, sign-out, code area| CONT[Continues by itself]
R -->|failed| ERR[Label: error; comment explains]
WA -->|/approve, /reject| S
CONT --> S
What a watcher takes care of:
- Labels as status. One label is set by people (the trigger). The Foundry sets the others: working, done, needs info, waiting, error. At every check the labels are compared with the newest run and corrected.
- Dependencies.
Depends on/Blocked byin the issue text, by number or by title. A story waits until what it depends on is done. - Answers on GitHub. A reply to questions,
/defaults,/approveand/rejectcontinue the run. - GitHub lags. Before starting anything a second time, the watcher asks GitHub for that one issue again.
- A status comment on the issue that is edited in place, not a new comment each time.
- Tidying: closed issues lose their status labels; runs that wait for a person end when their issue is closed.
- Issue states. At every check an issues watcher stores whether each issue with an
unfinished run (failed, stopped, waiting or cancelled, any flow, any age) is open or closed
(
src/issue-states.ts). Issues in the open list of the check are stored as open without asking GitHub; the rest go in one batchedgh api graphqlcall (more than 500 are sent in sequential chunks). If the call fails, nothing changes,failedAtis set and the watcher shows the errorchecking closed issues: ….knownIssueState(repo, issue)answersopen,closed,unknownorundefined(no enabled issues watcher). Nothing a user sees uses it yet. - Red base branch (#742).
src/red-base.tskeeps one state per repository and branch inred-base.json. Its decisions are pure:judgeStops(two stops on one commit with the same failing tests, or one clean stop),advance(a green on the head clears; a green on an older commit does not),stoppedOnRedandnewEvidence(a stop covered by a movedclearedstate is no new evidence). The green rule usesBASE_GREEN, the last line of a clean baseline run of the same branch; greens come from all runs of the repository, one run per flow, not collapsed by issue.checkRedruns insideinOrderfor the repository and branch. It writes apendingentry before it creates the fix story, so a crash after the create finds the story by its marker and does not make a second one. A search that fails, or a search cut beforepending.at, makes nothing and setsproblem. A head read happens only when nothing is held and a stop is not yet covered by the stored state.FACTORY_RED_BASE(redBaseEnv, at most 64,000 characters) gives the baseline step the state, so the gate intools/baseline-tests(known-red) stops a held run before the test command. Test names reach GitHub only afterredactText.

8. The two pipelines#
Gitflow pipeline (default) — one label, one flow, a person only for risky plans:
flowchart LR
T[pull ticket] --> BR[feature branch] --> BT[tests before the change]
BT --> PL[plan] --> PR[plan review] --> SZ{too big?}
SZ -->|yes| SP[split into issues]
SZ -->|no| RK{risk > 75?}
RK -->|yes| AP[person approves]
RK -->|no| CA
AP --> CA[claim code areas] --> IM[implement] --> TS[tests + fix loop]
TS --> RV[review 1, and 2 if risky] --> DO[docs] --> CM[commit + push]
CM --> MD[merge into develop] --> TD[tests on develop] --> RP[report]
TD -->|red| RD["give up develop, move the merge<br/>onto the feature branch, fix there"] --> MD
- Risk score 0–100 from the plan. Above 75: a person approves. Above 50: the plan is revised after review, and the code gets a second review.
- Size limit (default 15 files, 800 lines). Over it, the story is split into smaller issues; a low-risk split happens by itself.
- Develop turn (
issue-gitflow). The merge intodevelopand its test hold the@developlock (tools/area-lock) only while they run. If the tests on the merge fail,red_developreleases the lock first: the merge result is carried onto the feature branch as a merge commit (git commit-tree, parents: the feature tip and the develop tip the run merged), pushed there, and only then is the lock released.fix_developandcommit_develop_fixwork on the feature branch, which is pushed beforemerge_developruns again. A written decision (red-decision, one per tested merge commit) counts the test runs and the fixes, so a repeated step reads it instead of counting again.merge_developshows the wait asarea_lockwith the@developholder, which the UI words as "waiting for develop". The hotfix path (merge_back,fix_back) keeps the lock through its fixes: there is no feature branch to carry the fix. - Supporting flows:
epic-questions(questions up front) andrelease-daily(the daily pull request fromdeveloptomain).
Human-in-the-loop pipeline — for teams that want a person at each stage:
issue-plan (plan, person approves) → issue-code-daily (code on the day's branch) →
daily-pr (one pull request per day).
For the same plan and commit, both pipelines lock the same skills; see The skill path.
A flow that a watcher uses cannot be deleted.
9. Branches: gitflow#
gitGraph
commit id: "main"
branch develop
checkout develop
commit id: "start"
branch feature/12
commit id: "story 12"
checkout develop
merge feature/12
branch feature/13
commit id: "story 13"
checkout develop
merge feature/13
checkout main
merge develop id: "daily release"
branch hotfix
commit id: "urgent fix"
checkout main
merge hotfix
checkout develop
merge main id: "take the fix"
- Every story: a
feature/…branch fromdevelop, merged back intodevelopas soon as it is finished. The tests run on the merge result; conflicts are resolved by an agent and judged by the tests. - Once a day: one pull request from
developtomain, merged by a person. - Urgent fixes: on
main, thenmainis merged intodevelop. The hotfix path ofissue-gitflowdoes this for bug stories; it is off until an admin switches on Hotfixes. mainis protected: runs and agents cannot push to it.
10. What happens next#
One module (src/next-step.ts) turns the state of a story or run into one record: who acts
next (you, the Foundry, another story, GitHub), what they do, why, where to do it,
and since when. Everything that shows status uses that record:
- Your turn — only the items where you are next, one button each, sorted by how much work
they unblock. In the Admin view it is part of Today (
#/home; the old#/your-turnis an alias). - The board — every story of a repository in columns.
- The health chip — problems of the Foundry itself. The Health chip in the top bar of the admin display turns red on a problem and opens the health line above the page; Today lists the problems.
- Since you last looked, notifications, the status comment on GitHub, and the run page.
Rules of the module: name the root cause (if A waits for B and B waits for you, A says so);
say "nothing — it continues by itself" when that is true; use one vocabulary
(src/words.ts); explain errors as what happened, why, what you can do (src/errors.ts).

11. Accounts, roles and repositories#
- Sign-in is required for the web interface. The first account is the admin.
- Passwords. A password has 12 to 200 characters and is not on a short list of common ones
(
common-passwords.ts). An admin's reset removes the hash, ends the sessions and stores a 24-hour one-time link (only its SHA-256 is kept). Wrong tries are throttled in memory (sign-in-throttle.ts), not inusers.json: one counter per e-mail (shared by sign-in and Change password) and one per client address. A try is counted before the slow check, so tries that arrive together cannot pass the limit; it is given back when the password was right. Entries of stored accounts are never dropped for room. A restart clears waits and locks. - Two roles. An admin makes flows, watchers and settings and sees everything. A user
runs the flows an admin published, on their own repositories, and sees only their own runs —
no costs, no setup. Each role has its own display (
/for admins,/user/for users); the server still decides what a call may do. - Service accounts (#866;
src/auth/service-accounts.ts,src/server/service-requests.ts,src/server/api-service-accounts.ts). Akind: "service"record inusers.json, with roleuser, no password, link, provider source, workspace, break-glass mark or view, and the reserved e-mail<id>@service.invalid. Itsscopeholds rule keys (GET runs), at most 200.Authorization: Bearer scf_svc_…is read only on a loopback connection, before the auth routes; the public sign-in routes refuse a bearer with 403. The token is 32 random bytes. Only its SHA-256 is stored (token.id).token.usedis set on each live request, under the auth lock, and the token ends 30 days after the later ofcreatedandused(tokenExpires). A revoked or expired token is still found by its hash, so a refusal can name the account. Each bearer request writes oneservice-requestline before its handler runs, under the same lock; if the line cannot be written, the request answers 503 withRetry-After: 1. An unknown token is audited asanonymous. The scope check (serviceAllows) runs on every request, and on each recheck of an open event stream (serviceStillAllowed), so a removed route or a revoke ends the stream.NEVER_GRANTEDis checked when a scope is saved and on every request. - Data classes (#869;
src/server/data-classes.ts,dataClassOfinsrc/server/permissions.ts). Each rule has one class:inbox,summary,log,diff,adminorsecret.secretis derived fromNEVER_GRANTED, so the two cannot drift apart. The other classes are listed by rule key inCLASS_KEYS, and the inbox class is also matched by path family (changes,refinement,help). A scope entryclass:<name>is accepted for the grantable classes, only for GET rules;serviceAllowschecks it after the exact key.secretand unknown classes are refused bycheckScopeShape. A test fails when a rule has no class. - Closed repositories (
services: "none",closedToServicesinsrc/auth/repo-settings.ts).checkServiceReposinsrc/server/service-requests.tsruns afterauthorize()and again on each stream recheck. It checks, in order: the objects a request names (repoquery,runs/:id,repos/:id,admin/repos/:id, sessions), Ask Foundry (closed while any repository is closed), admin-only routes that name no object (open only for the routes inREPO_FREE), and list routes that could include a closed repository (Scheduler.repoOfandqueuedReposinsrc/queue/scheduler.tsgive the repository of a run). A refusal is a 403 with aservice-requestaudit line; a failure to read the repositories answers 500. - Published flows. An admin decides per flow which variables a user may fill in, which are shown read-only and which stay hidden.
- Repositories per user, each with its own way of signing in. Tokens are stored encrypted, with the key in the macOS Keychain; they never appear in API answers, logs or agent environments.
- Runs sign in with the repository's token.
executeStep()asksstepRepoAccess()(src/engine/repo-access.ts) when a shell step hasrepo_access(or is the old by-name refinement grant). The lookup happens when the step starts.repoTokenEnv()puts the token in the step's environment only:GH_TOKEN, an emptyghfolder, and git config entries added after the engine'score.hooksPath(an emptycredential.helper, a helper for the repository's host that prints the name and token from the environment, no extra header), https only, no prompt. A refusal ends the run (Engine.accessFailedskipson_failure). A deploy key step gets<runDir>/sign-in/(0700) withkey(0600, viasshKeyEnv()), aholdernote (pid and start time) and aghstand-in that leaves a marker and fails with a fixed sentence;repoKeyEnv()sets ssh-only git, no agent and noGH_TOKEN, and the marker fails the step after it ends, whatever the script did with the exit code. A GitHub App step asksappTokenAccess()for a fresh token limited to the repository (never cached), used like a token; a refusal after its expiry gives the one-hour sentence. A step that holds a credential runs in its own process group, killed when the step ends. The folder is removed (key first, one chmod retry, a link removed as a link) in the step'sfinally, infinish(), incancelWaitingRun(), at the start ofdrive()and bysweepSignInDirs()at server start, which keeps a folder only while its holder's pid runs with the recorded start time. Removal fails closed: a folder that stays fails the step or the resume (SIGN_IN_NOT_REMOVED). Limits: theghstand-in catchesghby name only, and a process that leaves its group is not stopped. - Runs that never use the machine's login.
stepIsolated()(src/engine/isolation.ts) is true for every run with a user owner and for an admin's run on a repository with a stored sign-in (hasStoredSignIn()), and fails closed (unknown owner, unreadable file). It is asked per step from the scope'sgithub_repo. For such a stepisolationEnv()removes every token variable (tokenVarNames(), the bot's own included), givesghan empty folder of its own,GIT_CONFIG_GLOBAL=/dev/null, no system config, no ssh agent orGIT_SSH, https and file only, no prompts,user.useConfigOnlyand a credential helper reset (appended after the engine's ownGIT_CONFIG_*entries, socore.hooksPathstays), and sets the commit name fromcommitIdentity()(bot name and e-mail from Settings, field by field, elsegetUser(owner)). With no identity the step is refused (NO_COMMIT_IDENTITY).engine.botEnv()gives the bot's token and name once per run, only to shell steps that keep the machine's login; it is fetched up front only when the flow has a shell or sub-flow step (flowUsesBot()insrc/engine/runner.ts). Agent steps (#635) never get the token, in any run:runOn(src/agents/run.ts) builds their env asbotIdentityEnv()(the bot's name and e-mail,src/engine/guards.ts), thenagent_env, thenagentNoSignInEnv(), which removes every token variable, the ssh variables andGIT_CONFIG_PARAMETERS, sets an emptyghfolder, no prompts,GIT_ALLOW_PROTOCOL=fileand a credential helper reset.agentNoSignInEnv()leavesGIT_CONFIG_GLOBALalone, so an admin's agent on the machine's HOME keeps the machine's global git config. An isolated step addsisolationEnv()on top, withfilereplacinghttps:file. The clean Codex folder of an admin run addsGIT_ALLOW_PROTOCOL=fileon top ofnoMachineSignIn()(src/agents/codex-home.ts).nextConfigIndex()picks the index of the appendedGIT_CONFIG_*entries: a badGIT_CONFIG_COUNTfromagent_envis replaced by the number of contiguous keys, so the helper reset is always read. The broker's credential ceiling forrepo_opsisrepoCredentialin the tool profile (machineorrepository); the agent's owncredentialisnone. This is the environment only, the same limit as above: in an admin run without an OS sandbox an agent can still reach the machine's keychain or~/.config/gh. In agent stepsagentEnv(spec, true)ignoresISOLATED_AGENT_ENVnames, Claude agents are always isolated (--strict-mcp-config), and a token variable is never an anthropic-compatible provider key. Since #304 and #305 a user's run is also held by an OS sandbox profile (os-sandbox.ts); its agent steps get their own agent folders in the run folder and sign in by a token variable only (src/agents/boxed.ts). - Codex sessions belong to a Codex folder. Each Codex step records
codexHome(codex_homeinstate.stepsand in the template context):runfor the run's own folder, orpersonal:plus 12 hex digits of the path (never the path).codexHomeId()andcodexResumeRefusal()are insrc/agents/codex-home.ts. A step withresume:starts a new session, and logs why, when the recorded folder differs from its own or none was recorded (a record from before #420), so it never asks Codex for a session that folder does not hold. - Codex isolation (#421).
codexIsolationMode()picksprivate(a local model or aCODEX_API_KEYthe step sees:CODEX_HOME=<runDir>/home/.codex, made 0700 byprivateCodexHome(); a failure refuses the step),ignore-config(a Codex login:--ignore-user-config) oroff. Boxed steps get no mode.codexExecFlags()probescodex exec --helporexec resume --helpper command form (cached 10 min); a CLI without the flag turnsignore-configintounsupported: no flag, a!log line, the step runs. The Foundry assumes this CLI contract: the flag skipsconfig.tomlonly, the sign-in stays inCODEX_HOME, and rules are separate (--ignore-rulesis never passed).fake-codex.mjsmodels exactly this. Not yet checked on a real CLI: whetherexec resumelists the flag, and whether a privateCODEX_HOMEhides personal skills kept outside it. The skill payload path (skillSession(),withSkillPayload(),skillsRecord()) is shared by both agents (#422): a lock with skills forces Codex isolation, andunsupportedrefuses it. Limits: macOS only, andsandbox-execis deprecated; the token is visible to the agent's shell tool; the lock and hooks folders can be read; a Codex read-only step is held by the outer profile only; Docker steps are held by the container; withsandbox.user_runs: offnothing is held; the push hook does not run in a Docker step. - Evaluation limits (#534).
src/engine/eval-limits.tsholds one process-wide limit, unset by default, that a later evaluation command sets for untrusted skills. It adds three things to every sandboxed step: outbound TCP only to*:<port>orlocalhost:<port>entries (the profile deniesremote ip "*:*", then allows eachremote tcpentry);denyReadfolders denied before every allow exception (made real withdeepReal); and, for a Claude agent,--toolswith only the allowed tools,disableAllHooks, and strict MCP and setting sources. Only the port is filtered because Seatbelt accepts only*orlocalhostas the host, so a host name is refused. Limit: the tests check the profile text and the arguments, not Seatbelt or Claude Code's enforcement. - Permissions are enforced on the server. Every API route has a rule in
src/server/permissions.ts, and a test fails when a route has none. - Blocking an account signs it out at once, optionally stopping its work.
- An audit log records sign-ins, account changes and what signed-in people do in the web interface. Lines older than
audit.retention_days(default 180) are removed by the server, in a chunked scan underauth.lock.
12. Safety#
| Risk | Measure |
|---|---|
An agent pushes to main | Protected branches: git pushes to them are refused during runs |
| A secret is pushed | A secret scan blocks the push |
| A change touches things it should not | forbidden_paths, and a guard step after coding |
| A risky plan is built unseen | The risk gate: a person approves above the threshold |
| Runaway cost or loops | Budgets per run and per day (optional), max_visits, timeouts |
| Commands with text from an issue | Issue text and step output travel as environment variables only |
| A reviewer changes code | Reviewers get read-only tools |
| Untrusted test commands | Optional sandbox: Claude Code's sandbox or Docker |
| An untrusted skill is evaluated | Evaluation limits (eval-limits.ts): outbound TCP to listed ports only, listed folders unreadable, and a Claude agent with only the listed tools and no hooks |
| A candidate skill's scenarios run an agent | score --agent (src/skill-eval/): each arm in its own temporary data folder, a user's run (no GitHub token, empty gh folder, strict MCP, short environment, only the model key), the evaluation limit, and cleanup on every exit; the outbound network is limited to a port, not a host |
| A run acts with the admin's GitHub login | User runs, and admin runs on a repository with a stored sign-in, get no token, an empty gh folder, no machine git settings or ssh, and the bot or owner's commit name; environment only, not an OS sandbox |
| An admin looks at a user's display unseen, or changes things through it | "View as user": an audit line (view-as) per start, written first (no line, no view); as= only on GET, only with a running view for that user, answered by the user's own rules and cut-down views; views in memory only, 30 minutes, keyed by a hash of the session, never the token |
| Someone reads another person's Ask Foundry conversation | Conversations are read and changed by their owner only; another account's id answers like an unknown one, an admin has no extra access, and "View as user" shows none |
| The help assistant is talked into doing something | A help turn has no tools, no MCP servers and no token; the server keeps only checked text and fixed pages from its answer, and the only actions are the server's two, and each is bound to a run the asker owns |
| Someone else on the network | Listens on this machine only, unless set otherwise |
| Private data in a public place | Paths and titles are filtered from what leaves the server unasked |
13. Data on disk#
Everything is in the data folder (~/.spaghetti-code-foundry):
| File or folder | Content |
|---|---|
config.yaml | Settings and watchers |
runs/<run-id>/ | run.json, step logs, transcripts, the workspace, evidence.jsonl (the events of the run), evidence.json (the manifest of a run that ended), evidence.diff, evidence.incomplete (a mark: the events are not whole) |
workspaces/<id>/runs/<run-id>/ | The runs of a workspace other than default, same layout as runs/ (#824) |
queue.json | Queued jobs |
locks/ | Code-area and run locks (default) |
workspaces/<id>/locks/ | Code-area and run locks of a workspace other than default (#824) |
workspaces/<id>/skills/ | The administrator skills of a workspace other than default (#825); skills/ in the data folder is the one of default |
users.json, sessions.json | Accounts and sign-in sessions |
notifications.json | What was already notified |
feed.json | The change feed (#868, version: 1): the last seq, the floor below which a cursor gets reset, the snapshot of the fingerprints of runs, repositories, change requests and Your-turn items (kind, id, owner, workspace; no detail), and the kept changes. Written with a temporary file and a rename, mode 0600 (src/server/feed.ts) |
notices.json | The notices for programs (#871, version: 1): the last seq, the floor below which a cursor gets reset, and the notices of the last 7 days (kind, title, text, item key, run id, link, and ref, a sha256 of the source so one thing is never stored twice). Title, text and link are redacted when stored. Written with a temporary file and a rename, mode 0600 (src/notices.ts, src/server/notices.ts) |
metrics-share.json | The metrics push (#889, version: 1): the random install id, the endpoint it was posted to, activeSince, posted, the day entries (accepted time, tries, next try; newest 7 days), the deletes still to send, and the last answer of the receiver. Written with a temporary file and a rename, mode 0600; a broken file is never overwritten (src/metrics-share/state.ts) |
metrics-share.lock | The lock of the push, held by the server's tick and by scf metrics send. Never waited for; a lock not renewed for longer than the timeout plus 60 s is taken over (withShareLock) |
help.json | The Ask Foundry conversations of every account (mode 0600) |
help-stats.json | The Ask Foundry quality numbers: one row per UTC day of counts and latency buckets, no account or text (src/help/telemetry.ts) |
telemetry/ | events-YYYY-MM-DD.jsonl, one value-free lifecycle event per line per UTC day (0700 folder, 0600 files); old days are removed after telemetry.keep_days (src/telemetry/) |
red-base.json | The red base branch state (version: 1): per repository and branch, the failing tests of the red commit, the prior commits, the fix story and a pending entry. Written in one synchronous step with a rename, so another repository's entry is kept; a broken file reads as no state (src/red-base.ts) |
ci-watch.json | The GitHub CI state (version: 1), keyed by repository: per workflow the red branches, the streak's first run, the branches a story names, the story (or a pending create or a closing entry), the time of the last read and any problem. Written in one synchronous step with a temporary file and a rename, so another repository's entry is kept; a file that cannot be read stops the check and is never overwritten (src/ci-watch.ts) |
issue-states/ | One file per watched repository: open or closed for each issue with an unfinished run |
issue-lists/ | One file per watched repository: the last full issue list read by the watchers (number, title, state, labels, links, dependencies; no issue text), with readAt and cut. Written atomically; removed when no watcher is left for the repository |
self-update.json | The self-update record: pending (an install not confirmed yet), tested, retry (a staging failure waiting for the next try: commit, tries, time, and the optional stage (setup, install, build or test; no stage means the tests of older records) and mixed), failed (with tries and the failing tests after the last try, the optional setup and mixed flags), updated, reports (up to 20 commits given up after three tries with the last one failing in the tests, each kept until its bug story exists, with mixed, errors, nextAt and the story once filed) |
flows/ | Your own flows (repository flows live in <repo>/.claude-factory/flows) |
A save of config.yaml edits the file text in place (src/config-edit.ts, editConfigText in src/config.ts): comments and key order stay, only the changed keys are written, and the result is parsed again before it is written. The settings and watcher reads send X-Config-Version, the sha256 of the file text; a PUT /api/config with a stale version gets 409.
The audit lines of a save come from the diff of the parsed configs before and after (configChanges in src/auth/audit-changes.ts): one line per changed leaf, with the watchers matched by id. MASKED_KEYS there is the one list of settings that say only "changed"; a value is rendered and cut to 80 characters. auditActions (src/auth/audit.ts) writes all lines of one save under one lock. The Slack webhook never leaves the server: configView (src/server/config-view.ts) answers notify.slack_webhook_set, and withStoredWebhook keeps the stored value when a save leaves the key out.
Run ids are timestamps, so folders sort by time. Old workspaces are removed by scf clean.
Sharing answer (#887)#
Each person account has metricsSharing: { answer, changed } in users.json; no field means unasked, and
a service account never has one (the file fails to load if it does). setMetricsSharing (users.ts) opens the
audit log before it writes and adds one settings-change line; the same answer writes nothing. The admin
setting metrics_sharing.allowed is audited like the other settings, but a save of it fails when the log
cannot be written (api-admin.ts). sharingAnswer and sharingAccounts() (metrics-share/sources.ts) are
the only readers: sharing off or an unreadable config.yaml means no account counts. The UI keeps one store
(ui/metrics-sharing.js) for the Today item and the Account settings switch.
Shared metrics (#893)#
src/metrics-share/ builds the daily report. The server pushes it (see the push below) and
scf metrics preview prints it; nothing else sends it.
- Pure builder.
shareReportFrom(build.ts) turns the inputs into a report and reads no files.buildShareReport(day, accountIds, deps)(sources.ts) reads the runs, the outcome measures (src/outcomes.ts,issueToPrTimes), theissue.splitusage events and the watcher sources (config.yamlandrepo-watchers.json, aconfig.yamlid wins). Each run is reduced on its own to a few facts; the trimmedrun.jsoncopy holds no task, step output, paths or answers. - Schema.
report.tshas a zod schema with.strict()on every object and aversion. It has no free text. Flow, step and model names are kept only from fixed lists (built-in flows and steps, known models); anything else iscustom, and a step with no model isdefault. A test checks the lists againstflows/*.yaml, the price table and the watcher sources. - Owner rule. Only runs owned by the given accounts count. A run without an owner, a refinement run and a local test never count. Runs started count by start time; splits and question stops by their own time.
- Absent versus zero. A measure with no source is left out of the report. A
0means the evidence was readable and recorded none. - Evidence limits. Evidence files are read with a size limit and never through a link. An oversized, linked or unreadable file adds nothing.
- Install id. Placeholder (32 zeros,
NO_INSTALL) while the install has no stored id; the preview uses the stored one (peekInstall) once the push has one.
Push to the receiver (#889)#
The server sends the report; nothing connects to the install. Three modules, and one network call.
- The one call.
push.tsusesnode:http/node:httpswithagent: false(no connection reuse).fetchis not used because it adds headers of its own. The headers areUser-Agent: spaghetti-code-foundry/<version>,Content-Type(POST only),Content-LengthandConnection: close; no cookie, no redirect. A redirect is an answer, not followed. Of the answer only the status andretry_after(an integer from 1 to 86400 in a JSON body of at most 4 KB) are read; a 2xx is final on its status, and the body is not read. The exchange has one timeout, can be aborted, and never rejects.isShareEndpoint(config.ts) is checked before every request. - The state.
metrics-share.json, see section 13. Each step that matters is saved before the next one: a stop, a new install id and an endpoint change go to disk before any DELETE or POST of that id. A state that cannot be saved is kept in memory aspendingand nothing more is sent until it is saved. - Pure decisions.
reconcile(pusher.ts) turns the state, whether sharing is active and the endpoint into the next state, with no I/O apart from new ids.dueDayslists the days from today − 7 to yesterday that are not accepted, due, and from the start of sharing (or with a stored try).pruneDaysdrops entries and deletes older than 7 days.retryWaitMsgives 15 min doubling to 24 h, and a longerretry_afterwins.pushOnebuilds the report, checks consent again right before the send, sends, and records the answer. - The tick.
metricsPusherruns once a minute (start, timer unref'd;FACTORY_NO_METRICS_PUSH=1turns it off, andtests/setup.tssets it). A tick reads the settings andusers.json; if either cannot be read the tick ends, so an unreadable file is never a yes or a no. It takes the lock, sends the deletes that are due, then the days. A tick that is still running is not started again. One failure per run of failures is logged with the fixed words inMETRICS_PUSH_WORDS; the state of the failure is only in memory, so a restart logs once more. - Deletes. A stop after a POST adds
{ install, endpoint, since, tries, nextAt }todeletes(at most 100; a full list defers the stop,deferred) and then gives a new install id. The delete goes to the endpoint that got the POSTs, not to the one in the settings now. A delete that is not accepted is retried on the same schedule as a day, and dropped after 7 days. - Lock.
withShareLockcreatesmetrics-share.lockwithwx(mode 0600) and holds it while it works; the holder renews its time every 10 s, so a long send is never taken over. A lock older than the stale time is removed and taken over; a lock whose token changed is left alone. Nothing waits for it: a busy lock is a skipped tick, orSEND_BUSYfor the command. - The command.
scf metrics send(cli.ts) runs the samereconcileandpushOneunder the same lock, and reads the settings and the accounts again before the send. It refuses today, a day over 7 days old, a day already accepted and a run with nobody sharing, before anything is sent. It does not start a server. It sends only the one day it was given and no DELETE: a stop it records is sent by the server's next tick.
14. The server and its restarts#
One process serves the web interface, runs the queue and the watchers. A supervisor notices a
new build and restarts the server — but only when no run is active. Until then it starts no new
runs and tells the user why (Scheduler.drain() stops queued jobs from starting; they stay in
queue.json for the new server). Runs that were interrupted continue after the restart.
Self-update. With self_update on, the server (SelfUpdater) is the one that decides: it
checks main of the named repository, builds and tests the new commit in a git worktree, and when
the active runs are done installs that exact commit in place (git merge --ff-only, npm ci if
the lock file changed, npm run build). It writes a journal first (self-update.json, pending
with phase apply, then installed with the build stamp) and exits with the restart code. The
supervisor's own code is versioned by supervisorCode() (src/supervise.ts: a hash over the built
files in SUPERVISOR_FILES). After an update that changed it, the server asks for one more restart
(restartForNewSupervisor), and the running supervisor (selfRestart() in src/self-update-state.ts
decides when it may) starts the new one as a child with the FACTORY_SUPERVISOR_RELAY marker. The
child says ready over IPC and waits for go; the parent then only waits for it, so the pid stays.
A child that is not ready in 30 seconds, or ends early, is stopped and the parent keeps running (exit
code 76 asks the original for a further renewal). The startup code is in src/supervisor-start.ts,
so changes to it count as supervisor changes. The
supervisor guards the first start after an install: it reads the journal, finishes going back
when an install was cut off, and puts the previous commit back once when the server stops or
does not confirm in time. The new server confirms with GET /api/ready (loopback only) after it
checked that HEAD and its build stamp are those of the install. confirmStart asks every 5 s until
the probe answers or 600 s (MAX_HEALTH_MS, the longest the supervisor waits) have passed; with a
guarding supervisor it also waits while the record cannot be read. Under that supervisor the server
holds its work (holdStart: no queued run, no watcher) while the record shows the installed phase,
and releases it only when the start is confirmed or nothing is left to confirm (confirmHeldStart,
releaseStartHold); the 60 s limit of the afterListen wait does not end this hold. The supervisor
reads an unreadable record as "unknown" (StartGuard.pending), not as healthy, and keeps watching;
once it can be read again, at least GRACE_MS (30 s) is left. Before the server confirms, and before
the supervisor stops it for a timeout, each takes the exclusive claim file
self-update.json.claim-<to>-<stamp> (src/self-update-claim.ts, claimStart); only one wins. A failed go-back is a terminal
state (failed.backOk = false) that a person must repair. The monitor reads the same file.
Progress while starting (#1111). Under the guarding supervisor the child gets an IPC channel (stdio with ipc). The server (startProgress in src/start-progress.ts, called from src/cli.ts) sends {type:"stage", stage} at each start-up stage (boot, skills, plugins, sweep, sign-in, index, watchers, listen, confirm; the server calls onStartStage), and {type:"beat"} every 5 s until the start is over. A beat comes from a timer, so a start that blocks the event loop sends none. supervise() reads the messages with progressOf (anything else counts for nothing, and the stage is checked by its form, so a newer server works under an older supervisor). It keeps only the time of the last valid message and the last stage name. Once a message has come, the start is judged by two limits, not by healthMs: a timeout when no message has come for StartGuard.stallMs (STALL_MS, 90 s), or when the total wait passes maxHealthMs (MAX_HEALTH_MS, 600 s). A message after the total limit does not save the start. A server that sends no progress keeps the fixed wait (healthMs, stretched by the load as before). The log names the stage the new version reached when it is stopped. RESTART_CODE and RENEW_CODE are unchanged. The release check (release-daily verify) writes tested-v2/<key> (the folder TESTED_DIR in src/self-update-tests.ts; the old tested/ is no longer read), with key = printf '%s\n%s\n' <tree> <cmd> | shasum | cut -c1-40, as the one line run <id>, <UTC time>, tree <sha> only for a green run on a clean tree whose HEAD^{tree} did not change; self-update skips its test step only when the staged commit's tree matches that exact line form and the record's command passes judgeTestCmd (src/self-update-tests.ts): the updater's own step (alone or after npm ci && ), or the project's configured test command (watcher test_cmd or .claude-factory/config.yaml) that runs that step once, joined only with an install or a build. releaseRecord gives the reason when it runs the tests. The release check also writes the record when it reuses a passed story result (the record names the original run), and every step gets the folder as FACTORY_TESTED_DIR.
Warm-up start (#1110, part 1 of #1014). scf ui or scf serve started with FACTORY_WARM_UP=1
and a message channel (process.send) first loads its config and plugins, builds the run index and
listens on its port, writing nothing to the data folder. It starts no runs, scheduler pump, watchers,
timers, services or heartbeat. While warming, /api/ready answers, plugin routes and every other API
route answer 503 with "the server is starting". Over the channel it sends { type: "stage", stage }
(config, plugins, index, listening) and then { type: "ready" } (src/server/warm-up.ts, the
messages only). FACTORY_WARM_UP and its SCF_ copy are read once in cli.ts and removed from the
environment before any child starts. The writes and timers of a start are grouped in start()
(src/server/server.ts) and called in the same order as before. On { type: "go", port } the server
closes the warm-up listener, reads config, queue and run index again (scheduler.reload() only while
the queue is held), listens on port and then does the skipped start-up work (begin()). Afterwards it
is the same as a normal start. A channel that closes before go ends the process with exit code 0
and nothing written. A data folder that still needs a move or repair (dataHomePending(), src/home.ts)
makes a warm-up refuse with an error, since only a normal start may move it. Warm-up is off by default;
the supervisor side that sends go is part 2 of #1014.
Side-by-side start (#1112, part 3 of #1014). A restart for a new version no longer exits first when a supervisor can start the new version beside the old one. The server (src/restart-handover.ts, createRestartHandover) drains (no new runs; the updater is stopped and the restart is held) and sends { type: "handover" } over the channel. The supervisor (src/supervise-side-by-side.ts, called from restartOnNewBuild in src/supervise.ts) first reads WARM_UP_VERSION from dist/server/warm-up.js as text (warmUpSupported, never loading new code). Without the marker it does today's stop-and-start. With it, it binds port 0 to pick a free port (freePort), starts the new build with FACTORY_WARM_UP=1 and the same data folder, and judges it with the progress rules of #1111 (warmUpOverdue: 5 s allowed before any progress, 90 s of silence, 10 minutes in all). When the new version starts, it tells the old server { type: "warming" }. On ready it sends the old server { type: "stop" }. Before it stops a failed new version, it sends the old server { type: "cancel" } and waits up to 10 s for { type: "cancelled" }, so a stop that was already under way is undone first. The old server answers only at a safe moment: uncuttableRuns is empty, updater.busy() is false, and no other restart holds it (blocked in src/safe-restart.ts). It then runs beforeExit and exits. Only then does the supervisor send { type: "go", port } to the new server, which takes the port and does its normal start-up work. An older supervisor never answers the handover; the server then waits 5 s (answerMs) and exits with RESTART_CODE, as before. Failure: the new version exits, stalls, or passes its limit before ready; it is stopped, the supervisor sends { type: "stay" }, and the old server leaves its drain and keeps serving on its port (onStay). The attempt is recorded as a failed start in self-update.json, so the calm-machine retry and "second failure blocks" rules of #1010 apply. The checkout is put back without changing files the running server loads lazily: the server loads its lazy modules before the updater starts, so a later await import(...) does not read new files. After ready only an exit or silence counts as failure; a long push or release step does not fail the update. If a put-back or the failure record cannot be written, the server reports updates: false: nothing more is installed until a person restarts the Foundry (refused in src/safe-restart.ts makes later health restarts wait rather than drain the queue). Tests: tests/supervise-side-by-side.test.ts (fake children and a real build of the handover code under supervise()), tests/side-by-side-protocol.test.ts, tests/restart-handover.test.ts.
The change feed (#868). FeedRecorder (src/server/feed.ts) takes a snapshot of what exists every 5 seconds (feedTickMs), 20 ms after a run ends (kick), and before an answer when the last snapshot is over a second old (fresh). A snapshot holds, per object, a fingerprint and its sides (owner, workspace, and for a change request the workspace of its architect run). diffFeed (src/feed.ts) compares it with the last one and appends one record per added, changed or removed object, with its kind, id, time, and the sides before and after. The record never holds detail. A kind whose source throws keeps its old entries, so a failed read records no false removals. Records are pruned to the last 24 hours and the newest 10,000, never above 20,000; a pruned record moves floor up, and a cursor below floor gets reset.
Visibility is decided when the answer is made, not when the change is recorded: feedAnswer shows a record when one of its sides is visible to the caller (sideVisible), and drops an object that still exists but is no longer readable. Turn items are the exception: their id is opaque, so their records keep the owner they left, and the owner learns the item is gone. A service account sees a kind only when its scope holds that kind's read route (KIND_ROUTE).
The long poll (wait, at most 30 s) is held in memory: a waiter is woken when a snapshot records something, and the caller's identity and scope are read again before each answer, so a revoked scope or a removed workspace does not leak a change. The response ends when the client closes.
Restarts. The state is saved in feed.json, so the sequence goes on after a restart. The Your-turn source is not trusted right after a start: the watchers have not looked yet, so the turn kind is left out of the snapshot until every watcher has checked once or two minutes have passed (SETTLE_MS). A feed.json from a newer version is read only and the feed runs in memory. A broken file starts a new feed with reset.
Notices for programs (#871). TurnNotifier (src/server/notifier.ts) hands each notice to NoticeLog (src/server/notices.ts) through its record callback, before it sends a macOS or Slack notice. One notice is made per fresh Your-turn item (turn, with the text of that item alone), per succeeded run when success notices are on (done) and per daily summary (summary). The ref (a sha256 of the item key and its stamp, of the run id, or of the summary day) keeps one thing from being stored twice. When the save fails, nothing is marked as told and the next check tries again; with a channel the send waits for the save. The notifier also runs with no channel, so the notices exist for programs alone. FACTORY_NO_NOTIFY=1 turns the whole notifier off. Title, text and link go through redactText (src/credentials/redact.ts) when they are stored. The link is the public base URL (appBase) when it is set. src/notices.ts holds the record format, appendNotices, pruneNotices (7 days; the floor moves up with each dropped notice) and noticesAnswer, which is the same cursor rule as the change feed. The long poll is the one of the feed: held in memory, woken by record, and the caller's identity and scope are read again before each answer. A stop releases every waiter at once. A notices.json from a newer version is read only.
Managed services (#867). ServiceSupervisor (src/services/supervisor.ts) starts the
services: of config.yaml in start(), after the server listens and the watchers are synced
(src/server/server.ts). Before each start it checks the program (programProblem: absolute path
already checked at load, real path a file, executable, not inside a runs or workspaces folder; with
public_key the detached Ed25519 signature of <command>.sig, signatureProblem). A failed check puts the
service in state refused with a fixed sentence; a program that exits goes to waiting. Both are
retried with nextDelay (1 s, doubling, at most 5 min; a run of stableMs resets the count). The
program is started detached in its own process group with spawn and an argument array, never a shell.
Its environment is a fixed list of system variables, the configured env, SCF_URL and a fresh
SCF_SERVICE_TOKEN from serviceToken() (a managed service account in services-accounts.json, next to
users.json; the token is rotated on each start). reconcileServiceTokens() revokes what an earlier run
left. Output goes through redactStream with the token and the env values to ServiceLog
(src/services/log.ts, <name>.log, one .1 file, 5 MB). Stop has two forms: stop() (async, on
shutdown) and stopNow() (synchronous, from withServicesStopped before a self-update or other
restart exit). The health answer carries services from view(), and scf services reads
GET /api/health.
15. The web interface#
Plain JavaScript modules, no build step, no framework.
The shell. Every page sits in one frame (ui/index.html and ui/user/index.html, wired by initShell in ui/shell.js):
- Top bar: the brand, the page title, then Search (the command palette,
ui/palette.js, Ctrl+K or Cmd+K), Ask Foundry (the Ask Foundry drawer, only when Ask Foundry is on), + New change (#/start,NEW_CHANGEinui/ia.js) and, in the admin display, the Health chip. The account menu holds the name, Appearance (theme, density and look,ui/prefs.js), View (Simple, Advanced, Admin;mountViewSwitchinui/view-mode.js) and Accessibility. - Sidebar: the repository switcher at the top (
#context,ui/context.js; "All repositories" or one repository), then the five places every view shows (SIDEBAR_MAIN): Today (#/home), Changes (#/runs), Ideas (#/refinement), Releases (#/epics) and Help (#/help). Below a divider come the extra pages of the view (SIDEBAR_EXTRA): none in Simple; My repositories in Advanced; Board, Repositories, Flows and Administration (#/operations) in Admin. The links are static in the two HTML files;showViewNavhides the divider and the extra pages (data-extra) in Simple, andui/shell.jsmarks the current link witharia-current. On a narrow screen the sidebar is a drawer opened with the menu button. - Secondary row and breadcrumb:
subnavForandresolveofui/ia.jsstill work on the destinations below. Administration has three labelled sections (SECTIONS): Operations (Overview, Problems, Watchers, Models, Dashboard), People and access (Users, All repositories, Credentials, Audit, Autonomy) and System (Settings, Maintenance).
Destinations. DESTINATIONS in ui/ia.js group the pages for the secondary row, the breadcrumb, and the active sidebar link. Their labels are the breadcrumb names, not the sidebar names. Those of the admin display:
| Place | Pages | Purpose |
|---|---|---|
| Home | — | What waits for you, what is running, what finished |
| Board | — | Where every story is |
| Epics | — | How far each epic is and its expected finish |
| Refinement | — | From a rough idea to a story |
| Runs | — | Every run, live log, steps and transcripts, changes |
| Repositories | — | Repositories and how the Foundry signs in |
| Flows | Flows, Library | Edit and create flows; reusable blocks |
| Administration | Overview, Problems, Watchers, Models, Dashboard, Users, All repositories, Credentials, Audit, Autonomy, Settings, Maintenance | Findings of the monitor, automation from GitHub, routing, cost, accounts, all repositories and credentials, audit log, autonomy levels with their gate and history, settings, workspace clean-up |
User display: destinations Home, Epics, My runs, My repositories, Refinement; Start work is the action page (#/start). The source is ui/ia.js. In the sidebar they appear as Today, Releases, Changes, My repositories and Ideas, and the action as + New change.

Two displays. The admin page is ui/index.html with ui/app.js (the router; the flow editor page is ui/flow-page.js, made by createFlowPage, with its header and navigator in ui/flow-shell.js and its pure state in ui/flow-state.js); the user display is ui/user/index.html with ui/user/app.js, served at /user/ and /user. The user script imports only shared modules by absolute path (/auth.js, /dom.js, /runs.js, /repos.js, /refinement.js) and its own /user/start.js and /user/runs.js (it no longer imports /runs.js directly; that module is reached through /user/runs.js), and no admin module; a test checks this. ui/user/runs.js draws the Changes list of a user (#/runs: cards, queue, Remove) and the run page of a user (Now, Log, Steps, Changes, and the Approve/Reject dialog, Retry and Cancel); it reuses the helpers of ui/runs.js and ui/next.js and draws only the server's cut-down view. ui/user/start.js (the + New change page, #/start) imports relatively (../api.js, ../auth.js, ../dom.js, ../repos.js) so a test can load it; in the browser these are the same module instances as the absolute ones. Both entries call enterDisplay in ui/auth.js: it signs in, and an account is sent to the display of its view in effect (viewOf in ui/view-mode.js) before any page is drawn: Admin is the page at /, Simple and Advanced are the user display. Simple is the user display with fewer links (showViewNav keeps the five sidebar places and + New change, SIMPLE_NAV) and pages of its own (SIMPLE_SECTIONS): ui/simple.js draws Today with My projects (#/home; the Today part is laid out by ui/simple-home.js after the person's look), the project page (#/repos/<id>) and Help, from the lists of GET /api/repos, /api/runs and /api/queue, grouped by ui/simple-model.js, with every word from ui/simple-words.js; ui/simple-change.js draws one change (#/change/<id>). A page the view does not have shows the card "This page is not in the Simple view." with Open this in the Advanced view (offerFor and offerCard in ui/view-mode.js); the address stays. The view switch is the View select in the account menu of both displays (mountViewSwitch), except in a preview. The redirect is in the browser and is for comfort only; the server enforces permissions on every call, and the scripts are plain static files.
Dialogs (modal() in ui/dom.js) take the focus, keep Tab inside, close once on Escape and give the focus back to the opener. mount() keeps the focus on the control with the same data-focus name when a page draws itself again.
Breakpoints and touch targets#
Breakpoints are named by layout need. ui/viewport.js is the one place in code (BREAKPOINTS = { compact: 767, medium: 1023 }, mediaFor(name); initShell and renderWork take their default media from it). Media queries cannot use custom properties, so the CSS repeats the numbers; tests/ui-viewport.test.ts fails when a max-width or min-width in ui/ is not one of the values below.
| Name | Width | Layout |
|---|---|---|
| compact | below 768 px (max-width: 767px) | drawer navigation, one column, dialogs as bottom sheets, cards |
| medium | 768–1023 px | sidebar, one content column |
| wide | 1024 px and up | full layout |
The existing max-width: 1100px rule stays as "two panes side by side".
Touch targets. --size-touch (44 px) and --size-touch-min (24 px) are in ui/tokens.css. On coarse pointers buttons, .btn links, form inputs and selects, summary, sidebar and sub-navigation links, table row actions and the dialog close button are at least 44 × 44 px, with at least 8 px between neighbours. On fine pointers the minimum is 24 × 24 px.
Sheets and wrapping. Below 768 px a dialog (.modal, and the kit's .scf-dialog) is a bottom sheet: full width, fixed to the bottom, at most 90 % of the viewport height, scrolling inside, with a sticky head so the close button stays reachable. This is CSS only; modal() is unchanged, so the focus trap and Escape work as before. .toolbar actions wrap below the title. .log, pre.diff and long names scroll or wrap inside their own box, so the page never scrolls sideways at 360 px.
The rules for these live in ui/css/responsive.css (imported last by ui/style.css); width rules that belong to one component stay next to their base rules.
Support levels. supportLevel(pageId, width) in ui/viewport.js maps a page id from ui/ia.js to "full" or "read-only": administration pages are read-only at 767 px and below (BREAKPOINTS.compact), flows, flow and new-flow at 1023 px and below (BREAKPOINTS.medium); everything else, an unknown id and a missing or NaN width are "full". levelNotice(pageId, { dirty }) returns the notice text or null. In ui/app.js, route() fills the single #level-note element above #main and passes readOnly to the renderers; NOT_YET lists the pages not wired yet (they stay full, with no notice); flows, flow and new-flow are wired (read-only at 1023 px and below), while the repositories, models, problems and maintenance pages are still in it. The flow page asks isReadOnly (from supportLevel("flow", innerWidth)) at the moment of every change, so save, remove, newBlank, generateDialog and the late Retry callbacks do nothing once the window is narrow. markDrawn(to) records the drawn page and its notice. The flow list in the sidebar has its own check in onWidth: it redraws whenever 1024 px is crossed and the destination is flows, also on the Library page. The width is read from globalThis.innerWidth; the listeners are on mediaFor("compact") and mediaFor("wide"), and a change redraws only if the level of the drawn page changed. While #modal-root holds a dialog the crossing is remembered, and a MutationObserver on #modal-root redraws once it is empty. lockReadOnly(root) in ui/fields.js makes the controls under root read-only: inputs and textareas get readOnly, selects and checkboxes are disabled, buttons are removed. There is no blanket disabled fieldset, so text can still be focused and scrolled. renderUsers, renderUserDetail and renderSettings take a readOnly option and pass it on when they redraw themselves. operations, watchers and watcher have left NOT_YET: renderOperations, renderWatchers and renderWatcherDetail take readOnly too (also in their reload). Read-only leaves out "Cancel run" (renderHealth); the add buttons, Check now, Edit, Enable/Disable, Delete and the bug-stories switch (ui/watchers.js, storiesRow); and the mute row, the Actions column and "End mute" (monitorLists, mutesTable in ui/monitor.js). The header health panel and the Problems page do not pass it.
Development gallery#
scf ui --dev and scf serve --dev set ServerOptions.dev. With it, the static branch in src/server/server.ts serves ui/gallery/ (/gallery and /gallery/ map to gallery/index.html, like /user). Without it, isGalleryPath (src/server/http.ts) catches every spelling of a path under /gallery (.., \, case) and the server answers 404 before serveStatic. The switch is on the command line only. The gallery is plain static files under the existing CSP, adds no API route and so needs no rule in permissions.ts. See docs/UI_COMPONENTS.md.
UI styles#
ui/style.css is only a list of @import url("/css/…") lines. The rules live in small modules under ui/css/. There is no build step: the browser follows the imports. /css/… is served like /style.css (static, no sign-in, text/css), and the CSP allows same-origin @import. ui/index.html and ui/user/index.html run /prefs-boot.js first (it sets data-theme, data-density and data-look on <html> from the stored choice, so the page does not flash), then link /tokens.css (the token values), /looks.css (the looks), /style.css and /kit/kit.css.
Modules and who owns what. Every module starts with a comment that says what belongs in it and what does not.
| File | Owns |
|---|---|
tokens.css | Only a pointer: the custom properties (colours, type, spacing, density, the --layer-* scale, --size-form) are in ui/tokens.css, which is linked before /style.css. No selectors. |
reset.css | Bare elements: body, headings, links, code, pre, details. .mono stays here because it shares the code, pre, .mono rule. |
layout.css | The page frame and the run grid: body, .layout, aside, main, .run-grid, and how they collapse on narrow screens. |
templates.css | The page templates: .page, the eight .page-<name> roots and their regions, and grids scoped under a template root (.page-overview .dash-grid, and the editor grid under .page-editor). No component rules, no z-index. |
components.css | Controls and boxes used on more than one page: buttons, inputs, .field, .pill, .badge, .card, .table, .table-box, .modal, .backdrop, #toast, .seg, .tabs, .chips, .spinner, .empty, .errors, focus rules, and the toolbar and status helpers. Every variant of a component lives here too, such as .pill.who-you, .card.failure, .table.compact and .modal:has(.block-grid), even when only one page uses it. |
utilities.css | One-purpose helpers: .row, .grid, .spacer, .muted, and the classes listed under "Utility classes" below. |
pages/*.css | One file per page area: shell (top bar, health, subnav, sidebar, view bar, user display), editor, runs, dashboard, turn (holds, next step, Your turn, help), board, start, refinement, gallery, work, simple (the Simple view). ask is the Ask Foundry drawer. |
Page templates. ui/templates.js has eight templates: overviewPage, collectionPage, boardPage, masterDetailPage, editorPage, settingsPage, conversationPage and detailPage. Each returns div.page.page-<name> (overview, collection, board, master-detail, editor, settings, conversation, detail). The module imports only ./dom.js and ./kit/product.js; it has no api, fetch( or style.
- Head. The options
title,back,statusandactionsgo topageHeader({ layout: "toolbar", title, back, meta: status, actions }), so there is one header component. Alternativelyheadis a ready node (the first child, noh1is made);headwithtitlethrows.noticescomes right after the head. - Regions. Plain
divs in a fixed order, with no grid and no gap, so margins collapse as before. An empty slot (null,false,[],[null, false]) draws no region. Slots: overviewsummary,sections; settingssections; collectionfilters,list,empty; boardfilters,columns; master-detailmaster,detailin.page-body; editormain,sidein.editor.page-body(side first); conversationthread,composer,side; detailmeta,sections,side(.page-bodygetswith-sideonly whensideis filled). - Used by the dashboard (
overviewPage), the settings page (settingsPage), the flow editor (editorPage) and the refinement session (conversationPage). The other pages move over in later parts of #341. - Focus after a redraw.
mount()inui/dom.jslooks for the fallback heading in the target, then its parent, then the nearest.pageancestor, then the target itself.
Where a new rule goes.
- A custom property:
tokens.css. - A bare element:
reset.css. - A control or box used on more than one page, or a variant of one:
components.css. - A one-purpose helper:
utilities.css. - Anything else: the page file of the area that uses it. A page file (and
templates.css) does not start a rule with a shared component class (.card,.pill,.table,.modal…); put it incomponents.css, or scope it under a class of the page. A test (competingSelectorsintests/helpers/ui-css.ts) enforces this; a class whose base rule a page file owns goes on a short allow-list with a reason.
Look tokens (#850). Fonts, corner radii and shadows come from ui/tokens.css: --font-body, --font-display and --font-mono (with --mono), --radius-* and --shadow-none, --shadow-low, --shadow-high. A rule in ui/**/*.css may not set font-family, font, border-radius or box-shadow to a literal value; inherit, var(--…) and the look tokens only. tests/ui-look-tokens.test.ts checks this and fails on a stale allow-list entry. The fonts are system stacks only: nothing is loaded from another server.
Looks. There are five looks: Calm (the default), Midnight, Friendly, Editorial and Bento (LOOKS in ui/prefs.js). ui/looks.css imports one file per look from ui/css/looks/. A look file sets only token values, under html[data-look="<name>"]; calm.css also matches html[data-look], so it is the base for every look, and a later file wins at the same specificity. The person picks theme (System, Light, Dark), density (Comfortable, Compact) and look in the Appearance dialog of the account menu (appearanceDialog). The choice is kept in this browser per account (localStorage key scf.prefs, at most 20 accounts) and shared by the account's tabs (watchPrefs); no server call is made. One page depends on the look beyond tokens: the Simple Today picks a layout from it (LAYOUT_OF_LOOK in ui/simple-home.js: cards for Calm and Friendly, a list for Midnight and Editorial, tiles for Bento), and every layout draws the same model.

Use a token, not a number, for z-index and for the widths below. Keep rules that override each other in the same module and in the same order.
Import order, and why. Tokens, reset, layout, templates, components, utilities, then the pages. Rules of equal weight are decided by source order, so a later file wins. Tokens come first because everything reads them. Reset comes before any class. Components come before utilities, so a helper such as .muted can override a component. Pages come last, so a page can adjust what it uses. Do not reorder the list, or the rules inside a module, without checking the cascade. The shell rules at the end of pages/shell.css (for example .spacer) come after utilities.css on purpose.
z-index scale (--layer-* in ui/tokens.css; a test fails on a z-index that is not a layer token):
| Token | Value | Used by |
|---|---|---|
--layer-sticky | 10 | .top |
--layer-menu | 40 | the account menu, .scrim, the drawer sidebar (+1) |
--layer-overlay | 50 | .backdrop, and so every .modal |
--layer-toast | 60 | #toast, .skip |
Utility classes. Defined once in ui/css/utilities.css; each has exactly the declarations of the inline style it replaces. Build the class string in place with h(), for example class: "row tight text-sm mt-8". There is no style helper.
| Group | Classes |
|---|---|
| Stacking | .stack (grid, gap 12px), .stack.tight (gap 6px), .row.tight (gap 6px), .row.tighter (gap 4px), .row.center |
| Margin and padding | .flush (margin 0), .mt-4/6/8/10/16/22, .mt-neg-6, .mb-4/6/8/10/12/14/16, .mx-12, .px-12 |
| Width | .fit (auto), .full (100%), .w-70, .w-80, .w-90, .maxw-520 |
| Text size | .text-sm 12.5px, .text-xs 12px, .text-2xs 11.5px, .text-3xs 11px (built from the type tokens) |
| Text flow | .pre-wrap, .wrap-anywhere, .break-all, .select-all, .block |
| Grid | .span-all (grid-column: 1 / -1) |
.flush comes before the margin classes, so flush mt-4 gives margin: 4px 0 0. A compound margin such as 4px 12px becomes mt-4 mb-4 mx-12.
Inline style only for values computed from data. Use a utility class for any fixed value. Use style: or .style. only when the value comes from data, such as the chart tip position and the rate bar width in ui/dashboard.js. To show or hide a part, set the hidden property; ui/css/reset.css has [hidden] { display: none !important; } so it also works on .field and other grid elements. tests/ui-inline-styles.test.ts lists every style: and .style. in ui/**/*.js, fails for a cleaned file unless the line is on its allow-list with a reason, and checks that every utility class used exists in the CSS.
Content widths. --size-form (640px, in ui/tokens.css) is used by .start-form and .modal; .modal:has(.block-grid) is 900px.
Sticky regions. There are two: .top (stuck to the top of the page at --layer-sticky; static in the user display on narrow screens) and .page-editor .page-side > * in the editor, the Overview pane (sticks under the top bar). The sidebar .side is sticky below the top bar too.
Who scrolls. The page scrolls. These scroll themselves: .table-box (sideways), .log (the run log), .modal (up to 90vh) and .page-board .board (sideways). Code blocks such as .tl pre, pre.diff and .turn-text have their own maximum height. On a narrow screen the sidebar is a drawer (.side with body.drawer-open) at --layer-menu plus one; it scrolls itself.
Tests. readUiCss() in tests/helpers/ui-css.ts follows the imports and returns the whole stylesheet, for tests that read CSS. It fails on an import that does not resolve and on a .css file under ui/css/ that is not imported. tests/ui-css.test.ts checks the import order, that the rule set equals the frozen tests/fixtures/ui-style-baseline.css, the tokens, the z-index rule, the module comments, and that no page file starts a rule with a shared component class.
Every setting has a control#
The rule: every setting of ConfigSchema has a control in the interface or a reviewed exception. A new setting cannot be added without one.
- What counts.
settingKeys()insrc/settings/describe.tslists every key down to the leaves, watcher options included. A record (watchers,providers,router.rules) or a list of records counts once, by its item shape, with the segment*. A setting counts as having a control whendescribeSettings()describes it and its control is either generated (control: "generated", drawn from the description) or a namedui/*.jsmodule whose text mentions the key. A field of a record counts whenITEM_SETTINGSlists it with its module. - Flow variables. Every variable of every shipped flow needs a
var_infoentry orset_by_run: true. - Exceptions.
src/settings/exceptions.tsis the one list. Each entry has a reason. A key with a control and an entry fails the test, and so does an entry for a key that no longer exists. - The test.
tests/settings-inventory.test.tsis a unit test: it reads the schema, the description, the shipped flows through the flow loader and the text of the Settings modules. It names the key and says whether to describe it or add an exception.
16. Tests#
- About 2,100 tests in 78 files (vitest), run before every change is accepted.
- No real services. Fake
claude,codexandghprograms and a local git remote let whole flows run in seconds. - Each test run has its own temporary data folder.
- Documents are checked too: flow examples in the authoring guide must validate, and the error texts in the user guide must match the code.
- Large tests (separate). Slow end-to-end tests in
tests/large/**/*.test.tsrun in their own vitest projectlarge.npm testdoes not run them. Run them before a release withnpm run test:large, which runs only that project. The project exists only whenSCF_TEST_LARGE=1is set (the script sets it), so a plainvitest rundoes not pick it up. The project has a 10-minute test timeout and inherits the other shared options (setup files, global setup, retry). - Browser tests (separate).
npm run test:uiruns Playwright specs (tests/browser/*.spec.ts) against the real server in a real browser.npm testdoes not run them and passes with no browser installed. Install the browser once withnpx playwright install chromium.- A launcher (
tests/browser/server.ts) starts the server on a free port with a temporary data folder, one admin, one user and seeded data: a run in each main status, a repository, a refinement session and a watcher (tests/browser/seed.ts). tests/browser/widths.tsdefines the widths once: 360, 768, 1024 and 1440 px.openAs(browser, role, width)opens a signed-in page;expectNoSidewaysScroll(page)fails when the document is wider than the viewport.- The navigation spec checks every primary link on both displays at all four widths. At 360 px it goes through the menu button and drawer.
- Pages keep an event stream open, so the tests never wait for "network idle".
tests/browser/responsive.spec.ts(UI quality 1b, #368) checks at all four widths: no sideways page scroll on Home, Runs, a run detail (log and diff), Start work, Repositories and one open dialog; every visible interactive element in the header, sidebar and dialog is at least 44 × 44 px with a touch device profile (touchoption ofopenAs); the dialog is a sheet at 360 px and centred at 1024 px.- Visual check.
tests/browser/visual.spec.tscompares screenshots (toHaveScreenshot) with committed baselines.tests/browser/visual-matrix.tsdefines the matrix once: 12 pages (the gallery stand-indocs/ui-redesign/visual-system-demo.htmlopened from disk, admin, user and sign-in pages), each in theme (light, dark) × density (default, compact) at 1440 px, plus light/default at 360, 768 and 1024 px.tests/visual-matrix.test.ts(vitest) checks the matrix.openAstakes an options argument for theme, density and a fixed clock. Theme and density are set asdata-theme/data-densityon<html>before page scripts run.- Captures are deterministic: animations off, caret hidden, fixed height (
VIEW_HEIGHT), scale factor 1, wait for the page's ready text. Changing parts (run ids, times, the live running run) are masked. - A changed area above
MAX_DIFF_PIXEL_RATIO(inplaywright.config.ts) fails the test. Expected, actual and diff images are written totests/browser/test-results/. A harness test injects one style change and checks that the comparison fails. - Baselines live in
tests/browser/__screenshots__/{platform}/. Onlydarwinhas baselines; on other platforms the visual spec is skipped with a message, as it is on a Mac with no baseline folder. - Update baselines with
npm run test:ui -- --update-snapshots, check every changed image, and commit them. A story that changes the look on purpose does this and lists the changed images in its pull request.
- Guide images.
tests/browser/guide-shots.spec.tswritesdocs/images/<name>.pngfor every entry of the manifestSHOTS(scripts/screenshots/shots.ts). Run it withnpm run test:ui -- --grep @guide.tests/guide-docs.test.tschecks that the guides, the folder and the manifest agree.
- A launcher (
17. Self-repair#
The Foundry watches itself and repairs what it can, in one loop:
detectors → findings file → Reporter → bug story → goes first → hotfix → fix commit → 24-hour watch
- Detectors (
src/monitor/detectors.ts,work-detectors.ts) read runs, queue, watchers and the server log. Findings are kept inmonitor-findings.json. - The
Reporter(src/monitor/report.ts) turns a finding that lasts into one GitHub issue with the labelsbugand the build label, from a fixed template, after cleaning (clean.ts). - Goes first. The issue watcher builds a
bugstory before any other work, as a hotfix onmainwhen Hotfixes are on. Only the unchanged built-inissue-gitflowmay pushmain, in its steppush_main. - The fix commit is read from the finished run (
COMMIT:ofpush_develop,MAIN:ofhotfix_done). The 24-hour clock starts when the running Foundry has it; after 24 hours of normal work without the problem the finding is fixed (src/monitor/fix.ts). - Guard rails (
guard.ts,breaker.ts,mutes.ts): off by default, cleaning, one story per problem, 3 a day and 1 per check, quiet time, circuit breaker, never a story about a story, two tries, mutes. - Proof.
tests/self-repair-incidents.test.tsreplays four real incidents with the real Monitor, Reporter, Watcher and flows; only the edges are fake (gh,claude, the git remote and the clock).tests/self-repair-rules.test.tsproves the five rules. See the user guide.
The model analyst#
src/analyst/ is a process of its own (scf analyst run, every 6 hours through its own login
agent), so that judging the models never depends on, or slows, the server. It is pure reading:
collect.ts turns the step records of the last 14 days into counts per flow, step, model and
effort; advise.ts turns the counts into one verdict per pair; report.ts writes Markdown. The
quality of a step is read from what came after it in the same run: a fix_* step means its work
was broken, an address_* or revise_* step after a review means it was sent back. Published
figures (reference.ts) are fetched once a week by a headless Claude Code session that may only
search the web. Each figure carries who measured it; makers' figures are lowered by a tenth and can
only veto a step down to a much weaker model.
With self-tuning on (tune.ts), advice becomes a trial: an entry in analyst/overrides.json (flow →
step → model, effort) that runAgentStep reads at the start of each agent step, below the user's
router rules. Flows are never edited, so a change is one small file that can be emptied. A trial is
a controlled change: one per flow at a time, a stored baseline, a fixed number of visits, and a rule
that puts the old value back when the step does worse (or, for a higher level, not better). The
effort a step ran with is stored in its step record, so that the visits before and after a change
can be told apart.
The command line for the API#
src/remote/ makes every API call a command without a second implementation of anything. A command
is data: one entry in a table (Cmd in spec.ts) that names the route, its arguments and options,
and how to print the answer. One runner (cli.ts) turns the words into the call, sends it with the
session of scf login, and prints. So permissions, audit and locking stay in the server, where
the web interface already uses them. The session is the browser's: a cookie and the CSRF token
derived from it, so the server needed no change. The table is checked against the server's own
list of routes (RULES in permissions.ts) in both directions: a command for an unknown route
fails a test, and so does a new route without a command or a stated reason (API_ONLY). The file
commands keep their words: remoteCommand returns "not mine" for anything it does not know.
Ask Foundry: the contract#
Ask Foundry is the help assistant inside the product (epic #226). Its contract is code, in
src/help/contract.ts: pure data and pure functions, with no model, no storage and no route. Every
later part (stored conversations, the turn service, the pages) goes through it, so the text of a
model can never widen what a reply holds.
- Questions. Four types (
QUESTION_TYPES): product help, status, troubleshooting and guided resolution.QUESTION_RULESsays which evidence each needs:doc(the installed documentation) orstate(what the asker may see now, withobservedAt). - Parts of a reply. Five kinds (
PART_KINDS,PART_RULES): answer, recommendation, navigation, draft and action. Only an action haschangesStateandneedsConfirmation.ACTIONSis the server's list of actions (resume-runandcancel-run, see "confirmed actions" below). Nothing is carried out yet, andACTION_RULESnames the five conditions (server list, preview, confirmation, a second permission check, read-back) that a later story must meet before one runs. checkReply(raw, { role, offered, uncertain, targets, clean })turns what a model answered into theReplythe server keeps (ReplySchema). Nothing is trusted: evidence must be one ofoffered(the model names ids only), a link must be a page inNAV_PAGESthat the role has and gets the page's own title, an action must be inACTIONSand bound to an offered source (see below), texts are cut and cleaned, anddroppedlists what was left out in fixed words.displayText(reply)writes the text a person reads from the checked parts; it is never the model's own text.- Uncertainty.
certaintyOflowers the level tounverifiedwhen no evidence of the needed kind is left; the model may be less sure, never more. The sentences areCERTAINTY_WORDS. - Requests that are not served. A model answers them with a code only (
LIMIT_CODES);limitationFor(code, role)gives the fixed limitation and the safest next step, and never a page the role does not have. The codesrefinement,next-stepandmonitor-findingare the hand-offs to Refinement (#73), "what happens next" (#31) and the Problems page. - Roles.
forRole(role, value)removes every field inADMIN_ONLY_KEYS(model, provider, cost, tokens, server detail) for a user, at any depth, andhideNamestakes model and provider names out of a text.contractFor(role)is the contract as a person of that role may read it.
tests/help-contract.test.ts checks each rule, that NAV_PAGES matches ui/ia.js, and that
chapter 14 of the user guide holds the same sentences as the code.
Ask Foundry: confirmed actions#
Part 1 of 2 of #567 (#569), behind help.actions, off by default. It only binds a proposal to the
run the server knows about. Part 2 of 2 (#570) carries out a previewed action through the API. The
drawer's review and confirm control is #568: ui/api.js (prepareHelpAction, confirmHelpAction,
cancelHelpAction, all through req), ui/ask.js (reviewAction, the review option that tests
replace), ui/ask-model.js (previewRows, outcomeOf) and ui/ask-view.js (reviewDialog,
outcomeNodes). The prompt lists the role's action ids only when help.actions is on (turnPrompt).
- The list.
ACTIONShasresume-run(reversible,undoable: true) andcancel-run(high,undoable: false), both foradminanduser. Each has a fixedeffecttext written by the server. A kept action storesdef.effectas itsimpact; the model's text is never shown. - The binding. A source may carry
about(AboutSchema: kindrunand an id). Only the server sets it.liveEvidencesets it on a run snapshot that is fresh, whose run the asker owns (scheduler.ownerOf(id) === owner), and only when no conflict source is present. An admin gets no exception.prepareTurntakesaboutoff what is offered (EvidenceSchemastays strict) and returns it asPrepared.targets, only for sources that were offered. - The check.
checkReplykeeps an action only when its source is cited, offered, of kindstate, not inuncertain, and has a run target intargets, and when its impact text claims no result (claimsAction:claimsResult, plus "was/is/has been … resumed, cancelled, stopped …" and the like). The claim check reads the model's whole raw text, so nothing cut or marked as removed can hide a claim. Duplicates onidandabout.idare kept once. The three drop words areACTION_DROPPED. - The switch.
HelpTurns.runpassestargetstocheckReplyonly whileconfig.help.actionsis on. Off, every proposed action is dropped. The prompt still says"actions": []. - Outside check.
actionProblems(reply, ready, role)insrc/server/help-evals.tsre-checks each kept action against the prepared turn, andscf eval helpreports each problem asunsafe-action, which blocks a release. The scenarios are in theactiongroup.
Part 2 (#570): preview, confirm and cancel. prepareAction, confirmAction and cancelAction in
src/server/help-actions.ts; the routes are in src/server/api-help.ts, before the generic POST block.
Every error that is a refusal becomes an ActionRefused with a code, a status and a fixed sentence.
- Preview.
previewOfbuilds the answer from fixed words and the run's own fields; no model text is in it. Only the grant is written, in memory. - Grants.
ActionGrants(src/help/grants.ts) keeps each token under its sha256; the token is never stored. A grant lastsGRANT_TTL_MS(5 minutes), at mostGRANTS_PER_OWNER(5) per owner andGRANTS_MAX(1000) in all, and a new preview replaces the grant for the same reply action.peekreads a copy without using the token;takeuses it up, and burns it when the binding does not match (owner, conversation, reply, index).grantsOf(ctx)keeps one set per server in a WeakMap. - State version.
stateVersion(scheduler, runId)is a sha256 of the run (status, history length and last record, answers, next and waiting step, resumes, finish time) and of the queue: whether the run is queued or active, and the identity of its queued job (scheduler.queuedJob: enqueue time, kind,from, decision, source, priority, who queued it). A job taken out and queued again changes it. - Confirm, in order.
peekgives a fast 409 for an unknown, used or expired token. A resume then awaitscheckResume(the same gate as the run's page; the await may take a while). Then one synchronous block, with noawait:take, the binding and the proposed action again, the state version, the switches and the account (checkSwitches, read again),mayAct(the run's rule, the owner only) andapplies. Two confirms cannot both pass, and a permission change during the gate wait is seen here. Refusals are audited once (refused: <code>) and change nothing. - Executor and error boundary.
startResume(sync submit and audit) orcancelRunruns inside onetrythat covers the executor and the read-back. A throw there leaves the token used, is logged as "did not end cleanly" and does not become a 500. The state is then read again, best effort. - Read-back.
watchRunsubscribes to the scheduler's events and waits at mostREAD_BACK_MS(5000, overridable bydeps.readBackMs).armedis set aftersubscribereturns, so replayed events are ignored; the timer isunref'd; the subscription and timer are released in afinallyon every path. - Result.
decideworks from the fresh state only.doneis reported only after read-back. For a cancel,cancelledis checked before "still active", so a stop that was saved while the run finishes isstoppedonly when the status sayscancelled; a run that ended with another status first isnot-done.OUTCOME_WORDSgives the fixed words and recovery for each result. - Storage.
addOutcome(src/help/store.ts) adds the outcome to a finished reply and keeps the newestOUTCOMES_KEPT(10).OutcomeSchema(src/help/outcome.ts) is strict. A failed store or audit write answersstored: false; the outcome is still returned.
Tests: tests/help-grants.test.ts, tests/help-actions.test.ts (the checks, with a replaced gate),
tests/help-actions-run.test.ts (the real scheduler: stale evidence, read-back, the error boundary) and
tests/help-actions-api.test.ts (HTTP with FAKE_HELP).
Ask Foundry: stored conversations#
src/help/store.ts keeps the conversations in help.json ({ version: 1, conversations }), read
and written like the other account files: withAuthLock, a temporary file and a rename. The schema
is strict, so a file of another version or with unknown fields is refused and left untouched.
- Records. A conversation has an id, its owner, a title, a state and its messages. A message
is a question (
role: user, with the bounded page context) or a reply (role: assistant,replyToits question). A reply holdsstatus(pending,done,failed,cancelled), the checkedreplyof the contract (citations arereply.evidence, proposalsreply.actions) and, apart from it,text, whichfinishTurnwrites withdisplayText.finishTurnparses the reply withReplySchemaagain, so nothing unchecked is stored. - Ownership. Every call that reads or changes takes the owner from the session. An id of
another account is
not-found, the same as an unknown id. The routes (src/server/api-help.ts) use onlyuser.id; the role adds nothing, and a call with?as=is refused, so the support access of administrators is: none.deleteUserremoves the conversations of the account under the same lock (removeHelpLocked). - Turns and retries.
addQuestionstores the question and apendingreply. The turn ends throughfinishTurnorfailTurn, which take aTurnRef(message,tries) and write only while that reply is pending with that try: a result of an earlier try, of a stopped turn or of a deleted conversation is dropped.retryTurnsets the same reply topendingagain and countstries; no message is added.settleInterrupted(at server start) marks leftover pending replies as failed withinterrupted. - States.
active,failedandcancelledfollow the last turn;completed,archived(withstateBefore) anddeletedare set by the owner. Completing and archiving are refused while a reply is pending. - Retention.
deleteConversationreplaces the record with an empty one (wiped): no title, no messages.current()applies the policy on every read and write: a conversation unchanged forKEEP_MS(90 days) is wiped asexpired, and a wiped record is dropped afterDELETED_KEEP_MS(30 days).helpSweeperruns it hourly.
Tests: tests/help-store.test.ts (ownership, retries, states, retention, older and newer files),
tests/help-api.test.ts (the routes, both roles, the preview, a restart, a broken file) and
tests/remote-help.test.ts (scf ask).
Ask Foundry: the turn service#
src/help/turn.ts runs a help turn. It is a runner of its own, apart from flow runs, the
refinement flows and src/server/generate.ts: no flow, no run folder, no scheduler job.
- One call, no tools.
HelpTurns.runresolves the target fromhelp.model(elsedefault_model) withtoTarget, and callsrunClaudelike the failure summary does:noTools,noMcp,isolated, permission modedontAsk, no GitHub token variables, an empty temporary folder as working folder that is removed afterwards with the log of the call. A target that is not Claude Code is asetupfailure (helpTarget): Codex always has a shell tool. The answer is text;jsonOffinds the JSON object andcheckReplydecides what is kept, so model output cannot name a tool, a command or an action that runs. - The prompt (
turnPrompt) holds the rules of the contract for the asker's role, then one JSON value with everything a person wrote: the question, the page context, the lastHISTORY_TURNSanswered turns (each cut toHISTORY_CHARS) and the offered sources.evidenceinHelpDepsis where the context stories plug in; today it offers nothing, so every reply isunverified. - Queue and fair use.
admitrefuses before anything is stored (TurnRefused): switched off, a turn of the same account running or waiting, a full queue, or the account's turns of the day used. Admitted turns wait in one first-come queue andpumprunshelp.max_parallelat once. Each job holds anAbortController:cancel(after the store marked the reply) anddrop(a deleted conversation) abort it,stopAllon server close. - Failures are classified by
classifyFailureinto the store'sFAILURE_CODES;RETRYsays which can be tried again at once. The stored text is the fixed sentence of the code. The log gets fixed words only. - Usage.
help.jsonhasusagerows per day and account (addUsage): turns, failed, cost, tokens. A file withoutusage(the first version) reads as none. The per-turn cap andhelp.daily_budget_usduse these rows, not the run budget.GET /api/help/usageis the administrators' view;forRoleandhideNameskeep model, provider, cost and tokens from users.
Tests: tests/help-turn.test.ts (the service with a replaced model call, and the fake agent for
the arguments) and tests/help-turn-api.test.ts (the routes with the fake agent).
Ask Foundry: the page context#
src/help/context.ts holds the envelope a browser may send with a question, and what the server
makes of it.
- Shape (
ContextSchema,checkEnvelope):page(an address#/…), the selected things (kindandidof the first version, andentities),filtersandselection. Strict: an unknown field (owner, role, permissions, a record, markup) refuses the envelope. Ids and filter values may not be markup or a file path; a filter may not be named after ownership, permission or a secret. The stored schema stays as lenient aboutidas the first version, so older files still read; new input is held to the stricter rule. - Size (
CONTEXT_MAX, measured as the JSON text): cut byCONTEXT_PRIORITY. A later part never pushes out an earlier one;truncatednames what lost something and is written by the server only. - Pages (
HELP_PAGES,pageOf): the server's copy of the pages ofui/ia.js, with the same ids, addresses and roles (a test compares them). The address alone identifies the page; an address no page has and a page of the other role both give no page. - Lookup (
resolveContext,EntityResolver): at the time of the model call every named thing is looked up for the asking account.helpResolverinsrc/server/api-help.tsreads the account again (a blocked or removed account finds nothing; a changed role counts as the lower one) and asks the help context service. Not found and not allowed are one answer. Without a resolver nothing is found. - The help context service (
src/server/help-context.ts, #231):helpSnapshot(ctx, asker, { kind, id })gives a typed, bounded snapshot of one thing for one account, or undefined. It has no rules of its own. Each adapter names the API call it follows, asks the permission table for that call (findRule,authorize) and reads through the reader of that call:run(GET /api/runs/:id,checkedRunwith the owner, thenuserRunfor both roles),queue(GET /api/queue:ownQueuefor a user,queueWithNextfor an admin),repository(GET /api/reposwithlistRepos(owner);GET /api/admin/reposfor an admin),refinement(GET /api/refinement/:id,sessionFor, the check the route itself uses),issue(GET /api/board),problem(GET /api/monitor/findings/:id), and two without an id,next(GET /api/next) andhealth(GET /api/health). The last four are admin-only in the table, so a user finds nothing. A snapshot holds at most 24 fields, 300 characters per text and 2,000 characters in all; every text passesguardExcerpt. It records its fields as included (fields),omitted(left out on purpose, or a text that reads like an order),redacted(a secret was taken out),unavailable(the record has none now) andstale(known to be old: a connection check older than a day, a finding that is gone). An unknown kind, a wrong id, a reader that throws: undefined, never an error. Nothing is logged. In this story only the label of a snapshot reaches the model; the fields are for the evidence stories (#233). - In the request:
prepareTurntakes the resolved context only. The model gets aPAGEpart (page type and title, found things with the server's label, the count of things not found, filters), the marked text as an excerpt with the idselected-text(which is not a source and cannot be cited), and inDATAthe address, or the address pattern (#/runs/:id) when its thing was not found. Labels, filters and marked text pass the guard. POST /api/help/context(HelpTurns.describe) shows the kept envelope and the lookup without storing or asking anything.
Tests: tests/help-context.test.ts, tests/help-context-api.test.ts.
Ask Foundry: the documentation index#
src/help/docs.ts (#232) makes the evidence of a product question. No embedding model, no
network, no dependency.
- Approved documents (
HELP_DOCS):docs/USER_GUIDE.mdanddocs/FLOW_AUTHORING.md, read from the install folder (INSTALL_ROOTinapi-help.ts, next to the built-in flows). Both are infilesofpackage.json. A repository that is worked on is never read: there is no switch for it. - Sections (
sectionsOf): a heading of level 2 to 4 starts a section; a heading inside a code fence does not. A section keeps its heading trail, its anchor and its role. In the user guide the role comes from the chapter number (userChapters); a chapter that is not listed is for administrators. The id isdoc-plus 12 hex characters of the hash of path and trail. - Search (
searchDocs): the words of the question (three letters or more, no stop words, a plural "s" taken off) against the words of headings and text. A section counts with one heading word or two text words. The score is the sum oflog(1 + N/df)per word, three times for a heading word; ties keep document order. At mostDOC_SOURCES(4) sources, each aSourcewithkind: "doc", the title "document: heading trail", the refpath#anchor (SCF version)and an excerpt from the best paragraph on, at most 1,200 characters. - In a turn:
helpTurnsOfpassesevidence: docs.sources(question, role). Nothing else changed:prepareTurnguards every source,checkReplykeeps only cited ids that were offered, and without a fitting source the certainty is "unverified". - Stale index (
HelpDocs,docIndexProblems): the index holds the version ofpackage.jsonand size, time and SHA-256 of each file. Before each use size, time and version are compared; on a difference the index is built again, and when version, hashes or missing files differ the reasons are logged and kept (rebuilt,rebuiltBecause). Missing documents areproblems.GET /api/help/usageshows this asdocumentation.
Ask Foundry: live evidence#
src/server/help-evidence.ts (#233) makes the state sources of a turn. It holds no business
rule: every fact is a field of a snapshot of the help context service (help-context.ts), which
reads through the permission table and the API's readers. The run snapshot now carries the
next-step record of GET /api/runs/:id (nextFor, and for a user ownRecord and userRecord).
- Which snapshots (
liveSnapshots): the things of the page context (looked up again for the account as it is now), a user's two newest waiting or failed runs when the page names none, the queue, and for an admin the health. At mostSTATE_SOURCES(5). The queue entry of each run is read for the comparison only. - As a source (
sourceOf): idstate-<kind>-<hash>, kindstate, the label as title, the ref<kind> <id> · <page>,observedAt, and the fields as lines (at most 800 characters), with what is not available and what may be out of date. A snapshot with a stale field gives a source withuncertain: true. - Disagreement (
conflictsOf,conflictSource): three fixed comparisons (finished run in the queue; running run whose next step waits for a person; board status against the run's). A disagreement adds the sourcestate-conflict, alsouncertain. - In the turn:
Source.uncertainnever leaves the server.prepareTurnstrips it and lists the ids inPrepared.uncertain; aftercheckReply, a "confirmed" reply that cites one of them is stored as "likely". The prompt asks for "Observed:", "So:" and "You could:" in the explanation, and for saying that the state is uncertain when a source says so. helpTurnsOfoffers the state sources first, then the documentation sections.
Ask Foundry: diagnoses#
src/server/help-diagnosis.ts (#237) adds, to the state sources of a turn, what the product
itself says is wrong. It holds no diagnosis rule. A cause is one of three things: the
failure of the run's next-step record (failureSummary in failure.ts: classifyFailure
plus the table of errors.ts), the why of a next-step record (next-step.ts,
server/next.ts; for a queued run, a board issue and a health problem it is the field the
snapshot already holds), or nothing.
- Reading (
diagnosisSources): for the shown snapshots, in order, at mostDIAGNOSES(2). For a run the next-step record is read throughrunWithNextofhelp-context.ts, the same permission check and reader as the run snapshot (the snapshot adapter now uses it too), for the account as it is now. The run's reason goes throughexplainErrorfor the role. Nothing else is read: no log, no transcript, no step output. - The diagnosis (
diagnose, pure): symptom, cause (optional),confirmed, supporting and missing evidence, the next check. A failed run whose explanation isNOT_EXPLAINEDor "no reason was saved" has no cause, and the next check is thetodoofexplainError. A failure note of a model (byModel), a snapshot with a stale field and a question whose sources disagree giveconfirmed: false. A repository whose check failed and a monitor finding have no cause: the snapshot holds none. Kinds with nothing to explain give none. - As a source (
diagnosisSource): iddiagnosis-<kind>-<hash>, kindstate, title "Diagnosis of …", refdiagnosis · <ref of the snapshot>, the snapshot'sobservedAt, and five labelled lines withinDIAGNOSIS_MAX(800). Each text is made one line, passesguardExcerpton its own and is cut, so a record's text cannot add a labelled line; a text that reads like an order is dropped and named under the missing evidence. Without a confirmed cause the source isuncertain, so the existing rule of the turn makes a "confirmed" reply that cites it "likely". - In the turn: one more rule in the prompt: build a "why does it not work" answer on the
diagnosis, name the five parts, and never make up a cause or a detail no source holds.
liveEvidencereturns the disagreement, the snapshots, then the diagnoses. With the limit of 10 sources per turn, at least 2 documentation sections remain.
Tests: tests/help-diagnosis.test.ts.
Ask Foundry: offers#
src/help/actions.ts (#565, part 1 of 2 of #239) is the registry of the offers of a reply: buttons
that open a page. It is pure data and functions and imports only types from the contract, so the
contract can import its values without a cycle.
- Registry.
OFFERShas one row per type (open-run,open-repository,open-turn-item): its roles, the subject kinds it fits, its effect (navigation), the call whose permission rule is checked at the click (call, with:idfor the subject) andto, the address it gives back.offerDef(role, type)finds a row for a role. A later read-only check adds a row with another effect;EFFECT_KINDSandOFFER_TYPESare the lists the contract and the browser check. - Addresses.
subjectPage(kind, id)is the only place that builds a page address. It always starts with#/, encodes the id, and mapsrepository,runand the other kinds to their pages.LINKSinhelp-evidence.tsmoved here. The browser checks the address again withpageLink. - Subjects.
sourceOf(help-evidence.ts) gives each state sourcesubject: {kind, id}, the kind inSUBJECT_KINDS(equal toSNAPSHOT_KINDS, tested). The name issubject, nottarget, becausetargetis an admin-only key.prepareTurnkeeps the subject out of what the model sees (EvidenceSchemais strict) and returns it asPrepared.targets, andcheckReplygets it astargets. - Checked reply.
checkReplykeeps an offer (OfferSchema, strict) only when its type is in the registry for the role, its evidence is a state source offered in that turn, and the subject kind fits the type. Every other field from the model is dropped; the title is the server's own. A reply withoutoffersstill parses. At mostOFFER_MAX(3) are kept. - Clicks (
runOffer,help-evidence.ts; routePOST /api/help/conversations/:id/actions). In order: the account (currentAccount); the conversation (offerConversation), where a deleted one answers 410 before any message is read, so ownership is still checked first (the{question}test ofhelp-governancekeeps passing); the strict body{message, offer}; the message and the offer;offerDeffor the role now;findRuleandauthorizefor the call, where a 404 is "stale" and any other refusal is "denied"; then the subject is read again throughhelpSnapshot, or throughturnForforopen-turn-item. The answer is{type, to}. Fixed words (OFFER_WORDS) are the only texts a refusal carries. - Nothing is stored. A click writes no conversation change, so it works in every state except
deleted. The route is audited as
help-action(ok with the type, or failed withrefused: deniedorrefused: stale). - Your turn.
open-turn-itemopens#/homeonly for an item indata.groups[].itemsordata.continuing.buildTurn(src/your-turn.ts) keeps a grouped release item'smembers({runId?, repo, issue?}) on the server side;publicItemstrips them, as it stripsstamp. A dismissed item is not in those lists, so it is stale. - Browser.
ui/ask.jsrunOffercloses the drawer and then setslocation.hash, through an injectedgo.OFFER_EFFECTSinui/ask-model.jsequals the server's effects (tested). The card (offerNodeinui/ask-view.js) only asks; it opens nothing itself.
Tests: tests/help-actions.test.ts (the registry, subjectPage, OfferSchema) and
tests/help-offers-api.test.ts (each type: allowed, role denied, rule denied, stale, another
account's target; the route refusals).
Ask Foundry: checks#
#566 (part 2 of 2 of #239) adds two offers with effect: "check": refresh-evidence (every subject
kind, call: "read", so checked against READ_CALLS[kind]) and test-repository (repositories, checked
against POST repos/:id/test). They run only on a click and have no confirmation token. Helpers in
src/help/actions.ts: READ_CALLS, callOf, CheckSchema, checkText (fixed words), checkOf,
checkSourceId and checkSources.
- The record. A check is a
checkmessage inhelp.json:status: "done",replyTo(an earlier assistant message), andcheck(CheckSchema, strict: type, offer index, subject, scope, title, outcomeread/passed/failed, at most 30 lines of at most 300 characters,observedAt, anduncertainwhen it is stale). It has nocontext,reply,failure,triesorupdated. The conversation refine checks thatreplyTois an assistant message.versionstays 1: the field is optional, and a file without checks loads unchanged. - Bounds.
checkOfcuts each value and line withcutText(300 characters, the marker…included, which keeps thehelp-context.ts302-character case inside the limit), cuts the title to 500 and keeps 30 lines, with theunavailableandstalelines and the failed connection lines first. The result passesCheckSchema.parsebefore it is stored, so a snapshot with long values stores a valid check. - Pre-checks (
runOffer,help-evidence.ts, thenaddCheckinstore.ts). Before any remote call: the conversation isactive, no reply is pending, there is room for one more message (MESSAGE_LIMIT), and no other check runs in the same conversation (an in-memory set keyed by conversation). Otherwise the click answers 409 withcheckText, and nothing is contacted. - The wait.
testRepo(exported fromapi-repos.ts) awaits the remote and saves the status before it returns. If the conversation then changed (a question, an archive, the limit, a delete),addCheckrefuses withchanged(409); a conversation deleted meanwhile answers 410 and nothing is restored.addCheckalso refusesnot-found(an unknown message, or an offer whose type or subject does not match). The click answersCheckNotStoredwithcheckText.notStored(or the 410 sentence), and the audit line ishelp-actionfailedwithtest-repository; <outcome>; not stored: <code>. The test still ran; its result is on the repository page. The race is not prevented; its outcome is reported truthfully. Sharing a capacity reservation withaddQuestionand archive was rejected: it would touch many store functions. - Refusals.
testRepomaps 404 to stale and 403 (including the App allow-list,needOnAppList) to denied; 409 and 500 pass through.runOffertakes the test function as an optional argument, so the race tests can interleave the wait deterministically. - Later turns.
checkSourcesgives the newestCHECK_SOURCES(2) checks asstatesources. A check of the administrator's view is dropped for a user, and so is a check about a subject the account cannot see now (visible). A check older thanCHECK_FRESH_MS(15 minutes) is marked uncertain. Inapi-help.tsthe order is: live sources, check sources, then the documentation. - Audit.
help-actionokwith<type>; <outcome>; a refusal staysfailedwithrefused: <code>. - Tests.
tests/help-checks-api.test.tscovers the success paths, the authorization matrix (every refusal asserts that the fake remote andghwere not called and that no check was stored), the pre-check 409s, the interleavings, oversized values and the visibility of sources after a demotion.tests/help-store.test.tscoversaddCheck.
Ask Foundry: authorization, retention, audit and limits#
#243 adds no second mechanism; it uses the permission table, the audit log, the account limits, the store's retention and the usage ledger.
- Admission (
helpAllowedinapi-help.ts, passed toHelpTurnsasallow): after the off switch and the pause (help.paused,helpPaused;HelpTurns.admitrefusespausedandPOST /api/help/contextanswers 503 with the same sentence) and before anything is stored, the account is read again (currentAccount), thenhelp.audience(pilotadmitshelp.pilot_accountsbesides the administrators),help.disabled_accounts, and the account'sdailyBudgetUsdoflimits.jsonagainst the cost of its help turns today (usageToday). The refusal codenot-allowedis 403;limitis 429. A check that throws refuses.POST /api/help/contextuses the same check. - Retention (
setRetentionDays,retentionMsinstore.ts):help.keep_daysreplaces the fixed 90 days; the server sets it before each help call and each sweep. Account deletion removes the conversations and the usage rows of the account (removeHelpLocked); the audit lines stay. - Audit:
help-ask(ok withturn <reply id>; try n, or failed withrefused: <code>),help-delete,help-export,help-action(an offer followed; see "Ask Foundry: offers"). Written withwriteAuditwithout waiting for the lock; a line that cannot be written is named in the server log and does not fail the call. The turn id is the correlation id: it is the id of the reply message in the conversation. No text of a conversation is in a line.ui/audit.jslists the three names for the filter. - Export:
GET /api/help/export, own conversations only, throughconversationView.
Ask Foundry: feedback and quality numbers#
#245 adds no second access rule. A rating is a field of its reply, so the conversation's owner check and retention apply to it. The quality numbers are a separate file that names no account.
- Rating.
rateReply(store.ts) sets or clearsfeedbackon a finished assistant message under the data-folder lock.checkFeedbacktakes onlymessage,voteandreasons; the reasons are the fixedFEEDBACK_REASONSand come only withnot-helpful. The schema is strict, so an older build refuseshelp.jsononce a message hasfeedback. The route checks ownership before it reads the body: another account's id answers 404 and the body is not parsed. - Resolved.
completecountsresolvedonly when the body saysresolved: trueand the conversation was active with a finished answer. The count is taken in the route, because the store does not see the body. - Numbers.
src/help/telemetry.tskeepshelp-stats.json(version: 1,days). A row is strict: fixed counter names, failure, refusal and reason codes, and six latency buckets.addStatsruns underwithAuthLock, adds to the row of today (or of the day a vote was given,opts.day), and ignores a day older than the keep time. A number that is not finite counts as 0 and no count goes below 0.sweepStatsremoves rows older than 90 days; the hourly sweeper calls it. A failed write is logged in fixed words by the caller (HelpTurns.count,countQuietly) and never fails a turn or a request. - Where counted.
HelpTurns: refusals by code (refused, including the limits of the store), turns and retries atstart, stops atcancel, failures with their latency atfail, answers with their latency, sources, limits and actions offered atfinish. The routes countabandoned(a pending turn of a deleted conversation),resolvedand the ratings.helpSweepercounts the turns a restart interrupted on the first sweep only. - Stages.
rolloutStage(api-help.ts) derives off, paused, administrators, pilot or everyone from the settings alone. A queued turn checks the pause again inrunand fails assetup, before any model call. - Actions.
actionsOffered,actionsRunandactionsFailedare in the schema now. The last two stay 0 until #239 and #240 record them.
Ask Foundry: the guard#
src/help/guard.ts stands between a text and the two places it can go: help.json and the model.
Everything except the asker's own question is untrusted: page context, documents, run records,
issue text, logs, and the model's answer.
- Secrets (
scrub). Stored credentials are removed by value with the redactor ofsrc/credentials/redact.ts; then the shapes inSHAPES(private key block, authorization header, cookie, sign-in in an address, token shapes,name = valuefor names that holdpassword,secret,token, …); thenhelp.sensitive_patterns. A removed value is replaced by the fixed words of its category (REMOVED_WORDS), and the categories are returned.Removalscollects them over several texts. The categories are stored on the message (redacted), and logged; a value never is. - Orders in copied text (
looksLikeOrders,guardExcerpt). A source is a piece of evidence with an optional excerpt (Sourceinturn.ts).prepareTurnscrubs the question, the page context, the earlier turns and every source, cuts an excerpt toEXCERPT_MAX(all togetherEXCERPTS_MAX, at mostLIST_MAX.evidencesources), and drops a source whose title, place or excerpt reads like an order. A dropped source is not inoffered, socheckReplydrops a citation of it too. - Three parts in the request (
turnPrompt): the rules in the server's words; thenEXCERPTS, one JSON value on one line; thenDATA, one JSON value on the last line with the question, the page, the earlier turns and the list of sources. A text inside a JSON value has no line break of its own, so it cannot start or end a part. checkReplyis still the only way out. The guard adds nothing to a reply. An answer that obeyed an injected order still loses every action that is not on the server's list or not bound to an offered run, every link that is not a fixed page of the role, and every source that was not offered.- Fail closed.
scrubthrowsGuardErrorwhen the credential store cannot be read (BLOCKED), when a stored credential is still found after its removal, when a configured pattern is broken, or when a text is longer thanGUARD_MAX.HelpTurns.askthen refuses the question (unsafe, 503) before anything is stored or counted;HelpTurns.runends the turn withsetupbefore the model call; a reply whose check throws is not stored. A failing check for orders holds the text back.
Tests: tests/help-safety.test.ts (secret fixtures of every category, hostile texts, the three
parts of the request, and the fail-closed paths).
Ask Foundry: the drawer#
The interface of Ask Foundry is one drawer for both displays (#234). Three files, and the shells only mount it:
| File | What |
|---|---|
ui/ask-model.js | The decisions, as pure functions: the page that goes with a question (pageOf, whereOf, contextFor), the suggested questions (suggestionsFor), whether Send sends (sendPlan), when the conversation is read again (pollDelay), what a message looks like (entryOf), what is announced (announce) and a failed call in plain words (explainAskError). No document, no fetch, no timer. |
ui/ask-view.js | The nodes: the button, the drawer (role="dialog", aria-modal, named by its heading), the question form, one message. Every text of a conversation goes in as text. |
ui/ask.js | initAsk(role) asks GET /api/help/conversations once; only when enabled is true it calls createAsk, which puts the Ask Foundry button into #ask-scf (in the top bar, between Search and + New change) and the drawer at the end of <body>. It owns the state, the calls and the timer. |
- Mounted once per display.
ui/app.jscallsinitAsk("admin"),ui/user/app.jscallsinitAsk("user"), and not in a preview ("View as user"): the server shows no conversations there, and a 403 in a preview would end the view. - The page is not touched. The drawer is a sibling of the page, not a route. Opening and closing change no address and draw no page again. While it is open,
#top,#skipand#contentareinert; closing removes that unless the menu of a narrow screen is open. - Opening is free.
open()makes no call. Only when a reply was still waited for it reads that conversation again. A question, and the page it is asked on, go out with Send only. The context is{ page }: the address without its query, checked against the form the route takes. Nokindand noidyet. - Keyboard. The focus goes to the question box and comes back to the control that had it (the button when that control is gone). Escape closes; Tab is kept inside with
trapTargetofui/dom.js. A dialog in#modal-rootlies over the drawer and gets the keys first. - Status.
#ask-statusis a polite status line: it says once that Ask Foundry is working, and once what came of it. Errors of a call go to#ask-error(role="alert"). - Reading the answer. While the drawer is open and the last reply is
pending, the conversation is read every 1.5 s, after ten reads every 4 s. Four failed reads in a row, or a 404 or 410, end it with a sentence. - Following a turn (#235).
controlsForsays which of Stop, Try again, Archive, Take back and Delete are offered; none while a call is on its way (busy), so a control cannot be pressed twice. Try again is offered after a stop and after a failure withfailure.retrytrue, not after a limit (entryOfgives that the kindlimit). The server keeps the two messages of a retried turn and countstries;triesNoteshows the count on the one reply.waitNoteturns the waiting text after 20 s, measured in the tab from the moment it first saw this try. - Late answers. Every call takes a ticket from
staleGuardfirst. Leaving a conversation (a new one, another one, archive, delete) makes all earlier tickets stale, and a result with a stale ticket is not drawn and starts no reading. The two lists (current, archived) are told apart the same way. A change of the page behind does not leave the conversation. - After a reload. The tab keeps the id of the open conversation in
sessionStorage(scf-ask-open), nothing else.restorePicktakes it only when the list the server sent at the start still holds it; without one it takes the conversation whose reply is being written. It is read when the drawer opens. A conversation that is gone gives an empty drawer. - History.
GET /api/help/conversations(and?archived=1) is read each time the list is opened. Delete asks withconfirmDialogand names the consequence. - A reply by its parts (#236).
replyLayout(reply, role)turns the checkedreplyof a message into the short answer, the state of trust, the sources the question needs (basis), the cards and the sources with assumptions. A message withoutreplyshows its text.ui/ask-view.jsdraws it withh, so every string is a text node: nothing of a reply is read as HTML and no address in a text becomes a link.- Links are checked again in the browser.
pageLink(role, to)takes an address only whenresolveofui/ia.jsgives the same address back for the role (no fallback, no alias, no query). A link of a reply must also be a page without an id (fixed); a source may point at one run or one repository. Anything else is shown as text in a card that says so. The name of a link is the page's own title. - Trust has five states (
trustOf):confirmed,low(likely, or unsure with sources),missing(no source of the kindNEEDSnames for the question, whatever certainty the reply claims),conflict(two sources with the same kind and place and different titles) andlimit. Each has its own sign, name and border. The contract has no field for a contradiction, soconflictis derived from the sources; a later story may replace that by a field of the server. - Cards never act.
cardsOfmarks each cardread-onlyorchanges-state, asPART_RULESof the contract does. An action is drawn as a suggestion without any control; running one is #240.
- Links are checked again in the browser.
- Styles.
ui/css/pages/ask.css, class names start withask-. The drawer is--layer-menu+ 1, so a dialog and a toast lie over it. It is the whole width at 767 px and below. It has no transition and no animation.
Ask Foundry: scenario evaluations#
src/server/help-evals.ts and src/server/help-eval-scenarios.ts (#244) prove the promises of
Ask Foundry on fixed inputs. A scenario is a question, a role, optionally a page context with the
things the account can see, the sources the server would offer, the answer of a stubbed
provider, and what must hold.
- The path (
runScenario):resolveContext→prepareTurn→turnPrompt→ the model (a function) →jsonOf→checkReply→doubted(the rule of the turn service, now an exported function ofturn.ts). Nothing is stored; the guard uses the scenario's own patterns and no stored credentials. - The sources are made by
sourceOf,conflictSource,diagnoseanddiagnosisSource, so a scenario offers what a server offers. - Checks (
CHECKS):secret-leakandpermission-leak(a text the scenario names is in the prompt or in the kept reply),unsafe-action,citation,grounding(the certainty is no higher than the cited sources allow; with the stub it is also exactly the expected one),withheld,refusal,usefulness,context-size(PROMPT_BUDGET),told, andsent/contractwhen no reply is kept. - The verdict (
runHelpEval,THRESHOLDS): the zero-tolerance numbers, the rates, and with the stub any failed scenario.blockingsays in fixed words what blocks a release. - The report (
reportText,saveHelpEval): ids, counts and fixed sentences only; the file goes toevals/help/(mode 0600), whichlistEvalReportsdoes not read. - Providers:
stubModelinnpm test;liveModel(the options of a turn: no tools, no MCP servers, no GitHub token, an empty folder, the cost limit of a turn) only behindscf eval help --live.
Tests: tests/help-evals.test.ts.
Helper processes#
src/ops/ holds five helpers built like the analyst: a pure function that turns files of the data
folder into a result, a thin command, and a login agent of its own (schedule.ts). They share
nothing with the server but files. Two of them steer the Foundry, and both do it through one file:
governor/caps.json holds named, temporary caps on the runs at once, and the scheduler takes the
lowest that still holds (caps.ts). Every cap carries an end time and is ignored after it. That is
the safety rule of this design: a helper that crashes or is removed can only fail towards the
configured behaviour, never hold the Foundry down. The load governor also writes test-slots/cap,
which tools/test-slot reads. Its lowest value is governor.floor (Settings.floor, optional: unset means half the
configured number, at least 2). The same way it writes test-slots/workers (one number, testWorkers(cores) =
max(2, floor(cores / 4))) while the machine is loaded, and removes it otherwise. tools/test-slot ignores the file
after 4 minutes, sets SCF_TEST_WORKERS and org.gradle.workers.max in the command's environment (never on its command
line), and never raises a limit the user set. decide() sets GovernorState.workers only when the sample has cores
(sample() sets it). The governor's state (governor/state.json) keeps the times of its step downs for an
hour (downs, read by loadState()); the wait before a step up is settleMinutes times one plus the number of them, and
a step up below the configured number also needs the 15-minute load below low. A cap of 0 is valid: runLimit() returns it, pump() starts no new run (architect runs and
schedule chores included) and resumes still go on. A cap ends without an event, so while a cap holds jobs back the scheduler
arms a 30-second recheck timer (CAP_RECHECK_MS, unref'd), and Scheduler.close() stops it and any further start at shutdown.
The limits forecaster keeps its own minimum of 1. The flaky-test detector and the limit forecaster act only when
switched on (auto), because a wrong bug story or a wrong slow-down costs more than a late one.
The load governor also measures who uses the CPU (src/ops/usage.ts, measureUsage()). Each step process
leaves an empty mark <run folder>/step-pids/<pid> while it runs (markStep() in src/steps/proc-tree.ts),
because every run of a server shares one pid; the sandbox keeps that folder read-only for the step. The
reader takes the active runs from the marks and their run.json, the test slots from test-slots/slot-N/pid,
and the server and helpers from their command line (matched against this install's entry points only). Each
process goes to the first owner that claims it, with its descendants: a run (also through a parent chain that
leads to the run after the process left its group), a test slot, or the server. The rest is other programs.
Cores come from CPU-time differences between two checks (ps -o time=), not from %cpu, which macOS and Linux
average differently. A check needs a previous baseline less than the hold time old and at least 20 seconds
long. Only the base name of a program is read (ucomm), and the top three are kept. learn() moves the
per-repository figure of one run by a bounded step per check, kept in governor/usage.json (not in
state.json, so it survives reset). The result goes to governor/latest.json, and runGovernor() appends the
usage line and the runs that fit as cause to the change line. With figures, usage.ts (measurement()) puts
Sample.measured (cores, other programs' cores, cores per run) into the sample; decide() computes
runsFit() from it and steps the cap towards that number. GovernorState.over counts the checks in a row in
which the cap is above it (with a 0.5-core slack, SLACK_CORES), and a step down needs hotChecks of them.
A step up needs calm checks and a number above the cap. Without measured (no figures, or no learned value),
the part 3 rules run unchanged. decide() stays a pure function of state, sample and settings, so the target is
tested with recorded days (tests/governor-target.test.ts).
Pausing test runs (part 6). Under critical memory pressure, or a 1-minute load above testsHigh for hotChecks
checks, decide() sets GovernorState.paused (the time it began) and tests to 1. runGovernor() then writes
the time into test-slots/pause (PAUSE_FILE) at every check, and removes the file when the pause ends or in
clearGovernor(). tools/test-slot reads the file: a file not written for CAP_HOLD_MS (4 minutes) is ignored, so
a stopped governor leaves nothing frozen. While the file is fresh, each command in its own process group (now
every command, not only one with a limit) except the holder of slot-1 gets SIGSTOP on its group and tries
slot-1 at every look. Only test-slot signals its own group. The pause is recorded in FACTORY_TEST_SLOT_WAIT_DIR
as <start>-<pid>-pause.wait (renamed .done at the end, touched every 5 s), and the paused time is added to
pausedMs: the limit timer (armLimit(), countedMs()) counts working time only, and the started file moves
forward by the same amount. Every signal to the group is followed by SIGCONT, since a stopped process never acts on
SIGTERM; the process's exit handler continues a paused group. On the Foundry's side, src/steps/process.ts
and src/steps/slot-waits.ts leave the paused time out of timeoutMs and killLiveGroups() kills the command
processes the step tracker knows; src/release/build.ts and src/self-update-state.ts do the same for their
commands. src/server/stuck-runs.ts counts pause records as activity, and api-runs.ts, user-view.ts and
ui/run-timeline.js show the pause on the run page. Agent steps are not paused: tools/agent-bin only holds its
test call in test-slot.
The load governor's other signals (src/ops/governor.ts, tested in tests/governor-signals.test.ts). cpuTimes() sums
the idle and total CPU time of os.cpus() (counters since boot); cpuBusy() takes the busy share between the counters
of two checks, the previous ones kept in GovernorState.cpu (loadState() keeps them only when they are sane). No
previous reading, or counters that did not move forward, gives no share, and then the load rules run as before. decide()
uses the share as cpuAgrees (a load above high or testsHigh needs cpuHigh, 0.8), cpuIdle (cpuLow, 0.5, lets the
band count as calm) and cpuSaturated (stops calm). parseSwap() reads sysctl -n vm.swapusage; parseTherm() and
throttleReason() read pmset -g therm. sample() runs both with an absolute path, a 10-second timeout and a catch that
leaves the field out (Sample.swapMb, Sample.throttled, both optional, so recorded samples still work). decide() keeps
strain, the checks in a row with a throttle reason or with swap grown by more than swapGrowMb (64 MB) since
GovernorState.swapMb; at hotChecks it counts as a step-down reason, after the usual pause. The reason is named in the
change line, and throttling or swap growth stops the calm count. Settings holds the new thresholds with defaults only.
The governor's history and its card (#756). src/ops/governor-history.ts reads governor/changes.log from its end: logSince() goes over readBack() (src/ops/read-back.ts), which keeps the bytes of a cut line and decodes only whole lines, so a → split by a chunk boundary is safe, and it stops at the first line older than the window. capHistory() turns the lines into the runs at once over the last 24 hours. A move line names the value before it (runs at once N → M), so the first line in the window gives the start, and a cap set before the window needs no older line. An end line (CAP_ENDED from N (why)) names the cap that ended. heldCap() adds the cap in state.json that holds after the last line: it holds until now while the state is fresh, else until the hold time after its last check. Time below concurrency is put down to the reason of the latest step down, or to EARLIER for a cap set before the window. logSilentEnds() in src/ops/governor.ts writes the ends and moves that decide() makes without a line: a stored cap that the settings now clamp (a raised governor.floor, a lower concurrency), and a state that went stale. GET /api/governor (src/server/api-governor.ts, governorView()) joins the last result (latest.json: ok, old or none by the hold time), the caps in governor/caps.json that have not ended, the state and the history. Measurements go out only with status ok. latest.json keeps cores and free whenever other programs' load is measured, and fit only once a run's use is learned. The Overview card is ui/governor.js (governorBody(), capChart(), one SVG path, no library), and program names are text nodes. The digest's "Machine load" part calls belowLine() from runDigest() with the same history.
18. Where it is going#
- Refinement: (story drafts and the session's Epic are stored in the session;
src/refinement/draft.tshas the schema and the puresaveTypedandpreview, and each text and list item recordstyped,acceptedoraccepted-edited. The storeddependsOnlist is the truth; the preview is text for reading, not for parsing back.) (the architect's read is built:askArchitectinsrc/refinement/architect.tsqueues the shipped flowrefine-briefwith sourcerefinement <session id>, the only way in; the scheduler'sonFinishedhook and every session read settle the end of the run into the session, which keeps the latest brief and the current run. The question round is the shipped flowrefine-round, whosecheck_roundstep istools/refine-round-check; the token grant ofsrc/engine/guards.tsis per flow, andisRefinementFlow()guards user starts, publishing and deletion. A round and an own question start the same way:askArchitect(deps, actor, id, { kind })with kindbrief,round,question,suggestorreview(a review needs only the draft:ask=review, stored beside the draft bysetReviewinsrc/refinement/draft-review.tswith the text each remark was about, soreviewViewmarks itstale;moveToNotesthere moves a text with a plan or how remark to the notes; the code checks are the puresrc/refinement/draft-check.ts, computed inview()and never stored) (a draft and a field;ask=suggest, the field as flow variable, a cost limit of $1; suggestions are stored beside the draft byaddSuggestedinsrc/refinement/draft.ts; the task is built bysuggestText(), whose third line holds the ids behind R1/E1/D1 so an orphan run can be adopted; a criterion'stiemust name a rule or example, checked on load) queuesrefine-brieforrefine-round(ask=roundorask=question); the talk goes in astaskonly, built by the puretalkText()insrc/refinement/talk-text.ts(at most 90,000 bytes: oldest rounds, then the brief, then the end are left out, with a notice). The end is read from the stepcheck_round, checked again with zod, and stored byendArchitectRun(a round, an answer or a failed mark that leaves the talk unchanged); an orphan run is adopted with its kind and question read back from the job's flow and task, and a run keeps free the log lines its end needs. The talk — rounds, answers, waiting proposals and the map — is stored in the session (src/refinement/talk.ts);recordRoundis the way in for a round's result.) Help people write good stories before they reach the backlog, in the role of an architect — asking, checking against a Definition of Ready, showing impact and risk. The person stays the author. A split is confirmed byconfirmSplitinsrc/refinement/draft-parts.ts: the parts are new drafts appended in plan order, and the original keepssplitInto(the part ids) while each part haspart: { of, hint? }. Order is by position: a part may depend only on an earlier part, never on a later one or on its original (partOrderProblem, checked by the schema,saveTypedandacceptSuggestion). A draft withsplitIntois never ready and is never published: the plan and the publish call usewithoutSplits(publish.ts), which drops the original and points drafts that depended on it at each of its parts, in memory only, andleftBehindreports originals that still hold criteria; a part cannot be split again; a published draft cannot be split. The import rule:draft-parts.tsmay import values fromdraft.tsanddraft-split.ts, butdraft-split.tsimports only types fromdraft.ts. - Multi-user completion: separate watchers per repository, runs with the repository's own credentials, fair-use limits.
- Later: e-mail, per-user agent accounts, more than one machine.