# Worker Runtime Contract

Workers are externally owned commands coordinated by `op-sys`.

Core does not define prompts, provider accounts, or native agent skills. It only defines the runtime payload, environment, and result shape used when a worker processes a claimed ledger entity.

## Protocol

The public generic protocol is:

```text
op-sys-worker-runtime.v1
```

The runtime payload is workflow-neutral:

```json
{
  "protocol_version": "op-sys-worker-runtime.v1",
  "entity": {},
  "workflow": {
    "namespace": "example.workflow",
    "version": "v1",
    "skill_contract": {},
    "instructions": "Workflow-facing worker guidance.",
    "metadata": {}
  },
  "claim": {},
  "events": [],
  "relations": [],
  "comments": [],
  "artifacts": [],
  "worker": {},
  "state_root": "...",
  "repo_root": "...",
  "runtime": {}
}
```

## Atomic state and lease ownership

Built-in ledger-service mutations commit primary state, the specified audit
entries, events, and idempotency results in one writer transaction. Worker
heartbeat intentionally emits its heartbeat event without a corresponding
audit entry. Session lifecycle/reconciliation writes and their audit/events
share the same boundary; this does not make process launch, process exit, or
filesystem work transactional.

Claim uses a conditional upsert. Heartbeat and release atomically require both
the requesting owner and a lease whose expiry is still in the future. They use
transaction-bound before images for auditing, including on supported SQLite
versions without `RETURNING`. An expired/previous owner cannot extend or delete
a new owner's lease. Treat `lease_missing`, `lease_expired`, and `lease_conflict`
as lost-ownership outcomes; stop ownership-dependent work and inspect current
state before deciding to claim again. Do not blindly retry the stale mutation.

Mutation events are a committed SQLite outbox. Post-commit notifications are
only wake-up hints; consumers must persist their event cursor and replay after
interruption. Idempotent service replay returns the original result without
duplicate audit/events. Policy and team launch context comes from canonical
SQLite settings, never a stale JSON projection.

## Environment

Both simple and prepared workers receive a new allowlisted environment, never
a copy of the caller environment. The inherited base is `PATH`, `HOME`,
`USERPROFILE`, `HOMEDRIVE`, `HOMEPATH`, `TMPDIR`, `TEMP`, `TMP`, `SYSTEMROOT`,
`WINDIR`, `COMSPEC`, `PATHEXT`, `LANG`, `LC_ALL`, `LC_CTYPE`, `LC_MESSAGES`,
`TZ`, `SSL_CERT_FILE`, `SSL_CERT_DIR`, and `REQUESTS_CA_BUNDLE`, when present.
Names are compared case-insensitively on every OS; ambiguous casing is rejected.
Python/loader configuration, Cloud/CI credentials, SSH agent/socket variables,
registry tokens and unrelated caller variables are not inherited.

Worker `env` supplies explicit string values. Names use ASCII letters, digits
and underscores, start with a letter/underscore, and are at most 128 characters.
NULs, non-string values and case-colliding names fail closed. There are at most
128 final variables, 16 KiB of UTF-8 per value, and 28 KiB for the entire
environment, including names, `=` separators and NUL terminators. The generated
`OP_SYS_WORK_ENVELOPE` counts toward these limits; an oversized envelope fails
launch rather than being silently truncated. Trusted OP_SYS context names
cannot be overridden by worker configuration.

Credential/token/key/password/secret/auth names and Cloud, CI, SSH and registry
prefixes require explicit opt-in in `metadata.worker.execution.secret_env`:

```json
{
  "worker": {
    "execution": {"secret_env": ["SERVICE_TOKEN"]}
  }
}
```

Pass this object as worker metadata and supply the corresponding `env` value
through private configuration. An opt-in never imports an ambient value; every
listed name must have an explicitly supplied value. Secret values are literal,
not `{entity_id}`-style templates. Non-secret values retain template expansion.
Rename public identifiers formerly called e.g. `ENTITY_TOKEN` to `ENTITY_REF`
if they are not credentials. The policy deliberately treats token-like names
conservatively. Arbitrary secret names must also be listed explicitly.

