Skip to content

Latest commit

 

History

History
1623 lines (1362 loc) · 123 KB

ops.md

File metadata and controls

1623 lines (1362 loc) · 123 KB

Agent-facing basal operations

Basal serves the flow tool alongside codemode. Core selects it with the tool capability tag basal:flow.manage/v1; until core selects that tag and retires its wrapper, agents use core's scoped relay to flow.install, flow.dry_run, flow.disable, flow.enable, flow.list, flow.instantiate and flow.instance.end. Caller identity comes from attributes.agent_id on the daemon's core-owned route scope stamp, never request parameters. flow.health is an operator and core pull view, not relayed to agents. Core does not poll it; basal pushes durable owner notices for failure episodes and rate auto-disables.

The daemon delivers agent-facing codemode calls directly to basal; prefrontal does not forward them. See codemode.

Basal routes to prefrontal and admits only reserved:prefrontal as that module. Stored flow, template and package versions may still name prefrontal-core in their approved bytes; basal uses prefrontal when running those versions without changing their bytes or approval hash. New manifest bytes must use prefrontal. Re-sending an identical stored version remains idempotent.

Package management is not agent-relayed: package.register is available to the attested operator and core; package.get, package.catalog_status, flow.instance.ensure, and flow.instance.remove are core-only. The attested operator is a caller on a route the daemon stamps as the reserved callosum module, the operator's own module. A plain local caller is a process holding the daemon's direct connection key, on a route with no scope, which the daemon cannot vouch for. A plain local caller refused any of these receives operator_attestation_required, consistently with the other management operations; other unauthorized callers receive not_permitted. See package manifests.

Shapes below use type names, | for alternatives, and a one-element array to describe each array item. ? on a request key means optional. Reply keys are always present unless a key is marked optional with ?. object and any describe open JSON values.

attribution.read

Read-only management query, admitted only for the daemon-attested, unscoped reserved:astrocyte caller. All other callers, including the operator, core, local callers and scoped routes, receive not_permitted.

Request: {"method":"attribution.read","params":{"after":0,"limit":100}}. after is a nonnegative integer sequence cursor (default 0); limit is an integer from 1 to 500 (default 100). Unknown fields and invalid values are refused with invalid_params. Response: {"facts":[object],"next":integer|null, "through":integer}. Facts are in permanent insertion order after the cursor; next is the last returned sequence when another page remains, otherwise null. through is the highest sequence in the read snapshot, or 0 for an empty feed. Resume a fully drained feed from through to discover later facts.

Each fact contains fact_id, supersedes, subject, alfonso (the owning agent id, or null when the owner is not an agent), parent, workload, task, project_id (null), effective_from_ms and recorded_at_ms. Bodies are under 4 KiB and contain ids and open names, not prompts, source text or paths. workload is 1–64 bytes of lowercase ASCII letters, digits, _, -; task additionally permits . and is at most 128 bytes. Facts cannot be updated or deleted. Each insertion atomically queues attribution.fact for ck.{acct}.event.basal.attribution_fact.v1, without a reader suffix, with the fact body and Nats-Msg-Id equal to fact_id.

Flow facts begin at first approval, or instance creation. Their ids are basal:flow:<flow_id>:v<approval version> or basal:flow:<flow_id>:created for instances. A later approval changing owner appends a fact superseding the prior flow fact; same-owner approvals do not. Session facts use basal:session:<exact session name>, subject runner and harness broca, and never supersede. A flow session names its parent flow; a program session names the admitted bind's runner/harness/session only when basal holds all three. The current bind holds only harness/session, so program parents are null; basal never guesses a runner. Program ownership uses the worker's attested on_behalf_of_agent, otherwise the agent's id.

Migration backfill uses current flow ownership, not reconstructed historical owner changes. Never-approved flows and program sessions whose owner record has already been pruned are excluded. A backfilled session's effective_from_ms is a lower bound, not the exact send time: it uses a retained intent/reservation time where available, otherwise the flow's first approval/instance creation or the program's admission time. Live session facts use the prepare clock. Samples and regeneration instructions are in attribution-facts-v1.

basal diagnostics.findings

Read-only management query, also listed in basal's flow_operations for self-diagnosis flows. Request: {"method":"diagnostics.findings","params":{"window_ms":21600000}}. Omitted/null params or window use six hours; integer windows must be in 1–604,800,000 ms. Unknown params and invalid windows are errors, never clamped. The v1 contract defines the reply: {"result":{"generated_at_ms":…, "window_ms":…, "findings":[…]}}. Every finding includes check, stable key, severity, positive count, first_seen_ms, last_seen_ms, summary, samples, and hint.

Admission uses only daemon route stamps: unscoped reserved:callosum and reserved:prefrontal; authorized core-owned agent Head scopes with no flow/run identity; and authorized core-owned scopes carrying a nonempty flow_id, except Worker scopes. Workers, foreign/unauthorized owners, direct local callers and dev desktop apps are refused. No repair, delivery, reconcile or enable operation is performed. A failed store read is an error frame.

Check Key Severity Threshold / evidence
event_reader bus error Immediately while the configured reader is disconnected or reports an error/restart.
flows_failing flow ID warn / error Enabled flow with at least 3 counted consecutive failures; any runtime auto-disable is error, even without 3 failed runs (rate saturation can disable a flow). Count is the failure streak, or 1 for an auto-disable without failures.
runs_overdue deadline, deferred warn Unfinished run at least 1 minute past its recorded deadline, or active deferred call at least 1 minute past retry_not_before; allows the normal engine sweep.
reconcile_pending runs, decisions warn Reconcile run admitted at least 1 hour ago, or open decision card created at least 1 hour ago; avoids nagging during normal human response time.
grant_lost disabled warn Immediately for flows disabled with reason grant_lost. Count is disabled flows.
agent_move_frozen freeze warn An agent frozen for a move for at least 6 hours: its flows run nothing until the move is released or aborted. Samples name the agent and the cut.
moved_flows_pending approval warn Flows that moved in from another computer approved there and have waited at least 24 hours for this computer's prefrontal to report the same code active. Count is waiting flows; samples name the flow and its agent.
outbox_stuck undelivered warn Owner-notice, late-result wake or attribution-fact bus publications pending for at least 1 hour, plus other undelivered outbox rows, excluding permanent secret-revocation failures. A bus-only event is never a pending call.
outbox_stuck secret_revocations error Immediately for undelivered secret revocations with failed_at: grants may still be live.
quarantined schedules_and_fires, outcomes warn Any schedule.corrupt audit events or quarantined call outcomes in the requested window. Counts are audit events or outcome rows.
worker_pool flows, codemode warn Immediately while either pool records a spawn error or retry backoff.

Standing conditions ignore the lookback, including old failure streaks and lost grants. Only quarantine history is windowed. Basal does not record reader outage start times, restart counts or typed provider cause codes, nor pool failure start times: those findings use the report time and fixed safe category codes (reader_failed, reader_connecting, spawn_backoff), not raw errors or invented outage durations. Run reconcile state-entry time is also unavailable; its admission-age proxy can include time spent running before reconciliation. Pending runs without a recorded deadline cannot be diagnosed as past-deadline. Scheduler quarantine is historical audit evidence, not proof that corruption remains unrepaired; fire corruption does not reliably record a fire ID.

Samples contain only identifiers, counts, status flags, codes and times—never scripts, arguments, event/card/outbox bodies, grant references or provider error text. Store scans are not row-limited. Findings sort by severity, descending count, check, then key. Each has at most 5 samples; count is before trimming. Basal removes samples first, then tail findings, until the compact whole response body is strictly below 65,536 bytes. Omission is not proof of health or complete evidence; there is no continuation or truncation field. Hints are guidance, not instructions to execute automatically.

flow tool

Use flow with an action and the fields for that action only:

  • install: script_path, manifest_path. Submits your files for approval, including warnings and a capture dry run.
  • dry_run: flow_id, optional version, and window (for example "6h") or a sample event in trigger. Runs in capture mode, without live effects.
  • disable: flow_id, optional reason.
  • enable: flow_id. Resumes your flow only if you disabled it yourself, not if the operator or runtime disabled it.
  • list: optional flow_ids. Lists only your flows, with state, approved version and last run.
  • instantiate: template, params, expires_in, optional version (defaults to the newest approved, not newest registered).
  • end: flow_id of your template instance.

Each action invokes the corresponding management operation below as the agent identified by the daemon's stamp. The operation retains its existing authority checks, including flow ownership. Do not pass agent_id, author, inline code, or a live dry-run mode. Success is tool-result/v1: a model-facing text summary and the complete operation JSON in structuredContent. Refusals retain the management operation's or upstream provider's typed code, message and detail.

The text uses plain language, not embedded JSON. Install replies identify the flow version and full code hash, and report the approval-card status (including the card ID when available). Install and dry-run replies describe the replay window, schedule caps and partial traces, then group equivalent run outcomes into at most five lines with counts; any omitted outcomes are counted. Distinct warnings appear as individual lines when present. Per-run IDs, arguments, results and the complete report remain in structuredContent for programs.

Install reads only the script and manifest through the AFT tool provider's file.read_exact operation. A direct call uses the caller's own head scope, which must name an agent and be owned by reserved:prefrontal with the daemon's owner_authorized stamp. A relayed call can still use prefrontal's short-lived flow-read/… scope. Basal opens the file-provider route with the invoking route's stamped scope owner, reference and epoch, and the same bind identity.

Relative paths resolve at your root in AFT, not basal's working directory. Basal verifies each returned SHA-256 digest and enforces 1 MiB for the script and 64 KiB for the manifest, then installs the exact UTF-8 bytes. A missing or incorrect read scope is flow_read_scope_missing, a changed digest is flow_read_digest_mismatch; there is no fallback to basal's own file access. AFT's file_read_exact_* refusals pass through unchanged.

If instantiate.version is absent, basal selects the newest approved, unheld version from its own records. If there is none, it refuses version_not_approved. Registration alone is not approval.

Operations that check an agent against core's agent.list registry tell an absent agent apart from a registry that could not be read. When the registry answers without the agent, the operation keeps its final refusal (agent_unknown, or for install an install_refused naming UnknownAgent). When the read fails (core restarting, a timeout, an unreadable or ambiguous reply), flow.instantiate, flow.install, template flow.dry_run and flow.instance.ensure refuse with agent_registry_unavailable and detail {"retryable":true}, write nothing, and can be repeated unchanged. It is never a verdict that the agent does not exist. Basal reads the registry before taking its SQLite write lock.

An opaque top-level call_key deduplicates flow calls durably per carrier, bound to the stamped agent. Repeating it returns the recorded success or refusal without re-reading files or repeating effects. A key cannot be reused for another agent. If basal stops after admission but before recording a reply, the key returns outcome_unknown: inspect the flow before issuing a new key. A cancelled route does not undo an admitted management operation.

flow.instantiate

Creates or extends a bounded template instance of an approved version, without raising an approval card. Agents act for themselves using their daemon-stamped identity. The attested operator and core must name the target agent_id. An explicit version may be held; its runs wait until the hold clears.

flow.instantiate parameters:

{"template":"string","version?":"integer","params":"object","expires_in":"string","agent_id?":"string"}

Agents must not supply agent_id. Replies contain flow_id, template, version, agent_id, canonical params, expires_at (Unix milliseconds) and new. Same-value calls reuse the id, move its version and extend but never shorten expiry. Templates specifies bounds, limits and refusal details.

Both explicit-version flow.instantiate and flow.instance.ensure refuse not_found for an unknown version, version_revoked for a revoked version, and version_not_approved for a declined or expired version. A pending version refuses version_pending with {"retryable":true} before any agent registry call. No instance, generation or schedule changes until the named version is approved.

If a template's on_create run cannot be admitted, flow.instantiate refuses with on_create_not_admitted and detail.reason (for example persona_off, disabled, draining, or rate_limited). The instance is not created or reopened. Try again after the condition clears.

package.register

Registers exact, immutable package or template bytes. The operator, core and admitted reserved modules may register, subject to package ownership. Only core may supply catalog.

Package registration and ordinary flow.install refuse trigger.on_create outside a template with trigger_on_create_requires_template. A template with on_create but neither events nor a schedule gets trigger_kinds.

{"script":"string","manifest":"string","catalog?":{"install_id":"string","name":"string","version":"string","abilities":["string"]},"persona?":"object"}

