# Agent configuration implementation plan

## Stages

| Stage, needs | Change | Exit evidence |
| --- | --- | --- |
| P0 | Typed AgentConfig projection; schema 2 migration; whole-config revision/CAS; recoverable multi-file lifecycle writes | A01 A02 A11: same-revision clients cannot both win; restart sees old or complete new config; migration semantic diff empty |
| P1, needs P0 | One pure resolver, read-only preview, canonical capability semantics, errors and provenance | A03 A07: equivalent inputs resolve identically, selected empty stays empty, explicit denied call fails |
| P2, needs P1 | Per-execution memory policy, namespace binding, eligibility lineage, policy-epoch revalidation | A05: reads, writes, delayed extraction, compaction and queued commits obey policy; optional outage visibly degrades |
| P3, needs P1 P2 | `agent()`/`llm()`, chat, CLI, dispatch and scheduler adapters; immutable execution snapshot, history filtering | A03 A04 A06 A08 A12: entry parity; concurrent, failing or cancelled calls do not leak config; resumes keep intent |
| P4, needs P0 P1, finishes after P2 P3 | Eight-section UI, whole draft, registry model picker, capability selectors, effective preview | A01 A02 A07 A10: real page actions, conflict recovery, unavailable references, responsive and keyboard |
| P5, needs P0–P4 | Portable import/export, duplicate/delete previews, compatibility preflight, product docs, release gate | A09 A11 A12: owned resources only; legacy callable behaviour kept; final candidate verified |
| P6, optional after P5 | Opt-in Agent/model selection policy over eligible candidates | Selection tests pass; manual paths unchanged without a policy |

- Schema and compatibility land before consumers.
- UI layout may use fixtures after P1; a mock does not satisfy P4.
- Memory controls ship only when every P2 ingress and egress is covered.
- One bounded stage is finished and reviewed before dependent work counts as complete.

## Fixed choices

- The first production release covers saved and inline configurations, atomic persistence, shared resolution, optional memory and the editor. Manual per-call model selection does not need automatic selection.
- AgentSpec is the only saved registry; AgentConfig is a typed value. Reuse `Runtime.exec`, MemoryBackend, Context Engine, capability catalogs and resource governance.
- New saved and anonymous configurations default to memory off. Legacy profiles keep effective behaviour through explicit migration; no history or memory store moves silently.
- Model selection occurs at invocation admission. Changing model mid-response or replaying side effects under a fallback is out of scope.
- Single-base resolution; no named-Agent inheritance tree, mandatory role, autonomous creation of saved Agents, new worker or orchestration engine.

## Source ownership