Default worker create/update/show/list results, `LaunchSpec.as_dict()`,
`resolve_worker_config()`, prepared-launch serialization,
worker envelopes, managed session launch records, and captured result/error/log
text redact declared secret values with `[REDACTED]`. Execution objects retain
private in-memory values to start the command; a returned environment copy
cannot mutate the frozen prepared environment. A secret overlapping a structural
field is rejected rather than changing protocol keys. Redaction covers literal
values and their JSON-escaped spelling, not arbitrary encodings or deliberate
exfiltration. Worker configuration remains private state, not a secret vault;
these controls do not encrypt it or erase earlier disclosure/history.
New worker audit snapshots and resource notifications are redacted before
storage/enqueue, so ordinary event synchronization does not forward configured
environment secrets. Existing canonical worker configuration and historical
records are not rewritten; review/rotate earlier disclosed values separately.
Do not round-trip a redacted display value into configuration: `[REDACTED]` is
rejected as an opted-in secret value. Omitting `env` from an ordinary worker
update preserves the private stored environment. Low-level state/record access
is not a redacted view and remains restricted to the state owner.

Invalid entries/bounds use `worker_environment_invalid`; non-string launch env
uses `worker_env_invalid`; missing secret opt-in uses
`worker_secret_environment_denied`; unsafe structural redaction uses
`worker_secret_redaction_unsafe`. A denied secret opt-in names the first blocked,
validated variable so its configuration can be corrected. Errors never echo
values or malformed variable names.

Stable generic environment keys:

- `OP_SYS_STATE_ROOT`
- `OP_SYS_REPO_ROOT`
- `OP_SYS_WORKER_ID`
- `OP_SYS_SESSION_ID`
- `OP_SYS_ENTITY_ID`
- `OP_SYS_ENTITY_TYPE`
- `OP_SYS_WORKFLOW_NAMESPACE`
- `OP_SYS_WORKFLOW_VERSION`
- `OP_SYS_WORK_ENVELOPE`

`OP_SYS_SESSION_ID` is set when the launch is attached to a session. The same value is available as `runtime.session_id` inside `OP_SYS_WORK_ENVELOPE` when present.

## Output budget configuration

Configure `metadata.worker.execution.output_limits` with any of these integer
byte budgets. Omitted fields use defaults; `null` or an omitted object selects
all defaults, never unlimited output. Booleans, strings, fractions, unknown
fields and out-of-range values fail with `worker_output_limits_invalid`.

| Field | Default | Minimum | Maximum |
| --- | ---: | ---: | ---: |
| `stdout_bytes` | 1 MiB | 1 byte | 16 MiB |
| `stderr_bytes` | 256 KiB | 1 byte | 4 MiB |
| `log_bytes` | 4 MiB | 1 KiB | 32 MiB |
| `line_bytes` | 256 KiB | 1 byte | 1 MiB |

KiB and MiB mean 1024 and 1048576 bytes. Stream/line budgets count incoming
bytes before decoding or redaction; LF is a line delimiter and is excluded
from line length. The log budget counts encoded JSONL framing and terminal
records, not only the worker's text. `op-sys schema worker-runtime` reports the
same defaults and hard bounds.

Resolved launches expose all four values as `output_limits`; a launch override
replaces the configured object and fills omitted fields from defaults. Managed
session launch and execution records retain the resolved budget. Prepared
launches freeze it: changing a display dictionary does not change execution.
Older records without this field select defaults when resolved; no schema
migration or historical record rewrite is needed.

## Controller, logs and exit receipts

Simple and prepared command runners use the same native process controller.
Linux/macOS workers start in a new session/process group. The controller retains
the original waitable leader, verifies boot/start identity, and uses group TERM,
a bounded grace period, then KILL. Windows workers are assigned atomically to
an unnamed, non-inherited kill-on-close Job Object; creation identity and an
owned process handle remain until job exit is verified. There is no
direct-child-only fallback when platform control is unavailable.