The reply includes package, version, code_hash, new, and outcome: card_raised (with install_id), approved, declined, or deferred_persona_off (pending with card_id:null). A new version normally asks for consent, even if policy would auto-approve a plain flow. An eligible persona approval instead reports approval:{kind:"persona"} and card_id:null. Approval applies to that version only and does not create instances or schedules. Several personas can bind the same version without changing its approval kind.

catalog.abilities must name keys declared by the manifest, or the call refuses invalid_params. The catalog values and install_id are fixed by the first registration; basal mints the id if catalog is omitted. Supplying different catalog values on a repeat (including adding them later), or supplying an id already held by another version, refuses catalog_conflict. A package cannot use an installed flow's id, and flow.install cannot use a package's id; both refuse flow_id_taken.

On a repeat with the same bytes, basal checks the catalog identity first, then refuses version_revoked for a revoked version or returns approved or declined without filing another card. A filed card is returned unchanged; if the send was not confirmed, basal resends the same attempt. An expired, refused, withdrawn or definitively unsent card can be refiled with the same registration id. If consent is unavailable, the version stays pending and the call refuses consent_unavailable with {"retryable":true}; repeat the registration to retry.

Persona codes

The optional persona input to package.register and flow.instance.ensure has the shape described in Packages, including an optional display-only title. When the call supplies persona, the version's persona result, when present in the reply or refusal detail, is {approved, reason, grew, card}. approved identifies an approval by persona (not a binding to an already card-approved version). reason is a code or null, grew is an array, and card is filed, deferred_persona_off, or none. filed means a card is pending for this version, while an already-answered card reads none with the reply's outcome giving the decision. Declined and revoked versions omit this member.

Refusals:

Code Meaning
package_owned_by_other_module Another caller owns the package; detail.owner names the owner.
package_unregistered A reserved module tried to ensure or remove an unowned package.
persona_source_mismatch The daemon-stamped caller cannot assert the supplied source.
persona_catalog_unavailable Catalog observations could not be obtained or disagreed with validation; retryable.
persona_unknown The switch pair has no persona record.
persona_off The pair is off; the instance cannot be enabled. Also the reason recorded on a switch disable.

Reasons a version takes the card path: persona_source_unverified (catalog source), persona_source_agent (agent source), a bound violation, persona_grew (wider grants), or persona_card_exists (a card is being sent, may already have been sent, or has been decided). Growth entries are {kind, item} with kinds op_added, op_mutate, sink_added, digest_louder, and target_added.

Bound violations, in evaluation order:

Code Meaning
bound_template A parameterized package or template.
bound_op_unresolved A granted op does not resolve.
bound_op_model_tool A granted op is a model tool.
bound_model_cost A model cost cap is present.
bound_op_for_target An op uses for_target.
bound_net Network access.
bound_fs_write Filesystem write access.
bound_fs_read Filesystem or Git read access.
bound_private_content_providers Private content providers.
bound_claims Claims.
bound_destinations Destinations.
bound_facts Facts.
bound_sink_room A Room sink.
bound_sink_target A Digest recipient other than $self.
bound_break_through break_through: true.
bound_board_target A board entry other than $self.
bound_status_target A status entry other than $self.
bound_board_read_target A board read entry other than $self.
bound_audience An audience is set.
bound_max_targets A non-default target limit.

On activation, losing a granted op closes the version's persona approval with reason bound_op_unresolved. Runs pinned to it are cancelled with error_kind: "persona_bound_violation".

package.catalog_status

Only the daemon-attested reserved:prefrontal caller may report the status of a package's catalog pin. Reports can apply to pending versions but never grant approval or request consent.

{"package":"string","version":"integer","state":"fresh|stale|revoked","observed_at_ms":"integer","catalog?":"object"}

observed_at_ms is the reporter's observation time in Unix milliseconds. A stale report holds instance runs and stores the optional catalog status details (for example {"state":"held","code":"catalog_status_stale","stale_since_ms":900100}). A fresh report omits catalog and clears both the hold and the stored details. If the reporter goes quiet, the last applied state stands.

The reply is {"applied":true} if the report took effect, or {"applied":false} if the observation is no newer than the stored one or the version is already revoked. revoked applies even if its observation time is older than or equal to the stored one. It revokes the version and its instances and stops their schedules for that version. No later report can undo a revocation.

An unregistered version refuses version_unregistered with {"retryable":true}; retry after registering it. A version registered without catalog values refuses invalid_params.

flow.instance.end

Only the owning agent, the operator, or core may end a template instance. Params {"flow_id":"string"}. Reply {"flow_id":"string","ended":"boolean"}; ended is false on a repeat. Ending prevents all further admission and scheduling, but keeps state and history. Creating the same valid values later reopens that id. Non-template flows return package_not_template; an unknown id returns not_found to the operator or core. Other callers receive not_permitted.

flow.install

Params:

{"script":"string","manifest":"string","author?":"string|null","loop_override?":"boolean"}

manifest is the exact manifest text, not a JSON object; its bytes enter the code hash. author defaults to the caller (operator defaults to operator); agents can author only for themselves and local callers only as local:unverified. Local callers share the unverified author identity local:unverified, cannot replace another author's flow, and must declare at least one digest sink, which names an agent or audience that can receive the flow's digest messages. Only the operator can set loop_override true to bypass the check for mutations that can trigger the same flow.

Reply:

{"flow_id":"string","version":"integer","code_hash":"string","card_id":"string|null","attempt":"integer|null","state":"pending|approved|declined","outcome":"card_raised|approved|declined","new":"boolean","warnings":"any","dry_run":"any","install_id?":"string","approval?":{"kind":"card|policy|import|unknown","rule?":"string"}}

warnings is an array of warning objects or null if unavailable. dry_run is the capture summary described under flow.dry_run, {error: string} if the capture failed, or null if unavailable.

Basal binds approval to the exact script and manifest bytes and files install cards directly on Cingulate. card_raised returns the durable install_id and attempt. approved returns the stored approval provenance; it does not raise another card. declined is final for those bytes; a new version can ask again. Repeating an approved install, including a superseded version that was never revoked, returns new: false. A revoked version cannot be reinstalled, and a never-approved version older than the approved version cannot raise a card.

The flow tool's file reads remain bounded to 1 MiB of script and 64 KiB of manifest. It verifies each returned digest before installing the exact bytes. It does not fall back to reading local files when an exact read fails.

For a manifest with secrets, Basal calls claustrum secret.request_flow_approval with {name, flow:{flow_id,version,code_hash,install_id}, target, methods?} once per declaration, without holding the SQLite write lock. It checks each statement's install identity and request id before filing and refuses secret_statement_mismatch if they differ. The vault's statement bytes are filed unchanged. Approving a version that declares secrets requires a card grant for those exact bytes; an install policy cannot approve it.

An unavailable vault or Cingulate returns consent_unavailable with detail.retryable: true; install again to retry. If the card may have reached Cingulate, retrying sends the exact same attempt and prepared statements, even after their expiry. A grant accepted on time still approves the matched version if its answer arrives late. A definitely unsent, expired or refused attempt ends; the next flow attempt uses a new install_id. Basal does not retry interactive filing in the background. Secret cleanup is pinned to the old id, so it cannot affect a later attempt.

Secret cleanup is durable best-effort work in the outbox. A declined, expired, rejected or stale pending install card enqueues a version-specific claustrum secret.revoke_flow_grants {flow_install_id,flow_version} in the same transaction that settles the card. Uninstall enqueues each secret install's id without flow_version. Approval of a replacement enqueues retirement of the old version, but does not send its revoke until its last run, durable call/model obligation and executing dispatch have ended. The engine drains due rows outside SQLite transactions; failures remain queued with bounded exponential backoff. Successful {"status":"revoked","grants":0} is also final success. When the consent provider definitively rejects a card after vault preparation, Basal queues the same cleanup, including unconsumed approval requests. Uncertain sends retain their original identity. Transport failures, store_error, and typed readiness, resource-busy, scope and vault-unavailable failures retry a revoke. Other refusal codes persist outbox.failed_at and failure_code, stop future drain/wake attempts and log one warning without provider prose. Failed rows are retained as unresolved history, not marked delivered. Migration 45 preserves populated journal/mailbox/Broca rows while adding the vault deferral CHECK value and durable cleanup-failure columns. Historical manifest inspection first probes for a secret declaration. Once the declaration is found, a stored decode failure keeps the row secret-declaring, with one warning: cleanup remains queued and policy cannot bypass explicit card provenance. Unrelated historical rows avoid that full decode. Approval validates the candidate's stored manifest before scheduling it; conservative secret inspection does not make an unreadable candidate runnable.

Uninstall preserves card history. Repeating an already-approved version after uninstall does not restore it or raise a fresh card: restoration requires a new version with a fresh install id. Approving a still-pending version after uninstall is a fresh approval decision, not revival of an old grant.

When the consent provider advertises card text, the flowInstall body includes dry_run_text, a plain-language summary of the capture. The shape is:

{"summary":"string","would":["string"],"problems":["string"]}
  • summary, at most 300 bytes, says when the flow runs. For a schedule that is how many runs the replayed window would have had and how often. For an event trigger it names the events and says that none were replayed. When runs stopped at a read the dry run captured, it adds "Each run stopped at its first read, because a flow that isn't approved yet doesn't read live data." (or "Some runs stopped at their first read, …" when only some did).
  • would lists at most 8 lines of at most 200 bytes, one for each distinct thing the flow did, in the order it first did each: for example "Wake 'ag_x': 'Wait ended: deploy'", "Read every board in its audience" or "Store 3 values". When there are more, the eighth line is "and N more".
  • problems lists at most 8 lines of at most 200 bytes, each naming a run by its due time and what went wrong. Only real failures count: a refused call (outside the manifest, or a size or validation refusal), a script error before the script saw any captured call, passing the deadline, or running out of a CPU, memory or stack budget. A captured call's rejection is the dry run's own doing and is never a problem, and neither is a script error that follows one. When there are more, the eighth line is "and N more". If the dry run itself could not run, the only problem says so.

All of it is UTF-8 with control and direction-changing characters removed, cut on a character boundary with "…". Text the script supplied (agent names, titles, error messages, paths) is always in single quotes and at most 80 bytes; a straight quote inside it becomes ’. Committed examples of real output, for flows/board-hygiene and the remind-at template, are in test-vectors/dry-run-text/.

Any author may request a self, workspace or global audience. Workspace ids must exist (unknown_workspace). Basal's managed install policy can approve an install requested under the route identity of an agent's main session (its head scope) for that agent, or for a workspace that contains a project it currently leads. The policy checks the allowed network hosts. A global audience, fixed recipients or secrets always require a card grant. Policy approval commits with the version at intake and includes approval: {kind: "policy", rule}. Neither path reads an approval from prefrontal.

A manifest carrying params or template is refused with params_require_package, naming the field. Those fields belong to templates, registered as packages, rather than ordinary installs. A manifest containing $self in any agent field is refused with self_requires_package: $self is available only in package manifests.

An agent-owned flow may name only its author in static sinks[].agent, status[], board_read[], claims[].agent and facts.targets[], even if the operator installs it in that agent's name. Manifest agents resolve through the catalog from display names or stable ids; each must resolve to the author's stable agent_id. A foreign target is refused with code foreign_agent_target and a message naming the field, target agent and author; no version or card is recorded or raised. Operator-authored flows and local installs may name any known agent. Audience-based sinks use $audience instead of static recipients and may request broader reach regardless of author. Ids ending in _ and exactly 16 lowercase hex characters are refused with flow_id_reserved before basal records a version or asks core to raise its install card, because that namespace is reserved for package instances.

flow.install_status

Read-only; prefrontal, Cerebellum and the operator only. Params: {flow_id, version?}. The id can be a flow, package, template or instance. Without version, Basal selects the current approved flow or instance version (the newest approved version for a package or template, even if held). If none is approved, it selects the highest stored version. An instance cannot be queried for a version it never materialized.

The result contains state and code_hash. A missing version returns { "state": "unknown", "code_hash": null }. Approved or superseded versions that have not been revoked return active, or held while a catalog pin is held, with approval: {kind, rule?}. A persona approval reports {kind:"persona"}. Pending versions return pending, declined or expired according to the card. A legacy rejection with a provider refusal reason stays pending; one without a reason is declined. Revoked versions return revoked without approval provenance.

