Compare commits
11 Commits
main
...
7ee49ab352
| Author | SHA1 | Date | |
|---|---|---|---|
| 7ee49ab352 | |||
| e94b2493e7 | |||
| ad371b2ec4 | |||
| ed104e5697 | |||
| f040493583 | |||
| d9214c671a | |||
| c8410946b8 | |||
| 2976dfab21 | |||
| 69012b2656 | |||
| 0851171a71 | |||
| 4fefe0ab33 |
54
.agents/plans/README.md
Normal file
54
.agents/plans/README.md
Normal file
@@ -0,0 +1,54 @@
|
||||
# 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 (uncommitted) | 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/` | planned | The enhancement backlog from the 2026-10-06 review: cheap fixes, the learning loop through Skills, overlay Skills, provider neutrality. |
|
||||
| 5 | `iter-05-jev-decisions/` | planned, gated on open questions | Jev (a hosted decision model) for the agent's closed decisions: checks, routing, context selection. |
|
||||
|
||||
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, uncommitted | none |
|
||||
| 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` (all of this iteration is uncommitted as of 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`).
|
||||
123
.agents/plans/iter-04-learning-and-skills/DETAIL.md
Normal file
123
.agents/plans/iter-04-learning-and-skills/DETAIL.md
Normal file
@@ -0,0 +1,123 @@
|
||||
# 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`.
|
||||
48
.agents/plans/iter-04-learning-and-skills/MAP.md
Normal file
48
.agents/plans/iter-04-learning-and-skills/MAP.md
Normal file
@@ -0,0 +1,48 @@
|
||||
# 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:** planned; no step started
|
||||
**This directory covers:** steps 1 to 14
|
||||
|
||||
## 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 | planned |
|
||||
| 2 | Carry the draft through `needs_input` | A | S | planned |
|
||||
| 3 | Reuse pillar advice across Revisions | A | S | planned |
|
||||
| 4 | Single source for Deliverable contracts | A | S | planned |
|
||||
| 5 | Cap parallel Specialists | A | S | planned |
|
||||
| 6 | Orchestrator step order | A | S | planned |
|
||||
| 7 | Capture lesson candidates | B | M | planned |
|
||||
| 8 | Evaluation that can see improvement | B | M | planned |
|
||||
| 9 | ADR: the lessons loop and overlay Skills | B | S | planned, owner's decision |
|
||||
| 10 | Lessons Skill and lesson curator | B | L | planned |
|
||||
| 11 | IaC patterns Skill | B | M | planned |
|
||||
| 12 | Overlay Skills and an organisation standards Skill | C | M | planned |
|
||||
| 13 | Trim Specialist context | C | M | planned |
|
||||
| 14 | Provider-owned contracts | C | M | planned |
|
||||
|
||||
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 8 comes before steps 10, 11 and 13 so each of them can be shown to help: same quality, fewer Revisions, seconds or tokens.
|
||||
151
.agents/plans/iter-05-jev-decisions/DETAIL.md
Normal file
151
.agents/plans/iter-05-jev-decisions/DETAIL.md
Normal file
@@ -0,0 +1,151 @@
|
||||
# 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: Orchestrator routing
|
||||
|
||||
- **Capability:** A recorded decision on whether code and Jev may take Orchestrator steps.
|
||||
- **Rationale:** ADR-0003 rejected running the dependency graph with no Orchestrator model, so the top level stays ReAct. Step 12 moves the mechanical steps to code.
|
||||
- **Evidence to bring:** results from steps 3 and 4, and the Orchestrator's 36 Pro requests and 53 thousand thinking tokens in case 03.
|
||||
- **Acceptance criteria:** An accepted ADR that amends or confirms ADR-0003. If it confirms, step 12 is closed as not doing.
|
||||
|
||||
## Step 12: Orchestrator routing
|
||||
|
||||
- **Report ref:** J1
|
||||
- **Capability:** The Orchestrator model runs only when judgement is needed.
|
||||
- **Design:** Four of the seven steps in `agents/orchestrator.md` are decided by fields already in its context: pending questions, a Phase ready for Approval, ready work, packaging approved. Code takes those. Jev answers two judgements: a Noul for "did the user's latest message ask for changes?" and a Choice over the Deliverables for what to reopen.
|
||||
- **Fallback:** the Orchestrator model, as today.
|
||||
- **Where:** `orchestrator_turn` in `app/nodes/execution_nodes.py`.
|
||||
- **Acceptance criteria:** Every Ledger rule still holds: the engine tests pass unchanged. On the cases, Orchestrator requests and seconds fall with the quality checks unchanged.
|
||||
|
||||
## 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.
|
||||
73
.agents/plans/iter-05-jev-decisions/MAP.md
Normal file
73
.agents/plans/iter-05-jev-decisions/MAP.md
Normal file
@@ -0,0 +1,73 @@
|
||||
# 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:** planned; gated on step 1
|
||||
**This directory covers:** steps 1 to 14
|
||||
|
||||
## 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).
|
||||
- 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.
|
||||
|
||||
## 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 | planned |
|
||||
| 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: Orchestrator routing | none | planned, owner's decision |
|
||||
| 12 | Orchestrator routing | J1 | planned |
|
||||
| 13 | Cloud-read call guard | J7 | planned |
|
||||
| 14 | Input guardrail | J11 | planned |
|
||||
|
||||
## 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: depends on step 4 having evaluation results
|
||||
- Step 12: depends on step 2, step 11
|
||||
- Step 13: depends on step 2
|
||||
- Step 14: depends on step 2
|
||||
|
||||
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.
|
||||
11
.dockerignore
Normal file
11
.dockerignore
Normal file
@@ -0,0 +1,11 @@
|
||||
# Keep the build context to what the image copies.
|
||||
.git
|
||||
.venv
|
||||
.cache
|
||||
.agents
|
||||
.scratch
|
||||
**/__pycache__
|
||||
*.db
|
||||
.env
|
||||
eval/results
|
||||
deliverables/executions
|
||||
57
.env.example
57
.env.example
@@ -1,26 +1,45 @@
|
||||
# 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
|
||||
# TF_PLUGIN_CACHE_DIR=/var/cache/terraform-plugins
|
||||
|
||||
# Hierarchical Execution Engine
|
||||
ORCHESTRATOR_BUDGET=40
|
||||
SPECIALIST_BUDGET=15
|
||||
MAX_REVISIONS=3
|
||||
MAX_ORCHESTRATOR_TURNS=100
|
||||
CHECKPOINTER=sqlite
|
||||
CHECKPOINT_DB_PATH=checkpoints.db
|
||||
|
||||
# PostgreSQL (Execution records, and checkpoints when CHECKPOINTER=postgres)
|
||||
POSTGRES_HOST=localhost
|
||||
POSTGRES_PORT=5432
|
||||
POSTGRES_DB=gcp_agent_db
|
||||
@@ -28,11 +47,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
|
||||
|
||||
9
.gitignore
vendored
9
.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,6 @@ tfplan
|
||||
# Container logs & temp files
|
||||
*.log
|
||||
.DS_Store
|
||||
|
||||
# Evaluation run outputs
|
||||
eval/results/
|
||||
|
||||
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.
|
||||
761
.scratch/solution-architect-agent/spec.md
Normal file
761
.scratch/solution-architect-agent/spec.md
Normal file
@@ -0,0 +1,761 @@
|
||||
# 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.
|
||||
|
||||
| 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`.
|
||||
65
CONTEXT.md
Normal file
65
CONTEXT.md
Normal file
@@ -0,0 +1,65 @@
|
||||
# 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.
|
||||
_Avoid_: run, job, workflow execution
|
||||
|
||||
**Session**:
|
||||
A caller-supplied grouping of Executions. A Session never feeds earlier outputs into a later Execution; each Execution starts clean.
|
||||
_Avoid_: conversation, context
|
||||
|
||||
**Phase**:
|
||||
A named grouping of Deliverables: requirements discovery, solution architecture, 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 diagrammer. 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, architecture diagram, architecture description, design recommendations, 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
|
||||
|
||||
**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"]
|
||||
|
||||
|
||||
141
README.md
141
README.md
@@ -1,55 +1,46 @@
|
||||
# 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:** `product-selector`, `diagrammer`, `describer`, `design-advisor` (which consults one `pillar-advisor` per architecture-framework pillar), `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.
|
||||
### 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.
|
||||
|
||||
### 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)
|
||||
### 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`.
|
||||
|
||||
The `SkillLoader` (`app/skills/loader.py`) dynamically parses frontmatter and injects instructions into phase system prompts.
|
||||
### 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/` and `skills/iac-validation/`: our own Skills for the tooling.
|
||||
|
||||
### 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.
|
||||
`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.
|
||||
|
||||
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 +54,19 @@ 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
|
||||
# Real-model evaluation of the engine (costs model usage; see eval/solution_eval.py)
|
||||
python3 -m eval.solution_eval
|
||||
|
||||
# Run static artifact validation
|
||||
python3 scripts/validate_artifacts.py
|
||||
```
|
||||
|
||||
### 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
|
||||
@@ -94,7 +85,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,10 +109,10 @@ 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"}'
|
||||
@@ -129,31 +123,30 @@ 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
|
||||
│ └── 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/ # Scalable deliverable repository (categorized & versioned)
|
||||
│ ├── as-is/ # Pre-emptive Source Environment Deliverables (Before State)
|
||||
│ │ ├── source-architecture.md
|
||||
|
||||
@@ -9,8 +9,8 @@ python3 scripts/validate_artifacts.py
|
||||
# 2. Pytest unit & integration test suite
|
||||
pytest -v
|
||||
|
||||
# 3. Offline ADK evaluation benchmark suite
|
||||
python3 -m eval.eval_harness
|
||||
# 3. Real-model evaluation of the engine (needs model credentials; costs usage)
|
||||
python3 -m eval.solution_eval
|
||||
|
||||
# 4. Optional Terraform formatting & validation
|
||||
terraform -chdir=terraform fmt -check -recursive
|
||||
|
||||
11
agents/decomposer.md
Normal file
11
agents/decomposer.md
Normal file
@@ -0,0 +1,11 @@
|
||||
---
|
||||
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.
|
||||
- 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.
|
||||
|
||||
- Explain the purpose of each component in the diagram, the relationships between components, and the task flow or data flow end to end.
|
||||
- Use the product names from the product selection and the component names from the diagram exactly.
|
||||
- Ground claims about product behaviour in the Cloud provider's documentation through your documentation tools, with citations.
|
||||
13
agents/design-advisor.md
Normal file
13
agents/design-advisor.md
Normal file
@@ -0,0 +1,13 @@
|
||||
---
|
||||
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.
|
||||
- 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.
|
||||
|
||||
Required headings, one per pillar: `Security, privacy, and compliance`, `Reliability`, `Operational excellence`, `Cost optimization`, `Performance efficiency`, `Sustainability`.
|
||||
11
agents/diagrammer.md
Normal file
11
agents/diagrammer.md
Normal file
@@ -0,0 +1,11 @@
|
||||
---
|
||||
role: diagrammer
|
||||
deliverable: architecture_diagram
|
||||
tools: [mermaid_check]
|
||||
includes: [specialist-protocol]
|
||||
---
|
||||
You produce the **architecture diagram** Deliverable: the Skill's task for generating a Mermaid architecture diagram.
|
||||
|
||||
- Draw every component from the product selection and every relationship the data and control flow need, labelled with the selected products.
|
||||
- Check the diagram with your Mermaid tool when one is available, and fix every error it reports.
|
||||
- Put the diagram source in the `architecture.mmd` attachment, and show the same diagram in a `mermaid` code block in the content with a one-paragraph legend.
|
||||
16
agents/iac-author.md
Normal file
16
agents/iac-author.md
Normal file
@@ -0,0 +1,16 @@
|
||||
---
|
||||
role: iac-author
|
||||
deliverable: deployment_guidance
|
||||
tools: [terraform_fmt, terraform_validate]
|
||||
budget: 30
|
||||
includes: [specialist-protocol]
|
||||
---
|
||||
You produce the **deployment guidance** Deliverable: the Skill's task for generating infrastructure-as-code and deployment instructions.
|
||||
|
||||
- Write Terraform that provisions every selected product with the configuration the design recommendations call for.
|
||||
- Take every environment-specific value (project, region, names, image references) from variables; embed no credentials or secrets.
|
||||
- Format and validate the Terraform with your tools when they are available, and fix everything they report. Pass the files with the same `terraform/` paths you will attach.
|
||||
- Submit as soon as validation passes. If a submission is refused, fix exactly what the refusal lists and submit again; don't rewrite the Terraform.
|
||||
- Put `terraform/main.tf` and `terraform/variables.tf` in the attachments (a list of `{path, content}`), adding `terraform/outputs.tf` when outputs help.
|
||||
|
||||
Required headings: `Deployment prerequisites` (APIs to enable, tools, permissions) and `Step-by-step deployment instructions`, whose commands you give for the user to run, never run yourself.
|
||||
23
agents/orchestrator.md
Normal file
23
agents/orchestrator.md
Normal file
@@ -0,0 +1,23 @@
|
||||
---
|
||||
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`, `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. **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.
|
||||
4. **Work is ready.** When `ready_work` is not empty, call `delegate` once with every ready Deliverable, so independent work runs in parallel.
|
||||
5. **Validation found problems.** When the validation results report failures that trace to an earlier Deliverable, call `reopen` on that Deliverable with the findings, then delegate it.
|
||||
6. **Packaging is approved.** Call `finish`.
|
||||
7. **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`.
|
||||
13
agents/packager.md
Normal file
13
agents/packager.md
Normal file
@@ -0,0 +1,13 @@
|
||||
---
|
||||
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 as a `mermaid` code block and the Terraform as code blocks.
|
||||
|
||||
Required headings: the template's eight top-level sections.
|
||||
20
agents/partials/specialist-protocol.md
Normal file
20
agents/partials/specialist-protocol.md
Normal file
@@ -0,0 +1,20 @@
|
||||
## 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, with its `content` and `attachments`.
|
||||
- `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.
|
||||
- `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. When `pre_approved` is `false`, confirm the draft with the user before submitting: call `needs_input` with a short summary of the draft and ask them to approve it or request changes. Skip this when `answers` already holds their approval of the same 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 required attachment. When it reports missing sections or attachments, add them 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.
|
||||
13
agents/product-selector.md
Normal file
13
agents/product-selector.md
Normal file
@@ -0,0 +1,13 @@
|
||||
---
|
||||
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.
|
||||
|
||||
Required heading: `Products and features mapping`, containing a table with columns for component, recommended product or feature, justification and citations, alternatives, and their pros and cons.
|
||||
15
agents/requirements-analyst.md
Normal file
15
agents/requirements-analyst.md
Normal file
@@ -0,0 +1,15 @@
|
||||
---
|
||||
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.
|
||||
- When non-functional requirements are missing, ask for them and explain what each one decides: availability tiers, scaling, cost budgets, resource types and security posture.
|
||||
- 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.
|
||||
|
||||
Required headings: `Functional requirements`, `Non-functional requirements`, `Current state`, `Dependencies`. Add `Open questions` and `Assumptions` when they apply.
|
||||
14
agents/validator.md
Normal file
14
agents/validator.md
Normal file
@@ -0,0 +1,14 @@
|
||||
---
|
||||
role: validator
|
||||
deliverable: validation_results
|
||||
tools: [terraform_validate, terraform_plan]
|
||||
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: format and validate the Terraform, and preview it with a plan when you have permission to read live cloud resources.
|
||||
- Analyse the architecture and policy statically: network routing and exposure, firewall rules, and IAM least privilege, against the design recommendations.
|
||||
- Report each finding with its evidence and the Deliverable it traces to, so the Orchestrator can send it back for revision.
|
||||
- Give the exact commands for every check you couldn't run, for the user to run themselves.
|
||||
|
||||
Required headings: `Deployment dry-run` and `Architecture and policy analysis`, each ending with a pass or fail verdict.
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
146
app/a2a_server.py
Normal file
146
app/a2a_server.py
Normal file
@@ -0,0 +1,146 @@
|
||||
"""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,
|
||||
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."""
|
||||
|
||||
323
app/adk/adk_runtime.py
Normal file
323
app/adk/adk_runtime.py
Normal file
@@ -0,0 +1,323 @@
|
||||
"""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 (
|
||||
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."
|
||||
)
|
||||
# Tool replies that mean the call did nothing, logged so stuck agents can be diagnosed.
|
||||
REJECTION_PREFIXES = (
|
||||
"Not submitted",
|
||||
"Refused",
|
||||
"Discovery gap",
|
||||
"terraform validate failed",
|
||||
)
|
||||
# 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(),
|
||||
)
|
||||
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) -> types.GenerateContentConfig | None:
|
||||
if self._model_timeout_seconds is None:
|
||||
return None
|
||||
return types.GenerateContentConfig(
|
||||
http_options=types.HttpOptions(
|
||||
timeout=int(self._model_timeout_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
|
||||
89
app/adk/fake_runtime.py
Normal file
89
app/adk/fake_runtime.py
Normal file
@@ -0,0 +1,89 @@
|
||||
"""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
|
||||
|
||||
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,
|
||||
BudgetExhausted,
|
||||
Outcome,
|
||||
RoleSpec,
|
||||
Stopped,
|
||||
ToolSpec,
|
||||
)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Call:
|
||||
tool: str
|
||||
args: Mapping[str, Any] = field(default_factory=dict)
|
||||
|
||||
|
||||
Turn = Sequence[Call] | Callable[[AgentTask], Sequence[Call]]
|
||||
|
||||
|
||||
@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
|
||||
132
app/adk/roles.py
Normal file
132
app/adk/roles.py
Normal file
@@ -0,0 +1,132 @@
|
||||
"""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"
|
||||
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, *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),
|
||||
)
|
||||
@@ -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", []),
|
||||
}
|
||||
139
app/adk/runtime.py
Normal file
139
app/adk/runtime.py
Normal file
@@ -0,0 +1,139 @@
|
||||
"""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
|
||||
|
||||
from collections.abc import Awaitable, Callable, Mapping, Sequence
|
||||
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
|
||||
|
||||
|
||||
@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."""
|
||||
|
||||
questions: tuple[str, ...]
|
||||
permission: str | None = None
|
||||
|
||||
|
||||
@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.
|
||||
ToolFactory = Callable[[RoleSpec, str | None], Sequence[ToolSpec]]
|
||||
|
||||
|
||||
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],
|
||||
)
|
||||
280
app/agent.py
280
app/agent.py
@@ -1,61 +1,243 @@
|
||||
"""gcp_solution_architecture_agent: Starlette application wiring & CLI entrypoint."""
|
||||
"""The agent: the ExecutionEngine that starts and resumes Executions, and its assembly.
|
||||
|
||||
ExecutionEngine is the one interface the A2A server, /generate and the evaluation
|
||||
harness use. Each call runs the Execution until it needs the user or finishes, and
|
||||
returns an Interaction describing which.
|
||||
|
||||
open_assembly is the composition root: the only place concrete runtimes, tools,
|
||||
checkpointers and recorders are chosen, from settings and the provider bundle.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import uuid
|
||||
from collections.abc import AsyncIterator, Mapping, Sequence
|
||||
from contextlib import asynccontextmanager
|
||||
import logging
|
||||
import click
|
||||
import uvicorn
|
||||
from starlette.applications import Starlette
|
||||
from starlette.routing import Route
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from app.config import get_settings
|
||||
from app.database import get_db_manager
|
||||
from app.workflows.routes import (
|
||||
get_card,
|
||||
get_session_route,
|
||||
health_check,
|
||||
run_workflow,
|
||||
validate_artifacts_route,
|
||||
)
|
||||
from langchain_core.runnables import RunnableConfig
|
||||
from langgraph.checkpoint.base import BaseCheckpointSaver
|
||||
from langgraph.types import Command
|
||||
|
||||
settings = get_settings()
|
||||
from app.adk.roles import load_roles
|
||||
from app.adk.runtime import AgentRuntime, RoleSpec, ToolFactory
|
||||
from app.checkpointing import open_checkpointer
|
||||
from app.config import Settings
|
||||
from app.providers import ProviderBundle, load_provider
|
||||
from app.recorder import DatabaseRecorder, ExecutionRecorder
|
||||
from app.states.ledger import Ledger
|
||||
from app.tools.execution import ORCHESTRATOR
|
||||
from app.tools.local import TerraformRunner, local_tools
|
||||
from app.tools.mcp import McpCatalog, auth_from_config
|
||||
from app.tools.toolkit import make_tool_factory
|
||||
from app.workflows.deliverables import DEPENDENCY_GRAPH
|
||||
from app.workflows.execution_graph import build_execution_graph
|
||||
|
||||
logging.basicConfig(
|
||||
level=getattr(logging, settings.LOG_LEVEL.upper(), logging.INFO),
|
||||
format="%(asctime)s %(name)s %(levelname)s %(message)s",
|
||||
)
|
||||
logger = logging.getLogger(__name__)
|
||||
_RECURSION_LIMIT = 10_000 # loops are bounded by max_orchestrator_turns instead
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Interaction:
|
||||
execution_id: str
|
||||
status: str # awaiting_user | completed | completed_with_warnings
|
||||
prompt: Mapping[str, Any] | None # questions | approval | permission
|
||||
state: Mapping[str, Any]
|
||||
|
||||
|
||||
class ExecutionNotAwaitingUser(RuntimeError):
|
||||
pass
|
||||
|
||||
|
||||
class ExecutionEngine:
|
||||
def __init__(
|
||||
self,
|
||||
*,
|
||||
runtime: AgentRuntime,
|
||||
roles: Mapping[str, RoleSpec],
|
||||
recorder: ExecutionRecorder,
|
||||
checkpointer: BaseCheckpointSaver,
|
||||
output_root: Path,
|
||||
max_revisions: int = 3,
|
||||
max_orchestrator_turns: int = 100,
|
||||
tool_factory: ToolFactory | None = None,
|
||||
) -> None:
|
||||
required = {
|
||||
ORCHESTRATOR,
|
||||
*(spec.specialist for spec in DEPENDENCY_GRAPH.values()),
|
||||
}
|
||||
missing = sorted(required - set(roles))
|
||||
if missing:
|
||||
raise ValueError(f"Missing roles: {', '.join(missing)}")
|
||||
self._max_revisions = max_revisions
|
||||
self._graph = build_execution_graph(
|
||||
runtime=runtime,
|
||||
roles=roles,
|
||||
recorder=recorder,
|
||||
output_root=output_root,
|
||||
max_orchestrator_turns=max_orchestrator_turns,
|
||||
tool_factory=tool_factory,
|
||||
).compile(checkpointer=checkpointer)
|
||||
|
||||
async def start(
|
||||
self,
|
||||
workflow_request: str,
|
||||
*,
|
||||
session_id: str | None = None,
|
||||
pre_approved: bool = False,
|
||||
allow_cloud_read: bool | None = None,
|
||||
execution_id: str | None = None,
|
||||
scripted_answers: Sequence[tuple[str, str]] = (),
|
||||
) -> Interaction:
|
||||
"""Start an Execution. `scripted_answers` are (regex, answer) pairs a
|
||||
pre-approved Execution uses to answer questions, for evaluation runs."""
|
||||
execution_id = execution_id or str(uuid.uuid4())
|
||||
if await self._exists(execution_id):
|
||||
raise ValueError(f"Execution {execution_id} already exists")
|
||||
if pre_approved and allow_cloud_read is None:
|
||||
allow_cloud_read = False
|
||||
initial: dict[str, Any] = {
|
||||
"execution_id": execution_id,
|
||||
"session_id": session_id or str(uuid.uuid4()),
|
||||
"workflow_request": workflow_request,
|
||||
"pre_approved": pre_approved,
|
||||
"allow_cloud_read": allow_cloud_read,
|
||||
"ledger": Ledger(
|
||||
pre_approved=pre_approved, max_revisions=self._max_revisions
|
||||
).to_dict(),
|
||||
"deliverables": {},
|
||||
"conversation": [{"from": "user", "text": workflow_request}],
|
||||
"notes": [],
|
||||
"pending_questions": [],
|
||||
"awaiting_questions": [],
|
||||
"answers": {},
|
||||
"pending_permission": None,
|
||||
"prompt": None,
|
||||
"outcomes": [],
|
||||
"outcomes_applied": 0,
|
||||
"events_recorded": 0,
|
||||
"turns": 0,
|
||||
"status": "running",
|
||||
"warnings": [],
|
||||
"scripted_answers": [
|
||||
[pattern, answer] for pattern, answer in scripted_answers
|
||||
],
|
||||
}
|
||||
await self._graph.ainvoke(initial, self._config(execution_id))
|
||||
return await self.interaction(execution_id)
|
||||
|
||||
async def resume(self, execution_id: str, reply: Mapping[str, Any]) -> Interaction:
|
||||
"""Answer the Execution's current prompt: {"reply"} | {"approval"} | {"permission"}."""
|
||||
current = await self.interaction(execution_id)
|
||||
if current.status != "awaiting_user":
|
||||
raise ExecutionNotAwaitingUser(
|
||||
f"Execution {execution_id} is {current.status}, not awaiting the user"
|
||||
)
|
||||
await self._graph.ainvoke(
|
||||
Command(resume=dict(reply)), self._config(execution_id)
|
||||
)
|
||||
return await self.interaction(execution_id)
|
||||
|
||||
async def interaction(self, execution_id: str) -> Interaction:
|
||||
snapshot = await self._graph.aget_state(self._config(execution_id))
|
||||
if not snapshot.values:
|
||||
raise KeyError(f"Unknown Execution {execution_id}")
|
||||
if snapshot.interrupts:
|
||||
return Interaction(
|
||||
execution_id,
|
||||
"awaiting_user",
|
||||
snapshot.interrupts[0].value,
|
||||
snapshot.values,
|
||||
)
|
||||
return Interaction(
|
||||
execution_id,
|
||||
snapshot.values.get("status", "running"),
|
||||
None,
|
||||
snapshot.values,
|
||||
)
|
||||
|
||||
async def _exists(self, execution_id: str) -> bool:
|
||||
snapshot = await self._graph.aget_state(self._config(execution_id))
|
||||
return bool(snapshot.values)
|
||||
|
||||
@staticmethod
|
||||
def _config(execution_id: str) -> RunnableConfig:
|
||||
return {
|
||||
"configurable": {"thread_id": execution_id},
|
||||
"recursion_limit": _RECURSION_LIMIT,
|
||||
}
|
||||
|
||||
|
||||
# --- assembly ----------------------------------------------------------------------
|
||||
|
||||
AGENTS_DIR = Path(__file__).resolve().parent.parent / "agents"
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Assembly:
|
||||
engine: ExecutionEngine
|
||||
bundle: ProviderBundle
|
||||
roles: dict[str, RoleSpec]
|
||||
mcp_gaps: dict[str, str]
|
||||
|
||||
routes = [
|
||||
Route("/health", health_check, methods=["GET"]),
|
||||
Route("/card", get_card, methods=["GET"]),
|
||||
Route("/generate", run_workflow, methods=["POST"]),
|
||||
Route("/validate", validate_artifacts_route, methods=["POST"]),
|
||||
Route("/sessions/{session_id}", get_session_route, methods=["GET"]),
|
||||
]
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(app: Starlette):
|
||||
"""Initialize PostgreSQL database schema on server startup."""
|
||||
logger.info("Initializing PostgreSQL database persistence...")
|
||||
get_db_manager()
|
||||
yield
|
||||
async def open_assembly(
|
||||
settings: Settings,
|
||||
*,
|
||||
runtime: AgentRuntime | None = None,
|
||||
recorder: ExecutionRecorder | None = None,
|
||||
output_root: Path | None = None,
|
||||
) -> AsyncIterator[Assembly]:
|
||||
bundle = load_provider(settings.CLOUD_PROVIDER)
|
||||
roles = load_roles(
|
||||
AGENTS_DIR,
|
||||
bundle,
|
||||
orchestrator_budget=settings.ORCHESTRATOR_BUDGET,
|
||||
specialist_budget=settings.SPECIALIST_BUDGET,
|
||||
include_preview_mcp=settings.MCP_ENABLE_PREVIEW,
|
||||
)
|
||||
if runtime is None:
|
||||
from app.adk.adk_runtime import AdkAgentRuntime
|
||||
|
||||
app = Starlette(
|
||||
debug=True,
|
||||
routes=routes,
|
||||
lifespan=lifespan,
|
||||
)
|
||||
runtime = AdkAgentRuntime(
|
||||
skill_dirs={name: meta.path for name, meta in bundle.skills.items()},
|
||||
model_timeout_seconds=settings.MODEL_TIMEOUT_SECONDS,
|
||||
)
|
||||
|
||||
catalog = McpCatalog()
|
||||
if settings.MCP_ENABLED:
|
||||
used = {server_id for role in roles.values() for server_id in role.mcp_servers}
|
||||
catalog = await McpCatalog.load(
|
||||
[bundle.mcp_servers[server_id] for server_id in sorted(used)],
|
||||
auth_from_config(bundle.mcp_auth, settings.MCP_QUOTA_PROJECT),
|
||||
timeout=settings.MCP_TIMEOUT_SECONDS,
|
||||
)
|
||||
|
||||
@click.command()
|
||||
@click.option("--host", default=settings.HOST, help="Host address to bind")
|
||||
@click.option("--port", default=settings.PORT, type=int, help="Port to listen on")
|
||||
def main(host: str, port: int) -> None:
|
||||
"""Start the GCP Solution Architecture Agent Starlette REST server."""
|
||||
logger.info("Starting GCP Solution Architecture Agent on %s:%d", host, port)
|
||||
uvicorn.run(app, host=host, port=port, log_level=settings.LOG_LEVEL.lower())
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
runner = TerraformRunner(
|
||||
binary=settings.TERRAFORM_BINARY,
|
||||
timeout_seconds=settings.TERRAFORM_TIMEOUT_SECONDS,
|
||||
plugin_cache_dir=settings.TF_PLUGIN_CACHE_DIR,
|
||||
)
|
||||
offered = [name for names in bundle.tools.values() for name in names]
|
||||
tool_factory = make_tool_factory(
|
||||
runtime,
|
||||
roles,
|
||||
bundle.pillar_skills,
|
||||
local_tools=local_tools(offered, runner),
|
||||
catalog=catalog,
|
||||
)
|
||||
|
||||
async with open_checkpointer(settings) as checkpointer:
|
||||
engine = ExecutionEngine(
|
||||
runtime=runtime,
|
||||
roles=roles,
|
||||
recorder=recorder or DatabaseRecorder(),
|
||||
checkpointer=checkpointer,
|
||||
output_root=output_root or settings.BASE_DIR,
|
||||
max_revisions=settings.MAX_REVISIONS,
|
||||
max_orchestrator_turns=settings.MAX_ORCHESTRATOR_TURNS,
|
||||
tool_factory=tool_factory,
|
||||
)
|
||||
yield Assembly(engine, bundle, roles, dict(catalog.gaps))
|
||||
|
||||
98
app/card.py
98
app/card.py
@@ -1,40 +1,66 @@
|
||||
"""AgentCard + skill declarations for GCP Solution Architecture Agent."""
|
||||
"""The A2A agent card, derived from the dependency graph and settings."""
|
||||
|
||||
from typing import Any, Dict
|
||||
from __future__ import annotations
|
||||
|
||||
AGENT_CARD: Dict[str, Any] = {
|
||||
"name": "gcp_solution_architecture_agent",
|
||||
"version": "1.0.0",
|
||||
"description": (
|
||||
"Automated Google Cloud Solution Architecture Agent executing an end-to-end "
|
||||
"migration workflow: Pre-emptive Source Environment Discovery -> Requirements Discovery -> "
|
||||
"Product Selection & Architecture Design -> Pre-deployment Validation -> Guide Packaging."
|
||||
),
|
||||
"capabilities": {
|
||||
"phases": ["source_discover", "discover", "design", "validate", "package"],
|
||||
"streaming": False,
|
||||
"async": True,
|
||||
"local_skills": [
|
||||
"source_discovery",
|
||||
"requirements_discovery",
|
||||
"architecture_design",
|
||||
"validation_rules",
|
||||
"packaging_guide",
|
||||
from a2a.types import (
|
||||
AgentCapabilities,
|
||||
AgentCard,
|
||||
AgentInterface,
|
||||
AgentProvider,
|
||||
AgentSkill,
|
||||
)
|
||||
|
||||
from app.config import Settings
|
||||
from app.workflows.deliverables import PHASE_ORDER, deliverables_in
|
||||
|
||||
A2A_PATH = "/a2a"
|
||||
|
||||
|
||||
def build_agent_card(settings: Settings) -> AgentCard:
|
||||
base_url = (
|
||||
settings.A2A_PUBLIC_URL or f"http://{settings.A2A_HOST}:{settings.A2A_PORT}"
|
||||
).rstrip("/")
|
||||
phases = "; ".join(
|
||||
f"{phase.value}: {', '.join(kind.value for kind in deliverables_in(phase))}"
|
||||
for phase in PHASE_ORDER
|
||||
)
|
||||
return AgentCard(
|
||||
name=settings.AGENT_NAME,
|
||||
description=(
|
||||
"Designs a cloud solution architecture with you: requirements discovery, "
|
||||
"grounded product selection, diagram, design recommendations, "
|
||||
"infrastructure-as-code and dry-run validation, packaged as a solution "
|
||||
f"guide. Cloud provider: {settings.CLOUD_PROVIDER}."
|
||||
),
|
||||
version=settings.AGENT_VERSION,
|
||||
provider=AgentProvider(
|
||||
organization="Kyndryl Agent Builder", url="https://www.kyndryl.com"
|
||||
),
|
||||
supported_interfaces=[
|
||||
AgentInterface(
|
||||
url=f"{base_url}{A2A_PATH}",
|
||||
protocol_binding="JSONRPC",
|
||||
protocol_version="1.0",
|
||||
)
|
||||
],
|
||||
},
|
||||
"metadata": {
|
||||
"cloud_provider": "gcp",
|
||||
"supported_outputs": [
|
||||
"deliverables/as-is/source-architecture.md",
|
||||
"deliverables/as-is/source-architecture.mmd",
|
||||
"deliverables/target/requirements.md",
|
||||
"deliverables/target/architecture.md",
|
||||
"deliverables/target/architecture.mmd",
|
||||
"deliverables/validation/validation-results.md",
|
||||
"deliverables/guides/solution-architecture-guide.md",
|
||||
"deliverables/executions/{execution_id}/*",
|
||||
"terraform/main.tf",
|
||||
capabilities=AgentCapabilities(streaming=True, push_notifications=False),
|
||||
default_input_modes=["text/plain", "application/json"],
|
||||
default_output_modes=["text/plain", "text/markdown", "application/json"],
|
||||
skills=[
|
||||
AgentSkill(
|
||||
id="solution-architecture",
|
||||
name="Cloud solution architecture",
|
||||
description=(
|
||||
"Interactive, multi-turn engagement. Phases and their Deliverables: "
|
||||
f"{phases}. Each Phase needs your approval, sent as data."
|
||||
),
|
||||
tags=["architecture", "cloud", settings.CLOUD_PROVIDER, "terraform"],
|
||||
examples=[
|
||||
"Design a regional event ingestion platform on Google Cloud.",
|
||||
"Migrate our on-premises order service to managed services.",
|
||||
],
|
||||
input_modes=["text/plain", "application/json"],
|
||||
output_modes=["text/plain", "text/markdown", "application/json"],
|
||||
)
|
||||
],
|
||||
},
|
||||
}
|
||||
|
||||
)
|
||||
|
||||
38
app/checkpointing.py
Normal file
38
app/checkpointing.py
Normal file
@@ -0,0 +1,38 @@
|
||||
"""The configured LangGraph checkpointer that makes paused Executions resumable."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import AsyncIterator
|
||||
from contextlib import asynccontextmanager
|
||||
|
||||
from langgraph.checkpoint.base import BaseCheckpointSaver
|
||||
from langgraph.checkpoint.memory import InMemorySaver
|
||||
|
||||
from app.config import Settings
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def open_checkpointer(settings: Settings) -> AsyncIterator[BaseCheckpointSaver]:
|
||||
"""Yield a checkpointer per CHECKPOINTER: memory | sqlite | postgres."""
|
||||
kind = settings.CHECKPOINTER
|
||||
if kind == "memory":
|
||||
yield InMemorySaver()
|
||||
elif kind == "sqlite":
|
||||
from langgraph.checkpoint.sqlite.aio import AsyncSqliteSaver
|
||||
|
||||
async with AsyncSqliteSaver.from_conn_string(
|
||||
settings.CHECKPOINT_DB_PATH
|
||||
) as saver:
|
||||
yield saver
|
||||
elif kind == "postgres":
|
||||
from langgraph.checkpoint.postgres.aio import AsyncPostgresSaver
|
||||
|
||||
async with AsyncPostgresSaver.from_conn_string(
|
||||
settings.get_database_url()
|
||||
) as saver:
|
||||
await saver.setup()
|
||||
yield saver
|
||||
else:
|
||||
raise ValueError(
|
||||
f"CHECKPOINTER must be memory, sqlite or postgres, not {kind!r}"
|
||||
)
|
||||
@@ -1,7 +1,7 @@
|
||||
"""Typed settings for GCP Solution Architecture Agent."""
|
||||
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
from pydantic_settings import BaseSettings, SettingsConfigDict
|
||||
|
||||
|
||||
@@ -19,24 +19,7 @@ class Settings(BaseSettings):
|
||||
AGENT_VERSION: str = "1.0.0"
|
||||
LOG_LEVEL: str = "INFO"
|
||||
|
||||
# Server Configuration
|
||||
HOST: str = "0.0.0.0"
|
||||
PORT: int = 8080
|
||||
|
||||
# LLM Settings
|
||||
OPENAI_API_KEY: str | None = None
|
||||
AZURE_OPENAI_API_KEY: str | None = None
|
||||
AZURE_OPENAI_ENDPOINT: str | None = None
|
||||
AZURE_OPENAI_DEPLOYMENT: str = "gpt-4o"
|
||||
AZURE_OPENAI_API_VERSION: str = "2024-02-15-preview"
|
||||
LLM_TEMPERATURE: float = 0.2
|
||||
|
||||
# Google Cloud Environment & Scanner Credentials
|
||||
GOOGLE_APPLICATION_CREDENTIALS: str | None = None
|
||||
GCP_PROJECT_ID: str | None = None
|
||||
GCP_REGION: str = "us-central1"
|
||||
|
||||
# Database & Storage Settings (External PostgreSQL)
|
||||
# Database & Storage Settings (External PostgreSQL, SQLite fallback)
|
||||
POSTGRES_HOST: str = "localhost"
|
||||
POSTGRES_PORT: int = 5432
|
||||
POSTGRES_DB: str = "gcp_agent_db"
|
||||
@@ -45,18 +28,34 @@ class Settings(BaseSettings):
|
||||
DATABASE_URL: str | None = None
|
||||
SQLITE_FALLBACK_DB: str = "gcp_agent_local.db"
|
||||
|
||||
# ADK Multi-Agent Orchestrator Settings
|
||||
ADK_MAX_LOOP_ITERATIONS: int = 5
|
||||
ADK_ENABLE_ARTIFACT_STORE: bool = True
|
||||
# Cloud Provider Bundle (providers/<name>.yaml) & Remote MCP Servers
|
||||
CLOUD_PROVIDER: str = "gcp"
|
||||
MCP_ENABLED: bool = True
|
||||
MCP_ENABLE_PREVIEW: bool = True
|
||||
MCP_QUOTA_PROJECT: str | None = None # defaults to the ADC project
|
||||
MCP_TIMEOUT_SECONDS: float = 30
|
||||
|
||||
# Google Developer Knowledge MCP Server Settings
|
||||
DEVELOPER_KNOWLEDGE_MCP_URL: str = "https://developerknowledge.googleapis.com/mcp"
|
||||
DEVELOPER_KNOWLEDGE_MCP_ENABLED: bool = True
|
||||
# Local Terraform tools (fmt, validate, plan; never apply)
|
||||
TERRAFORM_BINARY: str = "terraform"
|
||||
TERRAFORM_TIMEOUT_SECONDS: float = 300
|
||||
TF_PLUGIN_CACHE_DIR: str | None = None
|
||||
|
||||
# Models: a request with no response in this time is abandoned and retried
|
||||
MODEL_TIMEOUT_SECONDS: float = 180
|
||||
|
||||
# Hierarchical Execution Engine (LangGraph state, ReAct agents)
|
||||
A2A_HOST: str = "0.0.0.0"
|
||||
A2A_PORT: int = 8000
|
||||
A2A_PUBLIC_URL: str | None = None # advertised in the agent card
|
||||
ORCHESTRATOR_BUDGET: int = 40
|
||||
SPECIALIST_BUDGET: int = 15
|
||||
MAX_REVISIONS: int = 3
|
||||
MAX_ORCHESTRATOR_TURNS: int = 100
|
||||
CHECKPOINTER: str = "sqlite" # memory | sqlite | postgres
|
||||
CHECKPOINT_DB_PATH: str = "checkpoints.db"
|
||||
|
||||
# Paths
|
||||
BASE_DIR: Path = Path(__file__).resolve().parent.parent
|
||||
SKILLS_DIR: Path = Path(__file__).resolve().parent / "skills"
|
||||
EVAL_DATASET_PATH: Path = Path(__file__).resolve().parent.parent / "eval" / "datasets" / "benchmark_cases.json"
|
||||
|
||||
def get_database_url(self) -> str:
|
||||
"""Construct database connection URL (PostgreSQL or SQLite fallback)."""
|
||||
@@ -74,4 +73,3 @@ def get_settings() -> Settings:
|
||||
if _settings is None:
|
||||
_settings = Settings()
|
||||
return _settings
|
||||
|
||||
|
||||
194
app/database.py
194
app/database.py
@@ -9,11 +9,11 @@ import json
|
||||
import logging
|
||||
import sqlite3
|
||||
from datetime import datetime, timezone
|
||||
from typing import Any, Dict, List, Optional
|
||||
from typing import Any
|
||||
|
||||
try:
|
||||
import psycopg2
|
||||
from psycopg2.extras import RealDictCursor
|
||||
|
||||
HAS_PSYCOPG2 = True
|
||||
except ImportError:
|
||||
HAS_PSYCOPG2 = False
|
||||
@@ -26,10 +26,12 @@ logger = logging.getLogger(__name__)
|
||||
class DatabaseManager:
|
||||
"""Handles persistence of sessions, execution runs, artifacts, and review logs."""
|
||||
|
||||
def __init__(self, db_url: Optional[str] = None) -> None:
|
||||
def __init__(self, db_url: str | None = None) -> None:
|
||||
self.settings = get_settings()
|
||||
self.db_url = db_url or self.settings.get_database_url()
|
||||
self.is_postgres = self.db_url.startswith("postgresql://") or self.db_url.startswith("postgres://")
|
||||
self.is_postgres = self.db_url.startswith(
|
||||
"postgresql://"
|
||||
) or self.db_url.startswith("postgres://")
|
||||
self._init_db()
|
||||
|
||||
def _get_connection(self):
|
||||
@@ -38,7 +40,7 @@ class DatabaseManager:
|
||||
try:
|
||||
conn = psycopg2.connect(self.db_url, connect_timeout=3)
|
||||
return conn
|
||||
except Exception as exc:
|
||||
except Exception as exc: # noqa: BLE001 - any connection failure falls back to SQLite
|
||||
logger.warning(
|
||||
"PostgreSQL connection to %s failed (%s); falling back to local SQLite database %s",
|
||||
self.db_url,
|
||||
@@ -56,7 +58,7 @@ class DatabaseManager:
|
||||
conn = self._get_connection()
|
||||
try:
|
||||
cursor = conn.cursor()
|
||||
|
||||
|
||||
# 1. Sessions Table
|
||||
cursor.execute("""
|
||||
CREATE TABLE IF NOT EXISTS adk_sessions (
|
||||
@@ -125,12 +127,18 @@ class DatabaseManager:
|
||||
|
||||
conn.commit()
|
||||
logger.info("Database schema initialized successfully.")
|
||||
except Exception as exc:
|
||||
except Exception as exc: # noqa: BLE001 - persistence is best-effort; the failure is logged
|
||||
logger.error("Failed to initialize database schema: %s", exc)
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
def save_session(self, session_id: str, agent_name: str, state_data: Dict[str, Any], metadata: Optional[Dict[str, Any]] = None) -> bool:
|
||||
def save_session(
|
||||
self,
|
||||
session_id: str,
|
||||
agent_name: str,
|
||||
state_data: dict[str, Any],
|
||||
metadata: dict[str, Any] | None = None,
|
||||
) -> bool:
|
||||
"""Persist or update ADK session state in PostgreSQL."""
|
||||
conn = self._get_connection()
|
||||
now = datetime.now(timezone.utc).isoformat()
|
||||
@@ -140,41 +148,51 @@ class DatabaseManager:
|
||||
meta_json = json.dumps(metadata or {})
|
||||
|
||||
if isinstance(conn, sqlite3.Connection):
|
||||
cursor.execute("""
|
||||
cursor.execute(
|
||||
"""
|
||||
INSERT INTO adk_sessions (session_id, agent_name, created_at, updated_at, state_data, metadata)
|
||||
VALUES (?, ?, ?, ?, ?, ?)
|
||||
ON CONFLICT(session_id) DO UPDATE SET
|
||||
updated_at = excluded.updated_at,
|
||||
state_data = excluded.state_data,
|
||||
metadata = excluded.metadata
|
||||
""", (session_id, agent_name, now, now, state_json, meta_json))
|
||||
""",
|
||||
(session_id, agent_name, now, now, state_json, meta_json),
|
||||
)
|
||||
else:
|
||||
cursor.execute("""
|
||||
cursor.execute(
|
||||
"""
|
||||
INSERT INTO adk_sessions (session_id, agent_name, created_at, updated_at, state_data, metadata)
|
||||
VALUES (%s, %s, %s, %s, %s, %s)
|
||||
ON CONFLICT(session_id) DO UPDATE SET
|
||||
updated_at = EXCLUDED.updated_at,
|
||||
state_data = EXCLUDED.state_data,
|
||||
metadata = EXCLUDED.metadata
|
||||
""", (session_id, agent_name, now, now, state_json, meta_json))
|
||||
""",
|
||||
(session_id, agent_name, now, now, state_json, meta_json),
|
||||
)
|
||||
|
||||
conn.commit()
|
||||
return True
|
||||
except Exception as exc:
|
||||
except Exception as exc: # noqa: BLE001 - persistence is best-effort; the failure is logged
|
||||
logger.error("Error saving session %s: %s", session_id, exc)
|
||||
return False
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
def get_session(self, session_id: str) -> Optional[Dict[str, Any]]:
|
||||
def get_session(self, session_id: str) -> dict[str, Any] | None:
|
||||
"""Retrieve ADK session state by session_id."""
|
||||
conn = self._get_connection()
|
||||
try:
|
||||
cursor = conn.cursor()
|
||||
if isinstance(conn, sqlite3.Connection):
|
||||
cursor.execute("SELECT * FROM adk_sessions WHERE session_id = ?", (session_id,))
|
||||
cursor.execute(
|
||||
"SELECT * FROM adk_sessions WHERE session_id = ?", (session_id,)
|
||||
)
|
||||
else:
|
||||
cursor.execute("SELECT * FROM adk_sessions WHERE session_id = %s", (session_id,))
|
||||
cursor.execute(
|
||||
"SELECT * FROM adk_sessions WHERE session_id = %s", (session_id,)
|
||||
)
|
||||
|
||||
row = cursor.fetchone()
|
||||
if not row:
|
||||
@@ -197,7 +215,7 @@ class DatabaseManager:
|
||||
"state_data": json.loads(row[4]),
|
||||
"metadata": json.loads(row[5] or "{}"),
|
||||
}
|
||||
except Exception as exc:
|
||||
except Exception as exc: # noqa: BLE001 - persistence is best-effort; the failure is logged
|
||||
logger.error("Error reading session %s: %s", session_id, exc)
|
||||
return None
|
||||
finally:
|
||||
@@ -211,7 +229,7 @@ class DatabaseManager:
|
||||
current_phase: str,
|
||||
loop_count: int,
|
||||
request_summary: str,
|
||||
results: Dict[str, Any],
|
||||
results: dict[str, Any],
|
||||
) -> bool:
|
||||
"""Save workflow execution record to database."""
|
||||
conn = self._get_connection()
|
||||
@@ -221,7 +239,8 @@ class DatabaseManager:
|
||||
results_json = json.dumps(results)
|
||||
|
||||
if isinstance(conn, sqlite3.Connection):
|
||||
cursor.execute("""
|
||||
cursor.execute(
|
||||
"""
|
||||
INSERT INTO workflow_executions
|
||||
(execution_id, session_id, status, current_phase, loop_count, started_at, completed_at, request_summary, results_json)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
@@ -231,9 +250,22 @@ class DatabaseManager:
|
||||
loop_count = excluded.loop_count,
|
||||
completed_at = excluded.completed_at,
|
||||
results_json = excluded.results_json
|
||||
""", (execution_id, session_id, status, current_phase, loop_count, now, now, request_summary, results_json))
|
||||
""",
|
||||
(
|
||||
execution_id,
|
||||
session_id,
|
||||
status,
|
||||
current_phase,
|
||||
loop_count,
|
||||
now,
|
||||
now,
|
||||
request_summary,
|
||||
results_json,
|
||||
),
|
||||
)
|
||||
else:
|
||||
cursor.execute("""
|
||||
cursor.execute(
|
||||
"""
|
||||
INSERT INTO workflow_executions
|
||||
(execution_id, session_id, status, current_phase, loop_count, started_at, completed_at, request_summary, results_json)
|
||||
VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s)
|
||||
@@ -243,42 +275,67 @@ class DatabaseManager:
|
||||
loop_count = EXCLUDED.loop_count,
|
||||
completed_at = EXCLUDED.completed_at,
|
||||
results_json = EXCLUDED.results_json
|
||||
""", (execution_id, session_id, status, current_phase, loop_count, now, now, request_summary, results_json))
|
||||
""",
|
||||
(
|
||||
execution_id,
|
||||
session_id,
|
||||
status,
|
||||
current_phase,
|
||||
loop_count,
|
||||
now,
|
||||
now,
|
||||
request_summary,
|
||||
results_json,
|
||||
),
|
||||
)
|
||||
|
||||
conn.commit()
|
||||
return True
|
||||
except Exception as exc:
|
||||
except Exception as exc: # noqa: BLE001 - persistence is best-effort; the failure is logged
|
||||
logger.error("Error saving workflow execution %s: %s", execution_id, exc)
|
||||
return False
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
def save_artifact(self, artifact_id: str, execution_id: str, artifact_type: str, file_path: str, content: str) -> bool:
|
||||
def save_artifact(
|
||||
self,
|
||||
artifact_id: str,
|
||||
execution_id: str,
|
||||
artifact_type: str,
|
||||
file_path: str,
|
||||
content: str,
|
||||
) -> bool:
|
||||
"""Write ADK artifact metadata & content to database."""
|
||||
conn = self._get_connection()
|
||||
now = datetime.now(timezone.utc).isoformat()
|
||||
try:
|
||||
cursor = conn.cursor()
|
||||
if isinstance(conn, sqlite3.Connection):
|
||||
cursor.execute("""
|
||||
cursor.execute(
|
||||
"""
|
||||
INSERT INTO adk_artifacts (artifact_id, execution_id, artifact_type, file_path, content, created_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?)
|
||||
ON CONFLICT(artifact_id) DO UPDATE SET
|
||||
content = excluded.content,
|
||||
file_path = excluded.file_path
|
||||
""", (artifact_id, execution_id, artifact_type, file_path, content, now))
|
||||
""",
|
||||
(artifact_id, execution_id, artifact_type, file_path, content, now),
|
||||
)
|
||||
else:
|
||||
cursor.execute("""
|
||||
cursor.execute(
|
||||
"""
|
||||
INSERT INTO adk_artifacts (artifact_id, execution_id, artifact_type, file_path, content, created_at)
|
||||
VALUES (%s, %s, %s, %s, %s, %s)
|
||||
ON CONFLICT(artifact_id) DO UPDATE SET
|
||||
content = EXCLUDED.content,
|
||||
file_path = EXCLUDED.file_path
|
||||
""", (artifact_id, execution_id, artifact_type, file_path, content, now))
|
||||
""",
|
||||
(artifact_id, execution_id, artifact_type, file_path, content, now),
|
||||
)
|
||||
|
||||
conn.commit()
|
||||
return True
|
||||
except Exception as exc:
|
||||
except Exception as exc: # noqa: BLE001 - persistence is best-effort; the failure is logged
|
||||
logger.error("Error saving artifact %s: %s", artifact_id, exc)
|
||||
return False
|
||||
finally:
|
||||
@@ -299,25 +356,56 @@ class DatabaseManager:
|
||||
try:
|
||||
cursor = conn.cursor()
|
||||
if isinstance(conn, sqlite3.Connection):
|
||||
cursor.execute("""
|
||||
cursor.execute(
|
||||
"""
|
||||
INSERT INTO orchestrator_review_logs (log_id, execution_id, iteration, review_status, reviewer_agent, feedback, created_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?)
|
||||
""", (log_id, execution_id, iteration, review_status, reviewer_agent, feedback, now))
|
||||
""",
|
||||
(
|
||||
log_id,
|
||||
execution_id,
|
||||
iteration,
|
||||
review_status,
|
||||
reviewer_agent,
|
||||
feedback,
|
||||
now,
|
||||
),
|
||||
)
|
||||
else:
|
||||
cursor.execute("""
|
||||
cursor.execute(
|
||||
"""
|
||||
INSERT INTO orchestrator_review_logs (log_id, execution_id, iteration, review_status, reviewer_agent, feedback, created_at)
|
||||
VALUES (%s, %s, %s, %s, %s, %s, %s)
|
||||
""", (log_id, execution_id, iteration, review_status, reviewer_agent, feedback, now))
|
||||
""",
|
||||
(
|
||||
log_id,
|
||||
execution_id,
|
||||
iteration,
|
||||
review_status,
|
||||
reviewer_agent,
|
||||
feedback,
|
||||
now,
|
||||
),
|
||||
)
|
||||
|
||||
conn.commit()
|
||||
return True
|
||||
except Exception as exc:
|
||||
except Exception as exc: # noqa: BLE001 - persistence is best-effort; the failure is logged
|
||||
logger.error("Error recording orchestrator review log %s: %s", log_id, exc)
|
||||
return False
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
def save_evaluation(self, eval_id: str, case_id: str, total_score: float, max_score: float, pass_rate: float, passed: bool, details: Dict[str, Any]) -> bool:
|
||||
def save_evaluation(
|
||||
self,
|
||||
eval_id: str,
|
||||
case_id: str,
|
||||
total_score: float,
|
||||
max_score: float,
|
||||
pass_rate: float,
|
||||
passed: bool,
|
||||
details: dict[str, Any],
|
||||
) -> bool:
|
||||
"""Save ADK evaluation benchmark result to database."""
|
||||
conn = self._get_connection()
|
||||
now = datetime.now(timezone.utc).isoformat()
|
||||
@@ -325,26 +413,50 @@ class DatabaseManager:
|
||||
cursor = conn.cursor()
|
||||
details_json = json.dumps(details)
|
||||
if isinstance(conn, sqlite3.Connection):
|
||||
cursor.execute("""
|
||||
cursor.execute(
|
||||
"""
|
||||
INSERT INTO adk_evaluations (eval_id, case_id, total_score, max_score, pass_rate, passed, details_json, evaluated_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
|
||||
""", (eval_id, case_id, total_score, max_score, pass_rate, passed, details_json, now))
|
||||
""",
|
||||
(
|
||||
eval_id,
|
||||
case_id,
|
||||
total_score,
|
||||
max_score,
|
||||
pass_rate,
|
||||
passed,
|
||||
details_json,
|
||||
now,
|
||||
),
|
||||
)
|
||||
else:
|
||||
cursor.execute("""
|
||||
cursor.execute(
|
||||
"""
|
||||
INSERT INTO adk_evaluations (eval_id, case_id, total_score, max_score, pass_rate, passed, details_json, evaluated_at)
|
||||
VALUES (%s, %s, %s, %s, %s, %s, %s, %s)
|
||||
""", (eval_id, case_id, total_score, max_score, pass_rate, passed, details_json, now))
|
||||
""",
|
||||
(
|
||||
eval_id,
|
||||
case_id,
|
||||
total_score,
|
||||
max_score,
|
||||
pass_rate,
|
||||
passed,
|
||||
details_json,
|
||||
now,
|
||||
),
|
||||
)
|
||||
|
||||
conn.commit()
|
||||
return True
|
||||
except Exception as exc:
|
||||
except Exception as exc: # noqa: BLE001 - persistence is best-effort; the failure is logged
|
||||
logger.error("Error saving evaluation %s: %s", eval_id, exc)
|
||||
return False
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
_db_manager: Optional[DatabaseManager] = None
|
||||
_db_manager: DatabaseManager | None = None
|
||||
|
||||
|
||||
def get_db_manager() -> DatabaseManager:
|
||||
|
||||
125
app/main.py
Normal file
125
app/main.py
Normal file
@@ -0,0 +1,125 @@
|
||||
"""The A2A server: JSON-RPC at /a2a, the agent card, health, and pre-approved /generate.
|
||||
|
||||
Run with: python -m app.main
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from collections.abc import AsyncIterator, Callable
|
||||
from contextlib import AbstractAsyncContextManager, asynccontextmanager
|
||||
|
||||
import click
|
||||
import uvicorn
|
||||
from a2a.server.request_handlers.default_request_handler_v2 import (
|
||||
DefaultRequestHandlerV2,
|
||||
)
|
||||
from a2a.server.routes.agent_card_routes import create_agent_card_routes
|
||||
from a2a.server.routes.jsonrpc_routes import create_jsonrpc_routes
|
||||
from a2a.server.tasks import InMemoryTaskStore
|
||||
from a2a.utils.constants import AGENT_CARD_WELL_KNOWN_PATH
|
||||
from starlette.applications import Starlette
|
||||
from starlette.requests import Request
|
||||
from starlette.responses import JSONResponse
|
||||
from starlette.routing import Route
|
||||
|
||||
from app.a2a_server import SolutionArchitectExecutor
|
||||
from app.agent import Assembly, open_assembly
|
||||
from app.card import A2A_PATH, build_agent_card
|
||||
from app.config import Settings, get_settings
|
||||
from app.presentation import to_generate_response
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
AssemblyFactory = Callable[[Settings], AbstractAsyncContextManager[Assembly]]
|
||||
LEGACY_CARD_PATH = "/.well-known/agent.json"
|
||||
|
||||
|
||||
def create_app(
|
||||
settings: Settings | None = None,
|
||||
assembly_factory: AssemblyFactory = open_assembly,
|
||||
) -> Starlette:
|
||||
settings = settings or get_settings()
|
||||
card = build_agent_card(settings)
|
||||
|
||||
async def health(request: Request) -> JSONResponse:
|
||||
assembly: Assembly = request.app.state.assembly
|
||||
return JSONResponse(
|
||||
{
|
||||
"status": "healthy",
|
||||
"agent": settings.AGENT_NAME,
|
||||
"version": settings.AGENT_VERSION,
|
||||
"cloud_provider": assembly.bundle.name,
|
||||
"mcp_discovery_gaps": assembly.mcp_gaps,
|
||||
}
|
||||
)
|
||||
|
||||
async def generate(request: Request) -> JSONResponse:
|
||||
"""Pre-approved, one-shot Execution for batch and evaluation callers."""
|
||||
assembly: Assembly = request.app.state.assembly
|
||||
try:
|
||||
body = await request.json()
|
||||
except ValueError:
|
||||
body = {}
|
||||
workflow_request = str(body.get("request") or "").strip()
|
||||
if not workflow_request:
|
||||
return JSONResponse({"error": "'request' is required"}, status_code=400)
|
||||
try:
|
||||
interaction = await assembly.engine.start(
|
||||
workflow_request,
|
||||
session_id=body.get("session_id"),
|
||||
pre_approved=True,
|
||||
allow_cloud_read=bool(body.get("allow_cloud_read", False)),
|
||||
)
|
||||
except Exception as exc:
|
||||
logger.exception("/generate failed")
|
||||
return JSONResponse(
|
||||
{"error": f"{type(exc).__name__}: {exc}"}, status_code=500
|
||||
)
|
||||
return JSONResponse(to_generate_response(interaction, assembly.roles))
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(app: Starlette) -> AsyncIterator[None]:
|
||||
async with assembly_factory(settings) as assembly:
|
||||
handler = DefaultRequestHandlerV2(
|
||||
agent_executor=SolutionArchitectExecutor(assembly.engine),
|
||||
task_store=InMemoryTaskStore(),
|
||||
agent_card=card,
|
||||
)
|
||||
app.state.assembly = assembly
|
||||
app.state.request_handler = handler
|
||||
app.router.routes.extend(
|
||||
create_jsonrpc_routes(handler, A2A_PATH, enable_v0_3_compat=True)
|
||||
)
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
await handler.aclose()
|
||||
|
||||
return Starlette(
|
||||
routes=[
|
||||
Route("/health", health, methods=["GET"]),
|
||||
Route("/generate", generate, methods=["POST"]),
|
||||
*create_agent_card_routes(card, card_url=AGENT_CARD_WELL_KNOWN_PATH),
|
||||
*create_agent_card_routes(card, card_url=LEGACY_CARD_PATH),
|
||||
],
|
||||
lifespan=lifespan,
|
||||
)
|
||||
|
||||
|
||||
@click.command()
|
||||
@click.option("--host", default=None, help="Host to bind (default A2A_HOST)")
|
||||
@click.option("--port", default=None, type=int, help="Port (default A2A_PORT)")
|
||||
def main(host: str | None, port: int | None) -> None:
|
||||
"""Serve the solution architect agent over A2A."""
|
||||
settings = get_settings()
|
||||
logging.basicConfig(level=settings.LOG_LEVEL.upper())
|
||||
uvicorn.run(
|
||||
create_app(settings),
|
||||
host=host or settings.A2A_HOST,
|
||||
port=port or settings.A2A_PORT,
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -1,9 +1 @@
|
||||
"""Nodes package."""
|
||||
|
||||
from .design_node import design_node
|
||||
from .discover_node import discover_node
|
||||
from .package_node import package_node
|
||||
from .source_discover_node import source_discover_node
|
||||
from .validate_node import validate_node
|
||||
|
||||
__all__ = ["source_discover_node", "discover_node", "design_node", "validate_node", "package_node"]
|
||||
"""The nodes of the Execution graph."""
|
||||
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -1,139 +0,0 @@
|
||||
"""Phase 1: Architecture Design Node."""
|
||||
|
||||
import logging
|
||||
from typing import Any, Dict
|
||||
from app.states.state import GCPArchitectureState
|
||||
from app.skills.loader import SkillLoader
|
||||
from app.tools.mcp_developer_knowledge import get_mcp_client
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def design_node(state: GCPArchitectureState, skill_loader: SkillLoader) -> Dict[str, Any]:
|
||||
"""Processes Phase 1 Design: select GCP managed products, generate Mermaid graph, and Terraform IaC."""
|
||||
logger.info("Executing design_node")
|
||||
skill_prompt = skill_loader.format_skills_for_prompt("design")
|
||||
|
||||
# Developer Knowledge MCP Grounding Search
|
||||
mcp_client = get_mcp_client()
|
||||
mcp_knowledge = mcp_client.search_documents(query="Cloud Run PubSub event-driven architecture", category="compute")
|
||||
docs = mcp_knowledge.get("documents", [])
|
||||
citations_str = "\n".join([f"- [{doc['title']}]({doc['uri']})" for doc in docs[:3]]) if docs else "- [Google Cloud Architecture Framework](https://cloud.google.com/architecture/framework)"
|
||||
|
||||
architecture_doc = f"""# Phase 1 — Architecture & Product Selection
|
||||
|
||||
## Selected Products
|
||||
- **Compute / Serving**: Google Cloud Run (Fully Managed Container Ingress & Stateless Execution)
|
||||
- **Messaging & Eventing**: Google Cloud Pub/Sub (Regional Event Bus for Asynchronous Decoupling)
|
||||
- **State & Storage**: Google Cloud Storage & Firestore (Database & Bucket Storage for Durable Audit Event Replay)
|
||||
- **Security & Identity**: Cloud IAM (Least Privilege Service Accounts) & KMS (Customer-Managed Encryption Keys)
|
||||
- **Artifact Registry**: Google Artifact Registry (OCI Container Image Hosting)
|
||||
|
||||
## Component Responsibilities
|
||||
1. **Cloud Run Service**: Accepts HTTPS requests, validates client signatures, enqueues events to Pub/Sub, returns 202 Accepted.
|
||||
2. **Pub/Sub Topic & Subscription**: Buffer incoming payloads, deliver events asynchronously with exponential backoff retries to consumer handlers.
|
||||
3. **Audit Bucket (GCS)**: Raw event retention for replay, payload audit, and operational troubleshooting.
|
||||
|
||||
## Security & Compliance
|
||||
- HTTPS ingress with TLS 1.3 encryption in transit.
|
||||
- Default Google-managed encryption at rest for Cloud Storage and Pub/Sub.
|
||||
- Cloud Run service account bound strictly to `roles/pubsub.publisher` and `roles/storage.objectCreator`.
|
||||
|
||||
## Grounded Documentation Citations (Google Developer Knowledge MCP)
|
||||
{citations_str}
|
||||
"""
|
||||
|
||||
mermaid_diagram = """flowchart TD
|
||||
Client[External HTTPS Client] -->|HTTPS POST /events| CloudRun[Google Cloud Run Service]
|
||||
CloudRun -->|Publish Event| PubSubTopic[Cloud Pub/Sub Topic]
|
||||
CloudRun -->|Write Raw Payload| GCSAudit[Cloud Storage Audit Bucket]
|
||||
PubSubTopic -->|Push Delivery| EventConsumer[Cloud Run Consumer Service]
|
||||
EventConsumer -->|Acknowledge| PubSubTopic
|
||||
"""
|
||||
|
||||
terraform_code = """# Google Cloud Solution Architecture Baseline
|
||||
terraform {
|
||||
required_version = ">= 1.5.0"
|
||||
required_providers {
|
||||
google = {
|
||||
source = "hashicorp/google"
|
||||
version = "~> 5.0"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
provider "google" {
|
||||
project = var.project_id
|
||||
region = var.region
|
||||
}
|
||||
|
||||
# Cloud Run v2 Service
|
||||
resource "google_cloud_run_v2_service" "app_service" {
|
||||
name = "${var.environment}-app-service"
|
||||
location = var.region
|
||||
|
||||
template {
|
||||
containers {
|
||||
image = var.container_image
|
||||
ports {
|
||||
container_port = 8080
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
# Pub/Sub Topic for Event Ingestion
|
||||
resource "google_pubsub_topic" "event_ingestion" {
|
||||
name = "${var.environment}-event-ingestion-topic"
|
||||
labels = {
|
||||
environment = var.environment
|
||||
managed_by = "terraform"
|
||||
}
|
||||
}
|
||||
|
||||
# Cloud Storage Bucket for Event Replay Audit
|
||||
resource "google_storage_bucket" "audit_bucket" {
|
||||
name = "${var.project_id}-${var.environment}-audit-bucket"
|
||||
location = var.region
|
||||
force_destroy = false
|
||||
uniform_bucket_level_access = true
|
||||
|
||||
versioning {
|
||||
enabled = true
|
||||
}
|
||||
|
||||
lifecycle_rule {
|
||||
condition {
|
||||
age = 30
|
||||
}
|
||||
action {
|
||||
type = "Delete"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
# Least-Privilege IAM Service Account
|
||||
resource "google_service_account" "ingress_sa" {
|
||||
account_id = "${var.environment}-ingress-sa"
|
||||
display_name = "Cloud Run Ingress Identity"
|
||||
}
|
||||
|
||||
resource "google_pubsub_topic_iam_member" "publisher_binding" {
|
||||
topic = google_pubsub_topic.event_ingestion.name
|
||||
role = "roles/pubsub.publisher"
|
||||
member = "serviceAccount:${google_service_account.ingress_sa.email}"
|
||||
}
|
||||
"""
|
||||
|
||||
active_skills = state.get("active_skills", [])
|
||||
if "architecture_design" not in active_skills:
|
||||
active_skills.append("architecture_design")
|
||||
|
||||
return {
|
||||
"architecture_doc": architecture_doc,
|
||||
"mermaid_diagram": mermaid_diagram,
|
||||
"terraform_code": terraform_code,
|
||||
"product_selection_deferred": False,
|
||||
"current_phase": "design",
|
||||
"active_skills": active_skills,
|
||||
}
|
||||
560
app/nodes/execution_nodes.py
Normal file
560
app/nodes/execution_nodes.py
Normal file
@@ -0,0 +1,560 @@
|
||||
"""The nodes of the Execution graph (ADR-0003); app/workflows/execution_graph.py wires them.
|
||||
|
||||
Only orchestrator_turn and await_user change the Ledger; parallel Specialist tasks
|
||||
append outcomes that the next Orchestrator turn applies in order.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import re
|
||||
import time
|
||||
from collections.abc import Awaitable, Callable, Mapping, Sequence
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from langgraph.types import Command, Send, interrupt
|
||||
|
||||
from app.adk.runtime import (
|
||||
AgentRuntime,
|
||||
AgentTask,
|
||||
BudgetExhausted,
|
||||
NeedsInput,
|
||||
Outcome,
|
||||
RoleSpec,
|
||||
Stopped,
|
||||
Submitted,
|
||||
ToolFactory,
|
||||
ToolSpec,
|
||||
TurnEnded,
|
||||
)
|
||||
from app.recorder import ExecutionRecorder
|
||||
from app.states.execution_state import ExecutionState
|
||||
from app.states.ledger import Ledger, LedgerRefusal
|
||||
from app.tools.execution import ORCHESTRATOR, OrchestratorToolbox, specialist_tools
|
||||
from app.workflows.deliverables import (
|
||||
DEPENDENCY_GRAPH,
|
||||
PHASE_ORDER,
|
||||
DeliverableKind,
|
||||
inputs_of,
|
||||
)
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
NO_USER_REPLY = (
|
||||
"No user is available. State your assumption, record it in the Deliverable under "
|
||||
"'Assumptions', and proceed."
|
||||
)
|
||||
GUIDE_FILENAME = "solution-architecture-guide.md"
|
||||
|
||||
|
||||
def _no_tools(role: RoleSpec, deliverable: str | None) -> Sequence[ToolSpec]:
|
||||
return ()
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ExecutionNodes:
|
||||
"""The node functions of one Execution graph, bound to its runtime and recorder."""
|
||||
|
||||
orchestrator_turn: Callable[[ExecutionState], Awaitable[Command]]
|
||||
# Receives its Send payload, not the Execution state.
|
||||
specialist_task: Callable[[dict[str, Any]], Awaitable[dict[str, Any]]]
|
||||
await_user: Callable[[ExecutionState], Awaitable[Command]]
|
||||
finalize: Callable[[ExecutionState], Awaitable[dict[str, Any]]]
|
||||
end_with_warnings: Callable[[ExecutionState], Awaitable[dict[str, Any]]]
|
||||
|
||||
|
||||
def make_execution_nodes(
|
||||
*,
|
||||
runtime: AgentRuntime,
|
||||
roles: Mapping[str, RoleSpec],
|
||||
recorder: ExecutionRecorder,
|
||||
output_root: Path,
|
||||
max_orchestrator_turns: int = 100,
|
||||
tool_factory: ToolFactory | None = None,
|
||||
) -> ExecutionNodes:
|
||||
tool_factory = tool_factory or _no_tools
|
||||
|
||||
async def record_progress(
|
||||
state: ExecutionState, ledger: Ledger, status: str | None = None
|
||||
) -> int:
|
||||
recorded = state.get("events_recorded", 0)
|
||||
for event in ledger.events[recorded:]:
|
||||
logger.info(
|
||||
"[%s] ledger %s %s by %s%s",
|
||||
state["execution_id"],
|
||||
event.type,
|
||||
event.subject,
|
||||
event.actor,
|
||||
f" ({event.detail})" if event.detail else "",
|
||||
)
|
||||
await recorder.record_events(state["execution_id"], ledger.events[recorded:])
|
||||
if status:
|
||||
await recorder.record_status(
|
||||
state["execution_id"],
|
||||
session_id=state["session_id"],
|
||||
workflow_request=state["workflow_request"],
|
||||
status=status,
|
||||
current_phase=_current_phase(ledger),
|
||||
details={
|
||||
"revisions": sum(
|
||||
ledger.revisions(kind) for kind in DEPENDENCY_GRAPH
|
||||
),
|
||||
"warnings": state.get("warnings", []),
|
||||
},
|
||||
)
|
||||
return len(ledger.events)
|
||||
|
||||
async def orchestrator_turn(state: ExecutionState) -> Command:
|
||||
ledger = Ledger.from_dict(state["ledger"])
|
||||
deliverables = dict(state.get("deliverables", {}))
|
||||
pending_questions = list(state.get("pending_questions", []))
|
||||
notes = list(state.get("notes", []))
|
||||
pending_permission = state.get("pending_permission")
|
||||
warnings = list(state.get("warnings", []))
|
||||
|
||||
outcomes = state.get("outcomes", [])
|
||||
for record in outcomes[state.get("outcomes_applied", 0) :]:
|
||||
kind = DeliverableKind(record["kind"])
|
||||
try:
|
||||
if record["type"] == "submitted":
|
||||
ledger.submit(kind, record["attempt"], actor=record["role"])
|
||||
deliverables[kind.value] = {
|
||||
"content": record["content"],
|
||||
"attachments": record["attachments"],
|
||||
}
|
||||
await recorder.record_submission(
|
||||
state["execution_id"],
|
||||
kind.value,
|
||||
record["content"],
|
||||
record["attachments"],
|
||||
)
|
||||
continue
|
||||
ledger.release(kind, record["attempt"], reason=record["type"])
|
||||
except LedgerRefusal as exc:
|
||||
notes.append(f"Discarded a superseded result for {kind}: {exc}")
|
||||
continue
|
||||
if record["type"] == "needs_input" and record.get("permission"):
|
||||
if state.get("allow_cloud_read") is None:
|
||||
requested = (pending_permission or {}).get("requested_by", [])
|
||||
pending_permission = {
|
||||
"tier": record["permission"],
|
||||
"requested_by": [*requested, kind.value],
|
||||
}
|
||||
continue
|
||||
questions = record.get("questions") or [
|
||||
(
|
||||
f"The {record['role']} stopped: {record['summary']} "
|
||||
"How should it proceed?"
|
||||
)
|
||||
]
|
||||
pending_questions.append({"kind": kind.value, "questions": questions})
|
||||
|
||||
turns = state.get("turns", 0) + 1
|
||||
update: dict[str, Any] = {
|
||||
"deliverables": deliverables,
|
||||
"pending_questions": pending_questions,
|
||||
"pending_permission": pending_permission,
|
||||
"outcomes_applied": len(outcomes),
|
||||
"turns": turns,
|
||||
}
|
||||
|
||||
def finish_with(goto: str, **extra: Any) -> Command:
|
||||
return Command(
|
||||
update={**update, "ledger": ledger.to_dict(), "notes": notes, **extra},
|
||||
goto=goto,
|
||||
)
|
||||
|
||||
if pending_permission and not state.get("pre_approved"):
|
||||
update["events_recorded"] = await record_progress(
|
||||
state, ledger, "awaiting_user"
|
||||
)
|
||||
return finish_with("await_user", prompt={"permission": pending_permission})
|
||||
|
||||
if turns > max_orchestrator_turns:
|
||||
warnings.append(
|
||||
f"Stopped after {max_orchestrator_turns} Orchestrator turns without "
|
||||
"finishing."
|
||||
)
|
||||
return finish_with("end_with_warnings", warnings=warnings)
|
||||
|
||||
toolbox = OrchestratorToolbox(ledger, deliverables, pending_questions)
|
||||
task = AgentTask(
|
||||
role=ORCHESTRATOR,
|
||||
prompt="Decide the next step for this Execution using your tools.",
|
||||
context=_orchestrator_context(state, ledger, pending_questions, notes),
|
||||
)
|
||||
started = time.monotonic()
|
||||
outcome = await runtime.run(roles[ORCHESTRATOR], task, toolbox.tools())
|
||||
logger.info(
|
||||
"[%s] orchestrator turn %d (%s phase) ended in %.0fs: %s",
|
||||
state["execution_id"],
|
||||
turns,
|
||||
_current_phase(ledger),
|
||||
time.monotonic() - started,
|
||||
_summarise_outcome(outcome),
|
||||
)
|
||||
notes = []
|
||||
pre_approved = bool(state.get("pre_approved"))
|
||||
conversation = list(state.get("conversation", []))
|
||||
|
||||
def ask(prompt: dict[str, Any], **extra: Any) -> Command:
|
||||
conversation.append({"from": ORCHESTRATOR, "text": _render_prompt(prompt)})
|
||||
return finish_with(
|
||||
"await_user", prompt=prompt, conversation=conversation, **extra
|
||||
)
|
||||
|
||||
if isinstance(outcome, TurnEnded) and outcome.tool == "delegate":
|
||||
sends = [
|
||||
Send(
|
||||
"specialist_task",
|
||||
_specialist_input(state, ledger, deliverables, kind, attempt),
|
||||
)
|
||||
for kind, attempt in toolbox.started.items()
|
||||
]
|
||||
update["events_recorded"] = await record_progress(state, ledger)
|
||||
return Command(
|
||||
update={**update, "ledger": ledger.to_dict(), "notes": notes},
|
||||
goto=sends,
|
||||
)
|
||||
|
||||
if isinstance(outcome, TurnEnded) and outcome.tool == "finish":
|
||||
update["events_recorded"] = await record_progress(state, ledger)
|
||||
return finish_with("finalize")
|
||||
|
||||
if isinstance(outcome, TurnEnded) and outcome.tool == "escalate":
|
||||
warnings.append(toolbox.escalation or "Escalated without detail.")
|
||||
update["events_recorded"] = await record_progress(state, ledger)
|
||||
return finish_with("end_with_warnings", warnings=warnings)
|
||||
|
||||
if isinstance(outcome, TurnEnded) and outcome.tool == "request_approval":
|
||||
update["events_recorded"] = await record_progress(
|
||||
state, ledger, None if pre_approved else "awaiting_user"
|
||||
)
|
||||
return ask({"approval": toolbox.approval})
|
||||
|
||||
if isinstance(outcome, TurnEnded) and outcome.tool == "ask_user":
|
||||
update["events_recorded"] = await record_progress(
|
||||
state, ledger, None if pre_approved else "awaiting_user"
|
||||
)
|
||||
return ask(
|
||||
{"questions": toolbox.questions},
|
||||
pending_questions=[],
|
||||
awaiting_questions=pending_questions,
|
||||
)
|
||||
|
||||
message = _describe_unfinished(outcome)
|
||||
if pre_approved:
|
||||
warnings.append(f"The Orchestrator could not continue: {message}")
|
||||
update["events_recorded"] = await record_progress(state, ledger)
|
||||
return finish_with("end_with_warnings", warnings=warnings)
|
||||
update["events_recorded"] = await record_progress(
|
||||
state, ledger, "awaiting_user"
|
||||
)
|
||||
return ask({"questions": [{"from": ORCHESTRATOR, "question": message}]})
|
||||
|
||||
async def specialist_task(task_input: dict[str, Any]) -> dict[str, Any]:
|
||||
role = roles[task_input["role"]]
|
||||
kind = DeliverableKind(task_input["kind"])
|
||||
tools = specialist_tools(
|
||||
kind,
|
||||
extra=tool_factory(role, kind.value),
|
||||
allow_cloud_read=task_input["allow_cloud_read"],
|
||||
)
|
||||
task = AgentTask(
|
||||
role=role.name,
|
||||
prompt=f"Produce the {kind} Deliverable.",
|
||||
context=task_input["context"],
|
||||
deliverable=kind.value,
|
||||
)
|
||||
logger.info(
|
||||
"[%s] %s started %s (attempt %d)",
|
||||
task_input["execution_id"],
|
||||
role.name,
|
||||
kind,
|
||||
task_input["attempt"],
|
||||
)
|
||||
started = time.monotonic()
|
||||
try:
|
||||
outcome: Outcome = await runtime.run(role, task, tools)
|
||||
except Exception as exc:
|
||||
logger.exception("Specialist %s failed on %s", role.name, kind)
|
||||
outcome = Stopped(f"it failed with {type(exc).__name__}: {exc}")
|
||||
logger.info(
|
||||
"[%s] %s finished %s in %.0fs: %s",
|
||||
task_input["execution_id"],
|
||||
role.name,
|
||||
kind,
|
||||
time.monotonic() - started,
|
||||
_summarise_outcome(outcome),
|
||||
)
|
||||
return {
|
||||
"outcomes": [
|
||||
_outcome_record(role.name, kind, task_input["attempt"], outcome)
|
||||
]
|
||||
}
|
||||
|
||||
async def await_user(state: ExecutionState) -> Command:
|
||||
prompt = state["prompt"] or {}
|
||||
if state.get("pre_approved"):
|
||||
reply = _automatic_reply(prompt, state.get("scripted_answers", []))
|
||||
else:
|
||||
reply = interrupt(prompt)
|
||||
|
||||
ledger = Ledger.from_dict(state["ledger"])
|
||||
conversation = list(state.get("conversation", []))
|
||||
update: dict[str, Any] = {"prompt": None}
|
||||
|
||||
if "approval" in prompt:
|
||||
phase = prompt["approval"]["phase"]
|
||||
decision = reply.get("approval") if isinstance(reply, Mapping) else None
|
||||
if (
|
||||
isinstance(decision, Mapping)
|
||||
and decision.get("phase") == phase
|
||||
and decision.get("decision") in {"approve", "changes"}
|
||||
):
|
||||
phase_id = next(p for p in PHASE_ORDER if p.value == phase)
|
||||
if decision["decision"] == "approve":
|
||||
ledger.approve(phase_id, actor="user")
|
||||
text = f"Approved {phase}."
|
||||
else:
|
||||
feedback = str(decision.get("feedback", ""))
|
||||
ledger.request_changes(phase_id, feedback, actor="user")
|
||||
text = f"Requested changes to {phase}: {feedback}"
|
||||
conversation.append({"from": "user", "text": text})
|
||||
else:
|
||||
conversation.append({"from": "user", "text": _reply_text(reply)})
|
||||
elif "permission" in prompt:
|
||||
tier = prompt["permission"]["tier"]
|
||||
permission = reply.get("permission") if isinstance(reply, Mapping) else None
|
||||
grant = permission.get(tier) if isinstance(permission, Mapping) else None
|
||||
if isinstance(grant, bool):
|
||||
update["allow_cloud_read"] = grant
|
||||
update["pending_permission"] = None
|
||||
verdict = "granted" if grant else "denied"
|
||||
conversation.append(
|
||||
{
|
||||
"from": "user",
|
||||
"text": f"Permission to use {tier} tools {verdict}.",
|
||||
}
|
||||
)
|
||||
else:
|
||||
conversation.append({"from": "user", "text": _reply_text(reply)})
|
||||
else:
|
||||
text = _reply_text(reply)
|
||||
conversation.append({"from": "user", "text": text})
|
||||
answers = {
|
||||
kind: list(items) for kind, items in state.get("answers", {}).items()
|
||||
}
|
||||
for asked in state.get("awaiting_questions", []):
|
||||
answers.setdefault(asked["kind"], []).append(
|
||||
{"questions": list(asked["questions"]), "reply": text}
|
||||
)
|
||||
update.update(answers=answers, awaiting_questions=[])
|
||||
|
||||
update["events_recorded"] = await record_progress(state, ledger)
|
||||
update.update(ledger=ledger.to_dict(), conversation=conversation)
|
||||
return Command(update=update, goto="orchestrator_turn")
|
||||
|
||||
async def finalize(state: ExecutionState) -> dict[str, Any]:
|
||||
ledger = Ledger.from_dict(state["ledger"])
|
||||
_write_outputs(
|
||||
output_root / "deliverables" / "executions" / state["execution_id"],
|
||||
state.get("deliverables", {}),
|
||||
)
|
||||
await record_progress(state, ledger, "completed")
|
||||
return {"status": "completed"}
|
||||
|
||||
async def end_with_warnings(state: ExecutionState) -> dict[str, Any]:
|
||||
ledger = Ledger.from_dict(state["ledger"])
|
||||
await record_progress(state, ledger, "completed_with_warnings")
|
||||
return {"status": "completed_with_warnings"}
|
||||
|
||||
return ExecutionNodes(
|
||||
orchestrator_turn=orchestrator_turn,
|
||||
specialist_task=specialist_task,
|
||||
await_user=await_user,
|
||||
finalize=finalize,
|
||||
end_with_warnings=end_with_warnings,
|
||||
)
|
||||
|
||||
|
||||
# --- helpers ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def _summarise_outcome(outcome: Outcome) -> str:
|
||||
if isinstance(outcome, TurnEnded):
|
||||
return f"called {outcome.tool}"
|
||||
if isinstance(outcome, Submitted):
|
||||
return f"submitted ({len(outcome.content)} chars)"
|
||||
if isinstance(outcome, NeedsInput):
|
||||
return f"needs input ({len(outcome.questions)} questions)"
|
||||
if isinstance(outcome, BudgetExhausted):
|
||||
return f"budget exhausted: {outcome.summary[:200]}"
|
||||
return f"stopped: {outcome.message[:200]}"
|
||||
|
||||
|
||||
def _current_phase(ledger: Ledger) -> str:
|
||||
for phase in PHASE_ORDER:
|
||||
if ledger.phase_status(phase).value != "approved":
|
||||
return phase.value
|
||||
return PHASE_ORDER[-1].value
|
||||
|
||||
|
||||
def _orchestrator_context(
|
||||
state: ExecutionState,
|
||||
ledger: Ledger,
|
||||
pending_questions: Sequence[Mapping[str, Any]],
|
||||
notes: Sequence[str],
|
||||
) -> dict[str, Any]:
|
||||
return {
|
||||
"workflow_request": state["workflow_request"],
|
||||
"pre_approved": bool(state.get("pre_approved")),
|
||||
"allow_cloud_read": state.get("allow_cloud_read"),
|
||||
"deliverables": {
|
||||
kind.value: {
|
||||
"phase": spec.phase.value,
|
||||
"status": ledger.status(kind).value,
|
||||
"revisions": ledger.revisions(kind),
|
||||
"feedback": list(ledger.feedback(kind)),
|
||||
}
|
||||
for kind, spec in DEPENDENCY_GRAPH.items()
|
||||
},
|
||||
"phases": {
|
||||
phase.value: ledger.phase_status(phase).value for phase in PHASE_ORDER
|
||||
},
|
||||
"ready_work": [kind.value for kind in ledger.ready_work()],
|
||||
"phases_ready_for_approval": [
|
||||
p.value for p in ledger.phases_ready_for_approval()
|
||||
],
|
||||
"pending_questions": list(pending_questions),
|
||||
"conversation": list(state.get("conversation", []))[-20:],
|
||||
"notes": list(notes),
|
||||
}
|
||||
|
||||
|
||||
def _specialist_input(
|
||||
state: ExecutionState,
|
||||
ledger: Ledger,
|
||||
deliverables: Mapping[str, Mapping[str, Any]],
|
||||
kind: DeliverableKind,
|
||||
attempt: int,
|
||||
) -> dict[str, Any]:
|
||||
spec = DEPENDENCY_GRAPH[kind]
|
||||
return {
|
||||
"execution_id": state["execution_id"],
|
||||
"role": spec.specialist,
|
||||
"kind": kind.value,
|
||||
"attempt": attempt,
|
||||
"allow_cloud_read": state.get("allow_cloud_read"),
|
||||
"context": {
|
||||
"workflow_request": state["workflow_request"],
|
||||
"pre_approved": bool(state.get("pre_approved")),
|
||||
"dependencies": {
|
||||
dependency.value: dict(deliverables[dependency.value])
|
||||
for dependency in inputs_of(kind)
|
||||
},
|
||||
"feedback": list(ledger.feedback(kind)),
|
||||
"answers": list(state.get("answers", {}).get(kind.value, [])),
|
||||
"attempt": attempt,
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def _outcome_record(
|
||||
role: str, kind: DeliverableKind, attempt: int, outcome: Outcome
|
||||
) -> dict[str, Any]:
|
||||
base = {"role": role, "kind": kind.value, "attempt": attempt}
|
||||
if isinstance(outcome, Submitted):
|
||||
return {
|
||||
**base,
|
||||
"type": "submitted",
|
||||
"content": outcome.content,
|
||||
"attachments": dict(outcome.attachments),
|
||||
}
|
||||
if isinstance(outcome, NeedsInput):
|
||||
return {
|
||||
**base,
|
||||
"type": "needs_input",
|
||||
"questions": list(outcome.questions),
|
||||
"permission": outcome.permission,
|
||||
}
|
||||
if isinstance(outcome, BudgetExhausted):
|
||||
return {**base, "type": "budget_exhausted", "summary": outcome.summary}
|
||||
return {**base, "type": "stopped", "summary": _describe_unfinished(outcome)}
|
||||
|
||||
|
||||
def _describe_unfinished(outcome: Outcome) -> str:
|
||||
if isinstance(outcome, BudgetExhausted):
|
||||
return f"I paused: {outcome.summary} How should I proceed?"
|
||||
if isinstance(outcome, Stopped):
|
||||
return outcome.message
|
||||
if isinstance(outcome, NeedsInput):
|
||||
return " ".join(outcome.questions)
|
||||
return f"Ended with an unexpected outcome: {type(outcome).__name__}."
|
||||
|
||||
|
||||
def _automatic_reply(
|
||||
prompt: Mapping[str, Any], scripted_answers: Sequence[Sequence[str]] = ()
|
||||
) -> dict[str, Any]:
|
||||
"""The reply in a pre-approved Execution: approve, deny cloud reads, and answer
|
||||
questions from scripted (pattern, answer) pairs where one matches."""
|
||||
if "approval" in prompt:
|
||||
return {
|
||||
"approval": {"phase": prompt["approval"]["phase"], "decision": "approve"}
|
||||
}
|
||||
if "permission" in prompt:
|
||||
return {"permission": {prompt["permission"]["tier"]: False}}
|
||||
lines = []
|
||||
unanswered = False
|
||||
for item in prompt.get("questions", []):
|
||||
answer = next(
|
||||
(
|
||||
scripted
|
||||
for pattern, scripted in scripted_answers
|
||||
if re.search(pattern, item["question"], re.IGNORECASE)
|
||||
),
|
||||
None,
|
||||
)
|
||||
if answer is None:
|
||||
unanswered = True
|
||||
else:
|
||||
lines.append(f"Q: {item['question']}\nA: {answer}")
|
||||
if unanswered or not lines:
|
||||
lines.append(NO_USER_REPLY)
|
||||
return {"reply": "\n\n".join(lines)}
|
||||
|
||||
|
||||
def _reply_text(reply: object) -> str:
|
||||
if isinstance(reply, str):
|
||||
return reply
|
||||
if isinstance(reply, Mapping) and isinstance(reply.get("reply"), str):
|
||||
return reply["reply"]
|
||||
return str(reply)
|
||||
|
||||
|
||||
def _render_prompt(prompt: Mapping[str, Any]) -> str:
|
||||
if "approval" in prompt:
|
||||
approval = prompt["approval"]
|
||||
return f"Please approve {approval['phase']}: {approval['summary']}"
|
||||
if "permission" in prompt:
|
||||
return f"May I use {prompt['permission']['tier']} tools?"
|
||||
return "\n".join(item["question"] for item in prompt.get("questions", []))
|
||||
|
||||
|
||||
def _write_outputs(
|
||||
out_dir: Path, deliverables: Mapping[str, Mapping[str, Any]]
|
||||
) -> None:
|
||||
out_dir.mkdir(parents=True, exist_ok=True)
|
||||
guide = deliverables.get(DeliverableKind.SOLUTION_GUIDE.value)
|
||||
if guide:
|
||||
(out_dir / GUIDE_FILENAME).write_text(guide["content"], encoding="utf-8")
|
||||
for kind, deliverable in deliverables.items():
|
||||
path = out_dir / "deliverables" / f"{kind}.md"
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_text(deliverable["content"], encoding="utf-8")
|
||||
for name, content in deliverable.get("attachments", {}).items():
|
||||
attachment = out_dir / name
|
||||
attachment.parent.mkdir(parents=True, exist_ok=True)
|
||||
attachment.write_text(content, encoding="utf-8")
|
||||
@@ -1,43 +0,0 @@
|
||||
"""Phase 0a: Existing Source Environment Discovery Node."""
|
||||
|
||||
import logging
|
||||
import re
|
||||
from typing import Any, Dict
|
||||
from app.states.state import GCPArchitectureState
|
||||
from app.skills.loader import SkillLoader
|
||||
from app.tools.gcp_scanner import GCPEnvironmentScanner
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def source_discover_node(state: GCPArchitectureState, skill_loader: SkillLoader) -> Dict[str, Any]:
|
||||
"""Processes Phase 0a Source Environment Discovery: documents existing as-is architecture before target migration."""
|
||||
logger.info("Executing source_discover_node")
|
||||
skill_prompt = skill_loader.format_skills_for_prompt("source_discover")
|
||||
|
||||
# Extract target GCP project ID from request if specified
|
||||
request_summary = state.get("workflow_request", "")
|
||||
project_id = state.get("project_id")
|
||||
if not project_id and request_summary:
|
||||
match = re.search(r"project\s+([a-z0-9-]+)", request_summary, re.IGNORECASE)
|
||||
if match:
|
||||
project_id = match.group(1)
|
||||
|
||||
# Run live GCP environment scanner
|
||||
scanner = GCPEnvironmentScanner(project_id=project_id)
|
||||
scan_result = scanner.scan_environment()
|
||||
report = scanner.format_scan_report(scan_result)
|
||||
|
||||
source_discovery_doc = report["doc"]
|
||||
source_mermaid_diagram = report["mermaid"]
|
||||
|
||||
active_skills = state.get("active_skills", [])
|
||||
if "source_discovery" not in active_skills:
|
||||
active_skills.append("source_discovery")
|
||||
|
||||
return {
|
||||
"source_discovery_doc": source_discovery_doc,
|
||||
"source_mermaid_diagram": source_mermaid_diagram,
|
||||
"current_phase": "source_discover",
|
||||
"active_skills": active_skills,
|
||||
}
|
||||
@@ -1,60 +0,0 @@
|
||||
"""Phase 2: Pre-deployment Validation Node."""
|
||||
|
||||
import logging
|
||||
from typing import Any, Dict
|
||||
from app.states.state import GCPArchitectureState
|
||||
from app.skills.loader import SkillLoader
|
||||
from app.tools.validation_tools import (
|
||||
validate_mermaid_diagram,
|
||||
validate_terraform_syntax,
|
||||
)
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def validate_node(state: GCPArchitectureState, skill_loader: SkillLoader) -> Dict[str, Any]:
|
||||
"""Processes Phase 2 Validation: verify diagram, Terraform IaC, and artifact integrity."""
|
||||
logger.info("Executing validate_node")
|
||||
skill_prompt = skill_loader.format_skills_for_prompt("validate")
|
||||
|
||||
mermaid_content = state.get("mermaid_diagram", "")
|
||||
terraform_content = state.get("terraform_code", "")
|
||||
|
||||
mermaid_check = validate_mermaid_diagram.invoke({"diagram_content": mermaid_content})
|
||||
terraform_check = validate_terraform_syntax.invoke({"terraform_content": terraform_content})
|
||||
|
||||
errors = []
|
||||
if not mermaid_check.get("valid"):
|
||||
errors.append(f"Mermaid Check Failed: {mermaid_check.get('error')}")
|
||||
if not terraform_check.get("valid"):
|
||||
errors.append(f"Terraform Check Failed: {terraform_check.get('error')}")
|
||||
|
||||
validation_passed = len(errors) == 0
|
||||
|
||||
validation_results = f"""# Validation Results
|
||||
|
||||
## Summary
|
||||
- **Overall Validation Status**: {"PASS" if validation_passed else "FAIL"}
|
||||
- **Mermaid Diagram Syntax**: {"PASS" if mermaid_check.get("valid") else "FAIL"}
|
||||
- **Terraform Structural Check**: {"PASS" if terraform_check.get("valid") else "FAIL"}
|
||||
- **Resource Provisioning Triggered**: False (Static non-deployment check enforced)
|
||||
|
||||
## Verification Rules Checklist
|
||||
- [x] Functional & Non-functional requirements specified
|
||||
- [x] Product selection deferred during discovery and resolved in design phase
|
||||
- [x] Regional High Availability and Security IAM boundaries configured
|
||||
- [x] Mermaid diagram follows valid graph syntax
|
||||
- [x] Terraform HCL declares provider, resources, and least-privilege IAM bindings
|
||||
"""
|
||||
|
||||
active_skills = state.get("active_skills", [])
|
||||
if "validation_rules" not in active_skills:
|
||||
active_skills.append("validation_rules")
|
||||
|
||||
return {
|
||||
"validation_results": validation_results,
|
||||
"validation_passed": validation_passed,
|
||||
"errors": errors,
|
||||
"current_phase": "validate",
|
||||
"active_skills": active_skills,
|
||||
}
|
||||
141
app/presentation.py
Normal file
141
app/presentation.py
Normal file
@@ -0,0 +1,141 @@
|
||||
"""Presenting an Execution to callers: prompt text and the /generate response shape."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import re
|
||||
from collections.abc import Mapping, Sequence
|
||||
from typing import Any
|
||||
|
||||
from app.adk.runtime import RoleSpec
|
||||
from app.agent import Interaction
|
||||
from app.workflows.deliverables import DEPENDENCY_GRAPH, DeliverableKind
|
||||
|
||||
|
||||
def describe_prompt(prompt: Mapping[str, Any]) -> str:
|
||||
"""Plain-text rendering of what the user is asked, including how to answer."""
|
||||
if "approval" in prompt:
|
||||
approval = prompt["approval"]
|
||||
reply = {"approval": {"phase": approval["phase"], "decision": "approve"}}
|
||||
changes = {
|
||||
"approval": {
|
||||
"phase": approval["phase"],
|
||||
"decision": "changes",
|
||||
"feedback": "<what to change>",
|
||||
}
|
||||
}
|
||||
return (
|
||||
f"Please review the {approval['phase']} Phase: {approval['summary']}\n\n"
|
||||
f"Deliverables: {', '.join(approval['deliverables'])}.\n\n"
|
||||
f"To approve, reply with the data {json.dumps(reply)}. "
|
||||
f"To request changes, reply with {json.dumps(changes)}. "
|
||||
"A text reply is recorded as conversation and never approves."
|
||||
)
|
||||
if "permission" in prompt:
|
||||
permission = prompt["permission"]
|
||||
grant = {"permission": {permission["tier"]: True}}
|
||||
return (
|
||||
"May I read live resources in your cloud environment to discover the current "
|
||||
f"state? Requested by: {', '.join(permission['requested_by'])}.\n\n"
|
||||
f"To allow, reply with the data {json.dumps(grant)}; to refuse, use false."
|
||||
)
|
||||
lines = [
|
||||
f"{index}. ({item['from']}) {item['question']}"
|
||||
for index, item in enumerate(prompt.get("questions", []), start=1)
|
||||
]
|
||||
return "\n".join(lines) + "\n\nReply in text; answer every question you can."
|
||||
|
||||
|
||||
def to_generate_response(
|
||||
interaction: Interaction, roles: Mapping[str, RoleSpec]
|
||||
) -> dict[str, Any]:
|
||||
"""Map an Execution onto the legacy /generate response keys."""
|
||||
state = interaction.state
|
||||
deliverables: Mapping[str, Mapping[str, Any]] = state.get("deliverables", {})
|
||||
ledger = state.get("ledger", {})
|
||||
|
||||
def content(kind: DeliverableKind) -> str | None:
|
||||
item = deliverables.get(kind.value)
|
||||
return item["content"] if item else None
|
||||
|
||||
def attachment(kind: DeliverableKind, name: str) -> str | None:
|
||||
item = deliverables.get(kind.value)
|
||||
return item.get("attachments", {}).get(name) if item else None
|
||||
|
||||
requirements = content(DeliverableKind.REQUIREMENTS)
|
||||
revisions = sum(
|
||||
d.get("revisions", 0) for d in ledger.get("deliverables", {}).values()
|
||||
)
|
||||
submitted = [kind for kind in DeliverableKind if kind.value in deliverables]
|
||||
skills = _skills_used(submitted, roles)
|
||||
status = {
|
||||
"completed": "success",
|
||||
"completed_with_warnings": "completed_with_warnings",
|
||||
}.get(interaction.status, interaction.status)
|
||||
|
||||
return {
|
||||
"execution_id": interaction.execution_id,
|
||||
"session_id": state.get("session_id"),
|
||||
"status": status,
|
||||
"validation_passed": interaction.status == "completed",
|
||||
"total_loop_iterations": revisions + 1,
|
||||
"current_phase": _current_phase(ledger),
|
||||
"artifacts": {
|
||||
"source_discovery_doc": _section(requirements, "Current state"),
|
||||
"source_mermaid_diagram": None,
|
||||
"requirements_doc": requirements,
|
||||
"architecture_doc": content(DeliverableKind.ARCHITECTURE_DESCRIPTION),
|
||||
"mermaid_diagram": attachment(
|
||||
DeliverableKind.ARCHITECTURE_DIAGRAM, "architecture.mmd"
|
||||
),
|
||||
"terraform_code": attachment(
|
||||
DeliverableKind.DEPLOYMENT_GUIDANCE, "terraform/main.tf"
|
||||
),
|
||||
"validation_results": content(DeliverableKind.VALIDATION_RESULTS),
|
||||
"solution_guide": content(DeliverableKind.SOLUTION_GUIDE),
|
||||
},
|
||||
"active_skills": skills,
|
||||
"warnings": list(state.get("warnings", [])),
|
||||
}
|
||||
|
||||
|
||||
def _skills_used(
|
||||
submitted: Sequence[DeliverableKind], roles: Mapping[str, RoleSpec]
|
||||
) -> list[str]:
|
||||
names: list[str] = []
|
||||
for kind in submitted:
|
||||
role = roles.get(DEPENDENCY_GRAPH[kind].specialist)
|
||||
for skill in role.skills if role else ():
|
||||
if skill not in names:
|
||||
names.append(skill)
|
||||
return names
|
||||
|
||||
|
||||
def _current_phase(ledger: Mapping[str, Any]) -> str | None:
|
||||
phases: Mapping[str, str] = ledger.get("phases", {})
|
||||
for phase, status in phases.items():
|
||||
if status != "approved":
|
||||
return phase
|
||||
return list(phases)[-1] if phases else None
|
||||
|
||||
|
||||
def _section(markdown: str | None, heading: str) -> str | None:
|
||||
"""The body under a heading (any level, numbering ignored), up to the next heading."""
|
||||
if not markdown:
|
||||
return None
|
||||
lines = markdown.splitlines()
|
||||
pattern = re.compile(
|
||||
rf"^#{{1,6}}\s+(?:\d+(?:\.\d+)*\.?\s+)?{re.escape(heading)}\s*$", re.IGNORECASE
|
||||
)
|
||||
for index, line in enumerate(lines):
|
||||
if pattern.match(line.strip()):
|
||||
level = len(line.strip()) - len(line.strip().lstrip("#"))
|
||||
body = []
|
||||
for following in lines[index + 1 :]:
|
||||
stripped = following.strip()
|
||||
hashes = len(stripped) - len(stripped.lstrip("#"))
|
||||
if stripped.startswith("#") and hashes <= level:
|
||||
break
|
||||
body.append(following)
|
||||
return "\n".join(body).strip() or None
|
||||
return None
|
||||
176
app/providers.py
Normal file
176
app/providers.py
Normal file
@@ -0,0 +1,176 @@
|
||||
"""Cloud provider bundles.
|
||||
|
||||
A Cloud provider is configuration, not code (ADR-0002): providers/<name>.yaml lists
|
||||
the Skills, local tools, remote MCP servers and default models that one Cloud
|
||||
provider brings. Nothing outside this module names a provider.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Mapping
|
||||
from dataclasses import dataclass, field
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
import yaml
|
||||
|
||||
from app.skills.agent_skills import SkillFormatError, SkillMeta, discover_skills
|
||||
|
||||
TIERS = ("general", "cloud_read")
|
||||
_REPO_ROOT = Path(__file__).resolve().parent.parent
|
||||
|
||||
|
||||
class ProviderConfigError(ValueError):
|
||||
"""A provider bundle is missing or invalid."""
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class McpServerSpec:
|
||||
"""A remote MCP server hosted by the Cloud provider.
|
||||
|
||||
Only tools named in `allow` are ever exposed; an empty `allow` exposes nothing.
|
||||
"""
|
||||
|
||||
id: str
|
||||
url: str
|
||||
tier: str
|
||||
allow: tuple[str, ...]
|
||||
preview: bool = False
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ModelConfig:
|
||||
default: str
|
||||
roles: Mapping[str, str] = field(default_factory=dict)
|
||||
|
||||
def for_role(self, role: str) -> str:
|
||||
return self.roles.get(role, self.default)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ProviderBundle:
|
||||
name: str
|
||||
skills_dirs: tuple[Path, ...]
|
||||
skills: Mapping[str, SkillMeta]
|
||||
output_template: Path
|
||||
models: ModelConfig
|
||||
tools: Mapping[str, tuple[str, ...]]
|
||||
mcp_auth: Mapping[str, Any]
|
||||
mcp_servers: Mapping[str, McpServerSpec]
|
||||
role_mcp_servers: Mapping[str, tuple[str, ...]]
|
||||
role_skills: Mapping[str, tuple[str, ...]] = field(default_factory=dict)
|
||||
pillar_skills: Mapping[str, str] = field(default_factory=dict)
|
||||
|
||||
def mcp_servers_for_role(
|
||||
self, role: str, include_preview: bool = True
|
||||
) -> tuple[McpServerSpec, ...]:
|
||||
servers = (
|
||||
self.mcp_servers[server_id]
|
||||
for server_id in self.role_mcp_servers.get(role, ())
|
||||
)
|
||||
return tuple(
|
||||
server for server in servers if include_preview or not server.preview
|
||||
)
|
||||
|
||||
|
||||
def load_provider(name: str, root: Path | None = None) -> ProviderBundle:
|
||||
"""Load and validate providers/<name>.yaml; relative paths resolve against `root`."""
|
||||
root = root or _REPO_ROOT
|
||||
config_path = root / "providers" / f"{name}.yaml"
|
||||
if not config_path.is_file():
|
||||
raise ProviderConfigError(f"No provider bundle for {name!r} at {config_path}")
|
||||
|
||||
config = yaml.safe_load(config_path.read_text(encoding="utf-8")) or {}
|
||||
if not isinstance(config, dict):
|
||||
raise ProviderConfigError(f"{config_path}: must be a mapping")
|
||||
|
||||
def fail(message: str) -> ProviderConfigError:
|
||||
return ProviderConfigError(f"{config_path}: {message}")
|
||||
|
||||
if config.get("name") != name:
|
||||
raise fail(f"'name' must be {name!r}")
|
||||
|
||||
skills_dirs = tuple(root / entry for entry in config.get("skills_dirs") or ())
|
||||
if not skills_dirs:
|
||||
raise fail("'skills_dirs' must list at least one directory")
|
||||
for directory in skills_dirs:
|
||||
if not directory.is_dir():
|
||||
raise fail(f"'skills_dirs' entry {directory} is not a directory")
|
||||
try:
|
||||
skills = discover_skills(skills_dirs)
|
||||
except SkillFormatError as exc:
|
||||
raise fail(str(exc)) from exc
|
||||
|
||||
output_template = root / str(config.get("output_template", ""))
|
||||
if not config.get("output_template") or not output_template.is_file():
|
||||
raise fail(f"'output_template' {output_template} does not exist")
|
||||
|
||||
models = config.get("models") or {}
|
||||
if not isinstance(models.get("default"), str) or not models["default"]:
|
||||
raise fail("'models.default' is required")
|
||||
model_config = ModelConfig(
|
||||
default=models["default"], roles=dict(models.get("roles") or {})
|
||||
)
|
||||
|
||||
tools = {}
|
||||
for tier, tool_names in (config.get("tools") or {}).items():
|
||||
if tier not in TIERS:
|
||||
raise fail(f"'tools' tier {tier!r} must be one of {TIERS}")
|
||||
tools[tier] = tuple(tool_names or ())
|
||||
|
||||
mcp_servers = {}
|
||||
for server_id, spec in (config.get("mcp_servers") or {}).items():
|
||||
url = spec.get("url", "")
|
||||
if not url.startswith("https://"):
|
||||
raise fail(f"MCP server {server_id!r} url must use https")
|
||||
if spec.get("tier") not in TIERS:
|
||||
raise fail(f"MCP server {server_id!r} tier must be one of {TIERS}")
|
||||
if not isinstance(spec.get("allow"), list):
|
||||
raise fail(
|
||||
f"MCP server {server_id!r} needs an 'allow' list (empty exposes no tools)"
|
||||
)
|
||||
mcp_servers[server_id] = McpServerSpec(
|
||||
id=server_id,
|
||||
url=url,
|
||||
tier=spec["tier"],
|
||||
allow=tuple(spec["allow"]),
|
||||
preview=bool(spec.get("preview", False)),
|
||||
)
|
||||
|
||||
role_mcp_servers = {}
|
||||
for role, server_ids in (config.get("role_mcp_servers") or {}).items():
|
||||
unknown = [
|
||||
server_id for server_id in server_ids or () if server_id not in mcp_servers
|
||||
]
|
||||
if unknown:
|
||||
raise fail(
|
||||
f"role {role!r} references unknown MCP servers: {', '.join(unknown)}"
|
||||
)
|
||||
role_mcp_servers[role] = tuple(server_ids or ())
|
||||
|
||||
role_skills = {}
|
||||
for role, skill_names in (config.get("role_skills") or {}).items():
|
||||
unknown = [skill for skill in skill_names or () if skill not in skills]
|
||||
if unknown:
|
||||
raise fail(f"role {role!r} references unknown skills: {', '.join(unknown)}")
|
||||
role_skills[role] = tuple(skill_names or ())
|
||||
|
||||
pillar_skills = {}
|
||||
for pillar, skill_name in (config.get("pillar_skills") or {}).items():
|
||||
if skill_name not in skills:
|
||||
raise fail(f"pillar {pillar!r} references unknown skill {skill_name!r}")
|
||||
pillar_skills[str(pillar)] = skill_name
|
||||
|
||||
return ProviderBundle(
|
||||
name=name,
|
||||
skills_dirs=skills_dirs,
|
||||
skills=skills,
|
||||
output_template=output_template,
|
||||
models=model_config,
|
||||
tools=tools,
|
||||
mcp_auth=dict(config.get("mcp_auth") or {}),
|
||||
mcp_servers=mcp_servers,
|
||||
role_mcp_servers=role_mcp_servers,
|
||||
role_skills=role_skills,
|
||||
pillar_skills=pillar_skills,
|
||||
)
|
||||
156
app/recorder.py
Normal file
156
app/recorder.py
Normal file
@@ -0,0 +1,156 @@
|
||||
"""Recording an Execution's progress for audit and reporting.
|
||||
|
||||
Two adapters sit behind ExecutionRecorder: InMemoryRecorder for tests, and
|
||||
DatabaseRecorder, which reuses the existing DatabaseManager tables until the
|
||||
Execution store (review candidate 03) replaces them.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import uuid
|
||||
from collections import defaultdict
|
||||
from collections.abc import Mapping, Sequence
|
||||
from typing import Any, Protocol
|
||||
|
||||
from app.states.ledger import LedgerEvent
|
||||
|
||||
SESSION_AGENT_NAME = "solution-architect"
|
||||
|
||||
|
||||
class ExecutionRecorder(Protocol):
|
||||
async def record_events(
|
||||
self, execution_id: str, events: Sequence[LedgerEvent]
|
||||
) -> None: ...
|
||||
|
||||
async def record_submission(
|
||||
self,
|
||||
execution_id: str,
|
||||
kind: str,
|
||||
content: str,
|
||||
attachments: Mapping[str, str],
|
||||
) -> None: ...
|
||||
|
||||
async def record_status(
|
||||
self,
|
||||
execution_id: str,
|
||||
*,
|
||||
session_id: str,
|
||||
workflow_request: str,
|
||||
status: str,
|
||||
current_phase: str,
|
||||
details: Mapping[str, Any],
|
||||
) -> None: ...
|
||||
|
||||
|
||||
class InMemoryRecorder:
|
||||
def __init__(self) -> None:
|
||||
self.events: dict[str, list[LedgerEvent]] = defaultdict(list)
|
||||
self.submissions: dict[str, list[dict[str, Any]]] = defaultdict(list)
|
||||
self.statuses: dict[str, list[dict[str, Any]]] = defaultdict(list)
|
||||
|
||||
async def record_events(
|
||||
self, execution_id: str, events: Sequence[LedgerEvent]
|
||||
) -> None:
|
||||
self.events[execution_id].extend(events)
|
||||
|
||||
async def record_submission(
|
||||
self,
|
||||
execution_id: str,
|
||||
kind: str,
|
||||
content: str,
|
||||
attachments: Mapping[str, str],
|
||||
) -> None:
|
||||
self.submissions[execution_id].append(
|
||||
{"kind": kind, "content": content, "attachments": dict(attachments)}
|
||||
)
|
||||
|
||||
async def record_status(
|
||||
self,
|
||||
execution_id: str,
|
||||
*,
|
||||
session_id: str,
|
||||
workflow_request: str,
|
||||
status: str,
|
||||
current_phase: str,
|
||||
details: Mapping[str, Any],
|
||||
) -> None:
|
||||
self.statuses[execution_id].append(
|
||||
{
|
||||
"session_id": session_id,
|
||||
"workflow_request": workflow_request,
|
||||
"status": status,
|
||||
"current_phase": current_phase,
|
||||
"details": dict(details),
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
class DatabaseRecorder:
|
||||
"""Writes to DatabaseManager (blocking) off the event loop."""
|
||||
|
||||
def __init__(self, db_manager: Any = None) -> None:
|
||||
if db_manager is None:
|
||||
from app.database import get_db_manager
|
||||
|
||||
db_manager = get_db_manager()
|
||||
self._db = db_manager
|
||||
|
||||
async def record_events(
|
||||
self, execution_id: str, events: Sequence[LedgerEvent]
|
||||
) -> None:
|
||||
for event in events:
|
||||
await asyncio.to_thread(
|
||||
self._db.record_orchestrator_log,
|
||||
log_id=str(uuid.uuid4()),
|
||||
execution_id=execution_id,
|
||||
iteration=event.sequence,
|
||||
review_status=event.type,
|
||||
reviewer_agent=event.actor,
|
||||
feedback=f"{event.subject}: {event.detail}".rstrip(": "),
|
||||
)
|
||||
|
||||
async def record_submission(
|
||||
self,
|
||||
execution_id: str,
|
||||
kind: str,
|
||||
content: str,
|
||||
attachments: Mapping[str, str],
|
||||
) -> None:
|
||||
files = {f"deliverables/{kind}.md": content, **attachments}
|
||||
for file_path, file_content in files.items():
|
||||
await asyncio.to_thread(
|
||||
self._db.save_artifact,
|
||||
artifact_id=str(uuid.uuid4()),
|
||||
execution_id=execution_id,
|
||||
artifact_type=kind,
|
||||
file_path=file_path,
|
||||
content=file_content,
|
||||
)
|
||||
|
||||
async def record_status(
|
||||
self,
|
||||
execution_id: str,
|
||||
*,
|
||||
session_id: str,
|
||||
workflow_request: str,
|
||||
status: str,
|
||||
current_phase: str,
|
||||
details: Mapping[str, Any],
|
||||
) -> None:
|
||||
await asyncio.to_thread(
|
||||
self._db.save_workflow_execution,
|
||||
execution_id=execution_id,
|
||||
session_id=session_id,
|
||||
status=status,
|
||||
current_phase=current_phase,
|
||||
loop_count=int(details.get("revisions", 0)),
|
||||
request_summary=workflow_request,
|
||||
results=dict(details),
|
||||
)
|
||||
await asyncio.to_thread(
|
||||
self._db.save_session,
|
||||
session_id=session_id,
|
||||
agent_name=SESSION_AGENT_NAME,
|
||||
state_data={"latest_execution_id": execution_id, "status": status},
|
||||
)
|
||||
@@ -1,5 +1 @@
|
||||
"""Skills package."""
|
||||
|
||||
from .loader import LocalSkill, SkillLoader
|
||||
|
||||
__all__ = ["LocalSkill", "SkillLoader"]
|
||||
"""Agent Skills discovery and validation. The Skills themselves live in skills/ at the repository root."""
|
||||
|
||||
Binary file not shown.
Binary file not shown.
142
app/skills/agent_skills.py
Normal file
142
app/skills/agent_skills.py
Normal file
@@ -0,0 +1,142 @@
|
||||
"""Agent Skills discovery and frontmatter validation.
|
||||
|
||||
A Skill is a directory holding a SKILL.md whose YAML frontmatter follows the
|
||||
Agent Skills specification (https://agentskills.io/specification).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from collections.abc import Iterable
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
|
||||
import yaml
|
||||
|
||||
SKILL_FILE = "SKILL.md"
|
||||
|
||||
_NAME_PATTERN = re.compile(r"^[a-z0-9]+(?:-[a-z0-9]+)*$")
|
||||
_FRONTMATTER_PATTERN = re.compile(
|
||||
r"\A---[ \t]*\r?\n(.*?)\r?\n---[ \t]*(?:\r?\n|\Z)", re.DOTALL
|
||||
)
|
||||
_ALLOWED_FIELDS = {
|
||||
"name",
|
||||
"description",
|
||||
"license",
|
||||
"compatibility",
|
||||
"metadata",
|
||||
"allowed-tools",
|
||||
}
|
||||
|
||||
|
||||
class SkillFormatError(ValueError):
|
||||
"""A SKILL.md does not conform to the Agent Skills specification."""
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class SkillMeta:
|
||||
"""The level-1 metadata of a Skill, plus where it lives."""
|
||||
|
||||
name: str
|
||||
description: str
|
||||
path: Path
|
||||
|
||||
|
||||
def split_frontmatter(text: str, source: Path) -> tuple[dict, str]:
|
||||
"""Split a markdown document into its YAML frontmatter mapping and body."""
|
||||
match = _FRONTMATTER_PATTERN.match(text)
|
||||
if not match:
|
||||
raise SkillFormatError(f"{source}: missing YAML frontmatter delimited by '---'")
|
||||
try:
|
||||
frontmatter = yaml.safe_load(match.group(1))
|
||||
except yaml.YAMLError as exc:
|
||||
raise SkillFormatError(
|
||||
f"{source}: frontmatter is not valid YAML: {exc}"
|
||||
) from exc
|
||||
if not isinstance(frontmatter, dict):
|
||||
raise SkillFormatError(f"{source}: frontmatter must be a mapping")
|
||||
return frontmatter, text[match.end() :]
|
||||
|
||||
|
||||
def read_skill(skill_dir: Path) -> SkillMeta:
|
||||
"""Parse and validate the SKILL.md in `skill_dir`."""
|
||||
skill_file = skill_dir / SKILL_FILE
|
||||
frontmatter, _ = split_frontmatter(
|
||||
skill_file.read_text(encoding="utf-8"), skill_file
|
||||
)
|
||||
|
||||
unknown = set(frontmatter) - _ALLOWED_FIELDS
|
||||
if unknown:
|
||||
raise SkillFormatError(
|
||||
f"{skill_file}: unsupported frontmatter fields: {', '.join(sorted(unknown))}"
|
||||
)
|
||||
|
||||
name = frontmatter.get("name")
|
||||
if not isinstance(name, str) or not name:
|
||||
raise SkillFormatError(f"{skill_file}: 'name' is required")
|
||||
if len(name) > 64:
|
||||
raise SkillFormatError(f"{skill_file}: 'name' must be at most 64 characters")
|
||||
if not _NAME_PATTERN.match(name):
|
||||
raise SkillFormatError(
|
||||
f"{skill_file}: 'name' must use lowercase letters, digits and single hyphens, "
|
||||
"without leading or trailing hyphens"
|
||||
)
|
||||
if name != skill_dir.name:
|
||||
raise SkillFormatError(
|
||||
f"{skill_file}: 'name' {name!r} must match its directory {skill_dir.name!r}"
|
||||
)
|
||||
|
||||
description = frontmatter.get("description")
|
||||
if not isinstance(description, str) or not description.strip():
|
||||
raise SkillFormatError(
|
||||
f"{skill_file}: 'description' is required and must be non-empty"
|
||||
)
|
||||
if len(description) > 1024:
|
||||
raise SkillFormatError(
|
||||
f"{skill_file}: 'description' must be at most 1024 characters"
|
||||
)
|
||||
|
||||
compatibility = frontmatter.get("compatibility")
|
||||
if compatibility is not None and (
|
||||
not isinstance(compatibility, str) or not 1 <= len(compatibility) <= 500
|
||||
):
|
||||
raise SkillFormatError(
|
||||
f"{skill_file}: 'compatibility' must be 1-500 characters"
|
||||
)
|
||||
|
||||
metadata = frontmatter.get("metadata")
|
||||
if metadata is not None and (
|
||||
not isinstance(metadata, dict)
|
||||
or not all(
|
||||
isinstance(key, str) and isinstance(value, str)
|
||||
for key, value in metadata.items()
|
||||
)
|
||||
):
|
||||
raise SkillFormatError(
|
||||
f"{skill_file}: 'metadata' must map string keys to string values"
|
||||
)
|
||||
|
||||
for field in ("license", "allowed-tools"):
|
||||
if field in frontmatter and not isinstance(frontmatter[field], str):
|
||||
raise SkillFormatError(f"{skill_file}: '{field}' must be a string")
|
||||
|
||||
return SkillMeta(name=name, description=description, path=skill_dir)
|
||||
|
||||
|
||||
def discover_skills(directories: Iterable[Path]) -> dict[str, SkillMeta]:
|
||||
"""Index every Skill that is an immediate child of one of `directories`.
|
||||
|
||||
Raises SkillFormatError on an invalid Skill or a name defined twice.
|
||||
"""
|
||||
skills: dict[str, SkillMeta] = {}
|
||||
for directory in directories:
|
||||
for child in sorted(directory.iterdir()):
|
||||
if not (child / SKILL_FILE).is_file():
|
||||
continue
|
||||
skill = read_skill(child)
|
||||
if skill.name in skills:
|
||||
raise SkillFormatError(
|
||||
f"Skill {skill.name!r} is defined in both {skills[skill.name].path} and {skill.path}"
|
||||
)
|
||||
skills[skill.name] = skill
|
||||
return skills
|
||||
@@ -1,22 +0,0 @@
|
||||
---
|
||||
name: architecture_design
|
||||
phase: design
|
||||
description: Guidance for GCP product selection, architecture design markdown, Mermaid diagrams, and Terraform IaC generation.
|
||||
---
|
||||
|
||||
# Phase 1: Architecture Design & Product Selection Skill
|
||||
|
||||
When designing a Google Cloud Solution Architecture based on `docs/requirements.md`:
|
||||
|
||||
1. **Resolve Deferred Product Choices**: Select Google Cloud managed services suited for regional high availability and scale:
|
||||
- Compute: Cloud Run / Cloud Functions / GKE.
|
||||
- Messaging & Ingestion: Pub/Sub, Eventarc, or Cloud Tasks.
|
||||
- State & Storage: Cloud Storage, Firestore, Cloud SQL, or Spanner.
|
||||
- Identity & Security: Cloud IAM, Secret Manager, KMS, Artifact Registry.
|
||||
2. **Architecture Documentation (`docs/architecture.md`)**:
|
||||
- Provide executive summary, component responsibilities, data flow, security model, and cost model.
|
||||
3. **Mermaid Diagram (`architecture.mmd`)**:
|
||||
- Render clean, valid Mermaid syntax (`graph TD` or `flowchart TD`) mapping client ingress, compute, messaging, and storage components.
|
||||
4. **Terraform Infrastructure as Code (`terraform/`)**:
|
||||
- Produce valid Terraform HCL files (`main.tf`, `variables.tf`, `outputs.tf`, `versions.tf`).
|
||||
- Ensure planability without credentials or resource provisioning during validation.
|
||||
@@ -1,105 +0,0 @@
|
||||
"""Dynamic Local Skill Loader."""
|
||||
|
||||
import logging
|
||||
from dataclasses import dataclass, field
|
||||
from pathlib import Path
|
||||
from typing import Dict, List, Optional
|
||||
import yaml
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
@dataclass
|
||||
class LocalSkill:
|
||||
"""Represents a local skill loaded from SKILL.md."""
|
||||
|
||||
name: str
|
||||
phase: str
|
||||
description: str
|
||||
content: str
|
||||
filepath: Path
|
||||
|
||||
|
||||
class SkillLoader:
|
||||
"""Discovers and parses local skills from SKILL.md files."""
|
||||
|
||||
def __init__(self, skills_dir: Path) -> None:
|
||||
self.skills_dir = skills_dir
|
||||
self._skills: Dict[str, LocalSkill] = {}
|
||||
|
||||
def load_skills(self) -> Dict[str, LocalSkill]:
|
||||
"""Scan skills_dir and load all valid SKILL.md files."""
|
||||
self._skills.clear()
|
||||
if not self.skills_dir.exists():
|
||||
logger.warning("Skills directory does not exist: %s", self.skills_dir)
|
||||
return self._skills
|
||||
|
||||
for skill_file in self.skills_dir.glob("**/SKILL.md"):
|
||||
try:
|
||||
skill = self._parse_skill_file(skill_file)
|
||||
if skill:
|
||||
self._skills[skill.name] = skill
|
||||
logger.info("Loaded skill '%s' (phase: %s)", skill.name, skill.phase)
|
||||
except Exception as exc:
|
||||
logger.error("Failed to parse skill file %s: %s", skill_file, exc)
|
||||
|
||||
return self._skills
|
||||
|
||||
def get_skill(self, name: str) -> Optional[LocalSkill]:
|
||||
"""Get skill by name."""
|
||||
if not self._skills:
|
||||
self.load_skills()
|
||||
return self._skills.get(name)
|
||||
|
||||
def get_skills_by_phase(self, phase: str) -> List[LocalSkill]:
|
||||
"""Get all skills matching a specific workflow phase."""
|
||||
if not self._skills:
|
||||
self.load_skills()
|
||||
return [skill for skill in self._skills.values() if skill.phase == phase]
|
||||
|
||||
def format_skills_for_prompt(self, phase: Optional[str] = None) -> str:
|
||||
"""Format skill instruction content into a single string for system prompt injection."""
|
||||
skills = self.get_skills_by_phase(phase) if phase else list(self._skills.values())
|
||||
if not skills:
|
||||
return ""
|
||||
|
||||
prompt_parts = ["## Injected Skill Instructions\n"]
|
||||
for skill in skills:
|
||||
prompt_parts.append(f"### Skill: {skill.name} (Phase: {skill.phase})\n{skill.content}\n")
|
||||
return "\n".join(prompt_parts)
|
||||
|
||||
def _parse_skill_file(self, filepath: Path) -> Optional[LocalSkill]:
|
||||
"""Parse frontmatter and markdown content from SKILL.md."""
|
||||
raw_text = filepath.read_text(encoding="utf-8")
|
||||
if not raw_text.startswith("---"):
|
||||
return LocalSkill(
|
||||
name=filepath.parent.name,
|
||||
phase="general",
|
||||
description="",
|
||||
content=raw_text,
|
||||
filepath=filepath,
|
||||
)
|
||||
|
||||
parts = raw_text.split("---", 2)
|
||||
if len(parts) < 3:
|
||||
return None
|
||||
|
||||
frontmatter_raw = parts[1]
|
||||
content = parts[2].strip()
|
||||
|
||||
try:
|
||||
metadata = yaml.safe_load(frontmatter_raw) or {}
|
||||
except Exception:
|
||||
metadata = {}
|
||||
|
||||
name = metadata.get("name", filepath.parent.name)
|
||||
phase = metadata.get("phase", "general")
|
||||
description = metadata.get("description", "")
|
||||
|
||||
return LocalSkill(
|
||||
name=name,
|
||||
phase=phase,
|
||||
description=description,
|
||||
content=content,
|
||||
filepath=filepath,
|
||||
)
|
||||
@@ -1,37 +0,0 @@
|
||||
---
|
||||
name: packaging_guide
|
||||
phase: package
|
||||
description: Guidance for assembling the comprehensive solution-architecture-guide.md following Google's official 8-section output template.
|
||||
---
|
||||
|
||||
# Phase 3: Solution Packaging Skill
|
||||
|
||||
When producing `solution-architecture-guide.md`, follow Google's official 8-section solution architecture output template:
|
||||
|
||||
1. **Executive summary and workload overview**
|
||||
- High-level business goals, workload description, and proposed solution architecture summary.
|
||||
2. **Requirements and current state**
|
||||
- **2.1. Functional requirements**: Business processes, key activities, and use cases.
|
||||
- **2.2. Non-functional requirements**: Security, reliability, cost, operations, performance, and sustainability requirements.
|
||||
- **2.3. Current state**: Existing As-Is architecture, pain points, and migration drivers.
|
||||
- **2.4. Dependencies**: Internal and external system dependencies.
|
||||
3. **Technical decomposition of the workload**
|
||||
- Layered breakdown of application tiers and logical components.
|
||||
4. **Proposed solution architecture**
|
||||
- **4.1. Google Cloud products and features mapping**: Selected products mapping table with justifications, doc citations, and alternatives considered.
|
||||
- **4.2. Architecture diagram**: Embedded Mermaid diagrams for As-Is (Before) and Target Google Cloud (After) architecture.
|
||||
- **4.3. Architecture description**: Data flow and task/control flow between components.
|
||||
5. **Design and configuration recommendations** (Architecture Framework Pillars)
|
||||
- 5.1 Security, privacy, and compliance (IAM, encryption, network security)
|
||||
- 5.2 Reliability (Redundancy, disaster recovery, RTO/RPO)
|
||||
- 5.3 Operational excellence (Monitoring, logging, IaC)
|
||||
- 5.4 Cost optimization (Sizing, autoscaling, pricing models)
|
||||
- 5.5 Performance efficiency (Caching, database & query optimization)
|
||||
- 5.6 Sustainability (Resource efficiency, serverless adoption)
|
||||
6. **Deployment guidance**
|
||||
- **6.1. Deployment prerequisites**: Required GCP APIs, SDK tools, and permissions.
|
||||
- **6.2. Step-by-step deployment instructions**: Complete Terraform IaC blueprint (`terraform/main.tf`) and CLI execution runbook.
|
||||
7. **Validation plan**
|
||||
- Pre-deployment validation results, dry-run checks, and Verification Checklist.
|
||||
8. **References**
|
||||
- Citations and documentation links grounded by Google Developer Knowledge MCP.
|
||||
@@ -1,19 +0,0 @@
|
||||
---
|
||||
name: requirements_discovery
|
||||
phase: discover
|
||||
description: Guidance for discovering, analyzing, and documenting GCP solution requirements.
|
||||
---
|
||||
|
||||
# Phase 0: Requirements Discovery Skill
|
||||
|
||||
When performing requirements discovery for a Google Cloud Solution Architecture:
|
||||
|
||||
1. **Analyze Workflow Request**: Extract functional and non-functional requirements from the user request or baseline specification.
|
||||
2. **Defer Product Selection**: During discovery, product selection must explicitly be marked as `deferred: true`. Do not commit to specific GCP products (e.g. Cloud Run vs GKE) until the design phase.
|
||||
3. **Capture Core Requirements**:
|
||||
- Authenticated HTTPS ingress, stateless processing, asynchronous domain events.
|
||||
- High availability within a selected GCP region.
|
||||
- At-least-once delivery with idempotent processing.
|
||||
- Least-privilege IAM service accounts and private networking where practical.
|
||||
4. **Document Assumptions and Open Questions**: Highlight unknowns regarding scale, traffic spikes, compliance, and specific region requirements.
|
||||
5. **Output Standard**: Produce a valid `docs/requirements.md` file matching the phase spec.
|
||||
@@ -1,22 +0,0 @@
|
||||
---
|
||||
name: source_discovery
|
||||
phase: source_discover
|
||||
description: Guidance for discovering, auditing, and documenting the existing pre-emptive source environment before target migration.
|
||||
---
|
||||
|
||||
# Phase 0a: Existing Source Environment Discovery Skill
|
||||
|
||||
When auditing and discovering an existing pre-emptive source environment:
|
||||
|
||||
1. **Assess As-Is Architecture**: Analyze existing workloads, on-premises applications, legacy infrastructure, or existing cloud provider setups.
|
||||
2. **Identify Existing Components**:
|
||||
- Monolithic / legacy application services & ingress endpoints.
|
||||
- Self-hosted database engines (e.g. MySQL, PostgreSQL, Oracle) or legacy file shares.
|
||||
- Traditional messaging queues (e.g. RabbitMQ, ActiveMQ).
|
||||
- Network topology, firewall rules, and authentication mechanisms.
|
||||
3. **Capture Source Metrics & Pain Points**:
|
||||
- Current scale, capacity constraints, downtime risks, and operational bottlenecks.
|
||||
- Security vulnerabilities, compliance gaps, and maintenance costs.
|
||||
4. **Document Source Architecture**:
|
||||
- Produce a clear `docs/source-architecture.md` baseline documenting the "Before" state.
|
||||
- Render a Mermaid diagram representing the existing source topology (`source-architecture.mmd`).
|
||||
@@ -1,19 +0,0 @@
|
||||
---
|
||||
name: validation_rules
|
||||
phase: validate
|
||||
description: Guidance for verifying Terraform syntax, Mermaid diagrams, and repository artifact completeness.
|
||||
---
|
||||
|
||||
# Phase 2: Pre-Deployment Validation Skill
|
||||
|
||||
When validating solution architecture artifacts:
|
||||
|
||||
1. **Static File Validation**:
|
||||
- Verify existence and non-emptiness of `workflow.yaml`, `requirements.yaml`, `docs/requirements.md`, `docs/architecture.md`, `architecture.mmd`, `terraform/main.tf`, `solution-architecture-guide.md`.
|
||||
2. **Mermaid Syntax Validation**:
|
||||
- Check diagram for matching subgraphs, valid node definitions, arrow syntaxes, and clean structure.
|
||||
3. **Terraform Integrity**:
|
||||
- Ensure Terraform modules, variables, and resource blocks adhere to Google Cloud provider standards.
|
||||
- Ensure static non-provisioning check passes (`deploy_resources: false`).
|
||||
4. **Output Report**:
|
||||
- Generate `validation-results.md` summarizing pass/fail status across all verification rules.
|
||||
@@ -1,5 +1 @@
|
||||
"""States package."""
|
||||
|
||||
from .state import GCPArchitectureState
|
||||
|
||||
__all__ = ["GCPArchitectureState"]
|
||||
"""Checkpointed Execution state and the Ledger that guards it."""
|
||||
|
||||
Binary file not shown.
Binary file not shown.
36
app/states/execution_state.py
Normal file
36
app/states/execution_state.py
Normal file
@@ -0,0 +1,36 @@
|
||||
"""The checkpointed state of one Execution. Plain, JSON-compatible data only."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import operator
|
||||
from typing import Annotated, Any, TypedDict
|
||||
|
||||
|
||||
class ExecutionState(TypedDict, total=False):
|
||||
execution_id: str
|
||||
session_id: str
|
||||
workflow_request: str
|
||||
pre_approved: bool
|
||||
allow_cloud_read: bool | None
|
||||
|
||||
ledger: dict[str, Any] # Ledger.to_dict()
|
||||
deliverables: dict[str, dict[str, Any]] # kind -> {content, attachments}
|
||||
|
||||
conversation: list[dict[str, str]] # {"from": "user" | "orchestrator", "text"}
|
||||
notes: list[str] # facts for the Orchestrator's next turn
|
||||
pending_questions: list[dict[str, Any]] # {kind, questions} not yet asked
|
||||
awaiting_questions: list[dict[str, Any]] # {kind, questions} asked, not answered
|
||||
answers: dict[str, list[dict[str, Any]]] # kind -> [{questions, reply}]
|
||||
pending_permission: dict[str, Any] | None # {tier, requested_by}
|
||||
prompt: dict[str, Any] | None # what the user is being asked
|
||||
|
||||
# Specialist outcomes, appended concurrently by parallel Specialist tasks and
|
||||
# applied to the Ledger by the next Orchestrator turn.
|
||||
outcomes: Annotated[list[dict[str, Any]], operator.add]
|
||||
outcomes_applied: int
|
||||
events_recorded: int
|
||||
|
||||
turns: int
|
||||
status: str # running | completed | completed_with_warnings
|
||||
warnings: list[str]
|
||||
scripted_answers: list[list[str]] # [regex, answer], pre-approved runs only
|
||||
317
app/states/ledger.py
Normal file
317
app/states/ledger.py
Normal file
@@ -0,0 +1,317 @@
|
||||
"""The Ledger: every rule code owns about Deliverable progress, Approvals and Revisions.
|
||||
|
||||
Pure and synchronous: no I/O, no framework types. Invalid requests raise
|
||||
LedgerRefusal and leave the Ledger unchanged; tools turn refusals into messages
|
||||
the agent can act on.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Iterable
|
||||
from dataclasses import asdict, dataclass, field
|
||||
from enum import StrEnum
|
||||
from typing import Any
|
||||
|
||||
from app.workflows.deliverables import (
|
||||
DEPENDENCY_GRAPH,
|
||||
PHASE_ORDER,
|
||||
DeliverableKind,
|
||||
PhaseId,
|
||||
deliverables_in,
|
||||
)
|
||||
|
||||
PRE_APPROVED_ACTOR = "pre-approved"
|
||||
|
||||
|
||||
class DeliverableStatus(StrEnum):
|
||||
PENDING = "pending"
|
||||
IN_PROGRESS = "in_progress"
|
||||
SUBMITTED = "submitted"
|
||||
|
||||
|
||||
class PhaseStatus(StrEnum):
|
||||
OPEN = "open"
|
||||
AWAITING_APPROVAL = "awaiting_approval"
|
||||
APPROVED = "approved"
|
||||
|
||||
|
||||
class LedgerRefusal(Exception):
|
||||
"""A request the Ledger's rules don't allow. Nothing was changed."""
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class LedgerEvent:
|
||||
sequence: int
|
||||
type: str # started | released | submitted | approval_requested | approved |
|
||||
# changes_requested | reopened | reset | approval_withdrawn | escalated
|
||||
subject: str # a DeliverableKind or PhaseId value
|
||||
actor: str
|
||||
detail: str = ""
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ReopenResult:
|
||||
reset: tuple[DeliverableKind, ...]
|
||||
withdrawn_approvals: tuple[PhaseId, ...]
|
||||
escalation: str | None = None
|
||||
|
||||
|
||||
@dataclass
|
||||
class _DeliverableRecord:
|
||||
status: DeliverableStatus = DeliverableStatus.PENDING
|
||||
attempt: int = 0
|
||||
revisions: int = 0
|
||||
feedback: list[str] = field(default_factory=list)
|
||||
|
||||
|
||||
class Ledger:
|
||||
def __init__(self, pre_approved: bool = False, max_revisions: int = 3) -> None:
|
||||
self.pre_approved = pre_approved
|
||||
self.max_revisions = max_revisions
|
||||
self._deliverables = {kind: _DeliverableRecord() for kind in DEPENDENCY_GRAPH}
|
||||
self._phases = {phase: PhaseStatus.OPEN for phase in PHASE_ORDER}
|
||||
self._events: list[LedgerEvent] = []
|
||||
|
||||
# --- queries -----------------------------------------------------------------
|
||||
|
||||
@property
|
||||
def events(self) -> tuple[LedgerEvent, ...]:
|
||||
return tuple(self._events)
|
||||
|
||||
def status(self, kind: DeliverableKind) -> DeliverableStatus:
|
||||
return self._deliverables[kind].status
|
||||
|
||||
def phase_status(self, phase: PhaseId) -> PhaseStatus:
|
||||
return self._phases[phase]
|
||||
|
||||
def revisions(self, kind: DeliverableKind) -> int:
|
||||
return self._deliverables[kind].revisions
|
||||
|
||||
def feedback(self, kind: DeliverableKind) -> tuple[str, ...]:
|
||||
return tuple(self._deliverables[kind].feedback)
|
||||
|
||||
def dependencies_met(self, kind: DeliverableKind) -> bool:
|
||||
spec = DEPENDENCY_GRAPH[kind]
|
||||
for dependency in spec.depends_on:
|
||||
dependency_phase = DEPENDENCY_GRAPH[dependency].phase
|
||||
if dependency_phase is spec.phase:
|
||||
if self.status(dependency) is not DeliverableStatus.SUBMITTED:
|
||||
return False
|
||||
elif self._phases[dependency_phase] is not PhaseStatus.APPROVED:
|
||||
return False
|
||||
return True
|
||||
|
||||
def ready_work(self) -> tuple[DeliverableKind, ...]:
|
||||
return tuple(
|
||||
kind
|
||||
for kind in DEPENDENCY_GRAPH
|
||||
if self.status(kind) is DeliverableStatus.PENDING
|
||||
and self.dependencies_met(kind)
|
||||
)
|
||||
|
||||
def phases_ready_for_approval(self) -> tuple[PhaseId, ...]:
|
||||
return tuple(
|
||||
phase
|
||||
for phase in PHASE_ORDER
|
||||
if self._phases[phase] is PhaseStatus.OPEN and not self._unsubmitted(phase)
|
||||
)
|
||||
|
||||
def can_finish(self) -> bool:
|
||||
return self._phases[PHASE_ORDER[-1]] is PhaseStatus.APPROVED
|
||||
|
||||
# --- delegation and submission -----------------------------------------------
|
||||
|
||||
def start(
|
||||
self, kinds: Iterable[DeliverableKind], actor: str
|
||||
) -> dict[DeliverableKind, int]:
|
||||
"""Move ready Deliverables in progress; returns the attempt number for each."""
|
||||
kinds = list(dict.fromkeys(kinds))
|
||||
ready = set(self.ready_work())
|
||||
not_ready = [kind for kind in kinds if kind not in ready]
|
||||
if not_ready:
|
||||
raise LedgerRefusal(
|
||||
"Not ready to start: "
|
||||
+ ", ".join(self._describe_unready(k) for k in not_ready)
|
||||
)
|
||||
attempts = {}
|
||||
for kind in kinds:
|
||||
record = self._deliverables[kind]
|
||||
record.status = DeliverableStatus.IN_PROGRESS
|
||||
record.attempt += 1
|
||||
attempts[kind] = record.attempt
|
||||
self._record("started", kind, actor, f"attempt {record.attempt}")
|
||||
return attempts
|
||||
|
||||
def submit(self, kind: DeliverableKind, attempt: int, actor: str) -> None:
|
||||
"""Accept the current attempt. Any later start, release or reopen supersedes it."""
|
||||
self._require_current_attempt(kind, attempt)
|
||||
self._deliverables[kind].status = DeliverableStatus.SUBMITTED
|
||||
self._record("submitted", kind, actor, f"attempt {attempt}")
|
||||
|
||||
def release(self, kind: DeliverableKind, attempt: int, reason: str) -> None:
|
||||
"""Return in-progress work to pending (e.g. the Specialist needs input)."""
|
||||
self._require_current_attempt(kind, attempt)
|
||||
record = self._deliverables[kind]
|
||||
record.status = DeliverableStatus.PENDING
|
||||
self._record("released", kind, DEPENDENCY_GRAPH[kind].specialist, reason)
|
||||
|
||||
# --- approvals ---------------------------------------------------------------
|
||||
|
||||
def request_approval(self, phase: PhaseId, actor: str) -> None:
|
||||
if self._phases[phase] is not PhaseStatus.OPEN:
|
||||
raise LedgerRefusal(f"Phase {phase} is {self._phases[phase]}, not open")
|
||||
unsubmitted = self._unsubmitted(phase)
|
||||
if unsubmitted:
|
||||
raise LedgerRefusal(
|
||||
f"Phase {phase} has unsubmitted Deliverables: {', '.join(unsubmitted)}"
|
||||
)
|
||||
self._phases[phase] = PhaseStatus.AWAITING_APPROVAL
|
||||
self._record("approval_requested", phase, actor)
|
||||
if self.pre_approved:
|
||||
self.approve(phase, actor=PRE_APPROVED_ACTOR)
|
||||
|
||||
def approve(self, phase: PhaseId, actor: str) -> None:
|
||||
self._require_awaiting(phase)
|
||||
self._phases[phase] = PhaseStatus.APPROVED
|
||||
self._record("approved", phase, actor)
|
||||
|
||||
def request_changes(self, phase: PhaseId, feedback: str, actor: str) -> None:
|
||||
self._require_awaiting(phase)
|
||||
self._phases[phase] = PhaseStatus.OPEN
|
||||
self._record("changes_requested", phase, actor, feedback)
|
||||
|
||||
# --- revisions ---------------------------------------------------------------
|
||||
|
||||
def reopen(
|
||||
self,
|
||||
kind: DeliverableKind,
|
||||
reason: str,
|
||||
actor: str,
|
||||
override_cap: bool = False,
|
||||
) -> ReopenResult:
|
||||
record = self._deliverables[kind]
|
||||
if record.status is not DeliverableStatus.SUBMITTED:
|
||||
raise LedgerRefusal(
|
||||
f"Only submitted Deliverables can be reopened; {kind} is {record.status}"
|
||||
)
|
||||
if record.revisions >= self.max_revisions and not override_cap:
|
||||
escalation = (
|
||||
f"{kind} has reached its revision limit ({self.max_revisions}). "
|
||||
f"Requested change: {reason}. Ask the user whether to revise it again "
|
||||
"or accept it as it stands."
|
||||
)
|
||||
self._record("escalated", kind, actor, reason)
|
||||
return ReopenResult(reset=(), withdrawn_approvals=(), escalation=escalation)
|
||||
|
||||
record.status = DeliverableStatus.PENDING
|
||||
record.revisions += 1
|
||||
record.feedback.append(reason)
|
||||
self._record("reopened", kind, actor, reason)
|
||||
reset = [kind]
|
||||
|
||||
for dependent in self._dependents_of(kind):
|
||||
dependent_record = self._deliverables[dependent]
|
||||
if dependent_record.status is DeliverableStatus.PENDING:
|
||||
continue
|
||||
dependent_record.status = DeliverableStatus.PENDING
|
||||
dependent_record.feedback.append(f"Dependency {kind} was revised: {reason}")
|
||||
self._record("reset", dependent, actor, f"dependency {kind} reopened")
|
||||
reset.append(dependent)
|
||||
|
||||
withdrawn = []
|
||||
for phase in PHASE_ORDER:
|
||||
affected = any(DEPENDENCY_GRAPH[k].phase is phase for k in reset)
|
||||
if affected and self._phases[phase] is not PhaseStatus.OPEN:
|
||||
self._phases[phase] = PhaseStatus.OPEN
|
||||
self._record("approval_withdrawn", phase, actor, f"{kind} reopened")
|
||||
withdrawn.append(phase)
|
||||
|
||||
return ReopenResult(reset=tuple(reset), withdrawn_approvals=tuple(withdrawn))
|
||||
|
||||
# --- persistence -------------------------------------------------------------
|
||||
|
||||
def to_dict(self) -> dict[str, Any]:
|
||||
return {
|
||||
"pre_approved": self.pre_approved,
|
||||
"max_revisions": self.max_revisions,
|
||||
"deliverables": {
|
||||
kind.value: {
|
||||
"status": record.status.value,
|
||||
"attempt": record.attempt,
|
||||
"revisions": record.revisions,
|
||||
"feedback": list(record.feedback),
|
||||
}
|
||||
for kind, record in self._deliverables.items()
|
||||
},
|
||||
"phases": {
|
||||
phase.value: status.value for phase, status in self._phases.items()
|
||||
},
|
||||
"events": [asdict(event) for event in self._events],
|
||||
}
|
||||
|
||||
@classmethod
|
||||
def from_dict(cls, data: dict[str, Any]) -> Ledger:
|
||||
ledger = cls(
|
||||
pre_approved=data["pre_approved"], max_revisions=data["max_revisions"]
|
||||
)
|
||||
for kind_value, record in data["deliverables"].items():
|
||||
ledger._deliverables[DeliverableKind(kind_value)] = _DeliverableRecord(
|
||||
status=DeliverableStatus(record["status"]),
|
||||
attempt=record["attempt"],
|
||||
revisions=record["revisions"],
|
||||
feedback=list(record["feedback"]),
|
||||
)
|
||||
for phase_value, status in data["phases"].items():
|
||||
ledger._phases[PhaseId(phase_value)] = PhaseStatus(status)
|
||||
ledger._events = [LedgerEvent(**event) for event in data["events"]]
|
||||
return ledger
|
||||
|
||||
# --- internals ---------------------------------------------------------------
|
||||
|
||||
def _record(self, type_: str, subject: str, actor: str, detail: str = "") -> None:
|
||||
self._events.append(
|
||||
LedgerEvent(len(self._events) + 1, type_, str(subject), actor, detail)
|
||||
)
|
||||
|
||||
def _unsubmitted(self, phase: PhaseId) -> list[DeliverableKind]:
|
||||
return [
|
||||
kind
|
||||
for kind in deliverables_in(phase)
|
||||
if self.status(kind) is not DeliverableStatus.SUBMITTED
|
||||
]
|
||||
|
||||
def _dependents_of(self, kind: DeliverableKind) -> list[DeliverableKind]:
|
||||
"""Every Deliverable that depends on `kind`, directly or not, in graph order."""
|
||||
dependents: set[DeliverableKind] = set()
|
||||
frontier = {kind}
|
||||
while frontier:
|
||||
frontier = {
|
||||
candidate
|
||||
for candidate, spec in DEPENDENCY_GRAPH.items()
|
||||
if candidate not in dependents and frontier & set(spec.depends_on)
|
||||
}
|
||||
dependents |= frontier
|
||||
return [candidate for candidate in DEPENDENCY_GRAPH if candidate in dependents]
|
||||
|
||||
def _describe_unready(self, kind: DeliverableKind) -> str:
|
||||
status = self.status(kind)
|
||||
if status is not DeliverableStatus.PENDING:
|
||||
return f"{kind} ({status})"
|
||||
return f"{kind} (dependencies not met)"
|
||||
|
||||
def _require_current_attempt(self, kind: DeliverableKind, attempt: int) -> None:
|
||||
record = self._deliverables[kind]
|
||||
if (
|
||||
record.status is not DeliverableStatus.IN_PROGRESS
|
||||
or attempt != record.attempt
|
||||
):
|
||||
raise LedgerRefusal(
|
||||
f"{kind} is {record.status}, not in_progress with attempt {attempt}; "
|
||||
"this attempt is not current"
|
||||
)
|
||||
|
||||
def _require_awaiting(self, phase: PhaseId) -> None:
|
||||
if self._phases[phase] is not PhaseStatus.AWAITING_APPROVAL:
|
||||
raise LedgerRefusal(
|
||||
f"Phase {phase} is {self._phases[phase]}, not awaiting_approval"
|
||||
)
|
||||
@@ -1,31 +0,0 @@
|
||||
"""State definition for GCP Solution Architecture Agent workflow."""
|
||||
|
||||
from typing import Any, Dict, List, Optional, TypedDict
|
||||
|
||||
|
||||
class GCPArchitectureState(TypedDict, total=False):
|
||||
"""LangGraph State tracking state across all workflow phases."""
|
||||
|
||||
# Workflow Request / Input Intent
|
||||
workflow_request: str
|
||||
target_dir: str
|
||||
|
||||
# Pre-emptive Source Environment Discovery Outputs (Before State)
|
||||
source_discovery_doc: Optional[str]
|
||||
source_mermaid_diagram: Optional[str]
|
||||
|
||||
# Target Phase Outputs (After State)
|
||||
requirements_doc: Optional[str]
|
||||
architecture_doc: Optional[str]
|
||||
mermaid_diagram: Optional[str]
|
||||
terraform_code: Optional[str]
|
||||
validation_results: Optional[str]
|
||||
solution_guide: Optional[str]
|
||||
|
||||
# Workflow Metadata & Dynamic Skill Context
|
||||
product_selection_deferred: bool
|
||||
current_phase: str
|
||||
active_skills: List[str]
|
||||
errors: List[str]
|
||||
validation_passed: bool
|
||||
status_summary: Dict[str, Any]
|
||||
@@ -1,27 +1 @@
|
||||
"""Tools package."""
|
||||
|
||||
from .gcp_scanner import GCPEnvironmentScanner
|
||||
from .mcp_developer_knowledge import (
|
||||
DeveloperKnowledgeMCPClient,
|
||||
developerknowledge_answer_query,
|
||||
developerknowledge_get_documents,
|
||||
developerknowledge_search_documents,
|
||||
get_mcp_client,
|
||||
)
|
||||
from .validation_tools import (
|
||||
validate_mermaid_diagram,
|
||||
validate_repository_artifacts,
|
||||
validate_terraform_syntax,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
"validate_mermaid_diagram",
|
||||
"validate_repository_artifacts",
|
||||
"validate_terraform_syntax",
|
||||
"developerknowledge_search_documents",
|
||||
"developerknowledge_get_documents",
|
||||
"developerknowledge_answer_query",
|
||||
"DeveloperKnowledgeMCPClient",
|
||||
"get_mcp_client",
|
||||
"GCPEnvironmentScanner",
|
||||
]
|
||||
|
||||
Binary file not shown.
Binary file not shown.
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user