Stdout and stderr drain concurrently through bounded queues into private JSONL
logs. Only complete, valid UTF-8 stdout within every budget is parsed as a result.
Overflow stops the tree, withholds result application and reports
`worker_output_limit_exceeded`. Logs have a versioned header and terminal marker,
including the exceeded limit where applicable; terminal writes are fsynced.
Heartbeat callbacks and bounded draining continue during the shutdown grace
period while tree members remain alive, then heartbeats stop after tree exit.
Tree exit and pipe shutdown must be verified before result application or
isolation cleanup. Failed verification retains isolation for explicit recovery.

Session-backed runs store versioned `execution.process` metadata: exact session
and worker IDs, a random control locator, native PID/group or job token, process
start identity, and controller-owner PID/start identity. Raw native handles,
arguments and environment values are not part of that metadata. Private
`session-control/<control_id>/` files bind a cancellation request and durable
exit receipt to that exact run. An out-of-process client can request stop, but
only the owning controller signals its retained process group or job. A missing
owner or receipt is not proof of tree exit. Receipts prove process cleanup, not
rollback of ledger changes or results already applied.

### Stop, recovery and restart

`session stop` and `LedgerService.stop_session()` first authorize the exact
session/worker, verify its native and owner identity, and request cancellation.
They wait up to 15 seconds for the private exact-run exit receipt without holding
the ledger writer transaction. They then recheck authority, the unchanged run
binding and receipt, and atomically write the stopped record, `session.stop`
audit and `session.stopped` event. A ledger failure does not undo process exit;
the receipt remains available for a retry. A normal terminal completion that
already won the race remains completed/failed rather than being rewritten.

Missing, stale, foreign-platform, reused or unverifiable identity, unavailable
owner, or an unconfirmed exit fails with `session_process_unverified`; it does
not claim termination or send a PID-only signal. A timed-out request may still
be handled later by the owner. Stop inside an enclosing ledger write transaction
fails with `session_stop_transaction_active` to avoid blocking the controller's
heartbeat/finalization behind its own waiter.

`session stop --record-only` (`stop_session(record_only=True)`) is explicit unsafe
record recovery: it sends no cancellation and proves no process exit. It writes
`metadata.record_only_stop=true`, audit `session.stop_record_only`, and event
`session.stopped_record_only`. Normal verified stop writes the flag as false;
callers cannot supply this reserved provenance flag. Record-only recovery does
not authorize restart or isolation removal; the original controller may continue.

`process_state` and its compatibility alias `lifecycle_state` distinguish `live`,
`exited`, `unverified`, and `identity_reused`. `pid_alive` is a diagnostic only;
`terminal` describes the recorded status, not tree-exit proof. A legacy/manual
session with a dead PID remains unverified. Reconcile marks an active managed
session failed only when an exact receipt proves tree exit and its exact owner
is confirmed gone; a live/unknown owner may still be applying results.
Restart requires a terminal record **and** a verified receipt, then creates a
fresh pending session without the old process binding or runtime/isolation
fields. Stored managed process identities cannot be replaced or removed, and
managed terminal writes require exit proof except for explicit record-only stop.

External Python launch users must use `ProcessController` with
`OwnedProcessControl`, bind `prepared.with_process_control(control.metadata())`
in `on_started`, and persist it with `mark_work_launch_running()`. After the
controller returns, `complete_work_launch()` requires that bound prepared object,
matching state/session metadata, exact native exit code and durable exit receipt.
It revalidates complete output budgets and redacts results before applying them.
A stopped session cannot apply a late external result. Missing proof retains
isolation and performs no result application/finalization/cleanup. A manually
supplied PID/exit code or session-less external completion is insufficient;
use `WorkerRunner` for supervised session-less execution. Display-only prepared
payloads are not executable capabilities. The private files are cooperative
state-owner records, not attestations against code running as that same owner.

Run reports include `reason` and `log_path`. Custom simple runtimes without a
managed state root retain logs under an OS temporary directory with a fresh
private per-run name; their caller owns log retention/removal. These runners do
not create a ledger session merely to hold a log.
Simple custom runtimes receive the minimal base environment, not credentials
reconstructed from redacted envelope fields; declared additions use the
ledger-backed prepared launch path.