An instance reflects its parent's version, except that its own revocation also makes it revoked. Catalog versions include pack from registration and catalog if a report supplied it. A fresh report clears catalog. See the wire samples. Basal advertises the flow-approvals/v1 capability in the daemon catalog.

Flow version change events

Basal publishes ck.<account>.event.basal.flow_version_changed.v1 when a version is approved or first revoked. Template and package changes carry kind: "package" and the parent's own install id. The parent's notice comes before the kind: "flow" notices of instance versions newly runnable or revoked by that change. A new instance version and a direct instance revoke also carry kind: "flow". An instance already revoked on its own is not revoked again. Holds and supersession publish no notice.

The outbox commits with the version change. The notice has an empty payload, flow_id and seq headers, and event key <flow_id>:<version>:<seq>, with seq increasing for each version. Prefrontal can call events_get {event_name: "flow_version_changed", event_key, version?: 1} to retrieve the exact body bytes as a JSON string, with their SHA-256 digest, event name, event key and published_at timestamp (null before the bus ack is recorded). A wrong event name is indistinguishable from an unknown key. The decoded body is:

{"kind":"flow|package","flow_id":"string","version":1,"code_hash":"64 lowercase hex digits","install_id":"string","state":"active|revoked","at_ms":0,"seq":1}

flow.revoked_install_ids

Prefrontal only. Params: {after?, limit?}; omit after for the first page. The default and maximum limit are 200. The reply is {install_ids, next} in revocation order, with next: null on the last page. A non-null next is an opaque cursor to pass as after. A cursor not issued by basal or a limit outside 1–200 returns invalid_params.

For a refill, first take a retained bus position (your cursor if it remains valid, otherwise the current position), then page the listing to next: null, then consume from that position. This replays revocations that landed during the refill, including those that missed its last page. Start over if the bus position expires before the refill finishes. A revocation enters the listing in the same transaction that records it.

Pinned v1 samples for the notice, events_get, and refill are in test-vectors/flow-version-changed-v1/.

flow.dry_run

Params:

{"flow_id":"string","version?":"integer|null","params?":"object","mode?":"capture|live|null","trigger?":"any","window?":"string|null"}

Absent mode means capture. Absent version selects the approved version, otherwise the newest installed version. Absent trigger replays schedule fires over the time window ending now; window is its duration, such as 6h. Capture is available to the operator and owning agent; live only to the operator. Local callers are refused.

A registered template accepts params, validated and canonicalized exactly as flow.instantiate (param_missing, param_unknown, param_out_of_bounds, with the same detail). Omitting values returns template_values_required. Only an agent may dry-run a template package: activation self is its route-stamped identity and activation params contains the canonical values. Operators have no agent identity and cannot use this package-template request; no agent_id override is accepted. The template name defaults to the newest registered version.

A template instance may be dry-run by its owning agent or the operator, without params. It uses its bound values and recorded grant boundaries, with self bound to its owner and version defaulting to its approved version. Supplying params on an instance, including null or unchanged values, returns params_not_allowed. Both template and instance dry runs are capture-only; mode: "live" returns not_permitted. No instance is created and no instance quota is checked or consumed.

The effective manifest substitutes grant and timing placeholders before replaying the supplied window or synthetic trigger. With no synthetic trigger, a one-shot at template or instance runs once immediately, with trigger.dry_run: true and trigger.due set to now, rather than waiting for the timestamp. Supplied timestamps still must satisfy the instantiate rules; an existing instance's already-bound timestamp is not revalidated against now.

An ordinary-flow request carrying params returns params_require_package, with {"field":"params"}. The ordinary dry runner also refuses stored manifests carrying params or template with params_require_package, naming the field.

Dry run validates the stored manifest under its author with the same self-only rule and foreign_agent_target refusal as install, including versions recorded before the rule was enforced.

Reply:

{"flow_id":"string","version":"integer","summary":"any","state_reset":"boolean"}

state_reset is always present: true when the selected version's declared state_epoch differs from the flow's recorded epoch, or from any retained instance's epoch when naming a template. Otherwise it is false, including for a template with no instances. This preview reads real state on one snapshot, but never clears it. The optional manifest state_epoch is an integer from 1 to 2147483647, default 1, and is covered by the version's hash and approval.

The summary is the dry-run trace, including calls and sink writes. Its journal uses an isolated scratch store; live mode dispatches eligible query ops to real hosts and is not a guarantee of no external effects. Its fields are:

{"mode":"capture|live","window":"window shape below","partial":"boolean","runs":[{"run_id":"string","trigger_id":"string","trigger":"any","state":"string","result":"any|null","error":{"kind":"string","detail":"string|null"},"ending":"string|null","partial":"boolean","calls":[{"position":"integer","kind":"string","module":"string|null","op":"string|null","args":"any","outcome":"outcome shape below|null","action":"live|captured|local|refused","partial":"boolean","sink?":{"agent":"string","requested":"string|null","cap":"string|null","effective":"string|null","policy":"string"}}],"calls_total":"integer"}]}

error may be null. If a replayed trigger is refused before a run can be admitted (for example, by a concurrency limit), its runs-array entry instead contains {trigger_id: string, trigger: any, admission: string}. sink is present only for digest calls. Large args are represented as {truncated: string, bytes: integer}. Outcome is {fulfilled: true} or {rejected: any} (the rejection code extracted from the result, or null); null outcome means no outcome. calls is capped at the configured listing limit (default 200); calls_total counts all calls. window is one of these shapes (times here are RFC 3339 strings):

{"kind":"synthetic"}
{"kind":"events","covered":"null","note":"string"}
{"kind":"schedule","requested":{"from":"string","to":"string"},"covered":{"from":"string","to":"string"},"due_times_in_window":"integer","due_times_is_lower_bound":"boolean","replayed":"integer","capped":"boolean"}

A one-shot template replay has window shape {"kind":"at","at":"string","replayed":1,"dry_run":true}. A schedule's covered may be null when no fires are replayed. partial marks traces affected by simulated calls: capture rejects external reads and mutations rather than executing them, so subsequent script branches may differ from a live run. It does not imply live effects.

flow.private_content_providers

Read-only management query for broca's private-content model-call gate. Only the daemon-attested module principal reserved:broca on a verified unscoped route may call it. Every other caller receives not_permitted. Request parameters cannot supply identity.

Params:

{"flow_id":"string"}

Reply:

{"flow_id":"string","version":"integer","code_hash":"string","providers":["string"]}

The list comes from the flow's currently approved version, in manifest order; an absent field returns providers: [] (base set only). version and code_hash identify the approval for broca's per-version cache. Template instances return their template version's manifest list, not instance parameters. Unknown flows and flows without an approved version both receive flow_not_approved, without revealing which flows exist. The query takes no write lock and makes no network call. See the private_content_providers manifest field.

flow.audience

Only daemon-attested reserved:plexus may call this query with call_service and no flow scope. Other routes receive flow_audience_caller_refused. Unknown fields and malformed parameters receive flow_audience_invalid_request.

Params:

{"flow_id":"string"}

Reply (machine-checked by audience::audience_reply_matches_documented_shape):

{"flow_id":"string","audience":"audience shape below","revision":"sha256:<hex>"}

The audience shapes are:

{"kind":"global"}
{"kind":"workspace","workspace_id":"string","project_ids":["string"]}
{"kind":"agent","agent_id":"string"}

The audience comes from the currently approved version's exact manifest, not a newer pending install. An unknown flow receives flow_unknown; a known flow without an approved version, or whose approved version declares no delivery audience, receives flow_not_approved. Basal enforces one approved head per flow, so it cannot return Prefrontal's flow_audience_conflict.

For a workspace audience, project_ids lists that workspace's registered projects, sorted with duplicates removed. If membership cannot be read, the query refuses with flow_audience_unavailable. The query does not rewrite a stored audience ID. revision is sha256: followed by the lowercase SHA-256 of compact, key-sorted JSON containing only audience and flow_id. Approval of another version with the same audience leaves the revision unchanged; a change to the audience or its workspace project IDs changes the revision.

See flow audience wire samples.

flow.disable

Params:

{"flow_id":"string","reason?":"string|null"}

The operator or owning agent may disable. Absent reason becomes disabled by request. When an owning agent disables a flow that the persona switch paused, the disable becomes the agent's own and survives switching the persona back on.

Reply:

{"flow_id":"string","state":"disabled","changed":"boolean"}

flow.enable

Params:

{"flow_id":"string"}

The operator may enable a flow unless it involves a retired agent. An owning agent may undo its own disable, or a grant_lost pause after restoration polling was stopped; it cannot undo an operator or automatic disable. Local callers are refused. A standing retirement returns the typed agent_retired refusal, including retirement evidence in detail, even to the operator. If the flow's named persona pair is off, enabling is refused with persona_off, even for the operator and even if the flow has a different disable cause. A flow without a named persona is held only when its version has bindings and all of them are off.

Reply:

{"flow_id":"string","state":"enabled","changed":"boolean"}

flow.persona.switch

The operator and a daemon-stamped operator app can switch a bound package and persona pair on or off. An unstamped local caller is refused with operator_carrier_required, as on the Flows screens. Use package and id from a row's persona object as package and persona_id, respectively. A row shows the instance's named persona, or the version's sole persona if the instance has none. It omits persona when there is no named persona and the version has no bindings or has several.

{"package":"string","persona_id":"string","on":"boolean"}

The reply is {package, persona_id, on, changed, instances, cards}. changed says whether the pair's setting changed; instances counts flows whose enabled state changed. A named instance follows only its own pair. A version's unsent card and instances without a named persona are held only while all of that version's bindings are off. cards is empty for off. Every on call checks pending versions, even if changed is false. The sweep reports each visited version in ascending order as {version, outcome}: filed (sent by this sweep), card_raised (already sent), stale (superseded), declined (a card was declined), deferred_persona_off (switched off again), or the version's error code. When there are no pending versions to visit, cards is empty. An unbound pair is refused with persona_unknown.

flow.list

For operator-facing summaries and bounded history, use flow.overview and flow.details below. flow.list retains its existing agent-facing contract.

Params:

{"flow_ids?":"array of string|null"}

Only an object is accepted, with no other keys. Omitted or null flow_ids means all visible flows; an empty array selects none. The operator sees all flows; an agent whose core-owned scope is vouched for by the daemon sees only its own; a local caller sees only flows authored as local:unverified. Core and other callers are refused. Requested invisible and nonexistent ids are both silently absent. Entries are ordered by flow id.

The reply shape below is validated by crates/basal-module/tests/list_contract.rs.

Reply (machine-checked by list_contract):

{"as_of":"integer","flows":[{"flow_id":"string","state_epoch":"integer","state":"enabled|disabled|unapproved","approved_version":"integer|null","approval":"approval|null","install_checks":[{"version":"integer","error":"string"}],"install_cards":[{"version":"integer","attempt":"integer|null","state":"pending|approved|declined|expired|rejected|stale","rejected_reason":"string|null","disposition":"string|null"}],"pending_version":"integer|null","disabled":{"by":"operator|owner|auto|core|persona","reason":"string","at":"integer"},"last_run":{"run_id":"string","state":"string","ended_at":"integer","error_kind":"string|null","error":"string|null"},"needs_reconcile":"boolean","grant_losses":[{"flow_id":"string","provider":"string","grant":"string","grant_label":"string","echoable":"boolean","run_id":"string","version":"integer","revision":"integer","state":"polling|stopped","failures":"integer","next_poll_at_ms":"integer","lost_at_ms":"integer"}],"agent_retirement":{"agent_id":"string|null","agent_reference":"string|null","provider":"string","action":"string","at_ms":"integer"}}]}

disabled and last_run may each be null, but their keys must be present. All times are Unix epoch milliseconds. pending_version is the newest undecided installed version (with a card or awaiting policy confirmation), or null; approved_version is null until approval. state uses the same approval-first computation as flow.health. last_run is the most recent finished run, not an in-flight run. For a run that did not succeed, last_run.error_kind is the run's stored error kind (such as script) and last_run.error is its error detail flattened to one plain line and cut to 200 characters, ending in … when cut; both are null for a successful run. The flow tool's list text adds the finish time, kind and error line after a failed run's id and leaves successful runs' lines unchanged. needs_reconcile is true if any run awaits reconciliation. The disable's actor kind, reason and time are the recorded disable, or null after enabling. by is operator, owner (the owning agent), auto (the runtime's loop protection), core, or persona (the persona switch). A core disable may mean core revoked the version, holds no install of that version, or approved a different code hash for it; it may also mean grant_lost or agent_retired. Losing core's approval also clears the approved version, so the flow lists as unapproved; approval of a newer version clears that stop, but does not override an operator or owner stop.

