Runtime Flow
The runtime is the execution engine inside the local Aegis workspace. It keeps agent work bounded by workflow stages, task contracts, tool allowlists, verifiers, and approval checkpoints.
Run State Machine
intake -> plan -> prepare -> execute -> verify -> repair -> review -> finalize
Rules:
repairis only reachable after verifier failurereviewis only required when policy creates an approval checkpoint- runs can be paused, resumed, canceled, or completed
- stage transitions are durable and traceable
Verifier Repair Loops
Verifier failures are treated as feedback, not just terminal errors, when the workflow owns a bounded repair path.
- Coding verification can transition to
repair, write repair notes, and re-runverify. - Research verification can transition to
repair, send verifier findings plus evidence/memo artifacts back through the selected model, rewrite the memo/evidence artifacts, and re-runverify. - Repair loops are bounded by
repairCountso a run cannot iterate forever. - Provider smoke checks do not repair content; they only validate provider plumbing and fail clearly when transport or structure is broken.
Agent Profiles
Workflow templates can declare agentProfiles for task roles. These profiles describe the effective execution identity for each role:
- role
- provider/model override
- prompt profile
- profile-level tool allowlist
- approval policy class
When a profile omits provider or model, the task defaults to the run-level provider/model. This keeps current behavior stable while making the future multi-agent model explicit. Task records persist the effective profile in inputs.agentProfile, and model calls honor provider/model overrides from that profile.
Aegis also maintains a durable read-only agent profile registry. It is seeded from built-in coordinator defaults and workflow-template specialist roles. Registry entries include stable IDs, status, version, source, role, provider/model hints, prompt profile, tool allowlists, skill IDs, approval policy class, allowed policy classes, and metadata. Task-session details link back to the matching registry entry so the operator can inspect both the effective runtime profile and its durable source.
Profile changes use a review/activation path:
AgentProfileChangeRequeststores the proposed profile, target profile, request reason, requester, review status, reviewer note, and timestamps.- New user profiles and changes to user profiles stay pending until explicitly approved.
- Built-in and workflow-template profiles cannot be overwritten by change requests; they can only be used as source context for a new user profile.
- Profile change creation validates proposed tool allowlist tokens, skill IDs, allowed policy classes, and approval policy class membership before the request can enter the pending queue.
- Proposed profiles include
permissionReviewmetadata so review and audit surfaces can see exactly which permission boundaries were checked. - Approval writes the proposed user profile into the registry. Rejection preserves the change request as audit history.
Future model routing should make agent profiles smarter without hiding decisions:
- coordinator, coder, researcher, verifier, memory curator, automation planner, voice assistant, and tool-builder roles can use different model profiles
- local hosted models should be preferred when they satisfy task requirements
- remote providers can be used for stronger reasoning, larger context, specialty capabilities, or fallback
- routing should consider privacy class, context size, structured-output reliability, cost, latency, rate limits, and provider health
- every routing and fallback decision should be recorded in traces and task sessions
Current routing foundation:
ModelCatalogEntryrecords provider, model, execution path, privacy class, capabilities, recommended roles, and catalog source.ModelRoutingPreviewshows the selected model, alternatives, rationale, and warnings for a role/task/privacy request before a run is created.ModelRoutingPolicystores explicit role/task/privacy preferences, including preferred provider/model, fallbacks, rationale, and remote-approval warnings.- Runs created without an explicit worker provider/model use the same routing policy path for execution selection. The selected provider/model, matching policy ID, rationale, and warnings are recorded on the run and model-call traces. Explicit run workers and task agent-profile overrides still take precedence.
Provider/model routing behavior is documented through the API reference, operator contracts, and model provider setup guide.
Secrets And Credentials
Provider API keys, Aegis API tokens, CLI credentials, and webhook secrets are represented as SecretRecord metadata plus local file-backed material.
Current foundation:
SecretRecordpersists stable ID, name, kind, optional provider, description, status, storage class, SHA-256, redacted preview, metadata, and timestamps.- Raw secret values are accepted only through set operations and are not returned by API, CLI, backup manifests, audit exports, or replay packets.
- Secret material is stored under
.agent-harness-secretswith restricted file permissions; the main SQLite database stores metadata and hashes only. SecretStatuschecks whether material is present and hash-matches the metadata without revealing the value.- Backup manifests include secret record counts and the secrets directory path, but they do not hash or export secret files.
This prepares provider execution, LAN/mobile auth, webhook automations, and future connector credentials without mixing raw credentials into run artifacts.
Model-provider CLI subprocesses do not inherit the full operator environment. The runtime builds a bounded child environment from a documented allowlist, then layers only the provider credential variables resolved from the secret registry. The inherited allowlist is limited to process/runtime basics (PATH, HOME, user/shell names, temp directory variables, locale/color/CI flags, and Windows command-resolution variables) plus provider CLI config homes (CODEX_HOME, OPENCODE_HOME, XDG_CONFIG_HOME, XDG_CACHE_HOME, XDG_DATA_HOME, and XDG_STATE_HOME). Other AGENT_HARNESS_*, cloud, connector, or local shell variables are absent unless the selected provider credential explicitly maps a secret to that environment variable.
Coordinator And Task Sessions
Coordinator-led runs add a planning layer over the existing workflow runtime:
CoordinatorProfilecaptures coordinator role, provider/model, prompt profile, allowed specialist roles, delegation policy, escalation rules, and the default approval boundary. The approval queue can still mark individual start/internal checkpoints as coordinator-approvable when the executor can validate the scope from durable evidence.DelegationPlanis written before the first specialist job is queued. It records goal interpretation, intended specialist tasks, dependencies, expected artifacts, risks, and approval expectations.TaskSessionrecords inspectable specialist work and links to the concreteTaskContractonce execution starts. Sessions persist dependency session IDs, expected artifacts, dispatch reason, attempt number, progress rollups, and parent session for repair/follow-up work.SteeringEventrecords user/coordinator guidance against a task session. Unconsumed guidance is appended to the next task prompt and then marked consumed. Repair and follow-up sessions can inherit unconsumed guidance from earlier sessions with the same specialist role. Guidance added to a completed session in a completed run creates a planned follow-up session for inspection.CoordinatorReportsummarizes task-session progress, blockers, approvals, pending guidance, linked artifacts, completed sessions, open questions, and recommended next action. Reports are recorded automatically at plan creation, task-session completion/failure, follow-up planning, and terminal run boundaries, and can also be requested manually.PreRunChecklistrecords the coordinator’s preflight interpretation before delegated work starts: selected workflow, provider/model routing, working directory, verifier command, specialist roles, expected approvals, and whether any item blocks queueing. Checklists are stored as coordinator conversation events and also attached to queued-run conversation metadata.
Coordinator chat currently has an intent layer before execution. A coordinator turn is classified as chat, clarify, plan, execute-small, execute-workflow, status, or steer. When live models are enabled, the coordinator profile’s provider/model can classify and answer; deterministic fallback keeps tests and offline local operation usable. Planning turns persist a pending plan and do not queue work until the user confirms. Small coding or analysis requests can route to single-agent workflows instead of always expanding to the full specialist workflow.
This intent layer is transitional. The target runtime is a model-backed coordinator loop with typed tools and structured action plans. The coordinator model should inspect conversation/run state, retrieve artifacts and approvals, delegate specialist work, and decide whether to answer, ask, steer, stop, resume, or queue work. The orchestrator should validate and execute those actions while preserving policy boundaries. See docs/architecture/model-backed-coordinator.md.
This keeps existing coding, research, provider-smoke, verifier repair, patch-bundle, and audit behavior intact while adding the backend primitives the dashboard needs.
Automation Lifecycle
Saved automations turn repeatable requests into durable definitions without hiding runtime policy checks.
Current foundation:
AutomationDefinitionstores a versioned saved run request, mode, trigger metadata, workflow template, provider/model hints, verifier command, repo path, and approval policy class.AutomationEventrecords create/update/status/preview/trigger activity as an audit trail.AutomationRunLinkconnects automation triggers to queued runs so history remains inspectable even if runs are later archived.- Manual trigger can queue a workflow or coordinator-led run. Schedule, file-watch, and webhook triggers are representable for planning, but no trigger worker executes them in v1.
- Dry-run preview reports what would be queued plus status and policy warnings before a run is created.
Memory And Context Lifecycle
Coordinator conversations, audio transcripts, task-session guidance, coordinator reports, verifier findings, and run summaries are durable source material for long-lived context.
Current foundation:
MemoryRecordpersists user preferences, project facts, decisions, guidance, run summaries, failure fixes, and agent-skill notes.MemoryCandidatepersists extracted preference/context signals with provenance event IDs and a candidate/promoted/rejected lifecycle.- Conversation summaries can be generated on demand and stored as conversation-scoped summary memory records.
- Memory context previews show which active records would be included for a conversation/run/task, which candidates are visible but excluded, and a rough token estimate.
- Memory review reports surface duplicate, stale, and conflicting records with recommended promote/archive/inspect actions. Review is non-destructive unless stale archiving is explicitly requested.
- Memory maintenance runs conversation summaries plus memory review as one routine operation. It avoids duplicating current summaries, can archive stale records when explicitly requested, and can promote only high-confidence candidates when requested.
- Coordinator reports automatically create run-summary or failure-fix memory records.
- Coordinator message handling assembles context from recent conversation events, relevant memory, active run state, and blockers.
- Audio transcript events can be mirrored into coordinator conversations, making voice input part of the same durable context stream.
Planned lifecycle:
- broaden candidate extraction beyond preference-like conversation events into transcripts, reports, failures, and verifier output
- schedule routine summaries for long coordinator conversations
- categorize logs into preferences, decisions, project facts, blockers, failure patterns, provider issues, policy notes, and noise
- promote candidates only after user acceptance, repeated evidence, or a high-confidence verifier policy
- routinely review and prune memory so stale or contradicted preferences are archived rather than fed into every prompt
- keep provenance links so every active memory can be traced back to the source event, run, task session, or artifact
Memory and context behavior is documented through the API reference, settings walkthrough, and operator contracts.
Workspace Model
Each run receives an isolated workspace:
/run/{run_id}/
goal.md
workflow.json
coordinator/
plan.md
tasks/
work/
reviews/
final/
evals/
logs/
manifest.json
Policy Model
The policy engine classifies each action with an action type, policy class, domain, risk level, approval requirement, implementation flag, and audit requirement.
Implemented classes:
- read-only
- write-to-workspace
- external-write-requires-approval
- repo-write-requires-approval
Implemented high-risk classes:
- self-development maps to
self-extension-requires-approvaland may prepare reviewed Aegis patch bundles through the existing coding workflow. Starting self-development requires human approval; repo mutation requires exact verified patch-bundle approval.
Prepared but blocked high-risk action types/classes:
- network-device-requires-approval
- purchase-requires-approval
- trade-requires-approval
- tax-advice-requires-approval
- broader
self-extensionaction (self-extension-requires-approval) - forbidden
Approvals are surfaced as checkpoints rather than implicit side effects. Checkpoints persist the action type, policy class, risk level, policy decision, evidence, reviewer decision, and timestamps. Policy decisions are also emitted to the trace log so a run has an audit trail for allowed, blocked, and approval-gated actions.
Coordinator/operator approval has three practical forms:
- Explicit request approval: when the operator asks the coordinator to do a bounded action such as commit or push the current git changes, that request is the approval for that action. The coordinator should still inspect state, execute through typed tools/actions, and leave an audit trail, but it should not ask for another confirmation.
- Conversational approval: when the coordinator has already presented a bounded action and the operator replies with approval language such as “approved”, “push it”, or “apply that plan”, that conversation turn authorizes the matching typed action.
- Physical review approval: applying a verified patch bundle into the current app/codebase remains evidence-bound. The operator reviews the exact patch/hash evidence through the approval surface, and the runtime applies only that approved bundle.
Future connectors for purchases, trades, tax workflows, network administration, device control, and broader self-extension already have explicit action types and policy classes, but they are marked unimplemented and blocked. Adding a live connector must first change that policy deliberately, add verifier coverage, and preserve approval checkpoints and audit traces.
Repo Write Bundles
Coding workflows do not approve a loose intent to mutate the repository. Small coordinator-managed coding requests use one patch-author agent to produce concrete edits, then verify and apply the exact bundle if checks pass. Larger coding and self-development workflows may still use planner, patch-author, verifier, and reviewer stages, but the implementation handoff is always a patch bundle rather than a plan-as-output. For git repositories, single-agent coding runs first create an isolated worktree and branch named for the run. The runtime snapshots the operator’s current tracked working-tree changes into that branch as a baseline, lets the worker edit the isolated checkout, then converts the branch diff back into an approval-gated patch bundle. For non-git repositories or fallback paths, patch authors may provide complete post-change file contents, or exact oldText/newText replacements for large files; the runtime expands replacements into full-file contents before hashing, validation, approval, and application. Before a repo-write approval is recorded or requested, the verifier stage writes:
work/repo-write-bundle.json: stable patch bundle with file list, before/after hashes, policy-relevant metadata, verifier result, scope checks, unified diff, and bundle hashwork/proposed-diff.patch: unified diff for the proposed editsevals/repo-write-scope.json: deterministic scope checks for paths, size limits, generated/sensitive paths, and candidate-file scopeevals/repo-write-validation.json: disposable-copy validation that applies the proposed edits outside the real repo, then runs the configured verifier command, package build/test scripts when present, andgit diff --check- optional branch artifacts:
work/branch-worktree.json,work/branch-summary.md, andwork/branch-diff.patch
The verifier stage refuses to create a repo-write approval checkpoint when disposable-copy validation fails. The approval checkpoint records the bundle hash, file before-hashes, and validation artifact. Start/internal checkpoints may be coordinator-approved only when the model-backed coordinator has inspected the approval and the executor marks that specific checkpoint as bounded. Repo-write patch bundles, external side effects, and unsupported high-risk actions are human-owned. Finalize recomputes the bundle from current workspace/repo state and refuses to apply if the proposed edits or repo file hashes changed after approval was recorded.
Repo-write tool calls are approval-contextual: an approved repo-write checkpoint only authorizes repo.write-text for files listed in that checkpoint evidence, with matching proposed content hash and current before-hash. A generic approved repo-write action does not unlock arbitrary repository mutation.
Self-development bundles include scope metadata: workflow mode, base git commit when available, allowed and blocked path rules, required commands, rollback notes, aggregate risk labels, and per-file risk labels. The scope report mirrors this metadata so approval review can distinguish documentation/test-only changes from policy, runtime, schema, dependency, workflow, or self-extension-surface changes.
Audit Export
Aegis can export a run audit package through GET /runs/:id/audit or export-audit <run-id> [output-json-path]. The package includes run metadata, summary, jobs, tasks, coordinator delegation plan, task sessions, steering events, coordinator conversation events linked to the run, coordinator reports, approvals, evaluations, trace events, and an artifact manifest with size and SHA-256 hashes. It intentionally exports artifact metadata rather than copying every artifact body into one large object.
For debugging and reproduction, GET /runs/:id/replay-packet and replay-packet <run-id> [output-json-path] return a smaller run replay packet: run state, summary, captured run input, workflow snapshot, task inputs, model trace summaries with prompt/response hashes, task sessions, approvals, evaluations, trace tail, artifact hashes, artifact manifest, verifier command, repo/workspace paths, and a dry-run replay plan. replay-from-packet <packet.json> --dry-run validates the packet and prints the required inputs and replay steps without mutating the repo or Aegis state. Replay packets are intended for operator troubleshooting; full audit exports remain the archival record.