Process groups are lifecycle control for cooperating commands, not containment
of commands deliberately escaping their group, closing inherited pipes and
daemonizing. Do not run hostile or self-daemonizing commands. Copy/worktree/branch
isolation is change management, not an OS security sandbox.

## Identifiers and managed isolation

The built-in ledger service validates requested IDs, the fetched worker, and
every fetched candidate before lease expiry or a built-in claim. Service
failures keep their field-specific reasons. The launch adapter validates IDs
again when it receives requested, fetched, or claim-returned runtime records,
including records from a custom ledger, and maps an unsafe runtime-boundary
failure to `unsafe_runtime_identifier` without including the value.

An opaque custom claim implementation controls its own internal mutation order,
so this contract cannot attest that validation preceded work performed inside
that implementation. It does guarantee that an unsafe value returned by that
implementation is rejected before any subsequent op-sys-managed isolation,
path, branch, log, or process operation.

Opaque IDs are ASCII, 1–128 characters, begin with an ASCII letter or digit,
and then use only ASCII letters, digits, `_`, `-`, or `.`. The values `.` and
`..`, path syntax, whitespace, controls/format characters, leading option
syntax, and Unicode confusables are invalid. Worker, entity, event, and relation
types plus comment and artifact kinds remain constrained to the stricter
lowercase, letter-first, 1–64-character subset advertised by `schema show`.

Copy isolation roots, Git worktree roots, and run branches use a SHA-256-derived
component plus a generated run token. Automatic session logs use a random run
token. Human IDs remain in the envelope/session metadata and never select a
managed filename. Stored `execution.isolation` metadata comes from the
isolation manager's canonical result. Manual/public session writes cannot
supply non-empty isolation metadata or claim the managed worker-session launch
marker. Only the private built-in launch-manager registration capability may
persist both; copying the marker into a payload is not authorization. Execution entity/worker IDs,
execution entity/worker types, launch worker type, and launch/match entity
references are validated exactly before operational session decoding or PID
inspection. Read-only store and export paths remain available for legacy
recovery.

An arbitrary custom ledger receives the ordinary public registration call,
without a private op-sys keyword, even if it exposes a similarly named method.
It controls mutation order and persistence inside that call, so op-sys cannot
attest to those internals; it still validates the returned session and
authoritative readback before any later managed path, process, or isolation
action. The private built-in method separates the supported public/manual API;
it is not a sandbox against arbitrary code already executing inside the
op-sys process.

Every managed recursive cleanup re-resolves the target, requires it to be a
direct child of the expected managed parent, rejects links/reparse points and
mounts, and verifies a matching per-run marker. A pre-existing or legacy
unmarked directory is left in place for operator quarantine/review. Files
copied back from a worker are revalidated as safe relative repository paths;
worker-created symlinks are not followed.

These controls contain managed path selection and change application. Copy and
Git-worktree isolation are not an operating-system security sandbox and do not
constrain arbitrary process access available to the worker account.

## Result JSON

Worker commands should write structured JSON to stdout:

```json
{
  "events": [
    {
      "type": "incident.triaged",
      "payload": {
        "severity": "high"
      }
    }
  ],
  "comments": [],
  "artifacts": [],
  "release": {
    "claim": true
  }
}
```

Core appends events to the claimed entity, attaches comments and artifacts through generic ledger methods, and releases the claim when requested.

The result root must be a JSON object. `events`, `comments`, and `artifacts` are optional arrays; when present, every item must be an object. `release` is optional, but when present it must be an object.

Workflow-specific lifecycle interpretation belongs to the workflow convention, not the runtime protocol.

`workflow.skill_contract` is populated only from discovered workflow files that parse as strict `op-sys.workflow-contract.v1` contracts. Malformed discovered contracts are ignored by runtime resolution and are never exposed to workers as valid skill contracts.

`workflow.instructions` and `workflow.metadata` are optional convenience fields derived from the strict skill contract when present. They do not change the ledger model.