Template instance entries additionally contain template, version, canonical params and expires_at in Unix milliseconds. Persona and ordinary entries omit those keys. Expired and ended instances remain visible to their owner and the operator. The enable state is independent of ending and expiry; enabling cannot reopen an ended or expired instance.

install_cards is always an array of {version, attempt, state, rejected_reason, disposition} records, including declined, expired and rejected requests; rejected_reason and disposition are null unless core reported a rejected status, and each is limited to 256 bytes. An attempt is null when no core card key was received. Both flow.list and flow.health also report approval for the current approved version: null when none is approved, {kind: card}, {kind: policy, rule: string}, or {kind: unknown} for approval whose provenance core did not supply. install_checks is always an array of {version: integer, error: string} records for pending versions whose last confirmation failed; a successful card raise or approval clears that version's error.

flow.overview

The route must be unscoped and either attested as reserved:callosum or direct with the daemon's operator_app stamp (operator-app/v1). That stamp admits recognized release desktop apps and trusted development builds, not federated harnesses (with a fed- prefix) or the OpenCode plugin's shared channel (alfonso with session prefrontal or prefrontal-core). An unstamped or excluded local route still lists locally authored flows and can request an install with an unverified-local card, but receives operator_carrier_required here. Prefrontal, Occipital and Magic Context use the same code for an unstamped local app, so the desktop can show one "trust this build" notice. Core, agents and other modules receive not_permitted. The same admissions and refusals apply to flow.overview_watch, flow.details, flow.templates and flow.uninstall, before parameter decoding.

Params (an object with no other keys, or null for defaults):

{"agent_id?":"agent_…","workspace_id?":"string","include_removed?":false,"removed_limit?":50,"removed_cursor?":"string"}

