Factory Shape — Specification
ReferenceStatus: draft v1.48, frozen for implementation planning. See the Changelog for version history.
Scope: the execution shape of the factory — modules, triggers, units, steps, runners, ports, bindings and execution semantics. Out of scope: tenancy, authentication, UI, persistence and deployment concerns.
1. Summary
A factory is a scope — a dataflow graph of triggers and steps — built
from nested scopes: the root, and the body of every composite unit. A step
invokes a unit (leaf or composite); a composite unit is itself a scope (a
cyclic dataflow graph of steps). Every connection is a binding — a
typed value flowing from a producer port to a consumer port. Loops and retries
are loop-carried (prev) bindings: a unit is a scope and need not loop,
whereas a loop is a unit (or the root) whose graph contains a prev cycle.
A unit declared with the loop keyword must contain a prev cycle; one
declared with unit need not.
Both are evaluated the same way — to quiescence as one firing — but only the
loop repeats. A scope is evaluated to quiescence as a single firing of the
node that invokes it, and only its boundary ports cross. The core is a pure
interpreter; everything with behaviour is a consumer-registered adapter.
2. Roles
| role | provides |
|---|---|
| Core (factory) | types & conformance, pure value built-ins (list and map operations), the graph, the scheduler, the time type, terminated_at, attempt, and the composite (engine) runner |
| Implementor | the three extension points: trigger kinds, external ports, runner implementations |
| Author | data: types, units, runners, triggers, bindings |
The core interprets; it implements none of the behaviour-bearing pieces. A deployment is a set of adapters plus authored data.
3. Extension points
Nothing with behaviour is built in. Consumers register adapters by name:
| point | selected by | contract |
|---|---|---|
| Trigger kind | kind: on a trigger |
fires; emits its declared out ports |
| External port | external port name |
takes params, returns one output |
| Runner implementation | kind: on a runner |
executes a leaf unit: consumes the runner's in: and produces its out: — or, for an open side, consumes/produces what the leaf declares (§6.4). A runner kind may perform an external effect; that is the adapter's concern, not a separate node |
How an external port is evaluated — when it runs, whether its result is memoized, and any per-Run state it keeps — is the implementation's concern, not the spec's.
The engine has no notion of success: a Run either reaches quiescence or is aborted by the max-firings bound, a system error, or an operator. What a step does — including any external effect — is its adapter's concern. An effect step may report, through its adapter, where the effect landed (a locator: a path, a URL, a commit id) and a one-line summary; the Run records them with the firing.
4. Types
Built-in types (only these):
text | int | float | bool | time | secret
Everything else is declared. text is a Unicode string, encoded as
UTF-8 at every external boundary (a trigger seed, an external-port argument
or return, a step input, file content). int is a signed 64-bit integer —
C's long long, two's complement — over the range −9,223,372,036,854,775,808 …
9,223,372,036,854,775,807. No value outside that range exists: a literal that
exceeds it is a load-time error, and any other out-of-range value — a seed, a
port, or an arithmetic result — is a runtime error that aborts the Run. An
int never wraps or saturates. At an external boundary it is a JSON number; one
outside the range is rejected like any other non-conforming value.
float is a 64-bit IEEE 754 binary value, and always finite: NaN and
the infinities are not float values, and a boundary value that is not finite is
rejected. time is an instant, written as an
RFC 3339 timestamp and normalized to its
canonical form: UTC, exactly three fractional digits, Z offset —
YYYY-MM-DDTHH:MM:SS.sssZ (e.g. 2026-10-06T04:49:52.292Z). Canonical time
strings sort lexicographically in chronological order, and equivalent instants
written with another offset or fractional precision compare equal.
There is no byte type. The language deliberately does not represent raw
bytes. dotFactory is a control plane: the values it carries are configuration,
events and results, and binary payloads are uncommon enough that a seventh
primitive is not justified yet. text is always UTF-8, so there is no opaque
byte string to bind; binary content that must cross a boundary has to be encoded
(base64, say) or kept outside the language. When a step must move binary data —
uploading an artifact to S3, for example — it does so inside a VM-based runner
step (the Docker runner, §6): the runner has a real filesystem and process, and
its command hands the bytes to the external tool directly, without the bytes
crossing a binding. A bytes type can be added later, additively, if a clear
need appears that this route cannot serve (§12).
type Issue = { id: text, title: text, body: text?, labels: [text] }
type Commit = { sha: text }
type Folder = { path: text }
type Repo = { name: text, url: text }
type Mcp = { url: text }
type Severity = enum { low, medium, high }
type Finding = { severity: Severity, location: text, description: text? }
type Labels = map(text, text)
type Verdict = choice {
succeeded { summary: text, findings: [Finding] }
failed { error: text }
clarify { question: text }
}
Type = Primitive | Record | List | Map | Optional | Enum | Choice | TypeRef ;
Primitive = "text" | "int" | "float" | "bool" | "time" | "secret" ;
Record = "{" { field } "}" ; # fields newline- or comma-separated
field = ident [ "?" ] ":" Type ; # "?" = optional
List = "[" Type "]" ;
Map = "map" "(" Type "," Type ")" ; # key must resolve to `text`
Optional = Type "?" ;
Enum = "enum" "{" ident { ("," | NEWLINE) ident } "}" ;
Choice = "choice" "{" { ident Record } "}" ; # tagged union
TypeRef = ident ;
decl = "type" ident "=" Type ;
Conformance. Type names are aliases, not nominal identities; conformance is always structural (duck-typed).
- Record (open): a value offering at least the declared fields conforms; extra fields are allowed.
- Enum / choice tag (closed): membership and tag are exact — the only closed sets.
- List / optional: element-wise / absent-or-conforming.
- Map (text keys): a value whose keys are text and whose values all conform
to the declared value type; the key set is not declared. A map's key type must
resolve to
text. A map conforms structurally, and an empty structure conforms to any map. A lookup through a path (m.key) is partial: a missing key is absence (§4.1); themap::atbuilt-in is total and returnsNonefor a missing key (§8.2). secret(opaque): conforms only tosecret.textandsecretdo not inter-convert, and there is no secret literal — a secret enters only as data (§4.2).Noneappears only under?. ANonevalue is legal only where the type isT?or the record field is declaredname?. ANonein any other position is a runtime error: trigger seeds are checked at admission, unit inputs at binding time, leaf/composite outputs at production — all abort before further code executes. Absence is separate fromNoneand follows the firing rule (§10); §4.1 defines the two, and §8 defines how each behaves in expressions. A field declaredname?is sugar forname: T?.T?issome(T) | none. The option is typed as a sum, with a canonical null encoding:noneis JSONnull,some(x)isx. Nested options flatten (T??=T?), because JSON cannot representsome(none). Stepping through an option requires?.; plain.on an option is an error.is some/is nonebranch, andopt::value(x)unwraps (noneis absent). An option in a boolean context is an error.someandnoneare reserved choice-tag names.
4.1 None and absence
Two different things can be unstated, and the spec keeps them apart:
- Absent is not a value. It is what evaluation reports when the port or
field it names has no value on this Run — a producer that has not fired, or an
optional (
?) port/field left unproduced. Absence never crosses a binding: when a binding's source is absent the binding is dropped or the node is disabled (§10), so no consumer ever receives it as a value. It is an evaluation outcome, not a member of the value domain: it is never stored in a record, list or map, never written to the journal, and never exposed at an external boundary. It exists only for the duration of probing an expression (a binding source, a guard, awhen). Noneis a value. It is legal only in a?position — aT?port, or a field whose type is optional — and it crosses bindings like any other value. There is noNoneliteral in the DSL:Noneenters the factory only as data, through a trigger seed, an external-port return, a leaf/composite output, or a core built-in (list::find,list::at,map::at) (§11).- Optional fields are values.
name?: Tis sugar forname: T?. At a typed boundary, an omitted field whose type is optional decodes tonone. Every typed boundary is strict: a present record missing a required field is an error — at admission, at binding time, at production, and on an external-port return — so a partial payload never becomes a Run or a value. An absent producer is a different thing: it is absence, and the firing rule decides (§10). Navigating an optional field never reports absence: it yields thenonevalue.
So T? denotes the set { a T, None } — some(T) | none — and absence is
a separate axis: a port either produced a value (possibly none) or it did not.
Navigating an option. ?. is the explicit optional hop:
a: A?; A.b: B?; B.c: text
a?.b?.c # text?: one flattened option
Every hop whose input may be none is written ?.; a plain . on an option is
a validation error. The result is optional iff a ?. was used. A none at a
hop short-circuits the whole path to none (a value), not to absence. The
alternatives for a T? are is some / is none, and opt::value(x) to unwrap
(a none makes the call absent, so the binder drops or blocks it). There is no
flow-sensitive narrowing, and an option is not a boolean: write
x is some, never when: x.
At one probe, "not available yet" and "will never be produced" are the same answer. The planner re-probes after every firing; if the Run reaches quiescence and no producer supplied the value, the consumer is skipped. That is what makes absence a scheduling fact, not data — and why it is not a third kind of value.
An external boundary renders the two the same. When a step or adapter must
serialize an input that was dropped as optional (absent), it presents it as
None — a kind: step receives an absent optional input as None (§10). A
consumer of the resulting artifact therefore cannot distinguish a None value
from a dropped optional; that conflation is the adapter's concern, not the
language's. (It is also why a step with inputs must have at least one required
input, §11.)
4.2 Secrets
secret is a built-in primitive: an opaque string whose content is
sensitive. Underneath it shares text's representation — it is carried as
a UTF-8 string at every boundary (a seed, a binding, an external-port argument
or return, a step input) — and secret adds only semantics (redaction and
opacity), not a distinct wire form. It has no literal — a secret is never
written in .fct, where it would enter the factory source and its digest. Like
None (§4.1), a secret enters the factory only as data: a trigger seed, an
external-port return, or a leaf/composite output. It may be declared in any type
position — secret, secret?, [secret], or a record field token: secret.
Redaction is an observation rule. Wherever the factory reports a value —
the Run's event log and store, a trace, an error message, a status page, the web
UI — a secret is rendered as a fixed marker of exactly eight characters
("********"), never its content. The marker's length is independent of the
secret's, so a redacted value never leaks how long the secret was.
Redaction is transitive through containers: a secret nested in a record, a
list or a map is redacted at that leaf, so a structure may be reported whole
while its secrets are hidden. Redaction is not a value-flow rule: every receiver gets
the secret as a secret, never a bare value — an external-port argument, a
leaf's inputs, a step input. The receiver therefore knows the value is sensitive,
and unwraps it to use it; that is the adapter's concern. What a receiver
reports is redacted: a generic runner (the file runner) writes the marker, and
only a boundary that deliberately opts in ever sees the content.
A secret is opaque in expressions. It may be bound, transported and passed,
but no operator may be applied to it. Truthiness (a guard, a step's when,
not, and/or), equality (==/!=), ordering, arithmetic and is are all
runtime errors on a secret (§8). A secret therefore cannot gate a node, and it
cannot be used to compute another value — there is no expression whose result
depends on a secret's content except passing it on unchanged.
No widening, no reveal. Despite the shared representation, secret
conforms only to secret: it is not text, text is not secret, and no
operator, cast or built-in converts between them. This keeps a secret from being interpolated into a command, a
path or a message by accident, and from drifting into an observation as text.
4.3 Deployment secrets
A secret enters a Run only as data (§4.2). One way a deployment supplies it is
a credential store: named secrets the deployment keeps and the
credential(key) external port resolves. This section fixes the invariants a
factory may rely on, and the scope precedence a hosted deployment is expected to
use — not the mechanism behind either.
Invariants (normative).
- A factory reads only its own tenant's secrets. Whatever key it names, a
credential(key)never returns a secret from a scope the Run does not belong to. The wrong scope would leak a credential across tenants. - The value stays a
secret. The port returns plaintext — unwrapping is the store's concern — but the engine conforms the return tosecret(§4.2), so redaction and opacity are unchanged: the Run cannot compute on it and every observation point reports the marker. - Write-only at the interface. A management interface (the deployment's API or UI) exposes a stored secret's metadata — its key and label — but never its value. A value cannot be read back; replacing one overwrites it.
- Never the environment. A
credential(key)is resolved only from the stored scopes below, never from the process environment. The environment is global and not tenant-scoped, so a key there would be readable by every tenant; a hosted deployment must not use it.
Scopes and precedence (expected). A deployment may keep secrets at several
scopes. A hosted deployment is expected to resolve a credential(key) from
the narrowest scope to the widest, first match winning:
- factory — the factory being run (most specific to the Run);
- user — the person the Run acts for;
- organization — the tenant the factory belongs to.
Only the scopes that apply are consulted: an automated Run with no acting user (a webhook delivery or a cron fire) has no user scope, so it resolves from factory then organization. A factory that belongs to no organization has no organization scope. A user may belong to several organizations, but a Run consults only its factory's organization.
Implementations may vary. How a deployment scopes, stores and protects secrets — a database, a KMS, an OS keychain — is its concern. The invariants above are what a factory relies on; the precedence above is the expected default, not a mandate. A factory run locally on an end user's machine, for example, may resolve only from that user's own scope (a keychain, a local file) and need no factory or organization tier at all — and may order what it has differently. The environment is never a scope, local or hosted. Authentication, tenancy, at-rest protection (encryption, a KMS, rotation) and who may manage a scope are likewise deployment concerns, out of scope here.
4.4 Deployment configuration
A config(key, default?) external port reads a configuration value: text a
deployment keeps for the Run's tenant, outside the factory source. It is the
non-sensitive counterpart of the credential store (§4.3) — the place for a model
name, a base URL, a feature flag, or a whole opencode.json document.
Invariants (normative).
- A factory reads only its own tenant's values. Whatever key it names, a
config(key)never returns a value from a scope the Run does not belong to. The scopes and precedence are those of §4.3 (factory → user → organization), first match winning. - A wider tier is allowed. Because a configuration value is not a credential, a deployment may append a deployment-wide tier below the tenant scopes (a file, the process environment, a defaults table). A tenant's value still wins, and no tenant sees another tenant's value.
- The value is data. The port returns
text, notsecret: it may be compared, interpolated, written to a file, reported and edited. A credential must never be kept here — that is whatcredential(key)is for. - Text only. A structured value is a text document (JSON, YAML, …) that the
factory writes whole or passes on. The language defines no parser or cast, so
a factory that needs structure outside a
filesystembody reads it in the adapter that consumes it. - A missing key needs a default.
default?is an optional parameter. When no scope (and no wider tier) holds the key, the port returns the default; without one, the call fails the step. Absence is never fabricated. - Plaintext management. A management interface may show and edit values at the scopes it administers; unlike a credential, a value can be read back.
4.5 AWS role assumption
The deployment may implement aws_assume_role(role_arn: text, external_id?: text, duration_seconds?: int) -> AwsCredentials. The ARN and external ID are ordinary
text, not credentials. AWS evaluates the deployment identity's permission and
the target role's trust policy; the function adds no registration, per-factory
grant or operation approval. Deployments must expose this port only to factories
trusted to exercise the deployment's AWS identity.
AwsCredentials is a record of access_key_id: secret,
secret_access_key: secret, session_token: secret, and expires_at: time.
Secret fields are wrapped before the result leaves the adapter, independently
of the caller's declared return type, and obey §4.2.
The implementation uses STS AssumeRole with the supplied ARN. external_id is
optional and is omitted from the AWS request when absent. When supplied, it
must be non-empty text; AWS enforces any external ID condition in the trust policy.
An omitted duration is omitted from the AWS request (AWS defaults to 3600
seconds). An explicit duration must be an integer from 900 to 43200 seconds;
AWS enforces the role's configured maximum and the 3600-second role-chaining
limit. Values are never silently clamped. Each call obtains a fresh session;
there is no refresh or credential persistence. Consumers must obtain a new
session when credentials expire. Revoking trust blocks new assumptions but
does not necessarily invalidate sessions already issued.
The reference adapter uses the deployment's dedicated FACTORY_AWS_ACCESS_KEY_ID
and FACTORY_AWS_SECRET_ACCESS_KEY credentials, never a customer key supplied
as a function argument. Both must be set; it does not fall back to the default
AWS credential chain. Other AWS clients may use that chain independently. A different injected adapter,
including one invoking a trusted container, may implement the same contract.
AWS failures abort the call with a sanitized error, without SDK response data
or credentials.
The in-app AWS guide renders customer trust and Terraform using the deployment's readable IAM caller principal. When the identity is absent or unreadable, the page is omitted from the index and its detail endpoint returns 404. An assumed role session must resolve to its actual IAM role ARN, including its path; an account-wide principal or a guessed role ARN is never substituted. The API and workers must share the identity for these deployment-specific instructions.
5. Implicit ports
Every trigger and step that fires exposes terminated_at: time, the
canonical instant of its most recent firing, and attempt: int, the
1-based ordinal of that firing (1 on the node's first firing, 2 on its next, …).
A node that is skipped (§10) does not fire, so it has neither; a node that
re-fires exposes the instant and ordinal of its latest firing. A trigger fires
exactly once, at admission (§10), so its terminated_at is the admission
instant and its attempt is 1. Every step is a binding source: an effect step
exposes the same implicit ports, so terminated_at orders effects exactly as it
orders value steps.
terminated_at and attempt are both information and sequencing tokens: binding
either forces one node to wait for another (see §10).
Identity metadata is exposed as the reserved source this, resolved
relative to the step whose binding is being evaluated:
this.metadata.run.id: text— the Run's identity. Assigned once when the Run is created (by the host, or by the engine for standalone runs); constant for the whole Run, including re-fires.this.metadata.node.id: text— the identity of the node being executed (the trigger or step). Stable across that node's re-fires, so it can key per-node (e.g. per-loop) state; distinct for distinct nodes.this.metadata.step.id: text— the current execution's identity. New for every step (every execution of a node); a node that re-fires has a different step id each time.
All three ids are opaque — factories must not parse them. Every node
execution — trigger or step — is a step and carries its own step.id.
A step may bind this like any other node. An adapter that emits an externally
visible artifact can therefore stamp the execution's identity on it — for
example, an S3 object's user metadata — so a downstream listener can recognize
an effect its own factory produced and refuse to admit it as new input, rather
than turning the factory into a feedback loop. The identity is also available
to the adapter itself: the engine hands a step its run.id, node.id,
step.id and the factory digest, so the stamp is automatic rather than
something every factory author must remember to bind. Which headers an adapter
writes, and their names, are the adapter's concern; factories treat them as
opaque.
6. Runners
A runner is a named definition that selects a registered implementation
(an extension point) and declares that implementation's interface. A runner
block carries only these fields — kind (final), extends?, in, out,
config:
in:/out:— the runner's interface: what the implementation consumes and produces at run time. The implementation reads and writes the interface's fields by name; the types are the only place those names appear. Both are required, and each is a type or the keywordopen:in:— a type is a minimum: the leaf binds every required field and may bind more, and those extras are data the implementation receives.openfixes no inputs — the leaf's inputs are its own;out:— a type is a fixed shape every leaf inherits (the leaf declares noout:);openfixes no shape, so each leaf declares its ownout:and the implementation produces a value for every declared port (§6.4). A type given to either side names at least one field. A map names no fields, so a map is not an interface; use a record with a map-valued field instead.
config:— the runner's static configuration: a typed value (config: DockerEnv = { … }) that holds every kind-specific knob fixed before the Run (fordocker, theimage/cpu/region/ … and the leaf'scommand). Since v1.22 it is the only place a runner's kind data lives.configis literal data (§8): read at bind time, never a binding source, and never part of the dataflow graph.
prompt and auth are declared by no kind and are not fields: an agent's
instruction is prompt: text in the runner's in: interface, and its
credential is a secret field of it (§6.3).
# agents.fct — a runner and its interface are declared together
type AgentCall = { token: secret, prompt: text }
runner agent: # an agent fixes its inputs …
kind: opencode
in: AgentCall
out: open # … and leaves the output to the leaf
A factory that reuses the runner imports the module, so the interface comes with it — the author binds the interface's fields and never restates the type:
# factory.fct
import "agents" as agents
step draft:
runner: agents::agent
in: # conforms to AgentCall
token: credential(key: "opencode") # secret
prompt: file "prompts/draft.md" # text
out: { draft: text }
Static configuration is a typed record, not free-form fields:
type DockerEnv = {
image: text
cpu: int?
network: enum { none, host, bridge }?
workdir: text?
region: text?
}
runner platform: # provided by the platform — the root
kind: docker
in: open
out: open
config: DockerEnv = { image: "factory-vm:base", cpu: 2, network: none }
runner builder:
extends: platform
in: open
out: open
config: DockerEnv = { image: "factory-vm:builder" } # records merge
Definitions are not versioned in the source: the factory is code under version control, and the runtime records a content digest of each resolved definition (see §11).
kind:is implicitly final — a runner cannot change its implementation.- The platform provides the root runner; deployments extend it.
configis a typed, checked value;in/outare the interface a leaf unit conforms to (§7).
6.1 Field modifiers
Fields of any definition carry a modifier:
| modifier | meaning |
|---|---|
name! |
required — a concrete definition must set it |
name? |
optional (explicit) |
final name |
private — inherited, but not overridable |
name |
optional, overridable |
A bare field is optional and overridable. A final field with no value is a
private default inherited by descendants but not overridable.
6.2 Inheritance (extends)
Any named definition may extends at most one other definition of the
same kind (runner←runner, unit←unit, trigger←trigger).
- Scalars are overridden by the child.
- Lists are merged (parent then child).
- Records are merged field-by-field: the child's fields override, the parent's other fields are kept.
- Maps are scalars for inheritance: the child's map replaces the parent's; they do not merge key-by-key.
finalfields may not be overridden.- Required (
!) fields must be satisfied by a concrete definition.
A definition that leaves a required (!) field unset is a template (an
abstract base); a descendant — or the deployment — must satisfy it before the
definition is used.
type DockerEnv = { image: text, region: text, mounts: [text]?, cpu: int? }
runner base:
kind: docker
in: open
out: open
config: DockerEnv = { image: "factory-vm:base", region: "eu-west-1",
mounts: ["/cache"] }
runner eu:
extends: base
in: open
out: open
config: DockerEnv = { mounts: ["/cache/deps"] }
# image and region are inherited; mounts merge -> ["/cache", "/cache/deps"]
runner eu_big:
extends: eu
in: open
out: open
config: DockerEnv = { cpu: 8, mounts: ["/data"] } # a new scalar; lists merge
runner us:
extends: eu
in: open
out: open
config: DockerEnv = { region: "us-east-1" } # a scalar overridden
# mounts is still ["/cache", "/cache/deps"]
A runner's config value is merged by the same rules — records field-by-field,
lists concatenated — and must conform to its declared type after merging.
6.3 Every block is closed
A runner, trigger and step carries the fields the spec defines plus one
non-structural key, config — its static data (v1.22). A unit / loop is
a pure definition and carries none. Any other field — a misspelling, or a knob
some other kind uses — is a load-time error, never silently ignored; the
reference parser enforces this syntactically, needing no kind registry:
| block | fields |
| runner | kind, extends?, in, out (each a type or open), config |
| trigger | kind, extends?, out, config |
| step | use xor kind xor (a runner, or nested steps), in, out?, when, config |
| unit / loop | extends?, in, out |
A step with kind: invokes a provider kind. Kinds that suspend the Run
(human gates) wait for external input and do not produce outputs until
resolved (§10); their out: declares the form fields and the shape of the
produced values, and their config is limited to the timeout and default
keys §10 defines.
- A runner's
in:/out:are each a type oropen(§6.4); itsconfigmust conform to the type named for it.configis literal data (§8): fixed before the Run, never a binding source, and never part of the dataflow graph. - A leaf provides its runner's interface. Against a typed
in:, a leaf binds every required interface field and may bind further inputs (the implementation receives them as data); against anopenin:, it declares its own. A typedout:is the leaf's fixed shape, which the leaf declares not; anopenout:is declared by the leaf (§6.4). - What a block's
configmay contain is the kind's schema — declaring it is the provider registry's job (§12). Until that exists the parser checks only thatconfigis a well-formed (optionally typed) literal value, and each adapter checks the entries it reads. promptandauthare declared by no kind. An agent's instruction isprompt: textin the runner'sin:interface, bound by the step; its credential istoken: secretthere.
6.4 Fixed and open outputs
A runner's output is fixed (out: is a type) or open (out: open).
Under a fixed runner every leaf inherits the shape and the implementation writes
those ports. Under an open runner the runner fixes no shape: each leaf
declares its own out:, and the implementation produces a value for every
declared port. A leaf may declare zero ports: that is a no-output step, not
a special node. The leaf's port types are then the caller's contract, not the
implementation's interface.
An open kind may be generative: it derives what to produce from the declared
ports. An agent is generative — the leaf's out: is the structure the model
must return, and the value is the validated result; so a generative kind may
restrict which types it accepts (a secret, for one). A kind that is not
generative is conventional and produces the declared ports by its own
convention.
Whether a kind is generative is the kind's concern; the provider registry (§12)
records it. The factory states only out: open.
An agent kind names the harness that runs the model — an in-machine server
or a managed service — and a deployment may implement more than one. The
factory's contract does not change with the harness: prompt is the
instruction, the credential is a secret input (§6.3), and out: is the shape
the model must return. Which harness a deployment trusts is its choice, not the
language's.
An agent kind whose harness runs remotely may outlive the worker that started it. A retry of the same firing reattaches: the deployment's attempt notes hold the non-secret handle (a machine and session id), and the harness's own session is the authority for whether the instruction was already admitted. The model is therefore neither asked twice nor restarted from scratch. A session that is gone, stopped, or no longer answers is released and the attempt starts a fresh one; the handle is cleared when the firing ends.
6.5 Container steps
A container runner executes a leaf by running an OCI image through a
deployment-provided container backend. The image is not the Machine and is
not the factory's unit of versioning: the backend pulls it, runs it in an
isolated environment, and returns the leaf's result. The backend, not the
factory, chooses where it runs.
The image speaks the container protocol (Appendix B): describe prints its
interface contract; run receives one JSON envelope on stdin and prints one
JSON result on stdout. That protocol is the only coupling between the factory
and the image — its language, filesystem and entrypoint are its own.
A container runner declares its interface like any runner (§6), and the
open/typed distinction is a checking switch:
in: open/out: open— neither side is checked. The leaf declares its own ports and the image is expected to produce them.- A declared type forces the contract: the runner asks the image for
describebeforerunand refuses a missing required input, an undeclared input, or a missing required output. The check is structural (port names and required presence); the declared DSL types are enforced by the engine. A deployment'scheckmay run the same comparison earlier. For this kind a typedin:is exact — the image's input schema is closed, so an extra binding the image does not declare is an error rather than payload (§6). - The two sides are independent: one may be
openwhile the other is typed.
Adapter inputs. A container leaf may bind inputs the runner consumes before
the image runs. They are part of the leaf's typed in: — the engine checks they
are bound — but they are not part of the image's describe payload: the
runner strips them before the contract check and the envelope. The image
contract therefore describes only the inputs the image receives. The reference
adapter reserves source, a tagged image source. Every variant carries the
image reference (with its tag or digest): public { image } has no
credentials, ghcr { image, username, token } and ecr { image, token } carry
what their registry expects (the ECR username is the fixed AWS). The registry
host is the reference's first segment. The adapter authenticates the pull with
the selected variant — or pulls anonymously for public — and never forwards
the source to the image. A variant with a missing field is a configuration
error; adding a registry kind is a new variant, not a reinterpretation of an
existing field. The runner's static image remains a fallback for a leaf that
binds no source.
config carries the kind's knobs and the image's parameters:
| field | meaning |
|---|---|
image |
the OCI image when no source input supplies it (a digest is recommended) |
base_image |
override the backend's base image |
cpu, memory_mb |
resources for the isolated environment |
network |
the container's network mode |
params |
static configuration passed to the image |
timeout |
seconds the image may run |
entrypoint |
override the image's entrypoint |
params is static configuration, so it cannot carry a secret: a secret
can only come from a credential(...) binding and therefore only appears in
in:. The envelope's inputs are the bound values minus the adapter inputs,
unwrapped at the execution boundary; nothing the factory observes is.
A non-zero exit is a step failure; an exit 0 with an unreadable, oversized or
wrong-version result is a non-retryable step failure. The Run still ends at
quiescence, or aborts on the operator's request, the max-firings bound or a
system error. The image's stderr is the log channel and its stdout is the
machine channel — one JSON document, never logs.
The backend is an extension point, not a new one: it is the same
StepRunner seam every kind uses, and a deployment registers the implementation
its FCT_CONTAINER_BACKEND names. The reference implementation runs the image
with podman inside a Fly Machine (Appendix B.6); another backend may run the
image as the Machine itself or through a hosted sandbox with the same protocol.
Reattaching after a worker restart. A machine-backed backend outlives the
worker that started it. Before provisioning, the runner asks the deployment's
machine ledger for a live lease of the same firing and phase. When the machine
still exists and is running that phase, the runner reattaches to it and
continues the phase within the attempt's original timeout instead of
provisioning another machine. When the machine is gone, stopped, or never
started the phase, the runner releases it and provisions a fresh one. A
reattach never runs a phase twice — the result is the one the dead worker was
waiting for — and it never extends the attempt's budget.
Caching the contract. The contract is the image's published interface, not
a per-run value, so a deployment may cache it — keyed by the image reference and
bounded by a TTL — and reuse it across attempts and worker restarts. A cache hit
skips describe; a miss, an expired row or an unreadable one asks the image
again and refreshes the cache. A cached contract never changes what is checked:
it is the same structural comparison against the image's last published
interface, and the debug describe path is always fresh.
7. Units & steps
A unit is a named, runnable definition. It is the unit of reuse and import.
runner:→ leaf unit, executed by a runner's implementation.- nested
step:entries → composite unit — a scope: a workflow (and, optionally, its effects), executed by the core engine. loop:declares a composite unit that must contain aprevcycle (§10.1);unit:may or may not loop. Otherwise the two are identical.
A step is an invocation inside a composite. It is one of:
- a reference —
use: nameplusin:bindings; the step inherits the unit'sout; - a kind invocation —
kind: nameplusin:/when/config: a leaf whose interface is the provider kind's, with no declared value outputs; or - an inline unit — an anonymous definition (a
runner:or nestedstep:s +in:+out:) used once at that step.
Name a unit only when it is reused or imported; otherwise inline its payload at the step.
unit planner: # leaf, named because it is reused
runner: platform
in: { issue: Issue }
out: { plan: Plan }
unit review:
in: { issue: Issue }
out:
plan: Plan = plan.plan
result: text = lint.result
step plan: # reference: out inherited from planner
use: planner
in: { issue: inputs.issue }
step lint: # inline unit: declares its own out
runner: platform
in: { plan: plan.plan, command: "make lint" }
out: { result: text }
Rules:
-
Every unit declares
in/out— leaf and composite alike. Ports are required unless marked?; optional inputs may be omitted and optional outputs may be absent on a given Run. -
Composite outputs coalesce. A composite's
out:may repeat a port, each binding with an optionalifguard; the port takes the value of a binding whose guard holds and whose source is present (a later binding wins on overlap). That is how disjoint branches — a recursion's base case versus its recursive call — select the result. -
A unit names a runner (
runner: name) — required for leaf units; a composite has no runner (the engine is its runner). -
A referenced step declares only
in:bindings and inherits the unit'sout— same ports, same names. It cannot rename or subset them; to reshape outputs, wrap the call in an inline composite (asunit reviewabove does):step p: in: { issue: inputs.issue } out: { the_plan: Plan = inner.plan } # expose only `the_plan` step inner: use: planner in: { issue: inputs.issue } -
An inline step declares
in:bindings and its ownout:types. Input types are inferred from the bound sources; a binding may optionally declare an upper-bound type (name: Type = source). A binding is required unless marked?(name?: source), which makes an absent source drop the binding without gating the node. A node's bindings may not all be optional: at least one must be required (§11). -
A leaf provides its runner's interface. Against a typed
in:(§6), the leaf binds every required field and may bind more; against anopenin:it declares its own. A typedout:is the leaf's fixed shape (it declares none); anopenout:is the leaf's to declare (§6.4). -
Closed (§6.3). A runner, trigger and step carry only their structural keys plus
config; aunit/loopcarries none. A step binds only ports its unit declares. An undeclared name is a load-time error; nothing is silently ignored. -
use:references any unit by name. Leaf and composite references are identical in form. -
A unit may invoke itself.
use:may name the enclosing unit, directly or transitively: recursion is ordinary composite invocation. It must terminate through guards (a base-case branch) or the max-firings bound; the spec defines no separate recursion limit. -
A composite is a scope. Its body is a cyclic dataflow of steps; the engine evaluates it to quiescence as a single firing of the invoking step, so only the unit's
outports cross the boundary (§10). Aprevcycle in the body makes the unit a loop; it still fires once and yields one result. -
Capabilities are ordinary ports. Folders, MCP servers and network access are just (usually optional) ports; how a runner provisions their values is the implementation's concern, not the spec's.
-
inputs./outputs.reference the enclosing composite's boundary ports:inputs.sourceis the value bound to the unit'sin: { source }andoutputs.verdictits declaredout: { verdict }. The words name the boundary record, not the declaration keyword, so they read the same forunitandloopand never repeat thein:/out:block key.
8. Declarations & bindings
external port checkout(issue: Issue) -> Folder
external port github_mcp() -> Mcp
external port loop_count(task_id: text) -> int
trigger on_issue:
kind: linear
config: { board: "ENG" }
out: { issue: Issue }
step run: # the root invocation of the workflow
runner: platform
config: { command: "factory-run" }
in:
issue: on_issue.issue
repo: checkout(issue: on_issue.issue) # external port -> Folder
mcp: github_mcp() # external port -> Mcp
round: loop_count(task_id: on_issue.issue.id) # external port -> int
out: { verdict: Verdict }
step notify_ci:
kind: webhook
in: { verdict: run.verdict }
when: run.verdict is succeeded
Block fields:
| block | fields |
|---|---|
runner |
kind (final), extends?, in / out (a type — the implementation's interface), config (a typed static value) |
trigger |
kind, extends?, out (types), config |
unit / loop |
runner xor a composite (nested step entries), extends?, in (types), out (types, or type = binding for a composite) |
step |
use (reference) xor kind (a provider kind) xor an inline unit (runner or nested steps, in (bindings), out (types)), when, config — valid at the root and inside a composite |
module = { import } { declaration } ;
import = "import" STRING "as" ident ;
declaration = type_decl | external_port | runner | trigger | unit | loop | step ;
type_decl = "type" ident "=" Type ;
external_port = "external" "port" ident "(" [ params ] ")" "->" Type ;
params = param { "," param } ;
param = ident [ "?" ] ":" Type ;
# `name?` is an optional parameter: a call may omit it, and an
# omitted argument is not passed to the implementation (§8).
runner = "runner" ident ":" block ; # kind + in/out interface + config
trigger = "trigger" ident ":" block ;
unit = "unit" ident ":" block ; # leaf if runner:, composite if nested step: entries
loop = "loop" ident ":" block ; # a composite unit that must contain a `prev` cycle
step = "step" ident ":" block ; # use: xor kind: xor inline unit
block = { entry } ; # indentation-scoped
entry = field | extends | step ;
field = [ "final" ] ident [ "!" | "?" ] ":" [ Type "=" ] [ value ] ;
extends = "extends" qual ;
in = "in" ":" ( types | bindings ) ;
out = "out" ":" ( types | out_bindings ) ;
# within a runner block, `in:` / `out:` hold a single Type or `open` — the
# implementation's interface: iface = ( "in" | "out" ) ":" ( Type | "open" ) ;
when = "when" ":" expr ;
types = map( ident [ "?" ] ":" Type ) ;
bindings = map( binding ) ;
binding = [ "prev" ] ident [ "?" ] ":" [ Type "=" ] source [ "if" expr ] ;
# `prev` marks a loop-carried (feedback) edge (§10.1); `Type =` is
# an optional upper bound on the bound value. `prev` is a reserved
# word: a port or binding may not be named `prev`. A target is a
# single port name: a record is supplied whole (§8).
seeded = "prev" ident [ "?" ] ":" Type "=" value "then" source [ "if" expr ] ;
# a `prev` binding may seed its first firing (§10.1); the seed is
# literal data (`value`), so it holds no path or call, and the guard
# gates from the second firing. `then` is a reserved word.
out_bindings = map( ident [ "?" ] ":" Type "=" source [ "if" expr ] ) ; # names may repeat (coalesce)
map(X) = "{" [ X { ("," | NEWLINE) X } ] "}" # inline
| NEWLINE INDENT { X NEWLINE } DEDENT ; # block
qual = [ ident "::" ] ident ;
# A value may be arithmetic; operators are whitespace-delimited (§8 notes).
value = additive ; # config data: literal / file / list / record / map
literal = STRING | NUMBER | "true" | "false" | WORD ;
# a `time` literal is a STRING in RFC 3339 form (§4); `-1` is a NUMBER
list = "[" [ value { "," value } ] "]"
| NEWLINE INDENT { "-" value NEWLINE } DEDENT ;
record = "{" [ vfield { ("," | NEWLINE) vfield } ] "}"
| NEWLINE INDENT { vfield NEWLINE } DEDENT ;
map_value = "{" [ vkey { ("," | NEWLINE) vkey } ] "}"
| NEWLINE INDENT { vkey NEWLINE } DEDENT ;
vfield = ident ":" [ Type "=" ] value ;
vkey = STRING ":" value ; # a map literal entry; no per-entry type
source = additive ; # binding source: a value, plus qual / path / call
# a record, map or list in a source position holds *sources* in
# its leaves (each may be a path, a call or a literal), nested freely
path = [ ident "::" ] ( ident | "inputs" | "outputs" | "abort" | "this" ) { "." ( ident | NUMBER ) } ;
call = qual "(" [ ident ":" source { "," ident ":" source } ] ")" ;
builtin_call = ( "list" | "map" ) "::" ident "(" [ source { "," source } ] ")" ; # positional (§8.1, §8.2)
# Arithmetic, shared by values and guards: left-associative, `* / %` bind
# tighter than `+ -`, unary `-` desugars to `0 - x`.
additive = multiplicative { ("+" | "-") multiplicative } ;
multiplicative = unary { ("*" | "/" | "%") unary } ;
unary = [ "-" ] primary ;
primary = literal | "file" STRING | list | record | map_value | "(" expr ")"
| qual | path | call | builtin_call ;
# qual/path/call/builtin_call: only in a `source` (not `config`)
Guard expressions (if, when, is):
expr = or ;
or = and { "or" and } ;
and = not { "and" not } ;
not = [ "not" ] test ;
test = additive [ cmp additive | "is" ident ] ;
cmp = "<" | ">" | "<=" | ">=" | "==" | "!=" ;
A source may be a record, a map or a list. repo: { url: … } builds the
record inline, and its leaves are themselves sources — paths, calls or
literals — nested to any depth (opts: { retries: run.n, tags: ["a", "b"] }).
A map literal uses quoted keys ({ "team": start.team }) and has one value type.
A complex value is therefore assembled at the binding, with each leaf read when
the node fires, and passed as one value. The value is present exactly when all
its leaves are: an absent leaf makes the whole value absent, so the binding
then drops or blocks as usual (§10). A literal record, map or list is
structural, so it is checked at load time against the port's declared type —
each leaf against its field or value type, and a record's required fields
against presence.
A target is one port name. There is no second way to build a record: in:
does not nest, so repo.url: is not a path into repo — a record-typed port
is supplied whole, inline or from a producer that emits it. (repo.url: is
therefore just an oddly-named extra input, and a typo like that is exactly what
the declared interface catches.)
An external-port call may omit an optional parameter. A parameter declared
name?: Type is not required at the call; an omitted argument is not passed to
the implementation, which supplies its own default. A required parameter must be
present, every argument must name a declared parameter, and no argument may
repeat. config(key: text, default?: text) -> text (§4.4) is the standard use:
config(key: "agent.model") and config(key: "agent.model", default: "…") are
both valid.
Reference semantics. Except where this spec says otherwise, the semantics of
values and expressions follow Python 3 — numeric comparison across int and
float, the sign of %, and so on. Each deviation is stated where it applies:
the 64-bit int, an out-of-range or non-finite result aborting, no implicit
int→float conversion, and a boolean context requiring a bool (below).
Arithmetic operators (+ - * / %) are numeric (int / float),
left-associative, with * / % binding tighter than + - and unary -
negating. + - * yield int for two ints, else float; / is true division
(always float); % is remainder, taking the sign of the divisor (as in
Python). Operators must be whitespace-delimited: a + b is arithmetic, while
a-b, factory-vm:base and src/** stay bare words. Arithmetic is allowed in
guards and in values (binding sources, out: bindings, config); the engine
evaluates it wherever it evaluates a value (binding and guard positions).
Integer arithmetic is 64-bit, exact, then range-checked. +, - and * on
two ints — and unary -, which desugars to 0 - x — are computed exactly and
the result checked against the 64-bit range (§4). A value above the maximum
(overflow) or below the minimum (underflow) is a runtime error that
aborts the Run; an int never wraps or saturates. A literal counts its sign
toward the check, so the minimum is writable (-9223372036854775808) while
9223372036854775808 is a load-time error. / is true division, so it yields a
float, never an out-of-range int.
Float arithmetic stays finite. A float result must be finite: arithmetic
that would overflow to an infinity, or underflow a nonzero result to
zero, is a runtime error that aborts the Run — exactly like an int out of range
(§4). A float is never NaN or infinite. Rounding a result to the nearest
float (including to a subnormal) is not an error.
A bad operand aborts the Run. A non-numeric or absent operand, or / or
% by zero (int and float alike), is a runtime error that aborts the Run
(§4).
Comparisons: == / != are structural equality, defined for any values
(except a secret, §4.2).
Ordering (< <= > >=) is defined for int, float, time and text —
numeric, chronological and lexicographic order (canonical time strings sort
chronologically). Numeric equality and ordering compare by value across int
and float (1 == 1.0, 1 < 1.5), as in Python. is <tag> tests a choice
value: true when the value is a single-key record named <tag>, false otherwise.
Numeric types do not implicitly convert. An int does not conform to a
declared float, and a float does not narrow to int; to place an int where
a float is expected, write a float. Operators are the one exception: a mixed
int/float pair is allowed in arithmetic (yielding a float) and in
comparison (comparing numerically).
A secret is opaque. It supports no operator (§4.2). Applying
truthiness — a guard, a step's when, not, and/or — equality (==/!=),
an ordering, arithmetic, or is to a secret is a runtime error that aborts the
Run. A secret may still be bound and passed unchanged; it is only computed
with that is forbidden.
Absence and None in expressions. A guard may read a port that is absent on
this Run (§10), or a ? port that holds None (§4.1). Both read as "no value"
in a boolean context, but they are not the same thing: absence is the report
that a producer did not supply a value on this Run and never crosses a binding,
while None is a value that did. The operators treat them as follows:
- Boolean context. A boolean context — a guard, a step's
when,not, or anand/oroperand — takes abool. An absent value and aNoneare falsy there (sonot xis true whenxis absent orNone); any other present value is a runtime error. There is no truthiness of a number or a string: write the test explicitly (x != 0,x != ""), which is always possible without loss of generality. - Equality.
==/!=are total and structural. Two absent values are equal and twoNones are equal; an absent value is unequal to every present value, and aNoneis unequal to every non-Nonepresent value. Because one is a value and the other is not, aNoneand an absence are unequal to each other. - Ordering.
<<=>>=are false if either operand is absent orNone(so<and>=may both be false). is <tag>. False for an absent value. On an option,some/nonetest the payload (canonical null); on a choice, the tag must be one the choice declares.someandnoneare reserved for options. A tag test on a type that is neither a choice nor an option is an error.- Options. An option is not a boolean: a guard/when whose value is
T?is a validation error, even thoughnoneis falsy at runtime. Useis some/is none. - Arithmetic.
+ - * / %are defined only for present numeric operands: an absent orNoneoperand is a runtime error that aborts the Run, exactly like a non-numeric operand (§4).
A guard that is absent, None, or false does not enable its node: a present
source with a false guard disables the node, and an absent source drops the
binding (§10).
8.1 List built-ins
The core provides a small, closed set of pure list built-ins. They are
values, not extension points: a deployment does not register them, and they
carry no external effect. list is a reserved namespace (as is map,
§8.2); the form is list::<name>(<arg>, …) with positional arguments.
| built-in | signature | meaning |
|---|---|---|
list::append(xs, item) |
([T], T) -> [T] |
a new list with item at the end |
list::concat(xs, ys) |
([T], [T]) -> [T] |
a new list, xs then ys |
list::without(xs, item) |
([T], T) -> [T] |
a new list with all structural matches removed |
list::remove_at(xs, index) |
([T], int?) -> [T] |
a new list without one position; None or out of range = unchanged |
list::find(xs, item) |
([T], T) -> int? |
the first structural match's index, or None |
list::contains(xs, item) |
([T], T) -> bool |
whether a structural match exists |
list::at(xs, index) |
([T], int?) -> T? |
the element at an index; None or out of range = None |
list::length(xs) |
([T]) -> int |
the number of elements |
list::map(xs, x -> body) |
([T], (T) -> U) -> [U] |
a new list with the callback applied to every element |
list::compact(xs) |
([T?]) -> [T] |
a new list without its none elements |
Callbacks. list::map's second argument is a callback expression, not a
value: x -> x.name. The parser only accepts it where the built-in signature
declares a callback, so it cannot be stored, returned, put in a record, or
passed to a declaration, and there is no function type in the value model. The
parameter is typed by the list's element type (one parameter, no index). The
body is pure: paths (including the parameter's fields), literals,
arithmetic, container construction and pure built-ins. An external-port call in
the body is a validation error, so a callback can never hide an effect fan-out.
Capture of outer sources is allowed; the parameter shadows them. Nested
callbacks are ordinary nesting. An absent body (the probe) makes the whole call
absent, exactly like an absent argument; a none element is an ordinary value.
filter, any, all and a narrowing filter are follow-ups.
Consuming options in a list. list::compact(xs) drops the none elements
of a [T?] and returns [T]; order is preserved and the input is unchanged. An
absent xs makes the call absent (the probe), not []. It is the consumption
idiom for a mapped or looked-up list, and it needs no narrowing: the input type
already says the elements are optional.
in:
labels: list::append(ticket.labels, "urgent")
open: list::without(review.findings, finding)
idx: list::find(issues, ticket) # int?
found: list::at(issues, list::find(issues, ticket)) # Issue?
pruned: list::remove_at(issues, list::find(issues, ticket))
known: list::contains(seen.ids, ticket.id)
empty: list::length(review.findings) == 0
Purity. Every built-in returns a new list; it never changes its input. Order is preserved. Lists are values under the same fan-out and content-addressing rules as any other value.
Equality. find, contains and without use the structural equality of
== (§8). The needle must conform to the element type: int into [float]
is allowed by the existing widening rule, float into [int] is not, and
bool is not an int. find is structural only — it finds a whole equal
element, not a record by one of its fields.
Absence. An absent argument makes the whole built-in call absent; the
binding then drops or blocks as usual (§10). Absence is reported before the
call, so a built-in is only ever evaluated over present values. This follows the
record/list-source rule, not the arithmetic rule. find and at return
None as a present value when there is no match; their result is T? /
int?, and None is legal only in a ? position. at with a None index
returns None; remove_at with a None index returns the list unchanged.
None where a non-optional T or [T] is expected is a runtime error.
Secrets. append, concat, remove_at, at and length only transport
or address values; a secret element stays wrapped and is redacted wherever
observed (§4.2). find, contains and without compare values, so a
secret anywhere in a compared value — the list, the needle, or a nested
record/choice field — is an error. When the element type is statically known
this is a load-time error; otherwise it is a runtime error that aborts the Run.
Bounds. An index is a non-negative int (or None where the signature
allows it); bool is not an int. An out-of-range index yields None from
at and the unchanged list from remove_at.
Positions. Built-ins are accepted wherever a source is accepted — a
step in: binding, a composite out: binding, a leaf of a record, map
or list source, and a guard or when expression. They are not accepted in
config, which stays literal data. A built-in takes positional arguments only;
a named argument is an error. An unknown list::<name> or map::<name> is a
load-time error.
8.2 Maps
A map is a value with a data-determined set of text keys and one value
type: map(text, V). The key type must resolve to text. A map is a JSON
object at every external boundary, and an empty structure conforms to any map.
type Labels = map(text, text)
type Counts = map(text, int)
A map literal uses quoted keys, inline or indented:
in:
labels: { "team": "platform", "owner": start.ticket.assignee }
config:
labels:
"team": "platform"
"owner": "platform"
Keys are string literals; duplicate keys are a load-time error; values are
sources (literal data in config). An absent value makes the whole map absent.
{} is the empty structure and conforms to a map or a record. A computed key is
built with map::with, not written in a literal.
Static access. m.key is a path into the map: any segment names a text key
and yields V. A key that is not present is absence, so the
binding drops or blocks as usual; a present key whose value is None (under
map(text, T?)) yields None. A key that cannot be written as a path segment
(one containing a dot or a space) is read with map::at.
Dynamic access and operations. The reserved map namespace provides the
same kind of pure, positional built-ins as list::*, with the same positions,
absence rule and config restriction (§8.1):
| built-in | signature | meaning |
|---|---|---|
map::has(m, key) |
(map(text,V), text) -> bool |
whether key is present (even with a None value) |
map::at(m, key) |
(map(text,V), text) -> V? |
the value, or None if absent |
map::length(m) |
(map(text,V)) -> int |
number of entries |
map::keys(m) |
(map(text,V)) -> [text] |
all keys, sorted lexicographically |
map::values(m) |
(map(text,V)) -> [V] |
all values, in sorted-key order |
map::with(m, key, value) |
(map(text,V), text, V) -> map(text,V) |
a new map with key set/replaced |
map::without(m, key) |
(map(text,V), text) -> map(text,V) |
a new map without key (missing = unchanged) |
map::merge(a, b) |
(map(text,V), map(text,V)) -> map(text,V) |
a new map; b wins on duplicate keys |
map::at is total: a missing key is a present None, not absence. This is
the same split as list::at (out of range is None) versus xs.0 (a path into
a list, which is absent). Use map::has when the two must be distinguished.
map::keys and map::values are deterministic: sorted by key.
Every map built-in is pure — it returns a new map/list and never changes its
input. No map built-in compares values: has, keys, without and merge
address keys (text); at, values and with transport values, so a secret
value stays wrapped and is redacted wherever observed (§4.2). A non-text key is
a load-time error when known and a runtime abort otherwise. None is legal only
where the value type is optional.
Lexical rules:
- Comments run from
#to the end of the line (outside strings). - Indentation (spaces) is significant; a block is an indented run of entries.
- A
:is a field separator only when followed by whitespace or the end of the line. Any other:belongs to a bare word — that is what keepsfactory-vm:baseandi::JiraTicketintact. file "<path>"reads a file relative to the module, wherever a value is accepted.- Values may be structured: records (
{ … }or an indented block), maps (quoted keys, inline or an indented block) and lists ([…]or indented-items), nested freely. - A field or record entry may be typed:
name: SomeType = value. The value must conform structurally to the type (checked at load). Types therefore describe config values as well as ports — that is how authors name their own abstractions. - A bare token runs to the next whitespace or one of
{}[](),=?!<>"#(a:followed by a non-space stays in the token, per above). A bare token that reads as a decimal numeral is aNUMBER(0,-1,1.5,2e3);true/falseare booleans; every other bare token is aWORD(docker,ro,none,factory-vm:base). - Structural keys are reserved inside a block:
kind,extends,runner,use,in,out,when,config,finalandstepare interpreted structurally and cannot be used as config field names. The binding markersprevandthenare reserved too: a port or binding may not be namedprev(§10.1) orthen.listandmapare reserved namespaces: a module may not be imported as either, and a declaration may not be named either (§8.1, §8.2).inputs,outputs,thisandabortare reserved path roots (§7, §11): a declaration may not be named any of them and no module may be imported under one, so a boundary reference can never be shadowed by a sibling node.
Notes:
- Every block is closed (§6.3). A runner, trigger and step carries its
structural keys plus the single key
config(its static data); aunit/loopcarries none. An unknown or misspelled field is a load-time error, never silently ignored. - The root and composite bodies hold Steps. Triggers are root-only sources; steps are invocations, including provider-kind effects, and may appear in any scope. A composite unit is invoked by a step.
- Reusable boundaries (
unit,runner,external port) declare types; local bindings (step.in) may infer, or declare an upper bound withname: Type = source. - A binding has exactly one source. The same value may be bound by several consumers (fan-out); there is no multi-writer port.
- Config is literal data. A
configvalue (a runner's, trigger's or step's) is a literal,file, list, record or arithmetic over those — never aqual,pathor external-portcall. Those appear only as a binding source.configis therefore static: evaluated at load time, fixed before the Run, and never part of the dataflow graph — the difference between a knob and an input. - A
choicevalue is a single-key record{ tag: { …fields } }, tested withis <tag>(§4). A binding source may author one inline when the target type is a choice: the key is the tag and its value is the variant's record. Without a choice target, a single-key record is an ordinary record; choice values otherwise cross bindings as data emitted by a node. - Empty values are allowed:
region!:,final endpoint:— a required or final field with no default.
9. Modules & files
A factory is a set of modules (files). The loader is given one root module; its transitive imports form the factory.
9.1 Imports
Imports are explicit and namespaced — nothing merges implicitly.
# factory.fct (root)
import "agents" as agents
import "runners" as runners
unit review: # local declaration
step implement:
use: agents::coder # qualified reference
import "<path>" as <alias>binds an alias for the module's declarations.- A declaration is referenced as
<alias>::<name>; declarations in the current module are unqualified. - Within a module, declaration names and aliases must be unique, and an alias may not collide with a local declaration name.
- Paths are resolved relative to the importing file, and the
.fctextension is implied:import "types"readstypes.fct. - Import cycles are allowed: resolution is by name, not load order.
9.2 External content
Large literals may live in their own files.
step coder:
runner: runners::builder
in: { prompt: file "prompts/coder.md" }
out: { commit: Commit }
step run_tests:
runner: runners::builder
in: { script: file "scripts/tests.sh" }
out: { result: GateResult }
10. Execution & concurrency
Scopes. Execution is defined over scopes. A scope is a dataflow graph
with boundary ports: the root (seeded by its trigger; no in), or the body
of a composite step (its in / out ports). A scope's nodes are its steps
and steps. A scope need not loop — but when its graph contains a prev cycle
(§10.1) it is a loop. A loop declaration must contain one; a unit
declaration need not. Every scope, looping or not, is evaluated the same
way: to quiescence, as one firing of the node that invokes it.
A scope runs to quiescence as one firing. A scope is evaluated once per
firing of the node that invokes it: the root once per Run (when its trigger
fires), a composite step once per firing of that step. Evaluation fires the
scope's nodes until none is enabled. Only the boundary ports cross: the
firings of nodes inside a scope are not visible outside it, so invoking a
composite step is a single firing that yields the scope's out values once.
A node's dependencies are its sibling nodes within the same scope (below); a
binding may not name a node in another scope. This is what makes an effect
inside a loop's scope fire on every pass, while an effect downstream of the
scope fires once per invocation of that scope (here, once — §10.2).
Checkpointing is invisible. A firing is atomic in its observable effect,
not in its duration: an implementation may record a firing's progress and resume
it after a crash. Resumption must be unobservable — a resumed Run yields the same
boundary values, fires the same steps the same number of times, and does not fire
again a node whose firing already completed. Node identity in such a Run is
derived from the factory and the firing's position, never from a random id, and
an external effect must be idempotent under that identity. A Run's scheduler
position is a function of its recorded firings, so a persisted cursor is a
derived checkpoint, not a second source of truth. A value the record cannot
reproduce — a secret is redacted (§4.2) — is not part of that position: it must
be re-resolved by its port or held in protected implementation state, and a
resumed Run must not re-fire a completed node to obtain it.
-
Triggers fire once, at admission. A Run begins when its trigger fires: the host supplies the trigger's
outvalues (the seed), which are checked at admission (§4, §11) and then held constant for the whole Run. The trigger exposes those values and itsterminated_at(the admission instant); it fires once, before the steps, and never re-fires. For a trigger to fire again the host starts a new Run — repetition across Runs is the listener's concern (§12), not this execution model's. -
Enabled — guards gate the node. A node is enabled when every required gating binding has a present source and no binding whose source is present has a false guard. A false guard disables the node for that pass — it does not fire, and that is how a loop terminates. A
prevbinding is inactive on the node's first firing and gates from the second (below), so it never prevents the first firing; a seededprevcontributes its seed on that firing, and its guard is likewise inactive then. A binding whose source is absent is dropped without gating: an optional (?) or undeclared input that is unsatisfied simply does not constrain the node. -
Step enablement. A step may appear in any scope (§7) and fires within that scope's fixpoint: a step inside a loop's scope fires on each pass, one downstream of the scope fires once (§10.2). A step fires when its
whenholds, no binding has a present source with a false guard, and every input is satisfied: a present source, or an absent source the binding marks?. An absent optional (?) input is dropped — the step still fires, and the input carries no value (akind:runner receivesNone, §4.1) — whereas an absent non-optional input disables the step. That is howresultandskippedinexamples/absencestay mutually exclusive. A step fires once per enablement like any node; every step is also a binding source for its implicit ports. A step with inputs must have at least one required input or awhen(§11), so an absent optional is never the node's only reason to fire. -
Fire on upstream firing. A node fires when it is enabled and at least one of its dependencies — a sibling node's port (a binding source) or a guard reference (below) within the same scope — has fired since this node last fired, or it has never fired. Firing is driven by upstream firing, not value equality: a node re-fires even when a re-fired source yields the same value. A firing's outputs are latest-wins per port. A node that never fires has all outputs absent (it is skipped); once it has fired it exposes its most recent outputs, and a pass that does not fire it does not retract them.
-
An external port is a value, not a source. A port call never makes a node fresh: it cannot by itself trigger or re-fire a node. Freshness comes from node firings (a step, the trigger) or the composite boundary
in; a port only supplies a value for an input, whose other inputs must still be present. -
prevbindings are loop-carried. A binding markedprevis inactive until its node has fired, then an ordinary binding; every unmarked binding gates from the start, and declaration order never affects gating. A seededprevsupplies its seed on that first firing, and its guard gates only from the second. Aprevbinding may reference the node itself (a self-loop). §10.1 defines the marker, its shape, and the loop invariant. -
Absent drops; false gates. An absent
?or undeclared source drops its binding and does not gate the node. A present source with a false guard disables the node (above), except on a seededprev's first firing (§10.1). An input is required unless marked?on the binding (name?: source) or declared?on the unit's port; aprevinput is required only from the node's second firing. -
Sequential vs parallel is implicit — there is no
seq/parkeyword. A binding between two nodes orders them; no binding means they may run concurrently. -
A guard is a dependency. The sibling nodes a guard (
if, or a step'swhen) references are dependencies exactly like binding sources: they order the node — it waits for them — and their firings make it fresh (it re-fires). Sox: a.x if b.flagdepends on bothaandb. A guard on aprevbinding is inactive on the node's first firing, like the binding itself (§10.1). A guard reference to the node's own name is not a dependency: it reads the node's own latest outputs, and a self-loop is expressed by marking a sourceprev(§10.1). -
Ordering is data-mediated. To order a step after another without consuming its value, thread
terminated_at(or any value). Every dependency carries a value (a guard reads one). A skipped step has noterminated_at, so ordering edges out of it skip coherently too. -
Loops and retries. A loop is a scope whose graph contains a cycle closed by a
prevedge — there is no seed primitive and nowhile/for; the scope still runs to quiescence and yields itsoutonce. Theprevedge is inactive on the first pass, so the loop starts — or, when seeded, contributes its seed there with the guard skipped; from the second pass it gates on its producer and re-fires the node each time that producer fires. A loop is bounded by a guard that disables a node when the budget is reached: attempts while under budget, the exhausted branch once the guard turns false. The budget is the loop node's own firing count,attempt(§5): e.g.review.verdict is rejected and plan.attempt < 3retries, and the exhausted branch readsplan.attempt >= 3. (A budget may instead be a loop-carried value or an adapter-provided external port, §3.) An unguarded cycle never quiesces and is aborted by the max-firings bound. -
Termination. A scope ends at quiescence — no node in it is enabled; the Run ends when the root quiesces — or is aborted by the max-firings bound. Value equality is irrelevant: a cycle does not converge on its own, so termination is the author's concern — a loop ends only when a guard disables a node in it, or the bound is hit. The spec fixes no number: the bound is the implementation's choice (§11).
-
Factory errors vs node failures. A factory error is the implementation's own fault — a runner that cannot execute, a binding that violates conformance, a missing
file, a system fault — and it aborts the Run. A node failure is ordinary data: a step that wants to report failure writes it to anoutport (an author-defined type), and the factory handles it with guards and steps. The engine interprets neither as "success" or "failure." -
Done is quiescence. A Run that reaches quiescence is done, whether or not any step performed an external effect. A factory with no effects is valid.
-
Operator abort. A deployment may stop a Run outside the factory's own dataflow — an operator, an API client, a timeout. A started Run is recorded aborted and no further node is enabled; there is no final pass. A Run that has not started ends immediately and is recorded aborted. Stopping is idempotent: a Run that already finished keeps its status. An effect already executing is not interrupted; it finishes and its result is recorded.
-
Human gates. A
kind: gatestep suspends the Run pending resolution: the gate'sout:defines a form (records, enums, choices, optionals, secrets, lists, maps) with the same expansion rules as a manual trigger, andin:supplies display context. While pending, the node produces no outputs and downstream nodes are not enabled; a Run may be waiting for one or more gates. Pending gates are tracked for review. An optionalconfig.timeoutspecifies a duration and adefaultresolution (conforming to the gate'sout:); on expiry the gate is auto-resolved with the default and the Run resumes, or it remains pending if no default is given. A resolved gate produces its values as outputs for that attempt and the Run resumes. A cancelled Run cancels pending gates.A gate's
confighas exactly two keys.timeoutis a duration string: one or more<count><unit>segments, with units,m,h,dorw(30s,15m,2h,1d,1w, or combined as1h30m), and it must be strictly positive.defaultis a literal record conforming to the gate'sout:that supplies every non-optional port — the values a timeout resolves the gate with — and it requirestimeout(without one it could never apply). Any otherconfigkey is a load-time error, as is adefaultthat is missing a required port, names an unknown one, or carries a value that does not conform. -
Operator pause of a schedule. A deployment may pause the schedule of a recurring trigger (a cron trigger, for one) without changing the factory. A paused schedule fires nothing; resuming re-arms it at the next occurrence, so the windows that passed while it was paused are skipped, not replayed. Pausing is durable and idempotent, and it never stops Runs already admitted — stop those individually (operator abort above). How a schedule is persisted, paused and resumed is the implementation's concern (§3).
unit build: # a composite unit
step a: use: ...
step b: use: ... # may run with a
step c: # all-of join: waits for a and b
use: ...
in: { x: a.x, y: b.y }
step d: # ordered after a
use: ...
in: { gate: a.terminated_at }
10.1 Forward and prev (loop-carried) bindings
A binding is forward by default: it gates its node from the first firing.
Marking it prev makes it loop-carried — the feedback edge a cycle needs
in order to start.
step plan:
in:
prev feedback: review.verdict if review.verdict is rejected and plan.attempt < 3
- Syntax.
prevprefixes the binding name:prev name: [Type =] source [if guard]. Aprevbinding may instead seed its first firing:prev name: Type = seed then source [if guard]. It is valid only on a step input (in:), never on anout:binding or akind:step binding.prevandthenare reserved words: a port or binding may not be namedprevorthen, so a leadingprevis always the marker andthenis always the seed separator (§8). - Meaning. A
prevbinding is inactive until its node has fired. On the node's first firing it contributes no value and does not gate (a seeded binding contributes its seed instead), so it cannot prevent that first firing. From the second firing on it is an ordinary binding: an absent required source leaves the node not enabled, and a present source with a false guard disables the node — that is how a loop ends. Declaration order never affects this; it is presentation only. - Seed. A seeded
prevbinding contributes its seed on the first firing instead of being inactive, so the loop has a first value to build on. The seed is literal data (value, §8) — a literal,file, list, record or arithmetic over those — with no path or external-port call, so it creates no dependency and never gates on another node. It must conform to the declaredType, which is therefore required in the seeded form. A guard on the binding does not gate the first firing; it gates from the second, exactly as an unseededprevcannot prevent the first firing. (To skip the first pass on a condition, use a forward binding, not theprevguard.) From the second firing the binding is an ordinaryprevedge. Seeding is how a loop accumulates a list from its first pass. - Shape. A
prevbinding's source must reference exactly one sibling node (or the node itself), possibly wrapped in arithmetic or a pure core built-in (§8.1) over that one sibling and constants, e.g.prev n: loop.n + 1orprev n: list::length(loop.seen) + 1. It may not reference two different siblings or an external-port call. A seed contains no references at all. - Loop invariant. The bindings not marked
prevmust form a DAG, and everyprevbinding must lie on a cycle (a self-loop counts) — the §11 rule, restated here. A cycle with noprevedge, or aprevedge not on a cycle, is a spec error. Because aprevbinding is inactive (or seeded, with its guard skipped) on the first firing, the cycle can be entered; thereafter the producer's firing re-fires the consumer.
10.2 Worked example: a retry loop
Reusing the §4 Issue and Verdict types and a per-Run retry port (§6, §10).
The loop is the body of deliver — a scope whose graph contains a prev
cycle. plan fires once, then re-fires each pass review fires; the guard on
the feedback binding disables plan once the budget is spent (or the verdict is
approved), which ends the loop. deliver itself fires once and yields one
verdict. The progress kind step sits inside the scope, next to the loop,
so it fires on every pass; succeeded / failed sit downstream of the scope,
so each fires once (when its when holds).
loop deliver: # the loop's scope: fires once, yields one verdict
in: { ticket: Issue }
out: { verdict: Verdict = review.verdict }
step plan: # feedback: review -> plan
runner: platform
in:
prompt: "plan the issue"
ticket: inputs.ticket
prev feedback: review.verdict if review.verdict is failed and plan.attempt < 3
out: { plan: text }
step review:
runner: platform
in: { prompt: "review the plan", plan: plan.plan }
out: { verdict: Verdict }
step progress: # inside the scope: fires once per pass
kind: webhook
in: { attempt: plan.attempt,
plan: plan.plan }
trigger manual_ticket:
kind: manual
out: { ticket: Issue }
step run:
use: deliver
in: { ticket: manual_ticket.ticket }
step succeeded: # downstream of the scope: fires once
kind: file
config: { path: "out/succeeded.json" }
in: { verdict: run.verdict }
when: run.verdict is succeeded
step failed:
kind: file
config: { path: "out/failed.json" }
in: { verdict: run.verdict }
when: run.verdict is failed
If progress fires on three passes and succeeded once, the event log has
three progress firings (each with its own step.id) and one succeeded
firing. A Run is done when it reaches quiescence; it does not need an effect to
be done, and there is no abort pass.
Factory run history initially shows five Runs and can expand to pages of twenty, ordered by start time and run identity, newest first. A factory-scoped history includes its started Runs across all pages; queued Runs remain available through the control queue.
11. Determinism & invariants
Determinism. The interface (ports + bindings) is fully declared and every value crossing a binding is recorded, keyed by a hash of its content (content-addressed): identical values are stored once, and a Run's trace can be replayed and checked. Conformance is a runtime check. This is reproducible interface and trace, not reproducible output: execution is not hermetic (agents are nondeterministic).
Invariants.
- A factory declares ≥ 1 Trigger.
- Every block is closed (§6.3): each field is spec-defined or declared by its
kind, and each binding names a declared port (or a field of the runner's
in:interface). An undeclared name is a spec error. - Every runner declares its interface:
in:andout:, each a type oropen(§6). - A leaf unit provides its runner's
in:/out:interface (§6): every required interface field is bound, a typedout:is inherited (the leaf declares none), and anopenout:is declared by the leaf (§6.4). - Required ports must be bound by a step.
- A node with bindings has at least one that is not optional (
?), or a step-levelwhen, which anchors enablement: an all-optional binding set with nowhenis a spec error, because an absent optional would be indistinguishable from a producer that has not fired yet (§10). - Every
TypeRefresolves to a built-in or a declared type. - A factory is rooted at exactly one module; every declaration is reachable through explicit imports.
- Every referenced declaration resolves (type, unit, runner, trigger, external port) across modules.
- Every binding source and guard path resolves statically: the enclosing scope
names a visible node (
inputs/outputs/this, a root trigger, or a sibling step), the first segment names a declared port on that node (terminated_atandattemptare implicit on every trigger/step and take no subfields), and each further segment resolves against the port's declared type (record field, map key, numeric list index, or choice tag). A map key is any segment: the key set is not declared.abortguaranteesreasons: [text]and otherwise accepts any segments (shape open);thisis the closed record{ metadata: { run: { id: text }, node: { id: text }, step: { id: text } } }. An external-port call binds exactly its declared params. Anything else is a spec error at load time; the only runtime absence is a declared optional (?) port left unproduced. - A list or map built-in names one of the closed sets (§8.1, §8.2), takes
exactly its declared positional arguments, and its arguments and result follow
the signature. A statically known mismatch — a non-list/non-map argument, an
ill-typed needle, index, key or value — is a spec error. An equality-requiring
list built-in (
find,contains,without) is a spec error when its element type containssecret; no map built-in compares values. - A seeded
prevbinding declares itsType, the seed conforms to that type, and the seed contains no path or external-port call (§10.1). - Gating is explicit: within a scope, a binding's dependencies
are the sibling nodes its source and its guard reference (a guard's
reference to the node's own name is not a dependency); the bindings not
marked
prevform a directed acyclic graph, and everyprevbinding lies on a cycle (a self-loop counts) — aprevbinding being inactive (or seeded, with its guard skipped) on its node's first firing. A cycle with noprevedge, or aprevedge not on a cycle, is a spec error. - A binding's optional
name: Type = sourceannotation is an upper bound: the source's type must conform to it and (for a referenced step) it must conform to the unit's declared port type. - A required
out:(no?) bound to a possibly-absent source — a port of a step that may not fire — is a spec error (make it?or add a covering branch). A record field is never absent: an optional field is anonevalue. Bareout:ports (no=) are exposed with open subsetting semantics — what supplies them is still open (§12) — and are not coverage-checked.
12. Open (deferred, additive)
- Further operators: arithmetic (
+ - * / %) is specified; bitwise, string concatenation and other operators are not. - A
bytesprimitive: raw bytes are deliberately not represented (§4). Binary work runs in a VM-based runner step instead; add a byte type only if a clear need appears that route cannot serve. - Collection operations beyond the core
list::andmap::sets (§8.1–§8.2): comprehensions,map/filter, predicate or keyedfind, and text/set operations. - Run status and resume.
- Provider registry API (how adapters are registered and resolved, how a kind
declares the schema of a block's
config— the §6.3 closure — and whether an open-output kind is generative, §6.4, and so which port types it accepts). - Value representation and content-addressing.
- Trigger seed syntax (how a trigger supplies its
outports at admission). unit←unitinheritance detail (whetherin/outports merge by name).- Bare
out:subsetting: what supplies a port declared with no=. - A spelling for a genuinely output-less runner (
out:is required, §6); a leaf may simply declare noout:underout: open. - Consolidating
use:-recursion withpreviteration, now that every unit is a scope that runs to quiescence — whether recursion is still needed.
Appendix A — Worked example (multi-file)
A factory split across modules. Leaf work is inlined at the step; only reused or imported pieces — types, runners, external ports and the composite unit — are named.
# ── types.fct ─────────────────────────────────────────────────
type Repository = {
name: text
url: text
}
type Commit = {
sha: text
repository: Repository
}
type Plan = {
text: text
}
type Severity = enum { low, medium, high }
type Finding = {
severity: Severity
location: text
description: text
}
type ReviewVerdict = choice {
approved { summary: text }
rejected { findings: [Finding], feedback: text }
}
type GateResult = {
name: text
passed: bool
output?: text
}
type QualityReport = {
lint: GateResult
typecheck: GateResult
unittests: GateResult
uat: GateResult
}
type Failure = choice {
plan_exhausted { findings: [Finding], feedback: text }
build_exhausted { report: QualityReport }
}
type PullRequest = {
number: int
url: text
}
# ── input.fct ─────────────────────────────────────────────────
type JiraTicket = {
key: text # e.g. "ACME-123"
title: text
body: text
labels: [text]?
url: text?
}
# ── runners.fct ───────────────────────────────────────────────
type RepoMount = {
source: text
target: text
include: [text]?
exclude: [text]?
mode: enum { ro, rw }?
}
type DockerEnv = {
image: text
cpu: int?
network: enum { none, host, bridge }?
workdir: text?
region: text?
mounts: [text]?
repos: [RepoMount]?
}
runner platform: # the platform's root runner
kind: docker
in: open
out: open
config: DockerEnv = {
image: "factory-vm:base"
cpu: 2
network: none
workdir: /workspace
region: eu-west-1
}
runner builder: # build/test: toolchains + dependency cache
extends: platform
in: open
out: open
config: DockerEnv = {
image: "factory-vm:builder"
mounts: ["/cache/deps"]
repos: [
{
source: "./repo"
target: "/workspace/repo"
include: ["src/**", "Makefile", "pyproject.toml"]
exclude: ["**/__pycache__/**"]
mode: ro
}
]
}
# ── factory.fct (root) ────────────────────────────────────────
import "types" as t
import "input" as i
import "runners" as r
loop deliver:
in: { ticket: i::JiraTicket }
out:
commit: t::Commit = implement.commit
pr: t::PullRequest? = open_pr.pr
plan_failure: t::Failure? = plan_failure.failure
build_failure: t::Failure? = build_failure.failure
# ---- plan, and have the plan reviewed; re-plan with feedback, up to 3 times
step plan:
runner: r::platform
in:
prompt: file "prompts/planner.md"
ticket: inputs.ticket
feedback?: review.verdict if review.verdict is rejected and plan.attempt < 3
out: { plan: t::Plan }
step review:
runner: r::platform
in: { prompt: file "prompts/adversary.md", plan: plan.plan }
out: { verdict: t::ReviewVerdict }
# ---- implement the approved plan
step implement:
runner: r::builder
in:
prompt: file "prompts/implementer.md"
ticket: inputs.ticket
plan: plan.plan
feedback?: gate.report if not gate.passed and implement.attempt < 3
out: { commit: t::Commit }
# ---- quality gates: all four run in parallel on the produced commit
step lint:
runner: r::builder
config: { command: "make lint" }
in: { commit: implement.commit }
out: { result: t::GateResult }
step typecheck:
runner: r::builder
config: { command: "make typecheck" }
in: { commit: implement.commit }
out: { result: t::GateResult }
step unittests:
runner: r::builder
config: { command: "make test" }
in: { commit: implement.commit }
out: { result: t::GateResult }
step uat:
runner: r::builder
config: { command: "make uat" }
in: { commit: implement.commit }
out: { result: t::GateResult }
# ---- join the gates (all-of)
step gate:
runner: r::platform
config: { command: "factory-gate" }
in:
lint: lint.result
typecheck: typecheck.result
unittests: unittests.result
uat: uat.result
out:
passed: bool
report: t::QualityReport
# ---- open the PR only if every gate passed
step open_pr:
runner: r::platform
config: { command: "gh pr create --fill" }
in:
commit: implement.commit if gate.passed
out: { pr: t::PullRequest }
# ---- failure exits: fire when a retry budget is exhausted
step plan_failure:
runner: r::platform
config: { command: "factory-fail plan" }
in:
ticket: inputs.ticket
verdict: review.verdict if review.verdict is rejected and plan.attempt >= 3
out: { failure: t::Failure }
step build_failure:
runner: r::platform
config: { command: "factory-fail build" }
in:
ticket: inputs.ticket
report: gate.report if not gate.passed and implement.attempt >= 3
out: { failure: t::Failure }
trigger manual_ticket: # a manual trigger (fires with provided input)
kind: manual
out: { ticket: i::JiraTicket }
step run: # root invocation: binds the workflow's inputs
use: deliver
in: { ticket: manual_ticket.ticket }
step write_result:
kind: file
config: { path: "out/result.json" }
in: { commit: run.commit, pr: run.pr }
step plan_needs_attention:
kind: file
config: { path: "out/plan_needs_attention.json" }
in: { failure: run.plan_failure }
step build_needs_attention:
kind: file
config: { path: "out/build_needs_attention.json" }
in: { failure: run.build_failure }
Appendix B — Container step protocol
An image opts in by answering two argv phases on its entrypoint:
<entrypoint> describe # print one contract document on stdout
<entrypoint> run # read one envelope on stdin, print one result on stdout
Both are one-shot: one JSON document, UTF-8, no trailing output. describe must
not read stdin or require configuration. The engine speaks version 1; an
image that answers another version is refused, not guessed at.
B.1 The contract (describe)
{
"protocol": 1,
"name": "acme/lint",
"version": "1.4.0",
"description": "Lint a checkout and report findings.",
"config": { "type": "object", "properties": {}, "required": [],
"additionalProperties": false },
"inputs": { "type": "object",
"properties": { "repo": { "type": "object", "properties": {
"path": { "type": "string" } },
"required": ["path"],
"additionalProperties": false } },
"required": ["repo"], "additionalProperties": false },
"outputs": { "type": "object",
"properties": { "ok": { "type": "boolean" },
"findings": { "type": "array",
"items": { "type": "string" } } },
"required": ["ok"], "additionalProperties": false }
}
protocol and name are required. description, inputs, outputs and
config are optional; an absent schema is the empty object. The three schemas
are the structural profile of JSON Schema in B.4 — not arbitrary JSON
Schema. An image enforces its own value constraints (ranges, patterns) and
reports a failure through the result's error.
B.2 The envelope (run stdin)
{
"protocol": 1,
"config": { "strict": true },
"inputs": { "repo": { "path": "/workspace/repo" } },
"context": {
"run_id": "…", "node": "lint", "attempt": 1,
"traceparent": "00-…-…-01"
}
}
config is the runner's params. inputs is the leaf's bound in values
minus the adapter inputs the runner consumed (§6.5); secrets are unwrapped here,
at the execution boundary, and nowhere earlier.
context carries the run/node/attempt identity and the W3C traceparent so an
image can stamp an artifact or join the Run's trace. Every member is optional
from the image's point of view; unknown members are ignored.
B.3 The result (run stdout)
Success:
{ "protocol": 1, "outputs": { "ok": true, "findings": ["a.py:3"] } }
Failure, on a non-zero exit:
{ "protocol": 1, "error": { "code": "lint_failed",
"message": "3 findings", "retryable": false } }
outputs is one value per declared out port. A non-zero exit is a step
failure whether or not an error document is present; error only makes the
record readable. An exit 0 with no readable result, an unknown protocol, or a
missing required output is a protocol violation: a non-retryable step
failure. stdout is capped; an over-cap result fails rather than truncating.
B.4 The JSON Schema profile
| JSON Schema | DSL |
|---|---|
object + properties + required |
record; required is a bare field, otherwise ? |
string / integer / number / boolean |
text / int / float / bool |
string + format: date-time |
time |
string + format: fct-secret |
secret |
array + items |
[T] |
object + additionalProperties: <schema> |
map(text, V) |
enum of strings |
enum { … } |
oneOf with a const tag |
choice |
anyOf: [T, null] |
T? |
$ref, allOf, patternProperties and prefixItems are outside the profile;
an image that needs them inlines the structure. Constraints (minimum,
pattern, minLength) are the image's own business: the protocol carries
structure, and the image validates values before producing a result.
B.5 Transport notes
The protocol is transport-neutral. The reference backend (runner.oci.fly)
runs the image with podman inside a machine of its own:
- the Machine image is the deployment's base (podman,
sleep, CA certs), not the customer image; podman pulls the customer image inside the VM, so a private registry needs no platform-side mirror; describeandrunarepodman run --rm <image> describe|run;- the Machines exec API returns
stdout/stderr/exit_codebut does not deliver stdin, so the backend writes the envelope withconfig.filesandrunredirects it:podman run --rm -i <image> run < /fct/envelope.json; - the Machine is destroyed on every path, including failure, and its lifetime
is bounded: the init process sleeps for the gate budget plus a grace period,
then
auto_destroyreleases it. A worker that dies mid-step therefore cannot leave a started Machine billing forever, and a delete that fails is retried from the deployment's machine ledger; - a worker that dies after starting a phase leaves the command running in the Machine. A retry reattaches to that Machine — the lease names it — and reads the same sidecar files within the attempt's budget, instead of pulling the image and running the phase again;
- the container receives
OTEL_EXPORTER_OTLP_ENDPOINT,OTEL_SERVICE_NAME,TRACEPARENTand thefct.*resource attributes, so an image's OTel SDK joins the Run's trace. A collector may run as a sibling in the same podman pod; the container reaches it on127.0.0.1.
A backend whose transport does support stdin (a local process, a hosted sandbox) writes the envelope directly and skips the file.
B.6 Versioning and errors
protocol is an integer. Version 1 is this appendix; a new member may be
added additively, but a breaking change bumps the version. An unknown version is
a check-time error (describe) and a run-time protocol violation (run).
Changelog
-
v1.48 — the image contract is cacheable. A typed container step may reuse the image's last published
describecontract from a deployment cache (bounded by a TTL) instead of provisioning a machine for it on every attempt; a miss or an unreadable row asks the image again, and the debugdescribepath is always fresh. (§6.5) -
v1.47 — an agent attempt reattaches to its session. A retry of an agent step (an in-machine harness or a hosted one) reads the non-secret handle a previous execution left — the machine and session id, or the hosted session and its turn baseline — and continues that session instead of provisioning a new machine and prompting the model again. The harness's own session decides whether the instruction was already admitted; an unusable session is released and replaced. (§6.4)
-
v1.46 — a container attempt reattaches to its Machine. A machine-backed runner looks up the live lease of the firing and phase before provisioning, so a worker restart (a deployment, a crash) continues the phase on the Machine that is already running it, within the original
timeout, instead of creating a second Machine and repeating the work. A Machine that is gone, stopped, or never started the phase is released and replaced. (§6.5, Appendix B.5) -
v1.45 — human gates. A step may use
kind: gateto suspend a Run pending human input. The gate'sout:ports define a form (records, enums, choices, optionals, secrets, lists, maps) rendered with the same expander as a manual trigger;in:provides display context. A pending gate is tracked so users can review all gates needing attention. An optionalconfig.timeoutnames a duration and adefaultresolution applied when it expires; without a default the gate remains pending until resolved or the Run is cancelled. Resolution produces the gate's outputs for downstream bindings and resumes the Run. (§3, §6, §7, §10). -
v1.44 — boundary ports are
inputs./outputs.A composite body reads its own boundary asinputs.<port>andoutputs.<port>(they replacein./out., which no longer resolve as path roots and now fail with a diagnostic naming the replacement). The words name the boundary record rather than the declaration keyword, so they are the same forunitandloopand do not repeat thein:/out:block key (§7, §8). The four reserved path rootsinputs,outputs,thisandabortjoinlistandmap: a declaration or import alias may not use them, so a sibling node can never shadow a boundary reference (§11). -
v1.43 — an agent step's
kindselects the harness. Two agent kinds may coexist — an in-machine server and a managed harness — behind the sameprompt/secret/ generativeout:contract; a deployment pins the one it runs. No new language surface: the kind was already an implementation choice, and a runner'sin:/out:stay the contract. -
v1.42 — choice literals in a typed binding. A binding source may author a choice as
{ tag: { …fields } }when the port or annotation expects a choice; the tag must name a variant and its record must conform. This is the same shape a choice value has on the wire, and it lets a typed input carry a tagged value — including a secret — without a producer unit (§4, §8). -
v1.41 — container adapter inputs. A container leaf may bind inputs the runner consumes before the image runs. They are part of the leaf's typed
in:but not of the image'sdescribepayload: the runner strips them before the contract check and the envelope. The reference adapter reservessource— a tagged image source withpublic { image },ghcr { image, username, token }andecr { image, token }variants — so the image reference and the way to pull it are one value. It is consumed at the execution boundary and never forwarded to the image (§6.5, Appendix B.2). -
v1.40 — container steps. A
containerrunner executes a leaf by running an OCI image through a deployment-provided backend. The image speaks a two-phase protocol (describepublishes its contract,runreads one JSON envelope and prints one result);openleaves the interface unchecked, a declared type forces the contract and the runner checks it beforerun(§6.5, Appendix B). The reference backend runs the image with podman inside a Fly Machine, so the customer image is pulled by the guest and private registries need no platform-side mirror. -
v1.39 — the old effect terminology is gone. The deprecated alias for a
kind:step no longer parses. Effect adapters live ineffect/and implementEffectWriter; a firing'sEffectResultis recorded aseffect, and the read model exposeskind_steps(thekind:steps that fired) witheffect_resultfor the latest one. Stored events, journal rows and columns are migrated. -
v1.38 — one step kind; effects are steps. The separate effect node is removed: a step is a reference (
use:), a provider-kind invocation (kind:), or an inline unit. Every step exposesterminated_at/attempt, so effects are ordered by the ordinary binding/guard rules. A step may have a node-levelwhen, and a leaf of anopen-output runner may declare zeroout:ports. The engine has no outcome set and no abort pass: a Run is done at quiescence (even with no effect) or aborted by the max-firings bound, a system error, or an operator. Static effect coverage is removed. The deprecated alias for akind:step was removed in v1.39. -
v1.37 — a sink firing reports its effect. Each sink adapter returns a locator (where the effect landed) and a one-line summary (what it did), recorded with the firing. A Run's result therefore points at its effects even when a sink produces no output of its own; an effect with no locator still reports its summary (§3, §10).
-
v1.36 — a recurring schedule can be paused. A deployment may pause and resume a schedule (a cron trigger's, in this implementation) without editing the factory: a paused schedule fires nothing, resuming arms the next occurrence without replaying the windows missed while paused, and Runs already admitted keep running until stopped individually (§10).
-
v1.35 — configuration values and optional port parameters. A
config(key: text, default?: text) -> textexternal port reads a deployment's configuration value at the Run's tenant scopes (factory → user → organization, as §4.3), with a deployment-wide tier allowed below them. The value istext, notsecret: it may be compared, reported, written to a file and edited. A missing key returns the default, or fails the step when no default is given. External-port parameters may now be optional (name?: Type): a call may omit one, and an omitted argument is not passed to the implementation. -
v1.34 — callbacks are expressions.
list::map(xs, x -> body)applies a callback expression to every element. The parameter is typed by the element, the body is pure (no external-port calls), captures outer sources, and the callback can appear only in a built-in's callback position — it is not a function value.list::compact(xs)drops thenoneelements of a[T?]and returns[T]. -
v1.33 — absence is a probe,
T?is an option, and records are total.Absenceis the evaluator's report that no value is available here: it is not a value, cannot be stored or bound, and a node's port map omits an absent port.T?is typed assome(T) | nonewith a canonical null encoding;?.navigates an option, plain.on one is an error,is some/is nonebranch, andopt::value(x)unwraps. Nested options flatten, an option is not a boolean, andsome/noneare reserved choice-tag names.name?: Tis sugar forname: T?: an omitted optional key decodes tonone. Every typed boundary is strict — a missing required key is an error at admission, binding and production — while an absent producer is still absence. -
v1.32 — credentials never come from the environment.
credential(key)resolves only from the stored scopes — factory → user → organization, narrowest first. TheFCT_CREDENTIAL_<KEY>fallback is gone: the environment is global, not tenant-scoped, so a key there could leak a credential across tenants. No deployment path — API or worker — reads it. -
v1.31 — no byte type. Raw bytes are deliberately not represented: dotFactory is a control plane, so its values are configuration, events and results. Binary work — uploading an artifact to S3, say — runs in a VM-based runner step with a real filesystem, not through a binding; a
bytesprimitive stays deferred, additive if a clear need appears (§4, §12). -
v1.30 — a seeded
prev's guard gates from the second firing. A seed is the loop's bootstrap, so the first firing contributes it unconditionally, exactly as an unseededprevcannot prevent the first firing. A guard on the binding gates from the second firing; a loop-exit guard that names the feedback producer (e.g.review.verdict is rejected) therefore no longer deadlocks a seeded loop. To skip the first pass on a condition, use a forward binding instead. -
v1.29 — maps. A first-class
map(text, V)type: text keys, one value type, structural conformance, JSON-object boundaries. Map literals use quoted keys ({ "team": "platform" });m.keyis a path lookup (a missing key is absence), while the reservedmap::built-ins providehas,at,length,keys,values,with,withoutandmerge— pure and positional likelist::*, withmap::atreturningNonefor a missing key. Maps replace onextends; secrets nested in a map are redacted as for any container. -
v1.28 — list built-ins, and a seed for
prev. The core provides a closed set of pure list operations in a reservedlist::namespace:append,concat,without,remove_at,find,contains,atandlength, with positional arguments (§8.1). They are immutable — each returns a new list — typed over[T], propagate absence, preservesecretwrappers, and reject a secret in an equality comparison.findreturns an index (int?);atandremove_atacceptint?so they compose with it. Aprevbinding may declare a first-firing seed:prev seen: [T] = [] then source(§10.1), which lets a loop accumulate a list from its first pass.listandthenjoin the reserved words; config remains literal data. -
v1.27 — a sink firing carries its execution identity. The engine gives a sink adapter the same opaque ids a
thisbinding exposes (run.id,node.id,step.id) plus the factory digest. An adapter that writes an externally visible artifact can stamp them on it — an S3 object's user metadata, say — so a listener can detect that the object was produced by the factory's own effect and avoid re-admitting it in a feedback loop. Factories still see only thethisrecord; the extra seal is the adapter's. -
v1.26 — a Run can be stopped by the operator. A deployment may abort a started Run on request: it aborts like a system error, with the operator's reason in
abort.reasons, the abort pass, and no further work. A Run stopped before it started ends immediately, with no abort pass and no effects. Stopping is idempotent; a finished Run keeps its outcome. Cancellation is no longer deferred (§12). -
v1.25 — runner interfaces are explicit, and outputs are fixed or open. Every runner declares
in:andout:, each a type or the keywordopen; an omitted side is a spec error (no implicit default). A typedout:is a fixed shape every leaf inherits;out: openfixes no shape — each leaf declares its ownout:, and the implementation produces a value for every declared port (§6.4). An open-output kind may be generative: it derives what to produce from the declared ports, which is how an agent's leaf types become the structure the model must return. A typedin:remains a minimum — the leaf binds its required fields and may pass more. -
v1.24 —
credentialis scoped. A deployment may keep named secrets at several scopes; the expected precedence, narrowest first, is factory → user → organization, then the deployment environment. A factory reads only its own tenant's secrets, the value stays asecret(redacted everywhere observed), and a management interface exposes metadata but never a value (§4.3). Implementations may scope differently — a local run need not have a factory or organization tier. -
v1.23 — a binding source may be a record or a list.
repo: { url: …, ref: … }builds the value inline from sources (paths, calls, literals), nested to any depth; each leaf is read when the node fires, and an absent leaf makes the whole value absent. A literal record or list is structural, so it is checked at load time against the declared type (§8). The grammar already admittedrecord/listin a source position; the parser now does too. A target stays a single port name — a record is supplied whole, never filled field by field. -
v1.22 —
configis the one static key. Arunner,trigger,sinkandstepcarry their static data under a singleconfig:key:triggerandsinkgain it, and a runner's kind fields (image, …) and a leaf'scommandmove inside it. Aunit/loopis a pure definition and carries no such field. Every block is now closed to a fixed key set, so the parser enforces §6.3 syntactically, with no kind registry; what a block'sconfigmay contain becomes the provider registry's concern (§12).configis literal data (§8): static, read before the Run, and never a binding source — the dynamic channel staysin/out. -
v1.21 —
loopis a declaration keyword.loop name:declares a composite unit that must contain aprevcycle — a load-time error without one — whileunit name:may or may not loop. Otherwise identical: both are scopes (§7, §10). A loop that is only implicit (aunitwhose graph happens to contain aprev) is still a loop; the keyword just states it. -
v1.20 — a closed language and typed runner interfaces. A runner declares its implementation's interface —
in:/out:(types) — and its staticconfig(a typed value); a leaf unit conforms to that interface, and a generic runner (no interface) lets each leaf declare its own ports. Every block is closed: its fields are the spec-defined ones plus those its kind declares, and an unknown or misspelled field is a load-time error, never silently ignored (§6.3).prompt:andauth:are no longer fields — an agent's instruction isprompt: textin the runner'sin:interface and its credential istoken: secret; a leaf'scommandis its kind's field (or anin:input). -
v1.19 — execution is defined over scopes. A scope (the root, or a composite body) runs to quiescence as one firing, and only its boundary ports cross; a unit is a scope, and it need not loop — a loop is a scope whose graph contains a
prevcycle. Sinks may appear in any scope, so a per-pass effect sits inside the loop's scope and a once-only effect sits downstream of it. Fixed §10.2, whose sinks referenced nodes in another scope. -
v1.18 — every receiver (port, leaf, sink) gets a secret as a secret, so it knows; the receiver unwraps it to use it and reports the marker.
-
v1.17 — a boolean context requires a
bool; no truthiness of numbers or strings;boolandintare distinct (true != 1). -
v1.16 — Python 3 is the reference for value semantics where the spec is silent; mixed
int/floatcomparison;%takes the sign of the divisor. -
v1.15 — no implicit
int→floatconversion. -
v1.14 —
floatis finite; overflow and underflow abort. -
v1.13 —
intis a signed 64-bit two's-complement integer; out of range aborts. -
v1.12 — restated
int's range. -
v1.11 — added the
secretprimitive (redacted at every observation). -
v1.10 — defined
float; named the valueNone. -
v1.9 — defined
text(UTF-8) andint. -
v1.8 — defined
None; distinguished it from absence. -
v1.7 — explicit loop-carried
prevedges; optional local binding types.
Public blog
A deployment may publish Markdown blog posts. Posts have a unique lowercase, hyphen-separated slug, title, summary and Markdown body, and are ordered by publication time, newest first. The blog index and posts are public. A site administrator can publish or replace a post through the authenticated API; publishing stores the content durably and makes it immediately public. The site administrator can also create and edit posts in the web UI, including importing Markdown and previewing it before publication.
The repository's content writer drafts articles for the hosted product at
https://factory.redbeardlab.com. Its articles use that URL directly and do
not instruct readers to set environment variables. API examples explain how to
create an appropriately scoped token in the hosted app and show a placeholder
for the bearer credential without embedding a real token. The content writer's
reviewers check these editorial requirements, and its publisher refuses to
create a draft issue when they are unmet, including after the review limit.
Your factories will appear here. Create one and open it beside this guide.