| Area and existing boundary | Responsibility |
| --- | --- |
| Persistence: `runtime/agent_registry/manager.py`, `workspace.py` | Keep AgentSpec and storage owner; proposed colocated `configuration.py` / `resolution.py` for typed values and pure logic |
| API: `interfaces/server/routes/catalog/agents.py` | One atomic manager operation; typed preview, revision and readiness responses; no route-local merge or second tools write |
| Function calls: `runtime/agent/agent_function.py`, `llm.py`, `runtime/execution.py` | Normalize old and new arguments once; immutable scoped configuration; keep return and validation, no Program/MCP tool loop, explicit authorized native search |
| Durable dispatch: `programs/tools/agents/agent/agent/agent.py`, `runtime/conversation/peer_agents/sub_agent_run.py` | Reuse dispatch and task lifecycle; persist snapshot and lineage through actual run and DAG stores |
| Memory: `state/memory/backend.py`, `state/memory/management/config.py` | Policy enforcement above the backend; namespace and commit contracts within it; trace every caller before signoff |
| UI: `apps/web/components/agents/agents-page.tsx` | Reuse components; typed draft, atomic save; extend the API and type layer at its actual import path |
| Docs | [Configuration contract](https://fzkuji.github.io/OpenProgram/docs/reference/design/runtime/agent-configuration/agent-configuration-ui.html), [Editor](https://fzkuji.github.io/OpenProgram/docs/reference/design/runtime/agent-configuration/agent-core-configuration-ui.html), [Capabilities](https://fzkuji.github.io/OpenProgram/docs/reference/design/runtime/agent-configuration/agent-capability-configuration-ui.html), [Programs](https://fzkuji.github.io/OpenProgram/docs/reference/design/runtime/agent-configuration/agent-tool-configuration-ui.html), both languages; product pages change only with real implementation |

Python paths are under `openprogram/`. Before each brief, find actual chat, scheduler and CLI consumers and persistence schemas in the call graph and record their paths. No unrelated frontend, provider or memory-engine refactors.

## Migration, old clients and rollback

| Topic | Rule |
| --- | --- |
| Preflight | Under the writer lock, read all saved records, the default pointer and effective legacy globals. Dry-run report of IDs, schema versions, unresolved references and semantic differences, without secrets or memory contents. Unknown schemas and corrupt records block that profile; never replaced with main. |
| Normalize | No version means schema 1; becomes schema 2, revision 1. Unknown extension data goes to a migration backup; unsupported executable fields are rejected until understood. Old memory binding and behaviour stay; no switch to empty self spaces. Legacy global inheritance stays a named compatibility source until the user picks a mode. |
| Write | Back up the exact owned files and index with restrictive permissions first. Journal and restart-safe reconciliation for multi-file work. Commit a profile only after validation; an interrupted migration resumes idempotently. No external workspace, credential, session, DAG or learned-memory content changes. |
| Preconditions | New writes require `expected_revision`. A temporary adapter compares a client's `updated_at` under the same lock, derives the revision and writes once. Neither given: 428; the UI keeps drafts and asks for reload. No last-write-wins. |
| Python calls | No-selector calls keep model, history, memory and output type. New keywords are keyword-only. Explicit `agent_id`/`config` defaults to clean history; explicit inherit obeys visibility rules. Conflicting aliases are validation errors. Durable `start_from` and `to` keep their meaning. |
| Rollback | Only with a reader that understands schema 2, or an explicit verified downgrade with writers stopped. Unsupported new fields prevent lossless downgrade. Restore a backup only before post-migration edits or after reconciling them. A legacy binary must not silently rewrite schema 2. |
| Rollout | Backend dual-reader, updated clients, migration enablement, legacy-adapter retirement. Retirement needs updated first-party clients and a documented deprecation period. |

## Failure scenarios

| ID | Action | Must hold |
| --- | --- | --- |
| A01 A03 | Create name-only config; call agent and llm with saved versus equivalent inline fields | No role needed; no anonymous persistence; equal effective fields except identity and provenance; llm has no Program/MCP loop; `web_search=False` emits no native search, explicit authorized True keeps it |
| A02 | Two processes PATCH model and tools from one revision; failure injected before replace | Exactly one 200, one 409; complete old or new file; no mixed fields; draft survives |
| A04 | Two nested parallel calls with different model and memory; one cancelled during await | Requests use their own fields; finally restores the caller; cancellation propagates |
| A05 | Distinct sentinels in memory and off/read-only outputs; force recall, compaction, session-end writer | No forbidden sentinel enters a request or store; derived summaries keep write restrictions |
| A05 A08 | Pause queued recall or write, revoke access, release, restart worker | Late recall discarded; write denied at commit; retry cannot broaden the grant |
| A06 | Switch saved Agent with clean, inherit and selected history; request an inaccessible node | Only authorized chosen context; no implicit transfer; fails before inference |
| A07 | `selected=[]`; denied explicit tool; missing required MCP; llm native search with and without Agent selection | Discovery and invocation agree; no side effect before preflight succeeds |
| A08 A12 | Queue a run, edit Agent, resume; fire the next schedule | Resume uses pinned config plus current revocations; new firing resolves latest revision |
| A09 | Duplicate, export, import, delete with self and shared memory, active run, external cwd | No copied memory, history, credentials or schedules; shared and external resources stay; active deletion rejected |
| A10 | All editor sections, desktop and mobile, keyboard; two-client save conflict | No draft loss, fake success, overflow or unreachable tabs; conflict offers reload or explicit reapplication |
| A11 | Migrate fixtures: global-memory inheritance, empty allows, names plus categories, uncategorized items, default Agent | Effective model, capabilities, memory and default match; rerun is a no-op |

P3 also owns C1–C10 in the [collaboration design](https://fzkuji.github.io/OpenProgram/docs/reference/design/runtime/collaboration/agent-collaboration.html): actual `execution_id`/`job_id` interfaces, completion follow-up and async archive, authorized output reads after message exhaustion, unified history visibility, result limits, exact attach navigation. A helper or a test calling it directly is not public-entry evidence.

## First brief: P0

- **Touch**: Agent management types and storage, Agent routes, their tests, relevant bilingual docs; the minimum value/schema module if it keeps the manager readable. Not function execution, memory behaviour or UI layout.
- **RED**: Concurrent same-precondition PATCH of model and tools, then read: must demonstrate a reproducible lost-update or mixed-write gap, not inspect method names. Add to `tests/component/webui/abilities/test_agent_tools_routes.py`; migration fixtures beside the agent-management tests prove legacy semantics before serialization changes.
- **GREEN**: One validated manager transaction compares revision under a cross-process writer lock and atomically replaces the full canonical file; routes cannot save tools separately. Read compatibility, typed errors and timestamp adapter stay.
- **Done**: Public-entry command, failure and pass evidence, changed files recorded; independent specification review, then fresh quality review.

```
uv run --locked --extra dev python -m pytest -q tests/component/webui/abilities/test_agent_tools_routes.py
```

## Verification

Choose focused RED/GREEN tests at each brief and extend existing ownership. These are starting points, not evidence the scenarios exist:

```
tests/component/webui/abilities/test_agent_tools_routes.py
tests/unit/agent/workflows/test_agentic_programming_agent.py
tests/component/webui/settings/test_memory_settings_routes.py
tests/unit/memory/test_memory_runtime_config.py
tests/unit/config/test_docs_information_architecture.py
tests/e2e/web/test_agents_configuration.py
```

**Commands**

```
# Documentation
python -m scripts.docs_site.build
python -m scripts.docs_site.checklinks
python -m scripts.docs_site.checklang
python -m scripts.docs_site.check_landing
uv run --locked --extra dev python -m pytest -q tests/unit/config/test_docs_information_architecture.py

# Final candidate
uv run --locked --extra dev python -m scripts.testing.affected_tests --base dev --run
npm --prefix apps/web run check
npm --prefix apps/web run build
uv run --locked --extra dev --extra browser python -m pytest -q -m browser tests/e2e/web
```

- Reconcile with `tests/README.md` and `.github/CONTRIBUTING.md` when implementing.
- Browser artifacts exercise the built production page.
- App acceptance: deploy to the development instance and check it there; see [Stable and development instances](https://fzkuji.github.io/OpenProgram/docs/reference/design/distribution/dev-instance.html).
- Source, tests, local commit, installed App and live deployment are separate evidence. A documentation build satisfies neither runtime nor App acceptance.

## P6: optional selection policy

Opt-in, runs before the resolver. A caller supplies a policy reference instead of `agent_id`/`config` (mutually exclusive). Candidates are saved Agent IDs or provider-qualified model references, never generated executable configuration. The policy declares its kind: a model choice keeps the caller's non-model fields; an Agent choice changes the base and follows normal history rules.

| Decision | Contract |
| --- | --- |
| Eligibility | Filter unavailable provider, account or model, required modality, structured output or tool support, context limit, authority and remaining resource cap before ranking |
| Ranking | Versioned ordered deterministic rules over task tags, required capabilities and caller preferences; model-assisted ranking is a separately enabled later mode |
| No match | Typed no-eligible-candidate error, or an explicitly configured eligible fallback before inference; never broaden authority |
| Trace | Policy version, eligible IDs, exclusions, chosen ID, rule identifier; no raw user content or unsupported cost and latency claims |
| Stability | Pinned for retries and resume; a new invocation may select again; an active tool loop never switches |
| Evaluation | Fixtures for correctness, no-match, denied candidate, unknown price metadata and deterministic replay; measured quality, cost and latency on an approved corpus before claims |

**Example Agent-kind policy**

- Tag `classify` and structured output required: first eligible saved Agent with a selected small model.
- Tag `code-edit` and tools required: a selected saved coding Agent.
- Otherwise: a specified saved default Agent.

A model-kind policy returns only model references. Candidate IDs and thresholds are user-configured, not hardcoded rankings. Missing price or latency means unknown, not free or fast.

## Known risks

| Risk | Treatment |
| --- | --- |
| Memory content appears in derived history | Propagate write restrictions through context dependencies and summaries; test cross-Agent transfer |
| A plugin cannot enforce namespace isolation | Expose unsupported readiness; block scoped binding; no prompt-only isolation claim |
| Concurrent files and default index lifecycle | Journal with recovery and idempotence; mutation authority in one manager |
| Old clients overwrite newly typed fields | Dual-reader, conditional write, explicit errors; no silent downgrade |
| Snapshots contain personal instructions | Existing execution storage ACLs and retention; diagnostics show hashes and references, not prompt text |
| UI ahead of runtime | Feature readiness follows verified backend support; prototype status stays explicit |

No product decision blocks P0. Exact consumer paths and backend revocation support are found during implementation, with the fail-closed behaviour above; a backend that cannot meet it stays unsupported.

## Implementation status

| Stage | Implemented | Planned |
| --- | --- | --- |
| P0 | Revision/CAS, compatible reads | Schema 2 migration, transactional lifecycle |
| P1 | Existing runtime resolution and capability policies reused | Unified resolver, effective preview |
| P2 | Execution, background extraction, derived eligibility and recovery policy for `self` and `legacy_global` |  |
| P3 | Saved Web configurations and trial snapshots | Full Python, CLI and scheduler entry parity |
| P4 | Eight sections, shared drafts, model selection, conflict comparison | Embedded trial, effective preview |
| P5 | Duplication, deletion, product docs | Portable import/export |
| P6 |  | All |