Reply: {as_of_ms, flows: [...], removed_count, removed_next_cursor}. Live rows are always sent in full, ordered by flow_id. Times in the phone flow reads are integer Unix epoch milliseconds, with *_at_ms names (the snapshot time is as_of_ms). Each flow contains:

  • flow_id, title, purpose, version, owner. The approved manifest supplies purpose and version; otherwise the newest installed request supplies them, including a declined or expired request when no version was ever approved. Title prefers the approved title, then the newest pending request's title, then the flow id. owner is that version's author agent id, or null for an operator or unverified local install. A row without any stored manifest has null purpose and trigger.
  • audience: {kind:"global"}, {kind:"workspace", id, name}, {kind:"agent", id}, or null. The workspace display name is entorhinal.enumerate {workspaceId:id}'s matching workspaces[].name. An absent name or failed registry read becomes name:null, never a lost flow or a failed list. Repeated workspace ids share one name lookup.
  • state: precedence is removed, pending_approval (no approved version), disabled, needs_reconcile (any run needs reconciliation), then enabled. A newer pending request does not hide a working approved version. Declined/expired-only flows remain pending_approval; their individual decisions appear in details, not as new overview states.
  • disabled: {by, reason} or null. The actor kinds are operator, owner, auto, core, and persona. persona means the persona switch disabled the flow; the owning agent's own disable remains owner while the pair is off. A disable can coexist with removed.
  • trigger: one plain line. Intervals render as every 5 minutes, cron as cron */5 * * * *, Europe/Madrid (UTC when no zone is given), one-shot template times as at 2026-10-24 09:00:00 UTC, and events as on plexus github_ci_job_failed (repo cortexkit/*). Multiple events are joined with ; and header filters with , . Basal supports one schedule per manifest, not a schedule array. Template timestamps are parameter-resolved.
  • last_run: {at_ms, outcome} for the latest finished run by finish time, or null. No run output appears here.
  • Template instances additionally have template and expires_at_ms.
  • Template and package instances have params, the stored bound parameter object ({} for a package without parameters). They also have made_by when the recorded maker differs from owner: {kind:"agent", agent_id}, {kind:"module", module}, or {kind:"operator"} for a copy the operator created through Connected Devices on a daemon-attested reserved:callosum route. An absent made_by means the maker is the owner or was not recorded. A NULL maker in the store means "not recorded", as for instances that predate creator tracking. Extending or re-ensuring an existing instance does not change its recorded maker.
  • An ensured template or package copy has managed_by in both overview and details while the current flow.instance.ensure record names that copy. {kind:"persona", persona_id, title?} names the persona that keeps the copy in place; title is omitted if not recorded for the copy's version. {kind:"module", module} names the reconciling module when the ensure is not tied to a persona. A copy made with flow.instantiate omits managed_by, even if it runs a persona-bound version or the same agent also has an ensured copy of that package. Plain flows omit it too.
  • Copies also have icon when declared and name: {text, parts} when a display pattern fits. Both come from the newest approved template or package version, even if the copy runs an older version. The patterns use the copy's stored params. {agent} uses the owner's display name, or the stable id for a known agent with no display name. If the owner can't be looked up, patterns needing {agent} are skipped; the read still succeeds. The text writes times in UTC. The parts array contains {"text": ...} and {"time_ms": ...} pieces, so clients can show times in their own zone. When name is absent, show the existing title.
  • An instance with a persona record for its current version additionally has persona: {package, id, source_kind, off, reason}. source_kind is module, person, catalog, or agent. A module source also includes persona.module, the name of the module that shipped the persona. off is the switch state for that package and persona, not the instance's disable cause. reason is the persona record's reason code or null. persona.title is present only when the binding has a stored display title. Unbound flows omit persona. The same member appears in flow.details.

Optional filters combine with AND. include_removed defaults to false. removed_count always counts all matching removed flows, regardless of the page. Only include_removed:true appends a page of removed rows, ordered by removal time newest first and by descending flow_id for ties. Older rows whose removal time was not recorded come last. removed_limit is an integer from 1 through 200, default 50. To read more, pass the previous reply's opaque removed_next_cursor as removed_cursor with the same filters. New removals that sort before the cursor don't shift later pages; start without a cursor to see them. removed_next_cursor is null when no more removed rows follow or when they were not requested. An out-of-range limit or malformed cursor is invalid_params.

workspace_id selects only that workspace audience, not global reach. agent_id must be a stable agent_… id, not a display name; it selects global audiences, that agent's workspace audience, that agent audience, flows owned by the agent, and audience-less flows with a static digest sink reaching it. Static display-name targets resolve through Core's paginated agent.list, as at install; failed target registry reads return the existing retryable agent_registry_unavailable refusal rather than guessing a match.

Workspace membership comes only from Entorhinal's live placement: agent.fleet_identity {} on its management query surface. Its raw wire reply is {result:{agents:[{agentId,workspace?:{id,name},...}],...}}; the transport unwraps result once. Only the exact agentId matches, and an absent agent or absent workspace means no membership. An agent belongs to at most one workspace. For an agent-filtered overview, this registry is read exactly once, before the store snapshot; Core's stored workspace_id is not used. If the read fails, the reply additionally contains workspace_membership:"unavailable": workspace reach cannot match, but owner, static target, agent and global matches still work. The key is absent on success and on unfiltered overviews. Store reads take no write transaction; all registry calls happen outside the store snapshot and outside any write transaction.

flow.overview_watch

A management query with watch delivery, replacing polls of flow.overview. It accepts exactly the same params and validates them under the same caller admission as flow.overview, including the admitted desktop app. Its snapshots carry removed_count and, by default, omit removed rows. A request can still opt into a removed page with include_removed:true.

The first StreamData frame contains the current answer. After that, basal wakes the watch on relevant committed flow, install, card, package, template and finished-run changes. Approving a new package or template version can change a copy's name or icon without changing its running version. The watch also wakes when core starts, updates or clears a temporary install hold (for example, because catalog status is stale), or when a live run starts or stops needing operator reconciliation of an unknown call outcome. No timer reads the store while nothing changes. Changes coalesce into at most one evaluation and snapshot per 3 seconds per watch; a change inside the window is retained until its end. Reads of Entorhinal and prefrontal happen outside write transactions. A change only in Entorhinal's membership or workspace names, or in prefrontal's agent names, appears on the next basal change or on reconnect, not through a separate registry watch.

Frames follow app-read-watch-v1:

{"frame":"snapshot","digest":"<sha256>","body":{"as_of_ms":0,"flows":[],"removed_count":0,"removed_next_cursor":null}}

body is the unmodified current flow.overview answer, and digest is the SHA-256 of its encoded bytes. Change detection ignores only as_of_ms, since snapshot time alone is not a content change. An unchanged answer sends no frame. If the encoded snapshot exceeds 196,608 bytes, the frame is instead {"frame":"hint","digest":"<sha256>"} and the app reads flow.overview.

An initial read failure ends with the read's SDK Error frame. Later transient read failures retry after 5 seconds without emitting; a refusal ends with the read's own Error. Cancellation, route loss or module stop ends with an empty SDK StreamEnd, not a JSON end notice. At most eight overview watches are open across basal. A ninth receives watch_limit_reached with the plain message basal already serves 8 overview watches; close one first. Cancel or route close releases capacity immediately.

flow.templates

Uses the same admission and refusals as flow.overview. Pass {} or null. The reply is {templates: [...]}, ordered by name, one row per template or package that has an approved version. There is no paging. Each row gives the newest approved version, name, title (null if not declared), purpose, and params in the order declared in that version's manifest. The row also has icon when declared. Each parameter has name, type, required (true for all current declarations), and its declared bounds or enum values. A parameter includes title and an enum includes a labels map from values to display text when declared. Packages without parameters have params: [].

requires.modules is the sorted, de-duplicated list of external module IDs explicitly named in the newest approved manifest's op grants (ops[].module) and event triggers (trigger.events[].module). It is [] when there are no fixed external requirements. Module settings written as $params.* are left out because they are chosen per instance. The list omits Basal itself and Prefrontal (including its legacy name prefrontal-core) because both are always present. It also excludes sinks, which describe output delivery, and private_content_providers, which are for Model Runner routing rather than module calls made by the template. Clients compare these IDs with the daemon catalog themselves; flow.templates does not report module availability.

copies counts live instances across all versions of that name. Removed and expired copies do not count; disabled copies do. made_by.agents: true means the approved version has a template parameter declaration and is eligible for agents to call flow.instantiate. made_by.personas lists persona ids registered to that approved version, sorted by id. made_by.persona_titles maps those ids with a stored title to their display text and is omitted if none have a title. Each key is omitted when it does not apply; an ordinary package without either maker type has made_by: {}.

flow.details

Params:

{"flow_id":"string","runs?":20}

runs is an integer from 1 through 50, default 20. Unknown flow ids return not_found. The reply is the overview entry (including removed flows), plus:

  • manifest: the approved manifest JSON, or the newest installed request when nothing is approved. For package/template instances this is the registered manifest, not script bytes or the parameter-resolved grant copy.
  • installs: newest version first, with version, code_hash (hex), requested_by (author agent id, operator or local), requested_at_ms, approval:{kind:"card"|"policy"|"unknown",rule?}, and state:"pending"|"approved"|"declined"|"expired"|"rejected"|"stale". decided_at_ms is present only when stored on the card or install. Superseded approvals remain approved history. A recorded card identifies the card approval path even while pending; absent provenance is unknown. Policy approval includes its stored rule. Package/template instances have no per-instance install/card request records, so their installs is empty: requester, request time and approval provenance are not fabricated from package registration.
  • runs: newest admission first, bounded by runs, with run_id, trigger (schedule, the event name, or manual), admitted_at_ms, ended_at_ms, outcome (stored run state), error_kind, and error. Nullable values are null for unfinished runs or absent failures. Admission time is not script start time: it can be earlier when a run waits for its slot. Basal does not store a script start timestamp, so no started_at_ms is claimed. Failure detail is rendered as one plain line of at most 200 UTF-8 bytes, removing terminal escape sequences and control characters. No script, run output, result payload or call journal is returned.

flow.display

Title lookup for Callosum's incoming call cards. Only daemon-attested reserved:callosum may call it, using call_management with no scope selector and a 2-second client timeout. Other callers receive not_permitted. It is for display only, not for admitting or rejecting a flow-scoped call.

Params:

{"flow_id":"string","flow_version?":"integer|null"}

Reply:

{"title":"string"}

Omit flow_version or send null to get the same title as flow.overview and flow.details. With a version, the title comes only from that flow version's stored manifest, falling back to the flow ID if it has no title. An unknown flow or a version not stored for that flow receives flow_unknown. See flow display wire samples.

flow.uninstall

Params: {"flow_id":"string"}. Reply:

{"flow_id":"string","removed":true,"changed":true}

An already removed flow returns changed:false. Unknown flows return not_found. Core-managed persona/package instances return managed_by_core; the operator must change the persona configuration instead of racing Core's reconciler. Template instances are ended just as by flow.instance.end, including their lifecycle event.

Uninstall keeps all history, records operator removal (operator for the operator, operator:local-direct for the admitted desktop app), uses the normal disable path to stop schedules and subsequent calls from runs in flight, and refuses queued event receipts so they cannot replay even after a reinstall. New notices are not admitted. flow.enable returns flow_removed for an operator-uninstalled flow. Core-removed packages and owner-ended templates retain their existing independent enable switch; enabling them never reopens their removed instance. A new installed version remains removed until normal approval commits; approval clears removal and the uninstall's disable, but not a pre-existing operator pause whose reason was preserved. Like an operator disable, uninstall takes over owner/runtime pauses. Reapproving or reinstalling the same already approved version does not restore the flow.

Migration 39 reuses the existing flows.removed bit and adds nullable flows.removed_by and flows.removed_at columns for the removal audit. Existing ordinary flows remain unremoved; existing removed instances keep their bit, with unknown audit fields left null. No history tables are rebuilt or deleted. Approval of a fresh ordinary version clears those audit fields with removal.

Synthetic, handler-generated examples (including refusals and SHA-256 hashes) are in test-vectors/flows-phone-v1. phone_vectors_match_real_dispatch_and_sha256sums checks every byte against real dispatch. Set BASAL_PRINT_PHONE_VECTORS=1 for that test with --nocapture to print the generated file map when intentionally updating the contract.

Health and owner notices

flow.health.consecutive_failures counts finished failed and engine-mismatch runs in admission order since the latest success. Cancelled runs neither count nor reset it. Readiness rejections, agent_retired, version_revoked, and deadlines backed by recognized typed scope rejections are exempt. Event-body fetch refusals such as event_not_visible count, even though no script started. The flow stays enabled: failure counting is not a new auto-disable policy.

Basal enqueues failing once when that streak reaches three, then recovered on the first succeeded run after that alert was enqueued. Recovery re-arms the latch; successes before three produce no notice. The independent rate breaker enqueues auto_disabled and still raises its operator re-enable decision card. The run finish (or rate disable), episode latch and notice enqueue commit in one transaction. Episodes use a persistent, per-flow increasing integer; auto-disable gets its own episode without clearing an outstanding failing latch.

The outbox publisher sends notices to prefrontal over the bus on ck.<account>.event.basal.flow_owner_notice.v1, without a reader token. The payload contains exactly notice_id (<flow_id>:<episode>:<kind>), flow_id, owner, version, kind (failing|auto_disabled|recovered), consecutive_failures, error_kind, phase, failing_since_ms, run_id and at_ms. owner names the flow's owner from basal's own record when the notice is enqueued: {"kind":"agent","agent_id":"<id>"} for an agent-owned flow, {"kind":"operator"} for an operator install, and {"kind":"local"} for an unverified local install. A template or package instance names the agent the instance runs for. When basal has no stored owner, the notice omits owner (never null) so prefrontal falls back to its own install-table lookup as before. Rows already in the outbox keep their old body. Times are Unix milliseconds. Error kinds contain only an error code, never failure detail text: it is truncated to 128 bytes and bytes outside [a-z0-9_.:-] become _. phase is preamble before script activation or script afterward; it is null for recovery and auto-disable. Recovery has null error_kind and zero failures, and retains the episode's first-failure time. Auto-disable uses the most recently admitted run's id and version, even when that run is not a counted failure; without any admitted run, basal warns and skips the notice instead of sending an invalid id. Exact JSON payload vectors live in test-vectors/owner-notice/vectors.json.

Only the oldest unpublished notice per flow is eligible, even during backoff. Failed publishes retry durably from 250 ms up to 30 s. A retry preserves the payload and Nats-Msg-Id (notice_id) so JetStream can deduplicate a publish whose acknowledgement was lost. A broker acknowledgement completes the row for basal; it does not mean an owner has read the notice. Unpublished notices at least one hour old are reported under outbox_stuck.

bus_published_at is the only completion marker used for owner notices. Notices already marked as published are not sent again, including historical notices marked that way when bus delivery was introduced to prevent replay. Unpublished notices stay queued and use the bus retry deadline only.

Obsolete install/disable owner-outbox rows without a consumer are discarded; install card status and operator decision cards remain authoritative.

Stored-value epochs in management replies

Each flow.list.flows[] and flow.health.flows[] entry includes integer state_epoch: the epoch of that flow id's current stored values, not necessarily its approved version's declared epoch. Existing flows start at 1. Health also includes last_state_reset_at, an RFC 3339 UTC timestamp or null if never reset. It timestamps the epoch-reset admission even if there were zero keys to clear. Both fields apply independently to package and template instances.

Core-only package.get returns the exact registered bytes plus integer state_epoch (that version's declaration, default 1) and, when instances exist, instance_state_epochs, an object mapping each retained instance flow id to its recorded integer epoch. Removed, ended and expired instances are included because they can still own stored values. No instances means the map is omitted. Core compares its values with the declared epoch and renders "Upgrading clears this flow's stored values (every instance)" when they differ. See packages.

The version's approval is approval of the reset, not a separate card. Only kv is cleared, at the first admitted run with a differing epoch, atomically with the admission and epoch update. Earlier admitted runs must finish first; events follow normal bounded-backlog and eligibility rules, and planned schedule fires wait for retry during that boundary. Rollback to a different epoch resets again. An epoch-busy flow does not stop other flows' planned fires from being admitted in the same scheduler pass. Approval or dry run alone resets nothing. Token/rate windows, schedule positions, event receipts/backlog, deduplication records, journals and decision cards are preserved. The durable state_resets log records flow id, old/new epoch, keys cleared and reset time.

Target flow scopes

For an audience flow's targeted module call, basal uses its reserved carrier route to prefrontal for flow.target_scope:

{"flow_id":"flow-id","version":1,"agent":"stable-agent-id","expires_at_ms":123456789}

expires_at_ms is the asking run's absolute deadline. Core checks that the version is approved and not revoked and that the agent belongs to its audience. It replies with {ref, epoch, delegates, expires_at_ms}, where the reply's expiry is the scope's actual lifetime. The scope is owned by core, carried by basal, and stamped with {flow_id, agent_id}. Its delegates attribute is true only when an approved op grant declares for_target: "delegate".

Basal caches the live refs for each flow and target agent, and a run keeps using the first ref it got for each target. It asks core only when no cached ref covers the run's deadline, on replay, or after that ref's scope ends or changes. For a later deadline, core registers a new ref and leaves older ones valid until they expire, so a run already using one is never cut off. There is no target scope close op: expiry and install revocation clean up all such scopes. Revoking an install ends every target scope for the flow. Provider route opens use these selectors exactly as they use the flow's own selector. A scope close during a call is a lost reply, never evidence that a mutation was unsent.

Core carrier operations: board.read and work.unsettled

Deploy a prefrontal build that accepts the flow identity and board audience fields before deploying a basal build that sends them. Older prefrontal builds decode these requests strictly and reject unknown fields. reserved:basal opens a flow-scoped management route for both sink writes and carrier reads. Basal uses unscoped management only if the request has no flow version or the transport lacks flow authority. Basal replays previously journaled requests without changing their bodies. See the flow sink identity samples for the new fields and where each operation carries them.

The explicit core carrier-op list contains prefrontal / board.read and prefrontal / work.unsettled. Both are queries with the approved install's stamp in the request body.

Declare {"module":"prefrontal","op":"board.read"} in ops and a nonempty board_read string array in the manifest, for example "board_read": ["$audience"] with "audience": {"kind":"global"}. Basal refuses either declaration without the other, naming board_read. With an audience every board-read reference must be exactly $audience; without one, use known static agents (or $self in packages), following the same self-only rules as sinks and status. Core checks each entry's separate live, revocable grant as well as audience membership. See the manifest. Call it with ops.call('prefrontal', 'board.read', args). Core carrier ops are exempt from the flow-service declaration check at install. The normal grant, catalog and shell checks remain in force.

Basal adds the approved run's install stamp and audience to the request and journals both before dispatch. Scripts cannot supply audience, stamp, flow_id, flow_version, flow_install_id, code_hash, or agent_id, even as null: basal refuses those arguments with invalid_arguments. The targeted-call for option is not supported for carrier ops. Within the approved audience, scripts can select boards using the read arguments. Core rechecks installation, the code hash, board-read authorization and the audience; the carrier route is not a grant bypass.

An approved global audience becomes {"all":true}. Other audiences become {"agents":[...]}, a nonempty, sorted list of unique stable IDs: the approved agent, the workspace's live agents from Entorhinal, or (with no explicit audience) the approved board_read targets. $self resolves to the instance's owner. An empty or unreadable workspace audience is refused without sending, with retryable sink_audience_unavailable.

{
  "stamp": {"flow_id":"board-hygiene","flow_version":3,"flow_install_id":"<approved install id>","code_hash":"<approved code hash>"},
  "audience": {"all":true},
  "limit": 16,
  "cursor": "<previous next_cursor>"
}

stamp and audience are required on the wire. The stamp includes agent_id when the flow scope names an agent. flow_id is 1–128 characters with no control characters; flow_version must be positive. Requests reject unknown fields. The optional read arguments are agent, agents, limit, and cursor:

  • With agent, core reads one board. This form cannot include agents, limit, or cursor and returns the board object directly.
  • Without agent, core pages boards in sorted agent-ID order. agents may explicitly select at most 64 IDs; if omitted, core enumerates board agents and filters them by the installed audience. An explicit out-of-audience ID is refused rather than silently filtered.
  • limit defaults to 16 and must be between 1 and 16. cursor is the exclusive after-agent ID: use the previous reply's next_cursor, or omit it for the first page. It must be nonempty, at most 256 bytes, and contain no control characters. A paged read requires an audience on the approved install.

The paged reply is {"boards":[{"agent_id":"...","board":{...}}],"next_cursor":null,"page_cap":16}. next_cursor is the last returned agent ID if another item exists, otherwise null. A board is core's BoardState JSON object, with fields roomId, sessionId, vocabulary, servedSeq, lanes, laneBlocks, blocks, servedBlocks, totalBlocks, and health.

Core's refusal codes are:

Code Meaning
sink_principal_refused Caller is not reserved:basal.
sink_item_invalid Strict request decoding or validation failed, including incompatible single/paged arguments, invalid limit/cursor, or more than 64 explicit agents. The message identifies the invalid field and reason.
sink_flow_not_installed No active approved install for the stamp.
sink_flow_hash_mismatch Stamp hash differs from the installed code hash.
sink_audience_check_required Paged read has no installed audience (also used when the lower-level single-board dispatcher is called without an agent).
sink_audience_unavailable Audience membership cannot be checked.
sink_target_not_in_audience Explicit target is outside the approved audience.
board_read_target_not_granted Target is unresolved/ungranted, board-read manifest authorization or a separate live grant is missing, owner restriction fails, or the board room is absent. Audience membership alone does not grant a read.

Core normally sets the refusal message to the refusal code identifier itself. sink_item_invalid instead identifies the invalid field and decoding or validation reason. sink_target_not_in_audience names the flow, target and audience; sink_audience_unavailable may include those names and the lookup failure detail. Basal exposes core refusals to the script as ordinary query rejections and journals them like other replies.

work.unsettled

work.unsettled lists every delivered work item whose owning head has not settled it yet. Declare {"module":"prefrontal","op":"work.unsettled"} in ops; there is no separate manifest field. Call it with ops.call('prefrontal', 'work.unsettled', {}), or {cursor} for a later page. Basal routes it like board.read and journals the approved install stamp before dispatch. Scripts cannot supply stamp fields or use the for option. The request has the same stamp fields as board.read, no audience member, and an optional cursor; core refuses unknown fields.

Core admits the call only for an active install whose approved audience is {"kind":"global"} (the reply spans every head's work) and whose approved manifest lists the op. The reply is {"items":[…],"next_cursor":…} with at most 200 items; pass next_cursor back as cursor. A page cut short by core's time budget also carries next_cursor, so read until it is absent rather than counting items. Each item has agent_id (the live head owning the delivering session, or null when no single live head holds it), item_id, title, delivery (unmerged, merged, none or unknown; accept error too), merged_ref (only when merged), delivered_at_ms, campaign_id (campaign items only) and blocks, the open campaign items that depend on it, as {item_id, title}. merged_at_ms is never sent: core does not record when a delivery was first seen merged.

Refusals are {code, message}: sink_principal_refused, sink_item_invalid (malformed body, or a cursor work.unsettled did not return), sink_flow_not_installed, sink_flow_hash_mismatch, work_unsettled_audience_not_global and work_unsettled_not_granted. Basal passes them to the script unchanged as query rejections. Core's captured request, reply and refusal vectors, copied from prefrontal revision 0c5d9069cfdb5097a765d0f934b6b44c4e7c29f9, are in test-vectors/work-unsettled-v1/.

Codemode

Basal provides codemode over tool-provider/v1. Core grants access and owns each ephemeral run scope; it does not carry the tool or provide its input schemas. The daemon verifies the caller's principal and stamps the incoming route with scope owner, ref, epoch and authoritative attributes including agent_id; basal takes its agent and invoking scope only from that stamp. Arguments cannot override either. Each child provider route carries the invoking route's harness and session in its BindIdentity, configuring the provider's client and session context, never authority. Bind identities carry no project fields: project attribution comes from the admitted run scope's stamped workdir and project_id. Basal declares bind-no-project/v1 and identifies the agent and scope only from the daemon's recorded principal and scope.

The named tool request uses the daemon wire protocol's ToolCallRequest:

{"name":"codemode","arguments":{"code":"string","description?":"string","limits?":{"wall_ms?":"integer","tool_calls?":"integer","output_bytes?":"integer"}},"call_key?":"string","schema_pin?":"string"}

The JavaScript function body sees only tools.<name>(input), console.log(...), and frozen intrinsics. Each tool has the same input and provider permission rules as the agent's direct calls, including writes and shell. Only codemode itself is excluded. A program can use a tool only if its provider declares call-modes/v1 and the tool's own tool.catalog entry lists codemode in its modes (an absent modes means classic only), or if the provider declares the legacy agent-run-scopes/v1, which admits all its tools. When the run starts, Basal reads each provider's tool catalog (role.describe, then tool.catalog, neither with an envelope call_key), on a route opened under the run's own scope and bound with the harness runner and the session basal:codemode:<run_id>. These reads never carry an envelope preset. The first tool.catalog read also omits the preset from its arguments; a second read can name a listed preset (see below). The daemon derives a bind's call mode from its scope, so every route basal opens on the run scope (these reads, the program's tool calls, late-result and withdraw requests, and Broca model calls) reaches its provider as codemode; basal has no other way to set it. A catalog read failure's warning suggests retrying the run only when the failure may clear: a timeout, a lost connection, or a transient refusal such as scope_not_synced; a permanent refusal such as principal_denied carries no such hint. AFT accepts only host harness names in a bind (opencode, pi, runner, mcp:<client>, fed:<fingerprint>), and runner is its label for headless executors; the harness is configuration, not authority. An entry its provider does not serve in codemode is dropped from the run, not the whole run: provider_not_opted_in and call_mode_unsupported drop that tool, while catalog_unreadable and invalid_answer drop every entry from that provider, since basal never guesses a result format. Each dropped group is a run warning {code:"tools_unavailable", module, reason, tools, message}, shown in the result's warnings and its text. The program still sees each dropped name; calling it rejects with tool_unavailable, detail: {reason, module}, and sends nothing. The run starts even if only basal's own tools remain. Core's catalog still fails the whole run when an entry names codemode itself, a provider or tool absent from the daemon catalog, or a tool declared ambiguously. A tool bind refused before anything was sent (scope_changed, scope_not_synced, or a stale route) is re-opened once; a call the provider may have received is never resent. Basal adds its own model and classify tools, which call Broca on the run's scope.

Basal's tool.catalog lists codemode and flow when no preset is named or when the head preset is named. The worker and reader presets list only codemode. role.describe advertises tool-catalog-tools/v1 and tool-catalog-direct/v1 for these optional parameters:

  • params.tools is a nonempty array of distinct, nonempty tool names the requested preset serves. It narrows the catalog in Basal's order, regardless of the order of the request.
  • params.direct requires params.tools and is an array of distinct, nonempty names from that list. When present, only the direct tools appear in the reply and in the tool list covered by catalog_digest. An empty array returns no direct tools. Requested system text still includes the codemode guidance if params.tools includes codemode, even when params.direct excludes it. Otherwise, when params.tools excludes codemode, the requested text is empty. system_text.tool_names lists the tools returned in the reply, sorted by name.

Basal refuses malformed selectors with invalid_request. detail.field is params.tools or params.direct for an invalid list, and names the first offending position (for example params.tools[0]) for an invalid element, including an unserved tool name. With neither selector, the catalog and requested guidance are unchanged.

Basal does not advertise tool-catalog-capability-filter/v1 and refuses params.capabilities with invalid_request and detail: {"field":"params.capabilities"}. The role.describe tool_capabilities index still lists basal:codemode/v1 and basal:flow.manage/v1 for discovery. Prefrontal uses basal:codemode/v1 to find the head codemode provider.

  • A keyed run's ID is domain-separated BLAKE3 over length-framed (agent_id, call_key). A repeated key attaches to its running run or returns its finished result, never starting another worker or dispatching another call.
  • Without a key, a fresh OS-random run ID executes once, with no deduplication, withdrawal or late result. Its result warns that a lost reply cannot be recovered.
  • description is optional, at most 1,024 UTF-8 bytes, and has no line breaks.
  • limits may only lower wall time (1–1,800,000 ms), tool calls (1–200), and captured output (1–65,536 bytes).
  • The parent enforces 30 minutes of wall time, excluding intervals when the worker is blocked and every in-flight call is held on a person. Person wait has one cumulative 10-minute cap per run. The confined worker enforces 10 seconds of JavaScript CPU, 64 MiB heap and 1 MiB stack.
  • Windows runs codemode under the launcher's full worker confinement, with the codemode job commit limit rather than the larger flow limit.

Basal records the run before calling core's codemode.run_scope.open over its own route stamped reserved:basal (the daemon-verified basal module principal), never by borrowing a program's agent authority:

{"agent_id":"string","invoking_scope":{"ref":"string","epoch":"integer"},"run_id":"string","expires_at_ms":"integer"}

For a worker session's call (a worker run) the request has no agent_id member, and invoking_scope is the worker's own scope; core derives the head the run works for from it. Core replies:

{"scope":{"ref":"string","epoch":"integer"},"expires_at_ms":"integer","catalog":[{"tool":"string","module":"string","op":"string"}],"preset?":"head | worker | reader"}

Expiry is fixed at admission time + 41 minutes. Basal checks the returned scope's daemon stamp for matching agent and run, and reads input schemas only from the daemon's declarations for the returned module/op. The optional preset is core's selection for the invoking agent's tool catalog: basal saves it with the opened scope reply and sends it on a program's tool call, in ToolCallRequest.preset, exactly when that provider's preset-less admission-time tool.catalog answer lists the run's preset in presets (tool-provider contract §4.3, CatalogAnswer::lists_preset). A provider that lists no presets, or lists other presets, gets no preset on its calls: the call then runs the provider's default variant, since an absent preset means exactly that. Basal first reads tool.catalog without a preset. It uses that answer for admission unless the answer is empty and lists the run's preset. Only then does Basal read again with that preset in the catalog arguments and use the second answer. A reply from core without a preset uses only the first answer. Late-result and withdraw requests do not carry a preset. The opened reply is already stored in the run-scope record, so no schema migration is needed. Core refusal codes, messages and optional details are preserved unchanged. No worker starts after a refused open or mismatched stamp.

Every terminal path calls core's codemode.run_scope.close with {run_id, epoch} before exposing the result. Close replies {closed, already_closed}. Cancellation closes the scope before killing the worker. Startup interrupts unfinished runs, closes leftover scopes and never resends a call. If close fails, the result carries a warning and the scope's fixed expiry remains its outer bound.

Tool availability at dispatch

An admitted tool is checked against the live daemon catalog when its call reaches dispatch, including calls that waited in the supervisor's queue. If its provider module is absent, or the daemon catalog cannot be read, basal holds the call for at most 15 seconds for the provider to reconnect. Catalog change notifications trigger a recheck; a fallback timer rechecks at most once per second. The hold occupies an in-flight slot and spends the run's wall budget, not its person-wait allowance. Cancellation or run termination releases the call without sending it.

If the provider returns with the operation still declared, basal dispatches the call normally. If the hold expires first, the call rejects with outcome and code tool_unavailable, an explanatory message naming the module, and detail {"reason":"provider_unavailable","module":"<id>","retryable":true}. The run's wall budget can end the hold sooner; the run retains its normal wall-budget outcome and the unsent call is recorded as tool_unavailable. The fixed run deadline also bounds the hold. A module that is present but no longer declares the operation rejects immediately with the same outcome and code, a message naming the tool and module, and detail {"reason":"tool_removed","module":"<id>","retryable":false}. Neither case records permission to send or a timestamp for entering the provider. Other pre-dispatch refusal codes, such as unknown_tool, invalid_input and queue_full, are unchanged and carry readable messages rather than the bare code.

Onward held calls

Run tool routes declare tool-result/v1 and held-reply/v1 as consumer capabilities, but declarations alone do not select a result format. Admission freezes each tool's own catalog result_format. Only tool-result/v1 tools use the shared tool-provider decoder, for direct replies and late result entries alike: structuredContent is the program value when present, otherwise text parts joined with newlines; isError: true rejects with the provider's errorCode and text. Legacy and unknown formats remain opaque JSON, even for a body such as {"path":"a.txt","content":"hello"}. An unreadable provider catalog, including a legacy provider's catalog, drops that provider's tools from the run with a catalog_unreadable warning whose message says retrying the run may succeed; the run's other tools still work. Basal never guesses a format.

Tool-provider 0.13.0's ToolResult::held() marks interim content, not an answer; the call's answer arrives later through late_results. The person-wait reasons are consent, login_handoff and login_capture (result::is_person_wait). running means the provider's own work continues and no person needs to act; any other well-formed snake_case reason also remains held and is not a person wait. The shared validation rejects malformed reasons, non-object detail, and held replies with isError: true. Basal keeps the await pending for every held call and pulls its late result whatever the reason. Only a person-wait hold sets waited_on_person, is named in the running reply's text, and counts as person time: person time accrues only while the worker is blocked and every in-flight call is held on a person, against the cumulative ten-minute budget. A running hold spends ordinary wall time, so the run's 30-minute wall budget still ends it. A final entry that races ahead of the initial held reply leaves basal without the reason, so it conservatively records waited_on_person because a person wait cannot be ruled out, and stops the person interval before budget checks or withdrawal.

Basal is the onward carrier and custodian. One persistent, sleeping worker per provider shares a cursor across all runs, starts at since: null, and follows the returned cursor. There is no result push; empty pages use bounded backoff (25 ms to two seconds) without needless acknowledgements. No held calls means no background reads, apart from completing acknowledgement of a page already consumed. Each live target commits before the page is acknowledged, and successful program completion keeps its route open until that acknowledgement succeeds. If a run ends before confirming that it stored an entry, the shared reader treats that run as gone; other runs on the provider continue. Malformed entries are logged and skipped. Result, not_started and expired entries with a foreign custodian or a scope mismatch against a live target are logged, skipped and acknowledged past without delivery. Progress and future non-result entry kinds are skipped at debug level, not treated as malformed or terminal; the cursor advances past them without settling the call. Pull timeouts, transient refusals and failed provider acknowledgements retry with bounded backoff while the run's budgets still permit waiting.

A transient provider/carrier/daemon reconnect does not change the run's scope epoch. Basal may reopen the same scoped route for late_results, late_results.ack and tool.withdraw, never to replay a tool action. Incarnation changes reset the cursor to null, including a restart during the final page's acknowledgement; already settled calls are not delivered twice. Only a definitive scope end, including a parent ending, ends held custody as unknown. Restarting basal still interrupts unfinished runs with no retry. Call-key correlation and provider cursors are memory-only and are discarded on restart.

Termination removes the run's custody targets before network cleanup. Cancel, budget exhaustion and deadlines withdraw held calls in parallel before closing the scope. Withdrawal cleanup has a two-second bound per call and retries transient refusals within that bound. A guaranteed not-started answer records withdrawn; a completed answer with a retained result records that known outcome. Started or uncertain answers remain outcome_unknown. Received final answers are never withdrawn. The call journal accepts withdrawn only when it has both send-intent and provider-call entry timestamps, plus a provider hold (held, any reason). These record permission to send, entry into the provider RPC, and the provider holding the call; no dispatch history is erased. waited_on_person is set only for a person-wait hold, and the journal refuses it on a call that was not held. Store schema 38 adds the held column by rebuilding codemode_calls; earlier holds were all counted as person waits, so existing rows start with held equal to waited_on_person. cancelled still means the call was never sent.

A late not_started entry records withdrawn and rejects with code: "not_started" and the provider's detail. Cerebellum consent approval uses this to return detail.consent: "approved" without executing a potentially stale action; denial is a terminal refusal. Login handoff/capture return their real final result. The program may deliberately make a fresh call after approval, preferably after refreshing its screenshot or other state. That is a new journal position and call key, not an automatic retry by basal. See the consent example. Expired and reduced results settle as unknown outcomes, never guessed successes. Unknown entry kinds leave the call pending for its final result.

Results and long calls

The tool declares result_format: "tool-result/v1" and returns an ordered content array with one text part containing the status line (status, duration, call count and person-wait time), the error as plain text, return value (at most 16 KiB of JSON; strings shown verbatim, objects and arrays pretty-printed), captured output when there is any, a per-call outcome/person-wait/duration table when there were calls, and warnings. The reply carries the machine fields in structuredContent, which never enters model input. See the result contract for errors and size handling. Budget termination preserves partial output and known call outcomes; sent calls without a recorded answer are outcome_unknown, never retried. Queued calls proven unsent are cancelled.

An oversized return is stored as failed with code result_too_large, but it keeps a text prefix in structuredContent.value_head, never value. Because the program finished and its tool calls ran, the reply is a partial success, not an error: isError is unset, structuredContent keeps status and error and adds partial: true, and the text leads with completed, return value cut, says the calls ran, and shows the prefix under Return value, cut: before the call table. The prefix is cut at a UTF-8 character boundary and ends with … cut: X bytes returned, the first N shown; the prefix and marker together fit within 16 KiB. This head is text, not a complete JSON value. Store schema 49 adds a nullable value_head column for the prefix; the completed return value remains separate. The outer tool-result limit and the captured-output and call-table limits are unchanged. Oversized arguments still fail with arguments_too_large, without a return head.

Keyed calls that outlive the 25-second foreground wait reply with status: "running" and run_id in structuredContent, and a text part naming each call held on a person (tool, call number and what the person must do) and saying that basal retains the final result for the call; see the result contract. Basal declares the late_results session capability. When the route declared both tool-result/v1 and held-reply/v1, the interim reply carries held: {reason}: the first available provider reason in call order when person-held calls have reasons, or running if none has a reason. running asks neither the person nor the agent to act. Routes missing either declaration retain the plain running reply; keyless calls wait for the final answer and are never held. The final late entry carries exactly the final content result a foreground reply would have returned, without the interim held marker. The custodian pulls late_results {since: null | cursor, limit?} and acknowledges with late_results.ack {through: cursor}; replies use the tool-provider contract's entries/cursor/more shapes. Only the custodian principal verified by the daemon on its route receives entries: the scope owner for a direct call, or the carrier for an onward call. A changed incarnation or future cursor refuses cursor_incarnation_changed. Unacked results survive scope closure and remain for 24 hours, then become identity-preserving expired entries; retention is bounded to 1,000 results per session and 1,000 expired entries per owner.

tool.withdraw {call_key, carrier?, scope?} follows the tool-provider contract's carrier/owner/scope checks. It cancels the run. A call proven not to have started replies withdrawn; an already started call replies already_started with an outcome, or unknown; a completed call returns its retained result. Basal stores the first withdrawal answer and returns identical bytes to every permitted caller and repeat. Role ops (role.describe, tool.catalog, tool.withdraw, late_results, late_results.ack) are named requests on the tool route, never model tools.

Catalog digest vectors

catalog_digest is the lowercase hex BLAKE3-256 of the catalog array's RFC 8785 (JCS) canonical JSON, with its entries sorted by name. For a codemode tool run the catalog is the resolved one the program can call: core's usable entries plus basal's own tools, without the tools dropped at admission. Canonical JSON sorts object members by name, has no whitespace, writes numbers the way JavaScript does (1.0 is 1, 1e21 is 1e+21), writes non-ASCII text as itself and escapes control characters. basal computes this digest for its run records; these vectors pin it. Each shows a catalog as sent, its canonical JSON, and its digest. crates/basal-core/tests/codemode_digest_vectors.rs reproduces every vector with its own canonical JSON and BLAKE3 code and checks basal's digest against them.

Vector base

[{"name":"find","module":"search","op":"search.find","input_schema":{"type":"object","properties":{"q":{"type":"string","maxLength":200}},"required":["q"]}},{"name":"read","module":"notes","op":"notes.read","input_schema":{"type":"object","properties":{"id":{"type":"integer","minimum":1}}}}]
[{"input_schema":{"properties":{"q":{"maxLength":200,"type":"string"}},"required":["q"],"type":"object"},"module":"search","name":"find","op":"search.find"},{"input_schema":{"properties":{"id":{"minimum":1,"type":"integer"}},"type":"object"},"module":"notes","name":"read","op":"notes.read"}]

Digest: aa6c1832de7397efb328c47d6c9d3dbfc15f09294ba77d84424fae2ed8537697

Vector keys-reordered

The base catalog with the members of every object in another order; the digest is the same.

[{"op":"search.find","input_schema":{"required":["q"],"properties":{"q":{"maxLength":200,"type":"string"}},"type":"object"},"name":"find","module":"search"},{"module":"notes","input_schema":{"properties":{"id":{"minimum":1,"type":"integer"}},"type":"object"},"op":"notes.read","name":"read"}]
[{"input_schema":{"properties":{"q":{"maxLength":200,"type":"string"}},"required":["q"],"type":"object"},"module":"search","name":"find","op":"search.find"},{"input_schema":{"properties":{"id":{"minimum":1,"type":"integer"}},"type":"object"},"module":"notes","name":"read","op":"notes.read"}]

Digest: aa6c1832de7397efb328c47d6c9d3dbfc15f09294ba77d84424fae2ed8537697

Vector entries-reordered

The base catalog with its entries in the other order; the digest is the same.

[{"name":"read","module":"notes","op":"notes.read","input_schema":{"type":"object","properties":{"id":{"type":"integer","minimum":1}}}},{"name":"find","module":"search","op":"search.find","input_schema":{"type":"object","properties":{"q":{"type":"string","maxLength":200}},"required":["q"]}}]
[{"input_schema":{"properties":{"q":{"maxLength":200,"type":"string"}},"required":["q"],"type":"object"},"module":"search","name":"find","op":"search.find"},{"input_schema":{"properties":{"id":{"minimum":1,"type":"integer"}},"type":"object"},"module":"notes","name":"read","op":"notes.read"}]

Digest: aa6c1832de7397efb328c47d6c9d3dbfc15f09294ba77d84424fae2ed8537697

Vector trailing-zero

1.0 is written 1.

[{"name":"scale","module":"math","op":"math.scale","input_schema":{"type":"number","multipleOf":0.5,"maximum":1.0}}]
[{"input_schema":{"maximum":1,"multipleOf":0.5,"type":"number"},"module":"math","name":"scale","op":"math.scale"}]

Digest: b3f666837a0021f0cdb2fb3815d50858d69577993c4ee657ab2cdbee99eba9a0

Vector exponent

Numbers at or above 1e21, and below 1e-6, take the exponent form with a lowercase e and an explicit sign.

[{"name":"measure","module":"lab","op":"lab.measure","input_schema":{"type":"number","minimum":2.5E-7,"maximum":1e21}}]
[{"input_schema":{"maximum":1e+21,"minimum":2.5e-7,"type":"number"},"module":"lab","name":"measure","op":"lab.measure"}]

Digest: c57fc8b429409c4fbd9ba5d30f9c13561a7a6a3a4c2011d85791d2a67a2a8cda

Vector string

Non-ASCII text is written as itself, whether it was sent raw or escaped; the control character U+0007 is written \u0007.

[{"name":"greet","module":"cafe","op":"cafe.greet","input_schema":{"type":"string","description":"Grüße, \u6771\u4eac\u0007!"}}]
[{"input_schema":{"description":"Grüße, 東京\u0007!","type":"string"},"module":"cafe","name":"greet","op":"cafe.greet"}]

Digest: dceff93392fb8a334efca1083e5503e335d450e2ad80be38a55291d7941f0eb6

Vector empty

[]
[]

Digest: d53d18c23212ea7b6300594bb89bce60218f6eff2b9d628b8cc42d3e79bbd5ab

Operator decision cards

Basal raises flow_decision cards for reconciliation, re-enabling an auto-disabled flow, and lost grants. Each initial raise reads the daemon catalog: a provider advertising consent/v1 receives consent.request on basal's attested reserved:basal route. If no provider advertises that capability, selection returns Unavailable naming consent/v1; no path is committed and the card stays pending for retry. prefrontal holds no decision cards (its elicitation.* ops are gone), so there is no other endpoint to fall back to. Install cards use the same provider directly.

The selected path is committed before sending, including requests whose replies may be lost. A card never changes paths. Updates use its original provider and dedup_key. Withdrawals use the original provider and current card id. Cingulate refreshes identical content in place, but changed content replaces the pending card with a new id. Basal records that replacement id and rejects answers to older bodies or known superseded ids. If a replacement request reply is lost, an answer can supply the new id only for an outstanding cingulate grant-loss card whose answer body exactly matches the current revision. This prevents an answer to older or unrelated content from claiming the replacement id.

Each provider's answer feed is read only while basal has an open card on it, or while a failed poll on that provider still needs a retry. If no card is open when basal starts, no poller is started: no thread, no timer and no page read. The first card raised starts it. Once every card is closed, the poller waits without a timer and reads nothing until the next card is raised. While cards are open, basal backs off to a 5-second poll until it sees a valid Cingulate card_settled.v1.basal bus pointer in this process. Each pointer wakes an immediate reread from basal's own cursor; pointers in a batch coalesce into one wake. After the first pointer, the timer is a 10-minute backstop instead. The pointer carries no answer and does not advance the saved cursor. Basal applies each answer durably and idempotently before acknowledging it on its own provider. The feed uses consent.answers continuations and a durable cursor, then consent.ack through the fully processed page, including empty final pages that cover withdrawals. A failed apply keeps the page unacknowledged; a failed ack is retried even after the last card closes. After a restart, a failed ack is sent again from the durable cursor before the next page is read on that provider, which happens once a card is open there again. Retention tombstones close only their matching owned card and never apply a choice.

Adding or removing a consent/v1 provider does not require changing the daemon catalog and basal's card state at the same time. If the provider is absent, new cards wait for retry; adding one later lets basal select it on a later pass. Previously recorded cards keep using their provider when it is reachable. A listed but unreachable consent provider delays its cards rather than raising them on another provider. Catalog read failures also delay selection rather than guessing a path.

Store schema 37 removes the legacy path. Cards that older builds recorded on core's legacy path go back to unselected: an open one also drops its core id and accepted revision, so the next pass raises it on a consent/v1 provider; a closed one keeps its id as history. Withdrawals and answer cursors on the legacy path are dropped. The store then refuses any path other than consent:<provider> on decision cards, withdrawals and answer cursors.

The decision body remains core's validated v2 body; cingulate checks the envelope but stores that body opaquely. Flow decisions cannot use consent.report_execution under the requester contract, so basal acknowledges settlements without reporting execution. The byte-pinned requester corpus is copied from cingulate tag consent-requester-v1, commit c650e9db6e87dbb28fe20dd5fc2815db5deb41e9, into crates/basal-module/tests/vectors/consent-requester-v1/. Its SHA256SUMS digest is e4eb488651dbd1e3c3164644a4e4bc0ba3d39f81cb4f3e1f09cc7913564a3248. The copied corpus README describes reproduction in its owning repository.

Lost grants and retirement in health and listing

Both flow.list and operator/core flow.health include grant_losses (an array, empty when no grant-loss cause remains) and agent_retirement (an object or null). They retain this evidence even when an operator or owner takes over the disable, so automatic restoration cannot hide a manual stop.

A module_grant_absent or agent_grant_absent refusal records grant_lost and pauses the flow. Each (flow_id, provider, grant) has one durable subject: flow_id, provider, grant, grant_label, echoable, run_id, version, revision, state, failures, next_poll_at_ms, and lost_at_ms. Repeated loss updates the subject and revision. state in visible evidence is polling or stopped. String grant references are preserved verbatim; structured references use compact JSON with recursively sorted object keys. References over 4 KiB use a BLAKE3 hex key with echoable:false: the key is neither sent to the provider nor suitable for a card to echo. The flow still stays disabled.

Basal performs only the read-only grants.would_ask diagnostic on the locally approved version's configured flow route, never on a route acting only as the Basal module. Unanswered or negative checks back off from one second to a one-minute cap on the runtime clock; yes clears the lost-grant cause. The flow runs again only if no other lost grant, stopped restoration, retirement, or operator/owner disable remains. Removal or revocation stops polling. Explicit enable clears the pause and permits the deferred call to retry; a fresh grant refusal can pause it again. Restoring access is an operator action outside basal, currently ck-plexus-admin grant …. Basal does not grant or offer provider access. It raises one open flow_decision card of kind grant_lost per (flow_id, provider, grant), updating that card on repeat loss. Its typed body is {flow_id, provider, grant, grant_label, refused_at_ms}; the run and version remain in basal's durable record, not in this body's closed schema. The grant_lost card prompt includes the refusal's full UTC date and time, so refusals on different days are distinguishable. check_now schedules an immediate scoped diagnostic; keep_disabled stops polling for that grant. Expiry or silence applies neither choice and keeps background polling. Once the grant returns, basal marks the card stale and durably queues withdrawal on the card's raising provider (consent.withdraw), retrying while that provider is unavailable. An oversized hash fallback raises no card.

An agent_retired refusal fails the run and disables the flow without a retirement or permission card. If an earlier mutation may already have been sent, its call remains unknown and the run still needs reconciliation: retirement does not settle whether that mutation happened. Its existing reconcile card remains available. A "not applied" answer permits the established re-issue path; a subsequent retirement refusal fails the run without another reconcile card. agent_retirement records agent_id, agent_reference, provider, action, and at_ms. Unknown identity is retained as null and cannot be assumed restored. Explicit enable is refused while that evidence stands. A newly approved reinstall clears retirement only when its owner differs from the retired agent and its manifest no longer names that agent. For an operator-installed flow, removal of the retired target from all manifest agent fields is sufficient. Changing code while retaining the retired owner or target does not clear retirement.

Moving an agent's flows (agent-data/v1)

When Entorhinal moves an agent to another computer, the agent's flows go with it: every flow whose owner is the agent (or, before any approval, whose versions it alone wrote), with all stored versions, schedules, template and package instances, kv state and run history (summaries and call metadata). Install cards, secret grants, rate windows and token and dollar ledgers stay behind, and so do events queued but not yet admitted: the receiver reports them as dropped: {"queued_event": n}, so the move reads as completed with losses. Operator flows with no owner agent never move.

Basal serves the contract (cortexkit-role-agent-data 0.4.2, all ten ops) on the internal service agent-data, declared in the manifest with agent-data/v1 in capabilities.provides. Only reserved:entorhinal on an unscoped route is served; every other caller is refused caller_forbidden before its request is read. describe declares ref kind agent and one store, basal-flows, with sync_class: "agent"; one ref {ref_kind: "agent", ref: <agent_id>} covers all of the agent's flows. It also declares archive: true (basal accepts a release to an archive file) and formats: {writes: {agent: "basal-flows/1"}, reads: ["basal-flows/1"]}, the same format prepare names on each item.

  • Source. busy reports run_active for a live run, reconcile_open for an unsettled call outcome or open decision card, and approval_open for an install card still waiting for an answer (a version's approval can't follow the move). The operator settles these on this computer first. prepare rechecks that and freezes the agent in one store transaction: its flows admit nothing, due schedule times pass unplanned (the schedule's missed policy settles them if the move is aborted), and matching events wait in the flow's backlog. The flows are encoded as a basal-flows/1 stream (capped at 64 MiB; a larger agent is refused not_exportable) and admitted through Engram's session door (the session-door internal service of the engram module, the only path an agent's data takes between computers). An agent with nothing here to carry (no flow, instance, kv entry, run history or instance generation) gets no item: prepare replies items: [] and admits no stream, and export replies {"items":[]}, so the move can go to a computer that doesn't run basal. The freeze and the tombstone apply all the same. release leaves a tombstone naming the new holder and discards the flows' backlogged events, including any queued during the freeze, which the receiver's dropped count can't include: basal logs the number at INFO and records it in the cut's checkpoint (discarded_at_release, beside the queued_event count the cut carried). abort lifts the freeze.
  • Receiver. import reads the sealed cut through the door, checks its digest and every carried code hash, and stages it without writing a live row. A flow id that belongs to another owner here is refused local_advanced, naming the flow and its owner: rename or remove one and move again. A cut with no basal item is an empty set: import replies items: [] and stages nothing, and activate writes no flow, only replacing a tombstone of the agent here. Against live flows of the agent here, such a cut is a fork: diverged answers advanced (it reads the cut only in that case, and answers cut_not_ready while it can't), and import refuses local_advanced. activate writes the flows in one transaction. A flow that was approved on the source arrives disabled with disabled_by: "move" and waits until this computer approves the code locally (for an instance, the matching parent version must be registered and approved here). Basal then restores the source's enable state, and the schedule's missed policy covers the time the move took. Basal checks after activation, at startup and when local approval changes; no approval lookup goes to prefrontal. Installing the flow again from its agent raises a fresh card as usual. A moved flow still waiting after a day shows in diagnostics.findings as moved_flows_pending. Moved runs keep their admission order, and runs admitted here afterwards come after them. A flow of the agent here that the incoming copy doesn't carry ends removed (removed_by: "moved:replaced").
  • Archive. When Entorhinal saves the agent to an archive file, the source runs busy, prepare and export as for a move, then the archive form of release ({refs, cutId, archive}). Unlike a move's release, the flows' rows stay exactly as they were: enable state, approvals, schedules, instances, kv and run history. The agent stays held and marked archived under the archive id, so its flows admit nothing and due schedule times pass unplanned. The flows' backlogged events are discarded and counted as on a move. The cut's checkpoint keeps the stream's sessionRef, end and digest. A repeat of the same release gets the same reply, and another archive id or a release to a computer is refused id_reused. The flows keep their routes while archived.
  • Restore. A restore from the archive file is a receiver's diverged, import and activate under the restore's own cutId. import, activate and abort carry sourceCutId, the cut the archive was sealed under, which names basal's stream in the file. Any other op refuses sourceCutId as invalid_request. On the computer that wrote the archive, diverged answers at_cut when the restore's cut carries the archived stream at the end and digest kept here; otherwise the usual rule applies. import stages as on a move. activate with the matching sourceCutId reopens the retained flows exactly as they were before the archive, with approvals intact and nothing waiting for approval, and clears the archived mark. If they changed since the archive, it refuses local_advanced. On a computer without that retained copy, activate writes the cut as on a move: approved flows arrive disabled by move and wait for this computer's approval. abort after import drops the staging only; the archived rows and their mark stay exactly as they were.

While an agent is frozen, changes to its flows are refused agent_moving (detail {agent_id, retryable: true}): flow.install, flow.instantiate, flow.enable, flow.disable, flow.uninstall, flow.instance.end, flow.instance.ensure, and flow.instance.remove. Retry after the move is released or aborted; a frozen flow admits nothing meanwhile. A flow belongs to an agent by the rule a move uses: its owner, or before any approval the single author of its versions. Once the agent has moved away the same ops are refused agent_moved (detail {agent_id, holder_box}, where holder_box is the receiving computer's box id, present only when the release named one) until a move back replaces the tombstone. While the agent is archived the same ops are refused agent_archived (detail {agent_id, archive_id}, message "agent <agent_id> is archived (<archive_id>); bring the Alfonso back to change its flows") until a restore reopens or replaces its flows. Bringing the Alfonso (the agent) back means restoring it from the archive file. A freeze held for 6 hours shows in diagnostics.findings as agent_move_frozen; an archived agent does not.

Run-log recovery and cutover

Live flow execution uses an append-only run-log/ beside the SQLite store. SQLite retains admission, accounting, control-plane state and finished-run summaries. A remote dispatch always has durable intent. Anything leaving basal, including a host acknowledgement or a terminal result, is backed by a durable log prefix or a committed SQLite transaction containing the values it depended on. Outcomes and delivery order need not be synced before the worker sees them: after a crash, execution resumes from the durable prefix, and clock, random and kv values beyond that prefix may differ on re-execution.

Successful runs retain a summary and result only. Failed, engine-mismatch and cancelled runs retain their call detail with the history row. Open obligations protect history from retention; settled host receipts survive until that history is pruned, so a redelivery does not cause another send.

Runtime maintenance reclaims eligible sealed run-log segments on its first pass and then on the retention cadence (hourly by default), preserving every live run's replay start.

Backup and restore

Do not back up or restore run-log/. Restoring that directory by any tool is unsupported. Exclude it from OS-level backups and the ENGRAM backup catalog. Back up the SQLite store using its supported backup procedure instead. A SQLite restore can leave the log missing, foreign, older or newer than the store. Basal then reinitializes the log once and marks previously live runs history_lost. A repeated boot must not advance the epoch again. A corrupt retained segment or broken link chain is a startup failure, not permission to discard evidence: preserve the files and investigate the operator diagnostic.

Resolving history_lost

A history_lost run is non-terminal and continues to hold its flow's slot. It appears in diagnostics.findings; it is not automatically resent. Inspect the run, the restore event and downstream effects before choosing a resolution. The operator operation is:

{"op":"flow.reconcile","run_id":"<full run id>","resolution":"cancel"}

Use resolution: "retrigger" instead only when a new execution is wanted. cancel records a cancelled history row with unavailable call detail, preserves late Broca completions as obligations and releases the slot. retrigger first cancels, then admits a new run under the normal gate with a fresh run ID and idempotency keys. Neither choice reconstructs lost call detail or automatically resends an unknown unkeyed write. Reconcile any such external effect manually before retriggering. Accounting lost with the log can under-count once; the history row records that limitation. This operation applies only to history_lost, not ordinary unknown-write decision cards.

Cutover hold point

Cutover is a stop-the-world deploy under the store lease. A committed migration_phase makes restart resume migration rather than start traffic. Each phase is idempotent. Admission and activation remain held until the migration's post-checks. Before any production-shaped rehearsal or production migration, the release operator must obtain the project maintainer's recorded approval and a pre-migration backup and rollback plan, retained with the deployment's change record. The supervising release operator owns the live-store-copy crash rehearsal and production deploy; synthetic-fixture tests do not authorize them. Startup serves only after all persisted post-checks pass. A failed post-check refuses startup and names the check; there is no separate runtime release CLI.

Compare finished/live and identity counts, first-segment snapshots, failed call detail, broken/activation counts, accounting windows and reservations, late-work obligations, Broca waits/wakes and tombstones. Audit retained foreign keys and sqlite_schema views and triggers for references to removed tables. Rollback using the backup and previous binaries is valid only before new traffic starts; after traffic begins, rollback requires a reverse migration. Keep the hold if any check fails.