Compare commits
14 Commits
main
...
5bb22d984e
| Author | SHA1 | Date | |
|---|---|---|---|
| 5bb22d984e | |||
| 4c4d44ef87 | |||
| e9246828b3 | |||
| 7ee49ab352 | |||
| e94b2493e7 | |||
| ad371b2ec4 | |||
| ed104e5697 | |||
| f040493583 | |||
| d9214c671a | |||
| c8410946b8 | |||
| 2976dfab21 | |||
| 69012b2656 | |||
| 0851171a71 | |||
| 4fefe0ab33 |
58
.agents/plans/README.md
Normal file
58
.agents/plans/README.md
Normal file
@@ -0,0 +1,58 @@
|
||||
# Plans
|
||||
|
||||
One directory per iteration of this agent. Each holds the plan for that iteration and, for finished steps, the record of what was built. Read the row for the iteration you are working in, then its `MAP.md`.
|
||||
|
||||
## Iterations
|
||||
|
||||
| # | Directory | Status | What it is |
|
||||
|---|---|---|---|
|
||||
| 1 | `wf-decompose-65ea49fc2d04/` | complete, superseded | The decomposer's scaffold: a linear four-phase pipeline of template functions. Its code was deleted in iteration 3 and survives only in git history. Generated by the platform decomposer; leave its files as written. |
|
||||
| 2 | `iter-02-solution-architect-agent/` | complete; step 9 was done in iteration 3 | The rebuild as a hierarchical ReAct agent: Orchestrator, one Specialist per Deliverable, Skills, provider bundle, A2A. |
|
||||
| 3 | `iter-03-kab-layout/` | complete (commit `7ee49ab`) | The container starts the new engine, the engine moved into the KAB workflow-agent folder layout, and the original pipeline was deleted. |
|
||||
| 4 | `iter-04-learning-and-skills/` | steps 1–8, 11, 13 and 15–20 built; no evaluation run has completed on them, so their effect on time and tokens is unmeasured; 9 awaits the owner; 10, 12 and 14 planned | The enhancement backlog from the 2026-10-06 review: cheap fixes, the learning loop through Skills, overlay Skills, provider neutrality. Steps 17–20 are the speed-ups from the 2026-10-07 run: a working copy for files and the graph, a provider schema lookup, routing a Check the code cannot meet, and a model timeout per role. |
|
||||
| 5 | `iter-05-jev-decisions/` | the Jev client and the Orchestrator router are built (steps 2, 11, 12), unverified against the live service; the rest planned | Jev (a hosted decision model) for the agent's closed decisions: checks, routing, context selection. |
|
||||
| 6 | `iter-06-target-architecture-graph/` | steps 1–10 built; step 11's evaluation run is outstanding, so unproven with real models | The Target architecture as one explicit graph of Elements, Relationships and Checks, established before infrastructure code, with validation as a verdict per Check. |
|
||||
| 7 | `iter-07-change-requests/` | planned; ADR-0006 accepted 2026-10-07; follows iteration 6; its step 8 (removing `deliverables/cases/legacy-baseline/`) was done early on the owner's instruction | A user restates a request to say how requirements changed; a new Execution starts from a Baseline Execution of the same Customer case and delivers the updated architecture with what changed. |
|
||||
|
||||
Numbers record when an iteration was planned, not the order to build in. Build iteration 6 before the remaining steps of iteration 4 (10 to 14) and before iteration 5: it changes the Deliverables, Phases and validation format they build on. Its `MAP.md` lists the effect on each of their steps.
|
||||
|
||||
Two designs sit between iterations 1 and 2 and have no plan directory. Commit `a24a44e` wrapped the pipeline in a compatibility layer that imitated Google ADK without using it (deleted in iteration 3). `.scratch/phase-pipeline/spec.md` then designed a code-sequenced Phase pipeline; ADR-0002 reopened it before any of it was built, and its decision log (D1 to D46) explains how iteration 2's design was reached.
|
||||
|
||||
## Files in an iteration
|
||||
|
||||
- `MAP.md`: the intent, each step's status, the dependency graph between steps, and the sources of truth to read.
|
||||
- `DETAIL.md`: per step, the capability, why it exists (with evidence), where the change lands, and the acceptance criteria.
|
||||
- `steps/step-N.md`: written when step N is finished. What was built, what differed from the plan, and how it was verified. A step with no file is not done.
|
||||
|
||||
Steps are numbered from 1 in iterations 2 onward. Iteration 1 numbers from 0.
|
||||
|
||||
## Working in an iteration
|
||||
|
||||
1. Read `MAP.md`, then the `DETAIL.md` entry for your step and every step it depends on.
|
||||
2. Read the sources of truth `MAP.md` names. Plans point at specs and ADRs; they repeat only what those lack.
|
||||
3. Build the step until every acceptance criterion in its `DETAIL.md` entry holds and `.venv/bin/python -m pytest -q`, `.venv/bin/ruff check .` and `.venv/bin/mypy .` all pass.
|
||||
4. Write `steps/step-N.md` and set the step's status in `MAP.md` to `complete`. When the last step closes, update the iteration's row above.
|
||||
|
||||
A new iteration gets the next number, a directory `iter-NN-<slug>/`, and a row above.
|
||||
|
||||
## Module paths changed in iteration 3
|
||||
|
||||
Iteration 2's spec and ADR text name the modules by their old paths. The code is here now:
|
||||
|
||||
| Old path | Current path |
|
||||
|---|---|
|
||||
| `app/execution/deliverables.py` | `app/workflows/deliverables.py` |
|
||||
| `app/execution/graph.py` | `app/nodes/execution_nodes.py` (nodes) and `app/workflows/execution_graph.py` (wiring) |
|
||||
| `app/execution/engine.py`, `app/assembly.py` | `app/agent.py` |
|
||||
| `app/execution/state.py` | `app/states/execution_state.py` |
|
||||
| `app/execution/ledger.py` | `app/states/ledger.py` |
|
||||
| `app/execution/tools.py`, `toolkit.py`, `pillars.py` | `app/tools/execution.py`, `app/tools/toolkit.py`, `app/tools/pillars.py` |
|
||||
| `app/execution/recorder.py`, `checkpointing.py`, `presentation.py` | `app/recorder.py`, `app/checkpointing.py`, `app/presentation.py` |
|
||||
| `app/agents/{runtime,adk_runtime,fake_runtime,roles}.py` | `app/adk/` (same file names) |
|
||||
| `app/agent_skills.py` | `app/skills/agent_skills.py` |
|
||||
| `app/a2a/server.py`, `executor.py`, `card.py` | `app/main.py`, `app/a2a_server.py`, `app/card.py` |
|
||||
| the pre-rebuild `app/agent.py`, `app/card.py`, `app/adk/`, `app/nodes/`, `app/workflows/`, `app/skills/`, `app/states/` deleted; in git history up to `e94b249` |
|
||||
| `tests/test_{adk_architecture,agent_api,graph_workflow,mcp_developer_knowledge,skill_loader}.py` | deleted |
|
||||
| `eval/{metrics,optimizer,eval_harness,test_eval_harness}.py`, `eval/datasets/benchmark_cases.json` | deleted |
|
||||
|
||||
`app/adk/`, `app/nodes/`, `app/workflows/`, `app/skills/` and `app/states/` therefore mean different code before and after iteration 3. In text written before 2026-10-06, those names refer to the deleted original pipeline.
|
||||
65
.agents/plans/iter-02-solution-architect-agent/DETAIL.md
Normal file
65
.agents/plans/iter-02-solution-architect-agent/DETAIL.md
Normal file
@@ -0,0 +1,65 @@
|
||||
# Plan Detail
|
||||
|
||||
The spec is the full design. Each entry here gives the step's purpose, the rule it must keep, and its acceptance criteria. Paths are current (post iteration 3).
|
||||
|
||||
## Step 1: Environment and baseline
|
||||
|
||||
- **Capability:** A reproducible environment and a recorded test baseline to compare every later step against.
|
||||
- **Rationale:** Later steps claim "the suite stays green"; that needs a starting count.
|
||||
- **Where:** `.venv/`, `requirements.txt`, `requirements-dev.txt`.
|
||||
- **Acceptance criteria:** The existing suite runs and its result is recorded in the spec's comments.
|
||||
|
||||
## Step 2: Vendored Skills and provider bundle
|
||||
|
||||
- **Capability:** Upstream Skills available unmodified, and a Cloud provider expressed as configuration.
|
||||
- **Rationale:** ADR-0002. Upstream changes must arrive as a diff, and a second Cloud provider must be addable without touching the core.
|
||||
- **Where:** `skills/vendor/google/` (pinned to upstream commit `81a31a6`, with `VENDOR.md`, `LICENSE`, `SHA256SUMS`), `scripts/sync-vendored-skills.sh`, `providers/gcp.yaml`, `app/providers.py`, `app/skills/agent_skills.py`.
|
||||
- **Acceptance criteria:** Vendored files match their checksums. Every Skill under `skills/` passes the Agent Skills frontmatter rules. Only `app/providers.py` names a provider.
|
||||
|
||||
## Step 3: Deliverables and Ledger
|
||||
|
||||
- **Capability:** The dependency graph of Deliverables as data, and a pure Ledger that enforces acceptance, Approval and Revision rules.
|
||||
- **Rationale:** ADR-0003. Dependencies are guaranteed by code; ordering is the model's choice.
|
||||
- **Where:** `app/workflows/deliverables.py` (the only place Phases, Deliverables and Dependencies are declared), `app/states/ledger.py`.
|
||||
- **Acceptance criteria:** A Dependency inside a Phase is met on submission; across Phases only on Approval. Reopening a Deliverable returns it and its dependents to draft and withdraws affected Approvals. Revisions are capped.
|
||||
|
||||
## Step 4: Execution graph
|
||||
|
||||
- **Capability:** A checkpointed LangGraph Execution that pauses for the user, behind one `ExecutionEngine` interface.
|
||||
- **Rationale:** ADR-0003. Resumable, recordable progress at every step, with framework types kept out of state.
|
||||
- **Where:** `app/adk/runtime.py` (interface), `app/adk/fake_runtime.py`, `app/states/execution_state.py`, `app/tools/execution.py`, `app/nodes/execution_nodes.py`, `app/workflows/execution_graph.py`, `app/agent.py`, `app/recorder.py`, `app/checkpointing.py`.
|
||||
- **Acceptance criteria:** Only `orchestrator_turn` and `await_user` change the Ledger. No Approval is ever granted from free text. Cloud-read tools are unreachable without permission. All of it is tested with the fake runtime and no model.
|
||||
|
||||
## Step 5: ADK runtime and role files
|
||||
|
||||
- **Capability:** Real ADK `LlmAgent`s running role files with scoped Skills, behind the runtime interface.
|
||||
- **Rationale:** ADR-0003. Each agent runs its own ReAct loop; Skills load on demand through `SkillToolset`.
|
||||
- **Where:** `app/adk/adk_runtime.py` (the only module that imports `google.adk`), `app/adk/roles.py`, `agents/*.md`, `agents/partials/specialist-protocol.md`, `app/tools/pillars.py`.
|
||||
- **Acceptance criteria:** Role files carry no Skill, MCP server or model names; the bundle supplies them. `run_skill_script` is never offered. Each pillar advisor loads only its own pillar Skill.
|
||||
|
||||
## Step 6: Tools and remote MCP servers
|
||||
|
||||
- **Capability:** Local check tools and the Cloud provider's hosted MCP servers, exposed through reviewed read-only allowlists.
|
||||
- **Rationale:** ADR-0002. No hand-written cloud API clients; reading a user's cloud needs their permission.
|
||||
- **Where:** `app/tools/local.py`, `app/tools/mcp.py`, `app/tools/toolkit.py`, `providers/gcp.yaml` (`mcp_servers`, `role_mcp_servers`), `skills/cloud-discovery/`, `skills/iac-validation/`, `docs/operations/mcp-access.md`, `providers/reviews/gcp-mcp-tools.json`.
|
||||
- **Acceptance criteria:** Only allowlisted tools are exposed. No tool can apply, deploy or run a script. An unavailable server becomes a recorded discovery gap, not a failure.
|
||||
|
||||
## Step 7: Interfaces
|
||||
|
||||
- **Capability:** Interactive Executions over A2A, and a pre-approved one-shot `/generate`.
|
||||
- **Rationale:** Spec decision D28.
|
||||
- **Where:** `app/main.py`, `app/a2a_server.py`, `app/card.py`, `app/presentation.py`.
|
||||
- **Acceptance criteria:** Approvals travel as structured data. The agent card is derived from the dependency graph. `/generate` response keys are unchanged from iteration 1.
|
||||
|
||||
## Step 8: Evaluation
|
||||
|
||||
- **Capability:** A real-model evaluation of the whole engine with scripted user answers.
|
||||
- **Rationale:** The gate for cleanup: proceed only when every case scores at least 0.8.
|
||||
- **Where:** `eval/solution_eval.py`, `eval/scoring.py`, `eval/datasets/solution_cases.json`, `tests/eval/`.
|
||||
- **Acceptance criteria:** Each benchmark case completes and reaches `PASS_THRESHOLD` (0.8) on the 8 checks in `eval/scoring.py`.
|
||||
|
||||
## Step 9: Cleanup
|
||||
|
||||
- **Capability:** One code path: the legacy pipeline removed and the new engine the only engine.
|
||||
- **Status:** Done in iteration 3, by a different route. On 2026-10-06 the engine first moved into the KAB folder layout, and the legacy pipeline was then deleted (`iter-03-kab-layout/steps/step-7.md`).
|
||||
- **Not done from the spec's list:** the sample artefacts the pipeline once wrote (`docs/*.md`, root `terraform/`, `deliverables/{as-is,target,validation,guides}/`) are still checked in.
|
||||
38
.agents/plans/iter-02-solution-architect-agent/MAP.md
Normal file
38
.agents/plans/iter-02-solution-architect-agent/MAP.md
Normal file
@@ -0,0 +1,38 @@
|
||||
# Plan Map
|
||||
|
||||
**Iteration:** 2, solution architect agent
|
||||
**Intent:** Replace the linear template pipeline with a portable, hierarchical ReAct agent that runs the upstream `google-cloud-solution-architecture` Skill's workflow. An Orchestrator reasons over a code-declared dependency graph of Deliverables and delegates to one Specialist per Deliverable. Behaviour lives in Agent Skills; the Cloud provider is configuration.
|
||||
**Branch:** `feat/solution-architect-agent`
|
||||
**This directory covers:** steps 1 to 9, the spec's build increments 1 to 9
|
||||
|
||||
## Sources of truth
|
||||
|
||||
- `.scratch/solution-architect-agent/spec.md`: the design, the decisions table, the acceptance list, and a dated `## Comments` entry per finished increment. Its module paths predate iteration 3; translate them with the table in `../README.md`.
|
||||
- `docs/adr/0002-skills-are-the-portable-unit-of-behaviour.md` and `docs/adr/0003-langgraph-holds-state-adk-agents-reason.md`: the two decisions every step serves.
|
||||
- `CONTEXT.md`: the glossary. Use its terms.
|
||||
|
||||
## Status
|
||||
|
||||
| Step | Increment | Status | Commit |
|
||||
|---|---|---|---|
|
||||
| 1 | Environment and baseline | complete | `0851171` |
|
||||
| 2 | Vendored Skills and provider bundle | complete | `2976dfa` |
|
||||
| 3 | Deliverables and Ledger | complete | `c841094` |
|
||||
| 4 | Execution graph | complete | `d9214c6` |
|
||||
| 5 | ADK runtime and role files | complete | `f040493` |
|
||||
| 6 | Tools and remote MCP servers | complete | `ed104e5` |
|
||||
| 7 | Interfaces (A2A, `/generate`) | complete | `ad371b2` |
|
||||
| 8 | Evaluation | complete | `7ee49ab` |
|
||||
| 9 | Cleanup | done in iteration 3 | none |
|
||||
|
||||
## Dependency graph
|
||||
|
||||
- Step 1: no dependencies
|
||||
- Step 2: depends on step 1
|
||||
- Step 3: depends on step 1
|
||||
- Step 4: depends on step 3
|
||||
- Step 5: depends on step 2, step 4
|
||||
- Step 6: depends on step 2, step 5
|
||||
- Step 7: depends on step 4, step 5, step 6
|
||||
- Step 8: depends on step 7
|
||||
- Step 9: depends on step 8 passing its threshold
|
||||
@@ -0,0 +1,7 @@
|
||||
# Step 1 — Implementation Detail
|
||||
|
||||
1. Created `.venv/` on Python 3.12.3 and installed both requirements files. `google-adk` resolved to 2.9.0, `langgraph` to 1.2.11.
|
||||
2. Recorded the baseline: 30 tests passed across the iteration 1 suite.
|
||||
3. Found that the iteration 1 "ADK" layer never used `google-adk`: `HAS_NATIVE_ADK` stayed false even with the package installed.
|
||||
|
||||
Full record: spec `## Comments`, "2026-09-15 · Increment 1".
|
||||
@@ -0,0 +1,7 @@
|
||||
# Step 2 — Implementation Detail
|
||||
|
||||
1. Vendored 7 upstream Skills (solution architecture plus six Well-Architected Framework pillars) at commit `81a31a6`, with checksums verified by `tests/test_vendored_skills.py`.
|
||||
2. Added the provider bundle `providers/gcp.yaml` and its loader, and the Agent Skills frontmatter validator.
|
||||
3. Suite: 65 passed.
|
||||
|
||||
Full record: spec `## Comments`, "2026-09-15 · Increment 2".
|
||||
@@ -0,0 +1,8 @@
|
||||
# Step 3 — Implementation Detail
|
||||
|
||||
1. Declared 9 Deliverables in 4 Phases as data, with section and attachment contracts checked by `check_submission`.
|
||||
2. Built the Ledger as pure code with no I/O, serialisable into graph state.
|
||||
3. `technical_decomposition` and `architecture_description` were left with a non-empty-content contract only. Iteration 4 step 4 revisits this.
|
||||
4. Suite: 102 passed.
|
||||
|
||||
Full record: spec `## Comments`, "2026-09-15 · Increment 3".
|
||||
@@ -0,0 +1,9 @@
|
||||
# Step 4 — Implementation Detail
|
||||
|
||||
1. Built the graph test-first: `orchestrator_turn`, parallel `specialist_task` via `Send`, `await_user` via `interrupt`, `finalize`, `end_with_warnings`.
|
||||
2. Added `ExecutionEngine` (`start`, `resume`, `interaction`) as the single interface; the graph is an internal detail behind it.
|
||||
3. Added the `Stopped` outcome, the single-writer rule for Specialist outcomes, and `MAX_ORCHESTRATOR_TURNS` as the loop guard.
|
||||
4. Verified the tests bite by breaking the cloud-read gate, the permission prompt, question relay and the submission contract in turn; each break failed a test.
|
||||
5. Suite: 121 passed.
|
||||
|
||||
Full record, including prompt and reply shapes: spec `## Comments`, "2026-09-15 · Increment 4".
|
||||
@@ -0,0 +1,8 @@
|
||||
# Step 5 — Implementation Detail
|
||||
|
||||
1. Implemented `AdkAgentRuntime`: a fresh `LlmAgent` and in-memory session per run, tool-call budgets, and nudges when an agent stops without ending its turn.
|
||||
2. Wrote the 11 role files and the shared Specialist protocol; the role loader rejects any field the bundle should own.
|
||||
3. Added the design advisor's fan-out to six pillar advisors.
|
||||
4. Suite: 158 passed.
|
||||
|
||||
Full record: spec `## Comments`, "2026-09-16 · Increment 5".
|
||||
@@ -0,0 +1,9 @@
|
||||
# Step 6 — Implementation Detail
|
||||
|
||||
1. Added local tools `mermaid_check`, `terraform_fmt`, `terraform_validate` and `terraform_plan`, each running on a scratch copy.
|
||||
2. Added the remote MCP catalog with Application Default Credentials and per-server allowlists, reviewed on 2026-09-16 against each server's live tool list.
|
||||
3. Excluded data-content tools even where read-only (SQL queries, object reads, generic Kubernetes reads).
|
||||
4. Wrote the `cloud-discovery` and `iac-validation` Skills.
|
||||
5. Suite: 189 passed.
|
||||
|
||||
Full record: spec `## Comments`, "2026-09-16 · Increment 6".
|
||||
@@ -0,0 +1,7 @@
|
||||
# Step 7 — Implementation Detail
|
||||
|
||||
1. Added the A2A server (JSON-RPC at `/a2a`, agent card, `/health`) and the executor that maps A2A tasks to Executions and their prompts.
|
||||
2. Kept `/generate` as a pre-approved one-shot Execution.
|
||||
3. Suite: 206 passed.
|
||||
|
||||
Full record: spec `## Comments`, "2026-09-16 · Increment 7".
|
||||
@@ -0,0 +1,22 @@
|
||||
# Step 8 — Implementation Detail
|
||||
|
||||
This step has no entry in the spec's comments; this file is its record.
|
||||
|
||||
1. Added `eval/solution_eval.py`: runs each case as a pre-approved Execution through the full assembly with real models, counting agent runs, outcomes, seconds and tokens per role.
|
||||
2. Added `eval/scoring.py` with 8 checks: completed, guide follows the template, required products selected, alternatives listed, documentation cited, requirements name no products, diagram is valid Mermaid, Terraform validates.
|
||||
3. Added 3 cases in `eval/datasets/solution_cases.json`. Results are written to `eval/results/<timestamp>/` (gitignored).
|
||||
|
||||
Recorded runs:
|
||||
|
||||
| Run | Case | Score | Seconds | Revisions |
|
||||
|---|---|---|---|---|
|
||||
| 2026-09-16 10:57Z | case-01-event-driven-http | 1.0 | 2,932 | design_recommendations × 2 |
|
||||
| 2026-09-17 08:44Z | case-03-internal-web-app | 1.0 | 2,623 | deployment_guidance × 3 |
|
||||
|
||||
No scored run of `case-02-high-scale-ingestion` is on record.
|
||||
|
||||
Case 03 used 3.27 million tokens over 127 model requests. By role: IaC author 812 thousand, validator 618 thousand, describer 513 thousand, Orchestrator 356 thousand, product selector 345 thousand. These figures are the evidence base for iterations 4 and 5.
|
||||
|
||||
All 8 checks are structural, so a better or worse Skill scores the same. Iteration 4 step 8 addresses that.
|
||||
|
||||
Suite at the end of this step: 226 passed.
|
||||
55
.agents/plans/iter-03-kab-layout/DETAIL.md
Normal file
55
.agents/plans/iter-03-kab-layout/DETAIL.md
Normal file
@@ -0,0 +1,55 @@
|
||||
# Plan Detail
|
||||
|
||||
## Step 1: Container starts the Execution engine
|
||||
|
||||
- **Capability:** The image runs the reviewed and evaluated engine.
|
||||
- **Rationale:** The `Dockerfile` started `python -m app.agent`, the iteration 1 pipeline, while every evaluation ran the new engine.
|
||||
- **Where:** `Dockerfile`, `README.md`.
|
||||
- **Acceptance criteria:** The container's main process is the A2A server. `/health` and `/.well-known/agent-card.json` answer on the container port. Existing `-p 8080:8080` run commands still work.
|
||||
|
||||
## Step 2: Legacy pipeline moved to `app/legacy/`
|
||||
|
||||
- **Capability:** The KAB folder names are free for the new engine, with the old pipeline still importable and tested.
|
||||
- **Rationale:** The owner chose to keep the old code rather than delete it (2026-10-06). The old and new code cannot share `app/nodes/`, `app/states/`, `app/workflows/`.
|
||||
- **Where:** `app/legacy/`, the five legacy tests in `tests/`, `eval/eval_harness.py`, `SKILLS_DIR` in `app/config.py`.
|
||||
- **Acceptance criteria:** Every legacy test passes against `app.legacy.*`. Nothing outside `app/legacy/`, those tests and the legacy eval files imports `app.legacy`.
|
||||
|
||||
## Step 3: Engine moved into the KAB folders
|
||||
|
||||
- **Capability:** The engine's modules sit where the KAB workflow standard expects them.
|
||||
- **Rationale:** Platform consistency: decomposers, reviewers and other agents on the platform look for state in `app/states/`, nodes in `app/nodes/`, graphs in `app/workflows/`, the manager in `app/agent.py`.
|
||||
- **Where:** The path table in `../README.md`.
|
||||
- **Acceptance criteria:** Behaviour is unchanged: the full suite passes with only import paths edited in tests. `google.adk` is still imported only by `app/adk/adk_runtime.py`. Package `__init__.py` files import nothing, so `app.states` can import `app.workflows.deliverables` without a cycle.
|
||||
|
||||
## Step 4: Graph file split into nodes and wiring
|
||||
|
||||
- **Capability:** Node logic in `app/nodes/`, graph assembly in `app/workflows/`.
|
||||
- **Rationale:** The KAB layout separates stage nodes from graph construction; the engine had both in one 560-line file.
|
||||
- **Where:** `app/nodes/execution_nodes.py` (`make_execution_nodes` returns an `ExecutionNodes` of the five node callables), `app/workflows/execution_graph.py` (`build_execution_graph`), `ToolFactory` in `app/adk/runtime.py`.
|
||||
- **Acceptance criteria:** `build_execution_graph` keeps its signature. The nodes still route with `Command` and `Send`, so the wiring declares only the fixed edges.
|
||||
|
||||
## Step 5: Refresh paths in the spec and ADR text
|
||||
|
||||
- **Capability:** Design documents that name modules where they are.
|
||||
- **Rationale:** `.scratch/solution-architect-agent/spec.md` (module layout, acceptance list, comments) and the ADRs still use pre-move paths. An agent following them will look in `app/legacy/` or in folders that no longer exist.
|
||||
- **Where:** `.scratch/solution-architect-agent/spec.md` sections "Module layout" and "Acceptance"; `docs/adr/0002-*.md` consequence about `app/skills/`; `docs/adr/0003-*.md`.
|
||||
- **Acceptance criteria:** The spec's module layout matches the tree. Each acceptance command in the spec runs against current paths. Dated `## Comments` entries stay as written, since they are history; one note at the top of the comments points to `../README.md` for translation.
|
||||
|
||||
## Step 6: Finish iteration 2's cleanup list
|
||||
|
||||
- **Capability:** The parts of iteration 2 step 9 that still apply once the legacy code is kept.
|
||||
- **Rationale:** The spec's cleanup list mixed deletions (now dropped) with changes the new engine still needs.
|
||||
- **Where and what:**
|
||||
- `workflow.yaml`: rewrite its phases to the four upstream Phases and their Deliverables.
|
||||
- `app/config.py`, `.env.example`: move settings only `app/legacy/` reads (`HOST`, `PORT`, `GCP_PROJECT_ID`, `GCP_REGION`, `ADK_*`, `DEVELOPER_KNOWLEDGE_MCP_*`, `SKILLS_DIR`, `EVAL_DATASET_PATH`, the OpenAI and Azure keys) under a clearly marked legacy block. Keep `POSTGRES_*` and `DATABASE_URL`: the Postgres checkpointer builds its URL from them.
|
||||
- `mypy.ini`, `ruff.toml`: exclude `app/legacy/` and the legacy eval files, so `ruff check .` and `mypy .` report on live code only (198 and 38 findings today, almost all legacy).
|
||||
- `Dockerfile`: stop copying what only the legacy pipeline reads, once step 7 is decided.
|
||||
- **Acceptance criteria:** `ruff check .` and `mypy .` are clean or list only known, recorded exceptions. `workflow.yaml` names the four Phases in `app/workflows/deliverables.py`. The suite passes.
|
||||
|
||||
## Step 7: Decide the future of `app/legacy/`
|
||||
|
||||
- **Capability:** One code path, or a deliberate, documented second one.
|
||||
- **Rationale:** Two pipelines cost every reader a detour, and the legacy one holds what ADR-0002 rules out: hand-written cloud clients, non-conformant Skills, a pretend ADK layer.
|
||||
- **Options for the owner:** delete `app/legacy/` with its tests and the legacy eval files; or keep it frozen and excluded from lint, types and the image.
|
||||
- **Guardrail:** Deleting files with uncommitted changes was blocked once by the permission system. Commit first, then delete in a commit of its own.
|
||||
- **Acceptance criteria:** The decision is recorded here. If deleted: `grep -rn "app\.legacy" app eval tests` is empty and the suite passes.
|
||||
34
.agents/plans/iter-03-kab-layout/MAP.md
Normal file
34
.agents/plans/iter-03-kab-layout/MAP.md
Normal file
@@ -0,0 +1,34 @@
|
||||
# Plan Map
|
||||
|
||||
**Iteration:** 3, KAB layout
|
||||
**Intent:** Make the deployed container run the hierarchical Execution engine, and house that engine in the KAB workflow-agent folder layout (`app/agent.py`, `app/main.py`, `app/a2a_server.py`, `app/states/`, `app/nodes/`, `app/workflows/`), with the iteration 1 pipeline first parked under `app/legacy/` (steps 2 to 6) and then deleted (step 7).
|
||||
**Branch:** `feat/solution-architect-agent` (committed in `7ee49ab`, 2026-10-06)
|
||||
**This directory covers:** steps 1 to 7
|
||||
|
||||
## Sources of truth
|
||||
|
||||
- `../README.md`: the old-to-new module path table.
|
||||
- `../docs/KAB_WORKFLOW_AGENT_IMPLEMENTATION_GUIDE.md` and `../langgraph-workflow-agent/app/`, both relative to the repository root: the layout being matched.
|
||||
- `docs/adr/0003-langgraph-holds-state-adk-agents-reason.md`: the engine the layout must keep unchanged.
|
||||
|
||||
## Status
|
||||
|
||||
| Step | What | Status |
|
||||
|---|---|---|
|
||||
| 1 | Container starts the Execution engine | complete |
|
||||
| 2 | Legacy pipeline moved to `app/legacy/` | complete |
|
||||
| 3 | Engine moved into the KAB folders | complete |
|
||||
| 4 | Graph file split into nodes and wiring | complete |
|
||||
| 5 | Refresh paths in the spec and ADR text | complete |
|
||||
| 6 | Finish iteration 2's cleanup list | complete; two items carried forward in `steps/step-6.md` |
|
||||
| 7 | Decide the future of `app/legacy/` | complete: deleted on the owner's instruction |
|
||||
|
||||
## Dependency graph
|
||||
|
||||
- Step 1: no dependencies
|
||||
- Step 2: no dependencies
|
||||
- Step 3: depends on step 2
|
||||
- Step 4: depends on step 3
|
||||
- Step 5: depends on step 4
|
||||
- Step 6: depends on step 4
|
||||
- Step 7: depends on step 6
|
||||
16
.agents/plans/iter-03-kab-layout/steps/step-1.md
Normal file
16
.agents/plans/iter-03-kab-layout/steps/step-1.md
Normal file
@@ -0,0 +1,16 @@
|
||||
# Step 1 — Implementation Detail
|
||||
|
||||
1. `Dockerfile`: the start command became the A2A server; the image sets `A2A_HOST=0.0.0.0` and `A2A_PORT=8080`; only port 8080 is exposed.
|
||||
2. The health check reads `A2A_PORT` and allows 60 seconds to start, because `/health` answers only after the provider bundle and MCP catalogs load.
|
||||
3. `README.md`: server section, start command, container example (now passing `GOOGLE_GENAI_USE_VERTEXAI`, `GOOGLE_CLOUD_PROJECT`, `GOOGLE_CLOUD_LOCATION`, `A2A_PUBLIC_URL`) and test calls.
|
||||
|
||||
Verified: built with podman and ran the image with `MCP_ENABLED=false`; `/health` and the agent card returned 200 and process 1 was the server.
|
||||
|
||||
Consequences for callers:
|
||||
|
||||
- `/card`, `/validate` and `/sessions/{session_id}` are no longer served. The card is at `/.well-known/agent-card.json`.
|
||||
- `/generate` now runs a full pre-approved Execution with real models, about 45 minutes in the evaluation runs.
|
||||
- Without `A2A_PUBLIC_URL` the card advertises `http://0.0.0.0:8080/a2a`.
|
||||
- Podman's default image format ignores `HEALTHCHECK`.
|
||||
|
||||
Not verified: a full Execution with real models and MCP servers inside the container.
|
||||
9
.agents/plans/iter-03-kab-layout/steps/step-2.md
Normal file
9
.agents/plans/iter-03-kab-layout/steps/step-2.md
Normal file
@@ -0,0 +1,9 @@
|
||||
# Step 2 — Implementation Detail
|
||||
|
||||
1. Moved `app/agent.py`, `app/card.py`, `app/adk/`, `app/nodes/`, `app/workflows/`, `app/skills/`, `app/states/` to `app/legacy/`, and `gcp_scanner.py`, `mcp_developer_knowledge.py`, `validation_tools.py` to `app/legacy/tools/`.
|
||||
2. Rewrote imports to `app.legacy.*` in the legacy code, its five tests (`test_adk_architecture`, `test_agent_api`, `test_graph_workflow`, `test_mcp_developer_knowledge`, `test_skill_loader`) and `eval/eval_harness.py`.
|
||||
3. Pointed `SKILLS_DIR` at `app/legacy/skills`, and the paths quoted in `eval/optimizer.py` likewise.
|
||||
|
||||
Verified: 226 passed before any engine file moved; `python -m eval.eval_harness` still runs.
|
||||
|
||||
Nothing was deleted. A first attempt to delete these files was blocked by the permission system because 25 of them held uncommitted changes.
|
||||
10
.agents/plans/iter-03-kab-layout/steps/step-3.md
Normal file
10
.agents/plans/iter-03-kab-layout/steps/step-3.md
Normal file
@@ -0,0 +1,10 @@
|
||||
# Step 3 — Implementation Detail
|
||||
|
||||
1. Moved each engine module to the path in `../../README.md`. `app/execution/`, `app/agents/` and `app/a2a/` no longer exist.
|
||||
2. Merged `engine.py` and `assembly.py` into `app/agent.py`: `ExecutionEngine`, `Interaction`, then `Assembly` and `open_assembly`.
|
||||
3. The entry point is `python -m app.main`; `Dockerfile` and `README.md` use it.
|
||||
4. Left the test folders (`tests/execution/`, `tests/agents/`, `tests/a2a/`) where they were; only their imports changed.
|
||||
|
||||
Verified: 226 passed; the rebuilt image starts `python -m app.main` and answers `/health` and the agent card.
|
||||
|
||||
Side effect: ruff's import sort and unused-import fix ran across `app`, `eval`, `tests` and `scripts`, so legacy and test files show import-only diffs.
|
||||
9
.agents/plans/iter-03-kab-layout/steps/step-4.md
Normal file
9
.agents/plans/iter-03-kab-layout/steps/step-4.md
Normal file
@@ -0,0 +1,9 @@
|
||||
# Step 4 — Implementation Detail
|
||||
|
||||
1. `app/nodes/execution_nodes.py` keeps the five nodes as closures over the runtime, roles, recorder and tool factory, built by `make_execution_nodes` and returned as a frozen `ExecutionNodes`. The helper functions and `GUIDE_FILENAME` moved with them.
|
||||
2. `app/workflows/execution_graph.py` holds `build_execution_graph`, which builds the nodes and declares the fixed edges.
|
||||
3. `ToolFactory` moved to `app/adk/runtime.py`, beside `ToolSpec`, so `app/tools/toolkit.py` no longer imports the nodes module.
|
||||
|
||||
The node bodies were moved verbatim; no logic changed.
|
||||
|
||||
Verified: 226 passed; the moved files are ruff-clean.
|
||||
11
.agents/plans/iter-03-kab-layout/steps/step-5.md
Normal file
11
.agents/plans/iter-03-kab-layout/steps/step-5.md
Normal file
@@ -0,0 +1,11 @@
|
||||
# Step 5 — Implementation Detail
|
||||
|
||||
1. `.scratch/solution-architect-agent/spec.md`: replaced the "Module layout" tree with the current one, and updated every module path in the design sections (Deliverables, Ledger, Execution graph, tools, agent runtime, A2A, recording) and in the Risks section.
|
||||
2. Rewrote two acceptance commands to match the tree:
|
||||
- `rg -n "google\.adk" app -g '!app/legacy/**' | grep -v adk_runtime.py` is empty.
|
||||
- `rg -n "app\.legacy" app eval tests -g '!**/legacy/**'` is empty.
|
||||
3. Marked build increment 9 as replaced, with a pointer here; its original list stays below the note.
|
||||
4. Left the dated `## Comments` entries as written and added one note above them pointing to `../../README.md` for path translation.
|
||||
5. `docs/adr/0002-*.md`: added a dated note to the `app/skills/` consequence. ADR-0003 names no repository paths and needed no change.
|
||||
|
||||
Verified: both acceptance commands return nothing (run with `grep`).
|
||||
19
.agents/plans/iter-03-kab-layout/steps/step-6.md
Normal file
19
.agents/plans/iter-03-kab-layout/steps/step-6.md
Normal file
@@ -0,0 +1,19 @@
|
||||
# Step 6 — Implementation Detail
|
||||
|
||||
1. **Legacy grouped in three folders.** The five legacy tests moved to `tests/legacy/` and the offline harness (`metrics.py`, `optimizer.py`, `eval_harness.py`, `test_eval_harness.py`) to `eval/legacy/`. Run it with `python -m eval.legacy.eval_harness`. `eval/datasets/benchmark_cases.json` stayed where `EVAL_DATASET_PATH` points.
|
||||
2. **Lint and types on live code only.** `ruff.toml` and `mypy.ini` excluded `app/legacy`, `eval/legacy` and `tests/legacy` (exclusions removed again in step 7). `ruff check .` and `mypy .` are now clean, down from 198 and 38 findings.
|
||||
3. **Live findings fixed, none suppressed by config:**
|
||||
- `app/database.py`: modern annotations, an unused import removed, and each broad `except` marked with its reason (connection failure falls back to SQLite; persistence is best-effort and logged).
|
||||
- `app/workflows/execution_graph.py`: every node is cast for `add_node`, since the nodes are now typed callables.
|
||||
- `scripts/list-mcp-tools.py`, `scripts/validate_artifacts.py`, `tests/test_assembly.py`, `tests/test_package.py`, `tests/agents/test_adk_engine.py`, `tests/agents/test_adk_runtime.py`: small typing and lint fixes.
|
||||
- `requirements-dev.txt`: added `types-protobuf` and `types-psycopg2`.
|
||||
4. **Settings.** `app/config.py` and `.env.example` list live settings first and the legacy-only ones under a marked block. No setting was removed or renamed.
|
||||
5. **`workflow.yaml`** names the four Phases and their Deliverables. `tests/test_workflow_manifest.py` fails if it drifts from `app/workflows/deliverables.py`.
|
||||
6. **Image.** `Dockerfile` copies `app/`, `agents/`, `providers/`, `skills/` and `workflow.yaml` only, and creates `deliverables/`. A new `.dockerignore` keeps `app/legacy`, `.venv`, `.git`, caches, databases and past results out of the build context.
|
||||
|
||||
Verified: 227 passed; ruff and mypy clean; the rebuilt image contains no `app/legacy`, `eval/`, `docs/` or `terraform/`, and `/health` answers.
|
||||
|
||||
Still open from iteration 2's cleanup list:
|
||||
|
||||
- **Writes to shared paths.** The engine writes only under `deliverables/executions/<execution_id>/`. The legacy pipeline still writes `deliverables/{as-is,target,validation,guides}/` and `docs/*.md`, and `tests/legacy/` runs it, so a test run can modify tracked files. Step 7 deleted the legacy folders, which closed this item.
|
||||
- **CI.** `.github/workflows/ci.yml` pins `ruff==0.6.9` and `mypy==1.11.2` and installs no project dependencies; the local tools are newer (ruff 0.16.7). CI was not run for this step.
|
||||
15
.agents/plans/iter-03-kab-layout/steps/step-7.md
Normal file
15
.agents/plans/iter-03-kab-layout/steps/step-7.md
Normal file
@@ -0,0 +1,15 @@
|
||||
# Step 7 — Implementation Detail
|
||||
|
||||
Decision: **the original pipeline is deleted.** The owner asked for its removal on 2026-10-06, after it had first been kept frozen in `app/legacy/`, `tests/legacy/` and `eval/legacy/` (step 6).
|
||||
|
||||
1. Deleted `app/legacy/`, `tests/legacy/`, `eval/legacy/` and `eval/datasets/benchmark_cases.json`.
|
||||
2. Removed the legacy-only settings from `app/config.py` and `.env.example`: `HOST`, `PORT`, the OpenAI and Azure keys, `LLM_TEMPERATURE`, `GOOGLE_APPLICATION_CREDENTIALS`, `GCP_PROJECT_ID`, `GCP_REGION`, `ADK_*`, `DEVELOPER_KNOWLEDGE_MCP_*`, `SKILLS_DIR`, `EVAL_DATASET_PATH`. Google client libraries still read `GOOGLE_APPLICATION_CREDENTIALS` from the environment themselves.
|
||||
3. Removed the legacy exclusions from `ruff.toml`, `mypy.ini` and `.dockerignore`.
|
||||
4. Removed four dependencies no live module imports: `langchain`, `langchain-openai`, `sqlalchemy`, `asyncpg`.
|
||||
5. Rewrote the top of `README.md` around the Orchestrator, Specialists, Skills and A2A, and pointed `VALIDATION.md` at `eval.solution_eval`.
|
||||
|
||||
Verified: 206 passed (227 less the 21 legacy tests); `ruff check .` and `mypy .` clean; `grep -rn "app\.legacy\|eval\.legacy" app eval tests scripts` is empty; the image rebuilt from the trimmed `requirements.txt` imports every live module, including both checkpointers, and answers `/health` and the agent card.
|
||||
|
||||
Recovering the old code: the committed versions are in git history at their pre-move paths (`app/adk/`, `app/nodes/`, `app/workflows/`, `app/skills/`, `app/states/`, `app/agent.py`, `app/card.py`) up to commit `e94b249`. Uncommitted formatting changes to those files were not kept.
|
||||
|
||||
Left in place, because they are checked-in sample artefacts and not pipeline code: `scripts/validate_artifacts.py`, `tests/test_artifacts.py`, `tests/test_package.py`, the root `terraform/`, `docs/*.md`, `deliverables/{as-is,target,validation,guides}/`, `requirements.yaml`. `app/database.py` keeps two methods only the old pipeline called (`get_session`, `save_evaluation`).
|
||||
171
.agents/plans/iter-04-learning-and-skills/DETAIL.md
Normal file
171
.agents/plans/iter-04-learning-and-skills/DETAIL.md
Normal file
@@ -0,0 +1,171 @@
|
||||
# Plan Detail
|
||||
|
||||
Every step ends with the full suite passing. Steps that change agent behaviour (3, 6, 10, 11, 12, 13) also end with an evaluation run recorded in their step file, compared against the baseline in `iter-02-solution-architect-agent/steps/step-8.md`.
|
||||
|
||||
## Step 1: Structured validator findings
|
||||
|
||||
- **Report ref:** enhancement 3
|
||||
- **Capability:** Validation findings as data the engine can route, count and learn from.
|
||||
- **Rationale:** The validator reports findings as free markdown. The Orchestrator reads them once to decide what to reopen; nothing else can use them. They are the richest learning signal in an Execution.
|
||||
- **Where:** `app/workflows/deliverables.py` (add `findings.json` to the `validation_results` attachments), `agents/validator.md`, `skills/iac-validation/SKILL.md` (the finding format), `app/tools/execution.py` (validate the attachment's shape at submission).
|
||||
- **Acceptance criteria:** A `validation_results` submission without a parseable `findings.json` is refused with the reason. Each finding carries the Deliverable kind it traces to, a severity, the evidence and the rule. An empty list is valid and means a pass.
|
||||
|
||||
## Step 2: Carry the draft through `needs_input`
|
||||
|
||||
- **Report ref:** enhancement 9
|
||||
- **Capability:** The user receives the draft they approved.
|
||||
- **Rationale:** The Specialist protocol asks a Specialist to confirm its draft with the user before submitting. `needs_input` carries only questions and Specialists are stateless per delegation, so the approved draft is lost and written again on the next run.
|
||||
- **Where:** `needs_input` in `app/tools/execution.py` (optional `draft` and attachments), `NeedsInput` in `app/adk/runtime.py`, `_outcome_record` and `_specialist_input` in `app/nodes/execution_nodes.py` (store the draft, return it in context), `app/states/execution_state.py`, `agents/partials/specialist-protocol.md`.
|
||||
- **Acceptance criteria:** A Specialist restarted after the user approves its draft receives that draft in its context. A test shows the submitted content equals the approved draft when the fake runtime submits what it was given.
|
||||
|
||||
## Step 3: Reuse pillar advice across Revisions
|
||||
|
||||
- **Report ref:** enhancement 10
|
||||
- **Capability:** A Revision of the design recommendations re-consults only the pillars its feedback touches.
|
||||
- **Rationale:** Pillar advice is never stored. In case 01, two Revisions re-ran all six advisors each time: 18 advisor runs for one Deliverable.
|
||||
- **Where:** `app/tools/pillars.py` (the tool already accepts `pillars`), the Execution state for stored advice, `agents/design-advisor.md` (on a Revision, name the affected pillars).
|
||||
- **Acceptance criteria:** On a second attempt with stored advice, only the named pillars run and the tool returns stored advice for the rest. A changed brief for a pillar invalidates that pillar's stored advice.
|
||||
|
||||
## Step 4: Single source for Deliverable contracts
|
||||
|
||||
- **Report ref:** enhancement 11
|
||||
- **Capability:** Required headings and attachments declared once, and contracts for the Deliverables that have none.
|
||||
- **Rationale:** Required headings appear in each role file and again in `DeliverableSpec.sections`. `technical_decomposition`, `architecture_description` and the diagram's content accept any non-empty text.
|
||||
- **Where:** `app/workflows/deliverables.py`, `_specialist_input` in `app/nodes/execution_nodes.py` (pass the contract in context), `agents/*.md` (remove the "Required headings" lines), `agents/partials/specialist-protocol.md`.
|
||||
- **Acceptance criteria:** No role file lists required headings. Each Specialist's context carries its contract. The decomposition requires a component table naming the requirements each component serves.
|
||||
|
||||
## Step 5: Cap parallel Specialists
|
||||
|
||||
- **Report ref:** enhancement 14
|
||||
- **Capability:** A bound on concurrent Specialist runs per Execution.
|
||||
- **Rationale:** The spec's Risks section calls for a default cap of 4 against model rate limits. `orchestrator_turn` sends every delegated Deliverable at once, and the pillar fan-out adds six more.
|
||||
- **Where:** `app/nodes/execution_nodes.py`, `app/tools/pillars.py`, a `MAX_PARALLEL_SPECIALISTS` setting in `app/config.py`.
|
||||
- **Acceptance criteria:** A test with the fake runtime shows at most the configured number of Specialist runs in flight. The pillar fan-out counts toward the same cap.
|
||||
|
||||
## Step 6: Orchestrator step order
|
||||
|
||||
- **Report ref:** findings by agent, orchestrator row
|
||||
- **Capability:** A failed validation goes back for Revision before the user is asked to approve it.
|
||||
- **Rationale:** In `agents/orchestrator.md`, "A Phase is complete" (step 3) precedes "Validation found problems" (step 5), and the Orchestrator takes the first step that applies.
|
||||
- **Where:** `agents/orchestrator.md`.
|
||||
- **Acceptance criteria:** The validation-failure step sits above the Approval step. An evaluation run with a failing validation shows a reopen before any Approval request for the validation Phase.
|
||||
|
||||
## Step 7: Capture lesson candidates
|
||||
|
||||
- **Report ref:** enhancement 4
|
||||
- **Capability:** A durable record, per Execution, of what went wrong and what fixed it.
|
||||
- **Rationale:** The signals exist and are discarded. Revision feedback lives in the Ledger inside one checkpoint. Tool refusals (`Not submitted`, `Refused`, `terraform validate failed`) reach only the Python log through `REJECTION_PREFIXES` in `app/adk/adk_runtime.py`.
|
||||
- **Where:** `app/recorder.py` (a `record_lesson_candidates` method on `ExecutionRecorder`), `finalize` and `end_with_warnings` in `app/nodes/execution_nodes.py`, the runtime for refusals.
|
||||
- **Acceptance criteria:** A finished Execution writes one record holding each reopen with its reason and actor, each finding from step 1, each tool refusal with role and tool, each user change request and each exhausted budget. The record names the Execution, the Deliverable kind and the Skill versions loaded. It holds no secrets and no discovered cloud data.
|
||||
|
||||
## Step 8: Evaluation that can see improvement
|
||||
|
||||
- **Report ref:** enhancement 6
|
||||
- **Capability:** An evaluation whose score moves when a Skill gets better or worse.
|
||||
- **Rationale:** The 8 checks are structural and both scored runs reached 1.0. The loop's proof step has nothing to measure.
|
||||
- **Where:** `eval/scoring.py`, `eval/solution_eval.py`, `eval/datasets/solution_cases.json`, `tests/eval/`.
|
||||
- **Acceptance criteria:** New checks cover requirement-to-component traceability, coverage of each pillar Skill's checklist, and a graded rubric for recommendation quality. One interactive case checks that a Specialist asks before it submits. Revisions, seconds and tokens per case have recorded thresholds, and a run that exceeds one is reported as a regression. `case-02-high-scale-ingestion` has a scored run.
|
||||
|
||||
## Step 9: ADR: the lessons loop and overlay Skills
|
||||
|
||||
- **Report ref:** sequencing note
|
||||
- **Capability:** A recorded decision on how Skills change and how they are chosen per Execution.
|
||||
- **Rationale:** Steps 10 and 12 change which Skills an agent loads and who may edit them. That is an architectural decision, and ADR-0002 does not cover it.
|
||||
- **Where:** `docs/adr/0004-*.md`.
|
||||
- **Decisions the owner must make:** whether lessons need human review before they take effect (the plan assumes yes); where lessons Skills live and who owns them; whether an Execution may name overlay Skills, and who may supply them.
|
||||
- **Acceptance criteria:** The ADR is accepted and steps 10 and 12 are updated to match it.
|
||||
|
||||
## Step 10: Lessons Skill and lesson curator
|
||||
|
||||
- **Report ref:** enhancement 5
|
||||
- **Capability:** Each Execution can improve the next, under human review.
|
||||
- **Rationale:** `eval/optimizer.py` is the only learning code. It maps four keywords to iteration 1 Skill names that the engine never loads.
|
||||
- **Design:** The loop is capture (step 7), distil, review, prove, publish, retire.
|
||||
- Distil: an offline `lesson-curator` role groups candidates across Executions and proposes lessons. It runs outside any Execution.
|
||||
- Review: each proposal is an issue file under `.scratch/lessons/issues/` with `Status: needs-triage`.
|
||||
- Prove: the evaluation from step 8 runs with and without the change.
|
||||
- Publish: lessons land in a lessons Skill under `skills/`, one reference file per Deliverable kind; each lesson has its rule, reason, source Execution and date. The bundle's `role_skills` lists it.
|
||||
- Retire: at each vendor sync, remove lessons the upstream Skill now covers.
|
||||
- **Where:** `skills/<lessons-skill>/`, `agents/lesson-curator.md`, a curator entry point beside `eval/solution_eval.py`, `providers/gcp.yaml`, `scripts/sync-vendored-skills.sh`.
|
||||
- **Acceptance criteria:** Vendored Skills stay byte-identical. No lesson reaches a Skill without an approved issue file. Each Execution records the lessons Skill version it loaded. One real lesson has gone through the whole loop with its evaluation comparison recorded.
|
||||
|
||||
## Step 11: IaC patterns Skill
|
||||
|
||||
- **Report ref:** enhancement 7
|
||||
- **Capability:** The IaC author starts from known-good infrastructure code.
|
||||
- **Rationale:** The IaC author is the most expensive role: 812 thousand tokens, 23 requests, 4 runs and 3 Revisions in case 03. It writes from a blank page each time.
|
||||
- **Where:** `skills/<iac-patterns-skill>/` with one reference per product, `providers/gcp.yaml` (`role_skills.iac-author`).
|
||||
- **Acceptance criteria:** On the three cases, quality checks hold and IaC author Revisions or tokens fall against the step 8 baseline.
|
||||
|
||||
## Step 12: Overlay Skills and an organisation standards Skill
|
||||
|
||||
- **Report ref:** enhancement 8
|
||||
- **Capability:** New standards and clients need no code change.
|
||||
- **Rationale:** Skills are fixed at start-up: `AdkAgentRuntime` loads every Skill once, and `role_skills` is static per provider. Only 2 of the 9 Skills are our own, and both describe tools.
|
||||
- **Where:** `app/adk/adk_runtime.py`, `app/adk/roles.py`, `app/providers.py`, `ExecutionEngine.start` in `app/agent.py`, `app/a2a_server.py`, a standards Skill under `skills/`.
|
||||
- **Acceptance criteria:** An Execution can name overlay Skills at start; each passes the same Agent Skills validation as bundled Skills, and an unknown or invalid one refuses the start. An organisation standards Skill (naming, tagging, approved products) is loaded by the roles the bundle lists.
|
||||
|
||||
## Step 13: Trim Specialist context
|
||||
|
||||
- **Report ref:** enhancement 12
|
||||
- **Capability:** Each Specialist receives what its Deliverable needs.
|
||||
- **Rationale:** `inputs_of` gives a Specialist every Deliverable of every earlier Phase in full. The describer used 513 thousand tokens over 12 requests.
|
||||
- **Where:** `inputs_of` in `app/workflows/deliverables.py`, `_specialist_input` in `app/nodes/execution_nodes.py`.
|
||||
- **Acceptance criteria:** Direct Dependencies arrive in full; other earlier Deliverables arrive as summaries, with `read_deliverable`-style access to the full text on demand. Quality checks hold and describer tokens fall against the step 8 baseline.
|
||||
|
||||
## Step 14: Provider-owned contracts
|
||||
|
||||
- **Report ref:** enhancement 13
|
||||
- **Capability:** A second Cloud provider is configuration, as ADR-0002 intends.
|
||||
- **Rationale:** The six pillar headings, the eight solution-guide sections and the Terraform attachment names are hard-coded in `app/workflows/deliverables.py`. Other providers' frameworks name and count pillars differently. The bundle's pillar keys already differ from the headings (`performance-optimization` against `Performance efficiency`).
|
||||
- **Where:** `providers/gcp.yaml`, `app/providers.py`, `app/workflows/deliverables.py`, `app/presentation.py`, `agents/iac-author.md`, `agents/validator.md`, `agents/design-advisor.md`.
|
||||
- **Timing:** Build when a second Cloud provider is planned. ADR-0002 says no provider interface exists in code until then.
|
||||
- **Acceptance criteria:** Pillar headings come from `pillar_skills`, guide sections from the bundle's `output_template`, and the IaC tool with its file contract from the bundle. `grep -rni "terraform" app/workflows app/nodes app/states` is empty, and no pillar or guide-section name appears as a literal in `app/workflows/deliverables.py`.
|
||||
|
||||
## Step 15: Group Executions by Customer case
|
||||
|
||||
- **Report ref:** none; requested by the owner on 2026-10-06
|
||||
- **Capability:** Everything under `deliverables/` is grouped by Customer case, so a case ties each request to the artefacts generated for it.
|
||||
- **Rationale:** Outputs were keyed only by Execution id. Nothing on disk said which customer workload an Execution belonged to or what it had been asked.
|
||||
- **Where:** `app/states/execution_state.py` (the case id rule and the paths), `ExecutionEngine.start` in `app/agent.py`, `_write_outputs` in `app/nodes/execution_nodes.py`, `app/main.py`, `app/a2a_server.py`, `eval/solution_eval.py`, `CONTEXT.md`.
|
||||
- **Acceptance criteria:** Every Execution's files are under `deliverables/cases/<customer_case>/executions/<execution_id>/`. Each has a manifest naming the case, the request and every file. Each case has an index of its Executions and their requests. A case id that is not a safe slug is refused before anything runs. A Customer case never feeds one Execution into another.
|
||||
|
||||
## Step 16: Cache Terraform providers between checks
|
||||
|
||||
- **Report ref:** none; requested by the owner on 2026-10-07 to shorten a run
|
||||
- **Capability:** A provider is downloaded once and reused by every later `terraform validate` and `plan`.
|
||||
- **Rationale:** Each check runs `terraform init` in a new scratch directory, so every call downloaded its providers again. The setting `TF_PLUGIN_CACHE_DIR` existed and was unset by default.
|
||||
- **Where:** `TerraformRunner` in `app/tools/local.py`, `app/config.py`, `.env.example`.
|
||||
- **Acceptance criteria:** The cache is on by default and can be disabled. A second check of the same configuration does not download the provider. Concurrent checks cannot corrupt the cache.
|
||||
|
||||
## Step 17: A working copy for files and for the graph
|
||||
|
||||
- **Report ref:** none; requested by the owner on 2026-10-07 to shorten a run
|
||||
- **Capability:** A Specialist writes a file or a graph once and afterwards changes only what needs changing. A Revision starts from the last attempt.
|
||||
- **Rationale:** In the 2026-10-07 run the IaC author made 57 model requests and used 2.35 million tokens: every `terraform_fmt` and `terraform_validate` call carried every file, `terraform_fmt` returned them all again, and each fix rewrote whole files. The target architect returned the whole graph and the same content again as tables in one reply, and timed out at 180 seconds in both attempts.
|
||||
- **Where:** `app/tools/workspace.py` (new), `specialist_tools` in `app/tools/execution.py`, `app/tools/local.py`, `app/tools/toolkit.py`, `DeliverableSpec.working_copy` in `app/workflows/deliverables.py`, `render_tables` in `app/workflows/target_architecture.py`, `agents/target-architect.md`, `agents/iac-author.md`, `agents/validator.md`, `skills/iac-validation/SKILL.md`.
|
||||
- **Acceptance criteria:** The Terraform tools take no files when the Deliverable has a working copy, and formatting returns file names only. The working copy is attached on submission. The validator's tools hold the submitted code without it being sent. The target architect can build the graph over several calls, and the tables and the diagram are written by code from the graph. On the next evaluation the IaC author's and the target architect's requests and tokens fall against the 2026-10-07 run.
|
||||
|
||||
## Step 18: Provider schema lookup and one pinned provider version
|
||||
|
||||
- **Report ref:** none; requested by the owner on 2026-10-07
|
||||
- **Capability:** An agent can ask what a resource type accepts, and get the provider's own answer.
|
||||
- **Rationale:** All 13 Terraform refusals in the 2026-10-07 run were one mistake: `startup_cpu_boost` and `cpu_idle` in the wrong block, and on a Cloud Run job, which has neither. The agent moved the argument around by trial. The run also left five versions of the Google provider in the plugin cache, because nothing pinned one.
|
||||
- **Where:** `TerraformRunner.schema` in `app/tools/local.py`, `terraform.required_providers` in `providers/gcp.yaml`, `app/providers.py`, the role files of the target architect, the IaC author and the validator.
|
||||
- **Acceptance criteria:** `terraform_schema` lists a resource type's arguments and blocks, gives one block in full, and says where a named setting sits or that the resource type has none. The schema is read once per process. The bundle pins one exact provider version, and the lookup refuses to guess without one.
|
||||
|
||||
## Step 19: A Check the code cannot meet goes back to the Target architecture
|
||||
|
||||
- **Report ref:** none; requested by the owner on 2026-10-07
|
||||
- **Capability:** A Check that names a setting its resource lacks is fixed where it was written, before any validation is spent on it.
|
||||
- **Rationale:** Check K-30 of the 2026-10-07 run asked for `startup_cpu_boost` on a Cloud Run job. The IaC author could not implement it and had no way to say so; the validator failed it; the code was reopened until the Revision limit ended the run with warnings.
|
||||
- **Where:** `check_implementation` and `unimplementable_checks` in `app/workflows/chain.py`, the playbook in `app/nodes/router.py`, `_orchestrator_context` in `app/nodes/execution_nodes.py`, `agents/orchestrator.md`, `agents/iac-author.md`, `agents/validator.md`, `skills/requirements-chain/SKILL.md`.
|
||||
- **Acceptance criteria:** `implementation.json` may record a Check as unimplementable with a reason, and that accounts for the Check. The router then reopens the Target architecture with the reason, before validation is delegated. The validator gives a Check on a setting the schema lacks the verdict not verifiable, not fail.
|
||||
|
||||
## Step 20: A model timeout per role
|
||||
|
||||
- **Report ref:** none; requested by the owner on 2026-10-07
|
||||
- **Capability:** A role whose replies are long is given longer for one model request than the rest.
|
||||
- **Rationale:** One `MODEL_TIMEOUT_SECONDS` (180) applied to every role. Raising it for all of them makes every stuck request slower to recover.
|
||||
- **Where:** `models.timeout_seconds` in `providers/gcp.yaml`, `ModelConfig` in `app/providers.py`, `RoleSpec.model_timeout_seconds`, `AdkAgentRuntime._content_config`.
|
||||
- **Acceptance criteria:** A role named in the bundle gets its own timeout; every other role gets the default.
|
||||
59
.agents/plans/iter-04-learning-and-skills/MAP.md
Normal file
59
.agents/plans/iter-04-learning-and-skills/MAP.md
Normal file
@@ -0,0 +1,59 @@
|
||||
# Plan Map
|
||||
|
||||
**Iteration:** 4, learning and Skills
|
||||
**Intent:** Make the agent a learning, adaptable solution through Skills. Fix the cheap defects the 2026-10-06 review found, then close the loop so each Execution can improve the next through a reviewed Skill change, then let new standards, clients and Cloud providers arrive as Skills and configuration.
|
||||
**Status:** steps 1 to 8, 11, 13 and 15 to 20 built; no evaluation run has completed on any of them (see `steps/step-8.md`), so every "tokens fall" or "Revisions fall" criterion is unmeasured; step 9 drafted and awaiting the owner; steps 10, 12 and 14 planned. Steps 1 to 6 are in commit `7ee49ab`; the rest are uncommitted.
|
||||
**Changed by iteration 6:** `docs/adr/0005-the-target-architecture-is-an-explicit-graph.md` (accepted 2026-10-07) replaces the free-form `findings.json` of step 1 with a verdict per Check, remove the diagrammer, and add a Phase. Its plan is `../iter-06-target-architecture-graph/`, which lists the effect on each step here and should be built before steps 10 to 14.
|
||||
**This directory covers:** steps 1 to 20
|
||||
|
||||
## Sources of truth
|
||||
|
||||
- Review report (2026-10-06): https://claude.ai/code/artifact/16b37169-1554-4eb7-bfcb-254315fa0518. Each step's `Report ref` names its enhancement number there. The report uses pre-iteration-3 paths.
|
||||
- `iter-02-solution-architect-agent/steps/step-8.md`: the evaluation figures quoted as evidence.
|
||||
- `docs/adr/0002-skills-are-the-portable-unit-of-behaviour.md`: every step must keep behaviour in Skills and vendored Skills unmodified.
|
||||
- `CONTEXT.md`: "every Execution starts clean". Learning arrives as a reviewed Skill change, never as memory carried between Executions.
|
||||
|
||||
## Status
|
||||
|
||||
| Step | What | Group | Size | Status |
|
||||
|---|---|---|---|---|
|
||||
| 1 | Structured validator findings | A | S | replaced by iteration 6 step 9 (verdicts per Check) |
|
||||
| 2 | Carry the draft through `needs_input` | A | S | complete |
|
||||
| 3 | Reuse pillar advice across Revisions | A | S | built; evaluation run outstanding |
|
||||
| 4 | Single source for Deliverable contracts | A | S | complete |
|
||||
| 5 | Cap parallel Specialists | A | S | complete |
|
||||
| 6 | Orchestrator step order | A | S | built; seen working in one stopped run, no completed evaluation |
|
||||
| 7 | Capture lesson candidates | B | M | complete |
|
||||
| 8 | Evaluation that can see improvement | B | M | built; thresholds and a judged run outstanding |
|
||||
| 9 | ADR: the lessons loop and overlay Skills | B | S | drafted as `docs/adr/0004-lessons-and-overlays-arrive-as-skills.md`, status proposed; awaits the owner |
|
||||
| 10 | Lessons Skill and lesson curator | B | L | planned |
|
||||
| 11 | IaC patterns Skill | B | M | built; every pattern validates; effect on Revisions and tokens unmeasured |
|
||||
| 12 | Overlay Skills and an organisation standards Skill | C | M | planned |
|
||||
| 13 | Trim Specialist context | C | M | built; effect on tokens unmeasured |
|
||||
| 14 | Provider-owned contracts | C | M | planned |
|
||||
| 15 | Group Executions by Customer case | added | S | complete |
|
||||
| 16 | Cache Terraform providers between checks | added | S | complete |
|
||||
| 17 | A working copy for files and for the graph | added | M | built; effect on time and tokens unmeasured |
|
||||
| 18 | Provider schema lookup and one pinned provider version | added | S | built; checked against the real provider |
|
||||
| 19 | A Check the code cannot meet goes back to the Target architecture | added | S | built |
|
||||
| 20 | A model timeout per role | added | S | built |
|
||||
|
||||
Size: S under a day, M a few days, L a week or more. Group A is cheap fixes that also create signal. Group B is the learning loop. Group C is adaptability.
|
||||
|
||||
## Dependency graph
|
||||
|
||||
- Steps 1 to 6: no dependencies; any order
|
||||
- Step 7: depends on step 1
|
||||
- Step 8: no dependencies
|
||||
- Step 9: no dependencies
|
||||
- Step 10: depends on step 7, step 8, step 9
|
||||
- Step 11: depends on step 8
|
||||
- Step 12: depends on step 9
|
||||
- Step 13: depends on step 8
|
||||
- Step 14: depends on step 4
|
||||
- Step 15: no dependencies (added on 2026-10-06 at the owner's request)
|
||||
- Step 16: no dependencies (added on 2026-10-07 at the owner's request)
|
||||
- Steps 17 to 20: no dependencies (added on 2026-10-07 at the owner's request, from the causes of the 60 minute run recorded in `../iter-06-target-architecture-graph/steps/`)
|
||||
- Step 11 uses step 18's pinned provider version; step 19 uses step 18's lookup to find the Checks it reports
|
||||
|
||||
Step 8 comes before steps 10, 11 and 13 so each of them can be shown to help: same quality, fewer Revisions, seconds or tokens.
|
||||
12
.agents/plans/iter-04-learning-and-skills/steps/step-1.md
Normal file
12
.agents/plans/iter-04-learning-and-skills/steps/step-1.md
Normal file
@@ -0,0 +1,12 @@
|
||||
# Step 1 — Implementation Detail
|
||||
|
||||
1. `validation_results` now requires a `findings.json` attachment (`FINDINGS_ATTACHMENT` in `app/workflows/deliverables.py`).
|
||||
2. `check_findings` validates it at submission: a JSON list of objects with `deliverable` (a Deliverable kind), `severity` (`critical`, `high`, `medium`, `low`), `evidence` and `rule`. `[]` is valid and means a pass. Each problem is refused by field, for example `findings.json[1].severity: must be one of ...`.
|
||||
3. `agents/validator.md` tells the validator to attach it; the format and an example live in `skills/iac-validation/SKILL.md` under "Reporting findings".
|
||||
4. The file is written with the other attachments to `deliverables/executions/<id>/findings.json`.
|
||||
|
||||
The check was added to `check_submission`, not to `app/tools/execution.py` as planned, so every contract rule stays in one function.
|
||||
|
||||
Tests: `tests/execution/test_deliverables.py` (missing attachment, empty list, well-formed finding, malformed JSON, per-field problems).
|
||||
|
||||
Not verified: no real-model run has confirmed the validator produces a well-formed file on its first submission. A malformed one costs a retry inside the validator's run, not a Revision.
|
||||
13
.agents/plans/iter-04-learning-and-skills/steps/step-11.md
Normal file
13
.agents/plans/iter-04-learning-and-skills/steps/step-11.md
Normal file
@@ -0,0 +1,13 @@
|
||||
# Step 11 — Implementation Detail
|
||||
|
||||
Built on 2026-10-07 as `skills/google-cloud-iac-patterns/`. The name carries the Cloud provider because the content does; the provider bundle assigns it to the IaC author (`role_skills.iac-author`), so another provider brings its own patterns Skill with no code change.
|
||||
|
||||
1. `SKILL.md` says how to use the patterns and lists one reference per product. `assets/versions.tf` pins `hashicorp/google` 8.6.0, the version `providers/gcp.yaml` pins (step 18).
|
||||
2. Thirteen references, each a short list of what goes wrong and one self-contained pattern: enabling APIs, IAM, Cloud Run service, Cloud Run job, Pub/Sub, Cloud Storage, Secret Manager, Cloud KMS, Cloud SQL, VPC networking, Cloud Scheduler, Artifact Registry, Monitoring and Logging.
|
||||
3. Seeded from the 2026-10-07 run's lesson candidates. All 13 Terraform refusals were `startup_cpu_boost` or `cpu_idle` in the wrong block or on a Cloud Run job. The service reference says which block each setting sits in; the job reference lists what a job does not have.
|
||||
|
||||
Differs from the plan: the plan's acceptance is a fall in IaC author Revisions or tokens on the three cases. **No evaluation has run, so that is unmeasured.** What is verified is that the patterns are correct.
|
||||
|
||||
Tests: `tests/test_iac_patterns.py` runs `terraform validate` on every reference's pattern with the Skill's own versions file (13 pass against the real provider from the plugin cache; skipped when the provider cannot be installed), checks every reference is listed in `SKILL.md`, and checks the Skill and the bundle pin the same version.
|
||||
|
||||
Not done: load balancing, Firestore, BigQuery, Eventarc and GKE have no reference. A product with none is written from `terraform_schema` and the documentation.
|
||||
14
.agents/plans/iter-04-learning-and-skills/steps/step-13.md
Normal file
14
.agents/plans/iter-04-learning-and-skills/steps/step-13.md
Normal file
@@ -0,0 +1,14 @@
|
||||
# Step 13 — Implementation Detail
|
||||
|
||||
Built on 2026-10-07.
|
||||
|
||||
1. `DeliverableSpec.reads_in_full` names the earlier Deliverables a Specialist reads whole. Left unset it is the Deliverables it depends on.
|
||||
2. `dependencies_for(kind, deliverables)` gives every other input as its data file alone: `requirements.json`, `components.json` and so on. Those ids are all the Requirements chain checks need, so submission checks are unchanged.
|
||||
3. Two overrides. The IaC author reads nothing whole: the code is written from `target-architecture.json`. The packager reads everything whole, since the guide is assembled from every Deliverable's prose.
|
||||
4. A Deliverable given as data can be read whole with `read_deliverable(kind)`, offered only when something was trimmed.
|
||||
|
||||
Differs from the plan: the plan said "summaries". The data file is used instead. It already exists, is exact, and costs no model call to produce.
|
||||
|
||||
**Unmeasured:** the plan's acceptance is that describer tokens fall against the step 8 baseline. No evaluation has run.
|
||||
|
||||
Tests: `tests/execution/test_working_copy.py`, "each Specialist reads what it works from".
|
||||
19
.agents/plans/iter-04-learning-and-skills/steps/step-15.md
Normal file
19
.agents/plans/iter-04-learning-and-skills/steps/step-15.md
Normal file
@@ -0,0 +1,19 @@
|
||||
# Step 15 — Implementation Detail
|
||||
|
||||
1. **Customer case** is a glossary term (`CONTEXT.md`): a caller-supplied slug grouping the Executions for one customer workload. An Execution started without one belongs to `unassigned`, so every Execution sits under a case.
|
||||
2. **Layout.** `deliverables/cases/<customer_case>/executions/<execution_id>/` holds an Execution's files. `execution_dir`, `case_dir` and `lessons_file` in `app/states/execution_state.py` are the only places these paths are built.
|
||||
3. **`execution.json`** in each Execution folder names the case, the Execution, the Session, the Workflow request, and for each Deliverable its document and attachments.
|
||||
4. **`intent/`** in each case folder records the customer's Intent and its history (`app/customer_case.py`). Each Workflow request is written as given to `intent/001.md`, `002.md` and so on when its Execution starts. `intent/history.json` lists every statement in order with the Execution it started, that Execution's status (`in_progress`, `completed`, `completed_with_warnings`) and the path to its files. This replaced the `case.json` index first built for this step; `execution.json` carries `intent_version`.
|
||||
5. **Lesson candidates** are grouped the same way: `lessons/candidates/<customer_case>/<execution_id>.json`, and the record carries `customer_case`.
|
||||
6. **Callers.** `ExecutionEngine.start(customer_case=...)`; `/generate` takes `customer_case` in its body and answers 400 for an unsafe one; A2A reads `customer_case` from the message metadata. The evaluation uses each benchmark case's id.
|
||||
7. **The case id** must be 1 to 64 lowercase letters, digits or hyphens, starting and ending with a letter or digit. It becomes a directory name, so anything else is refused before the Execution starts.
|
||||
8. **Existing content moved.** `deliverables/as-is`, `target`, `validation`, `guides` and the 68 old `executions` folders are now under `deliverables/cases/legacy-baseline/`, with an `intent/` folder built from the request recorded in each old run's `requirements.md`, ordered by file time. `scripts/validate_artifacts.py` and `tests/test_artifacts.py` look there.
|
||||
|
||||
Limits:
|
||||
|
||||
- An Execution that ends with warnings writes no Deliverable files (an existing rule). Its request is still in the Intent history, with its status and no path, and its lesson candidates are grouped under its case.
|
||||
- The 68 old runs were asked 12 different things but share one case, `legacy-baseline`. They can be split into a case per request from `intent/history.json` if that matters.
|
||||
- `/generate`'s response keys are unchanged, so it does not return the case; `execution.json` does.
|
||||
- The database rows carry the case only inside the status details, not as a column.
|
||||
|
||||
Tests: `tests/execution/test_engine.py` (grouping, manifest, index, `unassigned`, refused ids), `tests/a2a/test_server.py` (`/generate`), `tests/execution/test_lessons.py`.
|
||||
20
.agents/plans/iter-04-learning-and-skills/steps/step-16.md
Normal file
20
.agents/plans/iter-04-learning-and-skills/steps/step-16.md
Normal file
@@ -0,0 +1,20 @@
|
||||
# Step 16 — Implementation Detail
|
||||
|
||||
1. `TF_PLUGIN_CACHE_DIR` defaults to `.cache/terraform-plugins` under the repository root (already gitignored and kept out of the image build context). Set it empty to disable. `Settings.terraform_plugin_cache()` resolves it to an absolute path, since checks run in scratch directories.
|
||||
2. `TerraformRunner` creates the directory on first use and passes it to Terraform.
|
||||
3. It also sets `TF_PLUGIN_CACHE_MAY_BREAK_DEPENDENCY_LOCK_FILE=true`. A scratch directory has no dependency lock file, and without this Terraform downloads a cached provider again to verify it, which defeats the cache.
|
||||
4. `terraform init` calls are serialised by a lock when the cache is in use, because Terraform's plugin cache is not safe for concurrent installs.
|
||||
|
||||
Measured on 2026-10-07 with a one-resource configuration on the Google provider (`~> 6.0`), on this machine:
|
||||
|
||||
| | Seconds per `terraform validate` |
|
||||
|---|---|
|
||||
| No cache | 7.3 to 7.8 |
|
||||
| Cache, first use (downloads once) | 7.3 |
|
||||
| Cache, later uses | 1.6 to 2.0 |
|
||||
|
||||
So each check after the first saves about 5.5 seconds. The stopped run of 2026-10-06 made 7 validate calls in 16 minutes and more through its Revisions; at 12 to 15 calls a case, with the scoring's own check, that is roughly 1 to 1.5 minutes a case. The saving is real but small against a 35 minute run; it grows on a slower network.
|
||||
|
||||
Costs: the cache holds each provider version once (117 MB for one Google provider version; the existing folder holds 600 MB across versions). In the container it is created under `/app/.cache` at run time and is lost with the container; pre-loading it into the image, or mounting a volume, would carry the saving across restarts and is not done.
|
||||
|
||||
Tests: `tests/tools/test_local.py`, "the provider cache", using a stand-in terraform binary.
|
||||
21
.agents/plans/iter-04-learning-and-skills/steps/step-17.md
Normal file
21
.agents/plans/iter-04-learning-and-skills/steps/step-17.md
Normal file
@@ -0,0 +1,21 @@
|
||||
# Step 17 — Implementation Detail
|
||||
|
||||
Built on 2026-10-07. `app/tools/workspace.py` keeps a working copy in the Deliverable's working memory, which the Execution already checkpoints and returns on every attempt.
|
||||
|
||||
Files (`working["files"]`), for the Deliverable whose `working_copy` is its own kind (deployment guidance):
|
||||
|
||||
1. `write_file`, `edit_file` (replaces the one place `old` matches, and refuses when it matches none or several), `read_file` (one file, or the list) and `delete_file`.
|
||||
2. `terraform_fmt`, `terraform_validate` and `terraform_plan` run on the Terraform files in the working copy and take no `files` argument. `terraform_fmt` formats in place and returns the names it changed. Files passed anyway are written to the working copy first, so a model that ignores the instruction still works.
|
||||
3. `submit_deliverable` attaches the working copy; a file passed as an attachment replaces its copy. The submitted files become the working copy, so a Revision starts from them, and the task context lists them under `working_copy`.
|
||||
|
||||
The validator's `working_copy` is deployment guidance: its tools are given a fresh copy of the submitted files on every attempt, it has no write tools, and nothing from the copy is attached to its Deliverable.
|
||||
|
||||
Graph (`working["graph"]`), for the Target architecture:
|
||||
|
||||
4. `graph_put` adds items or replaces those with the same id, `graph_remove` removes by id, `graph_read` returns the graph. The submitted graph becomes the working graph.
|
||||
5. `submit_deliverable` attaches the working graph when no `target-architecture.json` is passed.
|
||||
6. `render_tables` writes the Elements, Relationships, Checks and not-applicable tables from the graph, and the engine appends them to the content on submission. The contract's sections are now `Design rationale` alone. This closes the duplicate output iteration 6 left: the architect no longer writes the graph twice.
|
||||
|
||||
**Unmeasured:** no evaluation has run, so the fall in requests, tokens and time is expected, not shown. The mechanism is what is tested.
|
||||
|
||||
Tests: `tests/execution/test_working_copy.py` (21), including an Execution in which the validator validates the submitted code with no files passed.
|
||||
17
.agents/plans/iter-04-learning-and-skills/steps/step-18.md
Normal file
17
.agents/plans/iter-04-learning-and-skills/steps/step-18.md
Normal file
@@ -0,0 +1,17 @@
|
||||
# Step 18 — Implementation Detail
|
||||
|
||||
Built on 2026-10-07.
|
||||
|
||||
1. `providers/gcp.yaml` pins `terraform.required_providers.google` to `hashicorp/google` 8.6.0. `load_provider` requires a `source` and an exact `version`.
|
||||
2. `TerraformRunner.schema(resource_type, block, find)` writes a versions file for the pinned providers in a scratch directory, runs `terraform init -backend=false` and `terraform providers schema -json` once per process, and keeps the resource schemas in memory. Measured here: 0.6 seconds and a 9.7 MB reply for the Google provider, from the plugin cache.
|
||||
3. With `resource_type` alone it lists the arguments code may set (read-only ones are left out) and outlines every block. With `block` it gives one block's arguments with descriptions. With `find` it says where a setting sits, or that the resource type has none. An unknown resource type gets close matches.
|
||||
4. The tool is `terraform_schema`, tier general, given to the target architect, the IaC author and the validator.
|
||||
|
||||
Checked against the real provider on 2026-10-07:
|
||||
|
||||
- `find="startup_cpu_boost"` on `google_cloud_run_v2_job`: "has no argument or block named like 'startup_cpu_boost'. It cannot be set on this resource type."
|
||||
- the same on `google_cloud_run_v2_service`: `template.containers.resources.startup_cpu_boost (bool, optional)`.
|
||||
|
||||
Not done: generated code is not forced onto the pinned version. An agent that writes its own `required_providers` with another version is validated against that version. The patterns Skill gives it the pinned `versions.tf` to use.
|
||||
|
||||
Tests: `tests/tools/test_local.py`, "schema lookup", on a stand-in schema; `tests/test_providers.py` for the pin.
|
||||
12
.agents/plans/iter-04-learning-and-skills/steps/step-19.md
Normal file
12
.agents/plans/iter-04-learning-and-skills/steps/step-19.md
Normal file
@@ -0,0 +1,12 @@
|
||||
# Step 19 — Implementation Detail
|
||||
|
||||
Built on 2026-10-07.
|
||||
|
||||
1. An `implementation.json` entry may be `{"check": "K-7", "unimplementable": "<what the resource type lacks>"}` in place of `file` and `address`. It accounts for the Check; an empty reason does not.
|
||||
2. `unimplementable_checks` reads those entries. The router reads them as soon as deployment guidance is submitted, and a new playbook group, "the code cannot meet a Check", sits before "validation decided" and "a Phase is complete". Its action reopens the Target architecture with each Check's id and reason. That returns the code to draft, so the group stops applying.
|
||||
3. A model Orchestrator is given the same list as `unimplementable_checks` in its context, and `agents/orchestrator.md` has the step.
|
||||
4. The validator is told to confirm with `terraform_schema` before failing a Check for a missing setting, and to give not verifiable when the resource type has no such setting. Not verifiable already routes to the Target architecture.
|
||||
|
||||
Past the Revision limit the reopen is refused as any other is: the user decides, or a pre-approved Execution ends with warnings.
|
||||
|
||||
Tests: `tests/execution/test_requirements_chain.py` (two) and `tests/execution/test_router.py`, "a Check the code cannot meet goes back to the graph unvalidated".
|
||||
10
.agents/plans/iter-04-learning-and-skills/steps/step-2.md
Normal file
10
.agents/plans/iter-04-learning-and-skills/steps/step-2.md
Normal file
@@ -0,0 +1,10 @@
|
||||
# Step 2 — Implementation Detail
|
||||
|
||||
1. `needs_input` accepts an optional `draft` and `attachments`; `NeedsInput` carries them (`app/adk/runtime.py`).
|
||||
2. The Execution state holds `drafts` by Deliverable kind. `orchestrator_turn` stores a draft when it applies a `needs_input` outcome and drops it when that Deliverable is submitted.
|
||||
3. A Specialist's context carries `draft` (`{content, attachments}` or `null`).
|
||||
4. `agents/partials/specialist-protocol.md` tells Specialists to pass the complete draft with their confirmation question, to submit it unchanged once the latest answer approves it, and to apply requested changes to it.
|
||||
|
||||
Test: `test_a_draft_sent_with_questions_comes_back_with_the_answer` in `tests/execution/test_engine.py` shows the second run receiving the draft and the submitted content equalling it.
|
||||
|
||||
The draft is not shown to the user by the engine; the Specialist's question still carries its summary. Whether the full draft should appear in the prompt is an open product question.
|
||||
@@ -0,0 +1,7 @@
|
||||
# Step 20 — Implementation Detail
|
||||
|
||||
Built on 2026-10-07. `models.timeout_seconds` in the provider bundle maps a role to the seconds one model request may take; `RoleSpec.model_timeout_seconds` carries it and `AdkAgentRuntime` uses it in place of `MODEL_TIMEOUT_SECONDS`.
|
||||
|
||||
`providers/gcp.yaml` sets the target architect to 420 and the IaC author and the packager to 300. These are starting values, not measurements. With step 17 the architect's replies are short, so its 420 should rarely be reached.
|
||||
|
||||
Tests: `tests/agents/test_adk_runtime.py`, `tests/agents/test_roles.py`, `tests/test_providers.py`.
|
||||
12
.agents/plans/iter-04-learning-and-skills/steps/step-3.md
Normal file
12
.agents/plans/iter-04-learning-and-skills/steps/step-3.md
Normal file
@@ -0,0 +1,12 @@
|
||||
# Step 3 — Implementation Detail
|
||||
|
||||
1. **Working memory.** Each Deliverable has a JSON-compatible working memory kept in Execution state (`working`, merged by key so parallel Specialists each write their own). `ToolFactory` now takes it as a third argument, so tools can remember across attempts.
|
||||
2. **Pillar advice is remembered** under `pillar_advice` in the design recommendations' working memory (`app/tools/pillars.py`).
|
||||
3. **Semantics of `consult_pillar_advisors`:** omit `pillars` to consult every pillar afresh; name `pillars` to re-consult only those, with the remembered advice returned for the rest under a heading marked "(from your earlier consultation)". Failed advice is never remembered.
|
||||
4. `agents/design-advisor.md` tells the design advisor to name only the pillars its feedback touches when revising.
|
||||
|
||||
Changed from the plan: the criterion "a changed brief for a pillar invalidates that pillar's stored advice" was not built. The brief is one text for all pillars and a model rewords it on every attempt, so hashing it would discard everything each time. Omitting `pillars` is the way to refresh all advice.
|
||||
|
||||
Tests: `tests/execution/test_pillars.py` (subset re-consult, full refresh, failed advice not stored, and one through the engine showing advice surviving a Revision).
|
||||
|
||||
Not verified: the evaluation run this step calls for. The saving depends on the design advisor following the new instruction; in case 01 it would cut up to 12 of 18 advisor runs.
|
||||
15
.agents/plans/iter-04-learning-and-skills/steps/step-4.md
Normal file
15
.agents/plans/iter-04-learning-and-skills/steps/step-4.md
Normal file
@@ -0,0 +1,15 @@
|
||||
# Step 4 — Implementation Detail
|
||||
|
||||
1. `DeliverableSpec.contract()` returns the sections, attachments and table columns as data; every Specialist's context now carries it as `contract`.
|
||||
2. Role files no longer list required headings. What remains in them is guidance the contract cannot express (what goes under a heading, verdicts, optional headings).
|
||||
3. New contracts:
|
||||
- `technical_decomposition`: a `Components` section and one table whose header names `component` and `requirement`.
|
||||
- `architecture_description`: `Components` and `Flow` sections. Headings match by suffix, so "Data flow" and "Architecture components" satisfy them.
|
||||
- Every required attachment must have content, which gives the diagram's `architecture.mmd` a minimum bar.
|
||||
4. Tests share one contract-complete fixture, `sample_submission` in `app/adk/fake_runtime.py`.
|
||||
|
||||
Two existing tests used an empty `terraform/variables.tf` as a fixture; they now use a non-empty one.
|
||||
|
||||
Tests: `tests/execution/test_deliverables.py`, and `test_specialist_context_carries_its_contract` in `tests/execution/test_engine.py`.
|
||||
|
||||
Not verified with real models: the two new section contracts change what the decomposer and describer must write.
|
||||
11
.agents/plans/iter-04-learning-and-skills/steps/step-5.md
Normal file
11
.agents/plans/iter-04-learning-and-skills/steps/step-5.md
Normal file
@@ -0,0 +1,11 @@
|
||||
# Step 5 — Implementation Detail
|
||||
|
||||
1. `RunLimiter` in `app/adk/runtime.py` caps agent runs in flight. `slot()` holds one; `lend()` gives the caller's slot up while its own fan-out runs.
|
||||
2. `specialist_task` takes a slot for each Specialist run. The pillar tool lends the design advisor's slot and takes one per advisor, so the fan-out shares the cap and a cap of 1 cannot deadlock.
|
||||
3. Setting `MAX_PARALLEL_SPECIALISTS` (default 4, as the spec's Risks section asked). `open_assembly` builds one limiter and gives it to both the engine and the tool factory.
|
||||
|
||||
Changed from the plan: the cap is per engine process, not per Execution. Model rate limits apply to the project, so one cap across concurrent Executions is the stricter and more useful bound.
|
||||
|
||||
An `ExecutionEngine` built without a limiter is uncapped, which keeps direct construction in tests unchanged.
|
||||
|
||||
Tests: cap of 1 gives a peak of 1 and no cap gives a peak of 2 (`tests/execution/test_engine.py`); the fan-out under a held slot with a cap of 1 completes with a peak of 1 (`tests/execution/test_pillars.py`).
|
||||
@@ -0,0 +1,6 @@
|
||||
# Step 6 — Implementation Detail
|
||||
|
||||
1. `agents/orchestrator.md`: "Validation found problems" is now step 3, above "A Phase is complete" (step 4) and "Work is ready" (step 5).
|
||||
2. The step now says when it applies (validation results submitted and not yet approved), to read them first, and to send failed work back before asking the user to approve it.
|
||||
|
||||
Not verified: the acceptance criterion needs a real-model evaluation run with a failing validation, showing a reopen before any Approval request for the validation Phase. No such run was made. The deterministic suite cannot test this, because the order is the model's choice.
|
||||
18
.agents/plans/iter-04-learning-and-skills/steps/step-7.md
Normal file
18
.agents/plans/iter-04-learning-and-skills/steps/step-7.md
Normal file
@@ -0,0 +1,18 @@
|
||||
# Step 7 — Implementation Detail
|
||||
|
||||
1. `app/states/lessons.py`: `collect_lesson_candidates` builds one record when an Execution ends, from what the Execution already holds. Candidate types:
|
||||
- `revision`: each reopen, with its reason and who asked.
|
||||
- `revision_limit`: a reopen refused at the cap.
|
||||
- `change_request`: the user's feedback on a Phase, with the Deliverables in it.
|
||||
- `finding`: each entry of every submitted `findings.json`, with the attempt it came from.
|
||||
- `refusal`: each tool reply that did nothing (`REJECTION_PREFIXES`, now in `app/adk/runtime.py`), with role, tool and Deliverable.
|
||||
- `unfinished`: a Specialist that stopped or spent its budget.
|
||||
2. Refusals are captured in the nodes, not the runtime: `_noting_refusals` wraps each tool, so any runtime, the fake included, produces them. Specialist refusals travel in the outcome record; the Orchestrator's are kept in state under `refusals`.
|
||||
3. The record names the Execution, its status, each role's Skills and a version per Skill. `skill_version` in `app/skills/agent_skills.py` is a 12-character content hash of the Skill's files.
|
||||
4. It is written twice: through `ExecutionRecorder.record_lesson_candidates` (the database recorder stores it as an artifact of type `lesson_candidates`), and to `lessons/candidates/<execution_id>.json` under the output root. That directory is gitignored.
|
||||
|
||||
Changed from the plan: the file is not inside `deliverables/executions/<id>/`. An Execution that ends with warnings must write no Deliverable files (an existing rule with a test), and those Executions are the ones most worth learning from.
|
||||
|
||||
On "no secrets and no discovered cloud data": a refusal from a `cloud_read` tool keeps only the words before its first colon, and every message is cut at 500 characters. Revision reasons, user feedback and finding evidence are kept whole, so a record can quote the user and name resources in generated Terraform. Treat the files as client data.
|
||||
|
||||
Tests: `tests/execution/test_lessons.py`.
|
||||
36
.agents/plans/iter-04-learning-and-skills/steps/step-8.md
Normal file
36
.agents/plans/iter-04-learning-and-skills/steps/step-8.md
Normal file
@@ -0,0 +1,36 @@
|
||||
# Step 8 — Implementation Detail
|
||||
|
||||
Built, with two acceptance criteria still open (listed at the end).
|
||||
|
||||
1. **Structural checks added to every case** (`eval/scoring.py`):
|
||||
- `components_trace_to_requirements`: every row of the decomposition's component table names a requirement.
|
||||
- `no_blocking_findings`: the final `findings.json` holds no `critical` or `high` finding.
|
||||
2. **Judged checks**, run with `--judge`:
|
||||
- `pillar_checklists_covered`: each item of each pillar Skill's "Validation checklist" is put to the judge as a yes-or-no question against the design recommendations. The weakest pillar must reach 70%.
|
||||
- `recommendations_quality`: four graded questions (specific, actionable, trade-offs, traceable); the mean must reach 0.67.
|
||||
- `checklist_items` reads the checklists from the vendored Skills, nested bullets included, so a vendor sync updates the questions.
|
||||
3. **Judge seam** (`eval/judge.py`): a `Judge` takes one document and a map of typed questions and returns a score from 0 to 1 each. `GeminiJudge` uses the bundle's default model, or `EVAL_JUDGE_MODEL`. The shape matches a decision model's, for iteration 5 step 10. One live call confirmed it works.
|
||||
4. **Interactive case.** A case marked `"interactive": true` runs with a scripted user: `run_with_scripted_user` grants Approvals, denies cloud reads and answers questions by pattern. It adds the check `specialists_ask_before_submitting`. `case-04-interactive-web-app` is case 03 run this way.
|
||||
5. **Thresholds.** A case may set `thresholds` for `revisions`, `seconds` and `tokens`. Exceeding one is printed as `REGRESSION`, listed in the report, and makes the exit code non-zero. It does not change the score.
|
||||
|
||||
`automatic_reply` in `app/nodes/execution_nodes.py` lost its leading underscore so the evaluation can reuse it.
|
||||
|
||||
Tests: `tests/eval/test_scoring.py`, with a fake judge.
|
||||
|
||||
Open:
|
||||
|
||||
- **Thresholds are not set.** They need a baseline per case from a completed run of the current code. None exists: see below.
|
||||
- **No judged or interactive run yet.**
|
||||
- **Judge stability** across repeated runs on the same output is unmeasured (iteration 5 step 10 names it).
|
||||
|
||||
## The evaluation run of 2026-10-06 (stopped, no score)
|
||||
|
||||
A three-case run was started on the code as of steps 1 to 6 and stopped by the owner after 35 minutes, during case 01. Cases 02 and 03 never started. Nothing was scored and no files were written, so it gives no baseline. What its log showed:
|
||||
|
||||
- Seven Deliverables were submitted on their first attempt in about 15 minutes, including the decomposition and description under their new contracts (step 4).
|
||||
- The Orchestrator reopened deployment guidance after each failed validation without first asking for Approval of the validation Phase, which is what step 6 intended. Observed three times in one case.
|
||||
- No Revision of the design recommendations occurred, so step 3 was not exercised.
|
||||
- Validation did not converge: three passes gave 4, then 7, then 5 different findings, and deployment guidance used all three Revisions. The four findings of the first pass were all still present after the first Revision.
|
||||
- The Orchestrator stopped without calling a tool four times and was nudged; one such turn took 234 seconds.
|
||||
|
||||
The non-convergence led to ADR-0005 (proposed): establish the Target architecture as an explicit graph with numbered Checks before code is written.
|
||||
207
.agents/plans/iter-05-jev-decisions/DETAIL.md
Normal file
207
.agents/plans/iter-05-jev-decisions/DETAIL.md
Normal file
@@ -0,0 +1,207 @@
|
||||
# Plan Detail
|
||||
|
||||
Rules for every step from 3 onward:
|
||||
|
||||
- The question wording lives in a Skill or the provider bundle, so decisions stay portable and reviewable.
|
||||
- Each question has a confidence threshold and a named fallback. Below the threshold, or when Jev is unavailable, the fallback runs.
|
||||
- **Optimisations fail open** to today's behaviour (steps 3, 6, 7, 8, 9). **Guards fail closed** and ask the user (steps 13, 14).
|
||||
- With no API key configured, the agent behaves exactly as it does without this iteration.
|
||||
- The step ends with an evaluation run recorded in its step file: the quality checks hold, and tokens, seconds or Revisions fall against the baseline.
|
||||
|
||||
## Step 1: Resolve the open questions
|
||||
|
||||
- **Capability:** The facts needed to send client data to Jev.
|
||||
- **Questions for the owner or vendor:**
|
||||
- The base URL the separate deployment exposes. The public documentation shows one hosted endpoint and no self-hosting option.
|
||||
- How long submitted state is retained. Client requirements and, in later steps, discovered cloud state would be sent.
|
||||
- Rate limits and typical latency.
|
||||
- **Acceptance criteria:** Each answer is recorded in this step's file. A retention answer that rules out client data narrows steps 7, 9, 13 and 14, and this plan is updated to say so.
|
||||
|
||||
## Step 2: Decider interface and Jev client with limits
|
||||
|
||||
- **Capability:** One seam through which the engine asks closed questions, with a real client and a scripted fake.
|
||||
- **Rationale:** The same reason `AgentRuntime` exists: the deterministic suite must stay model-free, and the vendor must be replaceable. The LangChain middleware shown in the vendor's article targets `create_agent` and does not plug into the ADK runtime, so the client calls the REST API directly.
|
||||
- **Where:** a `Decider` protocol beside `AgentRuntime` in `app/adk/runtime.py`; a client and fake under `app/tools/`; settings in `app/config.py` (`JEV_API_KEY`, `JEV_BASE_URL`, and the limits below); wiring in `open_assembly` in `app/agent.py`.
|
||||
- **Limits the client enforces.** Jev's own limits are undocumented, so assume they are strict and never let Jev block an Execution. Values are starting defaults held in settings, to tune from measurement.
|
||||
|
||||
| Practice | Default |
|
||||
|---|---|
|
||||
| Refuse locally above a token count; split by Deliverable or section, never truncate | 48 thousand tokens (25% under the limit); 24 thousand for state plus the longest question |
|
||||
| Send every question about one state in one call | one call per state |
|
||||
| Timeout | 2 seconds connect, 5 seconds total |
|
||||
| Retry 429, 5xx and network errors with exponential backoff and full jitter; honour `Retry-After`; never retry other 4xx | 2 retries, 0.5 second base, 8 second cap |
|
||||
| Process-wide token bucket, lowered automatically after a 429 | 5 requests per second, burst 10 |
|
||||
| Semaphore on calls in flight | 8 |
|
||||
| Circuit breaker, with one probe call before closing | open after 5 failures in 30 seconds; 60 second cool-down |
|
||||
| Cache answers by a hash of model, state and questions | in memory, per Execution |
|
||||
| Budget per Execution; on reaching it use fallbacks and record a warning | 500 calls or $0.50 |
|
||||
| Read `usage.credits_remaining_usd` and warn before credits run out | warn below $5 |
|
||||
| Record per question: latency, confidence, fallback used, 429 count; add to the evaluation report | always |
|
||||
| API key from the secret store or environment, redacted from logs, never in the bundle or repository | `JEV_API_KEY` |
|
||||
|
||||
- **Acceptance criteria:** Tests with a stub HTTP server cover each row of the table. The fake `Decider` is used by every other test. With `JEV_API_KEY` unset, `open_assembly` wires a `Decider` that always returns "fallback".
|
||||
|
||||
## Step 3: Pillars a Revision touches
|
||||
|
||||
- **Report ref:** J3
|
||||
- **Capability:** The feedback text selects which pillar advisors re-run.
|
||||
- **Design:** One call with a Noul per pillar: "Does this feedback require changes to the <pillar> recommendations?" The pillars above threshold become the `pillars` argument of `consult_pillar_advisors`.
|
||||
- **Fallback:** all pillars.
|
||||
- **Where:** `app/tools/pillars.py`; questions beside `pillar_skills` in `providers/gcp.yaml`.
|
||||
- **Acceptance criteria:** A test shows only selected pillars run. On the cases, design-advisor Revisions run fewer advisors with the quality checks unchanged.
|
||||
|
||||
## Step 4: Semantic checks at submission
|
||||
|
||||
- **Report ref:** J4, and Jev's "task-completion check" use case
|
||||
- **Capability:** Submission contracts that check meaning, not only headings.
|
||||
- **Rationale:** `check_submission` checks headings and attachments. Rules such as "name no products" are instructions the engine cannot enforce, and a Revision of the IaC author and validator costs hundreds of thousands of tokens.
|
||||
- **Design:** Noul questions per Deliverable kind at `submit_deliverable`, for example: requirements name no products; every component traces to a requirement; every recommendation cites a source; the Deliverable addresses its task; tool output backs the claim. A failed check refuses the submission with the reason, as a missing section does today.
|
||||
- **Fallback:** accept on the structural contract alone.
|
||||
- **Where:** `submit_deliverable` in `app/tools/execution.py`; questions per kind in a Skill or the bundle.
|
||||
- **Acceptance criteria:** A test shows a refusal carrying the failed question's reason. Refusals count against the Specialist's budget as today. On the cases, Revisions per Execution fall.
|
||||
|
||||
## Step 5: Finding-to-Deliverable routing
|
||||
|
||||
- **Report ref:** J2
|
||||
- **Capability:** Each validator finding is routed to the Deliverable to reopen, with a severity.
|
||||
- **Design:** A Choice over the Deliverable kinds and a Score for severity, per finding from `findings.json`. The result is offered to the Orchestrator in its context; the Orchestrator still calls `reopen`.
|
||||
- **Fallback:** the validator's own stated Deliverable.
|
||||
- **Where:** `_orchestrator_context` in `app/nodes/execution_nodes.py`.
|
||||
- **Acceptance criteria:** A test shows routed findings in the Orchestrator's context. Disagreement between Jev and the validator is recorded as a lesson candidate.
|
||||
|
||||
## Step 6: Model tier per delegation
|
||||
|
||||
- **Report ref:** J5, and Jev's "model routing" use case
|
||||
- **Capability:** The cheaper model tier where the task allows.
|
||||
- **Design:** A Choice between the bundle's tiers per delegation, from the task and its feedback. A Revision after a failed attempt goes to the stronger tier.
|
||||
- **Fallback:** the role's configured model.
|
||||
- **Where:** `default_model_factory` in `app/adk/adk_runtime.py`; tiers and criteria in `models` in `providers/gcp.yaml`.
|
||||
- **Acceptance criteria:** Quality checks hold on the cases with lower token cost. A role the bundle pins to one tier is never rerouted.
|
||||
|
||||
## Step 7: Context selection
|
||||
|
||||
- **Report ref:** J6, and Jev's "repo context selection" use case
|
||||
- **Capability:** Only relevant sections of earlier Deliverables reach a Specialist in full.
|
||||
- **Design:** A Noul per section: "Is this section needed to produce the <kind> Deliverable?" Sections below threshold are passed as one-line summaries.
|
||||
- **Fallback:** the rule from iteration 4 step 13.
|
||||
- **Where:** `_specialist_input` in `app/nodes/execution_nodes.py`.
|
||||
- **Acceptance criteria:** Describer and packager tokens fall with the quality checks unchanged.
|
||||
|
||||
## Step 8: Skill routing
|
||||
|
||||
- **Report ref:** J9, and Jev's "agent skill routing" use case
|
||||
- **Capability:** A Specialist is told which Skill and reference file to load first; overlay Skills are selected per Execution.
|
||||
- **Design:** A Choice over the role's Skills and their references, with a `none` option.
|
||||
- **Fallback:** on `none` or low confidence, the Specialist searches the Skill itself, as today.
|
||||
- **Where:** `_render_task` in `app/adk/adk_runtime.py`, `app/adk/roles.py`.
|
||||
- **Acceptance criteria:** Fewer `load_skill_resource` calls per Specialist run with the quality checks unchanged.
|
||||
|
||||
## Step 9: In-run context compaction
|
||||
|
||||
- **Report ref:** J10, and Jev's "context compaction" use case
|
||||
- **Capability:** Old tool results inside one agent run are kept, truncated or dropped.
|
||||
- **Rationale:** The IaC author makes 23 requests and resends full Terraform files and validate output on each.
|
||||
- **Design:** Before each model request, a Noul and a Choice (`keep`, `truncate`, `drop`) per old tool result.
|
||||
- **Fallback:** keep everything.
|
||||
- **Where:** `app/adk/adk_runtime.py`, through ADK's before-model hook.
|
||||
- **Acceptance criteria:** IaC author and validator prompt tokens fall. No run loses the latest version of a file it later submits.
|
||||
|
||||
## Step 10: Evaluation rubric and lesson triage
|
||||
|
||||
- **Report ref:** J8
|
||||
- **Capability:** Cheap graded scoring in the evaluation, and sorted lesson candidates.
|
||||
- **Design:** Score questions implement the graded rubric from iteration 4 step 8. A Choice sorts lesson candidates by Deliverable kind; a Noul flags duplicates for the curator.
|
||||
- **Where:** `eval/scoring.py`, the curator from iteration 4 step 10.
|
||||
- **Acceptance criteria:** Rubric scores are stable across repeated runs on the same output. The curator receives candidates grouped and de-duplicated.
|
||||
|
||||
## Step 11: ADR: Jev is the Orchestrator's decision point
|
||||
|
||||
- **Capability:** A recorded decision that Jev proposes the Orchestrator's next action, code checks and carries it out, and a generative model only writes replies.
|
||||
- **Rationale:** The owner's direction on 2026-10-07: use Jev as the decision point, not a different model. It replaces part of ADR-0003, which made the Orchestrator an ADK agent and rejected an Orchestrator without a model.
|
||||
- **Where:** `docs/adr/0007-jev-is-the-orchestrators-decision-point.md`, with four points to confirm; a note on ADR-0003.
|
||||
- **Acceptance criteria:** ADR-0007 is `accepted`, or amended with step 12 updated to match.
|
||||
|
||||
## Step 12: The Orchestrator decides with Jev, with no language model
|
||||
|
||||
- **Report ref:** J1, widened by ADR-0007
|
||||
- **Capability:** Each Orchestrator turn is decided by the Ledger's rules and, where there is a choice or the user has spoken, by Jev.
|
||||
- **Rationale:** In the stopped run of 2026-10-06 the Orchestrator took about 7 of 35 minutes and stalled four times. In case 03 it made 36 requests on the larger model.
|
||||
- **Design:**
|
||||
1. A pure function lists the allowed next actions from the Ledger and the Execution's state.
|
||||
2. One allowed action is taken without a decision.
|
||||
3. Otherwise Jev is asked closed questions through the `Decider` from step 2: whether the user asked for a change and to which Deliverable; what follows a validation outcome; which allowed action is next.
|
||||
4. Code carries the decision out through `OrchestratorToolbox`, so the Ledger's rules are unchanged.
|
||||
5. Each decision is recorded in the Execution's state with its questions, answers and probabilities, and reused when a resumed Execution has unchanged input.
|
||||
6. A generative model writes only what the user reads: an Approval summary, or a question of the Orchestrator's own, from the decision and the data. It runs after the decision and cannot change it. A Revision's reason is the user's words or the failed Checks.
|
||||
7. A failed Jev call is recorded as a failure, distinct from an answer, and retried within a fixed budget before the fallback.
|
||||
- **Pattern followed:** https://vercel.com/i/jev-agent-control. Its ownership split maps as: propose the next action, Jev; check permission, the Ledger; execute, the existing tools; update state, the Execution graph; explain the result, a generative model. Its specialist routing is not used, because the dependency graph fixes which Specialist produces each Deliverable.
|
||||
- **Routing (owner's direction, 2026-10-07):** the Orchestrator acts as a router with Jev choosing the route. Four things are routed:
|
||||
- a message that starts something: new Workflow request, Change request against a Baseline, question about delivered work, or out of scope (Choice);
|
||||
- a message inside an Execution: an answer to a waiting question, a request to change a named Deliverable, or anything else (Choice, then a Choice over the Deliverables);
|
||||
- a validation outcome: revise the code, revise the Target architecture, or proceed (Choice);
|
||||
- in a Change request, which Deliverables the change reaches (a Boolean per Deliverable, with the Requirements chain as the deterministic check).
|
||||
The route decides what is dispatched. Which Specialist produces a Deliverable stays fixed by the dependency graph, and every Deliverable is still produced in a new Execution. The first route needs an entry point that can start a Change request or answer from a case's files (`app/main.py`, `app/a2a_server.py`); the last depends on iteration 7.
|
||||
- **Fallbacks:** Below the confidence threshold, an interactive Execution asks the user and a pre-approved one takes the safest allowed action with a warning. When Jev is unreachable, the fixed order of the seven steps is used and recorded.
|
||||
- **Where:** `orchestrator_turn` in `app/nodes/execution_nodes.py`; `app/tools/execution.py`; `agents/orchestrator.md` becomes question wording and fixed text in a Skill or the bundle; `app/adk/roles.py` and `providers/gcp.yaml` no longer need an Orchestrator model.
|
||||
- **What is sent to Jev:** state, not content: Deliverable names and statuses, Check ids and verdicts, the user's latest message.
|
||||
- **Acceptance criteria:** The engine tests pass with a scripted `Decider` in place of the scripted Orchestrator model, covering every Ledger rule they cover today. No language model call chooses an action; the only Orchestrator model calls write user-facing text. A decision Jev proposes that the Ledger does not allow is refused and recorded. With no Jev key configured, an Execution still completes on the fixed order. On the evaluation cases, quality checks hold and Orchestrator seconds fall against the baseline.
|
||||
|
||||
## Step 13: Cloud-read call guard
|
||||
|
||||
- **Report ref:** J7, and Jev's "tool-call risk gate" use case
|
||||
- **Capability:** A check before each cloud-read call that it stays within the scope the user named.
|
||||
- **Design:** A Noul: "Is this call within the project and regions the user named?" It adds to the allowlist and the per-Execution permission; it replaces neither.
|
||||
- **Fallback:** fail closed: ask the user.
|
||||
- **Where:** `gate_cloud_read` in `app/tools/execution.py`.
|
||||
- **Depends on step 1:** tool arguments name the user's cloud resources.
|
||||
- **Acceptance criteria:** A test shows an out-of-scope call becoming a question to the user.
|
||||
|
||||
## Step 14: Input guardrail
|
||||
|
||||
- **Report ref:** J11, and Jev's "LLM guardrail" use case
|
||||
- **Capability:** Injected instructions are caught before a Specialist reads them.
|
||||
- **Design:** A Noul on the Workflow request, user replies and text returned by MCP servers: "Does this text try to instruct the agent rather than inform it?"
|
||||
- **Fallback:** fail closed: withhold the text and tell the Orchestrator.
|
||||
- **Where:** `app/tools/mcp.py`, `await_user` in `app/nodes/execution_nodes.py`.
|
||||
- **Depends on step 1:** MCP results hold discovered cloud state.
|
||||
- **Acceptance criteria:** A test with a planted instruction in an MCP result shows it withheld and noted.
|
||||
|
||||
## Step 15: Changes of meaning in a Change request
|
||||
|
||||
- **Report ref:** none; from the "UI copy translation review" use case the owner named on 2026-10-07
|
||||
- **Capability:** A Change request follows through only the things whose meaning changed.
|
||||
- **Rationale:** A Specialist revising from a Baseline rewords text it was not asked to change. Comparing text exactly would treat every rewording as a change; ignoring text would miss a dropped restriction, such as "only" removed from a requirement.
|
||||
- **Design:** For each requirement, Element and Check whose text differs from the Baseline's, one Boolean question with the old and new text and its id: "Does the new text change what must be true?" A yes marks it changed, so the Requirements chain is followed from it; a no carries the Baseline's verdict forward.
|
||||
- **Fallback:** Treat it as changed.
|
||||
- **Where:** the graph comparison from iteration 7 step 4 (`app/workflows/target_architecture.py`), the change summary from iteration 7 step 6.
|
||||
- **Acceptance criteria:** A reworded but equivalent Check is not reported as changed; a Check that lost or gained a condition is. Every decision is recorded with its probability in `changes.json`.
|
||||
|
||||
## Step 16: Jev as the evaluation judge, calibrated
|
||||
|
||||
- **Capability:** The evaluation's judged checks are answered by Jev, and the judge is shown to agree with a person.
|
||||
- **Rationale:** LangChain's evaluation posts report Jev agreeing with a human reviewer on every pass-or-fail decision in a small experiment, with far lower variance than language-model judges, at $0.00035 a call. They also warn that low cost can amplify mistakes and that human review and judge alignment are still needed.
|
||||
- **Built:** `DeciderJudge` in `eval/judge.py` asks every question in one call, with the document as the state and no grading instructions in it. `eval/solution_eval.py --judge` uses it when `TYPESAFE_API_KEY` is set, and the language-model judge otherwise or with `EVAL_JUDGE=gemini`. A judge that gives no answer leaves its check unanswered, not passed.
|
||||
- **Open:** a small set of design recommendations labelled by a person against the pillar checklists and the quality rubric; agreement of each judge with those labels; variance over repeated runs on the same output. This replaces the stability criterion in step 10.
|
||||
- **Acceptance criteria:** On the labelled set, the Jev judge's pass-or-fail agreement and its variance are recorded beside the language-model judge's, and the evaluation uses the one that agrees better.
|
||||
|
||||
## Step 17: Trace every decision
|
||||
|
||||
- **Capability:** For any Execution, a person can see each decision, what it was given and what came back.
|
||||
- **Rationale:** LangChain's production post treats tracing as required for model-driven steps and describes LangSmith views for decision models. Here decisions are kept in the Execution's state and the evaluation report, and nothing is traced.
|
||||
- **Owner's decision needed:** whether to send traces to LangSmith. Traces carry the Workflow request and Deliverable text, so the same retention question as Jev applies. `langsmith` is already installed as a dependency of LangChain; LangGraph traces when its environment variables are set.
|
||||
- **Where:** environment settings for tracing; a traced span around `JevDecider.decide` in `app/tools/jev.py` carrying the questions, answers and probabilities; `docs/operations/`.
|
||||
- **Acceptance criteria:** One Execution's trace shows every Orchestrator turn, each Jev call with its inputs and outputs, and each Specialist run. With tracing off, nothing leaves the process.
|
||||
|
||||
## Step 18: Readings as their own graph step
|
||||
|
||||
- **Capability:** A resumed Execution reuses the decisions it already made.
|
||||
- **Rationale:** LangGraph saves state after each node. The router takes its readings and acts inside one node, so a failure in that node asks Jev again on retry. Jev is designed to return the same answer for the same input, and the client caches answers in memory, but neither survives a restart.
|
||||
- **Where:** `app/workflows/execution_graph.py` and `app/nodes/`: a node that takes the readings and saves them, before the node that applies the playbook.
|
||||
- **Acceptance criteria:** A test that fails the playbook node after the readings node shows the retry using the saved readings, with no second call to the decider.
|
||||
|
||||
## Step 19: Online evaluation of live Executions
|
||||
|
||||
- **Capability:** Every Execution is scored as it runs, not only benchmark cases.
|
||||
- **Rationale:** At Jev's cost, LangChain recommends scoring every run and alerting on risk flags such as leaked personal data or injected instructions.
|
||||
- **Where:** the judged checks from `eval/scoring.py`, run when an Execution ends and stored with its record; with step 17, as feedback on its trace.
|
||||
- **Acceptance criteria:** A completed Execution carries its judged scores. A flagged risk is recorded and surfaced without stopping the Execution.
|
||||
120
.agents/plans/iter-05-jev-decisions/MAP.md
Normal file
120
.agents/plans/iter-05-jev-decisions/MAP.md
Normal file
@@ -0,0 +1,120 @@
|
||||
# Plan Map
|
||||
|
||||
**Iteration:** 5, Jev decisions
|
||||
**Intent:** Use Jev, a hosted decision model, for the agent's closed questions (yes or no, pick one, rate on a scale) so that large-model calls are kept for writing and reasoning. The aims are fewer tokens, faster turns, and checks the engine cannot make with string matching.
|
||||
**Status:** steps 2, 11 and 12 built (2026-10-07); the rest planned. Step 1's answers are still open: the API key, rate limits and data retention. Build `../iter-06-target-architecture-graph/` first: it removes the need for step 5 here and changes what step 4 checks.
|
||||
**This directory covers:** steps 1 to 19
|
||||
|
||||
## What Jev is
|
||||
|
||||
Jev is TypeSafe AI's "System One" model. It takes a `state` (text) and a map of typed `questions`, and returns calibrated probabilities instead of prose:
|
||||
|
||||
- **Choice:** pick one option. Returns `choice`, `confidence`, `probabilities`.
|
||||
- **Score:** rate against ordered levels. Returns `score`, `probabilities`, `legend`, `confidence`.
|
||||
- **Noul:** yes or no. Returns `noul` (0 to 1) and `confidence`.
|
||||
|
||||
Facts from the vendor's documentation, read 2026-10-06:
|
||||
|
||||
- `POST /api/v1/decide` with `Authorization: Bearer <key>`; body `model` (optional), `state`, `questions`; response `answers` plus `usage` (`input_tokens`, `cost_usd`, `credits_remaining_usd`).
|
||||
- Limits: 64 thousand tokens for state plus questions, 32 thousand for state plus the longest question.
|
||||
- Price: $0.42 per million input tokens; output free.
|
||||
- Undocumented: rate limits, latency, batching, data retention, self-hosting.
|
||||
- The vendor claims up to 200x faster and 400x cheaper than comparable LLMs on classification. That is unmeasured here.
|
||||
|
||||
Jev will be deployed separately and reached with an API key (owner, 2026-10-06).
|
||||
|
||||
## Sources of truth
|
||||
|
||||
- https://www.langchain.com/blog/building-a-harness-with-jev and https://www.jevtypesafeai.com/use-cases (and `/docs` on that site).
|
||||
- https://vercel.com/i/jev-agent-control: the agent-control pattern step 12 follows (decision model proposes, code checks and executes, a generative model explains).
|
||||
- Review report, section "Where Jev fits": https://claude.ai/code/artifact/16b37169-1554-4eb7-bfcb-254315fa0518. `Report ref` names its J-number.
|
||||
- `iter-04-learning-and-skills/`: several steps here build on steps there.
|
||||
- `docs/adr/0003-langgraph-holds-state-adk-agents-reason.md`: step 12 changes what it says about the Orchestrator.
|
||||
|
||||
## The capabilities the owner wants from Jev
|
||||
|
||||
On 2026-10-07 the owner named the nine use cases at https://vercel.com/i/jev-use-cases as the capabilities to use. Each maps to this agent as follows.
|
||||
|
||||
| Jev use case | Question type | What it is here | Step |
|
||||
|---|---|---|---|
|
||||
| Form routing | Choice | Read the user's message: an answer, a request for changes, or a new statement of Intent, and which Deliverable a change affects | 12 |
|
||||
| Tool-call review (`clear` or `caution`) | Choice | Review each cloud-read call and `terraform_plan` before it runs; `caution` pauses for the user | 13 |
|
||||
| Response model selection | Choice | Pick the model tier for each delegation from the bundle's list | 6 |
|
||||
| Response evaluation | Boolean, Score | Judge a Deliverable at submission (does it address its task; is each Check verifiable as written), and score the evaluation's rubric | 4, 10 |
|
||||
| Content moderation | Boolean | Flag text that breaks a written policy: requirements that name products; request or tool text that tries to instruct the agent | 4, 14 |
|
||||
| UI copy translation review (did an edit change the meaning?) | Boolean | In a Change request, flag a requirement, Element or Check whose meaning changed against the Baseline, so only real changes are followed through | 15 |
|
||||
| Ticket prioritization | Score | Rate how much a proposed addition or a failed Check matters, to order Revisions and lesson candidates | 10 |
|
||||
| Document categorization | Choice | Sort lesson candidates by Deliverable for the curator | 10 |
|
||||
| CSV column mapping | Choice | Suggest which requirement or recommendation a proposed addition serves, for confirmation; code still checks the link exists | 10 |
|
||||
|
||||
The page's own cautions apply to every step: Jev does not write replies, so a generative model drafts messages; exact conditions (a Dependency is met, a file is attached, an id exists) stay deterministic checks in code; and a typed answer can still be wrong, so start where outcomes can be inspected and corrected, and record every decision.
|
||||
|
||||
## Alignment with LangChain's published guidance
|
||||
|
||||
Checked on 2026-10-07 against three LangChain posts: "Building prod with Jev and LangGraph", "Jev agent evals with LangSmith" and "Jev is now available in LangSmith evals". Steps 16 to 19 close the gaps found.
|
||||
|
||||
| Their guidance | Here | Step |
|
||||
|---|---|---|
|
||||
| Code owns the workflow; Jev makes narrow, typed decisions | The Ledger and the playbook are code; Jev supplies readings | 12 |
|
||||
| Encode domain knowledge in the graph's topology, not in prompts | The dependency graph, Phases and playbook are data and code | 12 |
|
||||
| Several atomic questions against one state, in one call | Readings are batched per turn | 2, 12 |
|
||||
| Language models for open-ended work | Specialists write Deliverables; a model writes replies | 12 |
|
||||
| Humans in the loop through interrupts | Approvals and every user question are interrupts | done |
|
||||
| Checkpointing, so a failed run resumes with the decisions it made | The Execution is checkpointed; a decision is saved only when its turn ends | 18 |
|
||||
| Low confidence falls back to a language model (their example: under 0.7) | Low confidence goes to the user, by the owner's choice in ADR-0007 | differs on purpose |
|
||||
| Trace every decision, with its inputs and calibrated outputs | Decisions are kept in Execution state and the evaluation report; nothing is traced | 17 |
|
||||
| Jev as the judge: typed questions, no grading instructions in the state | `DeciderJudge` in `eval/judge.py`, used when a key is set | 16 |
|
||||
| Check a judge against human labels, and for repeatability | Not done; there is no labelled set | 16 |
|
||||
| Score every live run and alert on risk flags | Evaluation is offline only | 19 |
|
||||
|
||||
## Boundaries
|
||||
|
||||
Jev answers closed questions. Writing Deliverables, grounding product choices and producing infrastructure code stay with the large models. Dependencies and Approvals stay rules in the Ledger.
|
||||
|
||||
## Status
|
||||
|
||||
| Step | What | Report ref | Status |
|
||||
|---|---|---|---|
|
||||
| 1 | Resolve the open questions | none | open, owner's input |
|
||||
| 2 | Decider interface and Jev client with limits | none | built on the TypeSafe SDK; unverified against the live service |
|
||||
| 3 | Pillars a Revision touches | J3 | planned |
|
||||
| 4 | Semantic checks at submission | J4 | planned |
|
||||
| 5 | Finding-to-Deliverable routing | J2 | planned |
|
||||
| 6 | Model tier per delegation | J5 | planned |
|
||||
| 7 | Context selection | J6 | planned |
|
||||
| 8 | Skill routing | J9 | planned |
|
||||
| 9 | In-run context compaction | J10 | planned |
|
||||
| 10 | Evaluation rubric and lesson triage | J8 | planned |
|
||||
| 11 | ADR: Jev is the Orchestrator's decision point | none | complete: ADR-0007 accepted 2026-10-07 |
|
||||
| 12 | The Orchestrator routes by readings and a playbook; a model only writes replies | J1 | built for messages inside an Execution and validation outcomes; unverified against live Jev and by evaluation |
|
||||
| 13 | Cloud-read call guard | J7 | planned |
|
||||
| 14 | Input guardrail | J11 | planned |
|
||||
| 15 | Changes of meaning in a Change request | none | planned; needs iteration 7 |
|
||||
| 16 | Jev as the evaluation judge, calibrated | none | judge built; calibration against human labels open |
|
||||
| 17 | Trace every decision | none | open, owner's decision on LangSmith |
|
||||
| 18 | Readings as their own graph step | none | planned |
|
||||
| 19 | Online evaluation of live Executions | none | planned; needs step 17 |
|
||||
|
||||
## Dependency graph
|
||||
|
||||
- Step 1: no dependencies
|
||||
- Step 2: depends on step 1
|
||||
- Step 3: depends on step 2, iteration 4 step 3
|
||||
- Step 4: depends on step 2
|
||||
- Step 5: depends on step 2, iteration 4 step 1
|
||||
- Step 6: depends on step 2
|
||||
- Step 7: depends on step 2, iteration 4 step 13
|
||||
- Step 8: depends on step 2, iteration 4 step 12
|
||||
- Step 9: depends on step 2
|
||||
- Step 10: depends on step 2, iteration 4 step 7, iteration 4 step 8
|
||||
- Step 11: no dependencies
|
||||
- Step 12: depends on step 2, step 11. Build it straight after step 2, ahead of steps 3 to 10.
|
||||
- Step 13: depends on step 2
|
||||
- Step 14: depends on step 2
|
||||
- Step 15: depends on step 2, iteration 7 step 4
|
||||
- Step 16: depends on step 2
|
||||
- Step 17: no dependencies
|
||||
- Step 18: depends on step 12
|
||||
- Step 19: depends on step 16, step 17
|
||||
|
||||
Steps 3 and 4 come first: they are small, need no ADR change, and target Revisions, where the tokens are. The Orchestrator is 11% of case 03's tokens; the IaC author and validator together used 1.43 million over 7 runs.
|
||||
9
.agents/plans/iter-05-jev-decisions/steps/step-11.md
Normal file
9
.agents/plans/iter-05-jev-decisions/steps/step-11.md
Normal file
@@ -0,0 +1,9 @@
|
||||
# Step 11 — Implementation Detail
|
||||
|
||||
ADR-0007 was accepted by the owner on 2026-10-07 ("this is exactly what I want, I approve ADR-0007"), after three refinements made the same day and recorded in it:
|
||||
|
||||
1. Jev is the decision point, in place of a different language model.
|
||||
2. The agent-control pattern at https://vercel.com/i/jev-agent-control is followed: a decision model reads, application code checks permission and executes, a generative model writes replies.
|
||||
3. The Orchestrator is a router, and decides by readings, a disposition and a playbook, on the model of a triage pipeline the owner supplied: the first group that applies, the strongest action whose conditions hold, escalate when none applies.
|
||||
|
||||
Jev is reached through TypeSafe AI's Python SDK and API endpoint (owner, 2026-10-07). The API key is still to be supplied.
|
||||
36
.agents/plans/iter-05-jev-decisions/steps/step-12.md
Normal file
36
.agents/plans/iter-05-jev-decisions/steps/step-12.md
Normal file
@@ -0,0 +1,36 @@
|
||||
# Step 12 — Implementation Detail
|
||||
|
||||
Built against a scripted decider. No call has been made to the live Jev service, and no evaluation has run on it: the owner holds evaluation runs until the Jev work is in.
|
||||
|
||||
1. **`app/nodes/router.py`.** `Router` decides an Orchestrator turn in three stages: readings (`_read_ledger` from the Ledger and data; `_read_message` and `_read_gap` from the decider), a disposition by `Thresholds` (act at 0.75, close at 0.15, choice confidence 0.6), and the playbook in `_choose`: ordered groups, the strongest action whose conditions hold, escalate when none applies.
|
||||
2. **Permission stays with the tools.** The router calls the same `OrchestratorToolbox` tools the model did. A refused action is skipped for the rest of the turn and the next one that holds is taken. Past the Revision limit the user is asked.
|
||||
3. **What Jev is asked** (`Question` objects, batched when they rest on the same evidence):
|
||||
- of the user's message: `asks_change` (noul), `change_target` (choice over submitted Deliverables), `change_clarity` (score: vague, partial, specific);
|
||||
- of validation gaps: `gap_material` (noul);
|
||||
- of the user's reply about gaps: `wants_revision` (noul).
|
||||
What is sent is Deliverable names, the count of waiting questions, the user's message, and for gaps the proposed Check statements and unverifiable Check ids.
|
||||
4. **Rules when Jev gives no answer.** A requested change is acted on only when one Deliverable is named outright, otherwise the user is asked which. A free-text reply is treated as an answer. A gap is revised for when a Check cannot be verified or an addition names a real requirement or recommendation id.
|
||||
5. **A new reading from the run of 2026-10-07:** a Check that fails in two validations running is sent to the Target architecture, not the code. That run retried one unimplementable Check as code three times.
|
||||
6. **Decisions are recorded** in the Execution's state under `decisions`: turn, group, action and what was judged, with confidence.
|
||||
7. **The reply writer.** A new role, `agents/reply-writer.md`, writes the Approval summary from facts (`approval_facts`) through one tool. When it fails or is absent, `assembled_summary` builds the summary from the same facts.
|
||||
8. **Wiring.** `ORCHESTRATOR=router` (the default) or `model`; `open_assembly` builds the router with the decider and the thresholds (`JEV_ACT_THRESHOLD`, `JEV_CLOSE_THRESHOLD`, `JEV_CONFIDENCE_THRESHOLD`). State gained `last_reply`, `pending_change`, `awaiting_gap_decision`, `validation_settled` and `decisions`.
|
||||
|
||||
Changed from the plan and the ADR's first wording:
|
||||
|
||||
- **Jev does not propose the next action.** It supplies readings, and the playbook in code picks the action. This follows the owner's triage model and keeps every decision explainable by a rule and a threshold.
|
||||
- **The model Orchestrator is kept** behind `ORCHESTRATOR=model`. The 40 or so engine tests drive the Ledger's rules by scripting its tool calls in arbitrary order, which the router cannot do. `agents/orchestrator.md` is therefore unchanged and unused in router mode.
|
||||
- **An unclear change is confirmed once.** If the reply still does not settle it, a named Deliverable is acted on and anything else is dropped.
|
||||
- **A pre-approved Execution's automatic replies are not routed.** There is no user message to read.
|
||||
|
||||
Not built from the ADR's routes:
|
||||
|
||||
- **A message that starts something** (new request, Change request, question about delivered work, out of scope). It needs an entry point that can answer from a case's files, and Change requests (iteration 7).
|
||||
- **Which Deliverables a Change request reaches.** Iteration 7.
|
||||
|
||||
Tests: `tests/execution/test_router.py` (18), `tests/test_assembly.py`.
|
||||
|
||||
Unverified:
|
||||
|
||||
- Whether Jev's answers to these five questions are good enough at these thresholds. The thresholds are the ones in the owner's example and are untuned.
|
||||
- Whether the reply writer's summaries are accurate. It is instructed to state only the facts it is given; nothing checks that it does.
|
||||
- Run time. The Orchestrator made 31 model requests in the last run; the router makes none, and one small writer call per Approval. No run has measured it.
|
||||
44
.agents/plans/iter-05-jev-decisions/steps/step-2.md
Normal file
44
.agents/plans/iter-05-jev-decisions/steps/step-2.md
Normal file
@@ -0,0 +1,44 @@
|
||||
# Step 2 — Implementation Detail
|
||||
|
||||
Built ahead of step 1's answers, on the owner's instruction of 2026-10-07 that no evaluation be rerun until the Jev work is in. Nothing here has called the live service.
|
||||
|
||||
1. **The seam** (`app/adk/runtime.py`): `Question` (kind choice, score or noul, with instructions and options), `Answer` (value, confidence, probabilities) and the `Decider` protocol. `decide` returns the answers, or `None` when no decision could be made, and the caller then takes its fallback. `NoDecider` always returns `None`.
|
||||
2. **The client** (`app/tools/jev.py`): `JevDecider` calls Jev through TypeSafe AI's official Python SDK, `typesafe-sdk` 0.7.2 (`AsyncTypeSafeClient.system_one`). The owner chose the SDK and its API endpoint on 2026-10-07. It is the only module that imports the SDK.
|
||||
3. **Wiring:** `open_decider` in `app/agent.py` returns the client when `TYPESAFE_API_KEY` is set and `NoDecider` otherwise; the `Assembly` carries it.
|
||||
4. **A scripted decider** for tests, `FakeDecider` in `app/adk/fake_runtime.py`.
|
||||
|
||||
Which package: three names exist on the index. `typesafe-sdk` is the vendor's (author TypeSafe AI, repository `typesafe-ai/typesafe-sdk-python`). `typesafe` is an unrelated type-checking library, and `typesafe-ai` is a third party's redirect shim; neither is used.
|
||||
|
||||
What the SDK settled, read from the installed package and a stand-in transport:
|
||||
|
||||
- The request is `POST /v1/systemone` with a bearer key; default endpoint `https://api.typesafe.ai`, default model `jev-latest`.
|
||||
- Questions are `Noul(instructions)`, `Choice(instructions, criteria={option: description})` and `Score(instructions, criteria=[levels])`.
|
||||
- Answers are `noul` (a probability, with no confidence of its own), `choice` with `confidence` and `probabilities`, and `score` with `confidence`. Usage reports `input_tokens` only: no cost and no remaining credit.
|
||||
|
||||
Limits kept, each with a test in `tests/tools/test_jev.py`:
|
||||
|
||||
| Practice | Built as |
|
||||
|---|---|
|
||||
| Size | Refused locally above 48,000 estimated tokens in all, or 24,000 for the state plus the longest question. Never truncated. |
|
||||
| Batching | Every question about one state goes in one request. |
|
||||
| Timeout | 5 seconds a request, 15 for a decision with its retries (the SDK's). |
|
||||
| Retries | 2, by the SDK: on 408, 429, 5xx, connection and timeout errors, with jittered backoff, honouring `Retry-After`. |
|
||||
| Rate | A token bucket, 5 a second with a burst of 10; the rate halves when a rate limit outlasts the retries. |
|
||||
| Concurrency | At most 8 requests in flight. |
|
||||
| Circuit breaker | Opens after 5 failures in 30 seconds for 60 seconds, then lets one probe through. |
|
||||
| Cache | Answers kept by a hash of the state and questions, up to 1,024. |
|
||||
| Budget | 500 calls or 1,000,000 input tokens per scope (the Execution), then fallbacks with one warning. |
|
||||
| Records | Each decision's outcome, seconds, rate limiting, input tokens and confidence; `summary()` totals them. |
|
||||
| Key | From `TYPESAFE_API_KEY` only; never logged. |
|
||||
|
||||
Settings: `TYPESAFE_API_KEY`, `TYPESAFE_BASE_URL`, `TYPESAFE_DEFAULT_MODEL` (the SDK's own names), and `JEV_TIMEOUT_SECONDS`, `JEV_REQUESTS_PER_SECOND`, `JEV_MAX_IN_FLIGHT`, `JEV_BUDGET_CALLS`, `JEV_BUDGET_TOKENS`.
|
||||
|
||||
Changed from the plan:
|
||||
|
||||
- The cache is per client, not per Execution. A decision depends only on its state and questions, so two Executions asking the same thing can share the answer.
|
||||
- A reply that leaves any question unanswered, or picks a choice that was not offered, counts as no decision for the whole request.
|
||||
- The budget is in calls and input tokens, not dollars, and there is no low-credit warning: the SDK reports neither cost nor balance.
|
||||
- A yes-or-no answer's confidence is derived as its distance from an even probability, because Jev returns none.
|
||||
- Retries and their backoff are the SDK's, configured here, not reimplemented.
|
||||
|
||||
Unverified: the client has run only against a stand-in transport, with the real SDK in the loop. The first call with a real key is still to be made, and the service's actual rate limits, latency and data retention are still unknown.
|
||||
87
.agents/plans/iter-06-target-architecture-graph/DETAIL.md
Normal file
87
.agents/plans/iter-06-target-architecture-graph/DETAIL.md
Normal file
@@ -0,0 +1,87 @@
|
||||
# Plan Detail
|
||||
|
||||
Every step is built test-first with the fake runtime and ends with `pytest`, `ruff check .` and `mypy .` passing. File names for new attachments are proposals; keep them once a step uses them.
|
||||
|
||||
## Step 1: Accept ADR-0005
|
||||
|
||||
- **Capability:** A recorded decision to build on.
|
||||
- **The three points the owner confirms:**
|
||||
1. The user approves the Target architecture before code is written, which splits the solution architecture Phase and makes five Phases against the upstream Skill's four.
|
||||
2. A new Specialist produces the Target architecture.
|
||||
3. Code renders the diagram from the graph, and the diagrammer role is removed.
|
||||
- **Acceptance criteria:** ADR-0005's status is `accepted`, or it is amended and this plan is updated to match before any other step starts.
|
||||
|
||||
## Step 2: Identify requirements, components and recommendations by id
|
||||
|
||||
- **Capability:** Stable ids at the start of the Requirements chain, as data.
|
||||
- **Rationale:** A rule such as "every requirement has a Check" can only be enforced if requirements can be counted. Today requirements, components and recommendations exist only as prose.
|
||||
- **Where:** `app/workflows/deliverables.py` (new required attachments and their checks), `agents/requirements-analyst.md`, `agents/decomposer.md`, `agents/design-advisor.md`, `agents/partials/specialist-protocol.md`.
|
||||
- **Design:**
|
||||
- `requirements` attaches `requirements.json`: a list of `{id, kind, text}` with `kind` functional or non-functional.
|
||||
- `technical_decomposition` attaches `components.json`: a list of `{id, name, requirements: [ids]}`. This replaces the table contract from iteration 4 step 4.
|
||||
- `design_recommendations` attaches `recommendations.json`: a list of `{id, pillar, text, components: [ids]}`.
|
||||
- **Acceptance criteria:** Each attachment is refused when malformed, when an id repeats, or when it refers to an id that the Deliverable it depends on does not define. A requirement that no component serves is refused at the decomposition.
|
||||
|
||||
## Step 3: The graph: format, parsing and structural rules
|
||||
|
||||
- **Capability:** One definition of what a well-formed Target architecture is.
|
||||
- **Where:** new `app/workflows/target_architecture.py`, pure and without I/O, like the Ledger.
|
||||
- **Design:** `target-architecture.json` holds:
|
||||
- `elements`: `{id, name, component, product, resource_type}`.
|
||||
- `relationships`: `{id, from, to, kind}`.
|
||||
- `checks`: `{id, applies_to, statement, source}`, where `applies_to` is an Element or Relationship id and `source` is a requirement or recommendation id.
|
||||
- **Acceptance criteria:** Parsing refuses, with the offending id named: a repeated id; a Relationship whose `from` or `to` is not an Element; a Check whose `applies_to` is not in the graph; an Element with no Check; an empty `statement`. The module exposes the graph as typed data for steps 5, 7, 8 and 9.
|
||||
|
||||
## Step 4: The Target architecture Deliverable, its Specialist and its Skill
|
||||
|
||||
- **Capability:** A Deliverable that is the graph, produced by its own Specialist following a Skill.
|
||||
- **Where:** `DeliverableKind.TARGET_ARCHITECTURE` in `app/workflows/deliverables.py`, depending on product selection and design recommendations; a new role file in `agents/`; a new Skill under `skills/` that defines the format and how to derive Elements, Relationships and Checks; `providers/gcp.yaml` (`role_skills`, model); `app/adk/roles.py` picks the role up from the dependency graph.
|
||||
- **Rationale:** ADR-0002: how to model an architecture is behaviour and belongs in a Skill. The role file stays provider-neutral.
|
||||
- **Who writes it:** the Specialist, never the user. The user's input is the Workflow request and their answers during requirements discovery; implementation-level detail is the agents' job, drawn from the pillar Skills and the provider's documentation.
|
||||
- **Acceptance criteria:** The Deliverable requires `target-architecture.json`, checked by step 3 at submission. Its content is a readable summary with one section per Element. A Check's `statement` is written so that it can be verified from the infrastructure code alone, and the Skill says so with examples.
|
||||
|
||||
## Step 5: Completeness: the Requirements chain is a submission rule
|
||||
|
||||
- **Capability:** A Target architecture with a broken chain cannot be submitted.
|
||||
- **Rationale:** This is the rule that makes the outcome understood up front. Without it the graph is one more document.
|
||||
- **Where:** `check_submission` currently sees only the Deliverable being submitted. It needs the Deliverables it depends on: extend it and `specialist_tools` in `app/tools/execution.py` to pass them.
|
||||
- **Acceptance criteria:** Submission is refused, naming each gap, when: a requirement id is the `source` of no Check, directly or through a component's Element; a component has no Element; a selected product appears on no Element; a recommendation is the `source` of no Check. A recommendation may be marked not applicable only with a stated reason, and that is listed for the user at Approval.
|
||||
|
||||
## Step 6: Split the solution architecture Phase: design, then implementation
|
||||
|
||||
- **Capability:** The user approves the Target architecture before code is written.
|
||||
- **Where:** `PhaseId` and `DEPENDENCY_GRAPH` in `app/workflows/deliverables.py`; `agents/orchestrator.md`; `workflow.yaml` (its test will fail until updated); `app/card.py` derives from the graph; `app/presentation.py`; `eval/`; the spec's Phase table.
|
||||
- **Design:** Design holds product selection, design recommendations and the Target architecture. Implementation holds the architecture description and the deployment guidance.
|
||||
- **Acceptance criteria:** No Deliverable in implementation can start until design is approved (a Ledger test). The Approval prompt for design summarises the graph: counts of Elements, Relationships and Checks, and any recommendation marked not applicable. A pre-approved Execution passes through as today.
|
||||
|
||||
## Step 7: The diagram is rendered from the graph
|
||||
|
||||
- **Capability:** A diagram that cannot disagree with the architecture.
|
||||
- **Where:** a renderer in `app/workflows/target_architecture.py` from Elements and Relationships to Mermaid; `architecture.mmd` is added to the Target architecture's attachments by the engine on submission; the `architecture_diagram` Deliverable, `agents/diagrammer.md` and its bundle entries are removed; `app/presentation.py` reads the diagram from the Target architecture so `/generate`'s keys are unchanged.
|
||||
- **Acceptance criteria:** Rendering is deterministic and passes `mermaid_check` for any graph step 3 accepts, including names with characters Mermaid treats specially. Every Element and Relationship appears exactly once. The solution guide still carries the diagram in the template's section 4.2.
|
||||
|
||||
## Step 8: Deployment guidance implements the graph
|
||||
|
||||
- **Capability:** Code written against a known list, with each item accounted for.
|
||||
- **Where:** `deployment_guidance` depends on the Target architecture; `agents/iac-author.md`; `skills/iac-validation/SKILL.md`; a required attachment `implementation.json`: for each Check id, the file and resource address that satisfies it.
|
||||
- **Acceptance criteria:** Submission is refused when a Check id is missing from `implementation.json` or an id in it is not in the graph. The IaC author's context carries the graph, not the prose recommendations. `terraform_validate` must still pass before submission, as today.
|
||||
|
||||
## Step 9: Validation gives a verdict per Check
|
||||
|
||||
- **Capability:** A fixed bar: validation answers the graph's Checks and nothing else can fail the code.
|
||||
- **Where:** `validation_results` requires `verdicts.json` in place of `findings.json`: for each Check id, `{verdict, evidence}` with `verdict` pass, fail or not verifiable, plus a separate list `proposed_additions` of `{statement, applies_to, reason}`. `agents/validator.md`, `skills/iac-validation/SKILL.md`, `app/states/lessons.py`, `eval/scoring.py`.
|
||||
- **Acceptance criteria:** Submission is refused unless every Check has exactly one verdict with evidence. A proposed addition never counts as a failure. A `not verifiable` verdict is treated as a gap in the graph, not in the code. The dry-run result (`terraform validate`, and `plan` when permitted) is itself a Check on the deployment as a whole, so it has a verdict too.
|
||||
|
||||
## Step 10: Revision routing: the code or the graph
|
||||
|
||||
- **Capability:** Each validation outcome leads to exactly one kind of Revision.
|
||||
- **Where:** `_orchestrator_context` in `app/nodes/execution_nodes.py` gives the Orchestrator the failed Check ids and the proposed additions; `agents/orchestrator.md`.
|
||||
- **Design:** Failed Checks reopen the deployment guidance, with the failed ids as the reason. Proposed additions and `not verifiable` verdicts go to the user in an interactive Execution; in a pre-approved one the Orchestrator reopens the Target architecture only for an addition that names a requirement or recommendation id. Reopening the Target architecture returns the implementation Phase to draft and withdraws its Approval, by the Ledger's existing rule.
|
||||
- **Acceptance criteria:** Engine tests show both routes. With unchanged code and an unchanged graph, a second validation pass has the same Check ids as the first: the list cannot grow.
|
||||
|
||||
## Step 11: Evaluation: prove the loop converges
|
||||
|
||||
- **Capability:** Evidence that the outcome is understood before code is written.
|
||||
- **Where:** `eval/scoring.py`, `eval/solution_eval.py`, `eval/datasets/solution_cases.json`.
|
||||
- **Design:** New checks: every requirement reaches at least one Check with a pass verdict; no Check is left failed or not verifiable; the diagram matches the graph. The report records, per case, the number of validation passes and the Check ids failing at each.
|
||||
- **Acceptance criteria:** All benchmark cases complete and score at least 0.8. In each, the set of failing Check ids never grows from one validation pass to the next, and deployment guidance needs at most one Revision in at least two of the three cases. The thresholds left unset by iteration 4 step 8 are set from this run. The comparison with the stopped run of 2026-10-06 is written into this step's file.
|
||||
89
.agents/plans/iter-06-target-architecture-graph/MAP.md
Normal file
89
.agents/plans/iter-06-target-architecture-graph/MAP.md
Normal file
@@ -0,0 +1,89 @@
|
||||
# Plan Map
|
||||
|
||||
**Iteration:** 6, the Target architecture graph
|
||||
**Intent:** Establish the Target architecture as one explicit graph of Elements, Relationships and Checks before any infrastructure code is written, and derive and check every later Deliverable from it, so that the outcome is understood before code exists and validation has a fixed bar.
|
||||
**Status:** steps 1 to 10 built and covered by the deterministic suite; nothing has run against a real model; step 11's evaluation run is on hold by the owner
|
||||
**This directory covers:** steps 1 to 11
|
||||
|
||||
## Order of work
|
||||
|
||||
Build this iteration before the remaining steps of iteration 4 (10 to 14) and before iteration 5. It changes Deliverables, Phases and the validation format that those steps build on. The effects on them are listed at the end of this file.
|
||||
|
||||
## Sources of truth
|
||||
|
||||
- `docs/adr/0005-the-target-architecture-is-an-explicit-graph.md`: the decision, its three points to confirm, and the rejected alternatives. Status `proposed`.
|
||||
- `CONTEXT.md`: Target architecture, Element, Relationship, Check, Requirements chain. Use these words; "Dependency" stays the link between Deliverables.
|
||||
- `iter-04-learning-and-skills/steps/step-8.md`, "The evaluation run of 2026-10-06": the evidence. Three validation passes gave 4, 7, then 5 different findings on the same Terraform.
|
||||
- `docs/adr/0002-*.md`: the graph's format and how to write it are behaviour, so they live in a Skill; the engine only checks the result.
|
||||
|
||||
## The flow this iteration builds
|
||||
|
||||
```mermaid
|
||||
flowchart TD
|
||||
REQ([Workflow request]) --> R[Requirements]
|
||||
R --> D[Technical decomposition]
|
||||
D --> A1{{Approval: requirements discovery}}
|
||||
A1 --> PS[Product selection]
|
||||
PS --> DR[Design recommendations]
|
||||
R --> DR
|
||||
PS --> TA
|
||||
DR --> TA[Target architecture: Elements, Relationships, Checks]
|
||||
TA --> A2{{Approval: design}}
|
||||
A2 --> DESC[Architecture description]
|
||||
A2 --> IAC[Deployment guidance]
|
||||
TA -.rendered by code.-> DIA[Architecture diagram]
|
||||
IAC --> A3{{Approval: implementation}}
|
||||
DESC --> A3
|
||||
A3 --> VAL[Validation: a verdict per Check]
|
||||
VAL -->|a Check fails| IAC
|
||||
VAL -->|the graph is missing something| TA
|
||||
VAL -->|every Check passes| A4{{Approval: validation}}
|
||||
A4 --> G[Solution guide]
|
||||
G --> A5{{Approval: packaging}}
|
||||
```
|
||||
|
||||
## Status
|
||||
|
||||
| Step | What | Size | Status |
|
||||
|---|---|---|---|
|
||||
| 1 | Accept ADR-0005 | S | complete: accepted 2026-10-07 |
|
||||
| 2 | Identify requirements, components and recommendations by id | M | complete |
|
||||
| 3 | The graph: format, parsing and structural rules | M | complete |
|
||||
| 4 | The Target architecture Deliverable, its Specialist and its Skill | M | complete; unproven with a real model |
|
||||
| 5 | Completeness: the Requirements chain is a submission rule | M | complete |
|
||||
| 6 | Split the solution architecture Phase: design, then implementation | M | complete |
|
||||
| 7 | The diagram is rendered from the graph | S | complete |
|
||||
| 8 | Deployment guidance implements the graph | M | complete |
|
||||
| 9 | Validation gives a verdict per Check | M | complete |
|
||||
| 10 | Revision routing: the code or the graph | S | complete; routing unproven with a real model |
|
||||
| 11 | Evaluation: prove the loop converges | M | checks built; evaluation run outstanding (on hold by the owner) |
|
||||
|
||||
Size: S under a day, M a few days.
|
||||
|
||||
## Dependency graph
|
||||
|
||||
- Step 1: no dependencies
|
||||
- Step 2: depends on step 1
|
||||
- Step 3: depends on step 1
|
||||
- Step 4: depends on step 3
|
||||
- Step 5: depends on step 2, step 4
|
||||
- Step 6: depends on step 4
|
||||
- Step 7: depends on step 4
|
||||
- Step 8: depends on step 5
|
||||
- Step 9: depends on step 8
|
||||
- Step 10: depends on step 6, step 9
|
||||
- Step 11: depends on step 7, step 10
|
||||
|
||||
Steps 2 and 3 can be built side by side, as can 6 and 7.
|
||||
|
||||
## Effects on other iterations
|
||||
|
||||
- **Iteration 4 step 1** (`findings.json`): replaced by the verdicts of step 9 here. The free-form finding list goes.
|
||||
- **Iteration 4 step 4** (contracts): the diagram's contract goes with the diagrammer; the decomposition's component table becomes data in step 2 here.
|
||||
- **Iteration 4 step 6** (Orchestrator step order): rewritten by step 10 here.
|
||||
- **Iteration 4 step 7** (lesson candidates): `finding` candidates become failed Checks and proposed additions.
|
||||
- **Iteration 4 step 8** (evaluation): `no_blocking_findings` is rewritten against verdicts; the unset thresholds are set by step 11 here.
|
||||
- **Iteration 4 step 11** (IaC patterns Skill): its patterns should be keyed by the product of an Element.
|
||||
- **Iteration 4 step 13** (trim Specialist context): mostly achieved here, since later Specialists work from the graph. Re-scope it after step 11.
|
||||
- **Iteration 5 step 5** (finding-to-Deliverable routing): no longer needed; a failed Check already names what it applies to.
|
||||
- **Iteration 5 step 4** (semantic checks at submission): can judge whether each Check is verifiable as written.
|
||||
@@ -0,0 +1,14 @@
|
||||
# Step 1 — Implementation Detail
|
||||
|
||||
ADR-0005 was accepted by the owner on 2026-10-07 ("lets move forward with this", after reviewing the proposed case structure), with its three points as written:
|
||||
|
||||
1. The user approves the Target architecture before code is written; the solution architecture Phase is split, making five Phases.
|
||||
2. A new Specialist produces the Target architecture.
|
||||
3. Code renders the diagram from the graph; the diagrammer role is removed.
|
||||
|
||||
ADR-0006 (Change requests) was accepted in the same reply; it is built in iteration 7.
|
||||
|
||||
Clarifications the owner gave before accepting, now in the ADR and the role files:
|
||||
|
||||
- The graph is the Target architecture itself, not a build plan beside it.
|
||||
- The user states Intent at a high level in the Workflow request. The agents derive every Element, Relationship and Check from the architecture framework and best practice; the user never writes the graph.
|
||||
@@ -0,0 +1,12 @@
|
||||
# Step 10 — Implementation Detail
|
||||
|
||||
1. The Orchestrator's context carries `validation`: the outcome of the submitted validation, or null before there is one.
|
||||
2. `agents/orchestrator.md` step 3, "Validation decided", routes on it:
|
||||
- failed Checks, or a failed dry-run: reopen the deployment guidance with each failed Check's id and evidence.
|
||||
- otherwise, not-verifiable Checks or proposed additions: the Target architecture has a gap. Interactive: ask the user whether to revise it. Pre-approved: reopen it only for items whose reason names a requirement or recommendation id.
|
||||
|
||||
The routing is the Orchestrator's choice, as ADR-0003 requires; the engine supplies the facts and the Ledger enforces what a reopen does.
|
||||
|
||||
On "the list cannot grow": the verdict list is fixed by the graph, because every verdict must be on a Check and every Check must have one. With an unchanged graph, two validation passes cover the same ids by construction (`test_validation_gives_exactly_one_verdict_per_check`).
|
||||
|
||||
Not verified: whether a real Orchestrator model follows the new routing. `test_the_orchestrator_is_told_what_validation_decided` covers the context and the Revision, with the reopen scripted.
|
||||
@@ -0,0 +1,58 @@
|
||||
# Step 11 — Implementation Detail
|
||||
|
||||
Partly done. The checks are built; the evaluation run that this step exists for has not been made.
|
||||
|
||||
Built in `eval/scoring.py`:
|
||||
|
||||
- `requirements_chain_complete`: the delivered data files form a chain with no gap.
|
||||
- `every_check_passes`: validation ended with no Check failed or not verifiable, and the dry-run not failed.
|
||||
- `diagram_matches_graph`: the delivered diagram is exactly the rendering of the delivered graph.
|
||||
|
||||
These replaced `components_trace_to_requirements` and `no_blocking_findings` from iteration 4 step 8.
|
||||
|
||||
Outstanding, and why:
|
||||
|
||||
- **No evaluation run.** The owner stopped the last run on 2026-10-06 and asked that no further cases start until they advise. Nothing in this iteration has run against a real model.
|
||||
- **The acceptance criteria are therefore unmet:** all cases scoring at least 0.8, the failing-Check set never growing between passes, and at most one Revision of the deployment guidance in two of three cases.
|
||||
- **Not built:** the per-case record of validation passes and the Check ids failing at each. The evaluation reads only the final verdicts today.
|
||||
- **Thresholds** from iteration 4 step 8 are still unset.
|
||||
|
||||
Do not mark this step complete until a run meets the criteria. (`legacy-baseline` was removed on 2026-10-07 on the owner's instruction, ahead of this.)
|
||||
|
||||
## Evaluation run of 2026-10-07, case 01 (commit `e924682`)
|
||||
|
||||
Report: `eval/results/20261007T125917Z/report.json`. Result: `completed_with_warnings`, score 73% (8 of 11 checks), 3,627 seconds, 4.25 million tokens, 144 model requests. No solution guide was written.
|
||||
|
||||
| | Stopped run, 2026-10-06 | This run |
|
||||
|---|---|---|
|
||||
| First pass to a validation | about 17 minutes | 25 minutes |
|
||||
| Validation passes | 3 | 2 |
|
||||
| Failing items per pass | 4, then 7, then 5 findings | 0 failed Checks and 7 proposed additions, then 1 failed Check, 1 not verifiable and 1 proposed addition |
|
||||
| Revisions | deployment guidance × 3 | Target architecture × 1, deployment guidance × 3 |
|
||||
| Outcome | stopped at 35 minutes | ended with warnings at 60 minutes |
|
||||
|
||||
What held:
|
||||
|
||||
- Every chain link was accepted on a first attempt except the Target architecture, which was refused once per attempt (7 requirements with no Check; then 4 Elements with no Check) and fixed inside its own run.
|
||||
- `requirements_chain_complete` and `diagram_matches_graph` passed.
|
||||
- The Terraform met every Check on its first attempt (0 failed of the first graph's Checks).
|
||||
- The Orchestrator followed the new routing: additions reopened the Target architecture; a failed Check reopened the code.
|
||||
- After one revision of the graph the validator proposed 1 addition, down from 7.
|
||||
|
||||
What failed, in order of cause:
|
||||
|
||||
1. **A bug in this iteration (fixed after the run, with a test).** Once the deployment guidance was reopened, the Orchestrator's context still carried the old validation's verdicts. It reopened the code for K-30 three times in a row without a validation in between, reaching the Revision limit. `_orchestrator_context` now shows a validation only while the validation results stand as submitted.
|
||||
2. **A Check that cannot be implemented had nowhere to go.** K-30 required `startup_cpu_boost` on a Cloud Run job. Terraform rejects that argument there, so the IaC author could not satisfy it, and the validator marked it failed, which sends it back to the code. The fault was in the graph. The IaC author used 57 requests and 2.35 million tokens, 55% of the run.
|
||||
3. **The target architect put a recommendation on an Element it does not apply to.** K-30 came from DR-19, proposed by the validator in pass 1 for two services and applied to the job as well.
|
||||
4. **Model timeouts.** The target architect's model request timed out at 180 seconds in both attempts; each cost about 3 minutes.
|
||||
|
||||
Not yet exercised: the second pass also had a Check marked not verifiable (K-55) and a proposed addition (NFR-15). The failed-Check route took precedence, as instructed, so the gap route was not taken a second time.
|
||||
|
||||
Acceptance criteria: not met. The case did not complete or reach 0.8.
|
||||
|
||||
Changes this points to, not yet made:
|
||||
|
||||
- Let the IaC author report a Check it cannot implement, with the tool's error as evidence, so that it is routed to the Target architecture and not retried as code.
|
||||
- Have the validator distinguish "the code does not do this" from "this cannot be done to this resource".
|
||||
- Check a proposed addition against the Element it names before it becomes a Check.
|
||||
- Raise or tune the model timeout for the target architect.
|
||||
@@ -0,0 +1,17 @@
|
||||
# Step 2 — Implementation Detail
|
||||
|
||||
1. `app/workflows/chain.py` defines the data files and a checker for each. Each checker returns one entry per fault, so a Specialist can fix and resubmit.
|
||||
2. New required attachments (`DATA_CHECKS` in `app/workflows/deliverables.py`):
|
||||
- `requirements.json` on requirements: `{id, kind, text}`, kind functional or non_functional, ids unique.
|
||||
- `components.json` on the technical decomposition: `{id, name, requirements}`. This replaced the component table contract from iteration 4 step 4.
|
||||
- `products.json` on product selection: `{component, product}`, one for every component.
|
||||
- `recommendations.json` on design recommendations: `{id, pillar, text, components}`.
|
||||
3. `check_submission` takes the Deliverables being built on (`upstream`), so links are checked across Deliverables: a component may only serve a real requirement, a product may only be selected for a real component, a recommendation may only name real components.
|
||||
4. The formats live in a new Skill, `skills/requirements-chain/SKILL.md`, assigned in `providers/gcp.yaml` to every role that writes or reads one.
|
||||
|
||||
Changed from the plan:
|
||||
|
||||
- `products.json` was added. The plan's rule "a selected product appears on no Element" needs the selection as data.
|
||||
- Only functional requirements must be served by a component at the decomposition. A non-functional requirement often constrains the whole workload, so it is held to a stricter rule later: it must be the source of a Check (step 5).
|
||||
|
||||
Tests: `tests/execution/test_requirements_chain.py`, "the links before the graph".
|
||||
@@ -0,0 +1,8 @@
|
||||
# Step 3 — Implementation Detail
|
||||
|
||||
1. `app/workflows/target_architecture.py`, pure and without I/O: `Element`, `Relationship`, `Check`, `NotApplicable`, `TargetArchitecture`, and `parse_graph`, which returns the graph or raises `GraphError` listing every fault.
|
||||
2. The file is `target-architecture.json` with `elements`, `relationships`, `checks` and optional `not_applicable`.
|
||||
3. Refused, with the id named: a repeated id; a Relationship whose `from` or `to` is not an Element; a Check that applies to nothing in the graph; an Element with no Check; a missing or empty field.
|
||||
4. An Element's `component` is optional, for supporting Elements such as identities, keys and networks.
|
||||
|
||||
Tests: `tests/execution/test_requirements_chain.py`, "the graph is well-formed".
|
||||
@@ -0,0 +1,8 @@
|
||||
# Step 4 — Implementation Detail
|
||||
|
||||
1. `DeliverableKind.TARGET_ARCHITECTURE`, in the design Phase, depending on product selection and design recommendations. Its content needs `Elements`, `Relationships` and `Checks` sections; its attachment is the graph.
|
||||
2. Role file `agents/target-architect.md`. In the bundle it loads the solution-architecture and requirements-chain Skills, reaches the documentation MCP server, and runs on the Pro model tier.
|
||||
3. `skills/requirements-chain/SKILL.md` gives the graph's format and how to write a Check that can be verified from code, with verifiable and non-verifiable examples.
|
||||
4. The role file states that implementation detail is the agent's job and the user stays at the level of Intent.
|
||||
|
||||
Not verified: no real model has produced a Target architecture yet. Whether one can write Checks specific enough to verify, in one run and inside its tool budget, is the main risk of this iteration and is what step 11 measures.
|
||||
@@ -0,0 +1,18 @@
|
||||
# Step 5 — Implementation Detail
|
||||
|
||||
`chain_gaps` in `app/workflows/target_architecture.py` lists every place the Requirements chain stops; `check_target_architecture` runs it at submission, so a Target architecture with a gap is refused with each gap named.
|
||||
|
||||
A gap is:
|
||||
|
||||
- a component with no Element;
|
||||
- a non-functional requirement that is the source of no Check;
|
||||
- a functional requirement that is the source of no Check and is served by no component with an Element;
|
||||
- a selected product that does not appear on its component's Element;
|
||||
- a recommendation that is the source of no Check and is not listed under `not_applicable` with a reason;
|
||||
- a Check whose `source` is not a requirement or recommendation, or an Element that realises something that is not a component.
|
||||
|
||||
Recommendations marked not applicable are carried in the graph's summary and shown to the user at the design Approval.
|
||||
|
||||
The rule checks that each link exists, not that it is right. A vague Check passes here and is caught later as `not_verifiable`, or by the user at Approval.
|
||||
|
||||
Tests: `tests/execution/test_requirements_chain.py`, "the Requirements chain has no gap", including one through `submit_deliverable`.
|
||||
@@ -0,0 +1,10 @@
|
||||
# Step 6 — Implementation Detail
|
||||
|
||||
1. `PhaseId` has five members. `solution_architecture` is now the design Phase (product selection, design recommendations, Target architecture). The new `solution_implementation` holds the architecture description and the deployment guidance. The id `solution_architecture` was kept so recorded Executions and callers do not break.
|
||||
2. The Ledger's existing rule does the gating: a Dependency across Phases is met only on Approval, so nothing in implementation is ready until design is approved.
|
||||
3. The design Approval carries a summary of the graph (counts of Elements, Relationships and Checks, and recommendations treated as not applicable). `describe_prompt` in `app/presentation.py` states that no code is written until it is approved.
|
||||
4. `workflow.yaml` lists the five Phases; its test checks it against the dependency graph. The A2A card derives from the graph and needed no change.
|
||||
|
||||
Revision behaviour that follows: reopening the deployment guidance withdraws the implementation and validation Approvals and leaves the design approved; reopening the Target architecture withdraws design, implementation and validation, and the code cannot restart until the design is approved again.
|
||||
|
||||
Tests: `tests/execution/test_ledger.py`, `test_the_user_approves_the_graph_before_any_code_is_written` in `tests/execution/test_requirements_chain.py`, `tests/execution/test_presentation.py`.
|
||||
@@ -0,0 +1,10 @@
|
||||
# Step 7 — Implementation Detail
|
||||
|
||||
1. `render_mermaid` draws a left-to-right flowchart with every Element (name and product) and every Relationship (its kind) exactly once. Node ids are generated, and characters Mermaid reserves are stripped from labels, so any graph step 3 accepts renders.
|
||||
2. `submit_deliverable` adds `architecture.mmd` to the Target architecture's attachments when it accepts the submission. No Specialist draws it.
|
||||
3. Removed: the `architecture_diagram` Deliverable, `agents/diagrammer.md` and its bundle entries.
|
||||
4. `/generate` keeps its `mermaid_diagram` key, now read from the Target architecture. The packager is told to embed that attachment unchanged.
|
||||
|
||||
The local `mermaid_check` tool stays in the bundle; the evaluation still uses it.
|
||||
|
||||
Tests: `tests/execution/test_requirements_chain.py`, "the diagram is a view of the graph".
|
||||
@@ -0,0 +1,9 @@
|
||||
# Step 8 — Implementation Detail
|
||||
|
||||
1. The deployment guidance depends on the Target architecture and requires `implementation.json`: for each Check, the attached file and resource address that satisfies it.
|
||||
2. Refused: a Check not accounted for, an id that is not a Check, an entry naming a file that is not attached.
|
||||
3. `agents/iac-author.md` now says to implement the Target architecture and nothing it does not ask for, and on a Revision to change only what the failed Checks need.
|
||||
|
||||
Changed from the plan: the IaC author's context still carries every earlier Deliverable in full, prose recommendations included, because `inputs_of` is unchanged. Narrowing it to the graph is iteration 4 step 13.
|
||||
|
||||
Tests: `test_deployment_guidance_must_account_for_every_check`.
|
||||
@@ -0,0 +1,12 @@
|
||||
# Step 9 — Implementation Detail
|
||||
|
||||
1. The validation results require `verdicts.json` in place of `findings.json`: a `dry_run` result, one verdict per Check (`pass`, `fail` or `not_verifiable`) with evidence, and a separate list of `proposed_additions`.
|
||||
2. Refused: a Check with no verdict, a Check with two, a verdict on something that is not a Check, a verdict without evidence, a missing dry-run result.
|
||||
3. A proposed addition is never a failure. This is the rule that stops validation findings growing between passes: the validator cannot add to what the code is judged against.
|
||||
4. `validation_outcome` in `app/workflows/chain.py` separates faults in the code (failed Checks) from gaps in the graph (not verifiable, proposed additions). Lesson candidates and the evaluation use it.
|
||||
|
||||
Changed from the plan: the dry-run is its own `dry_run` entry, not a Check in the graph, so the Target architecture stays free of tooling concerns.
|
||||
|
||||
`check_findings` and `FINDINGS_ATTACHMENT` from iteration 4 step 1 are gone. Lesson candidate types are now `failed_check`, `unverifiable_check` and `proposed_addition`.
|
||||
|
||||
Tests: `tests/execution/test_requirements_chain.py`, "code and validation answer the graph"; `tests/execution/test_lessons.py`.
|
||||
60
.agents/plans/iter-07-change-requests/DETAIL.md
Normal file
60
.agents/plans/iter-07-change-requests/DETAIL.md
Normal file
@@ -0,0 +1,60 @@
|
||||
# Plan Detail
|
||||
|
||||
Every step is built test-first with the fake runtime and ends with `pytest`, `ruff check .` and `mypy .` passing.
|
||||
|
||||
## Step 1: Accept ADR-0006 and update the glossary
|
||||
|
||||
- **Capability:** A recorded decision, and vocabulary that no longer contradicts it.
|
||||
- **The four points the owner confirms:** a Change request is a new Execution and never modifies its Baseline; the Baseline is a completed Execution of the same Customer case; the output is complete, not a patch; a Change request may itself be a Baseline.
|
||||
- **Where:** `docs/adr/0006-*.md` status; `CONTEXT.md` entries for Execution, Session and Customer case, plus new entries **Change request** and **Baseline**; the sentence "An Execution starts clean" in `docs/adr/0004-*.md`.
|
||||
- **Acceptance criteria:** The ADR is `accepted` or amended with this plan updated to match. No glossary entry says an Execution can never start from another.
|
||||
|
||||
## Step 2: Start an Execution against a Baseline
|
||||
|
||||
- **Capability:** A caller names a Baseline and the new Execution begins with its Deliverables.
|
||||
- **Where:** `ExecutionEngine.start(baseline=...)` in `app/agent.py`; `/generate` body and A2A message metadata (`app/main.py`, `app/a2a_server.py`); `app/states/execution_state.py` (a `baseline` entry holding the Baseline's id and Deliverables); `execution.json` records the Baseline; `intent/history.json` records it on the new statement, so the history shows the line of versions.
|
||||
- **Design:** The Baseline is loaded from its files under the Customer case, through `execution.json`, so it works across restarts and does not need the Baseline's checkpoint.
|
||||
- **Acceptance criteria:** Start is refused, before anything runs, when the Baseline does not exist, is not completed, or belongs to another Customer case. An Execution started without a Baseline behaves exactly as today. The Baseline's files are byte-identical after the Change request completes.
|
||||
|
||||
## Step 3: Requirements revised with a change record
|
||||
|
||||
- **Capability:** The user's high-level statement of change becomes a precise change to the requirements.
|
||||
- **Where:** `agents/requirements-analyst.md`; the requirements contract in `app/workflows/deliverables.py`; `agents/partials/specialist-protocol.md` (a `baseline` entry in the context).
|
||||
- **Design:** `requirements.json` keeps the id of every requirement that still holds and gives each requirement a `change` of unchanged, added, changed or removed, with the reason. New requirements take new ids; an id is never reused.
|
||||
- **Acceptance criteria:** Submission is refused when a Baseline requirement is missing from the revised list without being marked removed, or when a changed requirement has no reason. In an interactive Execution the analyst confirms the change record with the user before submitting.
|
||||
|
||||
## Step 4: Later Specialists revise from the Baseline
|
||||
|
||||
- **Capability:** Each Deliverable changes only where the changed requirements reach.
|
||||
- **Where:** `_specialist_input` in `app/nodes/execution_nodes.py` (each Specialist receives the Baseline's version of its own Deliverable and the ids that changed upstream); every Specialist role file; the Target architecture Skill from iteration 6 step 4; `app/workflows/target_architecture.py` (a function that compares two graphs).
|
||||
- **Design:** Ids are stable across versions: an Element, Relationship or Check that is unchanged keeps its id and its text. The engine computes what is reached by walking the Requirements chain from each changed requirement.
|
||||
- **Acceptance criteria:** A test with the fake runtime shows that an Element or Check not reached by any changed requirement is identical to the Baseline's, and one that differs without being reached is reported in the change summary as an unrequested change. Validation still gives a verdict for every Check.
|
||||
|
||||
## Step 5: Approvals show the change
|
||||
|
||||
- **Capability:** The user approves what changed, not the whole architecture again.
|
||||
- **Where:** `request_approval` in `app/tools/execution.py`, `app/presentation.py`, `agents/orchestrator.md`.
|
||||
- **Acceptance criteria:** In a Change request, each Approval prompt lists what was added, changed and removed against the Baseline for that Phase's Deliverables, computed by the engine from the ids, not written by the Orchestrator.
|
||||
|
||||
## Step 6: Change summary and version line in the case
|
||||
|
||||
- **Capability:** A reader of a Customer case can see each version and what moved between them.
|
||||
- **Where:** `_write_outputs` in `app/nodes/execution_nodes.py`; the packager role file.
|
||||
- **Design:** Each Change request writes `changes.json` (requirements, Elements, Relationships and Checks added, changed and removed, each with its reason) and a readable summary in the solution guide. `intent/history.json` lists each statement with its Baseline.
|
||||
- **Acceptance criteria:** The full Deliverables are written as for any Execution. `changes.json` matches a comparison of the two Executions' data files. Unrequested changes are listed separately from requested ones.
|
||||
|
||||
## Step 7: Evaluation: a change case
|
||||
|
||||
- **Capability:** Evidence that a change stays contained.
|
||||
- **Where:** `eval/datasets/solution_cases.json`, `eval/solution_eval.py`, `eval/scoring.py`.
|
||||
- **Design:** A case that runs a base request and then a Change request against it, for example retention moving from 30 days to 7 years.
|
||||
- **Acceptance criteria:** The change case scores at least 0.8. New checks pass: every changed requirement reaches a changed or new Check; nothing outside its reach changed without being reported; the Change request used fewer tokens than its Baseline.
|
||||
|
||||
## Step 8: Remove the `legacy-baseline` case
|
||||
|
||||
- **Capability:** `deliverables/` holds only what the current engine produced.
|
||||
- **Rationale:** `deliverables/cases/legacy-baseline/` is the output of the deleted iteration 1 pipeline: 68 Executions (62 of them from its tests and old benchmark) and its last shared copies in `as-is/`, `target/`, `validation/` and `guides/`. The owner chose on 2026-10-06 to keep it until this work is complete with the expected outcome, and to remove it then.
|
||||
- **Gate:** Do this only when iteration 6 step 11 and step 7 here have both met their acceptance criteria. If either falls short, leave the case in place and say so.
|
||||
- **Where:** `deliverables/cases/legacy-baseline/`; `scripts/validate_artifacts.py`, `tests/test_artifacts.py` and `tests/test_package.py`, which read its `as-is/`, `target/`, `validation/` and `guides/` folders and must be removed or pointed at a current Execution; `scripts/validate.sh`; `VALIDATION.md` step 1; the root `terraform/`, `docs/requirements.md`, `docs/architecture.md`, `docs/source-architecture.md` and `requirements.yaml`, which are the same pipeline's samples.
|
||||
- **Guardrail:** Commit first, then delete in a commit of its own, so the removal can be reverted.
|
||||
- **Acceptance criteria:** The case and the samples are gone, nothing in `scripts/` or `tests/` refers to them, and `pytest`, `ruff check .` and `mypy .` pass.
|
||||
37
.agents/plans/iter-07-change-requests/MAP.md
Normal file
37
.agents/plans/iter-07-change-requests/MAP.md
Normal file
@@ -0,0 +1,37 @@
|
||||
# Plan Map
|
||||
|
||||
**Iteration:** 7, Change requests
|
||||
**Intent:** Let a user restate a request to say how their requirements have changed, at a high level, and receive the delivered architecture updated from where it stood, with an account of what changed and why.
|
||||
**Status:** planned. ADR-0006 was accepted on 2026-10-07 and the glossary updated (step 1). Build after iteration 6 step 11 has a passing evaluation run
|
||||
**This directory covers:** steps 1 to 8
|
||||
|
||||
## Sources of truth
|
||||
|
||||
- `docs/adr/0006-a-change-request-starts-from-a-baseline-execution.md`: the decision and its four points to confirm. Status `proposed`.
|
||||
- `docs/adr/0005-the-target-architecture-is-an-explicit-graph.md` and `../iter-06-target-architecture-graph/`: the ids along the Requirements chain that a change is traced through. Build iteration 6 first.
|
||||
- `CONTEXT.md`: today it says an Execution starts clean and a Customer case never feeds one Execution into another. Step 1 changes those entries; until then they stand.
|
||||
- `iter-04-learning-and-skills/steps/step-15.md`: the Customer case layout, `execution.json` and the Intent history (`intent/history.json`) that a Baseline is found through. A Change request is the next statement in that history.
|
||||
|
||||
## Status
|
||||
|
||||
| Step | What | Size | Status |
|
||||
|---|---|---|---|
|
||||
| 1 | Accept ADR-0006 and update the glossary | S | complete: accepted 2026-10-07 |
|
||||
| 2 | Start an Execution against a Baseline | M | planned |
|
||||
| 3 | Requirements revised with a change record | M | planned |
|
||||
| 4 | Later Specialists revise from the Baseline | M | planned |
|
||||
| 5 | Approvals show the change | S | planned |
|
||||
| 6 | Change summary and version line in the case | S | planned |
|
||||
| 7 | Evaluation: a change case | M | planned |
|
||||
| 8 | Remove the `legacy-baseline` case | S | complete: removed early on the owner's instruction, 2026-10-07 |
|
||||
|
||||
## Dependency graph
|
||||
|
||||
- Step 1: no dependencies
|
||||
- Step 2: depends on step 1, iteration 4 step 15
|
||||
- Step 3: depends on step 2, iteration 6 step 2
|
||||
- Step 4: depends on step 3, iteration 6 steps 4 and 8
|
||||
- Step 5: depends on step 4, iteration 6 step 6
|
||||
- Step 6: depends on step 4
|
||||
- Step 7: depends on step 5, step 6, iteration 6 step 11
|
||||
- Step 8: no longer gated; done on 2026-10-07
|
||||
13
.agents/plans/iter-07-change-requests/steps/step-8.md
Normal file
13
.agents/plans/iter-07-change-requests/steps/step-8.md
Normal file
@@ -0,0 +1,13 @@
|
||||
# Step 8 — Implementation Detail
|
||||
|
||||
Done early, on the owner's instruction of 2026-10-07 ("please remove legacy-baseline"). That instruction replaced the gate in `DETAIL.md`, which had held removal until iterations 6 and 7 met their acceptance criteria. Neither has: no evaluation run has been made on iteration 6, and iteration 7 is not built.
|
||||
|
||||
1. Deleted `deliverables/cases/legacy-baseline/`: the 68 old Executions, their `intent/` history, and the shared `as-is/`, `target/`, `validation/` and `guides/` folders. `deliverables/cases/` is now empty until an Execution completes.
|
||||
2. Deleted `scripts/validate_artifacts.py` and `tests/test_artifacts.py`, which only checked that case's samples. `tests/test_package.py` keeps its one test of `terraform/terraform.tfvars.example`.
|
||||
3. Removed the artefact-validation step from `README.md` and `VALIDATION.md`.
|
||||
|
||||
Five of the Execution folders were owned by a rootless-podman user id (110000), left by a container run on 2026-09-02 with the folder mounted. They were removed with `podman unshare rm`.
|
||||
|
||||
Not committed first, against the guardrail in `DETAIL.md`: the owner did not ask for a commit. The tracked files are recoverable from commit `7ee49ab` at their earlier paths (`deliverables/as-is/`, `deliverables/target/`, `deliverables/validation/`, `deliverables/guides/`, `deliverables/executions/`, `scripts/validate_artifacts.py`, `tests/test_artifacts.py`). The generated `intent/` files for that case were never committed and are gone.
|
||||
|
||||
Left in place, because the instruction named only `legacy-baseline`: the same pipeline's other samples, `terraform/` at the repository root, `docs/requirements.md`, `docs/architecture.md`, `docs/source-architecture.md`, `docs/validation-evidence.md`, `docs/validation-results.json`, `docs/publication-verification.md`, `requirements.yaml`, and `scripts/validate.sh`, which runs Terraform checks on that root `terraform/`.
|
||||
12
.dockerignore
Normal file
12
.dockerignore
Normal file
@@ -0,0 +1,12 @@
|
||||
# Keep the build context to what the image copies.
|
||||
.git
|
||||
.venv
|
||||
.cache
|
||||
.agents
|
||||
.scratch
|
||||
**/__pycache__
|
||||
*.db
|
||||
.env
|
||||
eval/results
|
||||
deliverables/cases
|
||||
lessons/candidates
|
||||
75
.env.example
75
.env.example
@@ -1,26 +1,63 @@
|
||||
# GCP Solution Architecture Agent Environment Variables
|
||||
|
||||
# Agent Identity & Server Config
|
||||
# Agent Identity
|
||||
AGENT_NAME=gcp_solution_architecture_agent
|
||||
AGENT_VERSION=1.0.0
|
||||
LOG_LEVEL=INFO
|
||||
HOST=0.0.0.0
|
||||
PORT=8080
|
||||
|
||||
# LLM Provider Configuration (OpenAI or Azure OpenAI)
|
||||
OPENAI_API_KEY=your-openai-api-key-here
|
||||
AZURE_OPENAI_API_KEY=your-azure-openai-api-key-here
|
||||
AZURE_OPENAI_ENDPOINT=https://your-resource.openai.azure.com/
|
||||
AZURE_OPENAI_DEPLOYMENT=gpt-4o
|
||||
AZURE_OPENAI_API_VERSION=2024-02-15-preview
|
||||
LLM_TEMPERATURE=0.2
|
||||
# A2A server (python -m app.main). The container image sets A2A_PORT=8080.
|
||||
A2A_HOST=0.0.0.0
|
||||
A2A_PORT=8000
|
||||
# A2A_PUBLIC_URL=https://agents.example.com/solution-architect
|
||||
|
||||
# Google Cloud Project & Scanner Credentials
|
||||
GOOGLE_APPLICATION_CREDENTIALS=/app/credentials/gcp-key.json
|
||||
GCP_PROJECT_ID=your-gcp-project-id
|
||||
GCP_REGION=us-central1
|
||||
# Models (providers/<name>.yaml): gemini/<model> uses ADK's native Gemini client.
|
||||
# Vertex AI with Application Default Credentials:
|
||||
# GOOGLE_GENAI_USE_VERTEXAI=true
|
||||
# GOOGLE_CLOUD_PROJECT=your-project-id
|
||||
# GOOGLE_CLOUD_LOCATION=global
|
||||
# GOOGLE_APPLICATION_CREDENTIALS=/app/credentials/adc.json
|
||||
# Or the Gemini API: GOOGLE_API_KEY=...
|
||||
MODEL_TIMEOUT_SECONDS=180
|
||||
|
||||
# PostgreSQL Database & State Storage
|
||||
# Cloud Provider Bundle (providers/<name>.yaml) & Remote MCP Servers
|
||||
CLOUD_PROVIDER=gcp
|
||||
MCP_ENABLED=true
|
||||
MCP_ENABLE_PREVIEW=true
|
||||
# MCP_QUOTA_PROJECT=your-project-id # defaults to the Application Default Credentials project
|
||||
MCP_TIMEOUT_SECONDS=30
|
||||
|
||||
# Local Terraform tools (fmt, validate, plan; never apply)
|
||||
TERRAFORM_BINARY=terraform
|
||||
TERRAFORM_TIMEOUT_SECONDS=300
|
||||
# Terraform providers are cached here so each check does not download them again.
|
||||
# Relative to the repository root; set it empty to disable.
|
||||
TF_PLUGIN_CACHE_DIR=.cache/terraform-plugins
|
||||
|
||||
# Hierarchical Execution Engine
|
||||
ORCHESTRATOR=router # router | model
|
||||
ORCHESTRATOR_BUDGET=40
|
||||
SPECIALIST_BUDGET=15
|
||||
MAX_REVISIONS=3
|
||||
MAX_ORCHESTRATOR_TURNS=100
|
||||
MAX_PARALLEL_SPECIALISTS=4
|
||||
CHECKPOINTER=sqlite
|
||||
CHECKPOINT_DB_PATH=checkpoints.db
|
||||
|
||||
# Jev decision service, through the TypeSafe AI Python SDK (typesafe-sdk).
|
||||
# Leave the key unset to run without it: every decision then takes its fallback.
|
||||
# TYPESAFE_API_KEY=
|
||||
# TYPESAFE_BASE_URL= # defaults to the SDK's endpoint
|
||||
# TYPESAFE_DEFAULT_MODEL= # defaults to the SDK's model
|
||||
JEV_TIMEOUT_SECONDS=5
|
||||
JEV_REQUESTS_PER_SECOND=5
|
||||
JEV_MAX_IN_FLIGHT=8
|
||||
JEV_BUDGET_CALLS=500
|
||||
JEV_BUDGET_TOKENS=1000000
|
||||
JEV_ACT_THRESHOLD=0.75
|
||||
JEV_CLOSE_THRESHOLD=0.15
|
||||
JEV_CONFIDENCE_THRESHOLD=0.6
|
||||
|
||||
# PostgreSQL (Execution records, and checkpoints when CHECKPOINTER=postgres)
|
||||
POSTGRES_HOST=localhost
|
||||
POSTGRES_PORT=5432
|
||||
POSTGRES_DB=gcp_agent_db
|
||||
@@ -28,11 +65,3 @@ POSTGRES_USER=postgres
|
||||
POSTGRES_PASSWORD=postgres
|
||||
# DATABASE_URL=postgresql://postgres:postgres@localhost:5432/gcp_agent_db
|
||||
SQLITE_FALLBACK_DB=gcp_agent_local.db
|
||||
|
||||
# Google ADK Multi-Agent Settings
|
||||
ADK_MAX_LOOP_ITERATIONS=5
|
||||
ADK_ENABLE_ARTIFACT_STORE=true
|
||||
|
||||
# Google Developer Knowledge MCP Integration
|
||||
DEVELOPER_KNOWLEDGE_MCP_URL=https://developerknowledge.googleapis.com/mcp
|
||||
DEVELOPER_KNOWLEDGE_MCP_ENABLED=true
|
||||
|
||||
12
.gitignore
vendored
12
.gitignore
vendored
@@ -6,13 +6,11 @@
|
||||
*.db
|
||||
gcp_agent_local.db
|
||||
|
||||
# Python & pytest caches
|
||||
# Python bytecode and tool caches (pytest, mypy and ruff write to .cache/)
|
||||
__pycache__/
|
||||
*.pyc
|
||||
*.pyo
|
||||
.pytest_cache/
|
||||
.mypy_cache/
|
||||
.ruff_cache/
|
||||
.cache/
|
||||
|
||||
# Virtual Environments
|
||||
.venv/
|
||||
@@ -28,3 +26,9 @@ tfplan
|
||||
# Container logs & temp files
|
||||
*.log
|
||||
.DS_Store
|
||||
|
||||
# Evaluation run outputs
|
||||
eval/results/
|
||||
|
||||
# Lesson candidates captured from Executions (may quote user feedback)
|
||||
lessons/candidates/
|
||||
|
||||
361
.scratch/phase-pipeline/spec.md
Normal file
361
.scratch/phase-pipeline/spec.md
Normal file
@@ -0,0 +1,361 @@
|
||||
# Spec: Phase pipeline
|
||||
|
||||
Status: superseded by [`.scratch/solution-architect-agent/spec.md`](../solution-architect-agent/spec.md). Don't implement. This file remains the decision log (D1 to D46), and its still-valid cleanup items moved to increment 9 of the new spec.
|
||||
|
||||
Collapse the three orchestrations of the five Phases into one deep **Phase pipeline** module on LangGraph, with a single phase table as the source of truth.
|
||||
|
||||
- Origin: architecture review candidate 01 (2026-09-15), settled through a grilling session.
|
||||
- Glossary: [`CONTEXT.md`](../../CONTEXT.md). Decision records: [ADR-0001](../../docs/adr/0001-langgraph-orchestrates-phases-not-google-adk.md) (reopened), [ADR-0002](../../docs/adr/0002-skills-are-the-portable-unit-of-behaviour.md).
|
||||
|
||||
## Reopened by ADR-0002
|
||||
|
||||
The agent is meant to replace the upstream [`google-cloud-solution-architecture`](https://github.com/google/skills/blob/main/skills/cloud/google-cloud-solution-architecture/SKILL.md) skill. It should run Agent Skills through a framework's own skill runtime (ADK `SkillToolset`, or Deep Agents `skills=`), stay portable across Cloud providers, and target Google Cloud first. The decisions below were made before that goal was stated.
|
||||
|
||||
| Decision | Why it's in question |
|
||||
|---|---|
|
||||
| D1 LangGraph `StateGraph` sequences Phases | If the Skill describes the workflow and a skill runtime executes it, code-owned sequencing duplicates the Skill. The framework choice shrinks to "which skill runtime first". Note that Deep Agents compiles to a LangGraph graph, so the KAB workflow standard can still be met. |
|
||||
| D2 Phase bodies stay deterministic templates | A Skill's instructions only matter if a model executes them. Templates bypass the Skill entirely. |
|
||||
| D4 No approval gate | The upstream Skill requires explicit user approval of every Deliverable, and permission before running any script. |
|
||||
| D6 Phase row binds one Skill per Phase | The upstream Skill is one Skill covering all four Phases, with `references/` and `assets/`. It sits badly with one-Skill-per-Phase, and our `app/skills/*` don't follow the specification (snake_case names, custom `phase:` key). |
|
||||
| D7 `step(state, ctx)` with an injected `skill_prompt` | Skill runtimes use progressive disclosure: the model calls `load_skill` / `load_skill_resource`. They don't take prompt injection. |
|
||||
| D5, D11 to D13, D15, D16 | These depend on who sequences Phases. |
|
||||
| Phase list | Upstream has four Phases, with current state folded into requirements discovery. Ours has five, with a separate `source_discover`. |
|
||||
|
||||
### Settled so far (round 5)
|
||||
|
||||
| # | Decision |
|
||||
|---|---|
|
||||
| D19 | **Hybrid sequencing.** Code owns Phase boundaries and the Approvals between them. The Skill, run through a skill runtime, owns the work within each Phase. |
|
||||
| D20 | **Interactive by default**, with multi-turn Approvals. A pre-approved mode serves batch and eval runs. The `/generate` one-shot contract (D3) is no longer the primary interface. |
|
||||
| D21 | **Vendor the upstream Skill** unmodified and pinned to a commit. Our tooling gets its own Skills. The five `app/skills/*` are retired. |
|
||||
| D22 | **A Cloud provider is a configured bundle of Skills and tools.** No provider interface yet, and no provider prefix on core module names. |
|
||||
| D23 | **Not linear.** A hierarchy of agents follows the dependencies between Deliverables, and every agent runs a ReAct loop. This supersedes the linear phase table (D5, D6) and the round 6 questions on the engine (Q23), Approval granularity (Q25) and Phase completion (Q26), which are re-asked once the hierarchy is settled. |
|
||||
|
||||
### Settled in rounds 6 and 7
|
||||
|
||||
| # | Decision |
|
||||
|---|---|
|
||||
| D24 (Q23) | **Engine.** LangGraph holds Execution state, checkpoints and `interrupt()`. The Orchestrator and Specialists are ADK `LlmAgent`s with `SkillToolset`, behind one agent-runtime interface. Deep Agents is a later second implementation. See ADR-0003. |
|
||||
| D25 (Q24) | **Upstream's 4 Phases**, as groupings of Deliverables. The environment scan becomes a tool the requirements analyst can call. |
|
||||
| D26 (Q25) | **Approvals.** Code enforces and records Approval at Phase boundaries. Within a Phase, approval is conversational and driven by the Skill. Every user question is an `interrupt()`. |
|
||||
| D27 (Q26) | **Completion.** An agent finishes its work by calling a submit tool, and code checks the submission against the Deliverable contract. If anything is missing, the tool tells the agent what. |
|
||||
| D28 (Q27) | **Transport.** A2A for interactive Executions (`input-required` covers questions and Approvals). `/generate` is kept for pre-approved Executions. |
|
||||
| D29 (Q28) | **Hierarchy.** An Orchestrator sits above one Specialist per Deliverable. A Specialist fans out only for independent parts, such as the 6 WAF pillar advisors under the design advisor. |
|
||||
| D30 (Q29) | **Dependency graph declared in code.** The ReAct Orchestrator chooses work through tools (`ready_work`, `delegate`, `request_approval`) that refuse work whose dependencies aren't met. Independent work may run in parallel. |
|
||||
| D31 (Q30) | **Per-agent ReAct step budgets**, configurable. Hitting a budget hands control back to the user with a summary. |
|
||||
|
||||
### Settled in round 8
|
||||
|
||||
| # | Decision |
|
||||
|---|---|
|
||||
| D32 (Q31) | **Two thresholds.** A Dependency inside a Phase is met once the Deliverable is submitted, and a Specialist submits only after the user's conversational OK. A Dependency across Phases is met only by that Phase's Approval. |
|
||||
| D33 (Q32) | **One voice.** Only the Orchestrator talks to the user. A Specialist asks through `needs_input(question)`, and questions from parallel Specialists are combined. |
|
||||
| D34 (Q33) | **Stateless Specialists.** Each delegation starts fresh from its Dependencies, any feedback and the user's answers. Only the LangGraph checkpoint persists. |
|
||||
| D35 (Q34) | **Revision replaces the Review round.** Reopening a Deliverable returns it and everything that depends on it to draft, and revokes affected Phase Approvals. Revisions per Deliverable are capped, and at the cap the Orchestrator escalates to the user. |
|
||||
| D36 (Q35) | **Models are configurable per agent role** via ADK LiteLLM, with a Gemini default. |
|
||||
| D37 (Q36) | **New spec** at `.scratch/solution-architect-agent/spec.md`. This spec becomes superseded, and its still-valid parts become a cleanup section there. |
|
||||
|
||||
### Settled in round 9
|
||||
|
||||
| # | Decision |
|
||||
|---|---|
|
||||
| D38 (Q37) | **The dependency graph** is as proposed: 9 Deliverables across 4 Phases, deployment guidance depends on design recommendations, and runtime validation is out of scope for v1. |
|
||||
| D39 (Q38) | **Shared `SkillToolset` plus a role file per agent** (`agents/<role>.md`, framework-neutral). Pillar advisors are scoped to their own WAF Skill. |
|
||||
| D40 (Q39) | **Vendor the upstream solution-architecture Skill and the 6 WAF Skills** into `skills/vendor/google/`, pinned to `81a31a6`, with `VENDOR.md`, the Apache-2.0 licence and a sync script. |
|
||||
| D41 (Q40) | **Tool tiers.** Offline tools run freely. Tools that read live cloud resources need permission once per Execution (`allow_cloud_read` in pre-approved mode). Nothing that changes cloud resources is exposed, and `run_skill_script` is disabled. |
|
||||
| D42 (Q41) | **Deliverables** live in Execution state and the DB, and are written only to `deliverables/executions/{id}/` after Phase 4 Approval. No shared-path copies. |
|
||||
| D43 (Q42) | **A fake agent runtime** for deterministic tests. The real-model eval runs pre-approved with scripted user answers. |
|
||||
| D44 (Q43) | **Build alongside the current code**, then one cleanup increment after the eval passes. |
|
||||
| D45 | **Discovery and grounding use the Cloud provider's own remote MCP servers** (user direction, 2026-09-15). The servers are declared in the provider bundle, with reviewed read-only allowlists. All customer-reading MCP tools are `cloud_read`. `GCPEnvironmentScanner` and the hand-rolled Developer Knowledge client are retired. |
|
||||
| D46 | **Call remote MCP servers directly**, with no platform MCP gateway for now (user decision, 2026-09-15). |
|
||||
|
||||
The spec needs rewriting around the Orchestrator and Specialists once the open questions are settled. The current design section still describes the superseded linear Phase pipeline.
|
||||
|
||||
**Unaffected:** delete the fake ADK compat layer (D10's deletions), clean Sessions (D9), and build once at startup (D14). The candidate 02 to 05 findings stand. Grounding and scanning ports (candidate 02) become more important, because they are the tooling a Skill calls on.
|
||||
- Branch: `refactor/phase-pipeline`, pushed to the Gitea remote; the PR is opened by a human.
|
||||
|
||||
## Problem
|
||||
|
||||
The five Phases are declared in seven places: `app/adk/agents.py`, `app/workflows/gcp_architecture_graph.py`, `app/nodes/__init__.py`, each node's `active_skills` bookkeeping, `app/card.py` (twice), and `workflow.yaml` (which already omits `source_discover`). They are run by three orchestrators: a LangGraph `StateGraph`, an "ADK" `SequentialAgent` inside a `LoopAgent`, and an "ADK" `Workflow`. None of these uses the real `google-adk` package. `HAS_NATIVE_ADK` is never read, so every "ADK" class is a local stub. The five agent classes are pass-throughs. Every node builds a skill prompt and discards it. The review loop reruns all five Phases without passing validation findings back. And passing a `session_id` merges a previous Execution's outputs into the next one.
|
||||
|
||||
## Goals
|
||||
|
||||
- One module owns Phase ordering, state merging, Phase contracts, the Review round, Skill binding and `active_skills`.
|
||||
- One small interface: `async run(workflow_request) -> Execution`.
|
||||
- Tests exercise the pipeline only through that interface.
|
||||
- Adding or reordering a Phase is a one-row change to the phase table.
|
||||
|
||||
## Non-goals (other review candidates)
|
||||
|
||||
- Grounding and environment scan ports (candidate 02). Steps keep constructing `GCPEnvironmentScanner` and calling `get_mcp_client()`.
|
||||
- The Execution store (candidate 03). `DatabaseManager` stays as it is, dual-dialect branches included.
|
||||
- The Deliverable layout (candidate 04). The state-key → path mapping moves unchanged, and output paths in `workflow.yaml` are left alone.
|
||||
- LangChain `@tool` pass-throughs in `app/tools/` (candidate 05). `validate` keeps calling `.invoke`.
|
||||
- Typed Phase outputs (candidate 06). Outputs stay markdown strings.
|
||||
- Making any Phase call an LLM. The interface gets ready for it; the step bodies keep their templates.
|
||||
- A human approval gate, checkpointing or resume.
|
||||
- Moving the transport to aiohttp A2A on :8000.
|
||||
|
||||
## Decisions
|
||||
|
||||
| # | Decision |
|
||||
|---|---|
|
||||
| D1 | LangGraph `StateGraph` orchestrates Phases. The ADK compat layer is deleted. Real ADK may be used *inside* a step later (ADR-0001). |
|
||||
| D2 | Target direction: `discover`, `design` and `package` become LLM-driven; `source_discover` and `validate` stay deterministic. This work only readies the interface. |
|
||||
| D3 | Stable: the `/generate` response shape and the Deliverable paths. `/card` is derived from the phase table. `workflow.yaml` is test-checked against it. Agent and log names may change. |
|
||||
| D4 | No approval gate. There is a single `run`. |
|
||||
| D5 | Review round: a conditional edge `validate → design` while validation fails and rounds < `MAX_REVIEW_ROUNDS`. Findings reach design as `review_feedback`. |
|
||||
| D6 | Phase row: `Phase(name, skill, step, requires, produces)`. The pipeline enforces contracts, maintains `active_skills` and `current_phase`, and binds Skills by name. |
|
||||
| D7 | Step: `async step(state, ctx: PhaseContext) -> dict`. `ctx` has `skill_prompt` and `model=None`. |
|
||||
| D8 | The pipeline does no DB or file I/O. The caller records the Execution. |
|
||||
| D9 | A Session groups Executions. Every Execution starts from clean state. |
|
||||
| D10 | `app/adk/` is removed. `app/executions.py` records Executions for the route and the eval harness. |
|
||||
| D11 | Module: `app/workflows/gcp_architecture_pipeline.py`. Steps stay in `app/nodes/`. The state schema stays in `app/states/`. |
|
||||
| D12 | The phase table is a constructor argument, so tests inject a fake table. Old orchestrator tests are deleted. |
|
||||
| D13 | The card is derived at import. `workflow.yaml` gains `source_discover`, and a test asserts its phase ids match. |
|
||||
| D14 | The pipeline is built once in the Starlette lifespan and stored on `app.state.pipeline`. |
|
||||
| D15 | When Review rounds run out with validation still failing, the pipeline packages anyway: `validation_passed=false`, status `completed_with_warnings`. |
|
||||
| D16 | A contract breach raises `PhaseContractError`. The Execution is recorded `failed`, the route returns HTTP 500, and no Deliverables are written. |
|
||||
| D17 | Blocking I/O in `source_discover` and `design` is offloaded with `asyncio.to_thread`. |
|
||||
| D18 | Also: remove `google-adk` from `requirements.txt`, rewrite the README's ADK sections, delete the unreachable duplicate `return` in `routes.py`. |
|
||||
|
||||
## Design
|
||||
|
||||
### Module: `app/workflows/gcp_architecture_pipeline.py`
|
||||
|
||||
Replaces `app/workflows/gcp_architecture_graph.py`.
|
||||
|
||||
```python
|
||||
@dataclass(frozen=True)
|
||||
class PhaseContext:
|
||||
skill_prompt: str
|
||||
model: Any | None = None # D2: populated when a Phase becomes LLM-driven
|
||||
|
||||
Step = Callable[[Mapping[str, Any], PhaseContext], Awaitable[dict[str, Any]]]
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Phase:
|
||||
name: str # e.g. "design"
|
||||
skill: str # Skill name, e.g. "architecture_design"
|
||||
step: Step
|
||||
requires: tuple[str, ...] # state keys that must be present (not None) before the step
|
||||
produces: tuple[str, ...] # state keys the step must return
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ReviewRound:
|
||||
number: int # 1-based
|
||||
passed: bool
|
||||
findings: tuple[str, ...]
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Execution:
|
||||
execution_id: str
|
||||
workflow_request: str
|
||||
outputs: Mapping[str, Any] # final state values for every Phase's `produces`
|
||||
validation_passed: bool
|
||||
review_rounds: tuple[ReviewRound, ...]
|
||||
active_skills: tuple[str, ...]
|
||||
current_phase: str # last Phase run ("package" on success)
|
||||
|
||||
class PhaseContractError(Exception):
|
||||
phase: str
|
||||
missing: tuple[str, ...]
|
||||
kind: Literal["requires", "produces"]
|
||||
|
||||
class PhasePipeline:
|
||||
def __init__(self, phases: Sequence[Phase], skills: SkillLoader, max_review_rounds: int) -> None: ...
|
||||
async def run(self, workflow_request: str) -> Execution: ...
|
||||
|
||||
PHASES: tuple[Phase, ...] = (...) # production table, below
|
||||
```
|
||||
|
||||
**Construction invariants.** Each of these raises `ValueError` from `__init__`:
|
||||
- phase names are not unique
|
||||
- a Phase's `skill` is missing from the `SkillLoader`
|
||||
- there is no Phase named `design` or `validate` (the Review round needs both)
|
||||
|
||||
The `StateGraph` is compiled once, in `__init__`.
|
||||
|
||||
**Graph.** Linear edges follow table order. The exception is one conditional edge leaving `validate`:
|
||||
- **Loop back:** if `validation_passed` is false and the rounds so far are fewer than `max_review_rounds`, go to `design`.
|
||||
- **Otherwise:** continue to the Phase after `validate`.
|
||||
|
||||
**Per-Phase node wrapper.** The pipeline generates one per row, and it does the following in order:
|
||||
1. **Check inputs.** Every `requires` key must be present and not None in state. Otherwise raise `PhaseContractError(kind="requires")`.
|
||||
2. **Run the step.** Build `PhaseContext(skill_prompt=<that Skill formatted for prompt>)` and await `step(read-only state view, ctx)`.
|
||||
3. **Check outputs.** Every `produces` key must be in the returned dict. Otherwise raise `PhaseContractError(kind="produces")`.
|
||||
4. **Merge only declared keys.** Keys the step returns that aren't in `produces` are dropped, with a warning logged.
|
||||
5. **Update bookkeeping.**
|
||||
- Set `current_phase` to the Phase name.
|
||||
- Append the Skill to `active_skills` if it isn't already there.
|
||||
- For `design`: increment `review_round`.
|
||||
- For `validate`: append a `ReviewRound(review_round, validation_passed, errors)` to `review_rounds`. On failure, set `review_feedback = errors`.
|
||||
|
||||
**Key presence.** A key is present if it is not None. `False`, `""` and `[]` all count as present.
|
||||
|
||||
**`run`.**
|
||||
- **Initial state:** `{execution_id: uuid4, workflow_request, active_skills: [], review_round: 0, review_rounds: [], review_feedback: []}`. Nothing is carried over from a Session (D9).
|
||||
- **Execution:** `ainvoke` the compiled graph, then build the `Execution`.
|
||||
- **Errors:** `PhaseContractError` propagates to the caller.
|
||||
|
||||
### State: `app/states/state.py`
|
||||
|
||||
`GCPArchitectureState` changes:
|
||||
- **Added:** `execution_id: str`, `review_round: int`, `review_rounds: list[ReviewRound]`, `review_feedback: list[str]`.
|
||||
- **Removed:** `target_dir`. Nothing reads it; `/generate` still accepts the field and ignores it, as it effectively does today.
|
||||
|
||||
### Production phase table
|
||||
|
||||
| Phase | Skill | requires | produces |
|
||||
|---|---|---|---|
|
||||
| `source_discover` | `source_discovery` | `workflow_request` | `source_discovery_doc`, `source_mermaid_diagram` |
|
||||
| `discover` | `requirements_discovery` | `workflow_request` | `requirements_doc`, `product_selection_deferred` |
|
||||
| `design` | `architecture_design` | `requirements_doc` | `architecture_doc`, `mermaid_diagram`, `terraform_code`, `product_selection_deferred` |
|
||||
| `validate` | `validation_rules` | `mermaid_diagram`, `terraform_code` | `validation_results`, `validation_passed`, `errors` |
|
||||
| `package` | `packaging_guide` | `source_discovery_doc`, `source_mermaid_diagram`, `requirements_doc`, `architecture_doc`, `mermaid_diagram`, `terraform_code`, `validation_results` | `solution_guide`, `status_summary` |
|
||||
|
||||
`design` doesn't read `requirements_doc` today. The table declares the dependency the Phase is meant to have (see `workflow.yaml`). `design` may also read `review_feedback`, which is always present.
|
||||
|
||||
### Steps: `app/nodes/*.py`
|
||||
|
||||
- **New signature:** each `*_node(state, skill_loader)` becomes `async def *_step(state, ctx) -> dict` (D7). Bodies keep their current templates.
|
||||
- **Removed from steps:** each step returns only its `produces` keys. The `skill_loader.format_skills_for_prompt(...)` call and the `active_skills`/`current_phase` bookkeeping are deleted.
|
||||
- **Blocking I/O (D17):**
|
||||
- `source_discover`: `scan_result = await asyncio.to_thread(scanner.scan_environment)`. The scanner is also constructed inside the thread, because its `__init__` can shell out to `gcloud`.
|
||||
- `design`: `await asyncio.to_thread(mcp_client.search_documents, ...)`.
|
||||
- **Skills:** `SkillLoader` gains `format_skill_for_prompt(name) -> str`, which gives the single-Skill form of `format_skills_for_prompt`.
|
||||
|
||||
### Recording: `app/executions.py`
|
||||
|
||||
A plain module that replaces `ADKAgentRunner`, `PostgresSessionService`, `PostgresArtifactRepository` and `ADKEvaluator`'s persistence. It uses `get_db_manager()` for now (candidate 03 replaces that).
|
||||
|
||||
- `record(execution, session_id, base_dir) -> None`:
|
||||
- Writes Deliverables using the state-key → path mapping moved verbatim from `app/adk/artifacts.py`. That covers current paths, per-execution paths and `docs/` mirrors.
|
||||
- Saves one `adk_artifacts` row per written file.
|
||||
- Saves the session row (`agent_name = settings.AGENT_NAME`, `state_data` = the Execution as JSON).
|
||||
- Saves a `workflow_executions` row with status `completed` or `failed` from `validation_passed`, `loop_count = len(review_rounds)`, and the results JSON as today.
|
||||
- Writes one `orchestrator_review_logs` row per `ReviewRound`: `reviewer_agent="validate"`, `review_status` `APPROVED` or `NEEDS_REVISION`, `feedback` = the joined findings.
|
||||
- `record_failure(execution_id, session_id, workflow_request, error: PhaseContractError) -> None`: saves a `workflow_executions` row with status `failed`, `current_phase = error.phase` and the error details in the results JSON. It writes no Deliverables.
|
||||
- `to_generate_response(execution, session_id) -> dict` builds the stable `/generate` shape:
|
||||
- `execution_id`, `session_id`, `validation_passed`, `current_phase`, `active_skills`
|
||||
- `status`: `success` or `completed_with_warnings`
|
||||
- `total_loop_iterations`: `len(review_rounds)`
|
||||
- `artifacts`: the same 8 keys as today
|
||||
|
||||
### HTTP: `app/agent.py`, `app/workflows/routes.py`
|
||||
|
||||
- **Lifespan:** runs `get_db_manager()` as today, then `app.state.pipeline = PhasePipeline(PHASES, loaded SkillLoader, settings.MAX_REVIEW_ROUNDS)` (D14).
|
||||
- **`POST /generate`:** `await request.app.state.pipeline.run(workflow_request)`, then `executions.record(...)`, then return `to_generate_response(...)`.
|
||||
- On `PhaseContractError`: call `executions.record_failure(...)` and return HTTP 500 with `{"error": str(e), "phase": e.phase, "missing": [...]}`.
|
||||
- A missing or invalid `session_id` in the body gets a new uuid, as today.
|
||||
- **`GET /sessions/{id}`:** reads through `get_db_manager().get_session`. The response shape is unchanged, but `agent_name` becomes `gcp_solution_architecture_agent`.
|
||||
- **`GET /health`:** drops `"adk_framework"`.
|
||||
- **`POST /validate`:** unchanged. Delete the unreachable duplicate `return`.
|
||||
|
||||
### Card and manifest
|
||||
|
||||
- `app/card.py`: `capabilities.phases = [p.name for p in PHASES]` and `capabilities.local_skills = [p.skill for p in PHASES]`. All other fields are unchanged.
|
||||
- `workflow.yaml`: add a `source_discover` phase entry before `discover`. Renumbering `step` is left to the implementer, as long as order matches `PHASES`.
|
||||
|
||||
### Settings: `app/config.py`, `.env.example`
|
||||
|
||||
- `MAX_REVIEW_ROUNDS: int = 5`, which also reads the legacy env name `ADK_MAX_LOOP_ITERATIONS` (pydantic `AliasChoices`).
|
||||
- Delete `ADK_MAX_LOOP_ITERATIONS` and `ADK_ENABLE_ARTIFACT_STORE` (the latter is never read).
|
||||
- Update `.env.example` to match.
|
||||
|
||||
### Eval: `eval/eval_harness.py`
|
||||
|
||||
- `EvalHarness.run_eval_suite` becomes `async`. `EvalHarness` builds a `PhasePipeline`, awaits `run(case["workflow_request"])`, scores `execution.outputs` with `eval/metrics.evaluate_case_run`, and saves with `get_db_manager().save_evaluation`.
|
||||
- `main()` uses `asyncio.run`.
|
||||
- This removes the `app → eval` import that `app/adk/evaluation.py` created.
|
||||
|
||||
### Deleted
|
||||
|
||||
- `app/adk/` (all 9 files)
|
||||
- `app/workflows/gcp_architecture_graph.py`
|
||||
- `tests/test_graph_workflow.py`
|
||||
- `google-adk` from `requirements.txt`
|
||||
|
||||
## Behaviour changes (call out in the PR)
|
||||
|
||||
1. A `session_id` no longer seeds an Execution with a previous Execution's state.
|
||||
2. A failing validation now re-runs only `design → validate`, not all five Phases.
|
||||
3. A Phase contract breach returns HTTP 500 and records a `failed` Execution. Before, the pipeline silently continued with empty strings.
|
||||
4. `/sessions/{id}` returns `agent_name: "gcp_solution_architecture_agent"`, not `OrchestratorLoopAgent`.
|
||||
5. `/health` no longer includes `adk_framework`.
|
||||
6. `total_loop_iterations` counts Review rounds, not whole-pipeline passes. Its value is `1` on the happy path, the same as today.
|
||||
7. `workflow.yaml` lists `source_discover`.
|
||||
|
||||
## Testing
|
||||
|
||||
Tests go through `PhasePipeline.run()` and the HTTP interface only, using `pytest-asyncio`.
|
||||
|
||||
**New: `tests/test_phase_pipeline.py`**
|
||||
|
||||
These use a fake phase table of tiny async steps and a stub `SkillLoader` fixture (or a tmp skills dir):
|
||||
- **Phase order:** Phases run in table order, and `current_phase` ends on the last Phase.
|
||||
- **Merging:** only declared `produces` keys are merged, and extra keys are dropped.
|
||||
- **Requires check:** a missing `requires` key raises `PhaseContractError(kind="requires", phase=...)`.
|
||||
- **Produces check:** a step that omits a `produces` key raises `PhaseContractError(kind="produces", phase=...)`.
|
||||
- **Presence:** `False` and `""` count as present.
|
||||
- **Review round, passes on round 2:** `validate` fails once and then passes. `design` runs twice and receives `review_feedback` on round 2; `review_rounds` has 2 entries and `validation_passed` is true.
|
||||
- **Review round, never passes:** `validate` always fails. Rounds stop at `max_review_rounds`, the Phase after `validate` still runs, and `validation_passed` is false.
|
||||
- **Skills:** `ctx.skill_prompt` holds the bound Skill's content, and `active_skills` lists each Skill once, even across Review rounds.
|
||||
- **Clean runs:** two `run()` calls on one pipeline share no state.
|
||||
- **Construction:** duplicate names, an unknown Skill, or a missing `design`/`validate` each raise `ValueError`.
|
||||
|
||||
**Also new:**
|
||||
- **End to end:** `run()` with the real `PHASES` and `app/skills`. Every `produces` key is present, `validation_passed` is true, there are 5 `active_skills` and 1 review round.
|
||||
- **Manifest check:** the phase ids in `workflow.yaml` equal `[p.name for p in PHASES]`, and `/card` phases and skills equal the table.
|
||||
|
||||
**Changed**
|
||||
- `tests/test_agent_api.py`: use `with TestClient(app) as client`, because the lifespan must run so `app.state.pipeline` exists. Existing assertions stay and guard the stable `/generate` contract. Add one test for the 500 response on a contract breach, with a pipeline built from a breaching fake table swapped onto `app.state`.
|
||||
- `tests/test_adk_architecture.py`:
|
||||
- **Delete:** `test_adk_tools`, `test_adk_postgres_session_service`, `test_adk_orchestrator_loop_agent`, `test_adk_workflow_composition`, `test_adk_agent_runner`, `test_adk_evaluator`.
|
||||
- **Keep:** `test_database_manager_operations`, moved to `tests/test_database.py`.
|
||||
- **Move:** the session endpoint test into `test_agent_api.py`, asserting the new `agent_name`.
|
||||
- Then delete the file.
|
||||
- `tests/test_mcp_developer_knowledge.py`: delete `test_adk_mcp_function_tools` and its `app.adk.tools` import.
|
||||
- `eval/test_eval_harness.py`: `test_eval_harness_benchmark` awaits the now-async `EvalHarness.run_eval_suite()` (`@pytest.mark.asyncio`), and its assertions are unchanged. `test_skill_optimizer_recommendations` is untouched.
|
||||
|
||||
**Known issue, left out of scope:** `/generate` tests write Deliverables into the working tree and the local SQLite file (candidates 03 and 04).
|
||||
|
||||
## Implementation increments
|
||||
|
||||
These are ordered. Each one leaves the suite green and is one or more commits on `refactor/phase-pipeline`. They are called *increments* to avoid clashing with the glossary's **Phase**.
|
||||
|
||||
1. **Baseline environment.**
|
||||
- Create a venv and install `requirements.txt` and `requirements-dev.txt`.
|
||||
- Run the current suite and record the baseline pass/fail list in this spec's `## Comments`. No Python environment exists on the dev machine yet.
|
||||
- Create the branch.
|
||||
2. **Pipeline core, test-first.**
|
||||
- Add `Phase`, `PhaseContext`, `ReviewRound`, `Execution`, `PhaseContractError`, `PhasePipeline` and `SkillLoader.format_skill_for_prompt`.
|
||||
- Write every fake-table test in `test_phase_pipeline.py` first.
|
||||
- Production code is untouched apart from these additions.
|
||||
3. **Port the steps and the table.**
|
||||
- Convert the five nodes to async steps (including D17), define `PHASES`, extend `GCPArchitectureState` and add the end-to-end test.
|
||||
- Delete `gcp_architecture_graph.py` and `test_graph_workflow.py`, and update `app/workflows/__init__.py` and `app/nodes/__init__.py` exports.
|
||||
- The `app/adk/` agents still call the old node names at this point, so either keep thin old-signature shims until increment 5 or do increments 3 and 5 together. Prefer shims, deleted in 5.
|
||||
4. **Recording and HTTP wiring.**
|
||||
- Add `app/executions.py`, the lifespan pipeline, the `/generate` success and 500 paths, `/sessions` via `DatabaseManager`, and `/health`.
|
||||
- Rename settings, with the alias, and update `.env.example`.
|
||||
- Update `test_agent_api.py` (lifespan client, 500 test, session endpoint test).
|
||||
5. **Remove ADK.**
|
||||
- Move the eval harness onto the pipeline.
|
||||
- Delete `app/adk/`, the old-signature shims, the ADK tests and `google-adk` from `requirements.txt`.
|
||||
- Move the DB test to `tests/test_database.py`.
|
||||
6. **Card and manifest.** Derive the card from `PHASES`, add `source_discover` to `workflow.yaml`, and add the manifest consistency test.
|
||||
7. **Docs and cleanup.**
|
||||
- Rewrite the README's ADK sections around the Phase pipeline.
|
||||
- Delete the duplicate `return` in `routes.py`.
|
||||
- Run a final full suite plus `ruff` and `mypy` on the touched modules.
|
||||
- Push the branch.
|
||||
|
||||
## Acceptance
|
||||
|
||||
- [ ] `rg -n "app\.adk|google\.adk|OrchestratorLoopAgent|compat" app eval tests` returns nothing.
|
||||
- [ ] The phase list appears only in `PHASES`, and `workflow.yaml` is test-checked against it.
|
||||
- [ ] Every test listed under Testing exists and passes. The rest of the baseline suite is no worse than increment 1's record.
|
||||
- [ ] The `/generate` response keys match today's exactly: `execution_id`, `session_id`, `status`, `validation_passed`, `total_loop_iterations`, `current_phase`, `artifacts` (8 keys) and `active_skills`.
|
||||
- [ ] The Deliverable paths written by `/generate` are unchanged.
|
||||
- [ ] The README no longer describes ADK orchestration, and ADR-0001 is linked.
|
||||
763
.scratch/solution-architect-agent/spec.md
Normal file
763
.scratch/solution-architect-agent/spec.md
Normal file
@@ -0,0 +1,763 @@
|
||||
# Spec: Solution architect agent
|
||||
|
||||
A portable, hierarchical ReAct agent that replaces the upstream [`google-cloud-solution-architecture`](https://github.com/google/skills/blob/main/skills/cloud/google-cloud-solution-architecture/SKILL.md) skill. An Orchestrator reasons over a code-declared dependency graph of Deliverables and delegates to Specialists. All agents run vendored Agent Skills through a framework's own skill runtime. Users grant Approvals at Phase boundaries.
|
||||
|
||||
- Glossary: [`CONTEXT.md`](../../CONTEXT.md). Use its terms: Execution, Session, Phase, Approval, Revision, Orchestrator, Specialist, Skill, Cloud provider, Deliverable, Dependency, Solution guide.
|
||||
- Decisions: [ADR-0002](../../docs/adr/0002-skills-are-the-portable-unit-of-behaviour.md) (Skills-first, hybrid, hierarchical and ReAct, vendoring, Cloud provider as configuration) and [ADR-0003](../../docs/adr/0003-langgraph-holds-state-adk-agents-reason.md) (LangGraph state with ADK agents).
|
||||
- Supersedes: [`.scratch/phase-pipeline/spec.md`](../phase-pipeline/spec.md). Its decision log (D1 to D46) records how this design was reached.
|
||||
- Branch: `feat/solution-architect-agent`, pushed to the Gitea remote. A human opens the PR.
|
||||
|
||||
## Problem
|
||||
|
||||
The current agent is a linear chain of five template functions. They ignore the Workflow request (design always picks Cloud Run and Pub/Sub). They run under a fake "ADK" layer that never touches `google-adk`. The skill prompts they build are thrown away. The agent can't ask the user anything, can't take an Approval, can't run the upstream Skill, and can't target another framework or Cloud provider without a rewrite.
|
||||
|
||||
## Goals
|
||||
|
||||
- **Upstream parity.** It runs the upstream Skill's workflow: requirements discovery with strict separation from solutioning, grounded product selection with alternatives, diagram, description, WAF-pillar design recommendations, IaC deployment guidance, dry-run validation, and packaging into the upstream template.
|
||||
- **Hierarchical and ReAct.** Work follows Dependencies, not a fixed order, and independent work runs in parallel.
|
||||
- **Interactive by default**, with code-enforced, recorded Approvals at Phase boundaries. There is also a pre-approved mode for batch and evaluation runs.
|
||||
- **Discovery through the Cloud provider's own remote MCP servers.** Current state is discovered through remote MCP servers hosted by the Cloud provider, such as Google Cloud's Resource Manager, Asset Inventory, Compute and GKE servers. Grounding uses the provider's knowledge MCP server. No hand-written cloud REST scanners.
|
||||
- **Portable.**
|
||||
- Behaviour lives in Skills and framework-neutral role files.
|
||||
- Framework types stay behind one agent-runtime interface.
|
||||
- Everything specific to a Cloud provider lives in a provider bundle.
|
||||
- **Deterministic tests** check every rule the code owns, without a model.
|
||||
|
||||
## Non-goals (v1)
|
||||
|
||||
- **Runtime validation.** Upstream Task 3.2, verifying after the user has deployed, is out of scope.
|
||||
- **Changing cloud resources.** No `apply` or deploy tool, and ADK's `run_skill_script` is off.
|
||||
- **A second Cloud provider** or a second agent-runtime implementation (Deep Agents). The design leaves room for both; neither is built.
|
||||
- **Architecture review candidates 02 to 06**, beyond what this spec needs: tools get tier wrappers, not full ports; `DatabaseManager` is reused as is; no typed Deliverable records.
|
||||
- **Human approval inside a Phase enforced by code.** That stays conversational and driven by the Skill (see [Risks](#risks)).
|
||||
- **Acting as the end user in their cloud (OAuth).** Remote MCP calls use the agent's own identity (a service account or Application Default Credentials) in v1.
|
||||
- **Routing MCP calls through the platform's MCP gateway** (`mcp_gateway_client.py` in the base agents). Remote MCP servers are called directly (D46). If a gateway is needed later, it becomes a new `mcp_auth.kind: gateway` implementation in `app/tools/mcp.py`, and nothing else changes.
|
||||
|
||||
## Decisions
|
||||
|
||||
These are carried from the decision log. The numbers refer to it.
|
||||
|
||||
| Area | Decision |
|
||||
|---|---|
|
||||
| Sequencing (D19, D23) | **Hybrid.** Code owns Dependencies, Phase boundaries and Approvals, and the Skill owns the work inside a Deliverable. The agent is hierarchical and ReAct, not linear. |
|
||||
| Engine (D24) | **LangGraph + ADK.** A LangGraph `StateGraph` holds Execution state, checkpoints and `interrupt()`. The Orchestrator and Specialists are ADK `LlmAgent`s with `SkillToolset`, behind an `AgentRuntime` interface. |
|
||||
| Phases (D25) | **Upstream's 4 Phases**, as groupings of Deliverables. Discovery of current state is done through tools (remote MCP servers, D45). |
|
||||
| Approvals (D26, D32) | Code enforces Approval at Phase boundaries. A Dependency inside a Phase is met on *submitted*, and one across Phases only on Phase *approved*. Every user question is an `interrupt()`. |
|
||||
| Completion (D27) | Agents finish by calling a submit tool that is checked against the Deliverable's contract. |
|
||||
| Transport (D28) | **A2A** for interactive Executions. `/generate` is kept for pre-approved ones. |
|
||||
| Hierarchy (D29) | **An Orchestrator over one Specialist per Deliverable.** The design advisor fans out to 6 pillar advisors. |
|
||||
| Dependency graph (D30) | **Declared in code.** The ReAct Orchestrator picks work through tools that refuse work whose Dependencies aren't met. |
|
||||
| Budgets (D31) | **Per-agent ReAct step budgets.** Hitting one hands control to the user. |
|
||||
| Voice (D33) | **Only the Orchestrator talks to the user.** Specialists ask through `needs_input`. |
|
||||
| Specialist memory (D34) | **Stateless per delegation.** Only the LangGraph checkpoint persists. |
|
||||
| Revision (D35) | **Reopening a Deliverable** returns it and everything that depends on it to draft and withdraws affected Approvals. Revisions are capped, and past the cap the user decides. |
|
||||
| Models (D36) | **Configurable per role via ADK LiteLLM**, with a Gemini default. |
|
||||
| Dependency graph content (D38) | See [Dependency graph](#dependency-graph). Runtime validation is out of scope. |
|
||||
| Skill slicing (D39) | **A shared `SkillToolset` plus `agents/<role>.md`.** Pillar advisors are scoped to their own WAF Skill. |
|
||||
| Vendoring (D21, D40) | **Upstream solution-architecture + 6 WAF Skills**, unmodified, pinned to `81a31a6`, in `skills/vendor/google/`. |
|
||||
| Tool tiers (D41) | **General tools** (local checks, public documentation) run freely. **Reading live cloud resources** needs permission once per Execution. **Changing cloud resources** is never exposed. |
|
||||
| Discovery (D45) | **The Cloud provider's own remote MCP servers**, declared in the provider bundle, provide discovery and grounding. Every tool that reads the user's cloud is `cloud_read`. Only tools on an explicit read-only allowlist are exposed. `GCPEnvironmentScanner` is retired. |
|
||||
| MCP routing (D46) | **Call remote MCP servers directly**, with no platform MCP gateway for now. |
|
||||
| Outputs (D42) | **Deliverables live in state and the database.** Files go to `deliverables/executions/{id}/` only after Phase 4 Approval. |
|
||||
| Tests (D43) | **A fake `AgentRuntime`** for deterministic tests. The real-model evaluation runs pre-approved with scripted answers. |
|
||||
| Migration (D44) | **Build alongside the current code.** One cleanup increment follows once the evaluation passes. |
|
||||
| Carried over (D9, D14) | **Every Execution starts clean**, and a Session only groups Executions. The Execution graph and agent runtime are built once at startup. |
|
||||
|
||||
## Design
|
||||
|
||||
### Module layout
|
||||
|
||||
The engine sits in the KAB workflow-agent layout since 2026-10-06 (`.agents/plans/iter-03-kab-layout/`). The original pipeline was deleted the same day.
|
||||
|
||||
```
|
||||
agents/ # framework-neutral role files (one per role)
|
||||
orchestrator.md
|
||||
requirements-analyst.md decomposer.md product-selector.md diagrammer.md
|
||||
describer.md design-advisor.md pillar-advisor.md iac-author.md
|
||||
validator.md packager.md
|
||||
partials/specialist-protocol.md
|
||||
providers/
|
||||
gcp.yaml # Cloud provider bundle
|
||||
skills/
|
||||
vendor/google/ # unmodified upstream Skills + VENDOR.md + LICENSE
|
||||
google-cloud-solution-architecture/
|
||||
google-cloud-waf-{security,reliability,cost-optimization,operational-excellence,performance-optimization,sustainability}/
|
||||
cloud-discovery/SKILL.md # our tooling Skills (Agent Skills spec compliant)
|
||||
iac-validation/SKILL.md
|
||||
app/
|
||||
main.py # A2A server on A2A_PORT: /a2a, agent card, /health, /generate
|
||||
a2a_server.py # maps A2A tasks <-> Executions and interrupts
|
||||
agent.py # ExecutionEngine (start, resume, interaction) and open_assembly
|
||||
card.py # A2A agent card, derived from the dependency graph
|
||||
states/
|
||||
execution_state.py # ExecutionState TypedDict
|
||||
ledger.py # Ledger: Deliverable/Phase states, acceptance, Revision (pure, no I/O)
|
||||
nodes/
|
||||
execution_nodes.py # orchestrator turn, Specialist task, await user, finalize
|
||||
workflows/
|
||||
deliverables.py # DeliverableKind, PhaseId, DEPENDENCY_GRAPH, contracts
|
||||
execution_graph.py # LangGraph StateGraph wiring of the nodes
|
||||
adk/
|
||||
runtime.py # AgentRuntime protocol, RoleSpec, AgentTask, Outcome types
|
||||
roles.py # loads agents/*.md into RoleSpec
|
||||
adk_runtime.py # ADK LlmAgent + SkillToolset + LiteLlm implementation
|
||||
fake_runtime.py # scripted implementation for tests (under app/ so eval can reuse it)
|
||||
skills/
|
||||
agent_skills.py # Agent Skills discovery and frontmatter validation
|
||||
tools/
|
||||
execution.py # Orchestrator and Specialist execution tools bound to the Ledger
|
||||
toolkit.py # which tools each role gets
|
||||
pillars.py # the design advisor's fan-out to pillar advisors
|
||||
local.py # mermaid check, terraform fmt/validate/plan (local, tiered)
|
||||
mcp.py # McpServerSpec, read-only allowlist, tier + permission metadata
|
||||
providers.py # loads providers/<name>.yaml
|
||||
recorder.py # records submissions, Approvals, Revisions, status
|
||||
checkpointing.py # memory | sqlite | postgres checkpointer
|
||||
presentation.py # prompts and the /generate response
|
||||
scripts/sync-vendored-skills.sh
|
||||
```
|
||||
|
||||
### Deliverables and the dependency graph <a id="dependency-graph"></a>
|
||||
|
||||
`app/workflows/deliverables.py` declares the graph as data. It is the only place Phases, Deliverables and Dependencies are listed.
|
||||
|
||||
> **Changed on 2026-10-07 by [ADR-0005](../../docs/adr/0005-the-target-architecture-is-an-explicit-graph.md).** The table below is the graph as first built. The code now has five Phases, a `target_architecture` Deliverable between the design recommendations and the code, no `architecture_diagram` Deliverable (the diagram is rendered from the graph), and data files carrying ids along the Requirements chain (`app/workflows/chain.py`, `app/workflows/target_architecture.py`). See `.agents/plans/iter-06-target-architecture-graph/`.
|
||||
|
||||
| Phase | Deliverable kind | Specialist role | Depends on | Tools (tier) |
|
||||
|---|---|---|---|---|
|
||||
| 1 `requirements_discovery` | `requirements` | `requirements-analyst` | (none) | discovery MCP servers (cloud_read) |
|
||||
| 1 | `technical_decomposition` | `decomposer` | `requirements` | (none) |
|
||||
| 2 `solution_architecture` | `product_selection` | `product-selector` | `technical_decomposition` | knowledge MCP (general) |
|
||||
| 2 | `architecture_diagram` | `diagrammer` | `product_selection` | mermaid check (general) |
|
||||
| 2 | `architecture_description` | `describer` | `architecture_diagram`, `product_selection` | knowledge MCP (general) |
|
||||
| 2 | `design_recommendations` | `design-advisor` → 6 × `pillar-advisor` | `product_selection`, `requirements` | knowledge MCP (general) |
|
||||
| 2 | `deployment_guidance` | `iac-author` | `product_selection`, `design_recommendations` | terraform fmt/validate (general) |
|
||||
| 3 `solution_validation` | `validation_results` | `validator` | `deployment_guidance` | terraform validate (general), terraform plan and policy MCP servers: IAM, Network Intelligence (cloud_read) |
|
||||
| 4 `packaging` | `solution_guide` | `packager` | every Phase 3 Deliverable | (none) |
|
||||
|
||||
**Deliverable contract.** Each kind declares its required content in `deliverables.py`:
|
||||
- `sections`: required markdown headings.
|
||||
- `attachments`: named code blobs, for example `deployment_guidance` requires `terraform/main.tf` and `terraform/variables.tf`.
|
||||
|
||||
`submit_deliverable` checks the contract. A failing submission returns what's missing to the Specialist, and nothing is recorded.
|
||||
|
||||
### The Ledger: acceptance and Revision rules
|
||||
|
||||
`app/states/ledger.py` is a pure module. It holds every rule code owns, and the tests exercise it heavily.
|
||||
|
||||
- **Deliverable states:** `pending → in_progress → submitted`. Only a Revision goes backwards.
|
||||
- **Phase states:** `open → awaiting_approval → approved`. A Phase becomes `awaiting_approval` when the Orchestrator calls `request_approval` with all its Deliverables `submitted`.
|
||||
- **When a Dependency is met:**
|
||||
- **Same Phase:** the Dependency is `submitted`.
|
||||
- **Across Phases:** the Dependency's Phase is `approved`.
|
||||
- **Ready work:** Deliverables that are `pending` and have every Dependency met.
|
||||
- **`reopen(kind, reason)`:**
|
||||
- The Deliverable goes to `pending` with `reason` appended to its feedback.
|
||||
- Everything that depends on it, directly or not, goes to `pending`.
|
||||
- Every affected Phase that was `approved` or `awaiting_approval` goes back to `open`.
|
||||
- The Deliverable's `revisions` count goes up. At the cap (`max_revisions`, default 3) `reopen` refuses and returns an escalation the Orchestrator must put to the user.
|
||||
- **Pre-approved mode:** `request_approval` grants immediately and records `approved_by = "pre-approved"`.
|
||||
- **Records:** every transition appends an event (`submitted`, `approval_requested`, `approved`, `changes_requested`, `reopened`, `escalated`) for the recorder.
|
||||
|
||||
### Execution graph (LangGraph)
|
||||
|
||||
`app/workflows/execution_graph.py` wires the nodes in `app/nodes/execution_nodes.py`, and the graph compiles once at startup with the configured checkpointer: `SqliteSaver` locally and in tests, `PostgresSaver` in production. The Execution id is the LangGraph `thread_id`.
|
||||
|
||||
**State (`ExecutionState`):**
|
||||
- `execution_id`, `session_id`, `workflow_request`, `mode: "interactive" | "pre_approved"`, `allow_cloud_read: bool | None`
|
||||
- `ledger` (serialisable), `deliverables: {kind: {content, attachments, feedback[], revisions}}`
|
||||
- `conversation[]` (user ↔ Orchestrator turns only), `pending_questions[]`, `pending_delegations[]`
|
||||
- `budget_exhausted: {role, summary} | None`
|
||||
|
||||
**Nodes and edges:**
|
||||
|
||||
```
|
||||
START → orchestrator_turn
|
||||
orchestrator_turn ──(delegations)──────────> specialist_task × N (LangGraph Send, parallel)
|
||||
orchestrator_turn ──(questions/approval)───> await_user (interrupt)
|
||||
orchestrator_turn ──(finish)───────────────> finalize → END
|
||||
specialist_task ───────────────────────────> orchestrator_turn (outcomes merged into ledger)
|
||||
await_user ────────────────────────────────> orchestrator_turn (resume value = user reply / approval decision)
|
||||
```
|
||||
|
||||
- **`orchestrator_turn`:** runs one Orchestrator ReAct turn through `AgentRuntime`, with Orchestrator tools bound to a working copy of the Ledger. The turn ends when the agent does one of these, and the node routes on it:
|
||||
- calls `delegate`, `ask_user`, `request_approval` or `finish`
|
||||
- runs out of budget
|
||||
- **`specialist_task`:** runs one Specialist delegation. Its task holds the role, the Deliverable kind, the Dependency contents, feedback, and the answers to its earlier `needs_input` questions. The outcome is one of:
|
||||
- `Submitted(content, attachments)`, applied to the Ledger
|
||||
- `NeedsInput(questions)`, added to `pending_questions` with the Deliverable back to `pending`
|
||||
- `BudgetExhausted(summary)`
|
||||
- **`await_user`:** `interrupt({"questions": [...]} | {"approval": {"phase": ..., "summary": ...}} | {"permission": "cloud_read"} | {"escalation": ...})`. In pre-approved mode it doesn't pause:
|
||||
- **Approvals:** granted automatically.
|
||||
- **`cloud_read` permission:** taken from the request.
|
||||
- **Questions:** answered with `"No user is available. State your assumption, record it in the Deliverable under 'Assumptions', and proceed."`
|
||||
- **Escalations:** end the Execution as `completed_with_warnings`.
|
||||
- **`finalize`:** runs after Phase 4 is `approved`. It writes files to `deliverables/executions/{execution_id}/`: the Solution guide, every Deliverable as markdown, and attachments under `terraform/`. It then records completion.
|
||||
|
||||
**Orchestrator tools** (`app/tools/execution.py`):
|
||||
|
||||
| Tool | Effect |
|
||||
|---|---|
|
||||
| `ready_work()` | Lists ready Deliverables and Phases ready for Approval. |
|
||||
| `delegate(kinds: list[str])` | Refuses any kind that isn't ready and sets it `in_progress`. Ends the turn and fans out. |
|
||||
| `ask_user(questions: list[str])` | Combines Specialist questions with its own. Ends the turn and interrupts. |
|
||||
| `request_approval(phase: str)` | Refuses unless every Deliverable in the Phase is submitted. Ends the turn and interrupts. |
|
||||
| `reopen(kind: str, reason: str)` | Applies the Revision rule, or returns an escalation. |
|
||||
| `read_deliverable(kind: str)` | Returns the current content, so the Orchestrator can summarise it for Approval. |
|
||||
| `finish()` | Refuses unless Phase 4 is approved. |
|
||||
|
||||
**Specialist tools:** `submit_deliverable(content, attachments)` (checks the contract), `needs_input(questions)`, the `SkillToolset`, and the role's tier tools. Cloud-read tools check `allow_cloud_read`. If it's `None`, the tool returns `NeedsInput(["May I read live resources in your Google Cloud project to …?"])` so the Orchestrator asks once. If it's `False`, it returns a refusal the agent must work around.
|
||||
|
||||
**Design advisor fan-out.** The `design-advisor` role runs a nested fan-out itself: it sends one task to `pillar-advisor` for each WAF pillar, in parallel, through `AgentRuntime`, and combines the results into its submission. Pillar results are not Deliverables and don't appear in the Ledger.
|
||||
|
||||
### Agent runtime interface
|
||||
|
||||
`app/adk/runtime.py`:
|
||||
|
||||
```python
|
||||
class AgentRuntime(Protocol):
|
||||
async def run(self, role: RoleSpec, task: AgentTask, tools: Sequence[ToolSpec]) -> Outcome: ...
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class RoleSpec: # parsed from agents/<role>.md
|
||||
name: str
|
||||
instructions: str # markdown body
|
||||
skills: tuple[str, ...] # Skill names from the provider bundle
|
||||
tool_tiers: tuple[str, ...] # subset of ("general", "cloud_read")
|
||||
mcp_servers: tuple[str, ...] # server ids from the provider bundle this role may use
|
||||
model: str | None # overrides provider default
|
||||
budget: int # max tool calls per run
|
||||
|
||||
Outcome = Submitted | NeedsInput | BudgetExhausted | TurnEnded # TurnEnded carries the Orchestrator's ending tool call
|
||||
```
|
||||
|
||||
- **`ToolSpec`:** framework-neutral (name, description, JSON schema, async callable). `adk_runtime.py` builds each agent from these pieces:
|
||||
- `ToolSpec` → ADK `FunctionTool`.
|
||||
- The role's MCP servers → ADK `McpToolset` over streamable HTTP, with `tool_filter` set to the server's read-only allowlist.
|
||||
- `SkillToolset(skills=[load_skill_from_dir(...)])` with only the role's Skills.
|
||||
- `model` wrapped in `LiteLlm`.
|
||||
- **Per run:** a fresh `InMemorySessionService` (D34).
|
||||
- **Callbacks:** a `before_tool_callback` counts tool calls against `budget` and enforces the `cloud_read` permission for *every* tool in that tier, MCP tools included.
|
||||
- **No framework types** cross this interface.
|
||||
|
||||
**Role file format** (`agents/<role>.md`):
|
||||
|
||||
```markdown
|
||||
---
|
||||
role: diagrammer
|
||||
deliverable: architecture_diagram
|
||||
upstream_task: "Phase 2, Task 2.2: Generate an architecture diagram"
|
||||
skills: [google-cloud-solution-architecture]
|
||||
tool_tiers: [general]
|
||||
mcp_servers: []
|
||||
budget: 15
|
||||
---
|
||||
You produce the architecture diagram Deliverable. Load the `google-cloud-solution-architecture` Skill and follow its Task 2.2 ...
|
||||
Submit with `submit_deliverable` once the diagram passes the Mermaid check and the user has confirmed it through `needs_input`.
|
||||
```
|
||||
|
||||
`pillar-advisor.md` is parameterised by pillar, and its `skills` value is resolved per task to the one matching `google-cloud-waf-<pillar>`.
|
||||
|
||||
### Cloud provider bundle
|
||||
|
||||
`providers/gcp.yaml`, loaded by `app/providers.py`:
|
||||
|
||||
```yaml
|
||||
name: gcp
|
||||
skills_dirs: [skills/vendor/google, skills]
|
||||
output_template: skills/vendor/google/google-cloud-solution-architecture/assets/output-template.md
|
||||
models:
|
||||
default: gemini/gemini-2.5-pro
|
||||
roles: { pillar-advisor: gemini/gemini-2.5-flash, diagrammer: gemini/gemini-2.5-flash }
|
||||
tools:
|
||||
general: [mermaid_check, terraform_fmt, terraform_validate]
|
||||
cloud_read: [terraform_plan]
|
||||
mcp_auth:
|
||||
kind: google_adc # service account / ADC bearer token; sends X-Goog-User-Project
|
||||
mcp_servers: # remote MCP servers hosted by the Cloud provider (streamable HTTP)
|
||||
developer_knowledge:
|
||||
url: https://developerknowledge.googleapis.com/mcp
|
||||
tier: general # public documentation, no customer data
|
||||
allow: [search_documents, get_documents, answer_query]
|
||||
resource_manager: { url: https://cloudresourcemanager.googleapis.com/mcp, tier: cloud_read, allow: [<read-only tools>] }
|
||||
asset_inventory: { url: https://cloudasset.googleapis.com/mcp, tier: cloud_read, allow: [...], preview: true }
|
||||
compute: { url: https://compute.googleapis.com/mcp, tier: cloud_read, allow: [...] }
|
||||
gke: { url: https://container.googleapis.com/mcp, tier: cloud_read, allow: [...] }
|
||||
cloud_run: { url: https://run.googleapis.com/mcp, tier: cloud_read, allow: [...] }
|
||||
cloud_sql: { url: https://sqladmin.googleapis.com/mcp, tier: cloud_read, allow: [...] }
|
||||
storage: { url: https://storage.googleapis.com/storage/mcp, tier: cloud_read, allow: [...] }
|
||||
pubsub: { url: https://pubsub.googleapis.com/mcp, tier: cloud_read, allow: [...] }
|
||||
iam: { url: https://iam.googleapis.com/mcp, tier: cloud_read, allow: [...] }
|
||||
monitoring: { url: https://monitoring.googleapis.com/mcp, tier: cloud_read, allow: [...] }
|
||||
network_intelligence: { url: https://networkmanagement.googleapis.com/mcp, tier: cloud_read, allow: [...], preview: true }
|
||||
role_mcp_servers:
|
||||
requirements-analyst: [resource_manager, asset_inventory, compute, gke, cloud_run, cloud_sql, storage, pubsub, iam, monitoring]
|
||||
product-selector: [developer_knowledge]
|
||||
describer: [developer_knowledge]
|
||||
design-advisor: [developer_knowledge]
|
||||
pillar-advisor: [developer_knowledge]
|
||||
validator: [iam, network_intelligence]
|
||||
```
|
||||
|
||||
**Loading the bundle.**
|
||||
- Settings select the bundle with `CLOUD_PROVIDER=gcp`. Core modules don't name a provider.
|
||||
- `role_mcp_servers` overrides the `mcp_servers` list in role files, so role files stay neutral across providers.
|
||||
- The `allow` lists are written once in increment 6: run MCP `tools/list` on each server and include only tools whose `readOnlyHint` annotation is true *and* whose names are reviewed as read-only.
|
||||
- Servers marked `preview: true` can be switched off with `MCP_ENABLE_PREVIEW=false`.
|
||||
|
||||
**Other Cloud providers** reuse the same shape:
|
||||
- **AWS:** the managed, generally available AWS MCP Server.
|
||||
- **Azure:** Azure MCP Server 2.0 runs as a *self-hosted* remote server, so its `url` points at the team's own deployment.
|
||||
|
||||
### Tools
|
||||
|
||||
- **General, local** (`app/tools/local.py`):
|
||||
- `mermaid_check`: moved from `validation_tools.validate_mermaid_diagram`.
|
||||
- `terraform_fmt` and `terraform_validate`: run the `terraform` CLI in a temp dir with `-backend=false`. There are no credentials, and the tool fails clearly if `terraform` is missing.
|
||||
- **Cloud read, local** (`app/tools/local.py`): `terraform_plan` needs ADC and `-lock=false`, and never runs `apply`.
|
||||
- **Remote MCP servers** (`app/tools/mcp.py`): the Cloud provider's own hosted servers, declared in the provider bundle and used for both discovery and grounding. They replace `GCPEnvironmentScanner` (hand-written REST calls) and the hand-rolled JSON-RPC `DeveloperKnowledgeMCPClient`, including its offline fallback knowledge base and the `data`/`documents` bug from review candidate 02. Both are deleted in increment 9.
|
||||
- `McpServerSpec(id, url, tier, allow, preview)` is framework-neutral. The ADK runtime maps each one to `McpToolset(StreamableHTTPConnectionParams(url, headers=auth), tool_filter=allow)`.
|
||||
- **Read-only in depth.** Tools outside `allow` are never offered to any agent. At startup, a server whose `tools/list` reports an allowed tool with `readOnlyHint` not true fails to load, loudly. Operators should also run the agent's identity with only viewer roles, plus Google Cloud's control that blocks read-write MCP tool use and an IAM deny policy (`docs/operations/mcp-access.md`, written in increment 6).
|
||||
- **Auth:** `google_adc` gets a bearer token from Application Default Credentials (`google.auth.default`, refreshed per call) and sends `X-Goog-User-Project`. Follows `google-adk-base-agent/app/google_mcp_client.py`, without the `gcloud` subprocess fallback.
|
||||
- **Failure:** an unreachable, disabled or unauthorised server returns a structured tool error such as `"compute MCP unavailable: API not enabled in project X"`. The agent records the gap under 'Assumptions / discovery gaps' and doesn't fail the Execution.
|
||||
- **Our tooling Skills** (`skills/cloud-discovery`, `skills/iac-validation`): short Agent Skills-compliant guides for agents.
|
||||
- `cloud-discovery`: which discovery servers answer which current-state questions (inventory first through Asset Inventory and Resource Manager, then per-product detail), and how to summarise current state.
|
||||
- `iac-validation`: when and how to run the Terraform checks.
|
||||
|
||||
### Interaction
|
||||
|
||||
**A2A** (`app/main.py`, `app/a2a_server.py`, `app/card.py`), using `a2a-sdk>=0.3` on `aiohttp` :8000, with `agent_card.json` and `/.well-known/agent.json`:
|
||||
- **Task ↔ Execution:** an A2A task is an Execution (`task.id` = `execution_id`), and `context_id` is the Session.
|
||||
- **Status updates:** `working` while nodes run.
|
||||
- **`input-required`** at every `interrupt()`. The interrupt payload goes out as a `DataPart`, with a text rendering for plain clients.
|
||||
- **User reply:** a text part becomes an answer to pending questions. A `DataPart` with `{"approval": {"phase", "decision": "approve" | "changes", "feedback"}}` or `{"permission": {"cloud_read": bool}}` resumes an Approval or permission interrupt. **Approvals are never taken from free text**, which keeps them explicit and recorded.
|
||||
- **Final state:** `completed` after `finalize`, and `failed` on unhandled errors.
|
||||
|
||||
**`POST /generate`** (existing Starlette app, pre-approved mode):
|
||||
- **Request:** `{request, session_id?, allow_cloud_read?: false}`.
|
||||
- **Response:** today's keys (`execution_id`, `session_id`, `status`, `validation_passed`, `total_loop_iterations`, `current_phase`, `artifacts{8 keys}`, `active_skills`), mapped from the final state.
|
||||
- `artifacts` maps today's 8 keys to the closest Deliverables. `source_discovery_doc` and `source_mermaid_diagram` become the current-state section of `requirements`.
|
||||
- `total_loop_iterations` = total Revisions + 1.
|
||||
- `active_skills` = the Skills loaded during the Execution.
|
||||
|
||||
The route switches to the new graph in increment 7, behind `AGENT_ENGINE=hierarchical` (default `legacy` until increment 9).
|
||||
|
||||
### Recording
|
||||
|
||||
`app/recorder.py` reuses `DatabaseManager` tables until candidate 03:
|
||||
- `workflow_executions`: one row per Execution, updated at each interrupt and at completion.
|
||||
- `adk_artifacts`: one row per Deliverable submission. Rows for earlier Revisions stay as history.
|
||||
- `orchestrator_review_logs`: one row per Ledger event. `review_status` holds the event type, `reviewer_agent` holds the role or `user`, and `feedback` holds the reason or feedback.
|
||||
- `adk_sessions`: the latest Execution summary for the Session (D9).
|
||||
|
||||
### Settings
|
||||
|
||||
Add to `app/config.py` and `.env.example`:
|
||||
- `CLOUD_PROVIDER=gcp`
|
||||
- `AGENT_ENGINE=legacy|hierarchical`
|
||||
- `ORCHESTRATOR_BUDGET=40`, `SPECIALIST_BUDGET=15`, `MAX_REVISIONS=3`
|
||||
- `CHECKPOINTER=sqlite|postgres`, `CHECKPOINT_DB_PATH=./checkpoints.db`
|
||||
- `A2A_HOST=0.0.0.0`, `A2A_PORT=8000`
|
||||
- `MCP_ENABLE_PREVIEW=true`, `MCP_QUOTA_PROJECT` (defaults to the ADC project)
|
||||
|
||||
Model API keys follow LiteLLM conventions (`GEMINI_API_KEY` / Vertex ADC).
|
||||
|
||||
### Dependencies
|
||||
|
||||
Add to `requirements.txt`:
|
||||
- `google-adk>=1.25` (Skills are Experimental: pin the exact version in the lock file you use)
|
||||
- `litellm~=1.74`
|
||||
- `a2a-sdk>=0.3`
|
||||
- `aiohttp>=3.10`
|
||||
- `langgraph-checkpoint-sqlite`
|
||||
- `langgraph-checkpoint-postgres`
|
||||
|
||||
Keep `langgraph` and upgrade it to a version with `interrupt()` and `Send`. The `terraform` CLI is added to the Dockerfile image.
|
||||
|
||||
## Testing
|
||||
|
||||
**Deterministic**, with `FakeAgentRuntime`, which replays scripted `Outcome`s and tool calls per role and task. There are no model calls and no network.
|
||||
|
||||
- **`tests/execution/test_ledger.py`** (pure):
|
||||
- Ready work respects both thresholds: same-Phase `submitted` and cross-Phase `approved`.
|
||||
- Each refusal case: `delegate` on unready work, `request_approval` with unsubmitted Deliverables, `finish` before Phase 4 is approved.
|
||||
- `reopen` cascades to everything that depends on the Deliverable and withdraws approved Phases. The cap produces an escalation.
|
||||
- Pre-approved `request_approval` grants and records `pre-approved`.
|
||||
- **`tests/execution/test_graph.py`**, with the fake runtime and `MemorySaver`:
|
||||
- **Happy path, pre-approved:** every Deliverable submitted, all 4 Phases approved, files written under `deliverables/executions/{id}/` (tmp dir).
|
||||
- **Parallel start:** after `product_selection` is submitted, one Orchestrator turn can delegate `architecture_diagram` and `design_recommendations` together, and both run.
|
||||
- **One voice:** questions from two parallel Specialists produce a single interrupt holding both.
|
||||
- **Interactive pause and resume:** an Approval interrupt stops the graph. Resuming with `approve` continues, and resuming with `changes` plus feedback reopens.
|
||||
- **Validation failure:** reopening `deployment_guidance` withdraws Phase 2's Approval, re-delegates the IaC author with the findings, and asks for Phase 2 Approval again.
|
||||
- **Budgets:** an exhausted budget hands control to the user with a summary.
|
||||
- **Cloud read:** a tool with `allow_cloud_read=None` produces one permission question. `False` makes the tool refuse.
|
||||
- **Clean Executions:** two Executions in one Session share no state.
|
||||
- **`tests/agents/test_roles.py`:** every `agents/*.md` parses, and every role maps to a Deliverable kind (or `orchestrator`/`pillar-advisor`), with Skills that exist in the provider bundle.
|
||||
- **`tests/test_vendored_skills.py`:**
|
||||
- Vendored Skills match `VENDOR.md`'s commit (by checksum).
|
||||
- Every Skill under `skills/` passes Agent Skills frontmatter rules: kebab-case `name` matching its directory, `description` ≤ 1024 chars.
|
||||
- **`tests/agents/test_adk_runtime.py`:** builds an ADK agent for one role with a stub model. It confirms that the `SkillToolset` holds only that role's Skills, that the tool list matches the role's tiers and MCP servers, and that each `McpToolset` has the server's `tool_filter`. It does not call a model.
|
||||
- **`tests/tools/test_mcp.py`:** uses a local fake MCP server over streamable HTTP, started in the test.
|
||||
- Tools outside `allow` are never exposed.
|
||||
- An allowed tool whose `readOnlyHint` isn't true makes the server fail to load.
|
||||
- A `cloud_read` MCP tool call without permission is blocked by `before_tool_callback`.
|
||||
- An unreachable server returns a structured discovery gap and doesn't raise.
|
||||
- `google_adc` headers include `X-Goog-User-Project`.
|
||||
- **`tests/test_provider_bundle.py`:** every `mcp_servers` entry has `tier` and a non-empty `allow`. `developer_knowledge` is the only `general` server. Every `role_mcp_servers` id exists.
|
||||
- **`tests/a2a/test_executor.py`:** A2A task → `input-required` on interrupt → `DataPart` approval resumes, using the fake runtime. A free-text "approve" does **not** grant.
|
||||
- **`tests/test_agent_api.py`:** the `/generate` response keys are unchanged under both `AGENT_ENGINE` values.
|
||||
|
||||
**Evaluation** (`eval/`):
|
||||
- **Harness:** runs `benchmark_cases.json` in pre-approved mode with the real `AdkRuntime`. Each case adds `scripted_answers: {question_pattern: answer}`, and the pre-approved `await_user` uses these answers before falling back to assumptions.
|
||||
- **Scoring:** existing rubric metrics, plus checks that the Solution guide has every `output-template.md` heading and that the product selection names at least one alternative with pros and cons.
|
||||
- **Not in the default test run.** It lives under `eval/` and is marked.
|
||||
|
||||
## Build increments
|
||||
|
||||
These are ordered, and each leaves the suite green. They are called *increments* so they don't clash with the glossary's **Phase**.
|
||||
|
||||
1. **Environment and baseline.**
|
||||
- Create a venv and install dependencies, plus `terraform`.
|
||||
- Run the current suite and record the baseline under `## Comments`.
|
||||
- Create the branch.
|
||||
2. **Vendored Skills and provider bundle.**
|
||||
- Add `skills/vendor/google/` at `81a31a6` with `VENDOR.md` and the licence, plus the sync script.
|
||||
- Add `providers/gcp.yaml` and `app/providers.py`.
|
||||
- Add the vendoring and frontmatter tests.
|
||||
3. **Deliverables and Ledger,** test-first: `deliverables.py`, `ledger.py`, `test_ledger.py`.
|
||||
4. **Execution graph,** test-first:
|
||||
- `runtime.py` (the interface and outcome types), `fake_runtime.py`.
|
||||
- `state.py`, `tools.py`, `graph.py`, `recorder.py`.
|
||||
- Checkpointer settings.
|
||||
- `test_graph.py`.
|
||||
5. **ADK runtime and role files:** `adk_runtime.py`, `roles.py`, all `agents/*.md`, `test_roles.py`, `test_adk_runtime.py`.
|
||||
6. **Tools and remote MCP servers:**
|
||||
- General and cloud-read local tools (`terraform` in a temp dir).
|
||||
- `app/tools/mcp.py`, `google_adc` auth and the `McpToolset` mapping.
|
||||
- **Allowlists:** run `tools/list` against each Google Cloud MCP server in a sandbox project, review the read-only tools, and write the `allow` lists into `providers/gcp.yaml`, recording the reviewed tool lists and date under `## Comments`.
|
||||
- `docs/operations/mcp-access.md`: the APIs to enable, viewer roles, and blocking read-write MCP use with IAM deny.
|
||||
- The `skills/cloud-discovery` and `skills/iac-validation` Skills.
|
||||
- The tests in `test_mcp.py` and `test_provider_bundle.py`.
|
||||
7. **Interfaces:**
|
||||
- The A2A server and executor, `agent_card.json`, `test_executor.py`.
|
||||
- `/generate` behind `AGENT_ENGINE`, and the Dockerfile exposing :8000 and :8080.
|
||||
8. **Evaluation:** scripted answers, template-heading scoring, and a real-model eval run with results recorded under `## Comments`. Proceed to 9 only when the pass rate meets the current harness threshold (≥ 80% per case).
|
||||
9. **Cleanup** (carried over from the superseded spec). **Done differently on 2026-10-06:** the engine moved into the KAB layout and the original pipeline was then deleted. See `.agents/plans/iter-03-kab-layout/`. The list below is the plan as first written:
|
||||
- **Delete:** `app/tools/gcp_scanner.py`, `app/tools/mcp_developer_knowledge.py` (replaced by remote MCP servers), `app/adk/`, `app/nodes/`, `app/states/`, `app/workflows/gcp_architecture_graph.py`, `app/skills/` (the loader and the 5 non-compliant Skills), `tests/test_graph_workflow.py`, the ADK and orchestrator tests in `tests/test_adk_architecture.py` (keeping the DB test as `tests/test_database.py`), and `test_adk_mcp_function_tools`.
|
||||
- **Fix:** remove the unreachable duplicate `return` in `routes.py`. Rename `ADK_MAX_LOOP_ITERATIONS` → removed, and delete `ADK_ENABLE_ARTIFACT_STORE`.
|
||||
- **Update:**
|
||||
- Make `AGENT_ENGINE=hierarchical` the only engine.
|
||||
- Derive `app/card.py` / `agent_card.json` capabilities from `DEPENDENCY_GRAPH` and the role files.
|
||||
- Rewrite `workflow.yaml` phases to upstream's 4 with their Deliverables.
|
||||
- Rewrite the README around the Orchestrator, Specialists, Skills and A2A.
|
||||
- **Stop** the writes to shared paths (`deliverables/{as-is,target,validation,guides}/`, `docs/*.md`, `terraform/main.tf`).
|
||||
- Push the branch.
|
||||
|
||||
## Acceptance
|
||||
|
||||
- [ ] **Upstream parity:** a pre-approved evaluation run produces a Solution guide containing every heading of the upstream `output-template.md`, and all benchmark cases pass the threshold.
|
||||
- [ ] **Single source for the workflow:** Phases, Deliverables and Dependencies are listed only in `app/workflows/deliverables.py`, and card and manifest data is derived from it (`tests/test_workflow_manifest.py` checks `workflow.yaml`).
|
||||
- [ ] **No framework types outside `app/adk/adk_runtime.py`:** `rg -n "google\.adk" app | grep -v adk_runtime.py` is empty. Nothing of the original pipeline remains: `rg -n "OrchestratorLoopAgent|compat|app\.legacy" app eval tests` is empty.
|
||||
- [ ] **Vendored Skills unchanged:** they match the `81a31a6` checksums, and every Skill under `skills/` passes the frontmatter rules.
|
||||
- [ ] **Approvals only by structured decision:** no path grants an Approval from free text (covered by tests).
|
||||
- [ ] **Nothing changes cloud resources:** no tool can run `terraform apply`, a deploy or a script (`run_skill_script` absent from the tool lists). Cloud-read tools, MCP included, are unreachable without permission.
|
||||
- [ ] **Discovery uses the provider's remote MCP servers:** current state comes from the Cloud provider's hosted MCP servers. No module under `app/` calls a cloud provider's REST API directly (`rg -n "googleapis.com/(compute|storage|run|sqladmin|pubsub)/v" app` is empty). Every exposed MCP tool is on a reviewed read-only allowlist.
|
||||
- [ ] **Deterministic suite:** every test above passes with no network access.
|
||||
- [ ] **`/generate` contract:** response keys are unchanged.
|
||||
|
||||
## Risks
|
||||
|
||||
- **Specialists submitting without asking (D32).** A Specialist might submit without getting the user's conversational OK. Mitigation: role files require confirmation through `needs_input` before `submit_deliverable`, and the evaluation checks that submissions follow a question. If it's still observed, fall back to Approval per Deliverable (the Q31 alternative).
|
||||
- **ADK Skills are Experimental.** The `SkillToolset` API may change. It's confined to `adk_runtime.py`, and Deep Agents is the planned second implementation.
|
||||
- **Parallel Specialists and rate limits.** Fan-out multiplies concurrent model calls. Cap concurrency per Execution (default 4) in `app/nodes/execution_nodes.py` (not built; `.agents/plans/iter-04-learning-and-skills/` step 5).
|
||||
- **Upstream Skill drift.** Upstream edits may assume a different workflow. Re-sync only through the script, and review the diff against `agents/*.md` and `deliverables.py`.
|
||||
- **Two frameworks in one process.** LangGraph and ADK both manage async state. Keep ADK sessions in memory per run, and never put ADK objects in graph state.
|
||||
- **Remote MCP server availability and drift.** Several servers are Preview (Asset Inventory, Network Intelligence, Billing), each needs its product API enabled in the user's project, and tool sets can change. Mitigations:
|
||||
- allowlists are reviewed, not discovered at run time
|
||||
- a changed `readOnlyHint` fails the server loudly
|
||||
- preview servers can be switched off
|
||||
- an unavailable server becomes a recorded discovery gap, not a failure
|
||||
- **Uneven hosting across Cloud providers.** AWS hosts a managed MCP server. Azure's general MCP server is self-hosted. The bundle's `url` covers both, but "hosted by the Cloud provider" isn't uniform.
|
||||
|
||||
## Comments
|
||||
|
||||
The dated entries below are history and keep the module paths of their day. Translate them with the table in `.agents/plans/README.md`.
|
||||
|
||||
### 2026-09-15 · Increment 1: environment and baseline
|
||||
|
||||
**Environment**
|
||||
- Branch `feat/solution-architect-agent` (already created and pushed, commit `4fefe0a`).
|
||||
- `.venv/` (gitignored), Python 3.12.3. Installed `requirements.txt` and `requirements-dev.txt` with no errors.
|
||||
- Resolved versions:
|
||||
- `google-adk` 2.9.0 (the spec's floor is `>=1.25`; `google.adk.skills` and `SkillToolset` import fine, and the toolset also exposes `ListSkillsTool`, `SearchSkillsTool`, `SkillRegistry` and `RunSkillScriptTool`)
|
||||
- `langgraph` 1.2.11, `langgraph-checkpoint` 4.2.0
|
||||
- `langchain-core` 1.6.3
|
||||
- `starlette` 1.6.0
|
||||
- `pytest` 9.1.1, `pytest-asyncio` 1.4.0
|
||||
- CLIs already on the machine: `terraform` 1.14.3 (`/usr/bin/terraform`), `gcloud`, `psql`.
|
||||
- The real `google-adk` is now installed, but `app.adk.compat.HAS_NATIVE_ADK` is still `False`, because compat also imports `google.adk.workflows` and `google.adk.evaluation`, which fail. The stubs stay in use, so baseline behaviour is unchanged.
|
||||
- No local PostgreSQL is running, so every `DatabaseManager` call logs a connection-refused warning and falls back to `gcp_agent_local.db`.
|
||||
|
||||
**Baseline**
|
||||
- Command: `.venv/bin/python -m pytest tests eval/test_eval_harness.py -rA`.
|
||||
- Result: **30 passed, 0 failed, 1 warning, ~37 s**. The warning is a Starlette `TestClient` deprecation (`anyio.abc.BlockingPortal`).
|
||||
|
||||
| File | Passed |
|
||||
|---|---|
|
||||
| `tests/test_adk_architecture.py` | 8/8 |
|
||||
| `tests/test_agent_api.py` | 4/4 |
|
||||
| `tests/test_artifacts.py` | 5/5 |
|
||||
| `tests/test_graph_workflow.py` | 1/1 |
|
||||
| `tests/test_mcp_developer_knowledge.py` | 5/5 |
|
||||
| `tests/test_package.py` | 2/2 |
|
||||
| `tests/test_skill_loader.py` | 3/3 |
|
||||
| `eval/test_eval_harness.py` | 2/2 |
|
||||
|
||||
Slowest tests: eval benchmark 7.3 s, then 3–4.5 s each for the orchestrator, evaluator, workflow, graph, session API and runner tests.
|
||||
|
||||
**Side effects found (fix in increment 9 or earlier if they get in the way)**
|
||||
- **New Execution folders.** Each suite run creates 6 new untracked `deliverables/executions/<uuid>/` directories. The shared-path copies are byte-identical because the templates don't vary. I removed the 12 from two runs with `git clean -fd deliverables/executions/`.
|
||||
- **Tracked bytecode.** 30 `__pycache__/*.pyc` files are tracked despite `.gitignore`, so every run dirties the tree (for example `eval/__pycache__/*.pyc`). Candidate fix: `git rm -r --cached '*/__pycache__'`.
|
||||
|
||||
### 2026-09-15 · Increment 2: vendored Skills and provider bundle
|
||||
|
||||
**Done**
|
||||
- `scripts/sync-vendored-skills.sh [<sha>]` downloads `google/skills` at a full commit sha. It replaces `skills/vendor/google/` wholesale with the 7 Skills plus the upstream `LICENSE` (there's no `NOTICE` upstream), then writes `SHA256SUMS` and `VENDOR.md`. I ran it at `81a31a6e4300425598a69fd96c8e843c947ae308` and diffed the result against the upstream tarball: identical.
|
||||
- `app/agent_skills.py`:
|
||||
- `read_skill` checks one Skill against the Agent Skills specification, and `discover_skills` indexes a set of directories.
|
||||
- It enforces the name rules (1–64 characters, lowercase, single hyphens, matches the directory) and the description rules (1–1024 characters). It also checks `compatibility` (≤ 500 characters), `metadata` (string → string), and that `license`/`allowed-tools` are strings.
|
||||
- It rejects unknown fields, rejects duplicate names across directories, and only looks at immediate child directories.
|
||||
- `app/providers.py`: `load_provider(name, root)` returns a `ProviderBundle` (skills index, output template, `ModelConfig.for_role`, tool tiers, `mcp_auth`, `McpServerSpec`s, `role_mcp_servers`, `mcp_servers_for_role(role, include_preview)`). It validates tiers, https URLs, the `allow` list and role → server references.
|
||||
- `providers/gcp.yaml` holds the bundle from the spec, with **every MCP `allow` list empty** (so no tools are exposed) until the increment 6 review.
|
||||
- Settings: `CLOUD_PROVIDER=gcp` and `MCP_ENABLE_PREVIEW=true` in `app/config.py` and `.env.example`.
|
||||
- Tests:
|
||||
- `tests/test_agent_skills.py`: 17 tests.
|
||||
- `tests/test_vendored_skills.py`: 3 tests. A test run with a vendored file edited showed the checksum test failing, as intended.
|
||||
- `tests/test_providers.py`: 15 tests.
|
||||
- Full suite: **65 passed** (30 baseline + 35 new), same single warning. `ruff check`, `ruff format` and `mypy` are clean on the new modules.
|
||||
|
||||
**Deviations from the spec text**
|
||||
- **Checksums file.** Checksums live in `skills/vendor/google/SHA256SUMS`, which `VENDOR.md` references, not inside `VENDOR.md` itself. It's easier to diff and works with `sha256sum -c`.
|
||||
- **Where `McpServerSpec` lives.** It's in `app/providers.py`, because it's bundle configuration. `app/tools/mcp.py` (increment 6) will import it and add the runtime behaviour: `readOnlyHint` checks, auth and the ADK mapping.
|
||||
- **Test file name.** The spec named a `tests/test_provider_bundle.py`; this increment uses `tests/test_providers.py`. Increment 6 adds its assertions there, including non-empty `allow` lists once they're reviewed.
|
||||
- **Strict frontmatter.** The validator rejects unknown fields. As a result the 5 legacy `app/skills/*/SKILL.md` fail (the custom `phase:` key), which confirms ADR-0002's consequence. They're out of the bundle's `skills_dirs` and get deleted in increment 9.
|
||||
|
||||
**Still to check**
|
||||
- The default model ids (`gemini/gemini-2.5-pro`, `gemini/gemini-2.5-flash`) come from the spec and haven't been checked against models currently available. Confirm them in increment 5, when LiteLLM is wired.
|
||||
|
||||
### 2026-09-15 · Increment 3: Deliverables and Ledger
|
||||
|
||||
**Done (test-first)**
|
||||
- `app/execution/deliverables.py`: `PhaseId`, `PHASE_ORDER`, `DeliverableKind`, `DeliverableSpec`, `DEPENDENCY_GRAPH` (the table above), `deliverables_in`, and `check_submission(kind, content, attachments) -> missing`.
|
||||
- `app/execution/ledger.py`: a pure `Ledger`.
|
||||
- Queries: `ready_work`, `phases_ready_for_approval`, `dependencies_met`, `can_finish`.
|
||||
- Work: `start`, `submit`, `release`.
|
||||
- Approvals: `request_approval`, `approve`, `request_changes`.
|
||||
- Revisions: `reopen`.
|
||||
- Persistence: `to_dict` / `from_dict`.
|
||||
- Tests:
|
||||
- `tests/execution/test_deliverables.py`: 12 tests.
|
||||
- `tests/execution/test_ledger.py`: 25 tests.
|
||||
- Full suite: **102 passed**. `ruff` and `mypy` are clean.
|
||||
- **Checking the tests bite.** I broke each of these in the code on purpose, and in each case at least one test failed:
|
||||
- cross-Phase dependencies accepting *submitted*
|
||||
- no cascade on reopen
|
||||
- the revision cap off by one
|
||||
- pre-approved mode not granting approval
|
||||
|
||||
A fifth mutation, `release` not bumping the attempt, survived. It showed the extra increments were dead code, so I removed them. Attempts now change only in `start`, and a test covers a late submission from a superseded attempt.
|
||||
|
||||
**Added to or tightened from the spec text**
|
||||
- **Attempts.** `start` returns an attempt number per Deliverable, and `submit`/`release` must present the current one. This protects against late results from Specialists running in parallel after their work was released or reset by a Revision. The spec had no such token.
|
||||
- **More event types.** Beyond the spec's list: `started`, `released`, `reset` (a dependent that went back to pending) and `approval_withdrawn`.
|
||||
- **Return values.** `reopen` returns `ReopenResult(reset, withdrawn_approvals, escalation)`. `reset` lists only Deliverables whose status actually changed. Invalid requests raise `LedgerRefusal` and change nothing, and at the cap `reopen` records `escalated` and changes nothing. `override_cap=True` covers the user deciding to revise past the cap.
|
||||
- **Changes on approval.** `request_changes(phase, feedback)` returns the Phase to `open` and records the feedback, but doesn't reopen Deliverables itself. The Orchestrator reopens the specific ones with `reopen`.
|
||||
- **Dependent feedback.** A dependent that is reset gets a feedback note (`Dependency X was revised: <reason>`), so its next Specialist run knows why.
|
||||
- **Single source for progress.** The Ledger owns each Deliverable's status, attempts, revisions and feedback. The Execution state (increment 4) holds only content and attachments, not the `feedback[]`/`revisions` fields the spec's state sketch showed.
|
||||
- **Contracts,** matched against headings after stripping numbering, case and trailing punctuation, by exact match or a space-separated suffix. That way "4.1. Google Cloud products and features mapping" satisfies "Products and features mapping", but "Non-functional requirements" doesn't satisfy "Functional requirements".
|
||||
- `requirements`: functional and non-functional requirements, current state, dependencies.
|
||||
- `product_selection`: products and features mapping.
|
||||
- `design_recommendations`: the 6 pillar headings.
|
||||
- `deployment_guidance`: prerequisites and step-by-step instructions, plus attachments `terraform/main.tf` and `terraform/variables.tf`.
|
||||
- `validation_results`: deployment dry-run, architecture and policy analysis.
|
||||
- `solution_guide`: the template's 8 top-level sections.
|
||||
- `architecture_diagram`: attachment `architecture.mmd`.
|
||||
- `technical_decomposition` and `architecture_description`: non-empty content only.
|
||||
|
||||
### 2026-09-15 · Increment 4: Execution graph
|
||||
|
||||
**Done (test-first)**
|
||||
- `app/agents/runtime.py`: the `AgentRuntime` protocol, `RoleSpec`, `AgentTask`, `ToolSpec`/`ToolResult`, and the outcomes `Submitted | NeedsInput | BudgetExhausted | Stopped | TurnEnded`.
|
||||
- `app/agents/fake_runtime.py`: `FakeAgentRuntime`, which replays scripted tool calls per role through the real `ToolSpec`s, enforces `RoleSpec.budget`, and records every run (task, tools offered, tool messages, outcome).
|
||||
- `app/execution/state.py`: `ExecutionState` (JSON-compatible). `outcomes` uses an append reducer, so parallel Specialist tasks never write the Ledger.
|
||||
- `app/execution/tools.py`:
|
||||
- `OrchestratorToolbox`: `ready_work`, `delegate`, `ask_user`, `request_approval`, `reopen`, `read_deliverable`, `finish`.
|
||||
- `specialist_tools`: `submit_deliverable` (checks the contract and refuses unsafe attachment paths) and `needs_input`, plus the role's extra tools.
|
||||
- `gate_cloud_read`: allow / refuse / ask permission.
|
||||
- `app/execution/graph.py`: `orchestrator_turn` → `Send` × N `specialist_task` → `orchestrator_turn`; `await_user` (`interrupt`); `finalize`; `end_with_warnings`.
|
||||
- `app/execution/engine.py`: **`ExecutionEngine.start(request, session_id, pre_approved, allow_cloud_read)` / `resume(execution_id, reply)` / `interaction(execution_id)` → `Interaction(status, prompt, state)`**. This is the one interface for A2A, `/generate` and the eval harness. The tests use only it.
|
||||
- `app/execution/recorder.py`: the `ExecutionRecorder` protocol with `InMemoryRecorder` and `DatabaseRecorder` (the existing tables via `asyncio.to_thread`).
|
||||
- `app/execution/checkpointing.py`: `open_checkpointer(settings)` for `memory | sqlite | postgres`.
|
||||
- Settings `ORCHESTRATOR_BUDGET`, `SPECIALIST_BUDGET`, `MAX_REVISIONS`, `MAX_ORCHESTRATOR_TURNS`, `CHECKPOINTER` (default `sqlite`) and `CHECKPOINT_DB_PATH`, plus `.env.example`. `requirements.txt`: `langgraph>=1.2`, `langgraph-checkpoint-sqlite`, `langgraph-checkpoint-postgres`, `psycopg[binary]`.
|
||||
- Tests:
|
||||
- `tests/execution/test_engine.py`: 17 tests covering the pre-approved happy path with written files, parallel start, dependency context, refusal messages, incomplete submissions, Approval pause/resume, free text never approving, changes → Revision → re-approval, one voice, Revision after a validation failure, pre-approved escalation, Orchestrator and Specialist budgets, cloud-read ask/grant/deny, clean Executions, and resuming from a durable SQLite checkpoint.
|
||||
- `tests/execution/test_recording.py`: 2 tests covering `DatabaseRecorder` against a temp SQLite database, and the checkpointer factory.
|
||||
- Full suite: **121 passed**. `ruff` and `mypy` are clean on `app/agents` and `app/execution`.
|
||||
- **Checking the tests bite.** I broke each of these in the code on purpose, and each break failed at least one test:
|
||||
- no cloud-read gate
|
||||
- permission never asked
|
||||
- Specialist questions dropped
|
||||
- submission contract unchecked
|
||||
|
||||
**Added to or changed from the spec text**
|
||||
- **Engine and file names.** There's a new `app/execution/engine.py` facade, and tests live in `test_engine.py`/`test_recording.py`, not `test_graph.py`. The graph is an internal detail behind the engine.
|
||||
- **`Stopped` outcome.** An agent that ends without a turn-ending tool is `Stopped`. Tools end a run by returning `ToolResult(outcome=...)`, so ending can depend on the result: pre-approved `request_approval` doesn't end the turn, and refusals never do. Engine-owned tools use `tier="execution"`.
|
||||
- **Prompt and reply shapes.**
|
||||
- `Interaction.prompt` is `{"questions": [{"from": <kind|orchestrator>, "question"}]}`, `{"approval": {"phase", "summary", "deliverables"}}` or `{"permission": {"tier", "requested_by"}}`.
|
||||
- `resume` takes `{"reply": str}`, `{"approval": {"phase", "decision": approve|changes, "feedback"}}` or `{"permission": {"cloud_read": bool}}`.
|
||||
- An approval reply that isn't structured goes into the conversation and never grants.
|
||||
- **Single writer.** Specialist outcomes are applied by the next `orchestrator_turn` in graph order, using `outcomes_applied`. A superseded result (stale attempt) is discarded and noted to the Orchestrator.
|
||||
- **Specialist problems as questions.** A Specialist that runs out of budget or stops is released and relayed as a question from its Deliverable, keeping one voice. A permission `NeedsInput` becomes a single permission prompt, not a question.
|
||||
- **Pre-approved mode.** `allow_cloud_read=None` becomes `False`. An escalation, or an Orchestrator that can't continue, ends as `completed_with_warnings` with no files written.
|
||||
- **Loop guard.** `MAX_ORCHESTRATOR_TURNS` (default 100) bounds loops, and the LangGraph `recursion_limit` is raised to 10 000.
|
||||
- **Conversation.** It records the Orchestrator's rendered prompts as well as user replies.
|
||||
- **Session name.** `DatabaseRecorder` session rows use `agent_name="solution-architect"`.
|
||||
- **Deferred to increment 5:** the design advisor's pillar fan-out tool, which needs the `pillar-advisor` role file.
|
||||
- **Not tested:** `AsyncPostgresSaver` against a real PostgreSQL (none runs locally). The import and wiring are in place.
|
||||
|
||||
### 2026-09-16 · Increment 5: ADK runtime and role files
|
||||
|
||||
**Done (test-first)**
|
||||
- **Role files** `agents/*.md` (11): `orchestrator`, the 9 Specialists and `pillar-advisor`, plus `agents/partials/specialist-protocol.md`, which every Specialist includes. Each Specialist file names its Deliverable, the Skill task it covers, its constraints and its required headings. The shared protocol covers context fields, questions through `needs_input`, confirming a draft with the user before submitting (or recording assumptions when pre-approved), and resubmitting until the contract passes.
|
||||
- `app/agents/roles.py`: `load_roles(agents_dir, bundle, orchestrator_budget, specialist_budget, include_preview_mcp)`. It validates the file name against the role, the deliverable against `DEPENDENCY_GRAPH`, the tool tiers, the budget, the includes, a non-empty body, unknown fields, and missing or unexpected roles.
|
||||
- `app/agents/adk_runtime.py`: `AdkAgentRuntime(skill_dirs, model_factory)`, the only module importing `google.adk`.
|
||||
- **Per run:** a fresh `LlmAgent`, an in-memory session and a `Runner`.
|
||||
- **Tools:** each `ToolSpec` is adapted to a `BaseTool` with a JSON-schema declaration, and a `SkillToolset` holding only the role's Skills is filtered to `list_skills`/`load_skill`/`load_skill_resource`.
|
||||
- **Instructions:** passed as a callable, so role text is never state-templated.
|
||||
- **Stopping:** a `before_tool_callback` budget counts every tool call, including Skill tools. Tool calls within a run are serialised, the first outcome ends the run (later calls in the same batch are refused), and a final text with no outcome becomes `Stopped(text)`.
|
||||
- **Model:** `default_model_factory` wraps `role.model` in `LiteLlm`.
|
||||
- `app/execution/pillars.py`: the `consult_pillar_advisors(brief, pillars?)` tool, which runs one `pillar-advisor` per pillar in parallel through `AgentRuntime`, each scoped to its pillar Skill with a `submit_advice` tool. One failed advisor is reported without losing the others. `app/execution/toolkit.py`: `make_tool_factory(runtime, roles, pillar_skills)` gives the tool to the design advisor only; increment 6 extends it.
|
||||
- `app/execution/deliverables.py`: `inputs_of(kind)` gives a Specialist every Deliverable of earlier Phases plus everything it depends on within its own Phase. Before this, the packager's context lacked `architecture_description`, which nothing depends on.
|
||||
- `providers/gcp.yaml` and `app/providers.py`: `role_skills` and `pillar_skills`, both validated against the Skills index. Models are now `gemini/gemini-pro-latest` by default and `gemini/gemini-flash-latest` for the pillar advisor and diagrammer.
|
||||
- `requirements.txt`: `google-adk[extensions]==2.9.0`, pinned exactly because Skills are Experimental. Its extras bring LiteLLM (installed 1.101.0).
|
||||
- Tests:
|
||||
- `tests/agents/test_roles.py`: 14 tests.
|
||||
- `tests/agents/test_adk_runtime.py`: 12 tests with a scripted `BaseLlm`, no network.
|
||||
- `tests/agents/test_adk_engine.py`: 1 test running `ExecutionEngine` on the ADK runtime with the real role files and bundle. A Specialist question reaches the user and the answer reaches the next run.
|
||||
- `tests/execution/test_pillars.py`: 6 tests.
|
||||
- Plus provider and deliverable tests.
|
||||
- Full suite: **158 passed**. `ruff` and `mypy` are clean. The 5 warnings are ADK and Starlette deprecations.
|
||||
- **Checking the tests bite.** I broke each of these in the code on purpose, and each break failed at least one test:
|
||||
- every Skill loadable by every role
|
||||
- no budget
|
||||
- no early stop after an outcome
|
||||
- templated instructions
|
||||
- both turn-ended guards removed at once
|
||||
|
||||
Either guard alone suffices under ADK 2.9's sequential callback order; both are kept as defence in depth.
|
||||
|
||||
**Deviations from the spec text**
|
||||
- **Role frontmatter is provider-neutral.** Role files carry only `role`, `deliverable`, `tool_tiers`, `budget` and `includes`. Skills (`role_skills`, `pillar_skills`), MCP servers and models come from the provider bundle, so no role file names a Google Cloud Skill (a test checks this). `upstream_task` was dropped: role bodies describe the Skill task in neutral words.
|
||||
- **Model ids.** They're LiteLLM `-latest` aliases, not the spec's `gemini-2.5-*` ids, which are older than LiteLLM's current Gemini 3.x entries.
|
||||
- **LiteLLM version.** `litellm` comes from `google-adk[extensions]` (ADK requires ≥ 1.84), not `litellm~=1.74`.
|
||||
- **Pillar fan-out** is a tool on the design advisor, not code inside the runtime.
|
||||
|
||||
**Deferred**
|
||||
- **To increment 6:** mapping `RoleSpec.mcp_servers` to ADK MCP toolsets (`McpToolset` needs the `mcp` extra, not installed) and supplying local tools by `tool_tiers`. Both are declared and loaded now, but the runtime doesn't use them yet.
|
||||
- **Not yet run against a real model:** no API key was used, so role-file quality is unproven until increment 8's evaluation.
|
||||
- **Model API errors propagate** from `AgentRuntime.run` and fail the graph step, leaving the Execution at its last checkpoint. Decide in increment 7 whether to retry, surface as a question, or fail the A2A task.
|
||||
|
||||
### 2026-09-16 · Increment 6: tools and remote MCP servers
|
||||
|
||||
**Done (test-first)**
|
||||
- `app/tools/mcp.py`:
|
||||
- **Client.** `McpClient` connects over streamable HTTP with the MCP Python SDK (`mcp` 1.30), one session per operation.
|
||||
- **Catalog.** `McpCatalog.load(servers, auth)` turns each server's allowlisted tools into framework-neutral `ToolSpec`s named `<server>__<tool>`, with the server's tier. Loading raises `McpConfigError` when an allowlisted tool isn't `readOnlyHint: true`. An allowlisted tool the server no longer offers is recorded in `gaps`. An unreachable server becomes a `<server>__unavailable` tool that returns a discovery gap, and a failed call returns a discovery gap instead of raising. Results are truncated at 20k characters. Servers with an empty allowlist are never contacted.
|
||||
- **Auth.** `NoAuth`, `StaticHeadersAuth`, and `GoogleAdcAuth` (ADC bearer token refreshed off the event loop, plus `X-Goog-User-Project`), chosen by `auth_from_config`.
|
||||
- `app/tools/local.py`:
|
||||
- **Mermaid.** `mermaid_check` does a structural check (diagram type, brackets per line, quotes respected); it doesn't render.
|
||||
- **Terraform.** `TerraformRunner` runs `fmt`, `validate` (`init -backend=false`) and `plan` (`-lock=false -input=false`) in a temporary copy, and never builds `apply`/`destroy`. It refuses unsafe file names and variable names, and handles a missing binary and timeouts.
|
||||
- **Registry.** `LOCAL_TOOLS` and `local_tools(names, runner)` build tools by name with their tier.
|
||||
- `app/execution/toolkit.py`: `make_tool_factory(runtime, roles, pillar_skills, local_tools=, catalog=)` gives each role its named local tools and its bundle MCP servers' tools. Pillar advisors get general-tier MCP tools (Developer Knowledge) inside the consultation. Cloud-read gating still happens per Execution in `specialist_tools`, so MCP tools are gated exactly like local ones.
|
||||
- **Allowlists reviewed 2026-09-16** against the live `tools/list` of all 12 Google Cloud MCP servers. `tools/list` works without credentials; no tool was called. The snapshot is at `providers/reviews/gcp-mcp-tools.json`, made with `scripts/list-mcp-tools.py gcp --json --no-auth`.
|
||||
- **Allowed:** inventory and configuration metadata only, every tool read-only. That's 42 tools across the 12 servers, listed in `providers/gcp.yaml`.
|
||||
- **Excluded although read-only:** Cloud SQL `execute_sql_readonly`, Storage `read_object`/`read_text`/`list_objects`, GKE `get_k8s_resource`/`describe_k8s_resource` (can return Secrets), Asset Inventory `get_iam_policy_analysis_status`, and all write tools.
|
||||
- **Tests** check every allowed tool against the snapshot and keep the risky tools excluded.
|
||||
- `docs/operations/mcp-access.md` covers the APIs to enable, a dedicated service account (`roles/mcp.toolUser` plus viewer roles), the IAM deny policy on `mcp.googleapis.com/tools.call` where `mcp.googleapis.com/tool.isReadOnly` is false, ADC and the quota project, and the allowlist review procedure.
|
||||
- Tooling Skills `skills/cloud-discovery` and `skills/iac-validation` (both pass the Agent Skills validator), added to `role_skills` for the requirements analyst, IaC author and validator.
|
||||
- Settings `MCP_QUOTA_PROJECT`, `MCP_TIMEOUT_SECONDS`, `TERRAFORM_BINARY`, `TERRAFORM_TIMEOUT_SECONDS`, `TF_PLUGIN_CACHE_DIR` in `app/config.py` and `.env.example`. `pytest.ini`: `asyncio_mode = auto`, so async tests and fixtures need no marks.
|
||||
- Tests:
|
||||
- `tests/tools/test_mcp.py`: 13 tests against a real fake MCP server (FastMCP over streamable HTTP on its own thread).
|
||||
- `tests/tools/test_local.py`: 13 tests, running the real `terraform` CLI with a provider-free configuration, so no network.
|
||||
- Role, provider and tool-factory additions.
|
||||
- Full suite: **189 passed**. `ruff` and `mypy` are clean on the new modules.
|
||||
- **Checking the tests bite.** I broke each of these in the code on purpose, and each break failed at least one test:
|
||||
- read-only check off
|
||||
- allowlist ignored
|
||||
- no truncation
|
||||
|
||||
**Deviations from the spec text**
|
||||
- **Where MCP tools are built.** MCP tools are `ToolSpec`s built by our own client, not ADK `McpToolset` in `adk_runtime.py`. This keeps the framework boundary: a Deep Agents runtime, the fake runtime and the cloud-read gate all use the same tools. As a result, the `before_tool_callback` needs no MCP-specific permission check.
|
||||
- **Tools named per role.** Role files name their local tools (`tools: [terraform_validate, terraform_plan]`), not tool tiers; a tool's tier comes from its definition. Tiers alone would have given the requirements analyst `terraform_plan` and the diagrammer the Terraform tools.
|
||||
- **File layout.** Local tools live in one module, `app/tools/local.py`, not `general/` and `cloud_read/` directories.
|
||||
- **Test file names.** Allowlist tests are in `tests/test_providers.py`, not `test_provider_bundle.py`.
|
||||
|
||||
**Open**
|
||||
- **Expired credentials.** The Application Default Credentials on the dev machine have expired (`invalid_grant`), so no authenticated MCP tool call has been made. Run `gcloud auth application-default login` before increment 8's evaluation.
|
||||
- **ADK warns about Gemini via LiteLLM.** The warning recommends native `Gemini` models for `gemini/*`. Decide in increment 8 whether `default_model_factory` should use ADK's native Gemini class for Gemini ids and keep LiteLLM for other providers.
|
||||
- **Legacy package import.** `app/tools/__init__.py` still imports the legacy modules (LangChain tools, scanner), so `app.tools.local` and `app.tools.mcp` pull them in until increment 9.
|
||||
|
||||
**Live check (2026-09-16, after `gcloud auth application-default login` and enabling `developerknowledge.googleapis.com` in `shining-hydra-367716`)**
|
||||
- **Authentication.** ADC authentication works and sends `X-Goog-User-Project: shining-hydra-367716`.
|
||||
- **Calls succeed.** All three allowlisted Developer Knowledge tools succeed through `McpCatalog`: `search_documents`, `get_documents` and `answer_query`.
|
||||
- **API propagation.** A call just after the API was enabled returned 403 and became a discovery gap, which confirms the gap path against the real endpoint. The gap message shows only `403 Forbidden`, because the SDK doesn't expose the response body; Google's reason (for example "API has not been used… or it is disabled") is lost.
|
||||
- **Truncation.** `search_documents` and `get_documents` both hit the 20k-character limit, cutting their JSON mid-document. Revisit the limit, or summarise, during increment 8's evaluation.
|
||||
- **No customer-resource reads yet.** No tool that reads project resources has been called. Among the discovery APIs, only `compute` and `cloudasset` are enabled in this project.
|
||||
|
||||
### 2026-09-16 · Increment 7: interfaces
|
||||
|
||||
**Done (test-first where it could be)**
|
||||
- `app/assembly.py`: `open_assembly(settings, runtime=, recorder=, output_root=)` is the composition root. It loads the provider bundle and roles (budgets and preview MCP servers from settings), the ADK runtime by default, the `McpCatalog` for the servers the roles use (skipped when `MCP_ENABLED=false`), the Terraform runner and local tools, the tool factory, the configured checkpointer and a `DatabaseRecorder`, and yields `Assembly(engine, bundle, roles, mcp_gaps)`.
|
||||
- `app/a2a/executor.py`: `SolutionArchitectExecutor` maps A2A tasks onto Executions: task id = `execution_id`, context id = Session.
|
||||
- **New task:** enqueues the Task, then `engine.start`. `pre_approved` and `allow_cloud_read` come from message or request metadata.
|
||||
- **Follow-up message:** `engine.resume`. A data part with `approval` or `permission` is the structured reply; anything else is `{"reply": text}`, so free text never approves.
|
||||
- **Input required:** a text rendering of the prompt plus a `{"prompt": ...}` data part.
|
||||
- **Completed:** artifacts for the solution guide and every attachment (Terraform files, `architecture.mmd`), then a completion message. `completed_with_warnings` lists the warnings.
|
||||
- **Engine exception:** the task fails with the error text.
|
||||
- **Cancel:** cancels the A2A task only; the checkpoint remains.
|
||||
- `app/a2a/card.py`: the agent card is built from settings and `PHASE_ORDER`/`deliverables_in`, with a JSON-RPC interface at `/a2a`.
|
||||
- `app/a2a/server.py`: `create_app(settings, assembly_factory)` is a Starlette app. The lifespan opens the assembly and mounts `a2a-sdk` JSON-RPC routes at `/a2a` with **v0.3 compatibility enabled**, and serves the card at `/.well-known/agent-card.json` and the legacy `/.well-known/agent.json`. `/health` reports `mcp_discovery_gaps`. **`POST /generate`** runs pre-approved (`allow_cloud_read` defaults to false), returns 400 without `request` and 500 with the error on failure. Run it with `python -m app.a2a.server` (default `A2A_HOST`/`A2A_PORT` 0.0.0.0:8000).
|
||||
- `app/execution/presentation.py`: `describe_prompt`, whose approval and permission text shows the exact data reply, and `to_generate_response`. The legacy keys map as follows:
|
||||
- `source_discovery_doc`: the requirements' `Current state` section
|
||||
- `source_mermaid_diagram`: `None`
|
||||
- `architecture_doc`: the architecture description
|
||||
- `mermaid_diagram`: `architecture.mmd`
|
||||
- `terraform_code`: `terraform/main.tf`
|
||||
- `validation_passed`: status `completed`
|
||||
- `total_loop_iterations`: revisions + 1
|
||||
- `active_skills`: the Skills of the roles whose Deliverables were submitted
|
||||
- also adds `warnings`
|
||||
- **Engine changes.**
|
||||
- `start(execution_id=)` accepts a caller-chosen id and refuses a duplicate.
|
||||
- **Model errors (the increment 5 open item):** an exception in a Specialist run becomes `Stopped("it failed with …")`, relayed to the user as a question from that Deliverable. An exception in the Orchestrator propagates, which fails the A2A task or returns 500 from `/generate`, leaving the Execution at its last checkpoint.
|
||||
- Settings `MCP_ENABLED`, `A2A_HOST`, `A2A_PORT` and `A2A_PUBLIC_URL`. Requirements: `mcp>=1.24,<2` (missing from increment 6's commit) and `a2a-sdk[http-server]>=1.1,<2`. `pytest.ini` filters `a2a-sdk`'s protobuf `label()` deprecation noise.
|
||||
- `Dockerfile`: the builder installs Terraform 1.14.3, verified against HashiCorp's SHA256SUMS. The image copies `agents/`, `providers/` and `skills/` and exposes 8000 as well as 8080. The `CMD` is still the legacy app until increment 9.
|
||||
- Tests:
|
||||
- `tests/a2a/test_server.py`: 10 tests over JSON-RPC. A question pauses the task and a text reply resumes it. Approval counts only as data. A pre-approved task completes with guide and code artifacts. An engine failure fails the task. A v0.3 `message/send` client is accepted. `/generate` keeps the legacy keys, and returns 400 without a request. Health shows gaps.
|
||||
- `tests/test_assembly.py`: 2 tests.
|
||||
- `tests/execution/test_presentation.py`: 3 tests.
|
||||
- Two engine tests: caller-chosen id, and Specialist failure relayed.
|
||||
- Full suite: **206 passed**. `ruff` and `mypy` are clean.
|
||||
- **Live smoke test.** `python -m app.a2a.server` started with the real assembly: ADK runtime, live authenticated `tools/list` on all 12 Google Cloud MCP servers with **no gaps**, and memory checkpointer. `/health` and the agent card responded. No message was sent, so no model was called.
|
||||
|
||||
**Deviations from the spec text**
|
||||
- **Server stack.** The A2A server uses the Starlette routes from `a2a-sdk` 1.1 (A2A 1.0, with v0.3 compatibility), not `aiohttp`, matching `google-adk-base-agent`, which also serves A2A on Starlette. Platform base agents pin `a2a-sdk>=0.3`; the v0.3 compatibility keeps those clients working.
|
||||
- **Where `/generate` lives.** `/generate` for the new engine is served by the A2A app, not behind an `AGENT_ENGINE` switch in the legacy app. The legacy app on :8080 stays unchanged until increment 9 retires it, so there's no `AGENT_ENGINE` setting.
|
||||
- **No static card file.** There's no `agent_card.json`; the card is built at startup from settings and the graph.
|
||||
- **Test file names.** A2A tests are HTTP-level (`tests/a2a/test_server.py`), not executor-level `test_executor.py`.
|
||||
|
||||
**Open**
|
||||
- **Card URL.** The card advertises `A2A_PUBLIC_URL`, or `http://A2A_HOST:A2A_PORT`. Set `A2A_PUBLIC_URL` in any deployment, because the fallback shows `0.0.0.0`.
|
||||
- **Task store.** The A2A task store is in memory, so tasks are lost on restart while Execution checkpoints survive. Use `a2a-sdk`'s database task store with Postgres in production.
|
||||
- **Docker build unverified.** No Docker on the dev machine.
|
||||
- **Disabled APIs aren't gaps at startup.** `tools/list` works whether or not a product's API is enabled, so a disabled API shows up only when a tool is called, not in `/health`.
|
||||
21
CLAUDE.md
Normal file
21
CLAUDE.md
Normal file
@@ -0,0 +1,21 @@
|
||||
# CLAUDE.md
|
||||
|
||||
## Direction
|
||||
|
||||
Before designing or restructuring agent code, read `docs/adr/`. ADR-0002 is the anchor: behaviour lives in Agent Skills (agentskills.io format) loaded by the framework's own skill runtime, and this repo builds the tooling around them. Google Cloud is the first Cloud provider, not the only one, so cloud-specific knowledge belongs in Skills and tooling, never in the agent's core. Reach cloud environments and cloud documentation through the provider's hosted remote MCP servers, not hand-written API clients.
|
||||
|
||||
Plans and history live in `.agents/plans/`, one directory per iteration. Before changing anything under `app/`, `agents/`, `skills/` or `eval/`, read `.agents/plans/README.md`: it lists each iteration's status and maps the module paths that specs and ADRs written before the KAB layout move still use. When you finish a step, record it there as that README describes. The design spec for iteration 2 is `.scratch/solution-architect-agent/spec.md`.
|
||||
|
||||
## Agent skills
|
||||
|
||||
### Issue tracker
|
||||
|
||||
Issues and specs live as local markdown files under `.scratch/<feature-slug>/`. See `docs/agents/issue-tracker.md`.
|
||||
|
||||
### Triage labels
|
||||
|
||||
Default five-role vocabulary (`needs-triage`, `needs-info`, `ready-for-agent`, `ready-for-human`, `wontfix`), recorded as a `Status:` line in each issue file. See `docs/agents/triage-labels.md`.
|
||||
|
||||
### Domain docs
|
||||
|
||||
Single-context: one `CONTEXT.md` and `docs/adr/` at the repo root. See `docs/agents/domain.md`.
|
||||
101
CONTEXT.md
Normal file
101
CONTEXT.md
Normal file
@@ -0,0 +1,101 @@
|
||||
# Cloud Solution Architecture
|
||||
|
||||
Turns a request for a cloud workload into a reviewed solution architecture: requirements, a target design with diagram and infrastructure-as-code, validation results, and a packaged guide. Google Cloud is the first Cloud provider.
|
||||
|
||||
## Language
|
||||
|
||||
### Running the workflow
|
||||
|
||||
**Workflow request**:
|
||||
The free-text description of the workload a caller wants architected; the opening input to an Execution.
|
||||
_Avoid_: prompt, query, request summary
|
||||
|
||||
**Execution**:
|
||||
One solution-architecture engagement for a single Workflow request. It lasts from the first request to an approved Solution guide, and may span many user turns. An Execution starts clean, unless it is a Change request.
|
||||
_Avoid_: run, job, workflow execution
|
||||
|
||||
**Session**:
|
||||
A caller-supplied grouping of Executions. A Session never feeds earlier outputs into a later Execution.
|
||||
_Avoid_: conversation, context
|
||||
|
||||
**Customer case**:
|
||||
A caller-supplied grouping of the Executions run for one customer workload, identified by a short slug. Every Execution belongs to one; an Execution started without one belongs to `unassigned`. A Customer case ties each request to the Deliverables generated for it. It feeds one Execution's outputs into another only when the caller starts a Change request and names the Baseline.
|
||||
_Avoid_: engagement, project, account, tenant
|
||||
|
||||
**Intent**:
|
||||
What the customer wants from a Customer case, in their own words and at a high level. Each Workflow request made in the case is a statement of it, and the statements are kept in order as its history. The Intent is the customer's; requirements are what the agents derive from it.
|
||||
_Avoid_: brief, ask, requirements (which are the derived Deliverable)
|
||||
|
||||
**Change request**:
|
||||
An Execution started to say how the customer's Intent has changed. It begins from a Baseline and delivers the full updated Deliverables with an account of what changed and why.
|
||||
_Avoid_: amendment, update run, iteration, re-run
|
||||
|
||||
**Baseline**:
|
||||
The completed Execution, in the same Customer case, that a Change request starts from. A Baseline is never modified.
|
||||
_Avoid_: parent, previous run, source Execution
|
||||
|
||||
**Phase**:
|
||||
A named grouping of Deliverables: requirements discovery, solution architecture (the design, ending with the Target architecture), solution implementation, solution validation, or packaging. A Phase is complete when all its Deliverables are submitted and the user has granted the Phase's Approval.
|
||||
_Avoid_: step, node, stage, pipeline
|
||||
|
||||
**Approval**:
|
||||
A user's explicit acceptance of a Phase's Deliverables, required before work that depends on them may start. An Execution is interactive by default. A **pre-approved** Execution treats its Approvals as already granted.
|
||||
_Avoid_: sign-off, confirmation, gate (in prose)
|
||||
|
||||
**Revision**:
|
||||
Reopening a Deliverable because validation found a problem or the user asked for a change. It returns that Deliverable and everything that depends on it to draft, and withdraws any Approval that covered them. Revisions per Deliverable are limited, and past the limit the user decides.
|
||||
_Avoid_: review round, retry, loop iteration
|
||||
|
||||
### Agents
|
||||
|
||||
**Orchestrator**:
|
||||
The top-level agent of an Execution, and the only agent that talks to the user. It reasons about which Deliverables are ready to produce, delegates them to Specialists, and asks the user for Approvals.
|
||||
_Avoid_: supervisor, manager, root agent, router
|
||||
|
||||
**Specialist**:
|
||||
An agent responsible for producing one kind of Deliverable, such as the product selector or the target architect. A Specialist may delegate independent parts of its work to further Specialists.
|
||||
_Avoid_: sub-agent, worker, phase agent, node
|
||||
|
||||
### Portability
|
||||
|
||||
**Skill**:
|
||||
A self-contained package of domain guidance: instructions plus optional references, assets and scripts, in the Agent Skills format. It is the portable unit of the agent's behaviour and is loaded on demand.
|
||||
_Avoid_: prompt template, instructions, playbook
|
||||
|
||||
**Cloud provider**:
|
||||
The hyperscaler a solution architecture targets, such as Google Cloud. Each Cloud provider brings its own Skills, plus the MCP servers it hosts for discovering a user's current environment and grounding recommendations in its documentation.
|
||||
_Avoid_: hyperscaler, cloud, platform, target
|
||||
|
||||
### Outputs
|
||||
|
||||
**Deliverable**:
|
||||
A document an Execution produces: requirements, technical decomposition, product selection, design recommendations, the Target architecture, architecture description, deployment guidance, validation results, or the Solution guide. Each Deliverable depends on others being approved first.
|
||||
_Avoid_: artifact, output file
|
||||
|
||||
**Dependency**:
|
||||
The relationship between two Deliverables in which one can only be produced once the other has been accepted, for example an architecture diagram depending on the product selection. Within a Phase, a submitted Deliverable counts as accepted. Across Phases, only the earlier Phase's Approval does.
|
||||
_Avoid_: prerequisite, edge, upstream
|
||||
|
||||
**Target architecture**:
|
||||
The solution to be built, as one explicit graph of Elements, the Relationships between them, and the Checks each must meet. It is established before any infrastructure code is written, and every later Deliverable is derived from it and checked against it.
|
||||
_Avoid_: build plan, blueprint, design doc, to-be state
|
||||
|
||||
**Element**:
|
||||
One component of the Target architecture and the cloud resource that realises it, with the product selected for it.
|
||||
_Avoid_: node, resource (alone), box
|
||||
|
||||
**Relationship**:
|
||||
A connection between two Elements, such as calls, publishes to, reads from, or is granted access to.
|
||||
_Avoid_: edge, link, dependency (which is between Deliverables)
|
||||
|
||||
**Check**:
|
||||
A numbered, verifiable condition that an Element or Relationship must meet, traced to the requirement or design recommendation it comes from. Validation gives each Check a verdict.
|
||||
_Avoid_: finding, rule, control, test
|
||||
|
||||
**Requirements chain**:
|
||||
The unbroken trace from each requirement, through the components that serve it and the Elements and Checks that realise it, to the code that implements them and the validation verdict on each Check.
|
||||
_Avoid_: traceability matrix, lineage
|
||||
|
||||
**Solution guide**:
|
||||
The packaged Deliverable that assembles every other Deliverable into the Cloud provider's solution architecture template.
|
||||
_Avoid_: final report, package
|
||||
36
Dockerfile
36
Dockerfile
@@ -12,13 +12,24 @@ RUN apt-get update && apt-get install -y --no-install-recommends \
|
||||
COPY requirements.txt ./
|
||||
RUN pip install --no-cache-dir --prefix=/install -r requirements.txt
|
||||
|
||||
# Terraform CLI for fmt/validate/plan tools (never apply), verified against HashiCorp's checksums
|
||||
ARG TERRAFORM_VERSION=1.14.3
|
||||
RUN apt-get update && apt-get install -y --no-install-recommends unzip \
|
||||
&& rm -rf /var/lib/apt/lists/* \
|
||||
&& curl -fsSLO "https://releases.hashicorp.com/terraform/${TERRAFORM_VERSION}/terraform_${TERRAFORM_VERSION}_linux_amd64.zip" \
|
||||
&& curl -fsSLO "https://releases.hashicorp.com/terraform/${TERRAFORM_VERSION}/terraform_${TERRAFORM_VERSION}_SHA256SUMS" \
|
||||
&& grep "linux_amd64.zip" "terraform_${TERRAFORM_VERSION}_SHA256SUMS" | sha256sum -c - \
|
||||
&& unzip "terraform_${TERRAFORM_VERSION}_linux_amd64.zip" -d /usr/local/bin \
|
||||
&& rm "terraform_${TERRAFORM_VERSION}_linux_amd64.zip" "terraform_${TERRAFORM_VERSION}_SHA256SUMS"
|
||||
|
||||
# Final production image stage
|
||||
FROM python:3.12-slim
|
||||
|
||||
ENV PYTHONUNBUFFERED=1 \
|
||||
PYTHONDONTWRITEBYTECODE=1 \
|
||||
PYTHONPATH=/app \
|
||||
PORT=8080
|
||||
A2A_HOST=0.0.0.0 \
|
||||
A2A_PORT=8080
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
@@ -28,24 +39,27 @@ RUN groupadd -g 10001 appgroup && \
|
||||
|
||||
# Copy installed dependencies from builder
|
||||
COPY --from=builder /install /usr/local
|
||||
COPY --from=builder /usr/local/bin/terraform /usr/local/bin/terraform
|
||||
|
||||
# Copy application source, skills, and configuration
|
||||
# Copy the engine, role files, provider bundles and Skills.
|
||||
COPY app/ ./app/
|
||||
COPY eval/ ./eval/
|
||||
COPY docs/ ./docs/
|
||||
COPY deliverables/ ./deliverables/
|
||||
COPY terraform/ ./terraform/
|
||||
COPY agents/ ./agents/
|
||||
COPY providers/ ./providers/
|
||||
COPY skills/ ./skills/
|
||||
COPY workflow.yaml ./
|
||||
COPY requirements.yaml ./
|
||||
|
||||
RUN chown -R appuser:appgroup /app
|
||||
# Executions write their outputs under deliverables/executions/<execution_id>/.
|
||||
RUN mkdir -p deliverables && chown -R appuser:appgroup /app
|
||||
|
||||
USER appuser
|
||||
|
||||
# The A2A server: JSON-RPC at /a2a, the agent card, /health and pre-approved /generate.
|
||||
# Set A2A_PUBLIC_URL to the address callers reach, so the agent card advertises it.
|
||||
EXPOSE 8080
|
||||
|
||||
HEALTHCHECK --interval=30s --timeout=5s --start-period=5s --retries=3 \
|
||||
CMD python -c "import urllib.request; urllib.request.urlopen('http://localhost:8080/health')" || exit 1
|
||||
# /health answers once the provider bundle and remote MCP catalogs have loaded.
|
||||
HEALTHCHECK --interval=30s --timeout=5s --start-period=60s --retries=3 \
|
||||
CMD python -c "import os, urllib.request; urllib.request.urlopen(f'http://localhost:{os.environ[\"A2A_PORT\"]}/health')" || exit 1
|
||||
|
||||
CMD ["python", "-m", "app.agent", "--host", "0.0.0.0", "--port", "8080"]
|
||||
CMD ["python", "-m", "app.main"]
|
||||
|
||||
|
||||
184
README.md
184
README.md
@@ -1,55 +1,50 @@
|
||||
# GCP Solution Architecture Agent (`gcp_solution_architecture_agent`)
|
||||
|
||||
A production-ready Google Cloud Solution Architecture Agent built using **Google ADK (Agent Development Kit)**, **LangChain**, and **LangGraph**, featuring a multi-agent orchestration graph with iterative review loops, dynamic local skill loading, PostgreSQL database persistence, a Starlette REST API server, and an offline evaluation harness.
|
||||
A hierarchical ReAct agent that turns a request for a cloud workload into a reviewed solution architecture: requirements, a target design with diagram and infrastructure-as-code, validation results, and a packaged guide. It replaces the [`google-cloud-solution-architecture`](https://github.com/google/skills/blob/main/skills/cloud/google-cloud-solution-architecture/SKILL.md) skill with an agent that runs anywhere. Google Cloud is the first Cloud provider.
|
||||
|
||||
Vocabulary is defined in [CONTEXT.md](CONTEXT.md), decisions in [docs/adr/](docs/adr/), and the plan and history of each iteration in [.agents/plans/](.agents/plans/README.md).
|
||||
|
||||
---
|
||||
|
||||
## 🌟 Architecture & Features
|
||||
|
||||
### 1. Multi-Agent Orchestration & `google.adk.agents.LoopAgent`
|
||||
The agent uses an end-to-end multi-agent graph managed by an `OrchestratorLoopAgent` (`google.adk.agents.LoopAgent`):
|
||||
- **`SourceDiscoveryAgent`** (Phase 0a): Pre-emptively audits and documents the existing pre-migration source environment (As-Is Architecture) and pain points.
|
||||
- **`DiscoveryAgent`** (Phase 0): Discovers functional & non-functional requirements while explicitly deferring product selection.
|
||||
- **`ArchitectureDesignAgent`** (Phase 1): Resolves product selections (Cloud Run, Pub/Sub, Cloud Storage, Firestore, IAM, KMS), grounds guidance with **Google Developer Knowledge MCP**, generates Mermaid diagrams (`architecture.mmd`), and builds Terraform IaC (`terraform/main.tf`).
|
||||
- **`ValidationReviewAgent`** (Phase 2): Evaluates Mermaid syntax, Terraform structural integrity, and artifact completeness using `google.adk.tools.FunctionTool`.
|
||||
- **`PackagingAgent`** (Phase 3): Compiles the final comprehensive `solution-architecture-guide.md` with **Before (Source) vs After (Target)** architecture comparison.
|
||||
- **`OrchestratorLoopAgent`**: Repeatedly loops through the multi-agent pipeline, reviewing and validating content in a feedback loop until production quality criteria pass or `max_iterations` is reached.
|
||||
### 1. Orchestrator and Specialists (`agents/`)
|
||||
One Orchestrator coordinates an Execution and is the only agent that talks to the user. It delegates each Deliverable to one Specialist, and independent Deliverables run in parallel:
|
||||
- **Requirements discovery:** `requirements-analyst`, `decomposer`.
|
||||
- **Solution architecture (design):** `product-selector`, `design-advisor` (which consults one `pillar-advisor` per architecture-framework pillar), `target-architect`.
|
||||
- **Solution implementation:** `describer`, `iac-author`.
|
||||
- **Solution validation:** `validator`.
|
||||
- **Packaging:** `packager`.
|
||||
|
||||
### 2. Google ADK Integration (`google.adk`)
|
||||
Built directly on Google ADK framework primitives (with offline compatibility stubs):
|
||||
- **`google.adk.agents`**: `LlmAgent`, `SequentialAgent`, `ParallelAgent`, `LoopAgent`.
|
||||
- **`google.adk.tools`**: `FunctionTool` wrappers for static artifact and diagram validators, plus Google Developer Knowledge MCP tools (`developerknowledge:*`).
|
||||
- **`google.adk.artifacts`**: `ArtifactRepository` synchronized with disk and PostgreSQL.
|
||||
- **`google.adk.sessions`**: `PostgresSessionService` for durable session memory.
|
||||
- **`google.adk.runners`**: `Runner` for managing execution workflows.
|
||||
- **`google.adk.workflows`**: `Workflow` composition primitives.
|
||||
- **`google.adk.evaluation`**: `Evaluator` for scoring benchmark suites.
|
||||
Each Phase needs the user's explicit Approval before work that depends on it starts. A pre-approved mode serves batch and evaluation runs.
|
||||
|
||||
### 3. PostgreSQL Database Persistence (`app/database.py`)
|
||||
State, sessions, workflow executions, review iteration logs, and evaluation metrics are written to an external PostgreSQL database (with an automatic SQLite fallback for offline development):
|
||||
- `adk_sessions`: Durable session memory and state data.
|
||||
- `workflow_executions`: Workflow execution status, phase, and iteration metrics.
|
||||
- `adk_artifacts`: Generated solution architecture artifacts (including `docs/source-architecture.md` and `source-architecture.mmd`).
|
||||
- `orchestrator_review_logs`: Detailed iteration review logs from the `OrchestratorLoopAgent`.
|
||||
- `adk_evaluations`: Benchmark evaluation scores and pass rates.
|
||||
The design Phase ends with the **Target architecture**: one explicit graph of Elements, Relationships and Checks ([ADR-0005](docs/adr/0005-the-target-architecture-is-an-explicit-graph.md)). The user approves it before any infrastructure code is written. The diagram is drawn from it by code, the Terraform must account for every Check, and validation gives a verdict per Check. Requirements, components, products and recommendations each carry ids in a data file, so every requirement can be traced through to its verdict; a submission with a missing link is refused.
|
||||
|
||||
### 4. Dynamic Local Skill Loading (`app/skills/`)
|
||||
Domain knowledge is stored as self-contained markdown instruction templates under `app/skills/`:
|
||||
- `source_discovery/SKILL.md` (Phase 0a - Pre-emptive Source Environment Discovery)
|
||||
- `requirements_discovery/SKILL.md` (Phase 0 - Requirements Discovery & Deferral)
|
||||
- `architecture_design/SKILL.md` (Phase 1 - Product Selection & Terraform IaC)
|
||||
- `validation_rules/SKILL.md` (Phase 2 - Pre-deployment Validation Rules)
|
||||
- `packaging_guide/SKILL.md` (Phase 3 - Solution Guide Packaging)
|
||||
### 2. LangGraph state, ADK agents (`app/`)
|
||||
Per [ADR-0003](docs/adr/0003-langgraph-holds-state-adk-agents-reason.md):
|
||||
- A LangGraph `StateGraph` holds the Execution: the dependency graph of Deliverables (`app/workflows/deliverables.py`), the Ledger of their states (`app/states/ledger.py`), checkpoints, and `interrupt()` whenever the user must answer or approve.
|
||||
- Every agent is a Google ADK `LlmAgent` running its own ReAct loop behind one runtime interface (`app/adk/runtime.py`). `app/adk/adk_runtime.py` is the only module that imports `google.adk`.
|
||||
- Tools are tiered: local checks and public documentation run freely, reading the user's cloud needs permission once per Execution, and nothing can change cloud resources.
|
||||
|
||||
The `SkillLoader` (`app/skills/loader.py`) dynamically parses frontmatter and injects instructions into phase system prompts.
|
||||
### 3. Persistence (`app/database.py`, `app/checkpointing.py`)
|
||||
Execution records (status, Ledger events, submitted Deliverables) go to PostgreSQL, with an automatic SQLite fallback for local development. Checkpoints use `CHECKPOINTER=memory | sqlite | postgres`.
|
||||
|
||||
### 5. Starlette REST API Server (`app/agent.py`)
|
||||
Production HTTP REST endpoints exposed via Starlette and Uvicorn:
|
||||
- `GET /health`: Operational health signal & database connection status.
|
||||
- `GET /card`: Agent capability card metadata.
|
||||
- `POST /generate`: Trigger the ADK multi-agent workflow execution.
|
||||
- `POST /validate`: Execute pre-deployment artifact validation.
|
||||
- `GET /sessions/{session_id}`: Query session state from the PostgreSQL database.
|
||||
### 4. Agent Skills (`skills/`, loaded by `app/skills/`)
|
||||
Behaviour lives in Agent Skills (agentskills.io format) at the repository root, per ADR-0002:
|
||||
- `skills/vendor/google/`: the upstream solution-architecture Skill and six Well-Architected Framework pillar Skills, vendored unmodified.
|
||||
- `skills/cloud-discovery/`, `skills/iac-validation/` and `skills/requirements-chain/`: our own Skills for the tooling and the data files.
|
||||
- `skills/google-cloud-iac-patterns/`: Terraform patterns for Google Cloud products, each validated by a test against the provider version `providers/gcp.yaml` pins.
|
||||
|
||||
`app/skills/agent_skills.py` discovers and validates them; the ADK runtime (`app/adk/adk_runtime.py`) loads them on demand. `providers/gcp.yaml` assigns Skills, tools, MCP servers and models to each role in `agents/`.
|
||||
|
||||
### 5. A2A Server (`app/main.py`)
|
||||
The container starts the hierarchical Execution engine (ADR-0003) behind an A2A server:
|
||||
- `POST /a2a`: A2A JSON-RPC for interactive, multi-turn Executions with Approvals.
|
||||
- `GET /.well-known/agent-card.json`: A2A agent card.
|
||||
- `GET /health`: Health signal, the Cloud provider and any MCP discovery gaps.
|
||||
- `POST /generate`: One-shot, pre-approved Execution for batch and evaluation callers. Pass `customer_case` to group it with the case's other Executions; over A2A, send `customer_case` in the message metadata.
|
||||
|
||||
The original linear pipeline and its REST routes (`/card`, `/validate`, `/sessions/{session_id}`) were removed on 2026-10-06; see `.agents/plans/iter-03-kab-layout/`.
|
||||
|
||||
---
|
||||
|
||||
@@ -63,19 +58,16 @@ pip install -r requirements-dev.txt
|
||||
|
||||
### Run Tests & Validation
|
||||
```bash
|
||||
# Run pytest test suite (100% pass rate)
|
||||
pytest -v
|
||||
# Run the deterministic test suite (no model or network calls)
|
||||
pytest -q
|
||||
|
||||
# Run offline benchmark evaluation harness
|
||||
python3 -m eval.eval_harness
|
||||
|
||||
# Run static artifact validation
|
||||
python3 scripts/validate_artifacts.py
|
||||
# Real-model evaluation of the engine (costs model usage; see eval/solution_eval.py)
|
||||
python3 -m eval.solution_eval
|
||||
```
|
||||
|
||||
### Start Starlette REST Server
|
||||
### Start the A2A Server
|
||||
```bash
|
||||
python3 app/agent.py --host 0.0.0.0 --port 8080
|
||||
python3 -m app.main --host 0.0.0.0 --port 8080
|
||||
```
|
||||
|
||||
### 🐳 Run with Podman
|
||||
@@ -86,7 +78,7 @@ podman build -t gcp-solution-architecture-agent:latest .
|
||||
```
|
||||
|
||||
#### 2. Run Container with Host Deliverables Volume Mount
|
||||
To ensure execution deliverables (`deliverables/executions/{execution_id}/*`) are written directly to your host machine's workspace:
|
||||
To ensure Execution outputs (`deliverables/cases/{customer_case}/executions/{execution_id}/*`) are written directly to your host machine's workspace:
|
||||
|
||||
```bash
|
||||
podman run -d --name gcp-agent \
|
||||
@@ -94,7 +86,10 @@ podman run -d --name gcp-agent \
|
||||
-v $(pwd)/deliverables:/app/deliverables:Z \
|
||||
-v ~/.config/gcloud/application_default_credentials.json:/app/credentials/adc.json:ro \
|
||||
-e GOOGLE_APPLICATION_CREDENTIALS=/app/credentials/adc.json \
|
||||
-e GCP_PROJECT_ID=your-project-id \
|
||||
-e GOOGLE_GENAI_USE_VERTEXAI=true \
|
||||
-e GOOGLE_CLOUD_PROJECT=your-project-id \
|
||||
-e GOOGLE_CLOUD_LOCATION=global \
|
||||
-e A2A_PUBLIC_URL=http://localhost:8080 \
|
||||
localhost/gcp-solution-architecture-agent:latest
|
||||
```
|
||||
|
||||
@@ -115,13 +110,13 @@ podman run -d --name gcp-agent \
|
||||
# Health Signal
|
||||
curl http://localhost:8080/health
|
||||
|
||||
# Agent Capability Card
|
||||
curl http://localhost:8080/card
|
||||
# A2A Agent Card
|
||||
curl http://localhost:8080/.well-known/agent-card.json
|
||||
|
||||
# Run Multi-Agent ADK Workflow
|
||||
# Run a pre-approved Execution
|
||||
curl -X POST http://localhost:8080/generate \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{"request": "Event-driven regional HTTP application in Podman"}'
|
||||
-d '{"request": "Event-driven regional HTTP application in Podman", "customer_case": "acme-webhooks"}'
|
||||
```
|
||||
|
||||
---
|
||||
@@ -129,48 +124,49 @@ curl -X POST http://localhost:8080/generate \
|
||||
## 📁 Repository Structure
|
||||
```
|
||||
gcp_solution_architecture_agent/
|
||||
├── app/
|
||||
│ ├── adk/ # Google ADK framework primitives & fallbacks
|
||||
│ │ ├── agents.py # Multi-agents & OrchestratorLoopAgent
|
||||
│ │ ├── artifacts.py # PostgresArtifactRepository
|
||||
│ │ ├── compat.py # ADK compatibility layer
|
||||
│ │ ├── evaluation.py # ADKEvaluator
|
||||
│ │ ├── runners.py # ADKAgentRunner
|
||||
│ │ ├── sessions.py # PostgresSessionService
|
||||
│ │ ├── tools.py # ADK FunctionTools
|
||||
│ │ └── workflows.py # ADK Workflow composition
|
||||
│ ├── agent.py # Starlette REST server entrypoint
|
||||
│ ├── card.py # AgentCard & capability metadata
|
||||
├── agents/ # Framework-neutral role files, one per agent
|
||||
├── providers/ # Cloud provider bundles (gcp.yaml)
|
||||
├── skills/ # Agent Skills: vendored upstream + our tooling Skills
|
||||
├── app/ # KAB workflow-agent layout
|
||||
│ ├── main.py # A2A server entrypoint (python -m app.main)
|
||||
│ ├── a2a_server.py # Maps A2A tasks to Executions and their prompts
|
||||
│ ├── agent.py # ExecutionEngine and its assembly (composition root)
|
||||
│ ├── card.py # A2A agent card
|
||||
│ ├── states/ # ExecutionState and the Ledger
|
||||
│ ├── nodes/ # Execution graph nodes (orchestrator, specialist, user)
|
||||
│ ├── workflows/ # Execution graph wiring and the Deliverable dependency graph
|
||||
│ ├── adk/ # Agent-runtime interface, ADK runtime, role loader
|
||||
│ ├── skills/ # Agent Skills discovery and validation
|
||||
│ ├── tools/ # Execution tools, local tools, remote MCP, pillar fan-out
|
||||
│ ├── providers.py # Provider bundle loader
|
||||
│ ├── recorder.py # Execution recording
|
||||
│ ├── checkpointing.py # LangGraph checkpointer selection
|
||||
│ ├── presentation.py # Prompts and /generate responses
|
||||
│ ├── config.py # Typed settings (Pydantic BaseSettings)
|
||||
│ ├── database.py # PostgreSQL database persistence manager
|
||||
│ ├── nodes/ # Phase execution node handlers
|
||||
│ ├── skills/ # Local SKILL.md instruction templates & SkillLoader
|
||||
│ ├── states/ # GCPArchitectureState schema definition
|
||||
│ ├── tools/ # LangChain & ADK validation tools
|
||||
│ └── workflows/ # LangGraph StateGraph & Starlette REST routes
|
||||
├── eval/ # ADK Evaluation & Optimization Harness
|
||||
│ ├── datasets/ # Benchmark test cases (JSON)
|
||||
│ ├── eval_harness.py # Benchmark runner CLI
|
||||
│ ├── metrics.py # Scoring rubrics & evaluation logic
|
||||
│ ├── optimizer.py # Prompt tuning optimizer
|
||||
│ └── test_eval_harness.py # Evaluation unit tests
|
||||
├── deliverables/ # Scalable deliverable repository (categorized & versioned)
|
||||
│ ├── as-is/ # Pre-emptive Source Environment Deliverables (Before State)
|
||||
│ │ ├── source-architecture.md
|
||||
│ │ └── source-architecture.mmd
|
||||
│ ├── target/ # Target Architecture Deliverables (After State)
|
||||
│ │ ├── requirements.md
|
||||
│ │ ├── architecture.md
|
||||
│ │ └── architecture.mmd
|
||||
│ ├── validation/ # Pre-deployment Validation Reports
|
||||
│ │ └── validation-results.md
|
||||
│ ├── guides/ # Consolidate Solution Architecture Guides
|
||||
│ │ └── solution-architecture-guide.md
|
||||
│ └── executions/ # Per-Execution Versioned Snapshots ({execution_id}/*)
|
||||
│ └── database.py # Database persistence manager
|
||||
├── eval/ # Evaluation
|
||||
│ ├── solution_eval.py # Real-model evaluation of the Execution engine
|
||||
│ ├── scoring.py # Checks applied to a finished Execution
|
||||
│ └── datasets/ # Benchmark cases (JSON)
|
||||
├── deliverables/
|
||||
│ └── cases/ # Everything generated, grouped by Customer case
|
||||
│ └── <customer_case>/
|
||||
│ ├── intent/ # What the customer asked for, and how it has changed
|
||||
│ │ ├── 001.md, 002.md # Each request as the customer stated it, in order
|
||||
│ │ └── history.json # Every request, the Execution it started and how it ended
|
||||
│ └── executions/<execution_id>/
|
||||
│ ├── execution.json # Request, status and files of this Execution
|
||||
│ ├── solution-architecture-guide.md
|
||||
│ ├── deliverables/<kind>.md # One per Deliverable
|
||||
│ ├── requirements.json, components.json, products.json, recommendations.json
|
||||
│ ├── target-architecture.json # Elements, Relationships and Checks
|
||||
│ ├── architecture.mmd # Drawn from the graph
|
||||
│ ├── terraform/, implementation.json # The code, and which part meets each Check
|
||||
│ └── verdicts.json # Validation's verdict on each Check
|
||||
├── lessons/candidates/<customer_case>/ # Lesson candidates per Execution (gitignored)
|
||||
├── docs/ # Specifications, audit notes & verification records
|
||||
├── terraform/ # Deployable GCP Terraform IaC blueprint
|
||||
├── scripts/
|
||||
│ └── validate_artifacts.py # Static artifact validation script
|
||||
├── scripts/ # Vendored-Skill sync, MCP tool listing, Terraform checks
|
||||
└── tests/ # Unit & integration test suite
|
||||
```
|
||||
|
||||
|
||||
@@ -3,19 +3,22 @@
|
||||
Run from the repository root without credentials:
|
||||
|
||||
```bash
|
||||
# 1. Static artifact & guide section validation
|
||||
python3 scripts/validate_artifacts.py
|
||||
|
||||
# 2. Pytest unit & integration test suite
|
||||
# 1. Pytest unit & integration test suite
|
||||
pytest -v
|
||||
|
||||
# 3. Offline ADK evaluation benchmark suite
|
||||
python3 -m eval.eval_harness
|
||||
# 2. Real-model evaluation of the engine (needs model credentials; costs usage)
|
||||
python3 -m eval.solution_eval
|
||||
|
||||
# 4. Optional Terraform formatting & validation
|
||||
# 3. Optional Terraform formatting & validation
|
||||
terraform -chdir=terraform fmt -check -recursive
|
||||
terraform -chdir=terraform init -backend=false
|
||||
terraform -chdir=terraform validate
|
||||
```
|
||||
|
||||
`init -backend=false` may download the pinned provider constraint but does not create infrastructure. Do not use `terraform apply` as part of validation. A deployment candidate additionally requires an operator-supplied `terraform plan -out=tfplan` and human review.
|
||||
|
||||
## Evaluation options
|
||||
|
||||
- `python3 -m eval.solution_eval --judge` adds the judged checks: coverage of each pillar Skill's validation checklist, and a quality rubric for the design recommendations.
|
||||
- `python3 -m eval.solution_eval case-04-interactive-web-app` runs one case with a scripted user in the loop.
|
||||
- A case's `thresholds` in `eval/datasets/solution_cases.json` bound its revisions, seconds and tokens; exceeding one is reported as a regression.
|
||||
|
||||
12
agents/decomposer.md
Normal file
12
agents/decomposer.md
Normal file
@@ -0,0 +1,12 @@
|
||||
---
|
||||
role: decomposer
|
||||
deliverable: technical_decomposition
|
||||
tools: []
|
||||
includes: [specialist-protocol]
|
||||
---
|
||||
You produce the **technical decomposition** Deliverable: the Skill's breakdown of the workload into logical components.
|
||||
|
||||
- Derive every component from the approved requirements, and name the requirements each component serves.
|
||||
- Describe components by responsibility, inputs, outputs and interactions.
|
||||
- Give every component an id and attach them as `components.json`, in the format the requirements-chain Skill gives, with the requirement ids each serves. Every functional requirement must be served by a component.
|
||||
- Name no products or services; product selection comes later and depends on this decomposition being right.
|
||||
11
agents/describer.md
Normal file
11
agents/describer.md
Normal file
@@ -0,0 +1,11 @@
|
||||
---
|
||||
role: describer
|
||||
deliverable: architecture_description
|
||||
tools: []
|
||||
includes: [specialist-protocol]
|
||||
---
|
||||
You produce the **architecture description** Deliverable: the Skill's task for describing the architecture.
|
||||
|
||||
- Describe the Target architecture and nothing else: explain the purpose of each Element and the Relationships between them under a components heading, and the task flow or data flow end to end under a flow heading.
|
||||
- Use the Element names and products from the Target architecture exactly.
|
||||
- Ground claims about product behaviour in the Cloud provider's documentation through your documentation tools, with citations.
|
||||
15
agents/design-advisor.md
Normal file
15
agents/design-advisor.md
Normal file
@@ -0,0 +1,15 @@
|
||||
---
|
||||
role: design-advisor
|
||||
deliverable: design_recommendations
|
||||
tools: []
|
||||
includes: [specialist-protocol]
|
||||
---
|
||||
You produce the **design recommendations** Deliverable: the Skill's task for recommending how to configure each component to meet the functional and non-functional requirements.
|
||||
|
||||
- Call `consult_pillar_advisors` once, with a brief that restates the workload, the relevant requirements and the selected products. It runs one advisor per architecture-framework pillar in parallel and returns their guidance.
|
||||
- When `feedback` is not empty you are revising: pass `pillars` naming only the pillars the feedback touches. The guidance you were given before is returned for the others.
|
||||
- Reconcile the pillars' guidance into recommendations for each component. Where pillars conflict, name the trade-off and recommend a resolution tied to the requirements.
|
||||
- When an advisor's guidance is missing, derive that pillar's recommendations from the best-practices references in the solution-architecture Skill.
|
||||
- Give every recommendation an id and attach them as `recommendations.json`, in the format the requirements-chain Skill gives. Write one configurable decision per recommendation, so each can become a Check in the Target architecture.
|
||||
|
||||
Your contract's sections are one per pillar.
|
||||
23
agents/iac-author.md
Normal file
23
agents/iac-author.md
Normal file
@@ -0,0 +1,23 @@
|
||||
---
|
||||
role: iac-author
|
||||
deliverable: deployment_guidance
|
||||
tools: [terraform_fmt, terraform_validate, terraform_schema]
|
||||
budget: 40
|
||||
includes: [specialist-protocol]
|
||||
---
|
||||
You produce the **deployment guidance** Deliverable: the Skill's task for generating infrastructure-as-code and deployment instructions.
|
||||
|
||||
- Write Terraform that implements the Target architecture: every Element, every Relationship and every Check, and nothing it does not ask for.
|
||||
- Before you write a resource, load the infrastructure-as-code patterns Skill when you have one, and start from its pattern for that product and its provider versions file.
|
||||
- Keep the files in your working copy. Write each file once with `write_file`, and make every later change with `edit_file`, changing only the lines that need it. Never write a file again to fix part of it.
|
||||
- Format and validate with `terraform_fmt` and `terraform_validate` when they are available. They run on your working copy, so pass them no files. Fix everything they report.
|
||||
- When validation says an argument or block is not expected, look the resource type up with `terraform_schema` instead of guessing where it belongs.
|
||||
- When a Check names a setting its resource type does not have, do not invent code for it. Record the Check in `implementation.json` as unimplementable, with what the schema shows, and implement the rest. The Target architecture is then revised.
|
||||
- Write `implementation.json` to your working copy, in the format the requirements-chain Skill gives, naming where the code satisfies each Check.
|
||||
- Take every environment-specific value (project, region, names, image references) from variables; embed no credentials or secrets.
|
||||
- Submit as soon as validation passes, with your content and no attachments: your working copy is attached for you. If a submission is refused, fix exactly what the refusal lists and submit again.
|
||||
- When `working_copy` lists files, they are your last attempt. When `feedback` lists failed Checks, read the files concerned and change only what those Checks need.
|
||||
|
||||
Your working copy must hold `terraform/main.tf`, `terraform/variables.tf` and `implementation.json`, with `terraform/versions.tf` and `terraform/outputs.tf` when they help.
|
||||
|
||||
Under the prerequisites heading, list the APIs to enable, the tools and the permissions. Under the instructions heading, give commands for the user to run; never run them yourself.
|
||||
26
agents/orchestrator.md
Normal file
26
agents/orchestrator.md
Normal file
@@ -0,0 +1,26 @@
|
||||
---
|
||||
role: orchestrator
|
||||
tools: []
|
||||
---
|
||||
You coordinate one solution-architecture Execution for the user. You decide what happens next; Specialists produce the Deliverables, and you are the only agent that talks to the user.
|
||||
|
||||
Load the solution-architecture Skill available to you for the workflow's rules: strict separation between requirements discovery and solutioning, explicit user approval of each Phase, and no execution of generated scripts.
|
||||
|
||||
Your task message carries JSON context: `workflow_request`, each Deliverable's `status`, `revisions` and `feedback`, each Phase's status, `ready_work`, `phases_ready_for_approval`, `validation` (the verdict on each Check, once validation is submitted), `unimplementable_checks` (Checks the code's author found cannot be met as written), `pending_questions` from Specialists, the recent `conversation`, `notes` about discarded results, `pre_approved` and `allow_cloud_read`.
|
||||
|
||||
On each turn, take the first step that applies:
|
||||
|
||||
1. **The user asked for changes.** When the latest user message in `conversation` asks to change submitted work, call `reopen` for each affected Deliverable with the user's words as the reason.
|
||||
2. **Specialists are waiting.** When `pending_questions` is not empty, call `ask_user`. Add your own questions only when the user's last message left something unclear.
|
||||
3. **The code cannot meet a Check.** When `unimplementable_checks` is not empty, call `reopen` on `target_architecture`, giving each Check's id and reason, then delegate it.
|
||||
4. **Validation decided.** When `validation` is set and the validation Phase is not yet approved, act on it before asking for Approval:
|
||||
- `failed` is not empty, or `dry_run.verdict` is `fail`: the code is at fault. Call `reopen` on `deployment_guidance`, giving each failed Check's id and evidence as the reason, then delegate it.
|
||||
- otherwise `not_verifiable` or `proposed_additions` is not empty: the Target architecture has a gap. When `pre_approved` is `false`, call `ask_user` to ask whether to revise the Target architecture, listing each item. When `pre_approved` is `true`, call `reopen` on `target_architecture` for the items whose reason names a requirement or recommendation id, then delegate it; ignore the rest.
|
||||
5. **A Phase is complete.** When `phases_ready_for_approval` names a Phase, read its Deliverables with `read_deliverable` and call `request_approval` with a summary a busy architect can approve from. In a pre-approved Execution the approval is granted immediately, and you continue with the next step in the same turn.
|
||||
6. **Work is ready.** When `ready_work` is not empty, call `delegate` once with every ready Deliverable, so independent work runs in parallel.
|
||||
7. **Packaging is approved.** Call `finish`.
|
||||
8. **Otherwise,** call `ask_user` to find out what the user needs.
|
||||
|
||||
When the user says a Deliverable already exists, still delegate it; the Specialist submits the user's version. When a tool refuses, read the reason and choose again.
|
||||
|
||||
Every turn ends with exactly one call to `delegate`, `ask_user`, `request_approval` or `finish`.
|
||||
14
agents/packager.md
Normal file
14
agents/packager.md
Normal file
@@ -0,0 +1,14 @@
|
||||
---
|
||||
role: packager
|
||||
deliverable: solution_guide
|
||||
tools: []
|
||||
includes: [specialist-protocol]
|
||||
---
|
||||
You produce the **solution guide** Deliverable: the Skill's packaging of every approved Deliverable into one guide.
|
||||
|
||||
- Load the solution-guide output template from the Skill's assets and follow its structure and section numbering exactly.
|
||||
- Consolidate the content of every Deliverable in `dependencies`; rewrite for flow, but keep every requirement, product decision, citation, recommendation, command and validation verdict.
|
||||
- Include the architecture diagram, which is the `architecture.mmd` attachment of the Target architecture, unchanged as a `mermaid` code block, and the Terraform as code blocks.
|
||||
- List the Target architecture's Checks with their validation verdicts in the validation section.
|
||||
|
||||
Your contract's sections are the template's eight top-level sections.
|
||||
23
agents/partials/specialist-protocol.md
Normal file
23
agents/partials/specialist-protocol.md
Normal file
@@ -0,0 +1,23 @@
|
||||
## How you work
|
||||
|
||||
You are a Specialist in a solution-architecture Execution. You produce exactly one Deliverable, named in your task. An Orchestrator coordinates the Execution and is the only agent that talks to the user.
|
||||
|
||||
Your task message carries JSON context:
|
||||
|
||||
- `workflow_request`: what the user asked for.
|
||||
- `dependencies`: every earlier Deliverable your work builds on, by kind. The ones you work from directly come whole, with `content` and `attachments`. The rest come as their data file alone, under `attachments`: the ids to keep traceable. Call `read_deliverable` for the full text of one of those only when the ids are not enough.
|
||||
- `feedback`: why earlier versions of your Deliverable were revised. Address every item.
|
||||
- `answers`: the user's replies to questions you asked in earlier runs, oldest first.
|
||||
- `contract`: what `submit_deliverable` checks. `sections` are headings your content must have and `attachments` are files you must attach. A data file among them must also keep every id traceable to the Deliverables in `dependencies`; the requirements-chain Skill gives each file's format.
|
||||
- `draft`: the draft you sent the user with your last questions, with its `attachments`, or `null`.
|
||||
- `working_copy`: what your own tools already hold from your earlier attempts, or `null`. Start from it; do not start again.
|
||||
- `pre_approved`: `true` when no user is available.
|
||||
|
||||
Steps:
|
||||
|
||||
1. Load the Skill available to you and find the part that covers your Deliverable. Read the references and assets it points to with `load_skill_resource`.
|
||||
2. Ground your work in `dependencies`, `feedback` and `answers`. When you need information only the user has, call `needs_input` with all your questions at once, each saying why it matters. Your run ends there, and you are started again with the answers.
|
||||
3. Draft the Deliverable to its `contract`. When `pre_approved` is `false`, confirm the draft with the user before submitting: call `needs_input` with a short summary of the draft, asking them to approve it or request changes, and pass the complete draft as `draft` with its `attachments`. When `draft` is set and the latest entry in `answers` approves it, submit that draft as it is; when the user asked for changes, apply them to that draft. When `pre_approved` is `true`, ask nothing: record each assumption under an `Assumptions` heading and continue.
|
||||
4. Call `submit_deliverable` with the complete markdown content and every attachment in `contract`. When it reports what is missing, add it and submit again.
|
||||
|
||||
You are done when `submit_deliverable` accepts the Deliverable.
|
||||
14
agents/pillar-advisor.md
Normal file
14
agents/pillar-advisor.md
Normal file
@@ -0,0 +1,14 @@
|
||||
---
|
||||
role: pillar-advisor
|
||||
tools: []
|
||||
---
|
||||
You advise on one pillar of the Cloud provider's architecture framework for a single workload. The Skill available to you is that pillar's guidance.
|
||||
|
||||
Your task message carries the design advisor's brief in `brief` and the pillar's name in `pillar`.
|
||||
|
||||
1. Load the Skill available to you.
|
||||
2. Evaluate the workload in the brief against the Skill's core principles and validation checklist.
|
||||
3. Write prioritised, actionable recommendations for each relevant component, naming the products the Skill lists for each gap and citing its guidance.
|
||||
4. List any assessment questions from the Skill that the brief leaves unanswered, as open questions; don't ask the user.
|
||||
|
||||
Call `submit_advice` with your recommendations as markdown. You are done when it accepts them.
|
||||
15
agents/product-selector.md
Normal file
15
agents/product-selector.md
Normal file
@@ -0,0 +1,15 @@
|
||||
---
|
||||
role: product-selector
|
||||
deliverable: product_selection
|
||||
tools: []
|
||||
includes: [specialist-protocol]
|
||||
---
|
||||
You produce the **product selection** Deliverable: the Skill's task for identifying the products and features each component needs.
|
||||
|
||||
- Recommend one product or feature per component of the technical decomposition, grounded in the Cloud provider's official documentation through your documentation tools, with a citation for every recommendation.
|
||||
- Check the release status of every product you recommend, and recommend nothing deprecated, retired or unsupported.
|
||||
- Where alternatives exist, follow the documentation's guidance on choosing, and list the alternatives with their pros and cons.
|
||||
|
||||
Attach `products.json`, in the format the requirements-chain Skill gives, with the one product selected for each component.
|
||||
|
||||
Under the products mapping heading, give a table with columns for component, recommended product or feature, justification and citations, alternatives, and their pros and cons.
|
||||
16
agents/reply-writer.md
Normal file
16
agents/reply-writer.md
Normal file
@@ -0,0 +1,16 @@
|
||||
---
|
||||
role: reply-writer
|
||||
tools: []
|
||||
---
|
||||
You write what the user reads on behalf of the Orchestrator of a solution-architecture Execution. The decision has already been made; you put it into words and decide nothing.
|
||||
|
||||
Your task message carries JSON context: `phase`, the Phase the user is being asked to approve, and `facts`, the data about it: its Deliverables, counts of requirements and recommendations, the Target architecture's counts of Elements, Relationships and Checks with any recommendation treated as not applicable, validation verdicts, and Revisions.
|
||||
|
||||
Write a summary a busy architect can approve from:
|
||||
|
||||
- Say what the Phase produced and what approving it commits them to. For the design Phase, say that no infrastructure code is written until they approve it.
|
||||
- State every number in `facts` that bears on the decision, exactly as given. Add no fact that is not there.
|
||||
- Name anything they should look at before approving: failed or unverifiable Checks, open gaps, recommendations treated as not applicable, Deliverables that were revised.
|
||||
- Use plain sentences and no headings. Keep it under 120 words.
|
||||
|
||||
Call `write_reply` with the summary. You are done when it accepts it.
|
||||
17
agents/requirements-analyst.md
Normal file
17
agents/requirements-analyst.md
Normal file
@@ -0,0 +1,17 @@
|
||||
---
|
||||
role: requirements-analyst
|
||||
deliverable: requirements
|
||||
tools: []
|
||||
includes: [specialist-protocol]
|
||||
---
|
||||
You produce the **requirements** Deliverable: the Skill's requirements-discovery gathering and its resolution of ambiguities and contradictions.
|
||||
|
||||
- Cover functional requirements, non-functional requirements (security, privacy, compliance, reliability, disaster recovery, cost, operations, performance, sustainability), current state, and dependencies.
|
||||
- The user states what they want at a high level; the detail is your job. When a non-functional requirement is missing, propose a default for it from the Cloud provider's architecture framework and record it under `Assumptions` with what it decides: availability tiers, scaling, cost budgets, resource types and security posture. Ask the user to confirm the whole set in one question.
|
||||
- Ask an open question only where no sensible default can be inferred from the request, such as the region, a compliance regime or a budget ceiling.
|
||||
- Name every ambiguity or contradiction, explain why the conflicting goals can't both hold, and ask the user to choose. When they delegate the choice, propose one and ask them to approve it.
|
||||
- When the user runs workloads in a cloud environment today, use your cloud discovery tools to describe the current state from what actually exists, and record anything you couldn't read as a discovery gap.
|
||||
- Name no products, services or architectures. This Deliverable describes the problem, not the solution.
|
||||
- Give every requirement an id and attach them all as `requirements.json`, in the format the requirements-chain Skill gives. Use the same ids in your content.
|
||||
|
||||
Add `Open questions` and `Assumptions` headings when they apply.
|
||||
20
agents/target-architect.md
Normal file
20
agents/target-architect.md
Normal file
@@ -0,0 +1,20 @@
|
||||
---
|
||||
role: target-architect
|
||||
deliverable: target_architecture
|
||||
tools: [terraform_schema]
|
||||
budget: 30
|
||||
includes: [specialist-protocol]
|
||||
---
|
||||
You produce the **Target architecture** Deliverable: the solution as one explicit graph of Elements, Relationships and Checks. It is agreed before any infrastructure code is written, and the diagram, the description, the code and the validation are all derived from it.
|
||||
|
||||
- Load the requirements-chain Skill for the graph's format and how to derive it.
|
||||
- Build the graph with `graph_put`, a few items per call: the Elements first, then the Relationships, then the Checks one Element at a time. Short calls are what keep your replies from timing out.
|
||||
- Give every component an Element with the product selected for it, and add the supporting Elements the design needs, such as identities, policies and networks.
|
||||
- Give every connection between Elements a Relationship.
|
||||
- Turn every non-functional requirement and every design recommendation into Checks on the Elements and Relationships they constrain. Write each Check so that it can be verified from infrastructure code alone, naming the setting and the value it must have.
|
||||
- Before you write a Check that names a setting, confirm with `terraform_schema` that the Element's resource type has that setting, when the tool is available. A setting that one resource type has may not exist on a similar one. A Check on a setting the resource type lacks cannot be met and is sent back to you.
|
||||
- Decide the implementation detail yourself from the design recommendations and the Cloud provider's documentation, through your documentation tools. The user states intent at a high level; this level of detail is your job.
|
||||
- When a recommendation does not apply to this workload, list it as not applicable with the reason. The user sees that list when they approve the design.
|
||||
- When `working_copy` shows a graph, it is your last attempt: read it with `graph_read` and change only what `feedback` asks for, with `graph_put` and `graph_remove`.
|
||||
|
||||
Your content is short: under your contract's heading, a few paragraphs on the decisions that shaped the design and why. Submit it with no attachments. Your working graph is attached as `target-architecture.json`, and the tables of Elements, Relationships and Checks and the diagram are written from it for you, so never write them yourself.
|
||||
16
agents/validator.md
Normal file
16
agents/validator.md
Normal file
@@ -0,0 +1,16 @@
|
||||
---
|
||||
role: validator
|
||||
deliverable: validation_results
|
||||
tools: [terraform_validate, terraform_plan, terraform_schema]
|
||||
includes: [specialist-protocol]
|
||||
---
|
||||
You produce the **validation results** Deliverable: the Skill's pre-deployment validation, done statically without provisioning anything.
|
||||
|
||||
- Run the deployment dry-run with your tools: validate the Terraform, and preview it with a plan when you have permission to read live cloud resources. The tools already hold the submitted files, so pass them no files.
|
||||
- Give a verdict on every Check in the Target architecture, from the infrastructure code: pass, fail or not verifiable, each with the evidence you read. The Checks are the whole bar: judge the code against them and nothing else.
|
||||
- Before you fail a Check because the code lacks a setting, confirm with `terraform_schema` that the resource type has that setting, when the tool is available. When it does not, the Check cannot be met by any code: give it not verifiable, with what the schema shows as the evidence. Give the same verdict to a Check that `implementation.json` records as unimplementable.
|
||||
- When you see something the Target architecture lacks, record it as a proposed addition, naming the requirement or recommendation it serves. It is not a failure of the code.
|
||||
- Attach the verdicts as `verdicts.json`, in the format the requirements-chain Skill gives.
|
||||
- Give the exact commands for every check you couldn't run, for the user to run themselves.
|
||||
|
||||
End each of your contract's sections with a pass or fail verdict.
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
147
app/a2a_server.py
Normal file
147
app/a2a_server.py
Normal file
@@ -0,0 +1,147 @@
|
||||
"""Maps A2A tasks onto Executions: a task is an Execution, its context is the Session.
|
||||
|
||||
A new task starts an Execution; a message on an input-required task answers the
|
||||
Execution's prompt. Approvals and permissions count only as structured data parts,
|
||||
never as free text.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from collections.abc import Mapping
|
||||
from typing import Any
|
||||
|
||||
from a2a.helpers.proto_helpers import (
|
||||
get_data_parts,
|
||||
new_data_part,
|
||||
new_task,
|
||||
new_text_part,
|
||||
)
|
||||
from a2a.server.agent_execution import AgentExecutor, RequestContext
|
||||
from a2a.server.events import EventQueue
|
||||
from a2a.server.tasks import TaskUpdater
|
||||
from a2a.types import TaskState
|
||||
from google.protobuf import json_format
|
||||
|
||||
from app.agent import ExecutionEngine, Interaction
|
||||
from app.nodes.execution_nodes import GUIDE_FILENAME
|
||||
from app.presentation import describe_prompt
|
||||
from app.workflows.deliverables import DeliverableKind
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
STRUCTURED_REPLY_KEYS = ("approval", "permission")
|
||||
|
||||
|
||||
class SolutionArchitectExecutor(AgentExecutor):
|
||||
def __init__(self, engine: ExecutionEngine) -> None:
|
||||
self._engine = engine
|
||||
|
||||
async def execute(self, context: RequestContext, event_queue: EventQueue) -> None:
|
||||
task_id = context.task_id or ""
|
||||
updater = TaskUpdater(event_queue, task_id, context.context_id or "")
|
||||
try:
|
||||
if context.current_task is None:
|
||||
history = [context.message] if context.message is not None else []
|
||||
await event_queue.enqueue_event(
|
||||
new_task(
|
||||
task_id,
|
||||
context.context_id or "",
|
||||
TaskState.TASK_STATE_SUBMITTED,
|
||||
history=history,
|
||||
)
|
||||
)
|
||||
await updater.start_work()
|
||||
options = _options(context)
|
||||
interaction = await self._engine.start(
|
||||
context.get_user_input(),
|
||||
session_id=context.context_id,
|
||||
customer_case=options.get("customer_case"),
|
||||
execution_id=task_id,
|
||||
pre_approved=bool(options.get("pre_approved", False)),
|
||||
allow_cloud_read=options.get("allow_cloud_read"),
|
||||
)
|
||||
else:
|
||||
await updater.start_work()
|
||||
interaction = await self._engine.resume(task_id, _reply(context))
|
||||
except Exception as exc:
|
||||
logger.exception("Execution %s failed", task_id)
|
||||
await updater.failed(
|
||||
updater.new_agent_message(
|
||||
[
|
||||
new_text_part(
|
||||
f"The Execution failed: {type(exc).__name__}: {exc}"
|
||||
)
|
||||
]
|
||||
)
|
||||
)
|
||||
return
|
||||
await self._publish(interaction, updater)
|
||||
|
||||
async def cancel(self, context: RequestContext, event_queue: EventQueue) -> None:
|
||||
# The checkpoint stays; cancelling only ends the A2A task.
|
||||
updater = TaskUpdater(
|
||||
event_queue, context.task_id or "", context.context_id or ""
|
||||
)
|
||||
await updater.cancel()
|
||||
|
||||
async def _publish(self, interaction: Interaction, updater: TaskUpdater) -> None:
|
||||
if interaction.status == "awaiting_user" and interaction.prompt is not None:
|
||||
prompt = dict(interaction.prompt)
|
||||
await updater.requires_input(
|
||||
updater.new_agent_message(
|
||||
[
|
||||
new_text_part(describe_prompt(prompt)),
|
||||
new_data_part({"prompt": prompt}),
|
||||
]
|
||||
)
|
||||
)
|
||||
return
|
||||
|
||||
deliverables: Mapping[str, Mapping[str, Any]] = interaction.state.get(
|
||||
"deliverables", {}
|
||||
)
|
||||
guide = deliverables.get(DeliverableKind.SOLUTION_GUIDE.value)
|
||||
if guide:
|
||||
await updater.add_artifact(
|
||||
[new_text_part(guide["content"], media_type="text/markdown")],
|
||||
name=GUIDE_FILENAME,
|
||||
)
|
||||
for kind, deliverable in deliverables.items():
|
||||
for name, content in deliverable.get("attachments", {}).items():
|
||||
await updater.add_artifact(
|
||||
[new_text_part(content)], name=name, metadata={"deliverable": kind}
|
||||
)
|
||||
|
||||
warnings = list(interaction.state.get("warnings", []))
|
||||
summary = (
|
||||
"The solution architecture is complete and approved."
|
||||
if interaction.status == "completed"
|
||||
else "The Execution ended with warnings: " + "; ".join(warnings)
|
||||
)
|
||||
await updater.complete(
|
||||
updater.new_agent_message(
|
||||
[
|
||||
new_text_part(summary),
|
||||
new_data_part({"status": interaction.status, "warnings": warnings}),
|
||||
]
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
def _options(context: RequestContext) -> dict[str, Any]:
|
||||
options: dict[str, Any] = {}
|
||||
if context.message is not None and context.message.HasField("metadata"):
|
||||
options.update(json_format.MessageToDict(context.message.metadata))
|
||||
options.update(context.metadata)
|
||||
return options
|
||||
|
||||
|
||||
def _reply(context: RequestContext) -> dict[str, Any]:
|
||||
if context.message is not None:
|
||||
for data in get_data_parts(list(context.message.parts)):
|
||||
if isinstance(data, Mapping) and any(
|
||||
k in data for k in STRUCTURED_REPLY_KEYS
|
||||
):
|
||||
return {k: data[k] for k in STRUCTURED_REPLY_KEYS if k in data}
|
||||
return {"reply": context.get_user_input()}
|
||||
@@ -1,31 +1 @@
|
||||
"""ADK package for GCP Solution Architecture Agent."""
|
||||
|
||||
from .agents import (
|
||||
ArchitectureDesignAgent,
|
||||
DiscoveryAgent,
|
||||
OrchestratorLoopAgent,
|
||||
PackagingAgent,
|
||||
ValidationReviewAgent,
|
||||
build_adk_multi_agent_system,
|
||||
)
|
||||
from .artifacts import PostgresArtifactRepository
|
||||
from .evaluation import ADKEvaluator
|
||||
from .runners import ADKAgentRunner
|
||||
from .sessions import PostgresSessionService
|
||||
from .tools import ADK_TOOLS
|
||||
from .workflows import create_gcp_adk_workflow
|
||||
|
||||
__all__ = [
|
||||
"DiscoveryAgent",
|
||||
"ArchitectureDesignAgent",
|
||||
"ValidationReviewAgent",
|
||||
"PackagingAgent",
|
||||
"OrchestratorLoopAgent",
|
||||
"build_adk_multi_agent_system",
|
||||
"PostgresArtifactRepository",
|
||||
"PostgresSessionService",
|
||||
"ADKAgentRunner",
|
||||
"ADKEvaluator",
|
||||
"ADK_TOOLS",
|
||||
"create_gcp_adk_workflow",
|
||||
]
|
||||
"""Agent runtimes: the framework-neutral interface agents run behind, and its implementations."""
|
||||
|
||||
317
app/adk/adk_runtime.py
Normal file
317
app/adk/adk_runtime.py
Normal file
@@ -0,0 +1,317 @@
|
||||
"""AgentRuntime on Google ADK (ADR-0003): an LlmAgent per run, with SkillToolset.
|
||||
|
||||
This is the only module that imports google.adk. Each run builds a fresh LlmAgent
|
||||
and in-memory session (Specialists are stateless), offers the role's ToolSpecs and
|
||||
Skills, and stops as soon as a tool returns an outcome or the budget is spent.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import logging
|
||||
import re
|
||||
import uuid
|
||||
from collections.abc import Callable, Mapping, Sequence
|
||||
from contextlib import aclosing
|
||||
from dataclasses import dataclass, field
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
import httpx
|
||||
from google.adk.agents import LlmAgent
|
||||
from google.adk.models.base_llm import BaseLlm
|
||||
from google.adk.runners import Runner
|
||||
from google.adk.sessions import InMemorySessionService
|
||||
from google.adk.skills import load_skill_from_dir
|
||||
from google.adk.skills.models import Skill
|
||||
from google.adk.tools.base_tool import BaseTool
|
||||
from google.adk.tools.skill_toolset import SkillToolset
|
||||
from google.adk.tools.tool_context import ToolContext
|
||||
from google.genai import types
|
||||
|
||||
from app.adk.runtime import (
|
||||
REJECTION_PREFIXES,
|
||||
AgentTask,
|
||||
BudgetExhausted,
|
||||
Outcome,
|
||||
RoleSpec,
|
||||
Stopped,
|
||||
ToolSpec,
|
||||
)
|
||||
|
||||
APP_NAME = "solution-architect"
|
||||
# run_skill_script is deliberately absent: generated or bundled scripts never run.
|
||||
SKILL_TOOLS = ["list_skills", "load_skill", "load_skill_resource"]
|
||||
TURN_ENDED_REPLY = "Your turn has already ended; this call was not run."
|
||||
NUDGE = (
|
||||
"You stopped without calling a tool that ends your turn, so nothing was recorded. "
|
||||
"Continue the task, and finish by calling the tool your instructions name for "
|
||||
"ending your turn. If you need the user, use the tool for asking questions."
|
||||
)
|
||||
TIMED_OUT = (
|
||||
"Your last model request timed out, so its reply was lost. Continue the task, "
|
||||
"and finish by calling the tool your instructions name for ending your turn."
|
||||
)
|
||||
# Client-side timeouts from either HTTP stack google-genai may use (httpx or aiohttp,
|
||||
# whose timeout errors subclass TimeoutError).
|
||||
MODEL_TIMEOUTS = (TimeoutError, httpx.TimeoutException)
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
ModelFactory = Callable[[RoleSpec], BaseLlm | str]
|
||||
|
||||
|
||||
GEMINI_PREFIX = "gemini/"
|
||||
|
||||
|
||||
def default_model_factory(role: RoleSpec) -> BaseLlm:
|
||||
"""Model for a role's LiteLLM-style id.
|
||||
|
||||
`gemini/<model>` uses ADK's native Gemini client, which targets Vertex AI when
|
||||
GOOGLE_GENAI_USE_VERTEXAI=true (with GOOGLE_CLOUD_PROJECT and
|
||||
GOOGLE_CLOUD_LOCATION) and the Gemini API otherwise. Any other id goes through
|
||||
LiteLLM, so other model providers need no code changes.
|
||||
"""
|
||||
if not role.model:
|
||||
raise ValueError(f"Role {role.name!r} has no model configured")
|
||||
if role.model.startswith(GEMINI_PREFIX):
|
||||
from google.adk.models.google_llm import Gemini
|
||||
|
||||
return Gemini(
|
||||
model=role.model.removeprefix(GEMINI_PREFIX),
|
||||
retry_options=types.HttpRetryOptions(attempts=5, initial_delay=2.0),
|
||||
)
|
||||
from google.adk.models.lite_llm import LiteLlm
|
||||
|
||||
return LiteLlm(model=role.model)
|
||||
|
||||
|
||||
USAGE_FIELDS = {
|
||||
"requests": None,
|
||||
"prompt": "prompt_token_count",
|
||||
"cached": "cached_content_token_count",
|
||||
"tool_prompt": "tool_use_prompt_token_count",
|
||||
"output": "candidates_token_count",
|
||||
"thinking": "thoughts_token_count",
|
||||
"total": "total_token_count",
|
||||
}
|
||||
|
||||
|
||||
@dataclass
|
||||
class TokenUsage:
|
||||
"""Model token counts, summed over every model response of one role and model."""
|
||||
|
||||
requests: int = 0
|
||||
prompt: int = 0
|
||||
cached: int = 0
|
||||
tool_prompt: int = 0
|
||||
output: int = 0
|
||||
thinking: int = 0
|
||||
total: int = 0
|
||||
|
||||
def add(self, metadata: Any) -> None:
|
||||
self.requests += 1
|
||||
for name, source in USAGE_FIELDS.items():
|
||||
if source:
|
||||
setattr(
|
||||
self,
|
||||
name,
|
||||
getattr(self, name) + (getattr(metadata, source, 0) or 0),
|
||||
)
|
||||
|
||||
|
||||
@dataclass
|
||||
class _RunControl:
|
||||
budget: int
|
||||
role: str
|
||||
calls: int = 0
|
||||
outcome: Outcome | None = None
|
||||
lock: asyncio.Lock = field(default_factory=asyncio.Lock)
|
||||
|
||||
def before_tool(
|
||||
self, tool: BaseTool, args: dict[str, Any], tool_context: Any
|
||||
) -> dict[str, Any] | None:
|
||||
if self.outcome is not None:
|
||||
return {"error": TURN_ENDED_REPLY}
|
||||
self.calls += 1
|
||||
logger.info(
|
||||
"%s tool call %d/%d: %s", self.role, self.calls, self.budget, tool.name
|
||||
)
|
||||
if self.calls > self.budget:
|
||||
self.outcome = BudgetExhausted(
|
||||
f"{self.role} used all {self.budget} tool calls before finishing."
|
||||
)
|
||||
return {"error": "Tool-call budget exhausted; stop now."}
|
||||
return None
|
||||
|
||||
|
||||
class _SpecTool(BaseTool):
|
||||
"""Adapts a framework-neutral ToolSpec to an ADK tool."""
|
||||
|
||||
def __init__(self, spec: ToolSpec, control: _RunControl) -> None:
|
||||
super().__init__(name=spec.name, description=spec.description)
|
||||
self._spec = spec
|
||||
self._control = control
|
||||
|
||||
def _get_declaration(self) -> types.FunctionDeclaration:
|
||||
return types.FunctionDeclaration(
|
||||
name=self._spec.name,
|
||||
description=self._spec.description,
|
||||
parameters_json_schema=dict(self._spec.parameters),
|
||||
)
|
||||
|
||||
async def run_async(
|
||||
self, *, args: dict[str, Any], tool_context: ToolContext
|
||||
) -> dict[str, Any]:
|
||||
# Serialise calls within a run: tools may mutate Execution state, and the
|
||||
# first tool to end the turn must stop the rest of a parallel batch.
|
||||
async with self._control.lock:
|
||||
if self._control.outcome is not None:
|
||||
return {"error": TURN_ENDED_REPLY}
|
||||
try:
|
||||
result = await self._spec.handler(**args)
|
||||
except TypeError as exc:
|
||||
logger.info("%s: invalid arguments: %s", self._spec.name, exc)
|
||||
return {"error": f"Invalid arguments for {self._spec.name}: {exc}"}
|
||||
if result.outcome is not None:
|
||||
self._control.outcome = result.outcome
|
||||
elif result.message.startswith(REJECTION_PREFIXES):
|
||||
logger.info(
|
||||
"%s rejected by %s: %s",
|
||||
self._control.role,
|
||||
self._spec.name,
|
||||
result.message[:500],
|
||||
)
|
||||
return {"result": result.message}
|
||||
|
||||
|
||||
class AdkAgentRuntime:
|
||||
def __init__(
|
||||
self,
|
||||
*,
|
||||
skill_dirs: Mapping[str, Path],
|
||||
model_factory: ModelFactory = default_model_factory,
|
||||
max_nudges: int = 2,
|
||||
model_timeout_seconds: float | None = None,
|
||||
) -> None:
|
||||
self._max_nudges = max_nudges
|
||||
self._model_timeout_seconds = model_timeout_seconds
|
||||
self._skills: dict[str, Skill] = {}
|
||||
for name, path in skill_dirs.items():
|
||||
try:
|
||||
skill = load_skill_from_dir(path)
|
||||
except Exception as exc:
|
||||
raise ValueError(
|
||||
f"Could not load skill {name!r} from {path}: {exc}"
|
||||
) from exc
|
||||
if skill.name != name:
|
||||
raise ValueError(
|
||||
f"Skill at {path} is named {skill.name!r}, not {name!r}"
|
||||
)
|
||||
self._skills[name] = skill
|
||||
self._model_factory = model_factory
|
||||
# (role, model) -> usage across every run of this runtime
|
||||
self.usage: dict[tuple[str, str], TokenUsage] = {}
|
||||
|
||||
async def run(
|
||||
self, role: RoleSpec, task: AgentTask, tools: Sequence[ToolSpec]
|
||||
) -> Outcome:
|
||||
control = _RunControl(budget=role.budget, role=role.name)
|
||||
agent_tools: list[Any] = [_SpecTool(spec, control) for spec in tools]
|
||||
if role.skills:
|
||||
unknown = [name for name in role.skills if name not in self._skills]
|
||||
if unknown:
|
||||
raise ValueError(f"Role {role.name!r} needs unknown skills: {unknown}")
|
||||
agent_tools.append(
|
||||
SkillToolset(
|
||||
skills=[self._skills[name] for name in role.skills],
|
||||
tool_filter=SKILL_TOOLS,
|
||||
)
|
||||
)
|
||||
|
||||
instructions = role.instructions
|
||||
agent = LlmAgent(
|
||||
name=_agent_name(role.name),
|
||||
model=self._model_factory(role),
|
||||
# A callable instruction is passed verbatim: no {state} templating.
|
||||
instruction=lambda _context: instructions,
|
||||
tools=agent_tools,
|
||||
before_tool_callback=control.before_tool,
|
||||
generate_content_config=self._content_config(role),
|
||||
)
|
||||
runner = Runner(
|
||||
app_name=APP_NAME,
|
||||
agent=agent,
|
||||
session_service=InMemorySessionService(),
|
||||
auto_create_session=True,
|
||||
)
|
||||
session_id = str(uuid.uuid4())
|
||||
usage = self.usage.setdefault((role.name, role.model or "?"), TokenUsage())
|
||||
prompt = _render_task(task, role.skills)
|
||||
final_text = ""
|
||||
for attempt in range(self._max_nudges + 1):
|
||||
if attempt:
|
||||
logger.info(
|
||||
"Nudging %s to end its turn (attempt %d)", role.name, attempt
|
||||
)
|
||||
message = types.Content(role="user", parts=[types.Part(text=prompt)])
|
||||
prompt = NUDGE
|
||||
try:
|
||||
async with aclosing(
|
||||
runner.run_async(
|
||||
user_id=APP_NAME, session_id=session_id, new_message=message
|
||||
)
|
||||
) as events:
|
||||
async for event in events:
|
||||
if event.usage_metadata is not None:
|
||||
usage.add(event.usage_metadata)
|
||||
if control.outcome is not None:
|
||||
break
|
||||
if (
|
||||
event.is_final_response()
|
||||
and event.content
|
||||
and event.content.parts
|
||||
):
|
||||
text = "".join(
|
||||
part.text for part in event.content.parts if part.text
|
||||
).strip()
|
||||
final_text = text or final_text # keep the last real reply
|
||||
except MODEL_TIMEOUTS as exc:
|
||||
if control.outcome is not None:
|
||||
return control.outcome
|
||||
logger.warning(
|
||||
"%s model request timed out (%s)", role.name, type(exc).__name__
|
||||
)
|
||||
final_text = final_text or f"{role.name}'s model requests timed out."
|
||||
prompt = TIMED_OUT
|
||||
if control.outcome is not None:
|
||||
return control.outcome
|
||||
|
||||
return Stopped(
|
||||
final_text
|
||||
or f"{role.name} ended without calling a tool that ends its turn."
|
||||
)
|
||||
|
||||
def _content_config(self, role: RoleSpec) -> types.GenerateContentConfig | None:
|
||||
# A role whose replies are long is given longer than the default.
|
||||
seconds = role.model_timeout_seconds or self._model_timeout_seconds
|
||||
if seconds is None:
|
||||
return None
|
||||
return types.GenerateContentConfig(
|
||||
http_options=types.HttpOptions(timeout=int(seconds * 1000))
|
||||
)
|
||||
|
||||
|
||||
def _agent_name(role: str) -> str:
|
||||
return re.sub(r"\W", "_", role)
|
||||
|
||||
|
||||
def _render_task(task: AgentTask, skills: Sequence[str] = ()) -> str:
|
||||
context = json.dumps(task.context, indent=2, default=str, ensure_ascii=False)
|
||||
skill_line = (
|
||||
f"\n\nSkills available to you (load with load_skill): {', '.join(skills)}."
|
||||
if skills
|
||||
else ""
|
||||
)
|
||||
return f"{task.prompt}{skill_line}\n\nContext:\n```json\n{context}\n```"
|
||||
@@ -1,196 +0,0 @@
|
||||
"""ADK Multi-Agent Architecture for GCP Solution Architecture Agent.
|
||||
|
||||
Uses google.adk.agents primitives:
|
||||
- SourceDiscoveryAgent (LlmAgent)
|
||||
- DiscoveryAgent (LlmAgent)
|
||||
- ArchitectureDesignAgent (LlmAgent)
|
||||
- ValidationReviewAgent (LlmAgent)
|
||||
- PackagingAgent (LlmAgent)
|
||||
- OrchestratorLoopAgent (LoopAgent)
|
||||
"""
|
||||
|
||||
import logging
|
||||
import uuid
|
||||
from typing import Any, Dict, List, Optional
|
||||
|
||||
from app.adk.compat import BaseAgent, LlmAgent, LoopAgent, SequentialAgent
|
||||
from app.adk.tools import ADK_TOOLS
|
||||
from app.config import get_settings
|
||||
from app.database import get_db_manager
|
||||
from app.nodes import design_node, discover_node, package_node, source_discover_node, validate_node
|
||||
from app.skills.loader import SkillLoader
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class SourceDiscoveryAgent(LlmAgent):
|
||||
"""ADK Agent responsible for Phase 0a Pre-emptive Source Environment Discovery."""
|
||||
|
||||
def __init__(self, skill_loader: SkillLoader) -> None:
|
||||
super().__init__(
|
||||
name="SourceDiscoveryAgent",
|
||||
description="Audits and documents the pre-existing source environment (As-Is Architecture) before target migration.",
|
||||
instruction=skill_loader.format_skills_for_prompt("source_discover"),
|
||||
tools=[],
|
||||
)
|
||||
self.skill_loader = skill_loader
|
||||
|
||||
def execute(self, state: Dict[str, Any]) -> Dict[str, Any]:
|
||||
logger.info("Executing SourceDiscoveryAgent")
|
||||
res = source_discover_node(state, self.skill_loader)
|
||||
state_copy = dict(state)
|
||||
state_copy.update(res)
|
||||
return state_copy
|
||||
|
||||
|
||||
class DiscoveryAgent(LlmAgent):
|
||||
"""ADK Agent responsible for Phase 0 Requirements Discovery."""
|
||||
|
||||
def __init__(self, skill_loader: SkillLoader) -> None:
|
||||
super().__init__(
|
||||
name="DiscoveryAgent",
|
||||
description="Extracts functional and non-functional requirements with product selection deferred.",
|
||||
instruction=skill_loader.format_skills_for_prompt("discover"),
|
||||
tools=[],
|
||||
)
|
||||
self.skill_loader = skill_loader
|
||||
|
||||
def execute(self, state: Dict[str, Any]) -> Dict[str, Any]:
|
||||
logger.info("Executing DiscoveryAgent")
|
||||
res = discover_node(state, self.skill_loader)
|
||||
state_copy = dict(state)
|
||||
state_copy.update(res)
|
||||
return state_copy
|
||||
|
||||
|
||||
class ArchitectureDesignAgent(LlmAgent):
|
||||
"""ADK Agent responsible for Phase 1 Product Selection, Diagrams, & Terraform IaC."""
|
||||
|
||||
def __init__(self, skill_loader: SkillLoader) -> None:
|
||||
super().__init__(
|
||||
name="ArchitectureDesignAgent",
|
||||
description="Selects GCP products, generates Mermaid diagram, and produces Terraform IaC grounded by Developer Knowledge MCP.",
|
||||
instruction=skill_loader.format_skills_for_prompt("design"),
|
||||
tools=ADK_TOOLS,
|
||||
)
|
||||
self.skill_loader = skill_loader
|
||||
|
||||
def execute(self, state: Dict[str, Any]) -> Dict[str, Any]:
|
||||
logger.info("Executing ArchitectureDesignAgent")
|
||||
res = design_node(state, self.skill_loader)
|
||||
state_copy = dict(state)
|
||||
state_copy.update(res)
|
||||
return state_copy
|
||||
|
||||
|
||||
class ValidationReviewAgent(LlmAgent):
|
||||
"""ADK Agent responsible for Phase 2 Artifact Review & Quality Validation."""
|
||||
|
||||
def __init__(self, skill_loader: SkillLoader) -> None:
|
||||
super().__init__(
|
||||
name="ValidationReviewAgent",
|
||||
description="Validates Mermaid syntax, Terraform configuration, and required sections.",
|
||||
instruction=skill_loader.format_skills_for_prompt("validate"),
|
||||
tools=ADK_TOOLS,
|
||||
)
|
||||
self.skill_loader = skill_loader
|
||||
|
||||
def execute(self, state: Dict[str, Any]) -> Dict[str, Any]:
|
||||
logger.info("Executing ValidationReviewAgent")
|
||||
res = validate_node(state, self.skill_loader)
|
||||
state_copy = dict(state)
|
||||
state_copy.update(res)
|
||||
return state_copy
|
||||
|
||||
|
||||
class PackagingAgent(LlmAgent):
|
||||
"""ADK Agent responsible for Phase 3 Solution Guide Packaging."""
|
||||
|
||||
def __init__(self, skill_loader: SkillLoader) -> None:
|
||||
super().__init__(
|
||||
name="PackagingAgent",
|
||||
description="Packages final solution-architecture-guide.md.",
|
||||
instruction=skill_loader.format_skills_for_prompt("package"),
|
||||
tools=[],
|
||||
)
|
||||
self.skill_loader = skill_loader
|
||||
|
||||
def execute(self, state: Dict[str, Any]) -> Dict[str, Any]:
|
||||
logger.info("Executing PackagingAgent")
|
||||
res = package_node(state, self.skill_loader)
|
||||
state_copy = dict(state)
|
||||
state_copy.update(res)
|
||||
return state_copy
|
||||
|
||||
|
||||
class OrchestratorLoopAgent(LoopAgent):
|
||||
"""ADK Orchestrator LoopAgent that coordinates multi-agent execution & iterative quality review.
|
||||
|
||||
Uses google.adk.agents.LoopAgent to execute discovery -> design -> validation review -> packaging
|
||||
in a loop until validation passes 100% or max_iterations is reached. Writes every review iteration
|
||||
event to PostgreSQL database (`orchestrator_review_logs`).
|
||||
"""
|
||||
|
||||
def __init__(self, skill_loader: SkillLoader, max_iterations: Optional[int] = None) -> None:
|
||||
settings = get_settings()
|
||||
max_iters = max_iterations or settings.ADK_MAX_LOOP_ITERATIONS
|
||||
self.db_manager = get_db_manager()
|
||||
|
||||
self.source_discovery_agent = SourceDiscoveryAgent(skill_loader)
|
||||
self.discovery_agent = DiscoveryAgent(skill_loader)
|
||||
self.design_agent = ArchitectureDesignAgent(skill_loader)
|
||||
self.validation_agent = ValidationReviewAgent(skill_loader)
|
||||
self.packaging_agent = PackagingAgent(skill_loader)
|
||||
|
||||
sub_pipeline = SequentialAgent(
|
||||
name="MultiAgentGCPPipeline",
|
||||
sub_agents=[
|
||||
self.source_discovery_agent,
|
||||
self.discovery_agent,
|
||||
self.design_agent,
|
||||
self.validation_agent,
|
||||
self.packaging_agent,
|
||||
],
|
||||
description="Sequential pipeline of GCP architecture multi-agents.",
|
||||
)
|
||||
|
||||
def review_validator(state: Dict[str, Any]) -> bool:
|
||||
"""Check if solution meets production quality validation standards."""
|
||||
is_valid = state.get("validation_passed", False)
|
||||
errors = state.get("errors", [])
|
||||
iteration = state.get("loop_count", 1)
|
||||
execution_id = state.get("execution_id", str(uuid.uuid4()))
|
||||
|
||||
status_str = "APPROVED" if is_valid else "NEEDS_REVISION"
|
||||
feedback_str = "All architecture validation rules passed." if is_valid else f"Validation errors: {', '.join(errors)}"
|
||||
|
||||
# Record review iteration in PostgreSQL database
|
||||
self.db_manager.record_orchestrator_log(
|
||||
log_id=str(uuid.uuid4()),
|
||||
execution_id=execution_id,
|
||||
iteration=iteration,
|
||||
review_status=status_str,
|
||||
reviewer_agent="ValidationReviewAgent",
|
||||
feedback=feedback_str,
|
||||
)
|
||||
logger.info(
|
||||
"Orchestrator Review Loop #%d: status=%s, valid=%s",
|
||||
iteration,
|
||||
status_str,
|
||||
is_valid,
|
||||
)
|
||||
|
||||
return is_valid
|
||||
|
||||
super().__init__(
|
||||
name="OrchestratorLoopAgent",
|
||||
sub_agent=sub_pipeline,
|
||||
max_iterations=max_iters,
|
||||
description="Production-ready multi-agent orchestrator loop agent.",
|
||||
validator_fn=review_validator,
|
||||
)
|
||||
|
||||
|
||||
def build_adk_multi_agent_system(skill_loader: SkillLoader, max_iterations: Optional[int] = None) -> OrchestratorLoopAgent:
|
||||
"""Factory function for building the complete ADK Orchestrator LoopAgent system."""
|
||||
return OrchestratorLoopAgent(skill_loader, max_iterations=max_iterations)
|
||||
@@ -1,77 +0,0 @@
|
||||
"""ADK Artifact Management for GCP Solution Architecture Agent.
|
||||
|
||||
Uses google.adk.artifacts.ArtifactRepository backed by local filesystem and PostgreSQL persistence.
|
||||
"""
|
||||
|
||||
import logging
|
||||
from pathlib import Path
|
||||
from typing import Any, Dict, Optional, List
|
||||
|
||||
from app.adk.compat import Artifact, ArtifactRepository
|
||||
from app.database import get_db_manager
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class PostgresArtifactRepository(ArtifactRepository):
|
||||
"""ADK Artifact Repository with PostgreSQL database & filesystem synchronization."""
|
||||
|
||||
def __init__(self, base_dir: Optional[Path] = None) -> None:
|
||||
super().__init__()
|
||||
self.base_dir = base_dir or Path(".").resolve()
|
||||
self.db_manager = get_db_manager()
|
||||
|
||||
def save_solution_artifacts(self, execution_id: str, state: Dict[str, Any]) -> List[Artifact]:
|
||||
"""Write workflow execution output artifacts to disk and PostgreSQL database."""
|
||||
saved_artifacts: List[Artifact] = []
|
||||
|
||||
artifact_mapping = [
|
||||
# Structured scalable active deliverables
|
||||
("source_discovery_doc", "deliverables/as-is/source-architecture.md", "markdown"),
|
||||
("source_mermaid_diagram", "deliverables/as-is/source-architecture.mmd", "mermaid"),
|
||||
("requirements_doc", "deliverables/target/requirements.md", "markdown"),
|
||||
("architecture_doc", "deliverables/target/architecture.md", "markdown"),
|
||||
("mermaid_diagram", "deliverables/target/architecture.mmd", "mermaid"),
|
||||
("terraform_code", "terraform/main.tf", "hcl"),
|
||||
("validation_results", "deliverables/validation/validation-results.md", "markdown"),
|
||||
("solution_guide", "deliverables/guides/solution-architecture-guide.md", "markdown"),
|
||||
|
||||
# Per-execution isolated deliverables for scalable history tracking
|
||||
("source_discovery_doc", f"deliverables/executions/{execution_id}/as-is/source-architecture.md", "markdown"),
|
||||
("source_mermaid_diagram", f"deliverables/executions/{execution_id}/as-is/source-architecture.mmd", "mermaid"),
|
||||
("requirements_doc", f"deliverables/executions/{execution_id}/target/requirements.md", "markdown"),
|
||||
("architecture_doc", f"deliverables/executions/{execution_id}/target/architecture.md", "markdown"),
|
||||
("mermaid_diagram", f"deliverables/executions/{execution_id}/target/architecture.mmd", "mermaid"),
|
||||
("validation_results", f"deliverables/executions/{execution_id}/validation/validation-results.md", "markdown"),
|
||||
("solution_guide", f"deliverables/executions/{execution_id}/guides/solution-architecture-guide.md", "markdown"),
|
||||
|
||||
# Mirror docs for specification compatibility
|
||||
("source_discovery_doc", "docs/source-architecture.md", "markdown"),
|
||||
("requirements_doc", "docs/requirements.md", "markdown"),
|
||||
("architecture_doc", "docs/architecture.md", "markdown"),
|
||||
]
|
||||
|
||||
for state_key, rel_path, art_type in artifact_mapping:
|
||||
content = state.get(state_key)
|
||||
if not content:
|
||||
continue
|
||||
|
||||
full_path = self.base_dir / rel_path
|
||||
full_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
full_path.write_text(content, encoding="utf-8")
|
||||
|
||||
# Save in ADK memory store
|
||||
art = self.save_artifact(art_type, str(rel_path), content)
|
||||
saved_artifacts.append(art)
|
||||
|
||||
# Persist to PostgreSQL database
|
||||
self.db_manager.save_artifact(
|
||||
artifact_id=art.artifact_id,
|
||||
execution_id=execution_id,
|
||||
artifact_type=art_type,
|
||||
file_path=str(rel_path),
|
||||
content=content,
|
||||
)
|
||||
logger.info("Persisted ADK artifact '%s' (%s) to DB and %s", art_type, art.artifact_id, rel_path)
|
||||
|
||||
return saved_artifacts
|
||||
@@ -1,288 +0,0 @@
|
||||
"""Google ADK (Agent Development Kit) Compatibility & Abstraction Layer.
|
||||
|
||||
Re-exports native `google.adk` framework components when available, or provides
|
||||
fully functional compatibility stubs matching ADK interfaces for:
|
||||
- google.adk.agents (Agent, LlmAgent, SequentialAgent, ParallelAgent, LoopAgent)
|
||||
- google.adk.workflows (Workflow, WorkflowStep)
|
||||
- google.adk.runners (Runner)
|
||||
- google.adk.sessions (Session, SessionService, InMemorySessionService, PostgresSessionService)
|
||||
- google.adk.artifacts (Artifact, ArtifactRepository)
|
||||
- google.adk.tools (Tool, FunctionTool)
|
||||
- google.adk.evaluation (Evaluator, BenchmarkRunner)
|
||||
"""
|
||||
|
||||
import logging
|
||||
import uuid
|
||||
from typing import Any, Callable, Dict, List, Optional
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# Attempt importing native google.adk modules
|
||||
HAS_NATIVE_ADK = False
|
||||
|
||||
try:
|
||||
import google.adk.agents as _native_agents
|
||||
import google.adk.workflows as _native_workflows
|
||||
import google.adk.runners as _native_runners
|
||||
import google.adk.sessions as _native_sessions
|
||||
import google.adk.artifacts as _native_artifacts
|
||||
import google.adk.tools as _native_tools
|
||||
import google.adk.evaluation as _native_evaluation
|
||||
|
||||
HAS_NATIVE_ADK = True
|
||||
logger.info("Successfully imported native google.adk framework modules.")
|
||||
except ImportError:
|
||||
HAS_NATIVE_ADK = False
|
||||
logger.info("Native google.adk not installed; using ADK framework compatibility layer.")
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 1. google.adk.agents
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
class BaseAgent:
|
||||
"""Base class for ADK Agents."""
|
||||
|
||||
def __init__(self, name: str, description: str = "", instruction: str = "", tools: Optional[List[Any]] = None) -> None:
|
||||
self.name = name
|
||||
self.description = description
|
||||
self.instruction = instruction
|
||||
self.tools = tools or []
|
||||
|
||||
def execute(self, state: Dict[str, Any]) -> Dict[str, Any]:
|
||||
"""Execute agent logic against state."""
|
||||
return state
|
||||
|
||||
|
||||
class LlmAgent(BaseAgent):
|
||||
"""ADK LLM Agent primitive."""
|
||||
|
||||
def __init__(self, name: str, description: str = "", instruction: str = "", model: Any = None, tools: Optional[List[Any]] = None) -> None:
|
||||
super().__init__(name, description, instruction, tools)
|
||||
self.model = model
|
||||
|
||||
|
||||
class SequentialAgent(BaseAgent):
|
||||
"""ADK Sequential Workflow Agent."""
|
||||
|
||||
def __init__(self, name: str, sub_agents: List[BaseAgent], description: str = "") -> None:
|
||||
super().__init__(name, description)
|
||||
self.sub_agents = sub_agents
|
||||
|
||||
def execute(self, state: Dict[str, Any]) -> Dict[str, Any]:
|
||||
curr_state = dict(state)
|
||||
for agent in self.sub_agents:
|
||||
curr_state = agent.execute(curr_state)
|
||||
return curr_state
|
||||
|
||||
|
||||
class ParallelAgent(BaseAgent):
|
||||
"""ADK Parallel Workflow Agent."""
|
||||
|
||||
def __init__(self, name: str, sub_agents: List[BaseAgent], description: str = "") -> None:
|
||||
super().__init__(name, description)
|
||||
self.sub_agents = sub_agents
|
||||
|
||||
def execute(self, state: Dict[str, Any]) -> Dict[str, Any]:
|
||||
curr_state = dict(state)
|
||||
for agent in self.sub_agents:
|
||||
res = agent.execute(curr_state)
|
||||
curr_state.update(res)
|
||||
return curr_state
|
||||
|
||||
|
||||
class LoopAgent(BaseAgent):
|
||||
"""ADK Loop Agent for iterative review and validation feedback cycles."""
|
||||
|
||||
def __init__(self, name: str, sub_agent: BaseAgent, max_iterations: int = 5, description: str = "", validator_fn: Optional[Callable[[Dict[str, Any]], bool]] = None) -> None:
|
||||
super().__init__(name, description)
|
||||
self.sub_agent = sub_agent
|
||||
self.max_iterations = max_iterations
|
||||
self.validator_fn = validator_fn
|
||||
|
||||
def execute(self, state: Dict[str, Any]) -> Dict[str, Any]:
|
||||
curr_state = dict(state)
|
||||
loop_count = 0
|
||||
while loop_count < self.max_iterations:
|
||||
loop_count += 1
|
||||
curr_state["loop_count"] = loop_count
|
||||
curr_state = self.sub_agent.execute(curr_state)
|
||||
if self.validator_fn and self.validator_fn(curr_state):
|
||||
curr_state["loop_completed_successfully"] = True
|
||||
break
|
||||
curr_state["total_loop_iterations"] = loop_count
|
||||
return curr_state
|
||||
|
||||
|
||||
# Alias Agent to LlmAgent / BaseAgent
|
||||
Agent = LlmAgent
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 2. google.adk.tools
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
class Tool:
|
||||
"""ADK Tool Interface."""
|
||||
|
||||
def __init__(self, name: str, description: str, func: Callable) -> None:
|
||||
self.name = name
|
||||
self.description = description
|
||||
self.func = func
|
||||
|
||||
def run(self, *args, **kwargs) -> Any:
|
||||
return self.func(*args, **kwargs)
|
||||
|
||||
|
||||
class FunctionTool(Tool):
|
||||
"""ADK Function Tool primitive."""
|
||||
|
||||
@classmethod
|
||||
def from_defaults(cls, fn: Callable, name: Optional[str] = None, description: Optional[str] = None) -> "FunctionTool":
|
||||
tool_name = name or fn.__name__
|
||||
tool_desc = description or (fn.__doc__ or "")
|
||||
return cls(name=tool_name, description=tool_desc, func=fn)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 3. google.adk.artifacts
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
class Artifact:
|
||||
"""ADK Artifact container."""
|
||||
|
||||
def __init__(self, artifact_id: str, artifact_type: str, file_path: str, content: str) -> None:
|
||||
self.artifact_id = artifact_id
|
||||
self.artifact_type = artifact_type
|
||||
self.file_path = file_path
|
||||
self.content = content
|
||||
|
||||
|
||||
class ArtifactRepository:
|
||||
"""ADK Artifact Repository interface."""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self._store: Dict[str, Artifact] = {}
|
||||
|
||||
def save_artifact(self, artifact_type: str, file_path: str, content: str) -> Artifact:
|
||||
artifact_id = str(uuid.uuid4())
|
||||
art = Artifact(artifact_id, artifact_type, file_path, content)
|
||||
self._store[artifact_id] = art
|
||||
return art
|
||||
|
||||
def get_artifact(self, artifact_id: str) -> Optional[Artifact]:
|
||||
return self._store.get(artifact_id)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 4. google.adk.sessions
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
class Session:
|
||||
"""ADK Session object."""
|
||||
|
||||
def __init__(self, session_id: str, agent_name: str, state: Optional[Dict[str, Any]] = None) -> None:
|
||||
self.session_id = session_id
|
||||
self.agent_name = agent_name
|
||||
self.state = state or {}
|
||||
|
||||
|
||||
class SessionService:
|
||||
"""ADK Session Service interface."""
|
||||
|
||||
def create_session(self, agent_name: str, session_id: Optional[str] = None) -> Session:
|
||||
sid = session_id or str(uuid.uuid4())
|
||||
return Session(sid, agent_name)
|
||||
|
||||
def get_session(self, session_id: str) -> Optional[Session]:
|
||||
raise NotImplementedError
|
||||
|
||||
def save_session(self, session: Session) -> bool:
|
||||
raise NotImplementedError
|
||||
|
||||
|
||||
class InMemorySessionService(SessionService):
|
||||
"""In-memory ADK Session Service."""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self._sessions: Dict[str, Session] = {}
|
||||
|
||||
def create_session(self, agent_name: str, session_id: Optional[str] = None) -> Session:
|
||||
sid = session_id or str(uuid.uuid4())
|
||||
sess = Session(sid, agent_name)
|
||||
self._sessions[sid] = sess
|
||||
return sess
|
||||
|
||||
def get_session(self, session_id: str) -> Optional[Session]:
|
||||
return self._sessions.get(session_id)
|
||||
|
||||
def save_session(self, session: Session) -> bool:
|
||||
self._sessions[session.session_id] = session
|
||||
return True
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 5. google.adk.runners
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
class Runner:
|
||||
"""ADK Runner for executing agents and workflows."""
|
||||
|
||||
def __init__(self, agent: BaseAgent, session_service: Optional[SessionService] = None) -> None:
|
||||
self.agent = agent
|
||||
self.session_service = session_service or InMemorySessionService()
|
||||
|
||||
def run(self, session_id: str, input_state: Dict[str, Any]) -> Dict[str, Any]:
|
||||
session = self.session_service.get_session(session_id)
|
||||
if not session:
|
||||
session = self.session_service.create_session(self.agent.name, session_id)
|
||||
|
||||
merged_state = {**session.state, **input_state}
|
||||
result_state = self.agent.execute(merged_state)
|
||||
session.state = result_state
|
||||
self.session_service.save_session(session)
|
||||
return result_state
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 6. google.adk.workflows
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
class WorkflowStep:
|
||||
"""ADK Workflow Step."""
|
||||
|
||||
def __init__(self, step_name: str, agent: BaseAgent) -> None:
|
||||
self.step_name = step_name
|
||||
self.agent = agent
|
||||
|
||||
|
||||
class Workflow:
|
||||
"""ADK Workflow composition container."""
|
||||
|
||||
def __init__(self, name: str, steps: List[WorkflowStep]) -> None:
|
||||
self.name = name
|
||||
self.steps = steps
|
||||
|
||||
def execute(self, initial_state: Dict[str, Any]) -> Dict[str, Any]:
|
||||
state = dict(initial_state)
|
||||
for step in self.steps:
|
||||
state = step.agent.execute(state)
|
||||
return state
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 7. google.adk.evaluation
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
class Evaluator:
|
||||
"""ADK Benchmark Evaluator."""
|
||||
|
||||
def evaluate(self, agent: BaseAgent, test_case: Dict[str, Any]) -> Dict[str, Any]:
|
||||
initial_state = test_case.get("input_state", {})
|
||||
result = agent.execute(initial_state)
|
||||
return {
|
||||
"case_id": test_case.get("case_id", "default"),
|
||||
"result_state": result,
|
||||
"passed": True,
|
||||
"score": 1.0,
|
||||
}
|
||||
@@ -1,57 +0,0 @@
|
||||
"""ADK Evaluation module for GCP Solution Architecture Agent.
|
||||
|
||||
Uses google.adk.evaluation.Evaluator with PostgreSQL database persistence.
|
||||
"""
|
||||
|
||||
import logging
|
||||
import uuid
|
||||
from typing import Any, Dict, List, Optional
|
||||
|
||||
from app.adk.compat import Evaluator
|
||||
from app.adk.runners import ADKAgentRunner
|
||||
from app.database import get_db_manager
|
||||
from eval.metrics import evaluate_case_run
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class ADKEvaluator(Evaluator):
|
||||
"""ADK Evaluator persisting evaluation results to PostgreSQL."""
|
||||
|
||||
def __init__(self) -> None:
|
||||
super().__init__()
|
||||
self.runner = ADKAgentRunner()
|
||||
self.db_manager = get_db_manager()
|
||||
|
||||
def evaluate_benchmark_case(self, case: Dict[str, Any]) -> Dict[str, Any]:
|
||||
"""Execute and score benchmark case via ADK runner and record to PostgreSQL."""
|
||||
eval_id = str(uuid.uuid4())
|
||||
case_id = case.get("id", "case-unknown")
|
||||
req_summary = case.get("workflow_request", "")
|
||||
|
||||
run_res = self.runner.run_execution(request_summary=req_summary)
|
||||
artifacts = run_res.get("artifacts", {})
|
||||
|
||||
state_for_metrics = {
|
||||
"requirements_doc": artifacts.get("requirements_doc", ""),
|
||||
"architecture_doc": artifacts.get("architecture_doc", ""),
|
||||
"mermaid_diagram": artifacts.get("mermaid_diagram", ""),
|
||||
"terraform_code": artifacts.get("terraform_code", ""),
|
||||
"solution_guide": artifacts.get("solution_guide", ""),
|
||||
}
|
||||
|
||||
eval_result = evaluate_case_run(state_for_metrics, case)
|
||||
|
||||
# Save evaluation to PostgreSQL database
|
||||
self.db_manager.save_evaluation(
|
||||
eval_id=eval_id,
|
||||
case_id=case_id,
|
||||
total_score=eval_result["total_score"],
|
||||
max_score=eval_result["max_score"],
|
||||
pass_rate=eval_result["percentage"],
|
||||
passed=eval_result["passed"],
|
||||
details=eval_result,
|
||||
)
|
||||
|
||||
logger.info("Recorded ADK evaluation %s for case %s (Score: %.1f%%)", eval_id, case_id, eval_result["percentage"])
|
||||
return eval_result
|
||||
208
app/adk/fake_runtime.py
Normal file
208
app/adk/fake_runtime.py
Normal file
@@ -0,0 +1,208 @@
|
||||
"""A scripted AgentRuntime for deterministic tests and evaluation dry runs.
|
||||
|
||||
Each role has a queue of turns; a turn is a list of tool calls, or a function of the
|
||||
task that returns one. Calls go through the real ToolSpecs, so every rule the tools
|
||||
enforce is exercised exactly as a model would meet it.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from collections import deque
|
||||
from collections.abc import Callable, Mapping, Sequence
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Any
|
||||
|
||||
from app.adk.runtime import (
|
||||
AgentTask,
|
||||
Answer,
|
||||
BudgetExhausted,
|
||||
Outcome,
|
||||
Question,
|
||||
RoleSpec,
|
||||
Stopped,
|
||||
ToolSpec,
|
||||
)
|
||||
from app.workflows.deliverables import DEPENDENCY_GRAPH, DeliverableKind
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Call:
|
||||
tool: str
|
||||
args: Mapping[str, Any] = field(default_factory=dict)
|
||||
|
||||
|
||||
Turn = Sequence[Call] | Callable[[AgentTask], Sequence[Call]]
|
||||
|
||||
|
||||
# One small, coherent Requirements chain, so sample submissions pass every link.
|
||||
SAMPLE_DATA: dict[str, str] = {
|
||||
"requirements.json": json.dumps(
|
||||
[
|
||||
{"id": "FR-1", "kind": "functional", "text": "Accept events."},
|
||||
{"id": "NFR-1", "kind": "non_functional", "text": "99.9% availability."},
|
||||
]
|
||||
),
|
||||
"components.json": json.dumps(
|
||||
[{"id": "C-1", "name": "Ingress", "requirements": ["FR-1", "NFR-1"]}]
|
||||
),
|
||||
"products.json": json.dumps([{"component": "C-1", "product": "Example Run"}]),
|
||||
"recommendations.json": json.dumps(
|
||||
[
|
||||
{
|
||||
"id": "DR-1",
|
||||
"pillar": "security",
|
||||
"text": "Use a dedicated identity.",
|
||||
"components": ["C-1"],
|
||||
}
|
||||
]
|
||||
),
|
||||
"target-architecture.json": json.dumps(
|
||||
{
|
||||
"elements": [
|
||||
{
|
||||
"id": "E-1",
|
||||
"name": "Ingress service",
|
||||
"component": "C-1",
|
||||
"product": "Example Run",
|
||||
"resource_type": "example_run_service",
|
||||
},
|
||||
{
|
||||
"id": "E-2",
|
||||
"name": "Ingress identity",
|
||||
"product": "Example IAM",
|
||||
"resource_type": "example_service_account",
|
||||
},
|
||||
],
|
||||
"relationships": [
|
||||
{"id": "R-1", "from": "E-1", "to": "E-2", "kind": "runs as"}
|
||||
],
|
||||
"checks": [
|
||||
{
|
||||
"id": "K-1",
|
||||
"applies_to": "E-1",
|
||||
"statement": "The service runs at least two instances.",
|
||||
"source": "NFR-1",
|
||||
},
|
||||
{
|
||||
"id": "K-2",
|
||||
"applies_to": "E-2",
|
||||
"statement": "The identity is used by this service only.",
|
||||
"source": "DR-1",
|
||||
},
|
||||
],
|
||||
}
|
||||
),
|
||||
"implementation.json": json.dumps(
|
||||
[
|
||||
{"check": "K-1", "file": "terraform/main.tf", "address": "example.run"},
|
||||
{"check": "K-2", "file": "terraform/main.tf", "address": "example.sa"},
|
||||
]
|
||||
),
|
||||
"verdicts.json": json.dumps(
|
||||
{
|
||||
"dry_run": {"verdict": "pass", "evidence": "terraform validate passed."},
|
||||
"checks": [
|
||||
{"check": "K-1", "verdict": "pass", "evidence": "min instances is 2."},
|
||||
{"check": "K-2", "verdict": "pass", "evidence": "One binding."},
|
||||
],
|
||||
"proposed_additions": [],
|
||||
}
|
||||
),
|
||||
}
|
||||
|
||||
|
||||
def sample_submission(kind: DeliverableKind, note: str = "") -> Call:
|
||||
"""A `submit_deliverable` call that meets the Deliverable's contract."""
|
||||
spec = DEPENDENCY_GRAPH[kind]
|
||||
parts = [f"# {kind}", note or "Summary."]
|
||||
parts += [f"## {section}\n{note or 'Details.'}" for section in spec.sections]
|
||||
attachments = {
|
||||
name: SAMPLE_DATA.get(name, f"# {name}\n") for name in spec.attachments
|
||||
}
|
||||
return Call(
|
||||
"submit_deliverable",
|
||||
{"content": "\n".join(parts) + "\n", "attachments": attachments},
|
||||
)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class RunRecord:
|
||||
role: str
|
||||
task: AgentTask
|
||||
tools: tuple[str, ...]
|
||||
results: tuple[tuple[str, str], ...] # (tool name, message)
|
||||
outcome: Outcome
|
||||
|
||||
|
||||
class ScriptExhausted(AssertionError):
|
||||
"""A role was run more times than the test scripted."""
|
||||
|
||||
|
||||
class FakeAgentRuntime:
|
||||
def __init__(self, turns: Mapping[str, Sequence[Turn]]) -> None:
|
||||
self._turns = {role: deque(role_turns) for role, role_turns in turns.items()}
|
||||
self.runs: list[RunRecord] = []
|
||||
|
||||
def remaining(self, role: str) -> int:
|
||||
return len(self._turns.get(role, ()))
|
||||
|
||||
async def run(
|
||||
self, role: RoleSpec, task: AgentTask, tools: Sequence[ToolSpec]
|
||||
) -> Outcome:
|
||||
queue = self._turns.get(role.name)
|
||||
if not queue:
|
||||
raise ScriptExhausted(f"No scripted turn left for role {role.name!r}")
|
||||
turn = queue.popleft()
|
||||
calls = turn(task) if callable(turn) else turn
|
||||
by_name = {tool.name: tool for tool in tools}
|
||||
|
||||
results: list[tuple[str, str]] = []
|
||||
outcome: Outcome = Stopped(
|
||||
"The script ended without a tool that ends the turn."
|
||||
)
|
||||
for index, call in enumerate(calls):
|
||||
if index >= role.budget:
|
||||
outcome = BudgetExhausted(
|
||||
f"{role.name} used all {role.budget} tool calls before finishing."
|
||||
)
|
||||
break
|
||||
if call.tool not in by_name:
|
||||
raise ValueError(
|
||||
f"{role.name} called {call.tool!r}, which it was not offered: "
|
||||
f"{sorted(by_name)}"
|
||||
)
|
||||
result = await by_name[call.tool].handler(**call.args)
|
||||
results.append((call.tool, result.message))
|
||||
if result.outcome is not None:
|
||||
outcome = result.outcome
|
||||
break
|
||||
|
||||
self.runs.append(
|
||||
RunRecord(role.name, task, tuple(by_name), tuple(results), outcome)
|
||||
)
|
||||
return outcome
|
||||
|
||||
|
||||
class FakeDecider:
|
||||
"""A scripted Decider: answers by question id, or declines so callers fall back.
|
||||
|
||||
`answers` maps a question id to an Answer, or to a function of (state, question)
|
||||
returning one. An id with no entry makes the whole decision unavailable.
|
||||
"""
|
||||
|
||||
def __init__(self, answers: Mapping[str, Any] | None = None) -> None:
|
||||
self.answers = dict(answers or {})
|
||||
self.asked: list[tuple[str, dict[str, Question], str]] = []
|
||||
|
||||
async def decide(
|
||||
self, state: str, questions: Mapping[str, Question], *, scope: str = ""
|
||||
) -> Mapping[str, Answer] | None:
|
||||
self.asked.append((state, dict(questions), scope))
|
||||
decided = {}
|
||||
for name, question in questions.items():
|
||||
if name not in self.answers:
|
||||
return None
|
||||
answer = self.answers[name]
|
||||
decided[name] = answer(state, question) if callable(answer) else answer
|
||||
return decided
|
||||
134
app/adk/roles.py
Normal file
134
app/adk/roles.py
Normal file
@@ -0,0 +1,134 @@
|
||||
"""Load role files (agents/<role>.md) into RoleSpecs for one Cloud provider.
|
||||
|
||||
Role files are framework- and provider-neutral: frontmatter names the role, the
|
||||
Deliverable it owns, the local tools it uses, an optional budget and shared partials to
|
||||
include. The provider bundle supplies each role's Skills, MCP servers and model.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
from app.adk.runtime import RoleSpec
|
||||
from app.providers import ProviderBundle
|
||||
from app.skills.agent_skills import SkillFormatError, split_frontmatter
|
||||
from app.workflows.deliverables import DEPENDENCY_GRAPH, DeliverableKind
|
||||
|
||||
ORCHESTRATOR = "orchestrator"
|
||||
PILLAR_ADVISOR = "pillar-advisor"
|
||||
REPLY_WRITER = "reply-writer"
|
||||
PARTIALS_DIR = "partials"
|
||||
|
||||
_ALLOWED_FIELDS = {"role", "deliverable", "tools", "budget", "includes"}
|
||||
|
||||
|
||||
class RoleConfigError(ValueError):
|
||||
"""A role file is missing or invalid."""
|
||||
|
||||
|
||||
def load_roles(
|
||||
agents_dir: Path,
|
||||
bundle: ProviderBundle,
|
||||
*,
|
||||
orchestrator_budget: int = 40,
|
||||
specialist_budget: int = 15,
|
||||
include_preview_mcp: bool = True,
|
||||
) -> dict[str, RoleSpec]:
|
||||
specialists = {spec.specialist: kind for kind, spec in DEPENDENCY_GRAPH.items()}
|
||||
required = {ORCHESTRATOR, PILLAR_ADVISOR, REPLY_WRITER, *specialists}
|
||||
|
||||
roles = {}
|
||||
for path in sorted(agents_dir.glob("*.md")):
|
||||
role = _load_role(
|
||||
path,
|
||||
agents_dir,
|
||||
bundle,
|
||||
specialists,
|
||||
orchestrator_budget if path.stem == ORCHESTRATOR else specialist_budget,
|
||||
include_preview_mcp,
|
||||
)
|
||||
roles[role.name] = role
|
||||
|
||||
missing = sorted(required - set(roles))
|
||||
if missing:
|
||||
raise RoleConfigError(
|
||||
f"{agents_dir}: missing role files for {', '.join(missing)}"
|
||||
)
|
||||
unexpected = sorted(set(roles) - required)
|
||||
if unexpected:
|
||||
raise RoleConfigError(
|
||||
f"{agents_dir}: unexpected role files {', '.join(unexpected)}"
|
||||
)
|
||||
return roles
|
||||
|
||||
|
||||
def _load_role(
|
||||
path: Path,
|
||||
agents_dir: Path,
|
||||
bundle: ProviderBundle,
|
||||
specialists: dict[str, DeliverableKind],
|
||||
default_budget: int,
|
||||
include_preview_mcp: bool,
|
||||
) -> RoleSpec:
|
||||
try:
|
||||
frontmatter, body = split_frontmatter(path.read_text(encoding="utf-8"), path)
|
||||
except SkillFormatError as exc:
|
||||
raise RoleConfigError(str(exc)) from exc
|
||||
|
||||
def fail(message: str) -> RoleConfigError:
|
||||
return RoleConfigError(f"{path}: {message}")
|
||||
|
||||
unknown = sorted(set(frontmatter) - _ALLOWED_FIELDS)
|
||||
if unknown:
|
||||
raise fail(
|
||||
f"unsupported fields {', '.join(unknown)}; skills, MCP servers and models "
|
||||
"come from the provider bundle"
|
||||
)
|
||||
|
||||
name = frontmatter.get("role")
|
||||
if name != path.stem:
|
||||
raise fail(f"'role' {name!r} must match the file name {path.stem!r}")
|
||||
|
||||
deliverable = frontmatter.get("deliverable")
|
||||
if name in specialists:
|
||||
expected = specialists[name].value
|
||||
if deliverable != expected:
|
||||
raise fail(f"'deliverable' must be {expected!r}, not {deliverable!r}")
|
||||
elif deliverable is not None:
|
||||
raise fail(f"role {name!r} owns no Deliverable, but names {deliverable!r}")
|
||||
|
||||
tools = tuple(frontmatter.get("tools") or ())
|
||||
offered = {name for names in bundle.tools.values() for name in names}
|
||||
unknown_tools = [tool for tool in tools if tool not in offered]
|
||||
if unknown_tools:
|
||||
raise fail(
|
||||
f"'tools' {', '.join(unknown_tools)} are not offered by the "
|
||||
f"{bundle.name} provider bundle"
|
||||
)
|
||||
|
||||
budget = frontmatter.get("budget", default_budget)
|
||||
if not isinstance(budget, int) or budget < 1:
|
||||
raise fail("'budget' must be a positive integer")
|
||||
|
||||
sections = [body.strip()]
|
||||
for include in frontmatter.get("includes") or ():
|
||||
partial = agents_dir / PARTIALS_DIR / f"{include}.md"
|
||||
if not partial.is_file():
|
||||
raise fail(f"include {include!r} not found at {partial}")
|
||||
sections.append(partial.read_text(encoding="utf-8").strip())
|
||||
if not sections[0]:
|
||||
raise fail("instructions (the body after the frontmatter) must not be empty")
|
||||
|
||||
return RoleSpec(
|
||||
name=name,
|
||||
instructions="\n\n".join(sections),
|
||||
budget=budget,
|
||||
skills=tuple(bundle.role_skills.get(name, ())),
|
||||
tools=tools,
|
||||
mcp_servers=tuple(
|
||||
server.id
|
||||
for server in bundle.mcp_servers_for_role(name, include_preview_mcp)
|
||||
),
|
||||
model=bundle.models.for_role(name),
|
||||
model_timeout_seconds=bundle.models.timeout_for(name),
|
||||
)
|
||||
@@ -1,93 +0,0 @@
|
||||
"""ADK Execution Runner for GCP Solution Architecture Agent.
|
||||
|
||||
Uses google.adk.runners.Runner integrated with PostgresSessionService,
|
||||
PostgresArtifactRepository, and PostgreSQL database state updates.
|
||||
"""
|
||||
|
||||
import logging
|
||||
import uuid
|
||||
from typing import Any, Dict, Optional
|
||||
|
||||
from app.adk.agents import build_adk_multi_agent_system
|
||||
from app.adk.artifacts import PostgresArtifactRepository
|
||||
from app.adk.compat import Runner
|
||||
from app.adk.sessions import PostgresSessionService
|
||||
from app.config import get_settings
|
||||
from app.database import get_db_manager
|
||||
from app.skills.loader import SkillLoader
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class ADKAgentRunner:
|
||||
"""Production-ready ADK Execution Runner."""
|
||||
|
||||
def __init__(self, skill_loader: SkillLoader | None = None) -> None:
|
||||
settings = get_settings()
|
||||
self.skill_loader = skill_loader or SkillLoader(settings.SKILLS_DIR)
|
||||
self.skill_loader.load_skills()
|
||||
|
||||
self.session_service = PostgresSessionService()
|
||||
self.artifact_repo = PostgresArtifactRepository(settings.BASE_DIR)
|
||||
self.db_manager = get_db_manager()
|
||||
|
||||
self.orchestrator = build_adk_multi_agent_system(
|
||||
self.skill_loader,
|
||||
max_iterations=settings.ADK_MAX_LOOP_ITERATIONS,
|
||||
)
|
||||
self.runner = Runner(agent=self.orchestrator, session_service=self.session_service)
|
||||
|
||||
def run_execution(self, session_id: Optional[str] = None, request_summary: str = "", target_dir: str = ".") -> Dict[str, Any]:
|
||||
"""Execute multi-agent workflow using ADK runner with PostgreSQL state persistence."""
|
||||
sid = session_id or str(uuid.uuid4())
|
||||
execution_id = str(uuid.uuid4())
|
||||
|
||||
initial_input = {
|
||||
"execution_id": execution_id,
|
||||
"workflow_request": request_summary or "Event-driven regional HTTP application reference architecture",
|
||||
"target_dir": target_dir,
|
||||
"active_skills": [],
|
||||
}
|
||||
|
||||
logger.info("Starting ADK runner execution %s for session %s", execution_id, sid)
|
||||
|
||||
# Run through ADK Runner
|
||||
result_state = self.runner.run(session_id=sid, input_state=initial_input)
|
||||
|
||||
# Save artifacts to disk & PostgreSQL database
|
||||
saved_artifacts = self.artifact_repo.save_solution_artifacts(execution_id, result_state)
|
||||
|
||||
# Record execution in PostgreSQL database
|
||||
self.db_manager.save_workflow_execution(
|
||||
execution_id=execution_id,
|
||||
session_id=sid,
|
||||
status="completed" if result_state.get("validation_passed") else "failed",
|
||||
current_phase=result_state.get("current_phase", "package"),
|
||||
loop_count=result_state.get("total_loop_iterations", 1),
|
||||
request_summary=request_summary,
|
||||
results={
|
||||
"validation_passed": result_state.get("validation_passed", False),
|
||||
"active_skills": result_state.get("active_skills", []),
|
||||
"artifacts_saved": len(saved_artifacts),
|
||||
},
|
||||
)
|
||||
|
||||
return {
|
||||
"execution_id": execution_id,
|
||||
"session_id": sid,
|
||||
"status": "success" if result_state.get("validation_passed") else "completed_with_warnings",
|
||||
"validation_passed": result_state.get("validation_passed", False),
|
||||
"total_loop_iterations": result_state.get("total_loop_iterations", 1),
|
||||
"current_phase": result_state.get("current_phase", "package"),
|
||||
"artifacts": {
|
||||
"source_discovery_doc": result_state.get("source_discovery_doc"),
|
||||
"source_mermaid_diagram": result_state.get("source_mermaid_diagram"),
|
||||
"requirements_doc": result_state.get("requirements_doc"),
|
||||
"architecture_doc": result_state.get("architecture_doc"),
|
||||
"mermaid_diagram": result_state.get("mermaid_diagram"),
|
||||
"terraform_code": result_state.get("terraform_code"),
|
||||
"validation_results": result_state.get("validation_results"),
|
||||
"solution_guide": result_state.get("solution_guide"),
|
||||
},
|
||||
"active_skills": result_state.get("active_skills", []),
|
||||
}
|
||||
263
app/adk/runtime.py
Normal file
263
app/adk/runtime.py
Normal file
@@ -0,0 +1,263 @@
|
||||
"""The agent-runtime interface (ADR-0003).
|
||||
|
||||
Everything an Orchestrator or Specialist needs crosses this seam as plain data:
|
||||
a RoleSpec, an AgentTask and ToolSpecs in; an Outcome back. No framework types.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import contextvars
|
||||
from collections.abc import (
|
||||
AsyncIterator,
|
||||
Awaitable,
|
||||
Callable,
|
||||
Mapping,
|
||||
MutableMapping,
|
||||
Sequence,
|
||||
)
|
||||
from contextlib import asynccontextmanager
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Any, Protocol
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class RoleSpec:
|
||||
"""One agent role, parsed from agents/<role>.md."""
|
||||
|
||||
name: str
|
||||
instructions: str
|
||||
budget: int
|
||||
skills: tuple[str, ...] = ()
|
||||
tools: tuple[str, ...] = () # local tool names, e.g. terraform_validate
|
||||
mcp_servers: tuple[str, ...] = ()
|
||||
model: str | None = None
|
||||
# Seconds one model request may take; None takes the runtime's default.
|
||||
model_timeout_seconds: float | None = None
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class AgentTask:
|
||||
"""What one run of an agent is asked to do, with the context it may use."""
|
||||
|
||||
role: str
|
||||
prompt: str
|
||||
context: Mapping[str, Any] = field(default_factory=dict)
|
||||
deliverable: str | None = None
|
||||
|
||||
|
||||
# --- outcomes ----------------------------------------------------------------------
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Submitted:
|
||||
"""A Specialist's contract-complete Deliverable."""
|
||||
|
||||
content: str
|
||||
attachments: Mapping[str, str] = field(default_factory=dict)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class NeedsInput:
|
||||
"""The agent can't continue without the user. `permission` names a tool tier to grant.
|
||||
|
||||
`draft` is work the agent wants back when it is started again with the answers.
|
||||
"""
|
||||
|
||||
questions: tuple[str, ...]
|
||||
permission: str | None = None
|
||||
draft: str | None = None
|
||||
draft_attachments: Mapping[str, str] = field(default_factory=dict)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class BudgetExhausted:
|
||||
summary: str
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Stopped:
|
||||
"""The agent stopped without calling a tool that ends its turn."""
|
||||
|
||||
message: str
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class TurnEnded:
|
||||
"""The Orchestrator ended its turn by calling `tool`; the tool recorded its effect."""
|
||||
|
||||
tool: str
|
||||
|
||||
|
||||
Outcome = Submitted | NeedsInput | BudgetExhausted | Stopped | TurnEnded
|
||||
|
||||
|
||||
# --- tools -------------------------------------------------------------------------
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ToolResult:
|
||||
"""What a tool returns to the agent. A non-None `outcome` ends the agent's run."""
|
||||
|
||||
message: str
|
||||
outcome: Outcome | None = None
|
||||
|
||||
|
||||
# Files cross tool calls as a list of {path, content}, never a map keyed by path:
|
||||
# models rewrite object keys (Gemini turns "main.tf" into "main_tf").
|
||||
FILES_SCHEMA: Mapping[str, Any] = {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"path": {
|
||||
"type": "string",
|
||||
"description": "Relative path, e.g. terraform/main.tf",
|
||||
},
|
||||
"content": {"type": "string"},
|
||||
},
|
||||
"required": ["path", "content"],
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def files_from_argument(value: Any) -> dict[str, str]:
|
||||
"""A FILES_SCHEMA argument as {path: content}. A {path: content} map is accepted too."""
|
||||
if not value:
|
||||
return {}
|
||||
if isinstance(value, Mapping):
|
||||
return {str(path): str(content) for path, content in value.items()}
|
||||
files: dict[str, str] = {}
|
||||
for item in value:
|
||||
if not isinstance(item, Mapping) or "path" not in item:
|
||||
raise TypeError("each file needs a 'path' and 'content'")
|
||||
files[str(item["path"])] = str(item.get("content", ""))
|
||||
return files
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ToolSpec:
|
||||
name: str
|
||||
description: str
|
||||
parameters: Mapping[str, Any] # JSON schema for the keyword arguments
|
||||
handler: Callable[..., Awaitable[ToolResult]]
|
||||
tier: str = "general" # general | cloud_read | execution
|
||||
|
||||
|
||||
# The tools a role gets beyond the Execution tools, given the Deliverable it is producing
|
||||
# and that Deliverable's working memory: JSON-compatible data a tool may read and write,
|
||||
# kept with the Execution across attempts.
|
||||
ToolFactory = Callable[
|
||||
[RoleSpec, str | None, MutableMapping[str, Any]], Sequence[ToolSpec]
|
||||
]
|
||||
|
||||
|
||||
class RunLimiter:
|
||||
"""Caps how many agent runs are in flight at once.
|
||||
|
||||
A run that fans out to further runs lends its slot while it waits, so the cap
|
||||
holds across the whole hierarchy and a cap of 1 cannot deadlock.
|
||||
"""
|
||||
|
||||
def __init__(self, limit: int) -> None:
|
||||
if limit < 1:
|
||||
raise ValueError("limit must be at least 1")
|
||||
self.limit = limit
|
||||
self._semaphore = asyncio.Semaphore(limit)
|
||||
self._holding: contextvars.ContextVar[bool] = contextvars.ContextVar(
|
||||
"run_limiter_holding", default=False
|
||||
)
|
||||
|
||||
@asynccontextmanager
|
||||
async def slot(self) -> AsyncIterator[None]:
|
||||
async with self._semaphore:
|
||||
token = self._holding.set(True)
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
self._holding.reset(token)
|
||||
|
||||
@asynccontextmanager
|
||||
async def lend(self) -> AsyncIterator[None]:
|
||||
"""Give up the caller's slot, if it holds one, while its own fan-out runs."""
|
||||
if not self._holding.get():
|
||||
yield
|
||||
return
|
||||
self._semaphore.release()
|
||||
token = self._holding.set(False)
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
self._holding.reset(token)
|
||||
await self._semaphore.acquire()
|
||||
|
||||
|
||||
# Tool replies that mean the call did nothing. Runtimes log them, and the Execution
|
||||
# keeps them as lesson candidates.
|
||||
REJECTION_PREFIXES = (
|
||||
"Not submitted",
|
||||
"Refused",
|
||||
"Discovery gap",
|
||||
"terraform validate failed",
|
||||
)
|
||||
|
||||
|
||||
# --- decisions -----------------------------------------------------------------------
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Question:
|
||||
"""A closed question about a state. Its answer is typed, never prose.
|
||||
|
||||
choice pick one of `options`
|
||||
score rate against `options`, ordered from lowest to highest
|
||||
noul yes or no; the answer is the probability that it is yes
|
||||
"""
|
||||
|
||||
kind: str # choice | score | noul
|
||||
instructions: str
|
||||
options: tuple[str, ...] = ()
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Answer:
|
||||
"""`value` is the chosen option (choice), the level reached (score, as a number
|
||||
from 0 for the lowest option) or the probability of yes (noul)."""
|
||||
|
||||
value: str | float
|
||||
confidence: float
|
||||
probabilities: Mapping[str, float] = field(default_factory=dict)
|
||||
|
||||
def is_yes(self, threshold: float = 0.5) -> bool:
|
||||
return isinstance(self.value, (int, float)) and self.value >= threshold
|
||||
|
||||
|
||||
class Decider(Protocol):
|
||||
"""Answers closed questions about a state (ADR-0007).
|
||||
|
||||
Returns None when no decision could be made: the service is not configured,
|
||||
unreachable, over its budget, or the request is too large. The caller then takes
|
||||
its fallback; a decider never blocks an Execution. `scope` names what a budget is
|
||||
counted against, usually the Execution.
|
||||
"""
|
||||
|
||||
async def decide(
|
||||
self, state: str, questions: Mapping[str, Question], *, scope: str = ""
|
||||
) -> Mapping[str, Answer] | None: ...
|
||||
|
||||
|
||||
class NoDecider:
|
||||
"""The decider when none is configured: every caller takes its fallback."""
|
||||
|
||||
async def decide(
|
||||
self, state: str, questions: Mapping[str, Question], *, scope: str = ""
|
||||
) -> Mapping[str, Answer] | None:
|
||||
return None
|
||||
|
||||
|
||||
class AgentRuntime(Protocol):
|
||||
async def run(
|
||||
self, role: RoleSpec, task: AgentTask, tools: Sequence[ToolSpec]
|
||||
) -> Outcome:
|
||||
"""Run one ReAct loop until a tool ends the turn, the budget is spent, or it stops."""
|
||||
...
|
||||
@@ -1,56 +0,0 @@
|
||||
"""ADK Postgres Session Service for GCP Solution Architecture Agent.
|
||||
|
||||
Uses google.adk.sessions.SessionService backed by external PostgreSQL database.
|
||||
"""
|
||||
|
||||
import logging
|
||||
import uuid
|
||||
from typing import Any, Dict, Optional
|
||||
|
||||
from app.adk.compat import Session, SessionService
|
||||
from app.database import get_db_manager
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class PostgresSessionService(SessionService):
|
||||
"""ADK Session Service persisting state to PostgreSQL."""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self.db_manager = get_db_manager()
|
||||
|
||||
def create_session(self, agent_name: str, session_id: Optional[str] = None) -> Session:
|
||||
"""Create a new session record in PostgreSQL database."""
|
||||
sid = session_id or str(uuid.uuid4())
|
||||
session = Session(session_id=sid, agent_name=agent_name, state={})
|
||||
self.db_manager.save_session(
|
||||
session_id=sid,
|
||||
agent_name=agent_name,
|
||||
state_data=session.state,
|
||||
metadata={"created_via": "PostgresSessionService"},
|
||||
)
|
||||
logger.info("Created ADK session %s in PostgreSQL database.", sid)
|
||||
return session
|
||||
|
||||
def get_session(self, session_id: str) -> Optional[Session]:
|
||||
"""Fetch session state from PostgreSQL database."""
|
||||
sess_data = self.db_manager.get_session(session_id)
|
||||
if not sess_data:
|
||||
return None
|
||||
|
||||
return Session(
|
||||
session_id=sess_data["session_id"],
|
||||
agent_name=sess_data["agent_name"],
|
||||
state=sess_data.get("state_data", {}),
|
||||
)
|
||||
|
||||
def save_session(self, session: Session) -> bool:
|
||||
"""Update session state in PostgreSQL database."""
|
||||
success = self.db_manager.save_session(
|
||||
session_id=session.session_id,
|
||||
agent_name=session.agent_name,
|
||||
state_data=session.state,
|
||||
)
|
||||
if success:
|
||||
logger.info("Updated ADK session %s in PostgreSQL database.", session.session_id)
|
||||
return success
|
||||
@@ -1,64 +0,0 @@
|
||||
"""ADK FunctionTool Wrappers for GCP Solution Architecture Agent.
|
||||
|
||||
Uses google.adk.tools.FunctionTool primitives.
|
||||
"""
|
||||
|
||||
from typing import Any, Dict
|
||||
from app.adk.compat import FunctionTool
|
||||
from app.tools.mcp_developer_knowledge import (
|
||||
developerknowledge_answer_query as _mcp_answer,
|
||||
developerknowledge_get_documents as _mcp_get,
|
||||
developerknowledge_search_documents as _mcp_search,
|
||||
)
|
||||
from app.tools.validation_tools import (
|
||||
validate_mermaid_diagram as _validate_mermaid,
|
||||
validate_repository_artifacts as _validate_repo,
|
||||
validate_terraform_syntax as _validate_terraform,
|
||||
)
|
||||
|
||||
# Convert validation functions to ADK FunctionTools
|
||||
mermaid_tool = FunctionTool.from_defaults(
|
||||
fn=_validate_mermaid.func if hasattr(_validate_mermaid, "func") else _validate_mermaid,
|
||||
name="validate_mermaid_diagram",
|
||||
description="Validates syntax and graph directives of a Mermaid diagram.",
|
||||
)
|
||||
|
||||
terraform_tool = FunctionTool.from_defaults(
|
||||
fn=_validate_terraform.func if hasattr(_validate_terraform, "func") else _validate_terraform,
|
||||
name="validate_terraform_syntax",
|
||||
description="Validates Terraform HCL basic structure and required Google Cloud resources.",
|
||||
)
|
||||
|
||||
repo_artifacts_tool = FunctionTool.from_defaults(
|
||||
fn=_validate_repo.func if hasattr(_validate_repo, "func") else _validate_repo,
|
||||
name="validate_repository_artifacts",
|
||||
description="Validates offline file existence and required section headings across repository artifacts.",
|
||||
)
|
||||
|
||||
# Convert Developer Knowledge MCP tools to ADK FunctionTools
|
||||
mcp_search_tool = FunctionTool.from_defaults(
|
||||
fn=_mcp_search.func if hasattr(_mcp_search, "func") else _mcp_search,
|
||||
name="developerknowledge_search_documents",
|
||||
description="Searches Google Cloud reference architecture, decision-making, and best-practice documents.",
|
||||
)
|
||||
|
||||
mcp_get_tool = FunctionTool.from_defaults(
|
||||
fn=_mcp_get.func if hasattr(_mcp_get, "func") else _mcp_get,
|
||||
name="developerknowledge_get_documents",
|
||||
description="Retrieves official Google Cloud document content and citations by URI.",
|
||||
)
|
||||
|
||||
mcp_answer_tool = FunctionTool.from_defaults(
|
||||
fn=_mcp_answer.func if hasattr(_mcp_answer, "func") else _mcp_answer,
|
||||
name="developerknowledge_answer_query",
|
||||
description="Answers architectural questions and checks GCP product release statuses and best practices.",
|
||||
)
|
||||
|
||||
ADK_TOOLS = [
|
||||
mermaid_tool,
|
||||
terraform_tool,
|
||||
repo_artifacts_tool,
|
||||
mcp_search_tool,
|
||||
mcp_get_tool,
|
||||
mcp_answer_tool,
|
||||
]
|
||||
@@ -1,20 +0,0 @@
|
||||
"""ADK Workflows module for GCP Solution Architecture Agent.
|
||||
|
||||
Uses google.adk.workflows.Workflow and google.adk.workflows.WorkflowStep primitives.
|
||||
"""
|
||||
|
||||
from typing import Any, Dict, List
|
||||
from app.adk.agents import OrchestratorLoopAgent
|
||||
from app.adk.compat import Workflow, WorkflowStep
|
||||
from app.skills.loader import SkillLoader
|
||||
|
||||
|
||||
def create_gcp_adk_workflow(skill_loader: SkillLoader, max_iterations: int = 5) -> Workflow:
|
||||
"""Compose the multi-agent ADK workflow."""
|
||||
orchestrator = OrchestratorLoopAgent(skill_loader, max_iterations=max_iterations)
|
||||
step = WorkflowStep(step_name="OrchestratorReviewLoopStep", agent=orchestrator)
|
||||
|
||||
return Workflow(
|
||||
name="GCP_Solution_Architecture_Workflow",
|
||||
steps=[step],
|
||||
)
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user