# One-shot approvals and cooperative policy

Schema v12 approvals authorize one exact operation by one named actor until a
bounded expiry. They are workflow controls, **not authentication**. Anyone able
to run the process as the state owner, edit the database, or change its files
can claim or change this metadata. Two voter IDs do not prove two people.

## Request, review, execute

Supply `approval request --operation-json` with the effect arguments of the
corresponding `LedgerService` method, excluding `actor` and `approval_id`.
The CLI's `--actor` binds the eventual executor. Requesting on behalf of a
worker therefore requires that worker's actor ID; a registered operator or
approver can review and vote using their own ID. Unknown actors are rejected.

For an existing entity `ent_example`:

```bash
op-sys approval request --action ledger.entity.patch \
  --target-type entity --target-id ent_example --reason 'Reviewed task update' \
  --operation-json '{"entity_id":"ent_example","patch":{"status":"done"}}'
op-sys approval show --id <approval-id>
op-sys approval decide --id <approval-id> --decision approve
op-sys ledger entity patch --id ent_example --patch '{"status":"done"}' \
  --approval <approval-id>
```

The returned `intent` uses `op-sys.approval-intent.v1`: action, ordered targets,
actor, resolved workflow/subject context, and a domain-separated SHA-256 hash
for every normalized effect argument. Object key order is immaterial; target
order, body, payload, patch, paths, metadata, relation endpoints, claim TTL,
idempotency keys, and the resolved workflow contract/strictness are material.
Omitted arguments receive the same defaults as execution. The full intent has
an `operation_digest`; approval ID and output formatting are not effect input.

Free-form effect values are not copied into approval output. Review the
original operation alongside these hashes. Hashes are not encryption and can
reveal guessed low-entropy values; never submit credentials as operation
metadata, actor/target IDs, review reasons, or context. Review reasons and
routing identifiers remain visible. Legacy context flags are equality
assertions, not a substitute for complete operation input. Old free-form
approval payloads are not copied into new records.

Pending and approved records expire at `expires_at <= now`. Requested TTL may
shorten, never extend, the effective policy TTL. Voting cannot revive expired,
revoked or consumed records. An unexpired denial can change through later
votes; denial is not a veto when the required approved count is met. Each
distinct registered voter ID counts
once. Execution checks actual approved votes against both the request's count
and the current effective requirement, with at least one vote for any explicit
approval ID, even when current policy requires zero.

Later policy changes recheck permissions and vote requirements at execution;
they do not rewrite an existing approval's stored expiry. Revoke outstanding
approvals when changing policy must cancel those grants immediately.

Consumption, its audit/event, and the authorized ledger mutation share one
outer transaction. Failure rolls them all back. A successful idempotent replay
returns its prior result before approval consumption; a non-idempotent second
use fails `approval_consumed`. Other stable reasons include
`approval_expired`, `approval_scope_mismatch`, `approval_insufficient_votes`,
`approval_intent_missing`, `approval_intent_invalid`, `approval_revoked`, and
`approval_denied`. A changed operation needs a new request, not a new vote on
the old digest.

Multi-operation batches carry a distinct `approval_id` on each gated inner
operation. A global `--approval` is accepted only for a single operation with
no inner approval ID; otherwise `batch_approval_ambiguous` is returned before
writes. Approval intents bind resolved inner operations, not reusable blanket
batches. Assign stable explicit entity IDs when requesting approvals for
newly created targets. A later batch failure rolls all consumptions back.

## Effective policy and roles

Policy precedence is base SQLite policy < canonical team `policy_defaults` <
the acting worker's registered worker-type `metadata.policy`. The operation's
subject worker does not select another actor's policy layer. Other workers do
not inherit that override. Policy documents reject unknown sections, malformed
selectors, unknown effects, non-integer/negative votes, non-positive TTLs, and
non-boolean strictness.

Scalar/default values use the later layer. Permission rule arrays accumulate
across layers: any matching explicit `deny` wins over every `allow`, including
wildcard and action-specific rules. A deny *default* can be overridden by a
later default or matching allow; it is not an explicit deny rule. Approval and
TTL rule arrays use the later layer's array. Within the resulting policy,
global default, wildcard, then exact-action default are considered; matching
vote rules take the maximum and matching TTL rules apply in order (last match
wins). Import evaluates each namespace/version pair independently, requiring
all permissions, the maximum votes, and the minimum resulting TTL.

`workflows.strict_contracts` follows the same scalar precedence. It requires a
contract for workflow-scoped mutations; unscoped generic records remain valid.
Explicit strict calls also require a contract. See the synthetic
[policy example](/docs/examples/approval-policy.json) for a base layer.

Canonical team settings contain an `operators` array:

```json
{"operators":[
  {"actor_id":"operator","roles":["operator"]},
  {"actor_id":"reviewer","roles":["approver"]}
]}
```

`operator` has operator-only capabilities; `approver` can manage approval
decisions/revocations but not other operator-only actions. Generic mutations
still use effective policy. Registered worker IDs take precedence over
colliding operator entries. An external actor string `system` has no operator
authority; internal reconciliation attributes its explicit internal work to
the system principal. Fresh state and migration bootstrap `operator` only
when no operator registry exists. Existing registries are not overwritten.
Use `save_team_config` for canonical changes, not edits to projected JSON.

## Offline state import and recovery

Request with `--action state.import --target-type state --target-id state_root
--bundle ./state.zip`, then pass that approval to `state import`. `--bundle`
and `--operation-json` are mutually exclusive. A verified manifest, its paired
workflow contexts, the actor, and a hash of the absolute target pathname bind
the intent. Moving the target or changing the manifest requires a new request.
Signed bundles must verify against the importing root; a retry that cannot
verify local trust fails closed too. Unsigned does not mean unchecked.

Stop every other op-sys process and external writer before import and keep
them stopped through success or recovery. The private import lock serializes
imports only; it does not enforce this shutdown condition or block arbitrary
external writers, policy changes, or revocations. Current policy authorizes
the entire reviewed replacement, including its imported policy/registry;
the imported policy is not a retroactive authorization source.

A private exclusive receipt is reserved at
`governance/imports/<manifest-sha256>.json`, outside the imported file set.
Bundles cannot import or export this governance tree. The verified snapshot
is migrated and its consumption/audit prepared in private staging before any
target file is replaced. The receipt binds every prepared publication file.
Governed import requires a database snapshot. An approval-ID collision inside
the imported snapshot fails closed rather than overwriting that record.

Ordinary failed restores release the reservation only after proven rollback.
A crash before publication can be reauthorized. A crash after publication can
be finalized without repeating restore only if the complete prepared file set
still matches and no SQLite sidecar exists. Any partial, changed, malformed,
or unsafe state returns `approval_import_recovery_required` and retains the
receipt. Keep writers stopped, retain the target/receipt/original bundle, and
use separately reviewed offline recovery; deleting the receipt to retry would
remove the replay guard. A consumed manifest cannot be re-imported at that
root, including under zero-vote policy. Zero-vote imports retain a receipt and
audit but do not fabricate an approval record.

## Upgrade and rollback

Migration 11→12 preserves old review data with NULL intent/digest: these rows
remain viewable/revocable but cannot authorize writes. Re-request needed work
with complete input. Handle the added `consumed` state and consumption fields.
The append-only migration history keeps previous v10/v11 origins and checksums.

Patch forward. Reverting to reusable approvals or unknown-actor authority is
unsafe. Any pre-upgrade restore requires an offline verified backup, retention
of the upgraded DB, proof of no later mutations or their explicit
reconciliation, and a trial restore at a new path. Older binaries do not enforce
the operator registry even if its metadata remains present.
