Compare commits

...

3 Commits

Author SHA1 Message Date
5bb22d984e fixed multile issues
Some checks failed
validation / verify (push) Failing after 8s
2026-10-07 17:33:36 +01:00
4c4d44ef87 fix: show the Orchestrator a validation only while it stands
After deployment guidance was reopened, the Orchestrator's context still
carried the previous validation's verdicts, so it reopened the code for the
same Check three times without a validation in between (evaluation run of
2026-10-07, case 01). Record that run in the iteration 6 plan.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-07 15:08:09 +01:00
e9246828b3 feat: establish the Target architecture as a graph before code
Design is now approved before any infrastructure code is written (ADR-0005).
A new target-architect Specialist produces one graph of Elements,
Relationships and Checks; the diagram is rendered from it, deployment
guidance must account for every Check, and validation gives a verdict per
Check. Requirements, components, products and recommendations carry ids in
data files, and a submission with a gap in the Requirements chain is refused.

Also in this commit:
- Customer cases group Executions, with an intent history per case
- lesson candidates are captured when an Execution ends
- evaluation gains chain, verdict, judged and interactive checks, and
  per-case thresholds
- Terraform providers are cached between checks
- the requirements analyst proposes defaults instead of asking
- the legacy-baseline case and the checks that only read it are removed
- ADR-0006 (Change requests) accepted; ADR-0004 and ADR-0007 proposed
- plans for iterations 4 to 7 under .agents/plans/

Unproven with a real model: no evaluation run has completed on this design.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-07 13:59:09 +01:00
624 changed files with 10942 additions and 22540 deletions

View File

@@ -8,9 +8,13 @@ One directory per iteration of this agent. Each holds the plan for that iteratio
|---|---|---|---|
| 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. |
| 3 | `iter-03-kab-layout/` | complete (commit `7ee49ab`) | The container starts the new engine, the engine moved into the KAB workflow-agent folder layout, and the original pipeline was deleted. |
| 4 | `iter-04-learning-and-skills/` | steps 1–8, 11, 13 and 15–20 built; no evaluation run has completed on them, so their effect on time and tokens is unmeasured; 9 awaits the owner; 10, 12 and 14 planned | The enhancement backlog from the 2026-10-06 review: cheap fixes, the learning loop through Skills, overlay Skills, provider neutrality. Steps 17–20 are the speed-ups from the 2026-10-07 run: a working copy for files and the graph, a provider schema lookup, routing a Check the code cannot meet, and a model timeout per role. |
| 5 | `iter-05-jev-decisions/` | the Jev client and the Orchestrator router are built (steps 2, 11, 12), unverified against the live service; the rest planned | Jev (a hosted decision model) for the agent's closed decisions: checks, routing, context selection. |
| 6 | `iter-06-target-architecture-graph/` | steps 1–10 built; step 11's evaluation run is outstanding, so unproven with real models | The Target architecture as one explicit graph of Elements, Relationships and Checks, established before infrastructure code, with validation as a verdict per Check. |
| 7 | `iter-07-change-requests/` | planned; ADR-0006 accepted 2026-10-07; follows iteration 6; its step 8 (removing `deliverables/cases/legacy-baseline/`) was done early on the owner's instruction | A user restates a request to say how requirements changed; a new Execution starts from a Baseline Execution of the same Customer case and delivers the updated architecture with what changed. |
Numbers record when an iteration was planned, not the order to build in. Build iteration 6 before the remaining steps of iteration 4 (10 to 14) and before iteration 5: it changes the Deliverables, Phases and validation format they build on. Its `MAP.md` lists the effect on each of their steps.
Two designs sit between iterations 1 and 2 and have no plan directory. Commit `a24a44e` wrapped the pipeline in a compatibility layer that imitated Google ADK without using it (deleted in iteration 3). `.scratch/phase-pipeline/spec.md` then designed a code-sequenced Phase pipeline; ADR-0002 reopened it before any of it was built, and its decision log (D1 to D46) explains how iteration 2's design was reached.

View File

@@ -22,7 +22,7 @@
| 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 |
| 8 | Evaluation | complete | `7ee49ab` |
| 9 | Cleanup | done in iteration 3 | none |
## Dependency graph

View File

@@ -2,7 +2,7 @@
**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)
**Branch:** `feat/solution-architect-agent` (committed in `7ee49ab`, 2026-10-06)
**This directory covers:** steps 1 to 7
## Sources of truth

View File

@@ -121,3 +121,51 @@ Every step ends with the full suite passing. Steps that change agent behaviour (
- **Where:** `providers/gcp.yaml`, `app/providers.py`, `app/workflows/deliverables.py`, `app/presentation.py`, `agents/iac-author.md`, `agents/validator.md`, `agents/design-advisor.md`.
- **Timing:** Build when a second Cloud provider is planned. ADR-0002 says no provider interface exists in code until then.
- **Acceptance criteria:** Pillar headings come from `pillar_skills`, guide sections from the bundle's `output_template`, and the IaC tool with its file contract from the bundle. `grep -rni "terraform" app/workflows app/nodes app/states` is empty, and no pillar or guide-section name appears as a literal in `app/workflows/deliverables.py`.
## Step 15: Group Executions by Customer case
- **Report ref:** none; requested by the owner on 2026-10-06
- **Capability:** Everything under `deliverables/` is grouped by Customer case, so a case ties each request to the artefacts generated for it.
- **Rationale:** Outputs were keyed only by Execution id. Nothing on disk said which customer workload an Execution belonged to or what it had been asked.
- **Where:** `app/states/execution_state.py` (the case id rule and the paths), `ExecutionEngine.start` in `app/agent.py`, `_write_outputs` in `app/nodes/execution_nodes.py`, `app/main.py`, `app/a2a_server.py`, `eval/solution_eval.py`, `CONTEXT.md`.
- **Acceptance criteria:** Every Execution's files are under `deliverables/cases/<customer_case>/executions/<execution_id>/`. Each has a manifest naming the case, the request and every file. Each case has an index of its Executions and their requests. A case id that is not a safe slug is refused before anything runs. A Customer case never feeds one Execution into another.
## Step 16: Cache Terraform providers between checks
- **Report ref:** none; requested by the owner on 2026-10-07 to shorten a run
- **Capability:** A provider is downloaded once and reused by every later `terraform validate` and `plan`.
- **Rationale:** Each check runs `terraform init` in a new scratch directory, so every call downloaded its providers again. The setting `TF_PLUGIN_CACHE_DIR` existed and was unset by default.
- **Where:** `TerraformRunner` in `app/tools/local.py`, `app/config.py`, `.env.example`.
- **Acceptance criteria:** The cache is on by default and can be disabled. A second check of the same configuration does not download the provider. Concurrent checks cannot corrupt the cache.
## Step 17: A working copy for files and for the graph
- **Report ref:** none; requested by the owner on 2026-10-07 to shorten a run
- **Capability:** A Specialist writes a file or a graph once and afterwards changes only what needs changing. A Revision starts from the last attempt.
- **Rationale:** In the 2026-10-07 run the IaC author made 57 model requests and used 2.35 million tokens: every `terraform_fmt` and `terraform_validate` call carried every file, `terraform_fmt` returned them all again, and each fix rewrote whole files. The target architect returned the whole graph and the same content again as tables in one reply, and timed out at 180 seconds in both attempts.
- **Where:** `app/tools/workspace.py` (new), `specialist_tools` in `app/tools/execution.py`, `app/tools/local.py`, `app/tools/toolkit.py`, `DeliverableSpec.working_copy` in `app/workflows/deliverables.py`, `render_tables` in `app/workflows/target_architecture.py`, `agents/target-architect.md`, `agents/iac-author.md`, `agents/validator.md`, `skills/iac-validation/SKILL.md`.
- **Acceptance criteria:** The Terraform tools take no files when the Deliverable has a working copy, and formatting returns file names only. The working copy is attached on submission. The validator's tools hold the submitted code without it being sent. The target architect can build the graph over several calls, and the tables and the diagram are written by code from the graph. On the next evaluation the IaC author's and the target architect's requests and tokens fall against the 2026-10-07 run.
## Step 18: Provider schema lookup and one pinned provider version
- **Report ref:** none; requested by the owner on 2026-10-07
- **Capability:** An agent can ask what a resource type accepts, and get the provider's own answer.
- **Rationale:** All 13 Terraform refusals in the 2026-10-07 run were one mistake: `startup_cpu_boost` and `cpu_idle` in the wrong block, and on a Cloud Run job, which has neither. The agent moved the argument around by trial. The run also left five versions of the Google provider in the plugin cache, because nothing pinned one.
- **Where:** `TerraformRunner.schema` in `app/tools/local.py`, `terraform.required_providers` in `providers/gcp.yaml`, `app/providers.py`, the role files of the target architect, the IaC author and the validator.
- **Acceptance criteria:** `terraform_schema` lists a resource type's arguments and blocks, gives one block in full, and says where a named setting sits or that the resource type has none. The schema is read once per process. The bundle pins one exact provider version, and the lookup refuses to guess without one.
## Step 19: A Check the code cannot meet goes back to the Target architecture
- **Report ref:** none; requested by the owner on 2026-10-07
- **Capability:** A Check that names a setting its resource lacks is fixed where it was written, before any validation is spent on it.
- **Rationale:** Check K-30 of the 2026-10-07 run asked for `startup_cpu_boost` on a Cloud Run job. The IaC author could not implement it and had no way to say so; the validator failed it; the code was reopened until the Revision limit ended the run with warnings.
- **Where:** `check_implementation` and `unimplementable_checks` in `app/workflows/chain.py`, the playbook in `app/nodes/router.py`, `_orchestrator_context` in `app/nodes/execution_nodes.py`, `agents/orchestrator.md`, `agents/iac-author.md`, `agents/validator.md`, `skills/requirements-chain/SKILL.md`.
- **Acceptance criteria:** `implementation.json` may record a Check as unimplementable with a reason, and that accounts for the Check. The router then reopens the Target architecture with the reason, before validation is delegated. The validator gives a Check on a setting the schema lacks the verdict not verifiable, not fail.
## Step 20: A model timeout per role
- **Report ref:** none; requested by the owner on 2026-10-07
- **Capability:** A role whose replies are long is given longer for one model request than the rest.
- **Rationale:** One `MODEL_TIMEOUT_SECONDS` (180) applied to every role. Raising it for all of them makes every stuck request slower to recover.
- **Where:** `models.timeout_seconds` in `providers/gcp.yaml`, `ModelConfig` in `app/providers.py`, `RoleSpec.model_timeout_seconds`, `AdkAgentRuntime._content_config`.
- **Acceptance criteria:** A role named in the bundle gets its own timeout; every other role gets the default.

View File

@@ -2,8 +2,9 @@
**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
**Status:** steps 1 to 8, 11, 13 and 15 to 20 built; no evaluation run has completed on any of them (see `steps/step-8.md`), so every "tokens fall" or "Revisions fall" criterion is unmeasured; step 9 drafted and awaiting the owner; steps 10, 12 and 14 planned. Steps 1 to 6 are in commit `7ee49ab`; the rest are uncommitted.
**Changed by iteration 6:** `docs/adr/0005-the-target-architecture-is-an-explicit-graph.md` (accepted 2026-10-07) replaces the free-form `findings.json` of step 1 with a verdict per Check, remove the diagrammer, and add a Phase. Its plan is `../iter-06-target-architecture-graph/`, which lists the effect on each step here and should be built before steps 10 to 14.
**This directory covers:** steps 1 to 20
## Sources of truth
@@ -16,20 +17,26 @@
| 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 |
| 1 | Structured validator findings | A | S | replaced by iteration 6 step 9 (verdicts per Check) |
| 2 | Carry the draft through `needs_input` | A | S | complete |
| 3 | Reuse pillar advice across Revisions | A | S | built; evaluation run outstanding |
| 4 | Single source for Deliverable contracts | A | S | complete |
| 5 | Cap parallel Specialists | A | S | complete |
| 6 | Orchestrator step order | A | S | built; seen working in one stopped run, no completed evaluation |
| 7 | Capture lesson candidates | B | M | complete |
| 8 | Evaluation that can see improvement | B | M | built; thresholds and a judged run outstanding |
| 9 | ADR: the lessons loop and overlay Skills | B | S | drafted as `docs/adr/0004-lessons-and-overlays-arrive-as-skills.md`, status proposed; awaits the owner |
| 10 | Lessons Skill and lesson curator | B | L | planned |
| 11 | IaC patterns Skill | B | M | planned |
| 11 | IaC patterns Skill | B | M | built; every pattern validates; effect on Revisions and tokens unmeasured |
| 12 | Overlay Skills and an organisation standards Skill | C | M | planned |
| 13 | Trim Specialist context | C | M | planned |
| 13 | Trim Specialist context | C | M | built; effect on tokens unmeasured |
| 14 | Provider-owned contracts | C | M | planned |
| 15 | Group Executions by Customer case | added | S | complete |
| 16 | Cache Terraform providers between checks | added | S | complete |
| 17 | A working copy for files and for the graph | added | M | built; effect on time and tokens unmeasured |
| 18 | Provider schema lookup and one pinned provider version | added | S | built; checked against the real provider |
| 19 | A Check the code cannot meet goes back to the Target architecture | added | S | built |
| 20 | A model timeout per role | added | S | built |
Size: S under a day, M a few days, L a week or more. Group A is cheap fixes that also create signal. Group B is the learning loop. Group C is adaptability.
@@ -44,5 +51,9 @@ Size: S under a day, M a few days, L a week or more. Group A is cheap fixes that
- Step 12: depends on step 9
- Step 13: depends on step 8
- Step 14: depends on step 4
- Step 15: no dependencies (added on 2026-10-06 at the owner's request)
- Step 16: no dependencies (added on 2026-10-07 at the owner's request)
- Steps 17 to 20: no dependencies (added on 2026-10-07 at the owner's request, from the causes of the 60 minute run recorded in `../iter-06-target-architecture-graph/steps/`)
- Step 11 uses step 18's pinned provider version; step 19 uses step 18's lookup to find the Checks it reports
Step 8 comes before steps 10, 11 and 13 so each of them can be shown to help: same quality, fewer Revisions, seconds or tokens.

View File

@@ -0,0 +1,12 @@
# Step 1 — Implementation Detail
1. `validation_results` now requires a `findings.json` attachment (`FINDINGS_ATTACHMENT` in `app/workflows/deliverables.py`).
2. `check_findings` validates it at submission: a JSON list of objects with `deliverable` (a Deliverable kind), `severity` (`critical`, `high`, `medium`, `low`), `evidence` and `rule`. `[]` is valid and means a pass. Each problem is refused by field, for example `findings.json[1].severity: must be one of ...`.
3. `agents/validator.md` tells the validator to attach it; the format and an example live in `skills/iac-validation/SKILL.md` under "Reporting findings".
4. The file is written with the other attachments to `deliverables/executions/<id>/findings.json`.
The check was added to `check_submission`, not to `app/tools/execution.py` as planned, so every contract rule stays in one function.
Tests: `tests/execution/test_deliverables.py` (missing attachment, empty list, well-formed finding, malformed JSON, per-field problems).
Not verified: no real-model run has confirmed the validator produces a well-formed file on its first submission. A malformed one costs a retry inside the validator's run, not a Revision.

View File

@@ -0,0 +1,13 @@
# Step 11 — Implementation Detail
Built on 2026-10-07 as `skills/google-cloud-iac-patterns/`. The name carries the Cloud provider because the content does; the provider bundle assigns it to the IaC author (`role_skills.iac-author`), so another provider brings its own patterns Skill with no code change.
1. `SKILL.md` says how to use the patterns and lists one reference per product. `assets/versions.tf` pins `hashicorp/google` 8.6.0, the version `providers/gcp.yaml` pins (step 18).
2. Thirteen references, each a short list of what goes wrong and one self-contained pattern: enabling APIs, IAM, Cloud Run service, Cloud Run job, Pub/Sub, Cloud Storage, Secret Manager, Cloud KMS, Cloud SQL, VPC networking, Cloud Scheduler, Artifact Registry, Monitoring and Logging.
3. Seeded from the 2026-10-07 run's lesson candidates. All 13 Terraform refusals were `startup_cpu_boost` or `cpu_idle` in the wrong block or on a Cloud Run job. The service reference says which block each setting sits in; the job reference lists what a job does not have.
Differs from the plan: the plan's acceptance is a fall in IaC author Revisions or tokens on the three cases. **No evaluation has run, so that is unmeasured.** What is verified is that the patterns are correct.
Tests: `tests/test_iac_patterns.py` runs `terraform validate` on every reference's pattern with the Skill's own versions file (13 pass against the real provider from the plugin cache; skipped when the provider cannot be installed), checks every reference is listed in `SKILL.md`, and checks the Skill and the bundle pin the same version.
Not done: load balancing, Firestore, BigQuery, Eventarc and GKE have no reference. A product with none is written from `terraform_schema` and the documentation.

View File

@@ -0,0 +1,14 @@
# Step 13 — Implementation Detail
Built on 2026-10-07.
1. `DeliverableSpec.reads_in_full` names the earlier Deliverables a Specialist reads whole. Left unset it is the Deliverables it depends on.
2. `dependencies_for(kind, deliverables)` gives every other input as its data file alone: `requirements.json`, `components.json` and so on. Those ids are all the Requirements chain checks need, so submission checks are unchanged.
3. Two overrides. The IaC author reads nothing whole: the code is written from `target-architecture.json`. The packager reads everything whole, since the guide is assembled from every Deliverable's prose.
4. A Deliverable given as data can be read whole with `read_deliverable(kind)`, offered only when something was trimmed.
Differs from the plan: the plan said "summaries". The data file is used instead. It already exists, is exact, and costs no model call to produce.
**Unmeasured:** the plan's acceptance is that describer tokens fall against the step 8 baseline. No evaluation has run.
Tests: `tests/execution/test_working_copy.py`, "each Specialist reads what it works from".

View File

@@ -0,0 +1,19 @@
# Step 15 — Implementation Detail
1. **Customer case** is a glossary term (`CONTEXT.md`): a caller-supplied slug grouping the Executions for one customer workload. An Execution started without one belongs to `unassigned`, so every Execution sits under a case.
2. **Layout.** `deliverables/cases/<customer_case>/executions/<execution_id>/` holds an Execution's files. `execution_dir`, `case_dir` and `lessons_file` in `app/states/execution_state.py` are the only places these paths are built.
3. **`execution.json`** in each Execution folder names the case, the Execution, the Session, the Workflow request, and for each Deliverable its document and attachments.
4. **`intent/`** in each case folder records the customer's Intent and its history (`app/customer_case.py`). Each Workflow request is written as given to `intent/001.md`, `002.md` and so on when its Execution starts. `intent/history.json` lists every statement in order with the Execution it started, that Execution's status (`in_progress`, `completed`, `completed_with_warnings`) and the path to its files. This replaced the `case.json` index first built for this step; `execution.json` carries `intent_version`.
5. **Lesson candidates** are grouped the same way: `lessons/candidates/<customer_case>/<execution_id>.json`, and the record carries `customer_case`.
6. **Callers.** `ExecutionEngine.start(customer_case=...)`; `/generate` takes `customer_case` in its body and answers 400 for an unsafe one; A2A reads `customer_case` from the message metadata. The evaluation uses each benchmark case's id.
7. **The case id** must be 1 to 64 lowercase letters, digits or hyphens, starting and ending with a letter or digit. It becomes a directory name, so anything else is refused before the Execution starts.
8. **Existing content moved.** `deliverables/as-is`, `target`, `validation`, `guides` and the 68 old `executions` folders are now under `deliverables/cases/legacy-baseline/`, with an `intent/` folder built from the request recorded in each old run's `requirements.md`, ordered by file time. `scripts/validate_artifacts.py` and `tests/test_artifacts.py` look there.
Limits:
- An Execution that ends with warnings writes no Deliverable files (an existing rule). Its request is still in the Intent history, with its status and no path, and its lesson candidates are grouped under its case.
- The 68 old runs were asked 12 different things but share one case, `legacy-baseline`. They can be split into a case per request from `intent/history.json` if that matters.
- `/generate`'s response keys are unchanged, so it does not return the case; `execution.json` does.
- The database rows carry the case only inside the status details, not as a column.
Tests: `tests/execution/test_engine.py` (grouping, manifest, index, `unassigned`, refused ids), `tests/a2a/test_server.py` (`/generate`), `tests/execution/test_lessons.py`.

View File

@@ -0,0 +1,20 @@
# Step 16 — Implementation Detail
1. `TF_PLUGIN_CACHE_DIR` defaults to `.cache/terraform-plugins` under the repository root (already gitignored and kept out of the image build context). Set it empty to disable. `Settings.terraform_plugin_cache()` resolves it to an absolute path, since checks run in scratch directories.
2. `TerraformRunner` creates the directory on first use and passes it to Terraform.
3. It also sets `TF_PLUGIN_CACHE_MAY_BREAK_DEPENDENCY_LOCK_FILE=true`. A scratch directory has no dependency lock file, and without this Terraform downloads a cached provider again to verify it, which defeats the cache.
4. `terraform init` calls are serialised by a lock when the cache is in use, because Terraform's plugin cache is not safe for concurrent installs.
Measured on 2026-10-07 with a one-resource configuration on the Google provider (`~> 6.0`), on this machine:
| | Seconds per `terraform validate` |
|---|---|
| No cache | 7.3 to 7.8 |
| Cache, first use (downloads once) | 7.3 |
| Cache, later uses | 1.6 to 2.0 |
So each check after the first saves about 5.5 seconds. The stopped run of 2026-10-06 made 7 validate calls in 16 minutes and more through its Revisions; at 12 to 15 calls a case, with the scoring's own check, that is roughly 1 to 1.5 minutes a case. The saving is real but small against a 35 minute run; it grows on a slower network.
Costs: the cache holds each provider version once (117 MB for one Google provider version; the existing folder holds 600 MB across versions). In the container it is created under `/app/.cache` at run time and is lost with the container; pre-loading it into the image, or mounting a volume, would carry the saving across restarts and is not done.
Tests: `tests/tools/test_local.py`, "the provider cache", using a stand-in terraform binary.

View File

@@ -0,0 +1,21 @@
# Step 17 — Implementation Detail
Built on 2026-10-07. `app/tools/workspace.py` keeps a working copy in the Deliverable's working memory, which the Execution already checkpoints and returns on every attempt.
Files (`working["files"]`), for the Deliverable whose `working_copy` is its own kind (deployment guidance):
1. `write_file`, `edit_file` (replaces the one place `old` matches, and refuses when it matches none or several), `read_file` (one file, or the list) and `delete_file`.
2. `terraform_fmt`, `terraform_validate` and `terraform_plan` run on the Terraform files in the working copy and take no `files` argument. `terraform_fmt` formats in place and returns the names it changed. Files passed anyway are written to the working copy first, so a model that ignores the instruction still works.
3. `submit_deliverable` attaches the working copy; a file passed as an attachment replaces its copy. The submitted files become the working copy, so a Revision starts from them, and the task context lists them under `working_copy`.
The validator's `working_copy` is deployment guidance: its tools are given a fresh copy of the submitted files on every attempt, it has no write tools, and nothing from the copy is attached to its Deliverable.
Graph (`working["graph"]`), for the Target architecture:
4. `graph_put` adds items or replaces those with the same id, `graph_remove` removes by id, `graph_read` returns the graph. The submitted graph becomes the working graph.
5. `submit_deliverable` attaches the working graph when no `target-architecture.json` is passed.
6. `render_tables` writes the Elements, Relationships, Checks and not-applicable tables from the graph, and the engine appends them to the content on submission. The contract's sections are now `Design rationale` alone. This closes the duplicate output iteration 6 left: the architect no longer writes the graph twice.
**Unmeasured:** no evaluation has run, so the fall in requests, tokens and time is expected, not shown. The mechanism is what is tested.
Tests: `tests/execution/test_working_copy.py` (21), including an Execution in which the validator validates the submitted code with no files passed.

View File

@@ -0,0 +1,17 @@
# Step 18 — Implementation Detail
Built on 2026-10-07.
1. `providers/gcp.yaml` pins `terraform.required_providers.google` to `hashicorp/google` 8.6.0. `load_provider` requires a `source` and an exact `version`.
2. `TerraformRunner.schema(resource_type, block, find)` writes a versions file for the pinned providers in a scratch directory, runs `terraform init -backend=false` and `terraform providers schema -json` once per process, and keeps the resource schemas in memory. Measured here: 0.6 seconds and a 9.7 MB reply for the Google provider, from the plugin cache.
3. With `resource_type` alone it lists the arguments code may set (read-only ones are left out) and outlines every block. With `block` it gives one block's arguments with descriptions. With `find` it says where a setting sits, or that the resource type has none. An unknown resource type gets close matches.
4. The tool is `terraform_schema`, tier general, given to the target architect, the IaC author and the validator.
Checked against the real provider on 2026-10-07:
- `find="startup_cpu_boost"` on `google_cloud_run_v2_job`: "has no argument or block named like 'startup_cpu_boost'. It cannot be set on this resource type."
- the same on `google_cloud_run_v2_service`: `template.containers.resources.startup_cpu_boost (bool, optional)`.
Not done: generated code is not forced onto the pinned version. An agent that writes its own `required_providers` with another version is validated against that version. The patterns Skill gives it the pinned `versions.tf` to use.
Tests: `tests/tools/test_local.py`, "schema lookup", on a stand-in schema; `tests/test_providers.py` for the pin.

View File

@@ -0,0 +1,12 @@
# Step 19 — Implementation Detail
Built on 2026-10-07.
1. An `implementation.json` entry may be `{"check": "K-7", "unimplementable": "<what the resource type lacks>"}` in place of `file` and `address`. It accounts for the Check; an empty reason does not.
2. `unimplementable_checks` reads those entries. The router reads them as soon as deployment guidance is submitted, and a new playbook group, "the code cannot meet a Check", sits before "validation decided" and "a Phase is complete". Its action reopens the Target architecture with each Check's id and reason. That returns the code to draft, so the group stops applying.
3. A model Orchestrator is given the same list as `unimplementable_checks` in its context, and `agents/orchestrator.md` has the step.
4. The validator is told to confirm with `terraform_schema` before failing a Check for a missing setting, and to give not verifiable when the resource type has no such setting. Not verifiable already routes to the Target architecture.
Past the Revision limit the reopen is refused as any other is: the user decides, or a pre-approved Execution ends with warnings.
Tests: `tests/execution/test_requirements_chain.py` (two) and `tests/execution/test_router.py`, "a Check the code cannot meet goes back to the graph unvalidated".

View File

@@ -0,0 +1,10 @@
# Step 2 — Implementation Detail
1. `needs_input` accepts an optional `draft` and `attachments`; `NeedsInput` carries them (`app/adk/runtime.py`).
2. The Execution state holds `drafts` by Deliverable kind. `orchestrator_turn` stores a draft when it applies a `needs_input` outcome and drops it when that Deliverable is submitted.
3. A Specialist's context carries `draft` (`{content, attachments}` or `null`).
4. `agents/partials/specialist-protocol.md` tells Specialists to pass the complete draft with their confirmation question, to submit it unchanged once the latest answer approves it, and to apply requested changes to it.
Test: `test_a_draft_sent_with_questions_comes_back_with_the_answer` in `tests/execution/test_engine.py` shows the second run receiving the draft and the submitted content equalling it.
The draft is not shown to the user by the engine; the Specialist's question still carries its summary. Whether the full draft should appear in the prompt is an open product question.

View File

@@ -0,0 +1,7 @@
# Step 20 — Implementation Detail
Built on 2026-10-07. `models.timeout_seconds` in the provider bundle maps a role to the seconds one model request may take; `RoleSpec.model_timeout_seconds` carries it and `AdkAgentRuntime` uses it in place of `MODEL_TIMEOUT_SECONDS`.
`providers/gcp.yaml` sets the target architect to 420 and the IaC author and the packager to 300. These are starting values, not measurements. With step 17 the architect's replies are short, so its 420 should rarely be reached.
Tests: `tests/agents/test_adk_runtime.py`, `tests/agents/test_roles.py`, `tests/test_providers.py`.

View File

@@ -0,0 +1,12 @@
# Step 3 — Implementation Detail
1. **Working memory.** Each Deliverable has a JSON-compatible working memory kept in Execution state (`working`, merged by key so parallel Specialists each write their own). `ToolFactory` now takes it as a third argument, so tools can remember across attempts.
2. **Pillar advice is remembered** under `pillar_advice` in the design recommendations' working memory (`app/tools/pillars.py`).
3. **Semantics of `consult_pillar_advisors`:** omit `pillars` to consult every pillar afresh; name `pillars` to re-consult only those, with the remembered advice returned for the rest under a heading marked "(from your earlier consultation)". Failed advice is never remembered.
4. `agents/design-advisor.md` tells the design advisor to name only the pillars its feedback touches when revising.
Changed from the plan: the criterion "a changed brief for a pillar invalidates that pillar's stored advice" was not built. The brief is one text for all pillars and a model rewords it on every attempt, so hashing it would discard everything each time. Omitting `pillars` is the way to refresh all advice.
Tests: `tests/execution/test_pillars.py` (subset re-consult, full refresh, failed advice not stored, and one through the engine showing advice surviving a Revision).
Not verified: the evaluation run this step calls for. The saving depends on the design advisor following the new instruction; in case 01 it would cut up to 12 of 18 advisor runs.

View File

@@ -0,0 +1,15 @@
# Step 4 — Implementation Detail
1. `DeliverableSpec.contract()` returns the sections, attachments and table columns as data; every Specialist's context now carries it as `contract`.
2. Role files no longer list required headings. What remains in them is guidance the contract cannot express (what goes under a heading, verdicts, optional headings).
3. New contracts:
- `technical_decomposition`: a `Components` section and one table whose header names `component` and `requirement`.
- `architecture_description`: `Components` and `Flow` sections. Headings match by suffix, so "Data flow" and "Architecture components" satisfy them.
- Every required attachment must have content, which gives the diagram's `architecture.mmd` a minimum bar.
4. Tests share one contract-complete fixture, `sample_submission` in `app/adk/fake_runtime.py`.
Two existing tests used an empty `terraform/variables.tf` as a fixture; they now use a non-empty one.
Tests: `tests/execution/test_deliverables.py`, and `test_specialist_context_carries_its_contract` in `tests/execution/test_engine.py`.
Not verified with real models: the two new section contracts change what the decomposer and describer must write.

View File

@@ -0,0 +1,11 @@
# Step 5 — Implementation Detail
1. `RunLimiter` in `app/adk/runtime.py` caps agent runs in flight. `slot()` holds one; `lend()` gives the caller's slot up while its own fan-out runs.
2. `specialist_task` takes a slot for each Specialist run. The pillar tool lends the design advisor's slot and takes one per advisor, so the fan-out shares the cap and a cap of 1 cannot deadlock.
3. Setting `MAX_PARALLEL_SPECIALISTS` (default 4, as the spec's Risks section asked). `open_assembly` builds one limiter and gives it to both the engine and the tool factory.
Changed from the plan: the cap is per engine process, not per Execution. Model rate limits apply to the project, so one cap across concurrent Executions is the stricter and more useful bound.
An `ExecutionEngine` built without a limiter is uncapped, which keeps direct construction in tests unchanged.
Tests: cap of 1 gives a peak of 1 and no cap gives a peak of 2 (`tests/execution/test_engine.py`); the fan-out under a held slot with a cap of 1 completes with a peak of 1 (`tests/execution/test_pillars.py`).

View File

@@ -0,0 +1,6 @@
# Step 6 — Implementation Detail
1. `agents/orchestrator.md`: "Validation found problems" is now step 3, above "A Phase is complete" (step 4) and "Work is ready" (step 5).
2. The step now says when it applies (validation results submitted and not yet approved), to read them first, and to send failed work back before asking the user to approve it.
Not verified: the acceptance criterion needs a real-model evaluation run with a failing validation, showing a reopen before any Approval request for the validation Phase. No such run was made. The deterministic suite cannot test this, because the order is the model's choice.

View File

@@ -0,0 +1,18 @@
# Step 7 — Implementation Detail
1. `app/states/lessons.py`: `collect_lesson_candidates` builds one record when an Execution ends, from what the Execution already holds. Candidate types:
- `revision`: each reopen, with its reason and who asked.
- `revision_limit`: a reopen refused at the cap.
- `change_request`: the user's feedback on a Phase, with the Deliverables in it.
- `finding`: each entry of every submitted `findings.json`, with the attempt it came from.
- `refusal`: each tool reply that did nothing (`REJECTION_PREFIXES`, now in `app/adk/runtime.py`), with role, tool and Deliverable.
- `unfinished`: a Specialist that stopped or spent its budget.
2. Refusals are captured in the nodes, not the runtime: `_noting_refusals` wraps each tool, so any runtime, the fake included, produces them. Specialist refusals travel in the outcome record; the Orchestrator's are kept in state under `refusals`.
3. The record names the Execution, its status, each role's Skills and a version per Skill. `skill_version` in `app/skills/agent_skills.py` is a 12-character content hash of the Skill's files.
4. It is written twice: through `ExecutionRecorder.record_lesson_candidates` (the database recorder stores it as an artifact of type `lesson_candidates`), and to `lessons/candidates/<execution_id>.json` under the output root. That directory is gitignored.
Changed from the plan: the file is not inside `deliverables/executions/<id>/`. An Execution that ends with warnings must write no Deliverable files (an existing rule with a test), and those Executions are the ones most worth learning from.
On "no secrets and no discovered cloud data": a refusal from a `cloud_read` tool keeps only the words before its first colon, and every message is cut at 500 characters. Revision reasons, user feedback and finding evidence are kept whole, so a record can quote the user and name resources in generated Terraform. Treat the files as client data.
Tests: `tests/execution/test_lessons.py`.

View File

@@ -0,0 +1,36 @@
# Step 8 — Implementation Detail
Built, with two acceptance criteria still open (listed at the end).
1. **Structural checks added to every case** (`eval/scoring.py`):
- `components_trace_to_requirements`: every row of the decomposition's component table names a requirement.
- `no_blocking_findings`: the final `findings.json` holds no `critical` or `high` finding.
2. **Judged checks**, run with `--judge`:
- `pillar_checklists_covered`: each item of each pillar Skill's "Validation checklist" is put to the judge as a yes-or-no question against the design recommendations. The weakest pillar must reach 70%.
- `recommendations_quality`: four graded questions (specific, actionable, trade-offs, traceable); the mean must reach 0.67.
- `checklist_items` reads the checklists from the vendored Skills, nested bullets included, so a vendor sync updates the questions.
3. **Judge seam** (`eval/judge.py`): a `Judge` takes one document and a map of typed questions and returns a score from 0 to 1 each. `GeminiJudge` uses the bundle's default model, or `EVAL_JUDGE_MODEL`. The shape matches a decision model's, for iteration 5 step 10. One live call confirmed it works.
4. **Interactive case.** A case marked `"interactive": true` runs with a scripted user: `run_with_scripted_user` grants Approvals, denies cloud reads and answers questions by pattern. It adds the check `specialists_ask_before_submitting`. `case-04-interactive-web-app` is case 03 run this way.
5. **Thresholds.** A case may set `thresholds` for `revisions`, `seconds` and `tokens`. Exceeding one is printed as `REGRESSION`, listed in the report, and makes the exit code non-zero. It does not change the score.
`automatic_reply` in `app/nodes/execution_nodes.py` lost its leading underscore so the evaluation can reuse it.
Tests: `tests/eval/test_scoring.py`, with a fake judge.
Open:
- **Thresholds are not set.** They need a baseline per case from a completed run of the current code. None exists: see below.
- **No judged or interactive run yet.**
- **Judge stability** across repeated runs on the same output is unmeasured (iteration 5 step 10 names it).
## The evaluation run of 2026-10-06 (stopped, no score)
A three-case run was started on the code as of steps 1 to 6 and stopped by the owner after 35 minutes, during case 01. Cases 02 and 03 never started. Nothing was scored and no files were written, so it gives no baseline. What its log showed:
- Seven Deliverables were submitted on their first attempt in about 15 minutes, including the decomposition and description under their new contracts (step 4).
- The Orchestrator reopened deployment guidance after each failed validation without first asking for Approval of the validation Phase, which is what step 6 intended. Observed three times in one case.
- No Revision of the design recommendations occurred, so step 3 was not exercised.
- Validation did not converge: three passes gave 4, then 7, then 5 different findings, and deployment guidance used all three Revisions. The four findings of the first pass were all still present after the first Revision.
- The Orchestrator stopped without calling a tool four times and was nudged; one such turn took 234 seconds.
The non-convergence led to ADR-0005 (proposed): establish the Target architecture as an explicit graph with numbered Checks before code is written.

View File

@@ -114,21 +114,37 @@ Rules for every step from 3 onward:
- **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
## Step 11: ADR: Jev is the Orchestrator's decision point
- **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.
- **Capability:** A recorded decision that Jev proposes the Orchestrator's next action, code checks and carries it out, and a generative model only writes replies.
- **Rationale:** The owner's direction on 2026-10-07: use Jev as the decision point, not a different model. It replaces part of ADR-0003, which made the Orchestrator an ADK agent and rejected an Orchestrator without a model.
- **Where:** `docs/adr/0007-jev-is-the-orchestrators-decision-point.md`, with four points to confirm; a note on ADR-0003.
- **Acceptance criteria:** ADR-0007 is `accepted`, or amended with step 12 updated to match.
## Step 12: Orchestrator routing
## Step 12: The Orchestrator decides with Jev, with no language model
- **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.
- **Report ref:** J1, widened by ADR-0007
- **Capability:** Each Orchestrator turn is decided by the Ledger's rules and, where there is a choice or the user has spoken, by Jev.
- **Rationale:** In the stopped run of 2026-10-06 the Orchestrator took about 7 of 35 minutes and stalled four times. In case 03 it made 36 requests on the larger model.
- **Design:**
1. A pure function lists the allowed next actions from the Ledger and the Execution's state.
2. One allowed action is taken without a decision.
3. Otherwise Jev is asked closed questions through the `Decider` from step 2: whether the user asked for a change and to which Deliverable; what follows a validation outcome; which allowed action is next.
4. Code carries the decision out through `OrchestratorToolbox`, so the Ledger's rules are unchanged.
5. Each decision is recorded in the Execution's state with its questions, answers and probabilities, and reused when a resumed Execution has unchanged input.
6. A generative model writes only what the user reads: an Approval summary, or a question of the Orchestrator's own, from the decision and the data. It runs after the decision and cannot change it. A Revision's reason is the user's words or the failed Checks.
7. A failed Jev call is recorded as a failure, distinct from an answer, and retried within a fixed budget before the fallback.
- **Pattern followed:** https://vercel.com/i/jev-agent-control. Its ownership split maps as: propose the next action, Jev; check permission, the Ledger; execute, the existing tools; update state, the Execution graph; explain the result, a generative model. Its specialist routing is not used, because the dependency graph fixes which Specialist produces each Deliverable.
- **Routing (owner's direction, 2026-10-07):** the Orchestrator acts as a router with Jev choosing the route. Four things are routed:
- a message that starts something: new Workflow request, Change request against a Baseline, question about delivered work, or out of scope (Choice);
- a message inside an Execution: an answer to a waiting question, a request to change a named Deliverable, or anything else (Choice, then a Choice over the Deliverables);
- a validation outcome: revise the code, revise the Target architecture, or proceed (Choice);
- in a Change request, which Deliverables the change reaches (a Boolean per Deliverable, with the Requirements chain as the deterministic check).
The route decides what is dispatched. Which Specialist produces a Deliverable stays fixed by the dependency graph, and every Deliverable is still produced in a new Execution. The first route needs an entry point that can start a Change request or answer from a case's files (`app/main.py`, `app/a2a_server.py`); the last depends on iteration 7.
- **Fallbacks:** Below the confidence threshold, an interactive Execution asks the user and a pre-approved one takes the safest allowed action with a warning. When Jev is unreachable, the fixed order of the seven steps is used and recorded.
- **Where:** `orchestrator_turn` in `app/nodes/execution_nodes.py`; `app/tools/execution.py`; `agents/orchestrator.md` becomes question wording and fixed text in a Skill or the bundle; `app/adk/roles.py` and `providers/gcp.yaml` no longer need an Orchestrator model.
- **What is sent to Jev:** state, not content: Deliverable names and statuses, Check ids and verdicts, the user's latest message.
- **Acceptance criteria:** The engine tests pass with a scripted `Decider` in place of the scripted Orchestrator model, covering every Ledger rule they cover today. No language model call chooses an action; the only Orchestrator model calls write user-facing text. A decision Jev proposes that the Ledger does not allow is refused and recorded. With no Jev key configured, an Execution still completes on the fixed order. On the evaluation cases, quality checks hold and Orchestrator seconds fall against the baseline.
## Step 13: Cloud-read call guard
@@ -149,3 +165,43 @@ Rules for every step from 3 onward:
- **Where:** `app/tools/mcp.py`, `await_user` in `app/nodes/execution_nodes.py`.
- **Depends on step 1:** MCP results hold discovered cloud state.
- **Acceptance criteria:** A test with a planted instruction in an MCP result shows it withheld and noted.
## Step 15: Changes of meaning in a Change request
- **Report ref:** none; from the "UI copy translation review" use case the owner named on 2026-10-07
- **Capability:** A Change request follows through only the things whose meaning changed.
- **Rationale:** A Specialist revising from a Baseline rewords text it was not asked to change. Comparing text exactly would treat every rewording as a change; ignoring text would miss a dropped restriction, such as "only" removed from a requirement.
- **Design:** For each requirement, Element and Check whose text differs from the Baseline's, one Boolean question with the old and new text and its id: "Does the new text change what must be true?" A yes marks it changed, so the Requirements chain is followed from it; a no carries the Baseline's verdict forward.
- **Fallback:** Treat it as changed.
- **Where:** the graph comparison from iteration 7 step 4 (`app/workflows/target_architecture.py`), the change summary from iteration 7 step 6.
- **Acceptance criteria:** A reworded but equivalent Check is not reported as changed; a Check that lost or gained a condition is. Every decision is recorded with its probability in `changes.json`.
## Step 16: Jev as the evaluation judge, calibrated
- **Capability:** The evaluation's judged checks are answered by Jev, and the judge is shown to agree with a person.
- **Rationale:** LangChain's evaluation posts report Jev agreeing with a human reviewer on every pass-or-fail decision in a small experiment, with far lower variance than language-model judges, at $0.00035 a call. They also warn that low cost can amplify mistakes and that human review and judge alignment are still needed.
- **Built:** `DeciderJudge` in `eval/judge.py` asks every question in one call, with the document as the state and no grading instructions in it. `eval/solution_eval.py --judge` uses it when `TYPESAFE_API_KEY` is set, and the language-model judge otherwise or with `EVAL_JUDGE=gemini`. A judge that gives no answer leaves its check unanswered, not passed.
- **Open:** a small set of design recommendations labelled by a person against the pillar checklists and the quality rubric; agreement of each judge with those labels; variance over repeated runs on the same output. This replaces the stability criterion in step 10.
- **Acceptance criteria:** On the labelled set, the Jev judge's pass-or-fail agreement and its variance are recorded beside the language-model judge's, and the evaluation uses the one that agrees better.
## Step 17: Trace every decision
- **Capability:** For any Execution, a person can see each decision, what it was given and what came back.
- **Rationale:** LangChain's production post treats tracing as required for model-driven steps and describes LangSmith views for decision models. Here decisions are kept in the Execution's state and the evaluation report, and nothing is traced.
- **Owner's decision needed:** whether to send traces to LangSmith. Traces carry the Workflow request and Deliverable text, so the same retention question as Jev applies. `langsmith` is already installed as a dependency of LangChain; LangGraph traces when its environment variables are set.
- **Where:** environment settings for tracing; a traced span around `JevDecider.decide` in `app/tools/jev.py` carrying the questions, answers and probabilities; `docs/operations/`.
- **Acceptance criteria:** One Execution's trace shows every Orchestrator turn, each Jev call with its inputs and outputs, and each Specialist run. With tracing off, nothing leaves the process.
## Step 18: Readings as their own graph step
- **Capability:** A resumed Execution reuses the decisions it already made.
- **Rationale:** LangGraph saves state after each node. The router takes its readings and acts inside one node, so a failure in that node asks Jev again on retry. Jev is designed to return the same answer for the same input, and the client caches answers in memory, but neither survives a restart.
- **Where:** `app/workflows/execution_graph.py` and `app/nodes/`: a node that takes the readings and saves them, before the node that applies the playbook.
- **Acceptance criteria:** A test that fails the playbook node after the readings node shows the retry using the saved readings, with no second call to the decider.
## Step 19: Online evaluation of live Executions
- **Capability:** Every Execution is scored as it runs, not only benchmark cases.
- **Rationale:** At Jev's cost, LangChain recommends scoring every run and alerting on risk flags such as leaked personal data or injected instructions.
- **Where:** the judged checks from `eval/scoring.py`, run when an Execution ends and stored with its record; with step 17, as feedback on its trace.
- **Acceptance criteria:** A completed Execution carries its judged scores. A flagged risk is recorded and surfaced without stopping the Execution.

View File

@@ -2,8 +2,8 @@
**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
**Status:** steps 2, 11 and 12 built (2026-10-07); the rest planned. Step 1's answers are still open: the API key, rate limits and data retention. Build `../iter-06-target-architecture-graph/` first: it removes the need for step 5 here and changes what step 4 checks.
**This directory covers:** steps 1 to 19
## What Jev is
@@ -26,10 +26,47 @@ Jev will be deployed separately and reached with an API key (owner, 2026-10-06).
## Sources of truth
- https://www.langchain.com/blog/building-a-harness-with-jev and https://www.jevtypesafeai.com/use-cases (and `/docs` on that site).
- https://vercel.com/i/jev-agent-control: the agent-control pattern step 12 follows (decision model proposes, code checks and executes, a generative model explains).
- Review report, section "Where Jev fits": https://claude.ai/code/artifact/16b37169-1554-4eb7-bfcb-254315fa0518. `Report ref` names its J-number.
- `iter-04-learning-and-skills/`: several steps here build on steps there.
- `docs/adr/0003-langgraph-holds-state-adk-agents-reason.md`: step 12 changes what it says about the Orchestrator.
## The capabilities the owner wants from Jev
On 2026-10-07 the owner named the nine use cases at https://vercel.com/i/jev-use-cases as the capabilities to use. Each maps to this agent as follows.
| Jev use case | Question type | What it is here | Step |
|---|---|---|---|
| Form routing | Choice | Read the user's message: an answer, a request for changes, or a new statement of Intent, and which Deliverable a change affects | 12 |
| Tool-call review (`clear` or `caution`) | Choice | Review each cloud-read call and `terraform_plan` before it runs; `caution` pauses for the user | 13 |
| Response model selection | Choice | Pick the model tier for each delegation from the bundle's list | 6 |
| Response evaluation | Boolean, Score | Judge a Deliverable at submission (does it address its task; is each Check verifiable as written), and score the evaluation's rubric | 4, 10 |
| Content moderation | Boolean | Flag text that breaks a written policy: requirements that name products; request or tool text that tries to instruct the agent | 4, 14 |
| UI copy translation review (did an edit change the meaning?) | Boolean | In a Change request, flag a requirement, Element or Check whose meaning changed against the Baseline, so only real changes are followed through | 15 |
| Ticket prioritization | Score | Rate how much a proposed addition or a failed Check matters, to order Revisions and lesson candidates | 10 |
| Document categorization | Choice | Sort lesson candidates by Deliverable for the curator | 10 |
| CSV column mapping | Choice | Suggest which requirement or recommendation a proposed addition serves, for confirmation; code still checks the link exists | 10 |
The page's own cautions apply to every step: Jev does not write replies, so a generative model drafts messages; exact conditions (a Dependency is met, a file is attached, an id exists) stay deterministic checks in code; and a typed answer can still be wrong, so start where outcomes can be inspected and corrected, and record every decision.
## Alignment with LangChain's published guidance
Checked on 2026-10-07 against three LangChain posts: "Building prod with Jev and LangGraph", "Jev agent evals with LangSmith" and "Jev is now available in LangSmith evals". Steps 16 to 19 close the gaps found.
| Their guidance | Here | Step |
|---|---|---|
| Code owns the workflow; Jev makes narrow, typed decisions | The Ledger and the playbook are code; Jev supplies readings | 12 |
| Encode domain knowledge in the graph's topology, not in prompts | The dependency graph, Phases and playbook are data and code | 12 |
| Several atomic questions against one state, in one call | Readings are batched per turn | 2, 12 |
| Language models for open-ended work | Specialists write Deliverables; a model writes replies | 12 |
| Humans in the loop through interrupts | Approvals and every user question are interrupts | done |
| Checkpointing, so a failed run resumes with the decisions it made | The Execution is checkpointed; a decision is saved only when its turn ends | 18 |
| Low confidence falls back to a language model (their example: under 0.7) | Low confidence goes to the user, by the owner's choice in ADR-0007 | differs on purpose |
| Trace every decision, with its inputs and calibrated outputs | Decisions are kept in Execution state and the evaluation report; nothing is traced | 17 |
| Jev as the judge: typed questions, no grading instructions in the state | `DeciderJudge` in `eval/judge.py`, used when a key is set | 16 |
| Check a judge against human labels, and for repeatability | Not done; there is no labelled set | 16 |
| Score every live run and alert on risk flags | Evaluation is offline only | 19 |
## Boundaries
Jev answers closed questions. Writing Deliverables, grounding product choices and producing infrastructure code stay with the large models. Dependencies and Approvals stay rules in the Ledger.
@@ -39,7 +76,7 @@ Jev answers closed questions. Writing Deliverables, grounding product choices an
| 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 |
| 2 | Decider interface and Jev client with limits | none | built on the TypeSafe SDK; unverified against the live service |
| 3 | Pillars a Revision touches | J3 | planned |
| 4 | Semantic checks at submission | J4 | planned |
| 5 | Finding-to-Deliverable routing | J2 | planned |
@@ -48,10 +85,15 @@ Jev answers closed questions. Writing Deliverables, grounding product choices an
| 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 |
| 11 | ADR: Jev is the Orchestrator's decision point | none | complete: ADR-0007 accepted 2026-10-07 |
| 12 | The Orchestrator routes by readings and a playbook; a model only writes replies | J1 | built for messages inside an Execution and validation outcomes; unverified against live Jev and by evaluation |
| 13 | Cloud-read call guard | J7 | planned |
| 14 | Input guardrail | J11 | planned |
| 15 | Changes of meaning in a Change request | none | planned; needs iteration 7 |
| 16 | Jev as the evaluation judge, calibrated | none | judge built; calibration against human labels open |
| 17 | Trace every decision | none | open, owner's decision on LangSmith |
| 18 | Readings as their own graph step | none | planned |
| 19 | Online evaluation of live Executions | none | planned; needs step 17 |
## Dependency graph
@@ -65,9 +107,14 @@ Jev answers closed questions. Writing Deliverables, grounding product choices an
- 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 11: no dependencies
- Step 12: depends on step 2, step 11. Build it straight after step 2, ahead of steps 3 to 10.
- Step 13: depends on step 2
- Step 14: depends on step 2
- Step 15: depends on step 2, iteration 7 step 4
- Step 16: depends on step 2
- Step 17: no dependencies
- Step 18: depends on step 12
- Step 19: depends on step 16, step 17
Steps 3 and 4 come first: they are small, need no ADR change, and target Revisions, where the tokens are. The Orchestrator is 11% of case 03's tokens; the IaC author and validator together used 1.43 million over 7 runs.

View File

@@ -0,0 +1,9 @@
# Step 11 — Implementation Detail
ADR-0007 was accepted by the owner on 2026-10-07 ("this is exactly what I want, I approve ADR-0007"), after three refinements made the same day and recorded in it:
1. Jev is the decision point, in place of a different language model.
2. The agent-control pattern at https://vercel.com/i/jev-agent-control is followed: a decision model reads, application code checks permission and executes, a generative model writes replies.
3. The Orchestrator is a router, and decides by readings, a disposition and a playbook, on the model of a triage pipeline the owner supplied: the first group that applies, the strongest action whose conditions hold, escalate when none applies.
Jev is reached through TypeSafe AI's Python SDK and API endpoint (owner, 2026-10-07). The API key is still to be supplied.

View File

@@ -0,0 +1,36 @@
# Step 12 — Implementation Detail
Built against a scripted decider. No call has been made to the live Jev service, and no evaluation has run on it: the owner holds evaluation runs until the Jev work is in.
1. **`app/nodes/router.py`.** `Router` decides an Orchestrator turn in three stages: readings (`_read_ledger` from the Ledger and data; `_read_message` and `_read_gap` from the decider), a disposition by `Thresholds` (act at 0.75, close at 0.15, choice confidence 0.6), and the playbook in `_choose`: ordered groups, the strongest action whose conditions hold, escalate when none applies.
2. **Permission stays with the tools.** The router calls the same `OrchestratorToolbox` tools the model did. A refused action is skipped for the rest of the turn and the next one that holds is taken. Past the Revision limit the user is asked.
3. **What Jev is asked** (`Question` objects, batched when they rest on the same evidence):
- of the user's message: `asks_change` (noul), `change_target` (choice over submitted Deliverables), `change_clarity` (score: vague, partial, specific);
- of validation gaps: `gap_material` (noul);
- of the user's reply about gaps: `wants_revision` (noul).
What is sent is Deliverable names, the count of waiting questions, the user's message, and for gaps the proposed Check statements and unverifiable Check ids.
4. **Rules when Jev gives no answer.** A requested change is acted on only when one Deliverable is named outright, otherwise the user is asked which. A free-text reply is treated as an answer. A gap is revised for when a Check cannot be verified or an addition names a real requirement or recommendation id.
5. **A new reading from the run of 2026-10-07:** a Check that fails in two validations running is sent to the Target architecture, not the code. That run retried one unimplementable Check as code three times.
6. **Decisions are recorded** in the Execution's state under `decisions`: turn, group, action and what was judged, with confidence.
7. **The reply writer.** A new role, `agents/reply-writer.md`, writes the Approval summary from facts (`approval_facts`) through one tool. When it fails or is absent, `assembled_summary` builds the summary from the same facts.
8. **Wiring.** `ORCHESTRATOR=router` (the default) or `model`; `open_assembly` builds the router with the decider and the thresholds (`JEV_ACT_THRESHOLD`, `JEV_CLOSE_THRESHOLD`, `JEV_CONFIDENCE_THRESHOLD`). State gained `last_reply`, `pending_change`, `awaiting_gap_decision`, `validation_settled` and `decisions`.
Changed from the plan and the ADR's first wording:
- **Jev does not propose the next action.** It supplies readings, and the playbook in code picks the action. This follows the owner's triage model and keeps every decision explainable by a rule and a threshold.
- **The model Orchestrator is kept** behind `ORCHESTRATOR=model`. The 40 or so engine tests drive the Ledger's rules by scripting its tool calls in arbitrary order, which the router cannot do. `agents/orchestrator.md` is therefore unchanged and unused in router mode.
- **An unclear change is confirmed once.** If the reply still does not settle it, a named Deliverable is acted on and anything else is dropped.
- **A pre-approved Execution's automatic replies are not routed.** There is no user message to read.
Not built from the ADR's routes:
- **A message that starts something** (new request, Change request, question about delivered work, out of scope). It needs an entry point that can answer from a case's files, and Change requests (iteration 7).
- **Which Deliverables a Change request reaches.** Iteration 7.
Tests: `tests/execution/test_router.py` (18), `tests/test_assembly.py`.
Unverified:
- Whether Jev's answers to these five questions are good enough at these thresholds. The thresholds are the ones in the owner's example and are untuned.
- Whether the reply writer's summaries are accurate. It is instructed to state only the facts it is given; nothing checks that it does.
- Run time. The Orchestrator made 31 model requests in the last run; the router makes none, and one small writer call per Approval. No run has measured it.

View File

@@ -0,0 +1,44 @@
# Step 2 — Implementation Detail
Built ahead of step 1's answers, on the owner's instruction of 2026-10-07 that no evaluation be rerun until the Jev work is in. Nothing here has called the live service.
1. **The seam** (`app/adk/runtime.py`): `Question` (kind choice, score or noul, with instructions and options), `Answer` (value, confidence, probabilities) and the `Decider` protocol. `decide` returns the answers, or `None` when no decision could be made, and the caller then takes its fallback. `NoDecider` always returns `None`.
2. **The client** (`app/tools/jev.py`): `JevDecider` calls Jev through TypeSafe AI's official Python SDK, `typesafe-sdk` 0.7.2 (`AsyncTypeSafeClient.system_one`). The owner chose the SDK and its API endpoint on 2026-10-07. It is the only module that imports the SDK.
3. **Wiring:** `open_decider` in `app/agent.py` returns the client when `TYPESAFE_API_KEY` is set and `NoDecider` otherwise; the `Assembly` carries it.
4. **A scripted decider** for tests, `FakeDecider` in `app/adk/fake_runtime.py`.
Which package: three names exist on the index. `typesafe-sdk` is the vendor's (author TypeSafe AI, repository `typesafe-ai/typesafe-sdk-python`). `typesafe` is an unrelated type-checking library, and `typesafe-ai` is a third party's redirect shim; neither is used.
What the SDK settled, read from the installed package and a stand-in transport:
- The request is `POST /v1/systemone` with a bearer key; default endpoint `https://api.typesafe.ai`, default model `jev-latest`.
- Questions are `Noul(instructions)`, `Choice(instructions, criteria={option: description})` and `Score(instructions, criteria=[levels])`.
- Answers are `noul` (a probability, with no confidence of its own), `choice` with `confidence` and `probabilities`, and `score` with `confidence`. Usage reports `input_tokens` only: no cost and no remaining credit.
Limits kept, each with a test in `tests/tools/test_jev.py`:
| Practice | Built as |
|---|---|
| Size | Refused locally above 48,000 estimated tokens in all, or 24,000 for the state plus the longest question. Never truncated. |
| Batching | Every question about one state goes in one request. |
| Timeout | 5 seconds a request, 15 for a decision with its retries (the SDK's). |
| Retries | 2, by the SDK: on 408, 429, 5xx, connection and timeout errors, with jittered backoff, honouring `Retry-After`. |
| Rate | A token bucket, 5 a second with a burst of 10; the rate halves when a rate limit outlasts the retries. |
| Concurrency | At most 8 requests in flight. |
| Circuit breaker | Opens after 5 failures in 30 seconds for 60 seconds, then lets one probe through. |
| Cache | Answers kept by a hash of the state and questions, up to 1,024. |
| Budget | 500 calls or 1,000,000 input tokens per scope (the Execution), then fallbacks with one warning. |
| Records | Each decision's outcome, seconds, rate limiting, input tokens and confidence; `summary()` totals them. |
| Key | From `TYPESAFE_API_KEY` only; never logged. |
Settings: `TYPESAFE_API_KEY`, `TYPESAFE_BASE_URL`, `TYPESAFE_DEFAULT_MODEL` (the SDK's own names), and `JEV_TIMEOUT_SECONDS`, `JEV_REQUESTS_PER_SECOND`, `JEV_MAX_IN_FLIGHT`, `JEV_BUDGET_CALLS`, `JEV_BUDGET_TOKENS`.
Changed from the plan:
- The cache is per client, not per Execution. A decision depends only on its state and questions, so two Executions asking the same thing can share the answer.
- A reply that leaves any question unanswered, or picks a choice that was not offered, counts as no decision for the whole request.
- The budget is in calls and input tokens, not dollars, and there is no low-credit warning: the SDK reports neither cost nor balance.
- A yes-or-no answer's confidence is derived as its distance from an even probability, because Jev returns none.
- Retries and their backoff are the SDK's, configured here, not reimplemented.
Unverified: the client has run only against a stand-in transport, with the real SDK in the loop. The first call with a real key is still to be made, and the service's actual rate limits, latency and data retention are still unknown.

View File

@@ -0,0 +1,87 @@
# Plan Detail
Every step is built test-first with the fake runtime and ends with `pytest`, `ruff check .` and `mypy .` passing. File names for new attachments are proposals; keep them once a step uses them.
## Step 1: Accept ADR-0005
- **Capability:** A recorded decision to build on.
- **The three points the owner confirms:**
1. The user approves the Target architecture before code is written, which splits the solution architecture Phase and makes five Phases against the upstream Skill's four.
2. A new Specialist produces the Target architecture.
3. Code renders the diagram from the graph, and the diagrammer role is removed.
- **Acceptance criteria:** ADR-0005's status is `accepted`, or it is amended and this plan is updated to match before any other step starts.
## Step 2: Identify requirements, components and recommendations by id
- **Capability:** Stable ids at the start of the Requirements chain, as data.
- **Rationale:** A rule such as "every requirement has a Check" can only be enforced if requirements can be counted. Today requirements, components and recommendations exist only as prose.
- **Where:** `app/workflows/deliverables.py` (new required attachments and their checks), `agents/requirements-analyst.md`, `agents/decomposer.md`, `agents/design-advisor.md`, `agents/partials/specialist-protocol.md`.
- **Design:**
- `requirements` attaches `requirements.json`: a list of `{id, kind, text}` with `kind` functional or non-functional.
- `technical_decomposition` attaches `components.json`: a list of `{id, name, requirements: [ids]}`. This replaces the table contract from iteration 4 step 4.
- `design_recommendations` attaches `recommendations.json`: a list of `{id, pillar, text, components: [ids]}`.
- **Acceptance criteria:** Each attachment is refused when malformed, when an id repeats, or when it refers to an id that the Deliverable it depends on does not define. A requirement that no component serves is refused at the decomposition.
## Step 3: The graph: format, parsing and structural rules
- **Capability:** One definition of what a well-formed Target architecture is.
- **Where:** new `app/workflows/target_architecture.py`, pure and without I/O, like the Ledger.
- **Design:** `target-architecture.json` holds:
- `elements`: `{id, name, component, product, resource_type}`.
- `relationships`: `{id, from, to, kind}`.
- `checks`: `{id, applies_to, statement, source}`, where `applies_to` is an Element or Relationship id and `source` is a requirement or recommendation id.
- **Acceptance criteria:** Parsing refuses, with the offending id named: a repeated id; a Relationship whose `from` or `to` is not an Element; a Check whose `applies_to` is not in the graph; an Element with no Check; an empty `statement`. The module exposes the graph as typed data for steps 5, 7, 8 and 9.
## Step 4: The Target architecture Deliverable, its Specialist and its Skill
- **Capability:** A Deliverable that is the graph, produced by its own Specialist following a Skill.
- **Where:** `DeliverableKind.TARGET_ARCHITECTURE` in `app/workflows/deliverables.py`, depending on product selection and design recommendations; a new role file in `agents/`; a new Skill under `skills/` that defines the format and how to derive Elements, Relationships and Checks; `providers/gcp.yaml` (`role_skills`, model); `app/adk/roles.py` picks the role up from the dependency graph.
- **Rationale:** ADR-0002: how to model an architecture is behaviour and belongs in a Skill. The role file stays provider-neutral.
- **Who writes it:** the Specialist, never the user. The user's input is the Workflow request and their answers during requirements discovery; implementation-level detail is the agents' job, drawn from the pillar Skills and the provider's documentation.
- **Acceptance criteria:** The Deliverable requires `target-architecture.json`, checked by step 3 at submission. Its content is a readable summary with one section per Element. A Check's `statement` is written so that it can be verified from the infrastructure code alone, and the Skill says so with examples.
## Step 5: Completeness: the Requirements chain is a submission rule
- **Capability:** A Target architecture with a broken chain cannot be submitted.
- **Rationale:** This is the rule that makes the outcome understood up front. Without it the graph is one more document.
- **Where:** `check_submission` currently sees only the Deliverable being submitted. It needs the Deliverables it depends on: extend it and `specialist_tools` in `app/tools/execution.py` to pass them.
- **Acceptance criteria:** Submission is refused, naming each gap, when: a requirement id is the `source` of no Check, directly or through a component's Element; a component has no Element; a selected product appears on no Element; a recommendation is the `source` of no Check. A recommendation may be marked not applicable only with a stated reason, and that is listed for the user at Approval.
## Step 6: Split the solution architecture Phase: design, then implementation
- **Capability:** The user approves the Target architecture before code is written.
- **Where:** `PhaseId` and `DEPENDENCY_GRAPH` in `app/workflows/deliverables.py`; `agents/orchestrator.md`; `workflow.yaml` (its test will fail until updated); `app/card.py` derives from the graph; `app/presentation.py`; `eval/`; the spec's Phase table.
- **Design:** Design holds product selection, design recommendations and the Target architecture. Implementation holds the architecture description and the deployment guidance.
- **Acceptance criteria:** No Deliverable in implementation can start until design is approved (a Ledger test). The Approval prompt for design summarises the graph: counts of Elements, Relationships and Checks, and any recommendation marked not applicable. A pre-approved Execution passes through as today.
## Step 7: The diagram is rendered from the graph
- **Capability:** A diagram that cannot disagree with the architecture.
- **Where:** a renderer in `app/workflows/target_architecture.py` from Elements and Relationships to Mermaid; `architecture.mmd` is added to the Target architecture's attachments by the engine on submission; the `architecture_diagram` Deliverable, `agents/diagrammer.md` and its bundle entries are removed; `app/presentation.py` reads the diagram from the Target architecture so `/generate`'s keys are unchanged.
- **Acceptance criteria:** Rendering is deterministic and passes `mermaid_check` for any graph step 3 accepts, including names with characters Mermaid treats specially. Every Element and Relationship appears exactly once. The solution guide still carries the diagram in the template's section 4.2.
## Step 8: Deployment guidance implements the graph
- **Capability:** Code written against a known list, with each item accounted for.
- **Where:** `deployment_guidance` depends on the Target architecture; `agents/iac-author.md`; `skills/iac-validation/SKILL.md`; a required attachment `implementation.json`: for each Check id, the file and resource address that satisfies it.
- **Acceptance criteria:** Submission is refused when a Check id is missing from `implementation.json` or an id in it is not in the graph. The IaC author's context carries the graph, not the prose recommendations. `terraform_validate` must still pass before submission, as today.
## Step 9: Validation gives a verdict per Check
- **Capability:** A fixed bar: validation answers the graph's Checks and nothing else can fail the code.
- **Where:** `validation_results` requires `verdicts.json` in place of `findings.json`: for each Check id, `{verdict, evidence}` with `verdict` pass, fail or not verifiable, plus a separate list `proposed_additions` of `{statement, applies_to, reason}`. `agents/validator.md`, `skills/iac-validation/SKILL.md`, `app/states/lessons.py`, `eval/scoring.py`.
- **Acceptance criteria:** Submission is refused unless every Check has exactly one verdict with evidence. A proposed addition never counts as a failure. A `not verifiable` verdict is treated as a gap in the graph, not in the code. The dry-run result (`terraform validate`, and `plan` when permitted) is itself a Check on the deployment as a whole, so it has a verdict too.
## Step 10: Revision routing: the code or the graph
- **Capability:** Each validation outcome leads to exactly one kind of Revision.
- **Where:** `_orchestrator_context` in `app/nodes/execution_nodes.py` gives the Orchestrator the failed Check ids and the proposed additions; `agents/orchestrator.md`.
- **Design:** Failed Checks reopen the deployment guidance, with the failed ids as the reason. Proposed additions and `not verifiable` verdicts go to the user in an interactive Execution; in a pre-approved one the Orchestrator reopens the Target architecture only for an addition that names a requirement or recommendation id. Reopening the Target architecture returns the implementation Phase to draft and withdraws its Approval, by the Ledger's existing rule.
- **Acceptance criteria:** Engine tests show both routes. With unchanged code and an unchanged graph, a second validation pass has the same Check ids as the first: the list cannot grow.
## Step 11: Evaluation: prove the loop converges
- **Capability:** Evidence that the outcome is understood before code is written.
- **Where:** `eval/scoring.py`, `eval/solution_eval.py`, `eval/datasets/solution_cases.json`.
- **Design:** New checks: every requirement reaches at least one Check with a pass verdict; no Check is left failed or not verifiable; the diagram matches the graph. The report records, per case, the number of validation passes and the Check ids failing at each.
- **Acceptance criteria:** All benchmark cases complete and score at least 0.8. In each, the set of failing Check ids never grows from one validation pass to the next, and deployment guidance needs at most one Revision in at least two of the three cases. The thresholds left unset by iteration 4 step 8 are set from this run. The comparison with the stopped run of 2026-10-06 is written into this step's file.

View File

@@ -0,0 +1,89 @@
# Plan Map
**Iteration:** 6, the Target architecture graph
**Intent:** Establish the Target architecture as one explicit graph of Elements, Relationships and Checks before any infrastructure code is written, and derive and check every later Deliverable from it, so that the outcome is understood before code exists and validation has a fixed bar.
**Status:** steps 1 to 10 built and covered by the deterministic suite; nothing has run against a real model; step 11's evaluation run is on hold by the owner
**This directory covers:** steps 1 to 11
## Order of work
Build this iteration before the remaining steps of iteration 4 (10 to 14) and before iteration 5. It changes Deliverables, Phases and the validation format that those steps build on. The effects on them are listed at the end of this file.
## Sources of truth
- `docs/adr/0005-the-target-architecture-is-an-explicit-graph.md`: the decision, its three points to confirm, and the rejected alternatives. Status `proposed`.
- `CONTEXT.md`: Target architecture, Element, Relationship, Check, Requirements chain. Use these words; "Dependency" stays the link between Deliverables.
- `iter-04-learning-and-skills/steps/step-8.md`, "The evaluation run of 2026-10-06": the evidence. Three validation passes gave 4, 7, then 5 different findings on the same Terraform.
- `docs/adr/0002-*.md`: the graph's format and how to write it are behaviour, so they live in a Skill; the engine only checks the result.
## The flow this iteration builds
```mermaid
flowchart TD
REQ([Workflow request]) --> R[Requirements]
R --> D[Technical decomposition]
D --> A1{{Approval: requirements discovery}}
A1 --> PS[Product selection]
PS --> DR[Design recommendations]
R --> DR
PS --> TA
DR --> TA[Target architecture: Elements, Relationships, Checks]
TA --> A2{{Approval: design}}
A2 --> DESC[Architecture description]
A2 --> IAC[Deployment guidance]
TA -.rendered by code.-> DIA[Architecture diagram]
IAC --> A3{{Approval: implementation}}
DESC --> A3
A3 --> VAL[Validation: a verdict per Check]
VAL -->|a Check fails| IAC
VAL -->|the graph is missing something| TA
VAL -->|every Check passes| A4{{Approval: validation}}
A4 --> G[Solution guide]
G --> A5{{Approval: packaging}}
```
## Status
| Step | What | Size | Status |
|---|---|---|---|
| 1 | Accept ADR-0005 | S | complete: accepted 2026-10-07 |
| 2 | Identify requirements, components and recommendations by id | M | complete |
| 3 | The graph: format, parsing and structural rules | M | complete |
| 4 | The Target architecture Deliverable, its Specialist and its Skill | M | complete; unproven with a real model |
| 5 | Completeness: the Requirements chain is a submission rule | M | complete |
| 6 | Split the solution architecture Phase: design, then implementation | M | complete |
| 7 | The diagram is rendered from the graph | S | complete |
| 8 | Deployment guidance implements the graph | M | complete |
| 9 | Validation gives a verdict per Check | M | complete |
| 10 | Revision routing: the code or the graph | S | complete; routing unproven with a real model |
| 11 | Evaluation: prove the loop converges | M | checks built; evaluation run outstanding (on hold by the owner) |
Size: S under a day, M a few days.
## Dependency graph
- Step 1: no dependencies
- Step 2: depends on step 1
- Step 3: depends on step 1
- Step 4: depends on step 3
- Step 5: depends on step 2, step 4
- Step 6: depends on step 4
- Step 7: depends on step 4
- Step 8: depends on step 5
- Step 9: depends on step 8
- Step 10: depends on step 6, step 9
- Step 11: depends on step 7, step 10
Steps 2 and 3 can be built side by side, as can 6 and 7.
## Effects on other iterations
- **Iteration 4 step 1** (`findings.json`): replaced by the verdicts of step 9 here. The free-form finding list goes.
- **Iteration 4 step 4** (contracts): the diagram's contract goes with the diagrammer; the decomposition's component table becomes data in step 2 here.
- **Iteration 4 step 6** (Orchestrator step order): rewritten by step 10 here.
- **Iteration 4 step 7** (lesson candidates): `finding` candidates become failed Checks and proposed additions.
- **Iteration 4 step 8** (evaluation): `no_blocking_findings` is rewritten against verdicts; the unset thresholds are set by step 11 here.
- **Iteration 4 step 11** (IaC patterns Skill): its patterns should be keyed by the product of an Element.
- **Iteration 4 step 13** (trim Specialist context): mostly achieved here, since later Specialists work from the graph. Re-scope it after step 11.
- **Iteration 5 step 5** (finding-to-Deliverable routing): no longer needed; a failed Check already names what it applies to.
- **Iteration 5 step 4** (semantic checks at submission): can judge whether each Check is verifiable as written.

View File

@@ -0,0 +1,14 @@
# Step 1 — Implementation Detail
ADR-0005 was accepted by the owner on 2026-10-07 ("lets move forward with this", after reviewing the proposed case structure), with its three points as written:
1. The user approves the Target architecture before code is written; the solution architecture Phase is split, making five Phases.
2. A new Specialist produces the Target architecture.
3. Code renders the diagram from the graph; the diagrammer role is removed.
ADR-0006 (Change requests) was accepted in the same reply; it is built in iteration 7.
Clarifications the owner gave before accepting, now in the ADR and the role files:
- The graph is the Target architecture itself, not a build plan beside it.
- The user states Intent at a high level in the Workflow request. The agents derive every Element, Relationship and Check from the architecture framework and best practice; the user never writes the graph.

View File

@@ -0,0 +1,12 @@
# Step 10 — Implementation Detail
1. The Orchestrator's context carries `validation`: the outcome of the submitted validation, or null before there is one.
2. `agents/orchestrator.md` step 3, "Validation decided", routes on it:
- failed Checks, or a failed dry-run: reopen the deployment guidance with each failed Check's id and evidence.
- otherwise, not-verifiable Checks or proposed additions: the Target architecture has a gap. Interactive: ask the user whether to revise it. Pre-approved: reopen it only for items whose reason names a requirement or recommendation id.
The routing is the Orchestrator's choice, as ADR-0003 requires; the engine supplies the facts and the Ledger enforces what a reopen does.
On "the list cannot grow": the verdict list is fixed by the graph, because every verdict must be on a Check and every Check must have one. With an unchanged graph, two validation passes cover the same ids by construction (`test_validation_gives_exactly_one_verdict_per_check`).
Not verified: whether a real Orchestrator model follows the new routing. `test_the_orchestrator_is_told_what_validation_decided` covers the context and the Revision, with the reopen scripted.

View File

@@ -0,0 +1,58 @@
# Step 11 — Implementation Detail
Partly done. The checks are built; the evaluation run that this step exists for has not been made.
Built in `eval/scoring.py`:
- `requirements_chain_complete`: the delivered data files form a chain with no gap.
- `every_check_passes`: validation ended with no Check failed or not verifiable, and the dry-run not failed.
- `diagram_matches_graph`: the delivered diagram is exactly the rendering of the delivered graph.
These replaced `components_trace_to_requirements` and `no_blocking_findings` from iteration 4 step 8.
Outstanding, and why:
- **No evaluation run.** The owner stopped the last run on 2026-10-06 and asked that no further cases start until they advise. Nothing in this iteration has run against a real model.
- **The acceptance criteria are therefore unmet:** all cases scoring at least 0.8, the failing-Check set never growing between passes, and at most one Revision of the deployment guidance in two of three cases.
- **Not built:** the per-case record of validation passes and the Check ids failing at each. The evaluation reads only the final verdicts today.
- **Thresholds** from iteration 4 step 8 are still unset.
Do not mark this step complete until a run meets the criteria. (`legacy-baseline` was removed on 2026-10-07 on the owner's instruction, ahead of this.)
## Evaluation run of 2026-10-07, case 01 (commit `e924682`)
Report: `eval/results/20261007T125917Z/report.json`. Result: `completed_with_warnings`, score 73% (8 of 11 checks), 3,627 seconds, 4.25 million tokens, 144 model requests. No solution guide was written.
| | Stopped run, 2026-10-06 | This run |
|---|---|---|
| First pass to a validation | about 17 minutes | 25 minutes |
| Validation passes | 3 | 2 |
| Failing items per pass | 4, then 7, then 5 findings | 0 failed Checks and 7 proposed additions, then 1 failed Check, 1 not verifiable and 1 proposed addition |
| Revisions | deployment guidance × 3 | Target architecture × 1, deployment guidance × 3 |
| Outcome | stopped at 35 minutes | ended with warnings at 60 minutes |
What held:
- Every chain link was accepted on a first attempt except the Target architecture, which was refused once per attempt (7 requirements with no Check; then 4 Elements with no Check) and fixed inside its own run.
- `requirements_chain_complete` and `diagram_matches_graph` passed.
- The Terraform met every Check on its first attempt (0 failed of the first graph's Checks).
- The Orchestrator followed the new routing: additions reopened the Target architecture; a failed Check reopened the code.
- After one revision of the graph the validator proposed 1 addition, down from 7.
What failed, in order of cause:
1. **A bug in this iteration (fixed after the run, with a test).** Once the deployment guidance was reopened, the Orchestrator's context still carried the old validation's verdicts. It reopened the code for K-30 three times in a row without a validation in between, reaching the Revision limit. `_orchestrator_context` now shows a validation only while the validation results stand as submitted.
2. **A Check that cannot be implemented had nowhere to go.** K-30 required `startup_cpu_boost` on a Cloud Run job. Terraform rejects that argument there, so the IaC author could not satisfy it, and the validator marked it failed, which sends it back to the code. The fault was in the graph. The IaC author used 57 requests and 2.35 million tokens, 55% of the run.
3. **The target architect put a recommendation on an Element it does not apply to.** K-30 came from DR-19, proposed by the validator in pass 1 for two services and applied to the job as well.
4. **Model timeouts.** The target architect's model request timed out at 180 seconds in both attempts; each cost about 3 minutes.
Not yet exercised: the second pass also had a Check marked not verifiable (K-55) and a proposed addition (NFR-15). The failed-Check route took precedence, as instructed, so the gap route was not taken a second time.
Acceptance criteria: not met. The case did not complete or reach 0.8.
Changes this points to, not yet made:
- Let the IaC author report a Check it cannot implement, with the tool's error as evidence, so that it is routed to the Target architecture and not retried as code.
- Have the validator distinguish "the code does not do this" from "this cannot be done to this resource".
- Check a proposed addition against the Element it names before it becomes a Check.
- Raise or tune the model timeout for the target architect.

View File

@@ -0,0 +1,17 @@
# Step 2 — Implementation Detail
1. `app/workflows/chain.py` defines the data files and a checker for each. Each checker returns one entry per fault, so a Specialist can fix and resubmit.
2. New required attachments (`DATA_CHECKS` in `app/workflows/deliverables.py`):
- `requirements.json` on requirements: `{id, kind, text}`, kind functional or non_functional, ids unique.
- `components.json` on the technical decomposition: `{id, name, requirements}`. This replaced the component table contract from iteration 4 step 4.
- `products.json` on product selection: `{component, product}`, one for every component.
- `recommendations.json` on design recommendations: `{id, pillar, text, components}`.
3. `check_submission` takes the Deliverables being built on (`upstream`), so links are checked across Deliverables: a component may only serve a real requirement, a product may only be selected for a real component, a recommendation may only name real components.
4. The formats live in a new Skill, `skills/requirements-chain/SKILL.md`, assigned in `providers/gcp.yaml` to every role that writes or reads one.
Changed from the plan:
- `products.json` was added. The plan's rule "a selected product appears on no Element" needs the selection as data.
- Only functional requirements must be served by a component at the decomposition. A non-functional requirement often constrains the whole workload, so it is held to a stricter rule later: it must be the source of a Check (step 5).
Tests: `tests/execution/test_requirements_chain.py`, "the links before the graph".

View File

@@ -0,0 +1,8 @@
# Step 3 — Implementation Detail
1. `app/workflows/target_architecture.py`, pure and without I/O: `Element`, `Relationship`, `Check`, `NotApplicable`, `TargetArchitecture`, and `parse_graph`, which returns the graph or raises `GraphError` listing every fault.
2. The file is `target-architecture.json` with `elements`, `relationships`, `checks` and optional `not_applicable`.
3. Refused, with the id named: a repeated id; a Relationship whose `from` or `to` is not an Element; a Check that applies to nothing in the graph; an Element with no Check; a missing or empty field.
4. An Element's `component` is optional, for supporting Elements such as identities, keys and networks.
Tests: `tests/execution/test_requirements_chain.py`, "the graph is well-formed".

View File

@@ -0,0 +1,8 @@
# Step 4 — Implementation Detail
1. `DeliverableKind.TARGET_ARCHITECTURE`, in the design Phase, depending on product selection and design recommendations. Its content needs `Elements`, `Relationships` and `Checks` sections; its attachment is the graph.
2. Role file `agents/target-architect.md`. In the bundle it loads the solution-architecture and requirements-chain Skills, reaches the documentation MCP server, and runs on the Pro model tier.
3. `skills/requirements-chain/SKILL.md` gives the graph's format and how to write a Check that can be verified from code, with verifiable and non-verifiable examples.
4. The role file states that implementation detail is the agent's job and the user stays at the level of Intent.
Not verified: no real model has produced a Target architecture yet. Whether one can write Checks specific enough to verify, in one run and inside its tool budget, is the main risk of this iteration and is what step 11 measures.

View File

@@ -0,0 +1,18 @@
# Step 5 — Implementation Detail
`chain_gaps` in `app/workflows/target_architecture.py` lists every place the Requirements chain stops; `check_target_architecture` runs it at submission, so a Target architecture with a gap is refused with each gap named.
A gap is:
- a component with no Element;
- a non-functional requirement that is the source of no Check;
- a functional requirement that is the source of no Check and is served by no component with an Element;
- a selected product that does not appear on its component's Element;
- a recommendation that is the source of no Check and is not listed under `not_applicable` with a reason;
- a Check whose `source` is not a requirement or recommendation, or an Element that realises something that is not a component.
Recommendations marked not applicable are carried in the graph's summary and shown to the user at the design Approval.
The rule checks that each link exists, not that it is right. A vague Check passes here and is caught later as `not_verifiable`, or by the user at Approval.
Tests: `tests/execution/test_requirements_chain.py`, "the Requirements chain has no gap", including one through `submit_deliverable`.

View File

@@ -0,0 +1,10 @@
# Step 6 — Implementation Detail
1. `PhaseId` has five members. `solution_architecture` is now the design Phase (product selection, design recommendations, Target architecture). The new `solution_implementation` holds the architecture description and the deployment guidance. The id `solution_architecture` was kept so recorded Executions and callers do not break.
2. The Ledger's existing rule does the gating: a Dependency across Phases is met only on Approval, so nothing in implementation is ready until design is approved.
3. The design Approval carries a summary of the graph (counts of Elements, Relationships and Checks, and recommendations treated as not applicable). `describe_prompt` in `app/presentation.py` states that no code is written until it is approved.
4. `workflow.yaml` lists the five Phases; its test checks it against the dependency graph. The A2A card derives from the graph and needed no change.
Revision behaviour that follows: reopening the deployment guidance withdraws the implementation and validation Approvals and leaves the design approved; reopening the Target architecture withdraws design, implementation and validation, and the code cannot restart until the design is approved again.
Tests: `tests/execution/test_ledger.py`, `test_the_user_approves_the_graph_before_any_code_is_written` in `tests/execution/test_requirements_chain.py`, `tests/execution/test_presentation.py`.

View File

@@ -0,0 +1,10 @@
# Step 7 — Implementation Detail
1. `render_mermaid` draws a left-to-right flowchart with every Element (name and product) and every Relationship (its kind) exactly once. Node ids are generated, and characters Mermaid reserves are stripped from labels, so any graph step 3 accepts renders.
2. `submit_deliverable` adds `architecture.mmd` to the Target architecture's attachments when it accepts the submission. No Specialist draws it.
3. Removed: the `architecture_diagram` Deliverable, `agents/diagrammer.md` and its bundle entries.
4. `/generate` keeps its `mermaid_diagram` key, now read from the Target architecture. The packager is told to embed that attachment unchanged.
The local `mermaid_check` tool stays in the bundle; the evaluation still uses it.
Tests: `tests/execution/test_requirements_chain.py`, "the diagram is a view of the graph".

View File

@@ -0,0 +1,9 @@
# Step 8 — Implementation Detail
1. The deployment guidance depends on the Target architecture and requires `implementation.json`: for each Check, the attached file and resource address that satisfies it.
2. Refused: a Check not accounted for, an id that is not a Check, an entry naming a file that is not attached.
3. `agents/iac-author.md` now says to implement the Target architecture and nothing it does not ask for, and on a Revision to change only what the failed Checks need.
Changed from the plan: the IaC author's context still carries every earlier Deliverable in full, prose recommendations included, because `inputs_of` is unchanged. Narrowing it to the graph is iteration 4 step 13.
Tests: `test_deployment_guidance_must_account_for_every_check`.

View File

@@ -0,0 +1,12 @@
# Step 9 — Implementation Detail
1. The validation results require `verdicts.json` in place of `findings.json`: a `dry_run` result, one verdict per Check (`pass`, `fail` or `not_verifiable`) with evidence, and a separate list of `proposed_additions`.
2. Refused: a Check with no verdict, a Check with two, a verdict on something that is not a Check, a verdict without evidence, a missing dry-run result.
3. A proposed addition is never a failure. This is the rule that stops validation findings growing between passes: the validator cannot add to what the code is judged against.
4. `validation_outcome` in `app/workflows/chain.py` separates faults in the code (failed Checks) from gaps in the graph (not verifiable, proposed additions). Lesson candidates and the evaluation use it.
Changed from the plan: the dry-run is its own `dry_run` entry, not a Check in the graph, so the Target architecture stays free of tooling concerns.
`check_findings` and `FINDINGS_ATTACHMENT` from iteration 4 step 1 are gone. Lesson candidate types are now `failed_check`, `unverifiable_check` and `proposed_addition`.
Tests: `tests/execution/test_requirements_chain.py`, "code and validation answer the graph"; `tests/execution/test_lessons.py`.

View File

@@ -0,0 +1,60 @@
# Plan Detail
Every step is built test-first with the fake runtime and ends with `pytest`, `ruff check .` and `mypy .` passing.
## Step 1: Accept ADR-0006 and update the glossary
- **Capability:** A recorded decision, and vocabulary that no longer contradicts it.
- **The four points the owner confirms:** a Change request is a new Execution and never modifies its Baseline; the Baseline is a completed Execution of the same Customer case; the output is complete, not a patch; a Change request may itself be a Baseline.
- **Where:** `docs/adr/0006-*.md` status; `CONTEXT.md` entries for Execution, Session and Customer case, plus new entries **Change request** and **Baseline**; the sentence "An Execution starts clean" in `docs/adr/0004-*.md`.
- **Acceptance criteria:** The ADR is `accepted` or amended with this plan updated to match. No glossary entry says an Execution can never start from another.
## Step 2: Start an Execution against a Baseline
- **Capability:** A caller names a Baseline and the new Execution begins with its Deliverables.
- **Where:** `ExecutionEngine.start(baseline=...)` in `app/agent.py`; `/generate` body and A2A message metadata (`app/main.py`, `app/a2a_server.py`); `app/states/execution_state.py` (a `baseline` entry holding the Baseline's id and Deliverables); `execution.json` records the Baseline; `intent/history.json` records it on the new statement, so the history shows the line of versions.
- **Design:** The Baseline is loaded from its files under the Customer case, through `execution.json`, so it works across restarts and does not need the Baseline's checkpoint.
- **Acceptance criteria:** Start is refused, before anything runs, when the Baseline does not exist, is not completed, or belongs to another Customer case. An Execution started without a Baseline behaves exactly as today. The Baseline's files are byte-identical after the Change request completes.
## Step 3: Requirements revised with a change record
- **Capability:** The user's high-level statement of change becomes a precise change to the requirements.
- **Where:** `agents/requirements-analyst.md`; the requirements contract in `app/workflows/deliverables.py`; `agents/partials/specialist-protocol.md` (a `baseline` entry in the context).
- **Design:** `requirements.json` keeps the id of every requirement that still holds and gives each requirement a `change` of unchanged, added, changed or removed, with the reason. New requirements take new ids; an id is never reused.
- **Acceptance criteria:** Submission is refused when a Baseline requirement is missing from the revised list without being marked removed, or when a changed requirement has no reason. In an interactive Execution the analyst confirms the change record with the user before submitting.
## Step 4: Later Specialists revise from the Baseline
- **Capability:** Each Deliverable changes only where the changed requirements reach.
- **Where:** `_specialist_input` in `app/nodes/execution_nodes.py` (each Specialist receives the Baseline's version of its own Deliverable and the ids that changed upstream); every Specialist role file; the Target architecture Skill from iteration 6 step 4; `app/workflows/target_architecture.py` (a function that compares two graphs).
- **Design:** Ids are stable across versions: an Element, Relationship or Check that is unchanged keeps its id and its text. The engine computes what is reached by walking the Requirements chain from each changed requirement.
- **Acceptance criteria:** A test with the fake runtime shows that an Element or Check not reached by any changed requirement is identical to the Baseline's, and one that differs without being reached is reported in the change summary as an unrequested change. Validation still gives a verdict for every Check.
## Step 5: Approvals show the change
- **Capability:** The user approves what changed, not the whole architecture again.
- **Where:** `request_approval` in `app/tools/execution.py`, `app/presentation.py`, `agents/orchestrator.md`.
- **Acceptance criteria:** In a Change request, each Approval prompt lists what was added, changed and removed against the Baseline for that Phase's Deliverables, computed by the engine from the ids, not written by the Orchestrator.
## Step 6: Change summary and version line in the case
- **Capability:** A reader of a Customer case can see each version and what moved between them.
- **Where:** `_write_outputs` in `app/nodes/execution_nodes.py`; the packager role file.
- **Design:** Each Change request writes `changes.json` (requirements, Elements, Relationships and Checks added, changed and removed, each with its reason) and a readable summary in the solution guide. `intent/history.json` lists each statement with its Baseline.
- **Acceptance criteria:** The full Deliverables are written as for any Execution. `changes.json` matches a comparison of the two Executions' data files. Unrequested changes are listed separately from requested ones.
## Step 7: Evaluation: a change case
- **Capability:** Evidence that a change stays contained.
- **Where:** `eval/datasets/solution_cases.json`, `eval/solution_eval.py`, `eval/scoring.py`.
- **Design:** A case that runs a base request and then a Change request against it, for example retention moving from 30 days to 7 years.
- **Acceptance criteria:** The change case scores at least 0.8. New checks pass: every changed requirement reaches a changed or new Check; nothing outside its reach changed without being reported; the Change request used fewer tokens than its Baseline.
## Step 8: Remove the `legacy-baseline` case
- **Capability:** `deliverables/` holds only what the current engine produced.
- **Rationale:** `deliverables/cases/legacy-baseline/` is the output of the deleted iteration 1 pipeline: 68 Executions (62 of them from its tests and old benchmark) and its last shared copies in `as-is/`, `target/`, `validation/` and `guides/`. The owner chose on 2026-10-06 to keep it until this work is complete with the expected outcome, and to remove it then.
- **Gate:** Do this only when iteration 6 step 11 and step 7 here have both met their acceptance criteria. If either falls short, leave the case in place and say so.
- **Where:** `deliverables/cases/legacy-baseline/`; `scripts/validate_artifacts.py`, `tests/test_artifacts.py` and `tests/test_package.py`, which read its `as-is/`, `target/`, `validation/` and `guides/` folders and must be removed or pointed at a current Execution; `scripts/validate.sh`; `VALIDATION.md` step 1; the root `terraform/`, `docs/requirements.md`, `docs/architecture.md`, `docs/source-architecture.md` and `requirements.yaml`, which are the same pipeline's samples.
- **Guardrail:** Commit first, then delete in a commit of its own, so the removal can be reverted.
- **Acceptance criteria:** The case and the samples are gone, nothing in `scripts/` or `tests/` refers to them, and `pytest`, `ruff check .` and `mypy .` pass.

View File

@@ -0,0 +1,37 @@
# Plan Map
**Iteration:** 7, Change requests
**Intent:** Let a user restate a request to say how their requirements have changed, at a high level, and receive the delivered architecture updated from where it stood, with an account of what changed and why.
**Status:** planned. ADR-0006 was accepted on 2026-10-07 and the glossary updated (step 1). Build after iteration 6 step 11 has a passing evaluation run
**This directory covers:** steps 1 to 8
## Sources of truth
- `docs/adr/0006-a-change-request-starts-from-a-baseline-execution.md`: the decision and its four points to confirm. Status `proposed`.
- `docs/adr/0005-the-target-architecture-is-an-explicit-graph.md` and `../iter-06-target-architecture-graph/`: the ids along the Requirements chain that a change is traced through. Build iteration 6 first.
- `CONTEXT.md`: today it says an Execution starts clean and a Customer case never feeds one Execution into another. Step 1 changes those entries; until then they stand.
- `iter-04-learning-and-skills/steps/step-15.md`: the Customer case layout, `execution.json` and the Intent history (`intent/history.json`) that a Baseline is found through. A Change request is the next statement in that history.
## Status
| Step | What | Size | Status |
|---|---|---|---|
| 1 | Accept ADR-0006 and update the glossary | S | complete: accepted 2026-10-07 |
| 2 | Start an Execution against a Baseline | M | planned |
| 3 | Requirements revised with a change record | M | planned |
| 4 | Later Specialists revise from the Baseline | M | planned |
| 5 | Approvals show the change | S | planned |
| 6 | Change summary and version line in the case | S | planned |
| 7 | Evaluation: a change case | M | planned |
| 8 | Remove the `legacy-baseline` case | S | complete: removed early on the owner's instruction, 2026-10-07 |
## Dependency graph
- Step 1: no dependencies
- Step 2: depends on step 1, iteration 4 step 15
- Step 3: depends on step 2, iteration 6 step 2
- Step 4: depends on step 3, iteration 6 steps 4 and 8
- Step 5: depends on step 4, iteration 6 step 6
- Step 6: depends on step 4
- Step 7: depends on step 5, step 6, iteration 6 step 11
- Step 8: no longer gated; done on 2026-10-07

View File

@@ -0,0 +1,13 @@
# Step 8 — Implementation Detail
Done early, on the owner's instruction of 2026-10-07 ("please remove legacy-baseline"). That instruction replaced the gate in `DETAIL.md`, which had held removal until iterations 6 and 7 met their acceptance criteria. Neither has: no evaluation run has been made on iteration 6, and iteration 7 is not built.
1. Deleted `deliverables/cases/legacy-baseline/`: the 68 old Executions, their `intent/` history, and the shared `as-is/`, `target/`, `validation/` and `guides/` folders. `deliverables/cases/` is now empty until an Execution completes.
2. Deleted `scripts/validate_artifacts.py` and `tests/test_artifacts.py`, which only checked that case's samples. `tests/test_package.py` keeps its one test of `terraform/terraform.tfvars.example`.
3. Removed the artefact-validation step from `README.md` and `VALIDATION.md`.
Five of the Execution folders were owned by a rootless-podman user id (110000), left by a container run on 2026-09-02 with the folder mounted. They were removed with `podman unshare rm`.
Not committed first, against the guardrail in `DETAIL.md`: the owner did not ask for a commit. The tracked files are recoverable from commit `7ee49ab` at their earlier paths (`deliverables/as-is/`, `deliverables/target/`, `deliverables/validation/`, `deliverables/guides/`, `deliverables/executions/`, `scripts/validate_artifacts.py`, `tests/test_artifacts.py`). The generated `intent/` files for that case were never committed and are gone.
Left in place, because the instruction named only `legacy-baseline`: the same pipeline's other samples, `terraform/` at the repository root, `docs/requirements.md`, `docs/architecture.md`, `docs/source-architecture.md`, `docs/validation-evidence.md`, `docs/validation-results.json`, `docs/publication-verification.md`, `requirements.yaml`, and `scripts/validate.sh`, which runs Terraform checks on that root `terraform/`.

View File

@@ -8,4 +8,5 @@
*.db
.env
eval/results
deliverables/executions
deliverables/cases
lessons/candidates

View File

@@ -29,16 +29,34 @@ 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
# Terraform providers are cached here so each check does not download them again.
# Relative to the repository root; set it empty to disable.
TF_PLUGIN_CACHE_DIR=.cache/terraform-plugins
# Hierarchical Execution Engine
ORCHESTRATOR=router # router | model
ORCHESTRATOR_BUDGET=40
SPECIALIST_BUDGET=15
MAX_REVISIONS=3
MAX_ORCHESTRATOR_TURNS=100
MAX_PARALLEL_SPECIALISTS=4
CHECKPOINTER=sqlite
CHECKPOINT_DB_PATH=checkpoints.db
# Jev decision service, through the TypeSafe AI Python SDK (typesafe-sdk).
# Leave the key unset to run without it: every decision then takes its fallback.
# TYPESAFE_API_KEY=
# TYPESAFE_BASE_URL= # defaults to the SDK's endpoint
# TYPESAFE_DEFAULT_MODEL= # defaults to the SDK's model
JEV_TIMEOUT_SECONDS=5
JEV_REQUESTS_PER_SECOND=5
JEV_MAX_IN_FLIGHT=8
JEV_BUDGET_CALLS=500
JEV_BUDGET_TOKENS=1000000
JEV_ACT_THRESHOLD=0.75
JEV_CLOSE_THRESHOLD=0.15
JEV_CONFIDENCE_THRESHOLD=0.6
# PostgreSQL (Execution records, and checkpoints when CHECKPOINTER=postgres)
POSTGRES_HOST=localhost
POSTGRES_PORT=5432

3
.gitignore vendored
View File

@@ -29,3 +29,6 @@ tfplan
# Evaluation run outputs
eval/results/
# Lesson candidates captured from Executions (may quote user feedback)
lessons/candidates/

View File

@@ -121,6 +121,8 @@ scripts/sync-vendored-skills.sh
`app/workflows/deliverables.py` declares the graph as data. It is the only place Phases, Deliverables and Dependencies are listed.
> **Changed on 2026-10-07 by [ADR-0005](../../docs/adr/0005-the-target-architecture-is-an-explicit-graph.md).** The table below is the graph as first built. The code now has five Phases, a `target_architecture` Deliverable between the design recommendations and the code, no `architecture_diagram` Deliverable (the diagram is rendered from the graph), and data files carrying ids along the Requirements chain (`app/workflows/chain.py`, `app/workflows/target_architecture.py`). See `.agents/plans/iter-06-target-architecture-graph/`.
| Phase | Deliverable kind | Specialist role | Depends on | Tools (tier) |
|---|---|---|---|---|
| 1 `requirements_discovery` | `requirements` | `requirements-analyst` | (none) | discovery MCP servers (cloud_read) |

View File

@@ -11,15 +11,31 @@ The free-text description of the workload a caller wants architected; the openin
_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.
One solution-architecture engagement for a single Workflow request. It lasts from the first request to an approved Solution guide, and may span many user turns. An Execution starts clean, unless it is a Change request.
_Avoid_: run, job, workflow execution
**Session**:
A caller-supplied grouping of Executions. A Session never feeds earlier outputs into a later Execution; each Execution starts clean.
A caller-supplied grouping of Executions. A Session never feeds earlier outputs into a later Execution.
_Avoid_: conversation, context
**Customer case**:
A caller-supplied grouping of the Executions run for one customer workload, identified by a short slug. Every Execution belongs to one; an Execution started without one belongs to `unassigned`. A Customer case ties each request to the Deliverables generated for it. It feeds one Execution's outputs into another only when the caller starts a Change request and names the Baseline.
_Avoid_: engagement, project, account, tenant
**Intent**:
What the customer wants from a Customer case, in their own words and at a high level. Each Workflow request made in the case is a statement of it, and the statements are kept in order as its history. The Intent is the customer's; requirements are what the agents derive from it.
_Avoid_: brief, ask, requirements (which are the derived Deliverable)
**Change request**:
An Execution started to say how the customer's Intent has changed. It begins from a Baseline and delivers the full updated Deliverables with an account of what changed and why.
_Avoid_: amendment, update run, iteration, re-run
**Baseline**:
The completed Execution, in the same Customer case, that a Change request starts from. A Baseline is never modified.
_Avoid_: parent, previous run, source Execution
**Phase**:
A named grouping of Deliverables: requirements discovery, solution architecture, solution validation, or packaging. A Phase is complete when all its Deliverables are submitted and the user has granted the Phase's Approval.
A named grouping of Deliverables: requirements discovery, solution architecture (the design, ending with the Target architecture), solution implementation, solution validation, or packaging. A Phase is complete when all its Deliverables are submitted and the user has granted the Phase's Approval.
_Avoid_: step, node, stage, pipeline
**Approval**:
@@ -37,7 +53,7 @@ The top-level agent of an Execution, and the only agent that talks to the user.
_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.
An agent responsible for producing one kind of Deliverable, such as the product selector or the target architect. A Specialist may delegate independent parts of its work to further Specialists.
_Avoid_: sub-agent, worker, phase agent, node
### Portability
@@ -53,13 +69,33 @@ _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.
A document an Execution produces: requirements, technical decomposition, product selection, design recommendations, the Target architecture, architecture description, deployment guidance, validation results, or the Solution guide. Each Deliverable depends on others being approved first.
_Avoid_: artifact, output file
**Dependency**:
The relationship between two Deliverables in which one can only be produced once the other has been accepted, for example an architecture diagram depending on the product selection. Within a Phase, a submitted Deliverable counts as accepted. Across Phases, only the earlier Phase's Approval does.
_Avoid_: prerequisite, edge, upstream
**Target architecture**:
The solution to be built, as one explicit graph of Elements, the Relationships between them, and the Checks each must meet. It is established before any infrastructure code is written, and every later Deliverable is derived from it and checked against it.
_Avoid_: build plan, blueprint, design doc, to-be state
**Element**:
One component of the Target architecture and the cloud resource that realises it, with the product selected for it.
_Avoid_: node, resource (alone), box
**Relationship**:
A connection between two Elements, such as calls, publishes to, reads from, or is granted access to.
_Avoid_: edge, link, dependency (which is between Deliverables)
**Check**:
A numbered, verifiable condition that an Element or Relationship must meet, traced to the requirement or design recommendation it comes from. Validation gives each Check a verdict.
_Avoid_: finding, rule, control, test
**Requirements chain**:
The unbroken trace from each requirement, through the components that serve it and the Elements and Checks that realise it, to the code that implements them and the validation verdict on each Check.
_Avoid_: traceability matrix, lineage
**Solution guide**:
The packaged Deliverable that assembles every other Deliverable into the Cloud provider's solution architecture template.
_Avoid_: final report, package

View File

@@ -11,12 +11,15 @@ Vocabulary is defined in [CONTEXT.md](CONTEXT.md), decisions in [docs/adr/](docs
### 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 architecture (design):** `product-selector`, `design-advisor` (which consults one `pillar-advisor` per architecture-framework pillar), `target-architect`.
- **Solution implementation:** `describer`, `iac-author`.
- **Solution validation:** `validator`.
- **Packaging:** `packager`.
Each Phase needs the user's explicit Approval before work that depends on it starts. A pre-approved mode serves batch and evaluation runs.
The design Phase ends with the **Target architecture**: one explicit graph of Elements, Relationships and Checks ([ADR-0005](docs/adr/0005-the-target-architecture-is-an-explicit-graph.md)). The user approves it before any infrastructure code is written. The diagram is drawn from it by code, the Terraform must account for every Check, and validation gives a verdict per Check. Requirements, components, products and recommendations each carry ids in a data file, so every requirement can be traced through to its verdict; a submission with a missing link is refused.
### 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.
@@ -29,7 +32,8 @@ Execution records (status, Ledger events, submitted Deliverables) go to PostgreS
### 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.
- `skills/cloud-discovery/`, `skills/iac-validation/` and `skills/requirements-chain/`: our own Skills for the tooling and the data files.
- `skills/google-cloud-iac-patterns/`: Terraform patterns for Google Cloud products, each validated by a test against the provider version `providers/gcp.yaml` pins.
`app/skills/agent_skills.py` discovers and validates them; the ADK runtime (`app/adk/adk_runtime.py`) loads them on demand. `providers/gcp.yaml` assigns Skills, tools, MCP servers and models to each role in `agents/`.
@@ -38,7 +42,7 @@ The container starts the hierarchical Execution engine (ADR-0003) behind an A2A
- `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.
- `POST /generate`: One-shot, pre-approved Execution for batch and evaluation callers. Pass `customer_case` to group it with the case's other Executions; over A2A, send `customer_case` in the message metadata.
The original linear pipeline and its REST routes (`/card`, `/validate`, `/sessions/{session_id}`) were removed on 2026-10-06; see `.agents/plans/iter-03-kab-layout/`.
@@ -59,9 +63,6 @@ pytest -q
# 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 the A2A Server
@@ -77,7 +78,7 @@ podman build -t gcp-solution-architecture-agent:latest .
```
#### 2. Run Container with Host Deliverables Volume Mount
To ensure execution deliverables (`deliverables/executions/{execution_id}/*`) are written directly to your host machine's workspace:
To ensure Execution outputs (`deliverables/cases/{customer_case}/executions/{execution_id}/*`) are written directly to your host machine's workspace:
```bash
podman run -d --name gcp-agent \
@@ -115,7 +116,7 @@ curl http://localhost:8080/.well-known/agent-card.json
# Run a pre-approved Execution
curl -X POST http://localhost:8080/generate \
-H "Content-Type: application/json" \
-d '{"request": "Event-driven regional HTTP application in Podman"}'
-d '{"request": "Event-driven regional HTTP application in Podman", "customer_case": "acme-webhooks"}'
```
---
@@ -147,23 +148,25 @@ gcp_solution_architecture_agent/
│ ├── 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
│ │ └── source-architecture.mmd
│ ├── target/ # Target Architecture Deliverables (After State)
│ │ ├── requirements.md
│ │ ├── architecture.md
│ │ └── architecture.mmd
│ ├── validation/ # Pre-deployment Validation Reports
│ │ └── validation-results.md
│ ├── guides/ # Consolidate Solution Architecture Guides
│ │ └── solution-architecture-guide.md
│ └── executions/ # Per-Execution Versioned Snapshots ({execution_id}/*)
├── deliverables/
│ └── cases/ # Everything generated, grouped by Customer case
│ └── <customer_case>/
│ ├── intent/ # What the customer asked for, and how it has changed
│ │ ├── 001.md, 002.md # Each request as the customer stated it, in order
│ │ └── history.json # Every request, the Execution it started and how it ended
│ └── executions/<execution_id>/
│ ├── execution.json # Request, status and files of this Execution
│ ├── solution-architecture-guide.md
│ ├── deliverables/<kind>.md # One per Deliverable
│ ├── requirements.json, components.json, products.json, recommendations.json
│ ├── target-architecture.json # Elements, Relationships and Checks
│ ├── architecture.mmd # Drawn from the graph
│ ├── terraform/, implementation.json # The code, and which part meets each Check
│ └── verdicts.json # Validation's verdict on each Check
├── lessons/candidates/<customer_case>/ # Lesson candidates per Execution (gitignored)
├── docs/ # Specifications, audit notes & verification records
├── terraform/ # Deployable GCP Terraform IaC blueprint
├── scripts/
│ └── validate_artifacts.py # Static artifact validation script
├── scripts/ # Vendored-Skill sync, MCP tool listing, Terraform checks
└── tests/ # Unit & integration test suite
```

View File

@@ -3,19 +3,22 @@
Run from the repository root without credentials:
```bash
# 1. Static artifact & guide section validation
python3 scripts/validate_artifacts.py
# 2. Pytest unit & integration test suite
# 1. Pytest unit & integration test suite
pytest -v
# 3. Real-model evaluation of the engine (needs model credentials; costs usage)
# 2. Real-model evaluation of the engine (needs model credentials; costs usage)
python3 -m eval.solution_eval
# 4. Optional Terraform formatting & validation
# 3. Optional Terraform formatting & validation
terraform -chdir=terraform fmt -check -recursive
terraform -chdir=terraform init -backend=false
terraform -chdir=terraform validate
```
`init -backend=false` may download the pinned provider constraint but does not create infrastructure. Do not use `terraform apply` as part of validation. A deployment candidate additionally requires an operator-supplied `terraform plan -out=tfplan` and human review.
## Evaluation options
- `python3 -m eval.solution_eval --judge` adds the judged checks: coverage of each pillar Skill's validation checklist, and a quality rubric for the design recommendations.
- `python3 -m eval.solution_eval case-04-interactive-web-app` runs one case with a scripted user in the loop.
- A case's `thresholds` in `eval/datasets/solution_cases.json` bound its revisions, seconds and tokens; exceeding one is reported as a regression.

View File

@@ -8,4 +8,5 @@ You produce the **technical decomposition** Deliverable: the Skill's breakdown o
- Derive every component from the approved requirements, and name the requirements each component serves.
- Describe components by responsibility, inputs, outputs and interactions.
- Give every component an id and attach them as `components.json`, in the format the requirements-chain Skill gives, with the requirement ids each serves. Every functional requirement must be served by a component.
- Name no products or services; product selection comes later and depends on this decomposition being right.

View File

@@ -6,6 +6,6 @@ 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.
- Describe the Target architecture and nothing else: explain the purpose of each Element and the Relationships between them under a components heading, and the task flow or data flow end to end under a flow heading.
- Use the Element names and products from the Target architecture exactly.
- Ground claims about product behaviour in the Cloud provider's documentation through your documentation tools, with citations.

View File

@@ -7,7 +7,9 @@ includes: [specialist-protocol]
You produce the **design recommendations** Deliverable: the Skill's task for recommending how to configure each component to meet the functional and non-functional requirements.
- Call `consult_pillar_advisors` once, with a brief that restates the workload, the relevant requirements and the selected products. It runs one advisor per architecture-framework pillar in parallel and returns their guidance.
- When `feedback` is not empty you are revising: pass `pillars` naming only the pillars the feedback touches. The guidance you were given before is returned for the others.
- Reconcile the pillars' guidance into recommendations for each component. Where pillars conflict, name the trade-off and recommend a resolution tied to the requirements.
- When an advisor's guidance is missing, derive that pillar's recommendations from the best-practices references in the solution-architecture Skill.
- Give every recommendation an id and attach them as `recommendations.json`, in the format the requirements-chain Skill gives. Write one configurable decision per recommendation, so each can become a Check in the Target architecture.
Required headings, one per pillar: `Security, privacy, and compliance`, `Reliability`, `Operational excellence`, `Cost optimization`, `Performance efficiency`, `Sustainability`.
Your contract's sections are one per pillar.

View File

@@ -1,11 +0,0 @@
---
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.

View File

@@ -1,16 +1,23 @@
---
role: iac-author
deliverable: deployment_guidance
tools: [terraform_fmt, terraform_validate]
budget: 30
tools: [terraform_fmt, terraform_validate, terraform_schema]
budget: 40
includes: [specialist-protocol]
---
You produce the **deployment guidance** Deliverable: the Skill's task for generating infrastructure-as-code and deployment instructions.
- Write Terraform that provisions every selected product with the configuration the design recommendations call for.
- Write Terraform that implements the Target architecture: every Element, every Relationship and every Check, and nothing it does not ask for.
- Before you write a resource, load the infrastructure-as-code patterns Skill when you have one, and start from its pattern for that product and its provider versions file.
- Keep the files in your working copy. Write each file once with `write_file`, and make every later change with `edit_file`, changing only the lines that need it. Never write a file again to fix part of it.
- Format and validate with `terraform_fmt` and `terraform_validate` when they are available. They run on your working copy, so pass them no files. Fix everything they report.
- When validation says an argument or block is not expected, look the resource type up with `terraform_schema` instead of guessing where it belongs.
- When a Check names a setting its resource type does not have, do not invent code for it. Record the Check in `implementation.json` as unimplementable, with what the schema shows, and implement the rest. The Target architecture is then revised.
- Write `implementation.json` to your working copy, in the format the requirements-chain Skill gives, naming where the code satisfies each Check.
- Take every environment-specific value (project, region, names, image references) from variables; embed no credentials or secrets.
- 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.
- Submit as soon as validation passes, with your content and no attachments: your working copy is attached for you. If a submission is refused, fix exactly what the refusal lists and submit again.
- When `working_copy` lists files, they are your last attempt. When `feedback` lists failed Checks, read the files concerned and change only what those Checks need.
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.
Your working copy must hold `terraform/main.tf`, `terraform/variables.tf` and `implementation.json`, with `terraform/versions.tf` and `terraform/outputs.tf` when they help.
Under the prerequisites heading, list the APIs to enable, the tools and the permissions. Under the instructions heading, give commands for the user to run; never run them yourself.

View File

@@ -6,17 +6,20 @@ You coordinate one solution-architecture Execution for the user. You decide what
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`.
Your task message carries JSON context: `workflow_request`, each Deliverable's `status`, `revisions` and `feedback`, each Phase's status, `ready_work`, `phases_ready_for_approval`, `validation` (the verdict on each Check, once validation is submitted), `unimplementable_checks` (Checks the code's author found cannot be met as written), `pending_questions` from Specialists, the recent `conversation`, `notes` about discarded results, `pre_approved` and `allow_cloud_read`.
On each turn, take the first step that applies:
1. **The user asked for changes.** When the latest user message in `conversation` asks to change submitted work, call `reopen` for each affected Deliverable with the user's words as the reason.
2. **Specialists are waiting.** When `pending_questions` is not empty, call `ask_user`. Add your own questions only when the user's last message left something unclear.
3. **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.
3. **The code cannot meet a Check.** When `unimplementable_checks` is not empty, call `reopen` on `target_architecture`, giving each Check's id and reason, then delegate it.
4. **Validation decided.** When `validation` is set and the validation Phase is not yet approved, act on it before asking for Approval:
- `failed` is not empty, or `dry_run.verdict` is `fail`: the code is at fault. Call `reopen` on `deployment_guidance`, giving each failed Check's id and evidence as the reason, then delegate it.
- otherwise `not_verifiable` or `proposed_additions` is not empty: the Target architecture has a gap. When `pre_approved` is `false`, call `ask_user` to ask whether to revise the Target architecture, listing each item. When `pre_approved` is `true`, call `reopen` on `target_architecture` for the items whose reason names a requirement or recommendation id, then delegate it; ignore the rest.
5. **A Phase is complete.** When `phases_ready_for_approval` names a Phase, read its Deliverables with `read_deliverable` and call `request_approval` with a summary a busy architect can approve from. In a pre-approved Execution the approval is granted immediately, and you continue with the next step in the same turn.
6. **Work is ready.** When `ready_work` is not empty, call `delegate` once with every ready Deliverable, so independent work runs in parallel.
7. **Packaging is approved.** Call `finish`.
8. **Otherwise,** call `ask_user` to find out what the user needs.
When the user says a Deliverable already exists, still delegate it; the Specialist submits the user's version. When a tool refuses, read the reason and choose again.

View File

@@ -8,6 +8,7 @@ You produce the **solution guide** Deliverable: the Skill's packaging of every a
- 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.
- Include the architecture diagram, which is the `architecture.mmd` attachment of the Target architecture, unchanged as a `mermaid` code block, and the Terraform as code blocks.
- List the Target architecture's Checks with their validation verdicts in the validation section.
Required headings: the template's eight top-level sections.
Your contract's sections are the template's eight top-level sections.

View File

@@ -5,16 +5,19 @@ You are a Specialist in a solution-architecture Execution. You produce exactly o
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`.
- `dependencies`: every earlier Deliverable your work builds on, by kind. The ones you work from directly come whole, with `content` and `attachments`. The rest come as their data file alone, under `attachments`: the ids to keep traceable. Call `read_deliverable` for the full text of one of those only when the ids are not enough.
- `feedback`: why earlier versions of your Deliverable were revised. Address every item.
- `answers`: the user's replies to questions you asked in earlier runs, oldest first.
- `contract`: what `submit_deliverable` checks. `sections` are headings your content must have and `attachments` are files you must attach. A data file among them must also keep every id traceable to the Deliverables in `dependencies`; the requirements-chain Skill gives each file's format.
- `draft`: the draft you sent the user with your last questions, with its `attachments`, or `null`.
- `working_copy`: what your own tools already hold from your earlier attempts, or `null`. Start from it; do not start again.
- `pre_approved`: `true` when no user is available.
Steps:
1. Load the Skill available to you and find the part that covers your Deliverable. Read the references and assets it points to with `load_skill_resource`.
2. Ground your work in `dependencies`, `feedback` and `answers`. When you need information only the user has, call `needs_input` with all your questions at once, each saying why it matters. Your run ends there, and you are started again with the answers.
3. Draft the Deliverable. 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.
3. Draft the Deliverable to its `contract`. When `pre_approved` is `false`, confirm the draft with the user before submitting: call `needs_input` with a short summary of the draft, asking them to approve it or request changes, and pass the complete draft as `draft` with its `attachments`. When `draft` is set and the latest entry in `answers` approves it, submit that draft as it is; when the user asked for changes, apply them to that draft. When `pre_approved` is `true`, ask nothing: record each assumption under an `Assumptions` heading and continue.
4. Call `submit_deliverable` with the complete markdown content and every attachment in `contract`. When it reports what is missing, add it and submit again.
You are done when `submit_deliverable` accepts the Deliverable.

View File

@@ -10,4 +10,6 @@ You produce the **product selection** Deliverable: the Skill's task for identify
- 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.
Attach `products.json`, in the format the requirements-chain Skill gives, with the one product selected for each component.
Under the products mapping heading, give a table with columns for component, recommended product or feature, justification and citations, alternatives, and their pros and cons.

16
agents/reply-writer.md Normal file
View File

@@ -0,0 +1,16 @@
---
role: reply-writer
tools: []
---
You write what the user reads on behalf of the Orchestrator of a solution-architecture Execution. The decision has already been made; you put it into words and decide nothing.
Your task message carries JSON context: `phase`, the Phase the user is being asked to approve, and `facts`, the data about it: its Deliverables, counts of requirements and recommendations, the Target architecture's counts of Elements, Relationships and Checks with any recommendation treated as not applicable, validation verdicts, and Revisions.
Write a summary a busy architect can approve from:
- Say what the Phase produced and what approving it commits them to. For the design Phase, say that no infrastructure code is written until they approve it.
- State every number in `facts` that bears on the decision, exactly as given. Add no fact that is not there.
- Name anything they should look at before approving: failed or unverifiable Checks, open gaps, recommendations treated as not applicable, Deliverables that were revised.
- Use plain sentences and no headings. Keep it under 120 words.
Call `write_reply` with the summary. You are done when it accepts it.

View File

@@ -7,9 +7,11 @@ 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.
- The user states what they want at a high level; the detail is your job. When a non-functional requirement is missing, propose a default for it from the Cloud provider's architecture framework and record it under `Assumptions` with what it decides: availability tiers, scaling, cost budgets, resource types and security posture. Ask the user to confirm the whole set in one question.
- Ask an open question only where no sensible default can be inferred from the request, such as the region, a compliance regime or a budget ceiling.
- Name every ambiguity or contradiction, explain why the conflicting goals can't both hold, and ask the user to choose. When they delegate the choice, propose one and ask them to approve it.
- When the user runs workloads in a cloud environment today, use your cloud discovery tools to describe the current state from what actually exists, and record anything you couldn't read as a discovery gap.
- Name no products, services or architectures. This Deliverable describes the problem, not the solution.
- Give every requirement an id and attach them all as `requirements.json`, in the format the requirements-chain Skill gives. Use the same ids in your content.
Required headings: `Functional requirements`, `Non-functional requirements`, `Current state`, `Dependencies`. Add `Open questions` and `Assumptions` when they apply.
Add `Open questions` and `Assumptions` headings when they apply.

View File

@@ -0,0 +1,20 @@
---
role: target-architect
deliverable: target_architecture
tools: [terraform_schema]
budget: 30
includes: [specialist-protocol]
---
You produce the **Target architecture** Deliverable: the solution as one explicit graph of Elements, Relationships and Checks. It is agreed before any infrastructure code is written, and the diagram, the description, the code and the validation are all derived from it.
- Load the requirements-chain Skill for the graph's format and how to derive it.
- Build the graph with `graph_put`, a few items per call: the Elements first, then the Relationships, then the Checks one Element at a time. Short calls are what keep your replies from timing out.
- Give every component an Element with the product selected for it, and add the supporting Elements the design needs, such as identities, policies and networks.
- Give every connection between Elements a Relationship.
- Turn every non-functional requirement and every design recommendation into Checks on the Elements and Relationships they constrain. Write each Check so that it can be verified from infrastructure code alone, naming the setting and the value it must have.
- Before you write a Check that names a setting, confirm with `terraform_schema` that the Element's resource type has that setting, when the tool is available. A setting that one resource type has may not exist on a similar one. A Check on a setting the resource type lacks cannot be met and is sent back to you.
- Decide the implementation detail yourself from the design recommendations and the Cloud provider's documentation, through your documentation tools. The user states intent at a high level; this level of detail is your job.
- When a recommendation does not apply to this workload, list it as not applicable with the reason. The user sees that list when they approve the design.
- When `working_copy` shows a graph, it is your last attempt: read it with `graph_read` and change only what `feedback` asks for, with `graph_put` and `graph_remove`.
Your content is short: under your contract's heading, a few paragraphs on the decisions that shaped the design and why. Submit it with no attachments. Your working graph is attached as `target-architecture.json`, and the tables of Elements, Relationships and Checks and the diagram are written from it for you, so never write them yourself.

View File

@@ -1,14 +1,16 @@
---
role: validator
deliverable: validation_results
tools: [terraform_validate, terraform_plan]
tools: [terraform_validate, terraform_plan, terraform_schema]
includes: [specialist-protocol]
---
You produce the **validation results** Deliverable: the Skill's pre-deployment validation, done statically without provisioning anything.
- Run the deployment dry-run with your tools: 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.
- Run the deployment dry-run with your tools: validate the Terraform, and preview it with a plan when you have permission to read live cloud resources. The tools already hold the submitted files, so pass them no files.
- Give a verdict on every Check in the Target architecture, from the infrastructure code: pass, fail or not verifiable, each with the evidence you read. The Checks are the whole bar: judge the code against them and nothing else.
- Before you fail a Check because the code lacks a setting, confirm with `terraform_schema` that the resource type has that setting, when the tool is available. When it does not, the Check cannot be met by any code: give it not verifiable, with what the schema shows as the evidence. Give the same verdict to a Check that `implementation.json` records as unimplementable.
- When you see something the Target architecture lacks, record it as a proposed addition, naming the requirement or recommendation it serves. It is not a failure of the code.
- Attach the verdicts as `verdicts.json`, in the format the requirements-chain Skill gives.
- Give the exact commands for every check you couldn't run, for the user to run themselves.
Required headings: `Deployment dry-run` and `Architecture and policy analysis`, each ending with a pass or fail verdict.
End each of your contract's sections with a pass or fail verdict.

View File

@@ -56,6 +56,7 @@ class SolutionArchitectExecutor(AgentExecutor):
interaction = await self._engine.start(
context.get_user_input(),
session_id=context.context_id,
customer_case=options.get("customer_case"),
execution_id=task_id,
pre_approved=bool(options.get("pre_approved", False)),
allow_cloud_read=options.get("allow_cloud_read"),

View File

@@ -31,6 +31,7 @@ from google.adk.tools.tool_context import ToolContext
from google.genai import types
from app.adk.runtime import (
REJECTION_PREFIXES,
AgentTask,
BudgetExhausted,
Outcome,
@@ -52,13 +53,6 @@ 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)
@@ -244,7 +238,7 @@ class AdkAgentRuntime:
instruction=lambda _context: instructions,
tools=agent_tools,
before_tool_callback=control.before_tool,
generate_content_config=self._content_config(),
generate_content_config=self._content_config(role),
)
runner = Runner(
app_name=APP_NAME,
@@ -299,13 +293,13 @@ class AdkAgentRuntime:
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:
def _content_config(self, role: RoleSpec) -> types.GenerateContentConfig | None:
# A role whose replies are long is given longer than the default.
seconds = role.model_timeout_seconds or self._model_timeout_seconds
if seconds is None:
return None
return types.GenerateContentConfig(
http_options=types.HttpOptions(
timeout=int(self._model_timeout_seconds * 1000)
)
http_options=types.HttpOptions(timeout=int(seconds * 1000))
)

View File

@@ -7,6 +7,7 @@ enforce is exercised exactly as a model would meet it.
from __future__ import annotations
import json
from collections import deque
from collections.abc import Callable, Mapping, Sequence
from dataclasses import dataclass, field
@@ -14,12 +15,15 @@ from typing import Any
from app.adk.runtime import (
AgentTask,
Answer,
BudgetExhausted,
Outcome,
Question,
RoleSpec,
Stopped,
ToolSpec,
)
from app.workflows.deliverables import DEPENDENCY_GRAPH, DeliverableKind
@dataclass(frozen=True)
@@ -31,6 +35,97 @@ class Call:
Turn = Sequence[Call] | Callable[[AgentTask], Sequence[Call]]
# One small, coherent Requirements chain, so sample submissions pass every link.
SAMPLE_DATA: dict[str, str] = {
"requirements.json": json.dumps(
[
{"id": "FR-1", "kind": "functional", "text": "Accept events."},
{"id": "NFR-1", "kind": "non_functional", "text": "99.9% availability."},
]
),
"components.json": json.dumps(
[{"id": "C-1", "name": "Ingress", "requirements": ["FR-1", "NFR-1"]}]
),
"products.json": json.dumps([{"component": "C-1", "product": "Example Run"}]),
"recommendations.json": json.dumps(
[
{
"id": "DR-1",
"pillar": "security",
"text": "Use a dedicated identity.",
"components": ["C-1"],
}
]
),
"target-architecture.json": json.dumps(
{
"elements": [
{
"id": "E-1",
"name": "Ingress service",
"component": "C-1",
"product": "Example Run",
"resource_type": "example_run_service",
},
{
"id": "E-2",
"name": "Ingress identity",
"product": "Example IAM",
"resource_type": "example_service_account",
},
],
"relationships": [
{"id": "R-1", "from": "E-1", "to": "E-2", "kind": "runs as"}
],
"checks": [
{
"id": "K-1",
"applies_to": "E-1",
"statement": "The service runs at least two instances.",
"source": "NFR-1",
},
{
"id": "K-2",
"applies_to": "E-2",
"statement": "The identity is used by this service only.",
"source": "DR-1",
},
],
}
),
"implementation.json": json.dumps(
[
{"check": "K-1", "file": "terraform/main.tf", "address": "example.run"},
{"check": "K-2", "file": "terraform/main.tf", "address": "example.sa"},
]
),
"verdicts.json": json.dumps(
{
"dry_run": {"verdict": "pass", "evidence": "terraform validate passed."},
"checks": [
{"check": "K-1", "verdict": "pass", "evidence": "min instances is 2."},
{"check": "K-2", "verdict": "pass", "evidence": "One binding."},
],
"proposed_additions": [],
}
),
}
def sample_submission(kind: DeliverableKind, note: str = "") -> Call:
"""A `submit_deliverable` call that meets the Deliverable's contract."""
spec = DEPENDENCY_GRAPH[kind]
parts = [f"# {kind}", note or "Summary."]
parts += [f"## {section}\n{note or 'Details.'}" for section in spec.sections]
attachments = {
name: SAMPLE_DATA.get(name, f"# {name}\n") for name in spec.attachments
}
return Call(
"submit_deliverable",
{"content": "\n".join(parts) + "\n", "attachments": attachments},
)
@dataclass(frozen=True)
class RunRecord:
role: str
@@ -87,3 +182,27 @@ class FakeAgentRuntime:
RunRecord(role.name, task, tuple(by_name), tuple(results), outcome)
)
return outcome
class FakeDecider:
"""A scripted Decider: answers by question id, or declines so callers fall back.
`answers` maps a question id to an Answer, or to a function of (state, question)
returning one. An id with no entry makes the whole decision unavailable.
"""
def __init__(self, answers: Mapping[str, Any] | None = None) -> None:
self.answers = dict(answers or {})
self.asked: list[tuple[str, dict[str, Question], str]] = []
async def decide(
self, state: str, questions: Mapping[str, Question], *, scope: str = ""
) -> Mapping[str, Answer] | None:
self.asked.append((state, dict(questions), scope))
decided = {}
for name, question in questions.items():
if name not in self.answers:
return None
answer = self.answers[name]
decided[name] = answer(state, question) if callable(answer) else answer
return decided

View File

@@ -16,6 +16,7 @@ from app.workflows.deliverables import DEPENDENCY_GRAPH, DeliverableKind
ORCHESTRATOR = "orchestrator"
PILLAR_ADVISOR = "pillar-advisor"
REPLY_WRITER = "reply-writer"
PARTIALS_DIR = "partials"
_ALLOWED_FIELDS = {"role", "deliverable", "tools", "budget", "includes"}
@@ -34,7 +35,7 @@ def load_roles(
include_preview_mcp: bool = True,
) -> dict[str, RoleSpec]:
specialists = {spec.specialist: kind for kind, spec in DEPENDENCY_GRAPH.items()}
required = {ORCHESTRATOR, PILLAR_ADVISOR, *specialists}
required = {ORCHESTRATOR, PILLAR_ADVISOR, REPLY_WRITER, *specialists}
roles = {}
for path in sorted(agents_dir.glob("*.md")):
@@ -129,4 +130,5 @@ def _load_role(
for server in bundle.mcp_servers_for_role(name, include_preview_mcp)
),
model=bundle.models.for_role(name),
model_timeout_seconds=bundle.models.timeout_for(name),
)

View File

@@ -6,7 +6,17 @@ 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
import asyncio
import contextvars
from collections.abc import (
AsyncIterator,
Awaitable,
Callable,
Mapping,
MutableMapping,
Sequence,
)
from contextlib import asynccontextmanager
from dataclasses import dataclass, field
from typing import Any, Protocol
@@ -22,6 +32,8 @@ class RoleSpec:
tools: tuple[str, ...] = () # local tool names, e.g. terraform_validate
mcp_servers: tuple[str, ...] = ()
model: str | None = None
# Seconds one model request may take; None takes the runtime's default.
model_timeout_seconds: float | None = None
@dataclass(frozen=True)
@@ -47,10 +59,15 @@ class Submitted:
@dataclass(frozen=True)
class NeedsInput:
"""The agent can't continue without the user. `permission` names a tool tier to grant."""
"""The agent can't continue without the user. `permission` names a tool tier to grant.
`draft` is work the agent wants back when it is started again with the answers.
"""
questions: tuple[str, ...]
permission: str | None = None
draft: str | None = None
draft_attachments: Mapping[str, str] = field(default_factory=dict)
@dataclass(frozen=True)
@@ -127,8 +144,115 @@ class ToolSpec:
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]]
# The tools a role gets beyond the Execution tools, given the Deliverable it is producing
# and that Deliverable's working memory: JSON-compatible data a tool may read and write,
# kept with the Execution across attempts.
ToolFactory = Callable[
[RoleSpec, str | None, MutableMapping[str, Any]], Sequence[ToolSpec]
]
class RunLimiter:
"""Caps how many agent runs are in flight at once.
A run that fans out to further runs lends its slot while it waits, so the cap
holds across the whole hierarchy and a cap of 1 cannot deadlock.
"""
def __init__(self, limit: int) -> None:
if limit < 1:
raise ValueError("limit must be at least 1")
self.limit = limit
self._semaphore = asyncio.Semaphore(limit)
self._holding: contextvars.ContextVar[bool] = contextvars.ContextVar(
"run_limiter_holding", default=False
)
@asynccontextmanager
async def slot(self) -> AsyncIterator[None]:
async with self._semaphore:
token = self._holding.set(True)
try:
yield
finally:
self._holding.reset(token)
@asynccontextmanager
async def lend(self) -> AsyncIterator[None]:
"""Give up the caller's slot, if it holds one, while its own fan-out runs."""
if not self._holding.get():
yield
return
self._semaphore.release()
token = self._holding.set(False)
try:
yield
finally:
self._holding.reset(token)
await self._semaphore.acquire()
# Tool replies that mean the call did nothing. Runtimes log them, and the Execution
# keeps them as lesson candidates.
REJECTION_PREFIXES = (
"Not submitted",
"Refused",
"Discovery gap",
"terraform validate failed",
)
# --- decisions -----------------------------------------------------------------------
@dataclass(frozen=True)
class Question:
"""A closed question about a state. Its answer is typed, never prose.
choice pick one of `options`
score rate against `options`, ordered from lowest to highest
noul yes or no; the answer is the probability that it is yes
"""
kind: str # choice | score | noul
instructions: str
options: tuple[str, ...] = ()
@dataclass(frozen=True)
class Answer:
"""`value` is the chosen option (choice), the level reached (score, as a number
from 0 for the lowest option) or the probability of yes (noul)."""
value: str | float
confidence: float
probabilities: Mapping[str, float] = field(default_factory=dict)
def is_yes(self, threshold: float = 0.5) -> bool:
return isinstance(self.value, (int, float)) and self.value >= threshold
class Decider(Protocol):
"""Answers closed questions about a state (ADR-0007).
Returns None when no decision could be made: the service is not configured,
unreachable, over its budget, or the request is too large. The caller then takes
its fallback; a decider never blocks an Execution. `scope` names what a budget is
counted against, usually the Execution.
"""
async def decide(
self, state: str, questions: Mapping[str, Question], *, scope: str = ""
) -> Mapping[str, Answer] | None: ...
class NoDecider:
"""The decider when none is configured: every caller takes its fallback."""
async def decide(
self, state: str, questions: Mapping[str, Question], *, scope: str = ""
) -> Mapping[str, Answer] | None:
return None
class AgentRuntime(Protocol):

View File

@@ -10,10 +10,11 @@ checkpointers and recorders are chosen, from settings and the provider bundle.
from __future__ import annotations
import dataclasses
import uuid
from collections.abc import AsyncIterator, Mapping, Sequence
from contextlib import asynccontextmanager
from dataclasses import dataclass
from dataclasses import dataclass, field
from pathlib import Path
from typing import Any
@@ -22,13 +23,31 @@ from langgraph.checkpoint.base import BaseCheckpointSaver
from langgraph.types import Command
from app.adk.roles import load_roles
from app.adk.runtime import AgentRuntime, RoleSpec, ToolFactory
from app.adk.runtime import (
AgentRuntime,
Decider,
NoDecider,
RoleSpec,
RunLimiter,
ToolFactory,
)
from app.checkpointing import open_checkpointer
from app.config import Settings
from app.customer_case import record_intent
from app.nodes.router import (
REPLY_WRITER,
OrchestratorPolicy,
Router,
RuntimeReplyWriter,
Thresholds,
)
from app.providers import ProviderBundle, load_provider
from app.recorder import DatabaseRecorder, ExecutionRecorder
from app.skills.agent_skills import skill_version
from app.states.execution_state import check_customer_case
from app.states.ledger import Ledger
from app.tools.execution import ORCHESTRATOR
from app.tools.jev import JevDecider, JevLimits
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
@@ -62,6 +81,9 @@ class ExecutionEngine:
max_revisions: int = 3,
max_orchestrator_turns: int = 100,
tool_factory: ToolFactory | None = None,
limiter: RunLimiter | None = None,
skill_versions: Mapping[str, str] | None = None,
orchestrator: OrchestratorPolicy | None = None,
) -> None:
required = {
ORCHESTRATOR,
@@ -71,6 +93,7 @@ class ExecutionEngine:
if missing:
raise ValueError(f"Missing roles: {', '.join(missing)}")
self._max_revisions = max_revisions
self._output_root = output_root
self._graph = build_execution_graph(
runtime=runtime,
roles=roles,
@@ -78,6 +101,9 @@ class ExecutionEngine:
output_root=output_root,
max_orchestrator_turns=max_orchestrator_turns,
tool_factory=tool_factory,
limiter=limiter,
skill_versions=skill_versions,
orchestrator=orchestrator,
).compile(checkpointer=checkpointer)
async def start(
@@ -85,6 +111,7 @@ class ExecutionEngine:
workflow_request: str,
*,
session_id: str | None = None,
customer_case: str | None = None,
pre_approved: bool = False,
allow_cloud_read: bool | None = None,
execution_id: str | None = None,
@@ -92,14 +119,25 @@ class ExecutionEngine:
) -> Interaction:
"""Start an Execution. `scripted_answers` are (regex, answer) pairs a
pre-approved Execution uses to answer questions, for evaluation runs."""
customer_case = check_customer_case(customer_case)
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
session_id = session_id or str(uuid.uuid4())
intent_version = record_intent(
self._output_root,
customer_case,
execution_id=execution_id,
session_id=session_id,
workflow_request=workflow_request,
)
initial: dict[str, Any] = {
"execution_id": execution_id,
"session_id": session_id or str(uuid.uuid4()),
"session_id": session_id,
"customer_case": customer_case,
"intent_version": intent_version,
"workflow_request": workflow_request,
"pre_approved": pre_approved,
"allow_cloud_read": allow_cloud_read,
@@ -112,9 +150,17 @@ class ExecutionEngine:
"pending_questions": [],
"awaiting_questions": [],
"answers": {},
"drafts": {},
"working": {},
"pending_permission": None,
"prompt": None,
"last_reply": None,
"pending_change": None,
"awaiting_gap_decision": False,
"validation_settled": 0,
"decisions": [],
"outcomes": [],
"refusals": [],
"outcomes_applied": 0,
"events_recorded": 0,
"turns": 0,
@@ -180,6 +226,27 @@ class Assembly:
bundle: ProviderBundle
roles: dict[str, RoleSpec]
mcp_gaps: dict[str, str]
decider: Decider = field(default_factory=NoDecider)
def open_decider(settings: Settings) -> Decider:
"""The Jev client when a key is configured; otherwise a decider that always
sends its caller to the fallback."""
if not settings.TYPESAFE_API_KEY:
return NoDecider()
return JevDecider(
api_key=settings.TYPESAFE_API_KEY,
base_url=settings.TYPESAFE_BASE_URL,
model=settings.TYPESAFE_DEFAULT_MODEL,
limits=dataclasses.replace(
JevLimits(),
request_timeout=settings.JEV_TIMEOUT_SECONDS,
requests_per_second=settings.JEV_REQUESTS_PER_SECOND,
max_in_flight=settings.JEV_MAX_IN_FLIGHT,
budget_calls=settings.JEV_BUDGET_CALLS,
budget_tokens=settings.JEV_BUDGET_TOKENS,
),
)
@asynccontextmanager
@@ -218,17 +285,40 @@ async def open_assembly(
runner = TerraformRunner(
binary=settings.TERRAFORM_BINARY,
timeout_seconds=settings.TERRAFORM_TIMEOUT_SECONDS,
plugin_cache_dir=settings.TF_PLUGIN_CACHE_DIR,
plugin_cache_dir=settings.terraform_plugin_cache(),
providers=bundle.terraform_providers,
)
offered = [name for names in bundle.tools.values() for name in names]
# One cap for Specialists and the pillar advisors they fan out to.
limiter = RunLimiter(settings.MAX_PARALLEL_SPECIALISTS)
tool_factory = make_tool_factory(
runtime,
roles,
bundle.pillar_skills,
local_tools=local_tools(offered, runner),
local_tools=lambda working_copy: local_tools(offered, runner, working_copy),
catalog=catalog,
limiter=limiter,
)
decider = open_decider(settings)
orchestrator: OrchestratorPolicy | None = None
if settings.ORCHESTRATOR == "router":
# The Orchestrator routes: Jev reads, the playbook decides, and a model only
# writes what the user reads. With no Jev key the playbook runs on its rules.
orchestrator = Router(
decider,
RuntimeReplyWriter(runtime, roles[REPLY_WRITER]),
Thresholds(
act=settings.JEV_ACT_THRESHOLD,
close=settings.JEV_CLOSE_THRESHOLD,
confidence=settings.JEV_CONFIDENCE_THRESHOLD,
),
)
elif settings.ORCHESTRATOR != "model":
raise ValueError(
f"ORCHESTRATOR must be router or model, not {settings.ORCHESTRATOR!r}"
)
async with open_checkpointer(settings) as checkpointer:
engine = ExecutionEngine(
runtime=runtime,
@@ -239,5 +329,14 @@ async def open_assembly(
max_revisions=settings.MAX_REVISIONS,
max_orchestrator_turns=settings.MAX_ORCHESTRATOR_TURNS,
tool_factory=tool_factory,
limiter=limiter,
skill_versions={
name: skill_version(meta.path) for name, meta in bundle.skills.items()
},
orchestrator=orchestrator,
)
yield Assembly(engine, bundle, roles, dict(catalog.gaps))
try:
yield Assembly(engine, bundle, roles, dict(catalog.gaps), decider)
finally:
if isinstance(decider, JevDecider):
await decider.aclose()

View File

@@ -38,7 +38,9 @@ class Settings(BaseSettings):
# Local Terraform tools (fmt, validate, plan; never apply)
TERRAFORM_BINARY: str = "terraform"
TERRAFORM_TIMEOUT_SECONDS: float = 300
TF_PLUGIN_CACHE_DIR: str | None = None
# Where Terraform providers are kept between checks, so they download once.
# Relative paths are under the repository root. Set it empty to disable the cache.
TF_PLUGIN_CACHE_DIR: str = ".cache/terraform-plugins"
# Models: a request with no response in this time is abandoned and retried
MODEL_TIMEOUT_SECONDS: float = 180
@@ -51,12 +53,43 @@ class Settings(BaseSettings):
SPECIALIST_BUDGET: int = 15
MAX_REVISIONS: int = 3
MAX_ORCHESTRATOR_TURNS: int = 100
# How an Orchestrator turn is decided (ADR-0007): "router" reads the Execution
# and follows its playbook, with Jev for the judgements; "model" has a language
# model choose the tool calls, as before, and is kept for comparison.
ORCHESTRATOR: str = "router"
# Agent runs in flight at once, pillar advisors included (model rate limits)
MAX_PARALLEL_SPECIALISTS: int = 4
CHECKPOINTER: str = "sqlite" # memory | sqlite | postgres
CHECKPOINT_DB_PATH: str = "checkpoints.db"
# Jev decision service (ADR-0007), reached through TypeSafe AI's Python SDK.
# With no key, every decision takes its fallback and the agent behaves as it does
# without Jev. The key comes from the environment or a secret store, never from
# the provider bundle or the repository.
TYPESAFE_API_KEY: str | None = None
TYPESAFE_BASE_URL: str | None = None # None: the SDK's default endpoint
TYPESAFE_DEFAULT_MODEL: str | None = None # None: the SDK's default model
JEV_TIMEOUT_SECONDS: float = 5.0 # one request
JEV_REQUESTS_PER_SECOND: float = 5.0
JEV_MAX_IN_FLIGHT: int = 8
JEV_BUDGET_CALLS: int = 500 # per Execution
JEV_BUDGET_TOKENS: int = 1_000_000 # per Execution
# A probability at or above ACT is acted on; at or below CLOSE is dropped; in
# between, the user is asked. A choice below CONFIDENCE is not relied on.
JEV_ACT_THRESHOLD: float = 0.75
JEV_CLOSE_THRESHOLD: float = 0.15
JEV_CONFIDENCE_THRESHOLD: float = 0.6
# Paths
BASE_DIR: Path = Path(__file__).resolve().parent.parent
def terraform_plugin_cache(self) -> str | None:
"""The provider cache directory as an absolute path; None when disabled."""
if not self.TF_PLUGIN_CACHE_DIR.strip():
return None
path = Path(self.TF_PLUGIN_CACHE_DIR).expanduser()
return str(path if path.is_absolute() else self.BASE_DIR / path)
def get_database_url(self) -> str:
"""Construct database connection URL (PostgreSQL or SQLite fallback)."""
if self.DATABASE_URL:

105
app/customer_case.py Normal file
View File

@@ -0,0 +1,105 @@
"""A Customer case on disk: its intent and the history of that intent.
deliverables/cases/<customer_case>/
intent/
001.md, 002.md, ... each statement of what the customer wants, as given
history.json every statement in order, the Execution it started
and how that Execution ended
executions/<execution_id>/ what was generated for one statement
The intent is recorded when an Execution starts, so a request is on record even if
nothing was delivered for it. history.json is the index of the case.
"""
from __future__ import annotations
import json
from datetime import UTC, datetime
from pathlib import Path
from typing import Any
from app.states.execution_state import case_dir
INTENT_DIR = "intent"
HISTORY_FILENAME = "history.json"
IN_PROGRESS = "in_progress"
def intent_dir(output_root: Path, customer_case: str) -> Path:
return case_dir(output_root, customer_case) / INTENT_DIR
def read_history(output_root: Path, customer_case: str) -> dict[str, Any]:
"""The case's intent history; empty when the case has none yet."""
path = intent_dir(output_root, customer_case) / HISTORY_FILENAME
if path.is_file():
try:
history = json.loads(path.read_text(encoding="utf-8"))
if isinstance(history, dict) and isinstance(history.get("intents"), list):
return history
except ValueError:
pass
return {"customer_case": customer_case, "intents": []}
def record_intent(
output_root: Path,
customer_case: str,
*,
execution_id: str,
session_id: str,
workflow_request: str,
) -> int:
"""Record a new statement of the customer's intent and return its version."""
folder = intent_dir(output_root, customer_case)
folder.mkdir(parents=True, exist_ok=True)
history = read_history(output_root, customer_case)
version = max((item["version"] for item in history["intents"]), default=0) + 1
recorded_at = datetime.now(UTC).isoformat(timespec="seconds")
statement = f"{version:03d}.md"
(folder / statement).write_text(
f"# Intent {version}: {customer_case}\n\n"
f"- Recorded: {recorded_at}\n"
f"- Execution: `{execution_id}`\n\n"
f"## What the customer wants\n\n{workflow_request.strip()}\n",
encoding="utf-8",
)
history["intents"].append(
{
"version": version,
"recorded_at": recorded_at,
"statement": f"{INTENT_DIR}/{statement}",
"workflow_request": workflow_request,
"execution_id": execution_id,
"session_id": session_id,
"status": IN_PROGRESS,
"execution": None,
}
)
_write_history(folder, history)
return version
def close_intent(
output_root: Path,
customer_case: str,
*,
execution_id: str,
status: str,
has_files: bool,
) -> None:
"""Record how the Execution started by an intent ended, and where its files are."""
history = read_history(output_root, customer_case)
for item in history["intents"]:
if item.get("execution_id") == execution_id:
item["status"] = status
item["execution"] = f"executions/{execution_id}" if has_files else None
_write_history(intent_dir(output_root, customer_case), history)
return
def _write_history(folder: Path, history: dict[str, Any]) -> None:
folder.mkdir(parents=True, exist_ok=True)
(folder / HISTORY_FILENAME).write_text(
json.dumps(history, indent=2, ensure_ascii=False) + "\n", encoding="utf-8"
)

View File

@@ -68,9 +68,12 @@ def create_app(
interaction = await assembly.engine.start(
workflow_request,
session_id=body.get("session_id"),
customer_case=body.get("customer_case"),
pre_approved=True,
allow_cloud_read=bool(body.get("allow_cloud_read", False)),
)
except ValueError as exc:
return JSONResponse({"error": str(exc)}, status_code=400)
except Exception as exc:
logger.exception("/generate failed")
return JSONResponse(

View File

@@ -6,10 +6,12 @@ append outcomes that the next Orchestrator turn applies in order.
from __future__ import annotations
import dataclasses
import json
import logging
import re
import time
from collections.abc import Awaitable, Callable, Mapping, Sequence
from collections.abc import Awaitable, Callable, Mapping, MutableMapping, Sequence
from dataclasses import dataclass
from pathlib import Path
from typing import Any
@@ -17,27 +19,44 @@ from typing import Any
from langgraph.types import Command, Send, interrupt
from app.adk.runtime import (
REJECTION_PREFIXES,
AgentRuntime,
AgentTask,
BudgetExhausted,
NeedsInput,
Outcome,
RoleSpec,
RunLimiter,
Stopped,
Submitted,
ToolFactory,
ToolSpec,
TurnEnded,
)
from app.customer_case import close_intent
from app.nodes.router import ModelOrchestrator, OrchestratorPolicy, TurnView
from app.recorder import ExecutionRecorder
from app.states.execution_state import ExecutionState
from app.states.ledger import Ledger, LedgerRefusal
from app.states.execution_state import (
UNASSIGNED_CASE,
ExecutionState,
execution_dir,
lessons_file,
)
from app.states.ledger import DeliverableStatus, Ledger, LedgerRefusal
from app.states.lessons import collect_lesson_candidates, refusal
from app.tools import workspace
from app.tools.execution import ORCHESTRATOR, OrchestratorToolbox, specialist_tools
from app.workflows.chain import (
IMPLEMENTATION_FILE,
VERDICTS_FILE,
unimplementable_checks,
validation_outcome,
)
from app.workflows.deliverables import (
DEPENDENCY_GRAPH,
PHASE_ORDER,
DeliverableKind,
inputs_of,
dependencies_for,
)
logger = logging.getLogger(__name__)
@@ -47,9 +66,12 @@ NO_USER_REPLY = (
"'Assumptions', and proceed."
)
GUIDE_FILENAME = "solution-architecture-guide.md"
MANIFEST_FILENAME = "execution.json" # request, status and files of one Execution
def _no_tools(role: RoleSpec, deliverable: str | None) -> Sequence[ToolSpec]:
def _no_tools(
role: RoleSpec, deliverable: str | None, working: MutableMapping[str, Any]
) -> Sequence[ToolSpec]:
return ()
@@ -73,8 +95,45 @@ def make_execution_nodes(
output_root: Path,
max_orchestrator_turns: int = 100,
tool_factory: ToolFactory | None = None,
limiter: RunLimiter | None = None,
skill_versions: Mapping[str, str] | None = None,
orchestrator: OrchestratorPolicy | None = None,
) -> ExecutionNodes:
tool_factory = tool_factory or _no_tools
# How an Orchestrator turn is decided. The default drives the tools from the
# Orchestrator role on the runtime; the assembly supplies the router (ADR-0007).
orchestrator = orchestrator or ModelOrchestrator(runtime, roles[ORCHESTRATOR])
def close(state: ExecutionState, status: str, *, has_files: bool) -> None:
close_intent(
output_root,
_case(state),
execution_id=state["execution_id"],
status=status,
has_files=has_files,
)
async def record_lessons(
state: ExecutionState, ledger: Ledger, status: str
) -> None:
record = collect_lesson_candidates(
execution_id=state["execution_id"],
customer_case=_case(state),
status=status,
ledger=ledger,
outcomes=state.get("outcomes", []),
orchestrator_refusals=state.get("refusals", []),
role_skills={name: role.skills for name, role in roles.items()},
skill_versions=skill_versions or {},
)
# Kept apart from deliverables/: an Execution that ends with warnings writes
# no Deliverable files, but what went wrong in it is still worth keeping.
path = lessons_file(output_root, state["execution_id"], _case(state))
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(
json.dumps(record, indent=2, ensure_ascii=False), encoding="utf-8"
)
await recorder.record_lesson_candidates(state["execution_id"], record)
async def record_progress(
state: ExecutionState, ledger: Ledger, status: str | None = None
@@ -102,6 +161,7 @@ def make_execution_nodes(
ledger.revisions(kind) for kind in DEPENDENCY_GRAPH
),
"warnings": state.get("warnings", []),
"customer_case": _case(state),
},
)
return len(ledger.events)
@@ -113,6 +173,7 @@ def make_execution_nodes(
notes = list(state.get("notes", []))
pending_permission = state.get("pending_permission")
warnings = list(state.get("warnings", []))
drafts = dict(state.get("drafts", {}))
outcomes = state.get("outcomes", [])
for record in outcomes[state.get("outcomes_applied", 0) :]:
@@ -124,6 +185,7 @@ def make_execution_nodes(
"content": record["content"],
"attachments": record["attachments"],
}
drafts.pop(kind.value, None)
await recorder.record_submission(
state["execution_id"],
kind.value,
@@ -143,6 +205,11 @@ def make_execution_nodes(
"requested_by": [*requested, kind.value],
}
continue
if record.get("draft"):
drafts[kind.value] = {
"content": record["draft"],
"attachments": record.get("draft_attachments", {}),
}
questions = record.get("questions") or [
(
f"The {record['role']} stopped: {record['summary']} "
@@ -154,6 +221,7 @@ def make_execution_nodes(
turns = state.get("turns", 0) + 1
update: dict[str, Any] = {
"deliverables": deliverables,
"drafts": drafts,
"pending_questions": pending_questions,
"pending_permission": pending_permission,
"outcomes_applied": len(outcomes),
@@ -180,13 +248,35 @@ def make_execution_nodes(
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),
refusals = list(state.get("refusals", []))
update["refusals"] = refusals
view = TurnView(
execution_id=state["execution_id"],
pre_approved=bool(state.get("pre_approved")),
ledger=ledger,
deliverables=deliverables,
pending_questions=pending_questions,
outcomes=outcomes,
last_reply=state.get("last_reply"),
pending_change=state.get("pending_change"),
awaiting_gap_decision=bool(state.get("awaiting_gap_decision")),
validation_settled=int(state.get("validation_settled", 0)),
context=_orchestrator_context(
state, ledger, deliverables, pending_questions, notes
),
)
started = time.monotonic()
outcome = await runtime.run(roles[ORCHESTRATOR], task, toolbox.tools())
decided = await orchestrator.turn(
view, _noting_refusals(toolbox.tools(), refusals, ORCHESTRATOR, None)
)
outcome = decided.outcome
update.update(decided.updates)
if decided.decisions:
# Every decision is kept: what was read, which group applied, what was done.
update["decisions"] = [
*state.get("decisions", []),
*({"turn": turns, **decision} for decision in decided.decisions),
]
logger.info(
"[%s] orchestrator turn %d (%s phase) ended in %.0fs: %s",
state["execution_id"],
@@ -209,7 +299,9 @@ def make_execution_nodes(
sends = [
Send(
"specialist_task",
_specialist_input(state, ledger, deliverables, kind, attempt),
_specialist_input(
state, ledger, deliverables, drafts, kind, attempt
),
)
for kind, attempt in toolbox.started.items()
]
@@ -257,10 +349,27 @@ def make_execution_nodes(
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"],
working: dict[str, Any] = dict(task_input.get("working") or {})
upstream = task_input["context"].get("dependencies") or {}
source = DEPENDENCY_GRAPH[kind].working_copy
if source and source is not kind:
# The tools work on the files as they were last submitted.
working[workspace.FILES] = dict(
upstream.get(source.value, {}).get("attachments", {})
)
refusals: list[dict[str, Any]] = []
tools = _noting_refusals(
specialist_tools(
kind,
extra=tool_factory(role, kind.value, working),
allow_cloud_read=task_input["allow_cloud_read"],
upstream=upstream,
working=working,
library=task_input.get("library"),
),
refusals,
role.name,
kind.value,
)
task = AgentTask(
role=role.name,
@@ -277,7 +386,11 @@ def make_execution_nodes(
)
started = time.monotonic()
try:
outcome: Outcome = await runtime.run(role, task, tools)
if limiter:
async with limiter.slot():
outcome: Outcome = await runtime.run(role, task, tools)
else:
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}")
@@ -291,20 +404,25 @@ def make_execution_nodes(
)
return {
"outcomes": [
_outcome_record(role.name, kind, task_input["attempt"], outcome)
]
{
**_outcome_record(role.name, kind, task_input["attempt"], outcome),
"refusals": refusals,
}
],
"working": {kind.value: working},
}
async def await_user(state: ExecutionState) -> Command:
prompt = state["prompt"] or {}
if state.get("pre_approved"):
reply = _automatic_reply(prompt, state.get("scripted_answers", []))
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}
said: dict[str, Any] | None = None # what the user said, for the next turn
if "approval" in prompt:
phase = prompt["approval"]["phase"]
@@ -322,9 +440,11 @@ def make_execution_nodes(
feedback = str(decision.get("feedback", ""))
ledger.request_changes(phase_id, feedback, actor="user")
text = f"Requested changes to {phase}: {feedback}"
said = {"kind": "changes", "phase": phase, "text": feedback}
conversation.append({"from": "user", "text": text})
else:
conversation.append({"from": "user", "text": _reply_text(reply)})
said = {"kind": "reply", "text": _reply_text(reply)}
elif "permission" in prompt:
tier = prompt["permission"]["tier"]
permission = reply.get("permission") if isinstance(reply, Mapping) else None
@@ -344,6 +464,7 @@ def make_execution_nodes(
else:
text = _reply_text(reply)
conversation.append({"from": "user", "text": text})
said = {"kind": "reply", "text": text}
answers = {
kind: list(items) for kind, items in state.get("answers", {}).items()
}
@@ -353,22 +474,25 @@ def make_execution_nodes(
)
update.update(answers=answers, awaiting_questions=[])
# Only a real user's words are routed; a pre-approved Execution has none.
update["last_reply"] = None if state.get("pre_approved") else said
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", {}),
)
_write_outputs(output_root, state)
close(state, "completed", has_files=True)
await record_progress(state, ledger, "completed")
await record_lessons(state, ledger, "completed")
return {"status": "completed"}
async def end_with_warnings(state: ExecutionState) -> dict[str, Any]:
ledger = Ledger.from_dict(state["ledger"])
close(state, "completed_with_warnings", has_files=False)
await record_progress(state, ledger, "completed_with_warnings")
await record_lessons(state, ledger, "completed_with_warnings")
return {"status": "completed_with_warnings"}
return ExecutionNodes(
@@ -383,6 +507,28 @@ def make_execution_nodes(
# --- helpers ---------------------------------------------------------------------------
def _noting_refusals(
tools: Sequence[ToolSpec],
sink: list[dict[str, Any]],
role: str,
deliverable: str | None,
) -> list[ToolSpec]:
"""The same tools, noting each reply that means the call did nothing."""
def noting(tool: ToolSpec) -> ToolSpec:
async def handler(**kwargs: Any) -> Any:
result = await tool.handler(**kwargs)
if result.outcome is None and result.message.startswith(REJECTION_PREFIXES):
sink.append(
refusal(role, deliverable, tool.name, tool.tier, result.message)
)
return result
return dataclasses.replace(tool, handler=handler)
return [noting(tool) for tool in tools]
def _summarise_outcome(outcome: Outcome) -> str:
if isinstance(outcome, TurnEnded):
return f"called {outcome.tool}"
@@ -405,10 +551,36 @@ def _current_phase(ledger: Ledger) -> str:
def _orchestrator_context(
state: ExecutionState,
ledger: Ledger,
deliverables: Mapping[str, Mapping[str, Any]],
pending_questions: Sequence[Mapping[str, Any]],
notes: Sequence[str],
) -> dict[str, Any]:
# Only a validation that still stands: once anything it judged is reopened, its
# verdicts are about work that no longer exists.
validation = (
deliverables.get(DeliverableKind.VALIDATION_RESULTS.value)
if ledger.status(DeliverableKind.VALIDATION_RESULTS)
is DeliverableStatus.SUBMITTED
else None
)
code = DeliverableKind.DEPLOYMENT_GUIDANCE
return {
# Checks the code's author reported cannot be met as written: faults in the
# Target architecture, known before any validation.
"unimplementable_checks": unimplementable_checks(
deliverables.get(code.value, {})
.get("attachments", {})
.get(IMPLEMENTATION_FILE, "")
)
if ledger.status(code) is DeliverableStatus.SUBMITTED
else [],
# The verdict on each Check, once validation is submitted: failed Checks are
# faults in the code; the rest are gaps in the Target architecture.
"validation": validation_outcome(
validation.get("attachments", {}).get(VERDICTS_FILE, "")
)
if validation
else None,
"workflow_request": state["workflow_request"],
"pre_approved": bool(state.get("pre_approved")),
"allow_cloud_read": state.get("allow_cloud_read"),
@@ -438,25 +610,37 @@ def _specialist_input(
state: ExecutionState,
ledger: Ledger,
deliverables: Mapping[str, Mapping[str, Any]],
drafts: Mapping[str, Mapping[str, Any]],
kind: DeliverableKind,
attempt: int,
) -> dict[str, Any]:
spec = DEPENDENCY_GRAPH[kind]
given = dependencies_for(kind, deliverables)
return {
"execution_id": state["execution_id"],
# The Deliverables given as data files alone, whole, for reading on demand.
"library": {
name: dict(deliverables[name])
for name, deliverable in given.items()
if "content" not in deliverable
},
"role": spec.specialist,
"kind": kind.value,
"attempt": attempt,
"allow_cloud_read": state.get("allow_cloud_read"),
"working": dict(state.get("working", {}).get(kind.value, {})),
"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)
},
"contract": spec.contract(),
"dependencies": given,
"feedback": list(ledger.feedback(kind)),
"answers": list(state.get("answers", {}).get(kind.value, [])),
"draft": dict(drafts[kind.value]) if kind.value in drafts else None,
# What the Specialist's own tools already hold from earlier attempts.
"working_copy": workspace.summary(
state.get("working", {}).get(kind.value, {})
),
"attempt": attempt,
},
}
@@ -479,6 +663,8 @@ def _outcome_record(
"type": "needs_input",
"questions": list(outcome.questions),
"permission": outcome.permission,
"draft": outcome.draft,
"draft_attachments": dict(outcome.draft_attachments),
}
if isinstance(outcome, BudgetExhausted):
return {**base, "type": "budget_exhausted", "summary": outcome.summary}
@@ -495,7 +681,7 @@ def _describe_unfinished(outcome: Outcome) -> str:
return f"Ended with an unexpected outcome: {type(outcome).__name__}."
def _automatic_reply(
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
@@ -543,18 +729,44 @@ def _render_prompt(prompt: Mapping[str, Any]) -> str:
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)
def _case(state: ExecutionState) -> str:
return state.get("customer_case") or UNASSIGNED_CASE
def _write_outputs(output_root: Path, state: ExecutionState) -> None:
"""Write a finished Execution's files under its Customer case, with a manifest
that ties the request to what was generated for it."""
customer_case = _case(state)
execution_id = state["execution_id"]
out_dir = execution_dir(output_root, execution_id, customer_case)
deliverables: Mapping[str, Mapping[str, Any]] = state.get("deliverables", {})
files: dict[str, str] = {}
by_kind: dict[str, dict[str, Any]] = {}
guide = deliverables.get(DeliverableKind.SOLUTION_GUIDE.value)
if guide:
(out_dir / GUIDE_FILENAME).write_text(guide["content"], encoding="utf-8")
files[GUIDE_FILENAME] = guide["content"]
for kind, deliverable in deliverables.items():
path = out_dir / "deliverables" / f"{kind}.md"
document = f"deliverables/{kind}.md"
files[document] = deliverable["content"]
attachments = dict(deliverable.get("attachments", {}))
files.update(attachments)
by_kind[kind] = {"document": document, "attachments": sorted(attachments)}
for name, content in files.items():
path = out_dir / name
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")
path.write_text(content, encoding="utf-8")
manifest = {
"customer_case": customer_case,
"execution_id": execution_id,
"session_id": state.get("session_id"),
"intent_version": state.get("intent_version"),
"workflow_request": state["workflow_request"],
"status": "completed",
"solution_guide": GUIDE_FILENAME if guide else None,
"deliverables": by_kind,
}
out_dir.mkdir(parents=True, exist_ok=True)
(out_dir / MANIFEST_FILENAME).write_text(
json.dumps(manifest, indent=2, ensure_ascii=False), encoding="utf-8"
)

779
app/nodes/router.py Normal file
View File

@@ -0,0 +1,779 @@
"""The Orchestrator as a router (ADR-0007): readings, a disposition, then a playbook.
1. Readings facts about the turn. Most come from the Ledger; the ones that need
judgement (what is the user asking for? does this gap matter?) are
typed answers from the decision model.
2. Disposition code turns a judged reading into act, queue or close, by threshold.
3. Playbook ordered groups. The first group that applies is taken, and within
it the strongest action whose conditions hold. When no group
applies, escalate to the user.
The decision model reads and never acts: every action goes through the Orchestrator's
tools, so the Ledger refuses anything that is not allowed, whatever was decided.
"""
from __future__ import annotations
import logging
import re
from collections.abc import Awaitable, Callable, Mapping, Sequence
from dataclasses import dataclass, field
from typing import Any, Protocol
from app.adk.runtime import (
AgentRuntime,
AgentTask,
Decider,
Outcome,
Question,
RoleSpec,
Stopped,
Submitted,
ToolResult,
ToolSpec,
)
from app.states.ledger import DeliverableStatus, Ledger, PhaseStatus
from app.workflows.chain import (
IMPLEMENTATION_FILE,
RECOMMENDATIONS_FILE,
REQUIREMENTS_FILE,
VERDICTS_FILE,
read_graph,
read_list,
unimplementable_checks,
validation_outcome,
)
from app.workflows.deliverables import DEPENDENCY_GRAPH, DeliverableKind, PhaseId
logger = logging.getLogger(__name__)
ORCHESTRATOR = "orchestrator"
REPLY_WRITER = "reply-writer"
MAX_STEPS = 12 # actions in one turn; a turn that needs more is not making progress
ACT, QUEUE, CLOSE = "act", "queue", "close"
@dataclass(frozen=True)
class Thresholds:
"""Where a probability becomes a disposition."""
act: float = 0.75 # at or above: do it
close: float = 0.15 # at or below: there is nothing to do
confidence: float = 0.6 # a choice below this is not relied on
def disposition(self, probability: float) -> str:
if probability >= self.act:
return ACT
if probability <= self.close:
return CLOSE
return QUEUE
@dataclass(frozen=True)
class TurnView:
"""What one Orchestrator turn can see."""
execution_id: str
pre_approved: bool
ledger: Ledger
deliverables: Mapping[str, Mapping[str, Any]]
pending_questions: Sequence[Mapping[str, Any]]
outcomes: Sequence[Mapping[str, Any]]
last_reply: Mapping[str, Any] | None = None # the user's message, not yet routed
pending_change: Mapping[str, Any] | None = None # a change we asked them to confirm
awaiting_gap_decision: bool = False
validation_settled: int = 0 # the validation attempt already decided on
context: Mapping[str, Any] = field(default_factory=dict) # for a model Orchestrator
@dataclass
class TurnResult:
outcome: Outcome
decisions: list[dict[str, Any]] = field(default_factory=list)
updates: dict[str, Any] = field(default_factory=dict)
class OrchestratorPolicy(Protocol):
async def turn(self, view: TurnView, tools: Sequence[ToolSpec]) -> TurnResult: ...
class ReplyWriter(Protocol):
async def approval_summary(
self, phase: str, facts: Mapping[str, Any]
) -> str | None: ...
# --- readings ------------------------------------------------------------------------
@dataclass
class Readings:
"""Everything the playbook decides from."""
# From the Ledger and the Execution's data.
questions_waiting: bool = False
phases_ready: tuple[PhaseId, ...] = ()
phases_awaiting: tuple[PhaseId, ...] = () # asked for Approval, not yet decided
ready_work: tuple[DeliverableKind, ...] = ()
can_finish: bool = False
validation_attempt: int = 0 # 0 when no validation stands undecided
failed: list[dict[str, Any]] = field(default_factory=list)
repeat_failed: list[dict[str, Any]] = field(default_factory=list)
unverifiable: list[dict[str, Any]] = field(default_factory=list)
additions: list[dict[str, Any]] = field(default_factory=list)
dry_run_failed: bool = False
# Checks the code's author reported cannot be met as the Target architecture
# words them.
unimplementable: list[dict[str, str]] = field(default_factory=list)
# Judged: what the user's message asks for.
change: str = CLOSE # act | queue | close
change_target: DeliverableKind | None = None
change_reason: str = ""
# Judged: whether a gap in the Target architecture is worth a Revision.
gap: str = CLOSE
judged: dict[str, Any] = field(default_factory=dict) # what the decider answered
def _attempt(ledger: Ledger, kind: DeliverableKind) -> int:
return int(ledger.to_dict()["deliverables"][kind.value].get("attempt", 0))
def _submitted(ledger: Ledger) -> list[DeliverableKind]:
return [
kind
for kind in DEPENDENCY_GRAPH
if ledger.status(kind) is DeliverableStatus.SUBMITTED
]
def _mentioned(
text: str, candidates: Sequence[DeliverableKind]
) -> list[DeliverableKind]:
"""Deliverables named outright in a message, as `deployment_guidance` or in words."""
lowered = re.sub(r"[\s_\-]+", " ", text.lower())
return [kind for kind in candidates if kind.value.replace("_", " ") in lowered]
def _failed_before(outcomes: Sequence[Mapping[str, Any]]) -> set[str]:
"""Check ids that failed in the validation before the one that stands now."""
validations = [
record
for record in outcomes
if record.get("type") == "submitted"
and record.get("kind") == DeliverableKind.VALIDATION_RESULTS.value
]
if len(validations) < 2:
return set()
previous = validation_outcome(
validations[-2].get("attachments", {}).get(VERDICTS_FILE, "")
)
return {item["check"] for item in previous["failed"]}
class Router:
"""Decides an Orchestrator turn from readings and a playbook, with no language
model choosing the action. A model, when one is given, only writes what the user
reads."""
def __init__(
self,
decider: Decider,
writer: ReplyWriter | None = None,
thresholds: Thresholds | None = None,
) -> None:
self._decider = decider
self._writer = writer
self._thresholds = thresholds or Thresholds()
async def turn(self, view: TurnView, tools: Sequence[ToolSpec]) -> TurnResult:
by_name = {tool.name: tool for tool in tools}
result = TurnResult(Stopped("The router took no action."))
# A user message is routed once; a confirmation we asked for is consumed.
result.updates = {
"last_reply": None,
"pending_change": None,
"awaiting_gap_decision": False,
}
readings = await self._read(view, result)
blocked: set[str] = set()
settled = view.validation_settled
async def call(tool: str, **arguments: Any) -> ToolResult:
return await by_name[tool].handler(**arguments)
for _ in range(MAX_STEPS):
group, action = self._choose(view, readings, blocked, settled)
result.decisions.append(
{"group": group, "action": action, "judged": dict(readings.judged)}
)
readings.judged = {}
reply = await self._perform(action, view, readings, call, result)
if action == "proceed":
settled = readings.validation_attempt
result.updates["validation_settled"] = settled
self._read_ledger(view, readings, settled)
continue
if reply is None:
return result
if reply.outcome is not None:
result.outcome = reply.outcome
return result
if "revision limit" in reply.message and not view.pre_approved:
# Past the Revision limit the user decides.
limit = await call(
"ask_user", questions=[reply.message.split(" Use ")[0]]
)
if limit.outcome is not None:
result.outcome = limit.outcome
return result
if reply.message.startswith("Refused") or "revision limit" in reply.message:
# Permission is the Ledger's: take the next action that is allowed.
blocked.add(action)
# The action changed the Execution; read the Ledger's facts again.
self._read_ledger(view, readings, settled)
if action in {"revise_requested", "confirm_change"}:
readings.change = CLOSE
result.outcome = Stopped("The router made no progress in this turn.")
return result
# --- readings ---------------------------------------------------------------------
async def _read(self, view: TurnView, result: TurnResult) -> Readings:
readings = Readings()
self._read_ledger(view, readings, view.validation_settled)
await self._read_message(view, readings)
await self._read_gap(view, readings)
return readings
def _read_ledger(self, view: TurnView, readings: Readings, settled: int) -> None:
ledger = view.ledger
readings.questions_waiting = bool(view.pending_questions)
readings.phases_ready = ledger.phases_ready_for_approval()
readings.phases_awaiting = tuple(
phase
for phase in PhaseId
if ledger.phase_status(phase) is PhaseStatus.AWAITING_APPROVAL
)
readings.ready_work = ledger.ready_work()
readings.can_finish = ledger.can_finish()
readings.validation_attempt = 0
readings.failed, readings.repeat_failed = [], []
readings.unverifiable, readings.additions = [], []
readings.dry_run_failed = False
code = DeliverableKind.DEPLOYMENT_GUIDANCE
readings.unimplementable = (
unimplementable_checks(
view.deliverables.get(code.value, {})
.get("attachments", {})
.get(IMPLEMENTATION_FILE, "")
)
if ledger.status(code) is DeliverableStatus.SUBMITTED
else []
)
validation = DeliverableKind.VALIDATION_RESULTS
phase = DEPENDENCY_GRAPH[validation].phase
attempt = _attempt(ledger, validation)
if (
ledger.status(validation) is not DeliverableStatus.SUBMITTED
or ledger.phase_status(phase) is PhaseStatus.APPROVED
or attempt == settled
):
return
outcome = validation_outcome(
view.deliverables.get(validation.value, {})
.get("attachments", {})
.get(VERDICTS_FILE, "")
)
before = _failed_before(view.outcomes)
readings.validation_attempt = attempt
readings.failed = outcome["failed"]
readings.repeat_failed = [f for f in outcome["failed"] if f["check"] in before]
readings.unverifiable = outcome["not_verifiable"]
readings.additions = outcome["proposed_additions"]
readings.dry_run_failed = outcome["dry_run"].get("verdict") == "fail"
async def _read_message(self, view: TurnView, readings: Readings) -> None:
"""Triage of the user's message: is it asking for a change, to what, and how
clearly?"""
reply = view.last_reply
if not reply or view.awaiting_gap_decision:
return
text = str(reply.get("text", "")).strip()
pending = view.pending_change
if pending:
text = f"{pending.get('text', '')}\nThe user then said: {text}"
candidates = _submitted(view.ledger)
if not text or not candidates:
return
readings.change_reason = text
# A structured request for changes is known to be one, and so is the reply to
# our own question about a change they already asked for.
structured = reply.get("kind") == "changes" or bool(pending)
questions = {
"change_target": Question(
"choice",
"Which submitted Deliverable would have to change first to do what "
"the user asks?",
tuple(kind.value for kind in candidates),
),
"change_clarity": Question(
"score",
"How specific is the user about what should change?",
("vague", "partial", "specific"),
),
}
if not structured:
questions["asks_change"] = Question(
"noul",
"Is the user asking for a change to work that has already been "
"submitted, as opposed to answering a question or adding information?",
)
state = (
f"Submitted Deliverables: {', '.join(kind.value for kind in candidates)}.\n"
f"Questions waiting for the user: {len(view.pending_questions)}.\n"
f"The user's message: {text}"
)
answers = await self._decider.decide(state, questions, scope=view.execution_id)
named = _mentioned(text, candidates)
if answers is None:
# No judgement available: act only on what is certain.
if structured:
target = (
candidates[0]
if len(candidates) == 1
else named[0]
if len(named) == 1
else None
)
readings.change = ACT if target else QUEUE
readings.change_target = target
return
readings.judged = {
name: {"value": answer.value, "confidence": answer.confidence}
for name, answer in answers.items()
}
probability = 1.0 if structured else float(answers["asks_change"].value)
disposition = self._thresholds.disposition(probability)
target_answer = answers["change_target"]
target = DeliverableKind(str(target_answer.value))
readings.change_target = target
if disposition == ACT and (
target_answer.confidence < self._thresholds.confidence
or float(answers["change_clarity"].value) < 0.5
):
# They want a change, but which, or what, is not clear enough to act on.
disposition = QUEUE
if disposition == QUEUE and pending:
# Asked once already: act if they named it, otherwise let it go.
disposition = ACT if len(named) == 1 else CLOSE
readings.change_target = named[0] if named else target
readings.change = disposition
async def _read_gap(self, view: TurnView, readings: Readings) -> None:
"""Whether a gap in the Target architecture is worth revising it for."""
if (
readings.failed
or readings.dry_run_failed
or not readings.validation_attempt
):
return
if not (readings.additions or readings.unverifiable):
return
items = "\n".join(
[
f"- proposed addition on {item.get('applies_to')}: "
f"{item.get('statement')} (serves {item.get('reason')})"
for item in readings.additions
]
+ [
f"- Check {item.get('check')} could not be verified: "
f"{item.get('evidence')}"
for item in readings.unverifiable
]
)
reply = view.last_reply if view.awaiting_gap_decision else None
if reply:
question = Question(
"noul",
"Is the user asking for the Target architecture to be revised to "
"close these gaps?",
)
state = f"Gaps found by validation:\n{items}\nThe user's reply: {reply.get('text', '')}"
name = "wants_revision"
else:
question = Question(
"noul",
"Would leaving these gaps open mean a stated requirement or design "
"recommendation is not met?",
)
state = f"Gaps found by validation:\n{items}"
name = "gap_material"
answers = await self._decider.decide(
state, {name: question}, scope=view.execution_id
)
if answers is None:
readings.gap = self._gap_by_rule(view, readings) if not reply else CLOSE
return
readings.judged[name] = {
"value": answers[name].value,
"confidence": answers[name].confidence,
}
disposition = self._thresholds.disposition(float(answers[name].value))
if reply and disposition == QUEUE:
disposition = CLOSE # asked once already; an unclear answer means go on
readings.gap = disposition
@staticmethod
def _gap_by_rule(view: TurnView, readings: Readings) -> str:
"""Without a judgement: a Check that cannot be verified must be fixed, and an
addition counts when it names a real requirement or recommendation."""
if readings.unverifiable:
return ACT
known = {
item["id"]
for name, kind in (
(REQUIREMENTS_FILE, "requirements"),
(RECOMMENDATIONS_FILE, "design_recommendations"),
)
for item in read_list(view.deliverables, kind, name)
if "id" in item
}
for item in readings.additions:
words = set(re.findall(r"[A-Za-z]+-\d+", str(item.get("reason", ""))))
if words & known:
return ACT
return CLOSE
# --- the playbook -----------------------------------------------------------------
def _choose(
self, view: TurnView, r: Readings, blocked: set[str], settled: int
) -> tuple[str, str]:
"""The first group that applies, and within it the strongest action whose
conditions hold. No group applies: escalate."""
interactive = not view.pre_approved
playbook: list[tuple[str, bool, list[tuple[str, bool]]]] = [
(
"the user asked for a change",
r.change in {ACT, QUEUE},
[
(
"revise_requested",
r.change == ACT and r.change_target is not None,
),
("confirm_change", r.change == QUEUE and interactive),
],
),
(
"questions are waiting",
r.questions_waiting,
[("relay_questions", True)],
),
(
# Known as soon as the code is submitted, so no validation is spent
# on a Check that cannot pass.
"the code cannot meet a Check",
bool(r.unimplementable),
[("revise_unimplementable", True)],
),
(
"validation decided",
bool(r.validation_attempt),
[
(
"revise_target_architecture",
bool(r.repeat_failed) or (not r.failed and r.gap == ACT),
),
("revise_code", bool(r.failed) or r.dry_run_failed),
("ask_about_gaps", r.gap == QUEUE and interactive),
("proceed", True),
],
),
(
"a Phase is complete",
bool(r.phases_ready or r.phases_awaiting),
# An Approval is granted only by a structured decision, so a Phase
# still awaiting one is asked for again.
[("request_approval", True)],
),
("work is ready", bool(r.ready_work), [("delegate", True)]),
("packaging is approved", r.can_finish, [("finish", True)]),
]
for group, applies, actions in playbook:
if not applies:
continue
for action, holds in actions:
if holds and action not in blocked:
return group, action
return "no group applies", "escalate"
async def _perform(
self,
action: str,
view: TurnView,
r: Readings,
call: Callable[..., Awaitable[ToolResult]],
result: TurnResult,
) -> ToolResult | None:
if action == "proceed":
return ToolResult("Proceeding.")
if action == "revise_requested":
assert r.change_target is not None
return await call(
"reopen", kind=r.change_target.value, reason=r.change_reason
)
if action == "confirm_change":
guess = r.change_target.value if r.change_target else None
result.updates["pending_change"] = {"text": r.change_reason, "guess": guess}
options = ", ".join(kind.value for kind in _submitted(view.ledger))
question = (
f"Do you want {guess} changed? Reply naming the Deliverable to change "
f"and what should be different. Submitted so far: {options}."
if guess
else "Which Deliverable should change, and what should be different? "
f"Submitted so far: {options}."
)
return await call("ask_user", questions=[question])
if action == "relay_questions":
return await call("ask_user", questions=[])
if action == "revise_code":
items = r.failed or [
{"check": "dry-run", "evidence": "the deployment dry-run failed"}
]
reason = "; ".join(f"{i['check']} failed: {i['evidence']}" for i in items)
return await call(
"reopen", kind=DeliverableKind.DEPLOYMENT_GUIDANCE.value, reason=reason
)
if action == "revise_unimplementable":
reason = " ".join(
f"Check {item['check']} cannot be implemented as written "
f"({item['reason']}). Rewrite it so it can be met, or remove it with "
"a reason."
for item in r.unimplementable
)
return await call(
"reopen", kind=DeliverableKind.TARGET_ARCHITECTURE.value, reason=reason
)
if action == "revise_target_architecture":
return await call(
"reopen",
kind=DeliverableKind.TARGET_ARCHITECTURE.value,
reason=_graph_reason(r),
)
if action == "ask_about_gaps":
result.updates["awaiting_gap_decision"] = True
listed = "; ".join(
[str(i.get("statement")) for i in r.additions]
+ [
f"Check {i.get('check')} could not be verified"
for i in r.unverifiable
]
)
question = (
"Validation passed every Check it could, and found gaps in the "
f"Target architecture: {listed}. Should the Target architecture "
"be revised to close them, or shall I proceed as it stands?"
)
return await call("ask_user", questions=[question])
if action == "request_approval":
phase = (r.phases_ready or r.phases_awaiting)[0]
return await call(
"request_approval",
phase=phase.value,
summary=await self._summary(phase, view, r),
)
if action == "delegate":
return await call("delegate", kinds=[kind.value for kind in r.ready_work])
if action == "finish":
return await call("finish")
# escalate: no group applies.
if view.pre_approved:
result.outcome = Stopped(
"No next step applies and no user is available to decide."
)
return None
return await call(
"ask_user",
questions=["I have no next step to take. What would you like me to do?"],
)
async def _summary(self, phase: PhaseId, view: TurnView, r: Readings) -> str:
facts = approval_facts(phase, view, r)
if self._writer is not None:
try:
written = await self._writer.approval_summary(phase.value, facts)
except Exception: # a summary must never stop an Approval
logger.exception("The reply writer failed; using the assembled summary")
written = None
if written and written.strip():
return written.strip()
return assembled_summary(phase, facts)
def _graph_reason(r: Readings) -> str:
parts = [
f"Check {item['check']} failed in two validations in a row and may not be "
f"implementable as written ({item['evidence']}). Rewrite it so it can be met, "
"or remove it with a reason."
for item in r.repeat_failed
]
if not r.repeat_failed:
parts += [
f"Check {item.get('check')} could not be verified from the code "
f"({item.get('evidence')}). Rewrite it so it can be."
for item in r.unverifiable
]
parts += [
f"Add a Check on {item.get('applies_to')}: {item.get('statement')} "
f"(serves {item.get('reason')})."
for item in r.additions
]
return " ".join(parts)
def approval_facts(phase: PhaseId, view: TurnView, r: Readings) -> dict[str, Any]:
"""What an Approval summary is written from: data, never Deliverable prose."""
kinds = [kind for kind, spec in DEPENDENCY_GRAPH.items() if spec.phase is phase]
facts: dict[str, Any] = {
"phase": phase.value,
"deliverables": [kind.value for kind in kinds],
"revisions": {
kind.value: view.ledger.revisions(kind)
for kind in kinds
if view.ledger.revisions(kind)
},
}
counts = {
"requirements": len(
read_list(view.deliverables, "requirements", REQUIREMENTS_FILE)
),
"recommendations": len(
read_list(view.deliverables, "design_recommendations", RECOMMENDATIONS_FILE)
),
}
facts["counts"] = {name: count for name, count in counts.items() if count}
graph = read_graph(view.deliverables)
if graph is not None:
facts["target_architecture"] = graph.summary()
validation = view.deliverables.get(DeliverableKind.VALIDATION_RESULTS.value)
if (
validation
and phase is DEPENDENCY_GRAPH[DeliverableKind.VALIDATION_RESULTS].phase
):
outcome = validation_outcome(
validation.get("attachments", {}).get(VERDICTS_FILE, "")
)
facts["validation"] = {
"passed": len(outcome["passed"]),
"failed": [item["check"] for item in outcome["failed"]],
"not_verifiable": [item["check"] for item in outcome["not_verifiable"]],
"open_gaps": [
item.get("statement") for item in outcome["proposed_additions"]
],
}
return facts
def assembled_summary(phase: PhaseId, facts: Mapping[str, Any]) -> str:
"""An Approval summary from the facts alone, used when no writer is available."""
lines = [
(
f"The {phase.value} Phase is ready: "
f"{', '.join(facts['deliverables'])} submitted."
)
]
counts = facts.get("counts") or {}
if counts:
lines.append(
", ".join(f"{count} {name}" for name, count in counts.items()) + "."
)
graph = facts.get("target_architecture")
if graph:
lines.append(
f"Target architecture: {graph['elements']} Elements, "
f"{graph['relationships']} Relationships, {graph['checks']} Checks."
)
validation = facts.get("validation")
if validation:
lines.append(
f"Validation: {validation['passed']} Checks passed, "
f"{len(validation['failed'])} failed, "
f"{len(validation['not_verifiable'])} not verifiable."
)
if validation["open_gaps"]:
lines.append(
"Open gaps: " + "; ".join(map(str, validation["open_gaps"])) + "."
)
if facts.get("revisions"):
lines.append(
"Revised: "
+ ", ".join(
f"{kind} × {count}" for kind, count in facts["revisions"].items()
)
+ "."
)
return " ".join(lines)
# --- the two ways an Orchestrator turn can be driven ---------------------------------
class ModelOrchestrator:
"""The Orchestrator as a reasoning agent: a language model chooses the tool calls.
Kept so the Ledger's rules can be driven in any order by a scripted runtime in
tests, and so an evaluation can compare it with the router.
"""
def __init__(self, runtime: AgentRuntime, role: RoleSpec) -> None:
self._runtime = runtime
self._role = role
async def turn(self, view: TurnView, tools: Sequence[ToolSpec]) -> TurnResult:
task = AgentTask(
role=ORCHESTRATOR,
prompt="Decide the next step for this Execution using your tools.",
context=view.context,
)
return TurnResult(await self._runtime.run(self._role, task, tools))
class RuntimeReplyWriter:
"""Writes what the user reads, on a language model. It is given a decision that
has already been made and the facts, and it decides nothing."""
def __init__(self, runtime: AgentRuntime, role: RoleSpec) -> None:
self._runtime = runtime
self._role = role
async def approval_summary(
self, phase: str, facts: Mapping[str, Any]
) -> str | None:
async def write_reply(text: str) -> ToolResult:
if not text.strip():
return ToolResult("Not submitted: the reply is empty.")
return ToolResult("Written.", Submitted(text))
tool = ToolSpec(
"write_reply",
"Give the text the user will read. Ends your turn.",
{
"type": "object",
"properties": {"text": {"type": "string"}},
"required": ["text"],
},
write_reply,
tier="execution",
)
task = AgentTask(
role=REPLY_WRITER,
prompt=f"Write the summary the user will approve the {phase} Phase from.",
context={"phase": phase, "facts": dict(facts)},
)
outcome = await self._runtime.run(self._role, task, [tool])
return outcome.content if isinstance(outcome, Submitted) else None

View File

@@ -27,6 +27,7 @@ def describe_prompt(prompt: Mapping[str, Any]) -> str:
return (
f"Please review the {approval['phase']} Phase: {approval['summary']}\n\n"
f"Deliverables: {', '.join(approval['deliverables'])}.\n\n"
f"{_describe_target_architecture(approval.get('target_architecture'))}"
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."
@@ -46,6 +47,24 @@ def describe_prompt(prompt: Mapping[str, Any]) -> str:
return "\n".join(lines) + "\n\nReply in text; answer every question you can."
def _describe_target_architecture(summary: Mapping[str, Any] | None) -> str:
"""What the design Approval commits to: no code is written until it is granted."""
if not summary:
return ""
text = (
f"The Target architecture has {summary['elements']} Elements, "
f"{summary['relationships']} Relationships and {summary['checks']} Checks. "
"No infrastructure code is written until you approve it; the code is then "
"validated against those Checks.\n\n"
)
for item in summary.get("not_applicable", []):
text += (
f"Recommendation {item['recommendation']} is treated as not applicable: "
f"{item['reason']}\n"
)
return text + ("\n" if summary.get("not_applicable") else "")
def to_generate_response(
interaction: Interaction, roles: Mapping[str, RoleSpec]
) -> dict[str, Any]:
@@ -86,7 +105,7 @@ def to_generate_response(
"requirements_doc": requirements,
"architecture_doc": content(DeliverableKind.ARCHITECTURE_DESCRIPTION),
"mermaid_diagram": attachment(
DeliverableKind.ARCHITECTURE_DIAGRAM, "architecture.mmd"
DeliverableKind.TARGET_ARCHITECTURE, "architecture.mmd"
),
"terraform_code": attachment(
DeliverableKind.DEPLOYMENT_GUIDANCE, "terraform/main.tf"

View File

@@ -42,10 +42,16 @@ class McpServerSpec:
class ModelConfig:
default: str
roles: Mapping[str, str] = field(default_factory=dict)
# Seconds one model request may take, for the roles whose replies are long. A
# role not named here gets the runtime's default.
timeouts: Mapping[str, float] = field(default_factory=dict)
def for_role(self, role: str) -> str:
return self.roles.get(role, self.default)
def timeout_for(self, role: str) -> float | None:
return self.timeouts.get(role)
@dataclass(frozen=True)
class ProviderBundle:
@@ -60,6 +66,9 @@ class ProviderBundle:
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)
# The Terraform providers generated code is written for, pinned so the schema
# lookup, the patterns and validation agree: {name: {source, version}}.
terraform_providers: Mapping[str, Mapping[str, str]] = field(default_factory=dict)
def mcp_servers_for_role(
self, role: str, include_preview: bool = True
@@ -108,10 +117,34 @@ def load_provider(name: str, root: Path | None = None) -> ProviderBundle:
models = config.get("models") or {}
if not isinstance(models.get("default"), str) or not models["default"]:
raise fail("'models.default' is required")
timeouts = {}
for role, seconds in (models.get("timeout_seconds") or {}).items():
if isinstance(seconds, bool) or not isinstance(seconds, (int, float)):
raise fail(f"'models.timeout_seconds' for {role!r} must be a number")
if seconds <= 0:
raise fail(f"'models.timeout_seconds' for {role!r} must be positive")
timeouts[str(role)] = float(seconds)
model_config = ModelConfig(
default=models["default"], roles=dict(models.get("roles") or {})
default=models["default"],
roles=dict(models.get("roles") or {}),
timeouts=timeouts,
)
terraform_providers = {}
pins = (config.get("terraform") or {}).get("required_providers") or {}
for provider, pin in pins.items():
if not isinstance(pin, dict) or not all(
isinstance(pin.get(key), str) and pin[key] for key in ("source", "version")
):
raise fail(
f"terraform provider {provider!r} needs a 'source' and an exact "
"'version', both strings"
)
terraform_providers[str(provider)] = {
"source": pin["source"],
"version": pin["version"],
}
tools = {}
for tier, tool_names in (config.get("tools") or {}).items():
if tier not in TIERS:
@@ -173,4 +206,5 @@ def load_provider(name: str, root: Path | None = None) -> ProviderBundle:
role_mcp_servers=role_mcp_servers,
role_skills=role_skills,
pillar_skills=pillar_skills,
terraform_providers=terraform_providers,
)

View File

@@ -8,6 +8,7 @@ Execution store (review candidate 03) replaces them.
from __future__ import annotations
import asyncio
import json
import uuid
from collections import defaultdict
from collections.abc import Mapping, Sequence
@@ -42,12 +43,22 @@ class ExecutionRecorder(Protocol):
details: Mapping[str, Any],
) -> None: ...
async def record_lesson_candidates(
self, execution_id: str, record: 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)
self.lessons: dict[str, dict[str, Any]] = {}
async def record_lesson_candidates(
self, execution_id: str, record: Mapping[str, Any]
) -> None:
self.lessons[execution_id] = dict(record)
async def record_events(
self, execution_id: str, events: Sequence[LedgerEvent]
@@ -154,3 +165,15 @@ class DatabaseRecorder:
agent_name=SESSION_AGENT_NAME,
state_data={"latest_execution_id": execution_id, "status": status},
)
async def record_lesson_candidates(
self, execution_id: str, record: Mapping[str, Any]
) -> None:
await asyncio.to_thread(
self._db.save_artifact,
artifact_id=str(uuid.uuid4()),
execution_id=execution_id,
artifact_type="lesson_candidates",
file_path="lesson-candidates.json",
content=json.dumps(dict(record), ensure_ascii=False),
)

View File

@@ -6,6 +6,7 @@ Agent Skills specification (https://agentskills.io/specification).
from __future__ import annotations
import hashlib
import re
from collections.abc import Iterable
from dataclasses import dataclass
@@ -123,6 +124,15 @@ def read_skill(skill_dir: Path) -> SkillMeta:
return SkillMeta(name=name, description=description, path=skill_dir)
def skill_version(skill_dir: Path) -> str:
"""A short content hash of every file in the Skill, to say which Skill was loaded."""
digest = hashlib.sha256()
for path in sorted(p for p in skill_dir.rglob("*") if p.is_file()):
digest.update(path.relative_to(skill_dir).as_posix().encode())
digest.update(path.read_bytes())
return digest.hexdigest()[:12]
def discover_skills(directories: Iterable[Path]) -> dict[str, SkillMeta]:
"""Index every Skill that is an immediate child of one of `directories`.

View File

@@ -3,12 +3,58 @@
from __future__ import annotations
import operator
import re
from pathlib import Path
from typing import Annotated, Any, TypedDict
# A Customer case id becomes a directory name, so it is a short lowercase slug.
CUSTOMER_CASE = re.compile(r"^[a-z0-9](?:[a-z0-9-]{0,62}[a-z0-9])?$")
# Executions started without a Customer case are grouped here, so every Execution's
# files sit under a case.
UNASSIGNED_CASE = "unassigned"
def check_customer_case(customer_case: object) -> str:
"""The Customer case id, defaulting to UNASSIGNED_CASE; a ValueError when it is
not a safe slug."""
if customer_case is None:
return UNASSIGNED_CASE
if not isinstance(customer_case, str) or not CUSTOMER_CASE.match(customer_case):
raise ValueError(
"customer_case must be 1 to 64 lowercase letters, digits or hyphens, "
f"starting and ending with a letter or digit; got {customer_case!r}"
)
return customer_case
def case_dir(output_root: Path, customer_case: str) -> Path:
"""Everything generated for one Customer case."""
return output_root / "deliverables" / "cases" / customer_case
def execution_dir(output_root: Path, execution_id: str, customer_case: str) -> Path:
"""Where one Execution's files go, under its Customer case."""
return case_dir(output_root, customer_case) / "executions" / execution_id
def lessons_file(output_root: Path, execution_id: str, customer_case: str) -> Path:
return (
output_root / "lessons" / "candidates" / customer_case / f"{execution_id}.json"
)
def merge_by_key(
current: dict[str, dict[str, Any]] | None, update: dict[str, dict[str, Any]] | None
) -> dict[str, dict[str, Any]]:
"""Parallel Specialist tasks each write their own Deliverable's entry."""
return {**(current or {}), **(update or {})}
class ExecutionState(TypedDict, total=False):
execution_id: str
session_id: str
customer_case: str # the Customer case this Execution belongs to
intent_version: int # which statement of the case's intent started this Execution
workflow_request: str
pre_approved: bool
allow_cloud_read: bool | None
@@ -21,6 +67,11 @@ class ExecutionState(TypedDict, total=False):
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}]
drafts: dict[
str, dict[str, Any]
] # kind -> {content, attachments} awaiting the user
# kind -> working memory its tools keep across attempts (e.g. pillar advice)
working: Annotated[dict[str, dict[str, Any]], merge_by_key]
pending_permission: dict[str, Any] | None # {tier, requested_by}
prompt: dict[str, Any] | None # what the user is being asked
@@ -28,8 +79,16 @@ class ExecutionState(TypedDict, total=False):
# applied to the Ledger by the next Orchestrator turn.
outcomes: Annotated[list[dict[str, Any]], operator.add]
outcomes_applied: int
refusals: list[dict[str, Any]] # the Orchestrator's refused tool calls
events_recorded: int
# Routing (ADR-0007).
last_reply: dict[str, Any] | None # the user's message, until a turn routes it
pending_change: dict[str, Any] | None # a change the user was asked to confirm
awaiting_gap_decision: bool # the user was asked whether to close gaps
validation_settled: int # the validation attempt already decided on
decisions: list[dict[str, Any]] # every routing decision, in order
turns: int
status: str # running | completed | completed_with_warnings
warnings: list[str]

125
app/states/lessons.py Normal file
View File

@@ -0,0 +1,125 @@
"""Lesson candidates: what went wrong in an Execution and what was asked to fix it.
Collected once, when the Execution ends, from what the Execution already holds: the
Ledger's events, the Specialists' outcome records and the tool refusals. They are raw
material for a reviewed change to a Skill, never memory carried into another Execution.
"""
from __future__ import annotations
from collections.abc import Mapping, Sequence
from typing import Any
from app.states.ledger import Ledger
from app.workflows.chain import VERDICTS_FILE, validation_outcome
from app.workflows.deliverables import (
DEPENDENCY_GRAPH,
DeliverableKind,
PhaseId,
)
MESSAGE_LIMIT = 500
_UNFINISHED = {"budget_exhausted", "stopped"}
def refusal(
role: str, deliverable: str | None, tool: str, tier: str, message: str
) -> dict[str, Any]:
"""One tool refusal, as stored in Execution state.
A cloud-read tool's message may describe the user's environment, so only its
leading words are kept.
"""
if tier == "cloud_read":
message = message.split(":", 1)[0]
return {
"role": role,
"deliverable": deliverable,
"tool": tool,
"message": message[:MESSAGE_LIMIT],
}
def collect_lesson_candidates(
*,
execution_id: str,
customer_case: str,
status: str,
ledger: Ledger,
outcomes: Sequence[Mapping[str, Any]],
orchestrator_refusals: Sequence[Mapping[str, Any]],
role_skills: Mapping[str, Sequence[str]],
skill_versions: Mapping[str, str],
) -> dict[str, Any]:
candidates: list[dict[str, Any]] = []
for event in ledger.events:
if event.type == "reopened":
candidates.append(
{
"type": "revision",
"deliverable": event.subject,
"reason": event.detail,
"requested_by": event.actor,
}
)
elif event.type == "escalated":
candidates.append(
{
"type": "revision_limit",
"deliverable": event.subject,
"reason": event.detail,
}
)
elif event.type == "changes_requested":
candidates.append(
{
"type": "change_request",
"phase": event.subject,
"deliverables": [
kind.value
for kind, spec in DEPENDENCY_GRAPH.items()
if spec.phase is PhaseId(event.subject)
],
"feedback": event.detail,
}
)
elif event.type == "released" and event.detail in _UNFINISHED:
candidates.append(
{
"type": "unfinished",
"deliverable": event.subject,
"role": event.actor,
"reason": event.detail,
}
)
for record in outcomes:
for item in record.get("refusals", ()):
candidates.append({"type": "refusal", **item})
if (
record.get("type") == "submitted"
and record.get("kind") == DeliverableKind.VALIDATION_RESULTS.value
):
outcome = validation_outcome(
record.get("attachments", {}).get(VERDICTS_FILE, "")
)
attempt = record.get("attempt")
for kind, items in (
("failed_check", outcome["failed"]),
("unverifiable_check", outcome["not_verifiable"]),
("proposed_addition", outcome["proposed_additions"]),
):
for item in items:
candidates.append({"type": kind, "attempt": attempt, **item})
for item in orchestrator_refusals:
candidates.append({"type": "refusal", **item})
return {
"execution_id": execution_id,
"customer_case": customer_case,
"status": status,
"role_skills": {role: list(skills) for role, skills in role_skills.items()},
"skill_versions": dict(skill_versions),
"candidates": candidates,
}

View File

@@ -7,8 +7,7 @@ outcome.
from __future__ import annotations
from collections.abc import Mapping, Sequence
from pathlib import PurePosixPath
from collections.abc import Mapping, MutableMapping, Sequence
from typing import Any
from app.adk.runtime import (
@@ -21,6 +20,14 @@ from app.adk.runtime import (
files_from_argument,
)
from app.states.ledger import Ledger, LedgerRefusal, PhaseStatus
from app.tools.workspace import (
file_tools,
graph_text,
graph_tools,
keep_graph,
safe_relative,
working_files,
)
from app.workflows.deliverables import (
DEPENDENCY_GRAPH,
DeliverableKind,
@@ -28,8 +35,18 @@ from app.workflows.deliverables import (
check_submission,
deliverables_in,
)
from app.workflows.target_architecture import (
DIAGRAM_ATTACHMENT,
GRAPH_ATTACHMENT,
GraphError,
TargetArchitecture,
parse_graph,
render_mermaid,
render_tables,
)
ORCHESTRATOR = "orchestrator"
_TARGET = DeliverableKind.TARGET_ARCHITECTURE
CLOUD_READ = "cloud_read"
_NO_ARGS: Mapping[str, Any] = {"type": "object", "properties": {}}
@@ -186,10 +203,23 @@ class OrchestratorToolbox:
"summary": summary,
"deliverables": [kind.value for kind in deliverables_in(phase_id)],
}
graph = self._target_architecture()
if graph and phase_id is DEPENDENCY_GRAPH[_TARGET].phase:
# What the user is approving before any code is written.
self.approval["target_architecture"] = graph.summary()
return ToolResult(
f"Asked the user to approve {phase_id}.", TurnEnded("request_approval")
)
def _target_architecture(self) -> TargetArchitecture | None:
deliverable = self._deliverables.get(_TARGET.value)
if not deliverable:
return None
try:
return parse_graph(deliverable.get("attachments", {})[GRAPH_ATTACHMENT])
except (KeyError, GraphError):
return None
async def reopen(self, kind: str, reason: str) -> ToolResult:
try:
result = self.ledger.reopen(
@@ -222,41 +252,84 @@ class OrchestratorToolbox:
return ToolResult("Finishing the Execution.", TurnEnded("finish"))
def _safe_relative(name: str) -> bool:
path = PurePosixPath(name)
return bool(name) and not path.is_absolute() and ".." not in path.parts
def specialist_tools(
kind: DeliverableKind,
extra: Sequence[ToolSpec],
allow_cloud_read: bool | None,
upstream: Mapping[str, Mapping[str, Any]] | None = None,
working: MutableMapping[str, Any] | None = None,
library: Mapping[str, Mapping[str, Any]] | None = None,
) -> list[ToolSpec]:
"""A Specialist's tools: submit, ask, and its role's tools with the cloud-read gate."""
"""A Specialist's tools: submit, ask, its working copy, and its role's tools with
the cloud-read gate.
`upstream` is the Deliverables this one builds on; with it, a submission's links
along the Requirements chain are checked. `working` is the Deliverable's working
memory, where its working copy is kept. `library` is the earlier Deliverables
given to the Specialist as data files alone, to read whole when it needs one.
"""
working = {} if working is None else working
is_graph = kind is DeliverableKind.TARGET_ARCHITECTURE
own_files = DEPENDENCY_GRAPH[kind].working_copy is kind
async def submit_deliverable(content: str, attachments: Any = None) -> ToolResult:
try:
attachments = files_from_argument(attachments)
except TypeError as exc:
return _refused(f"attachments: {exc}")
unsafe = [name for name in attachments if not _safe_relative(name)]
# The working copy is the submission; a file passed here replaces its copy.
if own_files:
attachments = {**working_files(working), **attachments}
if is_graph and GRAPH_ATTACHMENT not in attachments and graph_text(working):
attachments[GRAPH_ATTACHMENT] = graph_text(working)
unsafe = [name for name in attachments if not safe_relative(name)]
if unsafe:
return _refused(
"attachment names must be relative paths without '..': "
+ ", ".join(unsafe)
)
missing = check_submission(kind, content, attachments)
missing = check_submission(kind, content, attachments, upstream)
if missing:
return ToolResult(
"Not submitted. The Deliverable is missing: " + "; ".join(missing)
)
if own_files:
working_files(working).update(attachments)
if is_graph:
# The tables and the diagram are views of the graph, so the engine
# writes them: they cannot disagree with it.
graph = parse_graph(attachments[GRAPH_ATTACHMENT])
keep_graph(working, attachments[GRAPH_ATTACHMENT])
content = content.rstrip() + "\n\n" + render_tables(graph)
attachments[DIAGRAM_ATTACHMENT] = render_mermaid(graph)
return ToolResult(f"Submitted {kind}.", Submitted(content, attachments))
async def needs_input(questions: Sequence[str]) -> ToolResult:
async def read_deliverable(kind: str) -> ToolResult:
deliverable = (library or {}).get(kind)
if deliverable is None:
available = ", ".join(library or {}) or "none"
return _refused(f"{kind} is not one you can read here: {available}")
attached = ", ".join(deliverable.get("attachments", {})) or "none"
return ToolResult(
f"{deliverable.get('content', '')}\n\nAttachments: {attached}"
)
async def needs_input(
questions: Sequence[str], draft: str | None = None, attachments: Any = None
) -> ToolResult:
questions = tuple(q for q in questions if q)
if not questions:
return _refused("ask at least one question")
return ToolResult("Questions sent to the user.", NeedsInput(questions))
try:
draft_attachments = files_from_argument(attachments)
except TypeError as exc:
return _refused(f"attachments: {exc}")
return ToolResult(
"Questions sent to the user.",
NeedsInput(
questions, draft=draft or None, draft_attachments=draft_attachments
),
)
return [
ToolSpec(
@@ -274,14 +347,37 @@ def specialist_tools(
),
ToolSpec(
"needs_input",
"Ask the user questions you can't proceed without. Ends your turn.",
"Ask the user questions you can't proceed without. Ends your turn. When "
"you are asking them to confirm a draft, pass it as `draft` (with its "
"`attachments`): it is returned to you with their answers.",
_schema(
{"questions": {"type": "array", "items": {"type": "string"}}},
{
"questions": {"type": "array", "items": {"type": "string"}},
"draft": {"type": "string"},
"attachments": FILES_SCHEMA,
},
["questions"],
),
needs_input,
tier="execution",
),
*(
[
ToolSpec(
"read_deliverable",
"Read the full text of an earlier Deliverable that `dependencies` "
"gives you as its data file alone: "
f"{', '.join(library)}. Use it only when the ids are not enough.",
_schema({"kind": {"type": "string"}}, ["kind"]),
read_deliverable,
tier="execution",
)
]
if library
else ()
),
*(graph_tools(working) if is_graph else ()),
*(file_tools(working) if own_files else ()),
*(gate_cloud_read(tool, allow_cloud_read) for tool in extra),
]

327
app/tools/jev.py Normal file
View File

@@ -0,0 +1,327 @@
"""The Jev decision client: typed answers to closed questions, within strict limits.
Jev is TypeSafe AI's decision model. This module is the only one that speaks to it,
through the vendor's Python SDK (`typesafe-sdk`), which owns the request shape, the
timeout and the retries. Everything else here is ours: the service's limits are not
published, so the client assumes they are strict and never lets Jev hold up an
Execution. Any refusal, failure or timeout returns None and the caller takes its
fallback.
"""
from __future__ import annotations
import asyncio
import hashlib
import json
import logging
import time
from collections import OrderedDict, deque
from collections.abc import Awaitable, Callable, Mapping
from dataclasses import dataclass, field
from typing import Any
from typesafe_sdk import (
AsyncTypeSafeClient,
Choice,
ChoiceAnswer,
Noul,
NoulAnswer,
RetryPolicy,
Score,
ScoreAnswer,
TypeSafeError,
TypeSafeRateLimitError,
)
from app.adk.runtime import Answer, Question
logger = logging.getLogger(__name__)
@dataclass(frozen=True)
class JevLimits:
"""Every limit the client keeps. Starting values, to tune from measurement."""
max_tokens: int = 48_000 # state plus questions; the service allows 64,000
max_question_tokens: int = 24_000 # state plus the longest question; allows 32,000
request_timeout: float = 5.0 # one HTTP attempt
total_timeout: float = 15.0 # a decision, retries included
retries: int = 2
backoff_base: float = 0.5
backoff_cap: float = 8.0
requests_per_second: float = 5.0
burst: int = 10
max_in_flight: int = 8
breaker_failures: int = 5
breaker_window: float = 30.0
breaker_cooldown: float = 60.0
cache_size: int = 1024
budget_calls: int = 500 # per scope, usually one Execution
budget_tokens: int = 1_000_000 # per scope; about $0.42 at the published price
@dataclass
class DecisionRecord:
"""One attempt to decide, kept for the evaluation report and for tuning."""
scope: str
questions: tuple[str, ...]
# answered | cached | too_large | over_budget | breaker_open | failed
outcome: str = "failed"
seconds: float = 0.0
rate_limited: bool = False
input_tokens: int = 0
confidence: Mapping[str, float] = field(default_factory=dict)
def estimate_tokens(text: str) -> int:
"""A deliberately high estimate: refusing locally is cheaper than a rejected call."""
return len(text) // 3 + 1
def encode_question(question: Question) -> Noul | Choice | Score:
if question.kind == "choice":
return Choice(
instructions=question.instructions,
criteria=dict.fromkeys(question.options),
)
if question.kind == "score":
return Score(
instructions=question.instructions, criteria=list(question.options)
)
return Noul(instructions=question.instructions)
def decode_answer(question: Question, raw: object) -> Answer | None:
"""The SDK's answer as ours, or None when it does not answer the question asked."""
if question.kind == "choice" and isinstance(raw, ChoiceAnswer):
# A choice outside the options asked for is not an answer.
if raw.choice not in question.options:
return None
return Answer(raw.choice, raw.confidence, dict(raw.probabilities))
if question.kind == "score" and isinstance(raw, ScoreAnswer):
probabilities = {str(level): p for level, p in raw.probabilities.items()}
return Answer(raw.score, raw.confidence, probabilities)
if question.kind == "noul" and isinstance(raw, NoulAnswer):
# Jev gives a probability for a yes-or-no question and no separate
# confidence, so confidence is how far the probability is from even.
return Answer(raw.noul, abs(2 * raw.noul - 1))
return None
class JevDecider:
def __init__(
self,
*,
api_key: str,
base_url: str | None = None,
model: str | None = None,
limits: JevLimits | None = None,
transport: Any = None,
clock: Callable[[], float] = time.monotonic,
sleep: Callable[[float], Awaitable[None]] = asyncio.sleep,
) -> None:
self.limits = limits or JevLimits()
self._clock = clock
self._sleep = sleep
self._client = AsyncTypeSafeClient(
api_key=api_key,
base_url=base_url,
model=model,
timeout=self.limits.request_timeout,
# The SDK retries 408, 429 and 5xx, and connection and timeout errors,
# with jittered backoff, and honours Retry-After.
retry=RetryPolicy(
max_retries=self.limits.retries,
backoff_initial=self.limits.backoff_base,
backoff_max=self.limits.backoff_cap,
timeout=self.limits.total_timeout,
),
transport=transport,
)
self._in_flight = asyncio.Semaphore(self.limits.max_in_flight)
# Token bucket: starts full, refills at `rate`, which drops when the service
# says we are going too fast.
self._rate = self.limits.requests_per_second
self._tokens = float(self.limits.burst)
self._refilled = clock()
self._bucket = asyncio.Lock()
self._failures: deque[float] = deque()
self._open_until = 0.0
self._probing = False
self._cache: OrderedDict[str, dict[str, Answer]] = OrderedDict()
self._calls: dict[str, int] = {}
self._tokens_used: dict[str, int] = {}
self._over_budget: set[str] = set()
self.records: list[DecisionRecord] = []
async def aclose(self) -> None:
await self._client.aclose()
async def decide(
self, state: str, questions: Mapping[str, Question], *, scope: str = ""
) -> Mapping[str, Answer] | None:
record = DecisionRecord(scope=scope, questions=tuple(questions))
self.records.append(record)
started = self._clock()
try:
return await self._decide(state, questions, scope, record)
finally:
record.seconds = self._clock() - started
async def _decide(
self,
state: str,
questions: Mapping[str, Question],
scope: str,
record: DecisionRecord,
) -> Mapping[str, Answer] | None:
if not questions:
record.outcome = "answered"
return {}
asked = {
name: {
"kind": question.kind,
"instructions": question.instructions,
"options": list(question.options),
}
for name, question in questions.items()
}
sizes = [estimate_tokens(json.dumps(item)) for item in asked.values()]
state_size = estimate_tokens(state)
if (
state_size + sum(sizes) > self.limits.max_tokens
or state_size + max(sizes) > self.limits.max_question_tokens
):
# Never truncate: the caller must split by Deliverable or section.
record.outcome = "too_large"
return None
key = hashlib.sha256(
json.dumps({"state": state, "questions": asked}, sort_keys=True).encode()
).hexdigest()
if key in self._cache:
self._cache.move_to_end(key)
record.outcome = "cached"
return dict(self._cache[key])
if (
self._calls.get(scope, 0) >= self.limits.budget_calls
or self._tokens_used.get(scope, 0) >= self.limits.budget_tokens
):
if scope not in self._over_budget:
self._over_budget.add(scope)
logger.warning("Jev budget reached for %s; using fallbacks", scope)
record.outcome = "over_budget"
return None
if not self._breaker_allows():
record.outcome = "breaker_open"
return None
self._calls[scope] = self._calls.get(scope, 0) + 1
await self._take_token()
try:
async with self._in_flight:
response = await self._client.system_one(
state=state,
questions={
name: encode_question(question)
for name, question in questions.items()
},
)
except TypeSafeRateLimitError:
# Still rate limited after the SDK's retries: halve our own rate.
record.rate_limited = True
self._rate = max(self._rate / 2, 0.25)
self._note_failure()
return None
except TypeSafeError as exc:
logger.info("Jev request failed: %s", type(exc).__name__)
self._note_failure()
return None
self._note_success()
used = response.usage.input_tokens or 0
record.input_tokens = used
self._tokens_used[scope] = self._tokens_used.get(scope, 0) + used
answers: dict[str, Answer] = {}
for name, question in questions.items():
answer = decode_answer(question, response.answers.get(name))
if answer is None:
# A reply that does not answer every question answers none.
return None
answers[name] = answer
record.outcome = "answered"
record.confidence = {name: a.confidence for name, a in answers.items()}
self._cache[key] = answers
while len(self._cache) > self.limits.cache_size:
self._cache.popitem(last=False)
return dict(answers)
async def _take_token(self) -> None:
async with self._bucket:
while True:
now = self._clock()
self._tokens = min(
float(self.limits.burst),
self._tokens + (now - self._refilled) * self._rate,
)
self._refilled = now
if self._tokens >= 1:
self._tokens -= 1
return
await self._sleep((1 - self._tokens) / self._rate)
def _breaker_allows(self) -> bool:
now = self._clock()
if now < self._open_until:
return False
if self._open_until and not self._probing:
# Cool-down over: let exactly one call through to test the service.
self._probing = True
return True
def _note_failure(self) -> None:
now = self._clock()
if self._probing:
self._probing = False
self._open_until = now + self.limits.breaker_cooldown
return
self._failures.append(now)
while self._failures and now - self._failures[0] > self.limits.breaker_window:
self._failures.popleft()
if len(self._failures) >= self.limits.breaker_failures:
self._failures.clear()
self._open_until = now + self.limits.breaker_cooldown
logger.warning(
"Jev circuit open for %.0fs after repeated failures",
self.limits.breaker_cooldown,
)
def _note_success(self) -> None:
self._failures.clear()
self._open_until = 0.0
self._probing = False
def summary(self) -> dict[str, Any]:
"""Totals for the evaluation report."""
outcomes: dict[str, int] = {}
for record in self.records:
outcomes[record.outcome] = outcomes.get(record.outcome, 0) + 1
answered = [r for r in self.records if r.outcome == "answered"]
return {
"decisions": len(self.records),
"outcomes": outcomes,
"fallbacks": sum(
count
for name, count in outcomes.items()
if name not in {"answered", "cached"}
),
"rate_limited": sum(1 for r in self.records if r.rate_limited),
"seconds": round(sum(r.seconds for r in answered), 3),
"input_tokens": sum(r.input_tokens for r in self.records),
}

View File

@@ -1,17 +1,24 @@
"""Local tools: a Mermaid syntax check and Terraform checks in a scratch directory.
Terraform runs only fmt, init -backend=false, validate and plan. No command that
changes cloud resources is ever constructed.
Terraform runs only fmt, init -backend=false, validate, plan and providers schema. No
command that changes cloud resources is ever constructed.
A Specialist with a working copy (app/tools/workspace.py) runs the checks on it and
passes no files; `terraform_fmt` formats the working copy in place. That is what
keeps a fix cheap: the model changes a line and validates, without sending every file
again on each call.
"""
from __future__ import annotations
import asyncio
import difflib
import json
import os
import re
import tempfile
from collections.abc import Awaitable, Callable, Iterable, Mapping
from dataclasses import dataclass
from collections.abc import Awaitable, Callable, Iterable, Mapping, MutableMapping
from dataclasses import dataclass, field
from pathlib import Path, PurePosixPath
from typing import Any
@@ -76,9 +83,22 @@ async def mermaid_check(diagram: str) -> ToolResult:
class TerraformRunner:
binary: str = "terraform"
timeout_seconds: float = 300
# Providers are downloaded here once and reused by every later check. Without it,
# each validate or plan downloads its providers again into a scratch directory.
plugin_cache_dir: str | None = None
# The providers the schema lookup answers for, as the provider bundle pins them:
# {local name: {"source": ..., "version": ...}}.
providers: Mapping[str, Mapping[str, str]] = field(default_factory=dict)
# Terraform's plugin cache is not safe for concurrent installs.
_init_lock: asyncio.Lock = field(default_factory=asyncio.Lock, repr=False)
_schema_lock: asyncio.Lock = field(default_factory=asyncio.Lock, repr=False)
# resource type -> (provider label, the resource's schema block)
_schemas: dict[str, tuple[str, dict[str, Any]]] | None = field(
default=None, repr=False
)
async def fmt(self, files: Mapping[str, str]) -> ToolResult:
async def formatted(self, files: Mapping[str, str]) -> dict[str, str] | ToolResult:
"""The files formatting changes, with their new content; or why it failed."""
refusal = _check_files(files)
if refusal:
return refusal
@@ -89,19 +109,24 @@ class TerraformRunner:
)
if code != 0:
return ToolResult(f"terraform fmt failed:\n{output}")
changed = [
name for name in files if (root / name).read_text() != files[name]
]
if not changed:
return ToolResult("terraform fmt: all files are already formatted.")
formatted = "\n\n".join(
f"--- {name}\n{(root / name).read_text()}" for name in changed
)
return ToolResult(
_clip(
f"terraform fmt reformatted {len(changed)} file(s):\n\n{formatted}"
)
)
return {
name: (root / name).read_text()
for name in files
if (root / name).read_text() != files[name]
}
async def fmt(self, files: Mapping[str, str]) -> ToolResult:
changed = await self.formatted(files)
if isinstance(changed, ToolResult):
return changed
if not changed:
return ToolResult("terraform fmt: all files are already formatted.")
formatted = "\n\n".join(
f"--- {name}\n{content}" for name, content in changed.items()
)
return ToolResult(
_clip(f"terraform fmt reformatted {len(changed)} file(s):\n\n{formatted}")
)
async def validate(self, files: Mapping[str, str]) -> ToolResult:
refusal = _check_files(files)
@@ -146,10 +171,94 @@ class TerraformRunner:
_clip(f"terraform plan {verdict} (nothing was applied):\n{output}")
)
async def _init(self, root: Path) -> ToolResult | None:
code, output = await self._run(
[self.binary, "init", "-backend=false", "-input=false", "-no-color"], root
async def schema(
self, resource_type: str, block: str = "", find: str = ""
) -> ToolResult:
"""What a resource type accepts, from the pinned provider's own schema."""
loaded = await self._load_schemas()
if isinstance(loaded, ToolResult):
return loaded
if resource_type not in loaded:
close = difflib.get_close_matches(resource_type, loaded, n=5, cutoff=0.6)
hint = f" Close matches: {', '.join(close)}." if close else ""
return ToolResult(
f"No resource type {resource_type} in {self._provider_labels()}.{hint}"
)
label, root = loaded[resource_type]
title = f"{resource_type} ({label})"
if find:
return ToolResult(_clip(_find_in_schema(title, root, find)))
node = root
for step in [part for part in block.split(".") if part]:
nested = node.get("block_types", {}).get(step)
if nested is None:
inside = ", ".join(sorted(node.get("block_types", {}))) or "none"
return ToolResult(
f"{title} has no block {block!r}: {step!r} is not a block there. "
f"Blocks at that level: {inside}."
)
node = nested["block"]
heading = f"{title}, block {block}" if block else title
return ToolResult(_clip(_render_schema(heading, node)))
def _provider_labels(self) -> str:
return (
", ".join(
f"{pin['source']} {pin['version']}" for pin in self.providers.values()
)
or "no pinned provider"
)
async def _load_schemas(self) -> dict[str, tuple[str, dict[str, Any]]] | ToolResult:
async with self._schema_lock:
if self._schemas is not None:
return self._schemas
if not self.providers:
return ToolResult(
"Schema lookup is unavailable: the Cloud provider bundle pins no "
"Terraform provider."
)
required = "\n".join(
f' {name} = {{ source = "{pin["source"]}", '
f'version = "{pin["version"]}" }}'
for name, pin in self.providers.items()
)
with tempfile.TemporaryDirectory(prefix="tf-schema-") as tmp:
root = Path(tmp)
(root / "versions.tf").write_text(
f"terraform {{\n required_providers {{\n{required}\n }}\n}}\n"
)
failure = await self._init(root)
if failure:
return failure
code, output = await self._run(
[self.binary, "providers", "schema", "-json"], root
)
if code != 0:
return ToolResult(
_clip(f"terraform providers schema failed:\n{output}")
)
try:
data = json.loads(output)
except ValueError:
return ToolResult("terraform providers schema returned no JSON.")
labels = {pin["source"]: pin["version"] for pin in self.providers.values()}
schemas: dict[str, tuple[str, dict[str, Any]]] = {}
for address, provider in (data.get("provider_schemas") or {}).items():
source = address.split("/", 1)[-1] # drop the registry host
label = f"{source} {labels.get(source, '')}".strip()
for name, resource in (provider.get("resource_schemas") or {}).items():
schemas[name] = (label, resource.get("block") or {})
self._schemas = schemas
return schemas
async def _init(self, root: Path) -> ToolResult | None:
command = [self.binary, "init", "-backend=false", "-input=false", "-no-color"]
if self.plugin_cache_dir:
async with self._init_lock:
code, output = await self._run(command, root)
else:
code, output = await self._run(command, root)
if code != 0:
return ToolResult(_clip(f"terraform init failed:\n{output}"))
return None
@@ -159,7 +268,12 @@ class TerraformRunner:
) -> tuple[int, str]:
environment = {**os.environ, "TF_IN_AUTOMATION": "1", **(env or {})}
if self.plugin_cache_dir:
environment["TF_PLUGIN_CACHE_DIR"] = self.plugin_cache_dir
cache = Path(self.plugin_cache_dir).expanduser().resolve()
cache.mkdir(parents=True, exist_ok=True)
environment["TF_PLUGIN_CACHE_DIR"] = str(cache)
# Each check runs in a scratch directory with no dependency lock file.
# Without this, Terraform downloads a cached provider again to verify it.
environment["TF_PLUGIN_CACHE_MAY_BREAK_DEPENDENCY_LOCK_FILE"] = "true"
try:
process = await asyncio.create_subprocess_exec(
*args,
@@ -224,6 +338,100 @@ def _clip(text: str) -> str:
return text if len(text) <= _MAX_OUTPUT else text[:_MAX_OUTPUT] + "\n[truncated]"
def _type(value: Any) -> str:
if isinstance(value, str):
return value
if isinstance(value, list) and len(value) == 2 and value[0] != "object":
return f"{value[0]} of {_type(value[1])}"
return "object"
def _use(attribute: Mapping[str, Any]) -> str:
if attribute.get("required"):
return "required"
return "optional" if attribute.get("optional") else "read-only"
def _arguments(node: Mapping[str, Any]) -> dict[str, Mapping[str, Any]]:
"""The arguments code may set: everything but the read-only ones."""
return {
name: attribute
for name, attribute in sorted((node.get("attributes") or {}).items())
if _use(attribute) != "read-only"
}
def _block_note(nested: Mapping[str, Any]) -> str:
notes = [str(nested.get("nesting_mode", "block"))]
if nested.get("min_items"):
notes.append(f"at least {nested['min_items']}")
if nested.get("max_items"):
notes.append(f"at most {nested['max_items']}")
return ", ".join(notes)
def _render_schema(heading: str, node: Mapping[str, Any]) -> str:
"""One level in full, and the blocks beneath it as an outline of names."""
lines = [heading, "", "Arguments:"]
arguments = _arguments(node)
for name, attribute in arguments.items():
described = " ".join(str(attribute.get("description") or "").split())[:160]
deprecated = " DEPRECATED" if attribute.get("deprecated") else ""
lines.append(
f" {name} ({_type(attribute.get('type'))}, {_use(attribute)})"
f"{deprecated}" + (f": {described}" if described else "")
)
if not arguments:
lines.append(" none")
def outline(parent: Mapping[str, Any], depth: int) -> None:
for name, nested in sorted((parent.get("block_types") or {}).items()):
inner = nested.get("block") or {}
names = ", ".join(
f"{argument}*" if attribute.get("required") else argument
for argument, attribute in _arguments(inner).items()
)
lines.append(
f"{' ' * depth}{name} {{ }} ({_block_note(nested)}): {names or '-'}"
)
outline(inner, depth + 1)
lines += ["", "Blocks (* marks a required argument):"]
before = len(lines)
outline(node, 1)
if len(lines) == before:
lines.append(" none")
lines += ["", "Pass `block`, such as a.b, for one block's arguments in full."]
return "\n".join(lines)
def _find_in_schema(title: str, root: Mapping[str, Any], wanted: str) -> str:
"""Every argument or block whose name contains `wanted`, with where it sits."""
needle = wanted.lower()
found: list[str] = []
def search(node: Mapping[str, Any], path: str) -> None:
for name, attribute in sorted((node.get("attributes") or {}).items()):
if needle in name.lower():
where = f"{path}.{name}" if path else name
found.append(
f" {where} ({_type(attribute.get('type'))}, {_use(attribute)})"
)
for name, nested in sorted((node.get("block_types") or {}).items()):
where = f"{path}.{name}" if path else name
if needle in name.lower():
found.append(f" {where} {{ }} ({_block_note(nested)})")
search(nested.get("block") or {}, where)
search(root, "")
if not found:
return (
f"{title} has no argument or block named like {wanted!r}. It cannot be "
"set on this resource type."
)
return f"{title}: {wanted!r} is found at\n" + "\n".join(found)
_FILES_SCHEMA: dict[str, Any] = {
**FILES_SCHEMA,
"description": "Terraform files in one directory, e.g. terraform/main.tf",
@@ -232,19 +440,53 @@ _FILES_SCHEMA: dict[str, Any] = {
def _with_files(
method: Callable[..., Awaitable[ToolResult]],
working_copy: MutableMapping[str, str] | None = None,
) -> Callable[..., Awaitable[ToolResult]]:
"""Adapt a runner method to take the FILES_SCHEMA argument."""
"""Adapt a runner method to take the FILES_SCHEMA argument.
async def handler(files: Any, **kwargs: Any) -> ToolResult:
With a working copy, the files are the Terraform files in it and the argument is
optional: files passed anyway are written to the working copy first.
"""
async def handler(files: Any = None, **kwargs: Any) -> ToolResult:
try:
converted = files_from_argument(files)
except TypeError as exc:
return ToolResult(f"Refused: files: {exc}")
return await method(converted, **kwargs)
if working_copy is None:
return await method(converted, **kwargs)
working_copy.update(converted)
return await method(_terraform_files(working_copy), **kwargs)
return handler
def _terraform_files(files: Mapping[str, str]) -> dict[str, str]:
return {
name: content
for name, content in files.items()
if name.endswith(_TERRAFORM_SUFFIXES)
}
def _fmt_in_place(
runner: TerraformRunner, working_copy: MutableMapping[str, str]
) -> Callable[..., Awaitable[ToolResult]]:
async def format_working_copy(files: Mapping[str, str]) -> ToolResult:
changed = await runner.formatted(files)
if isinstance(changed, ToolResult):
return changed
working_copy.update(changed)
if not changed:
return ToolResult("terraform fmt: all files are already formatted.")
return ToolResult(
f"terraform fmt reformatted {len(changed)} file(s) in your working "
f"copy: {', '.join(sorted(changed))}."
)
return _with_files(format_working_copy, working_copy)
LOCAL_TOOLS: dict[str, tuple[str, str]] = {
"mermaid_check": ("general", "Check a Mermaid diagram's basic structure."),
"terraform_fmt": ("general", "Format Terraform files and return any that changed."),
@@ -256,10 +498,48 @@ LOCAL_TOOLS: dict[str, tuple[str, str]] = {
"cloud_read",
"Preview Terraform against the live cloud environment with a plan. Never applies.",
),
"terraform_schema": (
"general",
(
"Look up what a Terraform resource type accepts, from the provider's own "
"schema: its arguments and blocks, one block in full with `block`, or "
"whether an argument exists anywhere in it with `find`."
),
),
}
_ON_WORKING_COPY = " Runs on your working copy; pass no files."
def local_tools(
names: Iterable[str],
runner: TerraformRunner,
working_copy: MutableMapping[str, str] | None = None,
) -> list[ToolSpec]:
"""The named tools. With a `working_copy`, the Terraform checks run on it."""
files_required = [] if working_copy is not None else ["files"]
suffix = _ON_WORKING_COPY if working_copy is not None else ""
def checks(name: str, method: Callable[..., Awaitable[ToolResult]]) -> ToolSpec:
properties: dict[str, Any] = {"files": _FILES_SCHEMA}
if name == "terraform_plan":
properties["variables"] = {
"type": "object",
"additionalProperties": {"type": "string"},
}
tier, description = LOCAL_TOOLS[name]
return ToolSpec(
name,
description + suffix,
{
"type": "object",
"properties": properties,
"required": files_required,
},
method,
tier=tier,
)
def local_tools(names: Iterable[str], runner: TerraformRunner) -> list[ToolSpec]:
builders = {
"mermaid_check": lambda: ToolSpec(
"mermaid_check",
@@ -272,44 +552,41 @@ def local_tools(names: Iterable[str], runner: TerraformRunner) -> list[ToolSpec]
mermaid_check,
tier="general",
),
"terraform_fmt": lambda: ToolSpec(
"terraform_fmt": lambda: checks(
"terraform_fmt",
LOCAL_TOOLS["terraform_fmt"][1],
{
"type": "object",
"properties": {"files": _FILES_SCHEMA},
"required": ["files"],
},
_with_files(runner.fmt),
tier="general",
_fmt_in_place(runner, working_copy)
if working_copy is not None
else _with_files(runner.fmt),
),
"terraform_validate": lambda: ToolSpec(
"terraform_validate",
LOCAL_TOOLS["terraform_validate"][1],
{
"type": "object",
"properties": {"files": _FILES_SCHEMA},
"required": ["files"],
},
_with_files(runner.validate),
tier="general",
"terraform_validate": lambda: checks(
"terraform_validate", _with_files(runner.validate, working_copy)
),
"terraform_plan": lambda: ToolSpec(
"terraform_plan",
LOCAL_TOOLS["terraform_plan"][1],
"terraform_plan": lambda: checks(
"terraform_plan", _with_files(runner.plan, working_copy)
),
"terraform_schema": lambda: ToolSpec(
"terraform_schema",
LOCAL_TOOLS["terraform_schema"][1],
{
"type": "object",
"properties": {
"files": _FILES_SCHEMA,
"variables": {
"type": "object",
"additionalProperties": {"type": "string"},
"resource_type": {
"type": "string",
"description": "For example google_cloud_run_v2_service",
},
"block": {
"type": "string",
"description": "A nested block, such as template.containers",
},
"find": {
"type": "string",
"description": "An argument or block name to look for",
},
},
"required": ["files"],
"required": ["resource_type"],
},
_with_files(runner.plan),
tier="cloud_read",
runner.schema,
tier="general",
),
}
return [builders[name]() for name in names]

View File

@@ -1,25 +1,31 @@
"""The design advisor's fan-out to one advisor per architecture-framework pillar.
Pillar advice is working material for the design recommendations Deliverable, not a
Deliverable itself, so it never touches the Ledger.
Deliverable itself, so it never touches the Ledger. It is kept in that Deliverable's
working memory, so a Revision re-consults only the pillars its feedback touches.
"""
from __future__ import annotations
import asyncio
import dataclasses
from collections.abc import Mapping, Sequence
from collections.abc import Mapping, MutableMapping, Sequence
from contextlib import AsyncExitStack
from typing import Any
from app.adk.runtime import (
AgentRuntime,
AgentTask,
RoleSpec,
RunLimiter,
Submitted,
ToolResult,
ToolSpec,
)
CONSULT_TOOL = "consult_pillar_advisors"
NO_GUIDANCE = "No guidance"
ADVICE_KEY = "pillar_advice" # working memory: pillar -> the advice last given
def pillar_consultation_tool(
@@ -27,8 +33,22 @@ def pillar_consultation_tool(
advisor: RoleSpec,
pillar_skills: Mapping[str, str],
extra_tools: Sequence[ToolSpec] = (),
memory: MutableMapping[str, Any] | None = None,
limiter: RunLimiter | None = None,
) -> ToolSpec:
"""A tool that runs one pillar advisor per pillar, in parallel, each with its Skill."""
"""A tool that runs one pillar advisor per pillar, in parallel, each with its Skill.
With `memory`, advice is remembered: naming `pillars` re-consults only those and
returns the remembered advice for the rest.
"""
async def advise(pillar: str, brief: str) -> str:
async with AsyncExitStack() as stack:
if limiter:
await stack.enter_async_context(limiter.slot())
return await _advise(
runtime, advisor, pillar, pillar_skills[pillar], brief, extra_tools
)
async def consult(brief: str, pillars: Sequence[str] | None = None) -> ToolResult:
chosen = list(pillars) if pillars else list(pillar_skills)
@@ -38,20 +58,41 @@ def pillar_consultation_tool(
f"Refused: unknown pillars {', '.join(unknown)}; "
f"choose from {', '.join(pillar_skills)}"
)
results = await asyncio.gather(
*(
_advise(
runtime, advisor, pillar, pillar_skills[pillar], brief, extra_tools
async with AsyncExitStack() as stack:
if limiter:
# The calling Specialist only waits here, so its slot goes to advisors.
await stack.enter_async_context(limiter.lend())
fresh = dict(
zip(
chosen,
await asyncio.gather(*(advise(pillar, brief) for pillar in chosen)),
)
for pillar in chosen
)
remembered: dict[str, str] = (
dict(memory.get(ADVICE_KEY, {})) if memory is not None else {}
)
return ToolResult("\n\n".join(results))
sections = []
for pillar in pillar_skills:
if pillar in fresh:
advice = fresh[pillar]
if not advice.startswith(NO_GUIDANCE):
remembered[pillar] = advice
sections.append(f"## {pillar}\n\n{advice}")
elif pillar in remembered:
sections.append(
f"## {pillar} (from your earlier consultation)\n\n"
f"{remembered[pillar]}"
)
if memory is not None:
memory[ADVICE_KEY] = remembered
return ToolResult("\n\n".join(sections))
return ToolSpec(
CONSULT_TOOL,
"Get guidance from one advisor per architecture-framework pillar, in parallel. "
"Give a brief with the workload, its requirements and the selected products.",
"Give a brief with the workload, its requirements and the selected products. "
"Omit `pillars` to consult every pillar afresh. Name `pillars` to re-consult "
"only those; advice already given for the others is returned unchanged.",
{
"type": "object",
"properties": {
@@ -84,12 +125,10 @@ async def _advise(
try:
outcome = await runtime.run(role, task, [_submit_advice_tool(), *extra_tools])
except Exception as exc: # noqa: BLE001 - one failed advisor must not lose the others
return f"## {pillar}\n\nNo guidance: the advisor failed ({exc})."
return f"{NO_GUIDANCE}: the advisor failed ({exc})."
if isinstance(outcome, Submitted):
return f"## {pillar}\n\n{outcome.content.strip()}"
return (
f"## {pillar}\n\nNo guidance: the advisor ended with {type(outcome).__name__}."
)
return outcome.content.strip()
return f"{NO_GUIDANCE}: the advisor ended with {type(outcome).__name__}."
def _submit_advice_tool() -> ToolSpec:

View File

@@ -2,18 +2,24 @@
A role gets the local tools its role file names, the tools of the remote MCP servers
the provider bundle assigns it, and, for the design advisor, the pillar consultation.
When the Deliverable has a working copy, the local tools are built on it.
Cloud-read gating is applied later, per Execution, by `specialist_tools`.
"""
from __future__ import annotations
from collections.abc import Mapping, Sequence
from collections.abc import Callable, Mapping, MutableMapping, Sequence
from typing import Any
from app.adk.roles import PILLAR_ADVISOR
from app.adk.runtime import AgentRuntime, RoleSpec, ToolFactory, ToolSpec
from app.adk.runtime import AgentRuntime, RoleSpec, RunLimiter, ToolFactory, ToolSpec
from app.tools.mcp import McpCatalog
from app.tools.pillars import pillar_consultation_tool
from app.workflows.deliverables import DeliverableKind
from app.tools.workspace import working_files
from app.workflows.deliverables import DEPENDENCY_GRAPH, DeliverableKind
# The local tools, built on a working copy of files when the Deliverable has one.
LocalToolBuilder = Callable[[MutableMapping[str, str] | None], Sequence[ToolSpec]]
def make_tool_factory(
@@ -21,28 +27,56 @@ def make_tool_factory(
roles: Mapping[str, RoleSpec],
pillar_skills: Mapping[str, str],
*,
local_tools: Sequence[ToolSpec] = (),
local_tools: Sequence[ToolSpec] | LocalToolBuilder = (),
catalog: McpCatalog | None = None,
limiter: RunLimiter | None = None,
) -> ToolFactory:
local_by_name = {tool.name: tool for tool in local_tools}
def build_local(
working_copy: MutableMapping[str, str] | None,
) -> Sequence[ToolSpec]:
return local_tools(working_copy) if callable(local_tools) else local_tools
def mcp_tools(role: RoleSpec) -> list[ToolSpec]:
return catalog.tools_for(role.mcp_servers) if catalog else []
consult = None
advisor = roles.get(PILLAR_ADVISOR)
if pillar_skills and advisor:
# Pillar advisors can't ask for permission, so they get general-tier tools only.
advisor_tools = [tool for tool in mcp_tools(advisor) if tool.tier == "general"]
consult = pillar_consultation_tool(
runtime, advisor, pillar_skills, extra_tools=advisor_tools
)
# Pillar advisors can't ask for permission, so they get general-tier tools only.
advisor_tools = (
[tool for tool in mcp_tools(advisor) if tool.tier == "general"]
if advisor
else []
)
def tools_for(role: RoleSpec, deliverable: str | None) -> Sequence[ToolSpec]:
def tools_for(
role: RoleSpec, deliverable: str | None, working: MutableMapping[str, Any]
) -> Sequence[ToolSpec]:
has_working_copy = any(
kind.value == deliverable and spec.working_copy is not None
for kind, spec in DEPENDENCY_GRAPH.items()
)
local_by_name = {
tool.name: tool
for tool in build_local(
working_files(working) if has_working_copy else None
)
}
tools = [local_by_name[name] for name in role.tools if name in local_by_name]
tools += mcp_tools(role)
if consult and deliverable == DeliverableKind.DESIGN_RECOMMENDATIONS.value:
tools.append(consult)
if (
pillar_skills
and advisor
and deliverable == DeliverableKind.DESIGN_RECOMMENDATIONS.value
):
tools.append(
pillar_consultation_tool(
runtime,
advisor,
pillar_skills,
extra_tools=advisor_tools,
memory=working,
limiter=limiter,
)
)
return tools
return tools_for

289
app/tools/workspace.py Normal file
View File

@@ -0,0 +1,289 @@
"""A Specialist's working copy: files and a graph built up over several tool calls.
A model that must return a whole Deliverable in one reply spends most of its output
repeating itself, and a long reply is what times out. With a working copy it writes a
file once, changes only the lines that need changing, and adds to a graph a few items
at a time. The working copy is kept with the Execution, so a Revision starts from the
last attempt instead of from nothing.
It lives in the Deliverable's working memory:
working["files"] {path: content}
working["graph"] the Target architecture, as target-architecture.json holds it
"""
from __future__ import annotations
import json
from collections.abc import Mapping, MutableMapping, Sequence
from pathlib import PurePosixPath
from typing import Any
from app.adk.runtime import ToolResult, ToolSpec
FILES = "files"
GRAPH = "graph"
_GRAPH_LISTS = ("elements", "relationships", "checks", "not_applicable")
_MAX_READ = 40_000
def safe_relative(name: str) -> bool:
path = PurePosixPath(name)
return bool(name) and not path.is_absolute() and ".." not in path.parts
def working_files(working: MutableMapping[str, Any]) -> MutableMapping[str, str]:
files = working.get(FILES)
if not isinstance(files, MutableMapping):
files = working[FILES] = {}
return files
def _schema(properties: Mapping[str, Any], required: Sequence[str]) -> dict[str, Any]:
return {
"type": "object",
"properties": dict(properties),
"required": list(required),
}
def _lines(content: str) -> int:
return content.count("\n") + (1 if content and not content.endswith("\n") else 0)
def file_tools(working: MutableMapping[str, Any]) -> list[ToolSpec]:
"""Tools that write, change and read the files of a working copy."""
files = working_files(working)
async def write_file(path: str, content: str) -> ToolResult:
if not safe_relative(path):
return ToolResult(
f"Refused: {path!r} must be a relative path without '..'."
)
files[path] = content
return ToolResult(f"Wrote {path} ({_lines(content)} lines).")
async def edit_file(path: str, old: str, new: str) -> ToolResult:
if path not in files:
return ToolResult(f"Refused: {path} is not in your working copy.")
found = files[path].count(old) if old else 0
if found != 1:
return ToolResult(
f"Refused: `old` must match exactly one place in {path}; it matches "
f"{found}. Include more of the surrounding lines."
)
files[path] = files[path].replace(old, new)
return ToolResult(f"Edited {path}.")
async def read_file(path: str = "") -> ToolResult:
if not path:
if not files:
return ToolResult("Your working copy is empty.")
return ToolResult(
"Your working copy:\n"
+ "\n".join(
f"- {name} ({_lines(files[name])} lines)" for name in sorted(files)
)
)
if path not in files:
return ToolResult(f"Refused: {path} is not in your working copy.")
content = files[path]
if len(content) > _MAX_READ:
content = content[:_MAX_READ] + "\n[truncated]"
return ToolResult(content)
async def delete_file(path: str) -> ToolResult:
if files.pop(path, None) is None:
return ToolResult(f"Refused: {path} is not in your working copy.")
return ToolResult(f"Deleted {path}.")
text = {"type": "string"}
return [
ToolSpec(
"write_file",
"Write one file of your working copy, replacing it if it exists. Your "
"working copy is attached for you when you submit.",
_schema({"path": text, "content": text}, ["path", "content"]),
write_file,
),
ToolSpec(
"edit_file",
"Change part of one file: replace the single place `old` matches with "
"`new`. Use this for a fix instead of writing the file again.",
_schema({"path": text, "old": text, "new": text}, ["path", "old", "new"]),
edit_file,
),
ToolSpec(
"read_file",
"Read one file of your working copy, or list its files when `path` is "
"left out.",
_schema({"path": text}, []),
read_file,
),
ToolSpec(
"delete_file",
"Remove one file from your working copy.",
_schema({"path": text}, ["path"]),
delete_file,
),
]
# --- the graph -----------------------------------------------------------------------
def working_graph(working: MutableMapping[str, Any]) -> dict[str, list[dict[str, Any]]]:
graph = working.get(GRAPH)
if not isinstance(graph, dict):
graph = working[GRAPH] = {}
for name in _GRAPH_LISTS:
if not isinstance(graph.get(name), list):
graph[name] = []
return graph
def graph_text(working: MutableMapping[str, Any]) -> str:
"""The working graph as target-architecture.json, or "" when nothing is in it."""
graph = working.get(GRAPH)
if not isinstance(graph, dict) or not any(graph.get(n) for n in _GRAPH_LISTS):
return ""
return json.dumps(
{name: graph.get(name, []) for name in _GRAPH_LISTS},
indent=2,
ensure_ascii=False,
)
def keep_graph(working: MutableMapping[str, Any], text: str) -> None:
"""Make a submitted graph the working graph, so a Revision amends it."""
try:
data = json.loads(text)
except ValueError:
return
if isinstance(data, dict):
working[GRAPH] = {
name: [item for item in data.get(name, []) if isinstance(item, dict)]
for name in _GRAPH_LISTS
}
def _key(name: str) -> str:
return "recommendation" if name == "not_applicable" else "id"
def graph_tools(working: MutableMapping[str, Any]) -> list[ToolSpec]:
"""Tools that build the Target architecture a few items at a time."""
async def graph_put(
elements: Sequence[Any] = (),
relationships: Sequence[Any] = (),
checks: Sequence[Any] = (),
not_applicable: Sequence[Any] = (),
) -> ToolResult:
graph = working_graph(working)
given = dict(
zip(
_GRAPH_LISTS,
(elements, relationships, checks, not_applicable),
strict=True,
)
)
bad = [
f"{name}[{index}]"
for name, items in given.items()
for index, item in enumerate(items or ())
if not isinstance(item, Mapping)
or not isinstance(item.get(_key(name)), str)
or not item[_key(name)].strip()
]
if bad:
return ToolResult(
"Refused: each item must be an object with an `id` (a "
f"`recommendation` under not_applicable): {', '.join(bad)}"
)
added = replaced = 0
for name, items in given.items():
key = _key(name)
for item in items or ():
for index, existing in enumerate(graph[name]):
if existing.get(key) == item[key]:
graph[name][index] = dict(item)
replaced += 1
break
else:
graph[name].append(dict(item))
added += 1
return ToolResult(f"Added {added}, replaced {replaced}. {_counts(graph)}")
async def graph_remove(ids: Sequence[str]) -> ToolResult:
graph = working_graph(working)
wanted = set(ids)
removed = 0
for name in _GRAPH_LISTS:
kept = [item for item in graph[name] if item.get(_key(name)) not in wanted]
removed += len(graph[name]) - len(kept)
graph[name] = kept
return ToolResult(f"Removed {removed}. {_counts(graph)}")
async def graph_read() -> ToolResult:
return ToolResult(graph_text(working) or "Your working graph is empty.")
def items(*fields: str, optional: tuple[str, ...] = ()) -> dict[str, Any]:
return {
"type": "array",
"items": _schema(
{name: {"type": "string"} for name in (*fields, *optional)}, fields
),
}
lists = {
"elements": items(
"id", "name", "product", "resource_type", optional=("component",)
),
"relationships": items("id", "from", "to", "kind"),
"checks": items("id", "applies_to", "statement", "source"),
"not_applicable": items("recommendation", "reason"),
}
return [
ToolSpec(
"graph_put",
"Add items to your working graph, or replace the ones with the same id. "
"Call it several times with a few items each. Your working graph is "
"attached as target-architecture.json when you submit.",
_schema(lists, []),
graph_put,
),
ToolSpec(
"graph_remove",
"Remove items from your working graph by id (a not-applicable entry by "
"its recommendation id).",
_schema({"ids": {"type": "array", "items": {"type": "string"}}}, ["ids"]),
graph_remove,
),
ToolSpec(
"graph_read",
"Read your working graph.",
{"type": "object", "properties": {}},
graph_read,
),
]
def _counts(graph: Mapping[str, Sequence[Any]]) -> str:
return (
f"The graph has {len(graph['elements'])} Elements, "
f"{len(graph['relationships'])} Relationships and "
f"{len(graph['checks'])} Checks."
)
def summary(working: Mapping[str, Any]) -> dict[str, Any] | None:
"""What a Specialist is told it already has, at the start of a run."""
told: dict[str, Any] = {}
files = working.get(FILES)
if isinstance(files, Mapping) and files:
told["files"] = sorted(files)
graph = working.get(GRAPH)
if isinstance(graph, Mapping) and any(graph.get(name) for name in _GRAPH_LISTS):
told["graph"] = {name: len(graph.get(name) or ()) for name in _GRAPH_LISTS}
return told or None

367
app/workflows/chain.py Normal file
View File

@@ -0,0 +1,367 @@
"""The data files along the Requirements chain, and what each must hold (ADR-0005).
requirements.json requirements with ids
components.json components, and the requirements each serves
products.json the product selected for each component
recommendations.json design recommendations with ids
target-architecture.json the graph (see target_architecture.py)
implementation.json which code satisfies each Check
verdicts.json the validation verdict on each Check
Each checker returns what is wrong, one entry per fault, so a Specialist can fix it
and submit again. `upstream` is the Deliverables a submission builds on, by kind; a
link to one of them is checked only when it is there.
"""
from __future__ import annotations
import json
from collections.abc import Mapping, Sequence
from typing import Any
from app.workflows.target_architecture import (
GRAPH_ATTACHMENT,
GraphError,
TargetArchitecture,
chain_gaps,
parse_graph,
)
REQUIREMENTS_FILE = "requirements.json"
COMPONENTS_FILE = "components.json"
PRODUCTS_FILE = "products.json"
RECOMMENDATIONS_FILE = "recommendations.json"
IMPLEMENTATION_FILE = "implementation.json"
VERDICTS_FILE = "verdicts.json"
REQUIREMENT_KINDS = ("functional", "non_functional")
VERDICTS = ("pass", "fail", "not_verifiable")
DRY_RUN_VERDICTS = ("pass", "fail", "not_run")
Upstream = Mapping[str, Mapping[str, Any]]
def read_list(upstream: Upstream | None, kind: str, name: str) -> list[dict[str, Any]]:
"""An upstream data file as a list of objects; empty when absent or unreadable."""
text = ((upstream or {}).get(kind) or {}).get("attachments", {}).get(name, "")
try:
data = json.loads(text)
except ValueError:
return []
return (
[item for item in data if isinstance(item, dict)]
if isinstance(data, list)
else []
)
def read_graph(upstream: Upstream | None) -> TargetArchitecture | None:
text = (
((upstream or {}).get("target_architecture") or {})
.get("attachments", {})
.get(GRAPH_ATTACHMENT, "")
)
try:
return parse_graph(text)
except GraphError:
return None
def _objects(
text: str, name: str, strings: Sequence[str], lists: Sequence[str] = ()
) -> tuple[list[dict[str, Any]], list[str]]:
"""The file's objects that have every required field, and what is wrong with it."""
try:
data = json.loads(text)
except ValueError as exc:
return [], [f"{name}: not valid JSON ({exc})"]
if not isinstance(data, list):
return [], [f"{name}: must be a JSON list"]
accepted, problems = [], []
for index, item in enumerate(data):
where = f"{name}[{index}]"
if not isinstance(item, dict):
problems.append(f"{where}: must be an object")
continue
missing = [
field
for field in strings
if not isinstance(item.get(field), str) or not item[field].strip()
]
missing += [
field
for field in lists
if not isinstance(item.get(field), list)
or not all(isinstance(value, str) for value in item[field])
]
if missing:
problems.append(f"{where}: needs {', '.join(missing)}")
continue
accepted.append(item)
return accepted, problems
def _repeated(
items: Sequence[Mapping[str, Any]], name: str, key: str = "id"
) -> list[str]:
seen: set[str] = set()
problems = []
for item in items:
if item[key] in seen:
problems.append(f"{name}: {key} {item[key]} is used more than once")
seen.add(item[key])
return problems
def check_requirements(
attachments: Mapping[str, str], upstream: Upstream | None
) -> list[str]:
name = REQUIREMENTS_FILE
items, problems = _objects(attachments[name], name, ("id", "kind", "text"))
problems += _repeated(items, name)
problems += [
f"{name}: {item['id']} kind must be one of {', '.join(REQUIREMENT_KINDS)}"
for item in items
if item["kind"] not in REQUIREMENT_KINDS
]
if not items and not problems:
problems.append(f"{name}: lists no requirements")
return problems
def check_components(
attachments: Mapping[str, str], upstream: Upstream | None
) -> list[str]:
name = COMPONENTS_FILE
items, problems = _objects(
attachments[name], name, ("id", "name"), ("requirements",)
)
problems += _repeated(items, name)
if not items and not problems:
problems.append(f"{name}: lists no components")
requirements = read_list(upstream, "requirements", REQUIREMENTS_FILE)
if requirements:
known = {item["id"] for item in requirements}
served: set[str] = set()
for item in items:
served.update(item["requirements"])
problems += [
f"{name}: {item['id']} serves {reference}, which is not a requirement"
for reference in item["requirements"]
if reference not in known
]
problems += [
f"{name}: functional requirement {item['id']} is served by no component"
for item in requirements
if item.get("kind") == "functional" and item["id"] not in served
]
return problems
def check_products(
attachments: Mapping[str, str], upstream: Upstream | None
) -> list[str]:
name = PRODUCTS_FILE
items, problems = _objects(attachments[name], name, ("component", "product"))
components = read_list(upstream, "technical_decomposition", COMPONENTS_FILE)
if components:
known = {item["id"] for item in components}
chosen = {item["component"] for item in items}
problems += [
f"{name}: {item['component']} is not a component"
for item in items
if item["component"] not in known
]
problems += [
f"{name}: component {identifier} has no product selected"
for identifier in sorted(known - chosen)
]
return problems
def check_recommendations(
attachments: Mapping[str, str], upstream: Upstream | None
) -> list[str]:
name = RECOMMENDATIONS_FILE
items, problems = _objects(
attachments[name], name, ("id", "pillar", "text"), ("components",)
)
problems += _repeated(items, name)
if not items and not problems:
problems.append(f"{name}: lists no recommendations")
components = read_list(upstream, "technical_decomposition", COMPONENTS_FILE)
if components:
known = {item["id"] for item in components}
problems += [
f"{name}: {item['id']} names {reference}, which is not a component"
for item in items
for reference in item["components"]
if reference not in known
]
return problems
def check_target_architecture(
attachments: Mapping[str, str], upstream: Upstream | None
) -> list[str]:
try:
graph = parse_graph(attachments[GRAPH_ATTACHMENT])
except GraphError as exc:
return list(exc.problems)
if upstream is None:
return []
return list(
chain_gaps(
graph,
requirements=read_list(upstream, "requirements", REQUIREMENTS_FILE),
components=read_list(upstream, "technical_decomposition", COMPONENTS_FILE),
products=read_list(upstream, "product_selection", PRODUCTS_FILE),
recommendations=read_list(
upstream, "design_recommendations", RECOMMENDATIONS_FILE
),
)
)
def _covers_every_check(
items: Sequence[Mapping[str, Any]], name: str, graph: TargetArchitecture | None
) -> list[str]:
problems = _repeated(items, name, "check")
if graph is None:
return problems
given = {item["check"] for item in items}
problems += [
f"{name}: {identifier} is not a Check in the Target architecture"
for identifier in sorted(given - set(graph.check_ids))
]
problems += [
f"{name}: Check {identifier} is not accounted for"
for identifier in graph.check_ids
if identifier not in given
]
return problems
def _split_implementation(text: str, name: str) -> tuple[str, str]:
"""The entries that say where a Check is met, and those that say it cannot be."""
try:
data = json.loads(text)
except ValueError:
return text, "[]"
if not isinstance(data, list):
return text, "[]"
cannot = [
item for item in data if isinstance(item, dict) and "unimplementable" in item
]
met = [item for item in data if item not in cannot]
return json.dumps(met), json.dumps(cannot)
def check_implementation(
attachments: Mapping[str, str], upstream: Upstream | None
) -> list[str]:
name = IMPLEMENTATION_FILE
met_text, cannot_text = _split_implementation(attachments[name], name)
met, problems = _objects(met_text, name, ("check", "file", "address"))
cannot, faults = _objects(cannot_text, name, ("check", "unimplementable"))
problems += faults
problems += _covers_every_check([*met, *cannot], name, read_graph(upstream))
problems += [
f"{name}: {item['check']} names {item['file']}, which is not attached"
for item in met
if item["file"] not in attachments
]
return problems
def unimplementable_checks(implementation_text: str) -> list[dict[str, str]]:
"""The Checks the code's author found cannot be met as written, with the reason.
Each is a fault in the Target architecture, not in the code: the Check names
something the resource does not have.
"""
_, cannot_text = _split_implementation(implementation_text, IMPLEMENTATION_FILE)
cannot, _ = _objects(cannot_text, IMPLEMENTATION_FILE, ("check", "unimplementable"))
return [
{"check": item["check"], "reason": item["unimplementable"]} for item in cannot
]
def check_verdicts(
attachments: Mapping[str, str], upstream: Upstream | None
) -> list[str]:
name = VERDICTS_FILE
try:
data = json.loads(attachments[name])
except ValueError as exc:
return [f"{name}: not valid JSON ({exc})"]
if not isinstance(data, dict):
return [
f"{name}: must be an object with dry_run, checks and proposed_additions"
]
problems: list[str] = []
dry_run = data.get("dry_run")
if (
not isinstance(dry_run, dict)
or dry_run.get("verdict") not in DRY_RUN_VERDICTS
or not isinstance(dry_run.get("evidence"), str)
or not dry_run["evidence"].strip()
):
problems.append(
f"{name}.dry_run: needs a verdict ({', '.join(DRY_RUN_VERDICTS)}) and evidence"
)
items, faults = _objects(
json.dumps(data.get("checks", [])),
f"{name}.checks",
("check", "verdict", "evidence"),
)
problems += faults
problems += [
f"{name}.checks: {item['check']} verdict must be one of {', '.join(VERDICTS)}"
for item in items
if item["verdict"] not in VERDICTS
]
problems += _covers_every_check(items, f"{name}.checks", read_graph(upstream))
_, faults = _objects(
json.dumps(data.get("proposed_additions", [])),
f"{name}.proposed_additions",
("statement", "applies_to", "reason"),
)
return problems + faults
def validation_outcome(verdicts_text: str) -> dict[str, Any]:
"""What a validation decided, for routing a Revision and for scoring.
Failed Checks are faults in the code. A Check that could not be verified and a
proposed addition are gaps in the Target architecture.
"""
try:
data = json.loads(verdicts_text)
except ValueError:
data = {}
if not isinstance(data, dict):
data = {}
checks = [item for item in data.get("checks", []) if isinstance(item, dict)]
def with_verdict(verdict: str) -> list[dict[str, Any]]:
return [
{"check": item.get("check"), "evidence": item.get("evidence")}
for item in checks
if item.get("verdict") == verdict
]
dry_run = data.get("dry_run") if isinstance(data.get("dry_run"), dict) else {}
return {
"dry_run": dry_run,
"passed": [
item.get("check") for item in checks if item.get("verdict") == "pass"
],
"failed": with_verdict("fail"),
"not_verifiable": with_verdict("not_verifiable"),
"proposed_additions": [
item
for item in data.get("proposed_additions", [])
if isinstance(item, dict)
],
}

View File

@@ -9,14 +9,34 @@ solution-guide template by suffix (e.g. "Products and features mapping" matches
from __future__ import annotations
import re
from collections.abc import Mapping
from collections.abc import Callable, Mapping
from dataclasses import dataclass
from enum import StrEnum
from app.workflows.chain import (
COMPONENTS_FILE,
IMPLEMENTATION_FILE,
PRODUCTS_FILE,
RECOMMENDATIONS_FILE,
REQUIREMENTS_FILE,
VERDICTS_FILE,
Upstream,
check_components,
check_implementation,
check_products,
check_recommendations,
check_requirements,
check_target_architecture,
check_verdicts,
)
from app.workflows.target_architecture import GRAPH_ATTACHMENT
class PhaseId(StrEnum):
REQUIREMENTS_DISCOVERY = "requirements_discovery"
# Design: ends with the Target architecture, approved before any code is written.
SOLUTION_ARCHITECTURE = "solution_architecture"
SOLUTION_IMPLEMENTATION = "solution_implementation"
SOLUTION_VALIDATION = "solution_validation"
PACKAGING = "packaging"
@@ -28,9 +48,9 @@ class DeliverableKind(StrEnum):
REQUIREMENTS = "requirements"
TECHNICAL_DECOMPOSITION = "technical_decomposition"
PRODUCT_SELECTION = "product_selection"
ARCHITECTURE_DIAGRAM = "architecture_diagram"
ARCHITECTURE_DESCRIPTION = "architecture_description"
DESIGN_RECOMMENDATIONS = "design_recommendations"
TARGET_ARCHITECTURE = "target_architecture"
ARCHITECTURE_DESCRIPTION = "architecture_description"
DEPLOYMENT_GUIDANCE = "deployment_guidance"
VALIDATION_RESULTS = "validation_results"
SOLUTION_GUIDE = "solution_guide"
@@ -44,6 +64,21 @@ class DeliverableSpec:
depends_on: tuple[DeliverableKind, ...] = ()
sections: tuple[str, ...] = ()
attachments: tuple[str, ...] = ()
# Which earlier Deliverables the Specialist reads whole. None means the ones it
# depends on. Every other input arrives as its data file alone: the ids the
# Requirements chain runs through, without the prose written around them.
reads_in_full: tuple[DeliverableKind, ...] | None = None
# The Deliverable whose files this Specialist's tools work on. Its own kind: the
# files are its working copy, kept across attempts and attached on submission.
# Another kind: a fresh copy of that Deliverable's files on every attempt.
working_copy: DeliverableKind | None = None
def contract(self) -> dict[str, list[str]]:
"""What a submission must contain, as plain data for the Specialist's context."""
return {
"sections": list(self.sections),
"attachments": list(self.attachments),
}
_K = DeliverableKind
@@ -61,12 +96,15 @@ DEPENDENCY_GRAPH: Mapping[DeliverableKind, DeliverableSpec] = {
"Current state",
"Dependencies",
),
attachments=(REQUIREMENTS_FILE,),
),
DeliverableSpec(
_K.TECHNICAL_DECOMPOSITION,
PhaseId.REQUIREMENTS_DISCOVERY,
"decomposer",
depends_on=(_K.REQUIREMENTS,),
sections=("Components",),
attachments=(COMPONENTS_FILE,),
),
DeliverableSpec(
_K.PRODUCT_SELECTION,
@@ -74,19 +112,7 @@ DEPENDENCY_GRAPH: Mapping[DeliverableKind, DeliverableSpec] = {
"product-selector",
depends_on=(_K.TECHNICAL_DECOMPOSITION,),
sections=("Products and features mapping",),
),
DeliverableSpec(
_K.ARCHITECTURE_DIAGRAM,
PhaseId.SOLUTION_ARCHITECTURE,
"diagrammer",
depends_on=(_K.PRODUCT_SELECTION,),
attachments=("architecture.mmd",),
),
DeliverableSpec(
_K.ARCHITECTURE_DESCRIPTION,
PhaseId.SOLUTION_ARCHITECTURE,
"describer",
depends_on=(_K.ARCHITECTURE_DIAGRAM, _K.PRODUCT_SELECTION),
attachments=(PRODUCTS_FILE,),
),
DeliverableSpec(
_K.DESIGN_RECOMMENDATIONS,
@@ -101,17 +127,43 @@ DEPENDENCY_GRAPH: Mapping[DeliverableKind, DeliverableSpec] = {
"Performance efficiency",
"Sustainability",
),
attachments=(RECOMMENDATIONS_FILE,),
),
DeliverableSpec(
_K.TARGET_ARCHITECTURE,
PhaseId.SOLUTION_ARCHITECTURE,
"target-architect",
depends_on=(_K.PRODUCT_SELECTION, _K.DESIGN_RECOMMENDATIONS),
# The Specialist writes the reasoning and the graph. On submission the
# engine adds the Elements, Relationships and Checks tables to the content
# and architecture.mmd to the attachments, both rendered from the graph.
sections=("Design rationale",),
attachments=(GRAPH_ATTACHMENT,),
),
DeliverableSpec(
_K.ARCHITECTURE_DESCRIPTION,
PhaseId.SOLUTION_IMPLEMENTATION,
"describer",
depends_on=(_K.TARGET_ARCHITECTURE,),
sections=("Components", "Flow"),
),
DeliverableSpec(
_K.DEPLOYMENT_GUIDANCE,
PhaseId.SOLUTION_ARCHITECTURE,
PhaseId.SOLUTION_IMPLEMENTATION,
"iac-author",
depends_on=(_K.PRODUCT_SELECTION, _K.DESIGN_RECOMMENDATIONS),
depends_on=(_K.TARGET_ARCHITECTURE,),
sections=(
"Deployment prerequisites",
"Step-by-step deployment instructions",
),
attachments=("terraform/main.tf", "terraform/variables.tf"),
attachments=(
"terraform/main.tf",
"terraform/variables.tf",
IMPLEMENTATION_FILE,
),
# The graph is all the code is written from.
reads_in_full=(),
working_copy=_K.DEPLOYMENT_GUIDANCE,
),
DeliverableSpec(
_K.VALIDATION_RESULTS,
@@ -119,6 +171,8 @@ DEPENDENCY_GRAPH: Mapping[DeliverableKind, DeliverableSpec] = {
"validator",
depends_on=(_K.DEPLOYMENT_GUIDANCE,),
sections=("Deployment dry-run", "Architecture and policy analysis"),
attachments=(VERDICTS_FILE,),
working_copy=_K.DEPLOYMENT_GUIDANCE,
),
DeliverableSpec(
_K.SOLUTION_GUIDE,
@@ -135,10 +189,26 @@ DEPENDENCY_GRAPH: Mapping[DeliverableKind, DeliverableSpec] = {
"Validation plan",
"References",
),
# The guide is assembled from every Deliverable's prose.
reads_in_full=tuple(_K)[:-1],
),
)
}
# What each data file along the Requirements chain must hold, checked at submission.
DATA_CHECKS: Mapping[
DeliverableKind,
tuple[str, Callable[[Mapping[str, str], Upstream | None], list[str]]],
] = {
_K.REQUIREMENTS: (REQUIREMENTS_FILE, check_requirements),
_K.TECHNICAL_DECOMPOSITION: (COMPONENTS_FILE, check_components),
_K.PRODUCT_SELECTION: (PRODUCTS_FILE, check_products),
_K.DESIGN_RECOMMENDATIONS: (RECOMMENDATIONS_FILE, check_recommendations),
_K.TARGET_ARCHITECTURE: (GRAPH_ATTACHMENT, check_target_architecture),
_K.DEPLOYMENT_GUIDANCE: (IMPLEMENTATION_FILE, check_implementation),
_K.VALIDATION_RESULTS: (VERDICTS_FILE, check_verdicts),
}
def inputs_of(kind: DeliverableKind) -> tuple[DeliverableKind, ...]:
"""The Deliverables a Specialist works from, in graph order.
@@ -164,6 +234,31 @@ def inputs_of(kind: DeliverableKind) -> tuple[DeliverableKind, ...]:
)
def dependencies_for(
kind: DeliverableKind, deliverables: Mapping[str, Mapping[str, object]]
) -> dict[str, dict[str, object]]:
"""What a Specialist is given of each Deliverable it works from.
A Deliverable read in full arrives as submitted. Any other arrives as its data
file alone, which is all the Requirements chain needs of it.
"""
spec = DEPENDENCY_GRAPH[kind]
in_full = spec.depends_on if spec.reads_in_full is None else spec.reads_in_full
given: dict[str, dict[str, object]] = {}
for dependency in inputs_of(kind):
deliverable = deliverables[dependency.value]
if dependency in in_full or dependency not in DATA_CHECKS:
given[dependency.value] = dict(deliverable)
continue
name = DATA_CHECKS[dependency][0]
attachments = deliverable.get("attachments")
files = attachments if isinstance(attachments, Mapping) else {}
given[dependency.value] = {
"attachments": {name: files[name]} if name in files else {}
}
return given
def deliverables_in(phase: PhaseId) -> tuple[DeliverableKind, ...]:
return tuple(kind for kind, spec in DEPENDENCY_GRAPH.items() if spec.phase is phase)
@@ -179,9 +274,16 @@ def _normalise(text: str) -> str:
def check_submission(
kind: DeliverableKind, content: str, attachments: Mapping[str, str]
kind: DeliverableKind,
content: str,
attachments: Mapping[str, str],
upstream: Upstream | None = None,
) -> tuple[str, ...]:
"""Return what a submission lacks against its contract; empty means it's complete."""
"""Return what a submission lacks against its contract; empty means it's complete.
`upstream` is the Deliverables this one builds on, by kind. With it, the links
along the Requirements chain are checked too.
"""
if not content.strip():
return ("content: must not be empty",)
@@ -195,4 +297,10 @@ def check_submission(
for name in spec.attachments:
if name not in attachments:
missing.append(f"attachment: {name}")
elif not attachments[name].strip():
missing.append(f"attachment: {name} must not be empty")
if kind in DATA_CHECKS:
name, check = DATA_CHECKS[kind]
if attachments.get(name, "").strip():
missing.extend(check(attachments, upstream))
return tuple(missing)

View File

@@ -18,8 +18,9 @@ from typing import Any, cast
from langgraph.graph import END, START, StateGraph
from app.adk.runtime import AgentRuntime, RoleSpec, ToolFactory
from app.adk.runtime import AgentRuntime, RoleSpec, RunLimiter, ToolFactory
from app.nodes.execution_nodes import make_execution_nodes
from app.nodes.router import OrchestratorPolicy
from app.recorder import ExecutionRecorder
from app.states.execution_state import ExecutionState
@@ -32,6 +33,9 @@ def build_execution_graph(
output_root: Path,
max_orchestrator_turns: int = 100,
tool_factory: ToolFactory | None = None,
limiter: RunLimiter | None = None,
skill_versions: Mapping[str, str] | None = None,
orchestrator: OrchestratorPolicy | None = None,
) -> StateGraph:
nodes = make_execution_nodes(
runtime=runtime,
@@ -40,6 +44,9 @@ def build_execution_graph(
output_root=output_root,
max_orchestrator_turns=max_orchestrator_turns,
tool_factory=tool_factory,
limiter=limiter,
skill_versions=skill_versions,
orchestrator=orchestrator,
)
graph = StateGraph(ExecutionState)

View File

@@ -0,0 +1,345 @@
"""The Target architecture: one explicit graph, established before code (ADR-0005).
Elements every component and the resource that realises it
Relationships how Elements connect
Checks the numbered, verifiable conditions each must meet, each traced
to the requirement or design recommendation it comes from
This module is pure: it parses the graph, states what is wrong with it, renders it as
a diagram and as tables a person can review, and says whether the Requirements chain
through it is complete.
"""
from __future__ import annotations
import json
import re
from collections.abc import Iterable, Mapping, Sequence
from dataclasses import dataclass
from typing import Any
GRAPH_ATTACHMENT = "target-architecture.json"
DIAGRAM_ATTACHMENT = "architecture.mmd"
@dataclass(frozen=True)
class Element:
id: str
name: str
product: str
resource_type: str
component: str | None = None # None for a supporting Element, e.g. an identity
@dataclass(frozen=True)
class Relationship:
id: str
source: str # "from" in the data
target: str # "to" in the data
kind: str
@dataclass(frozen=True)
class Check:
id: str
applies_to: str # an Element or Relationship id
statement: str
source: str # a requirement or design recommendation id
@dataclass(frozen=True)
class NotApplicable:
recommendation: str
reason: str
@dataclass(frozen=True)
class TargetArchitecture:
elements: tuple[Element, ...]
relationships: tuple[Relationship, ...]
checks: tuple[Check, ...]
not_applicable: tuple[NotApplicable, ...] = ()
@property
def check_ids(self) -> tuple[str, ...]:
return tuple(check.id for check in self.checks)
def summary(self) -> dict[str, Any]:
"""What a user approving the design is told about the graph."""
return {
"elements": len(self.elements),
"relationships": len(self.relationships),
"checks": len(self.checks),
"not_applicable": [
{"recommendation": item.recommendation, "reason": item.reason}
for item in self.not_applicable
],
}
class GraphError(ValueError):
"""The graph is not well-formed; `problems` says how, one entry per fault."""
def __init__(self, problems: Sequence[str]) -> None:
super().__init__("; ".join(problems))
self.problems = tuple(problems)
def parse_graph(text: str) -> TargetArchitecture:
"""Parse target-architecture.json, or raise GraphError naming every fault."""
name = GRAPH_ATTACHMENT
try:
data = json.loads(text)
except ValueError as exc:
raise GraphError([f"{name}: not valid JSON ({exc})"]) from exc
if not isinstance(data, dict):
raise GraphError(
[f"{name}: must be an object with elements, relationships and checks"]
)
problems: list[str] = []
def items(key: str, required: Sequence[str]) -> list[dict[str, str]]:
raw = data.get(key, [])
if not isinstance(raw, list):
problems.append(f"{name}.{key}: must be a list")
return []
accepted = []
for index, item in enumerate(raw):
where = f"{name}.{key}[{index}]"
if not isinstance(item, dict):
problems.append(f"{where}: must be an object")
continue
missing = [
field
for field in required
if not isinstance(item.get(field), str) or not item[field].strip()
]
if missing:
problems.append(f"{where}: needs a non-empty {', '.join(missing)}")
continue
accepted.append(item)
return accepted
elements = tuple(
Element(
id=item["id"],
name=item["name"],
product=item["product"],
resource_type=item["resource_type"],
component=item.get("component") or None,
)
for item in items("elements", ("id", "name", "product", "resource_type"))
)
relationships = tuple(
Relationship(item["id"], item["from"], item["to"], item["kind"])
for item in items("relationships", ("id", "from", "to", "kind"))
)
checks = tuple(
Check(item["id"], item["applies_to"], item["statement"], item["source"])
for item in items("checks", ("id", "applies_to", "statement", "source"))
)
not_applicable = tuple(
NotApplicable(item["recommendation"], item["reason"])
for item in items("not_applicable", ("recommendation", "reason"))
)
if not elements and not problems:
problems.append(f"{name}.elements: the graph has no Elements")
seen: set[str] = set()
ids = [thing.id for group in (elements, relationships, checks) for thing in group]
for identifier in ids:
if identifier in seen:
problems.append(f"{name}: id {identifier} is used more than once")
seen.add(identifier)
element_ids = {element.id for element in elements}
for relationship in relationships:
for end, value in (("from", relationship.source), ("to", relationship.target)):
if value not in element_ids:
problems.append(
f"{name}: Relationship {relationship.id} {end} {value}, "
"which is not an Element"
)
targets = element_ids | {relationship.id for relationship in relationships}
for check in checks:
if check.applies_to not in targets:
problems.append(
f"{name}: Check {check.id} applies to {check.applies_to}, "
"which is not an Element or Relationship"
)
checked = {check.applies_to for check in checks}
for element in elements:
if element.id not in checked:
problems.append(f"{name}: Element {element.id} has no Check")
if problems:
raise GraphError(problems)
return TargetArchitecture(elements, relationships, checks, not_applicable)
# --- the Requirements chain through the graph ----------------------------------------
def chain_gaps(
graph: TargetArchitecture,
*,
requirements: Sequence[Mapping[str, Any]],
components: Sequence[Mapping[str, Any]],
products: Sequence[Mapping[str, Any]],
recommendations: Sequence[Mapping[str, Any]],
) -> tuple[str, ...]:
"""Every place the Requirements chain stops before reaching a Check.
A functional requirement is carried by a component that has an Element, or by a
Check of its own. A non-functional requirement and a design recommendation are
each a constraint, so each must be the source of a Check (a recommendation may
instead be marked not applicable, with a reason).
"""
gaps: list[str] = []
requirement_ids = {item["id"] for item in requirements}
recommendation_ids = {item["id"] for item in recommendations}
sources = {check.source for check in graph.checks}
realised = {element.component for element in graph.elements if element.component}
for check in graph.checks:
if check.source not in requirement_ids | recommendation_ids:
gaps.append(
f"Check {check.id} has source {check.source}, which is not a "
"requirement or design recommendation"
)
for element in graph.elements:
if element.component and element.component not in {c["id"] for c in components}:
gaps.append(
f"Element {element.id} realises {element.component}, "
"which is not a component"
)
for component in components:
if component["id"] not in realised:
gaps.append(f"Component {component['id']} has no Element")
for requirement in requirements:
if requirement["id"] in sources:
continue
served = any(
requirement["id"] in component.get("requirements", ())
and component["id"] in realised
for component in components
)
if requirement.get("kind") == "functional" and served:
continue
gaps.append(f"Requirement {requirement['id']} has no Check")
for selection in products:
used = any(
element.component == selection["component"]
and element.product == selection["product"]
for element in graph.elements
)
if not used:
gaps.append(
f"Product {selection['product']} selected for "
f"{selection['component']} appears on no Element"
)
excused = {item.recommendation for item in graph.not_applicable}
for item in graph.not_applicable:
if item.recommendation not in recommendation_ids:
gaps.append(
f"not_applicable names {item.recommendation}, "
"which is not a design recommendation"
)
for recommendation in recommendations:
if recommendation["id"] not in sources | excused:
gaps.append(f"Recommendation {recommendation['id']} has no Check")
return tuple(gaps)
# --- the diagram is a view of the graph ----------------------------------------------
_UNSAFE = re.compile(r'["\[\]{}()<>|`#;]')
def _label(*parts: str) -> str:
return "<br/>".join(_UNSAFE.sub(" ", part).strip() for part in parts if part)
def _node_ids(ids: Iterable[str]) -> dict[str, str]:
"""Mermaid-safe node ids; the graph's own ids may hold characters Mermaid rejects."""
return {identifier: f"n{index}" for index, identifier in enumerate(ids)}
def render_mermaid(graph: TargetArchitecture) -> str:
"""The architecture diagram: every Element and Relationship, exactly once."""
nodes = _node_ids(element.id for element in graph.elements)
lines = ["flowchart LR"]
for element in graph.elements:
lines.append(
f' {nodes[element.id]}["{_label(element.name, element.product)}"]'
)
for relationship in graph.relationships:
lines.append(
f" {nodes[relationship.source]} -->|{_label(relationship.kind)}| "
f"{nodes[relationship.target]}"
)
return "\n".join(lines) + "\n"
# --- so are the tables a person reviews ----------------------------------------------
def _cell(text: str | None) -> str:
return " ".join((text or "").replace("|", "\\|").split())
def _table(
heading: str, columns: Sequence[str], rows: Iterable[Sequence[str | None]]
) -> str:
lines = [
f"## {heading}",
"",
"| " + " | ".join(columns) + " |",
"|" + "|".join(" --- " for _ in columns) + "|",
]
lines += ["| " + " | ".join(_cell(value) for value in row) + " |" for row in rows]
return "\n".join(lines)
def render_tables(graph: TargetArchitecture) -> str:
"""The graph as markdown tables: what a person approving the design reads.
Written by code, so the tables cannot disagree with the graph and no model spends
output repeating it.
"""
names = {element.id: element.name for element in graph.elements}
parts = [
_table(
"Elements",
("Id", "Name", "Product", "Resource type", "Component"),
(
(e.id, e.name, e.product, e.resource_type, e.component)
for e in graph.elements
),
),
_table(
"Relationships",
("Id", "From", "Kind", "To"),
(
(r.id, names[r.source], r.kind, names[r.target])
for r in graph.relationships
),
),
_table(
"Checks",
("Id", "Applies to", "Statement", "Source"),
((c.id, c.applies_to, c.statement, c.source) for c in graph.checks),
),
]
if graph.not_applicable:
parts.append(
_table(
"Not applicable",
("Recommendation", "Reason"),
((n.recommendation, n.reason) for n in graph.not_applicable),
)
)
return "\n\n".join(parts) + "\n"

View File

@@ -1,15 +0,0 @@
# Pre-emptive Live GCP Environment Discovery (Project: `gcp-solution-architecture-demo`)
## Live Resource Audit
- **Target Google Cloud Project**: `gcp-solution-architecture-demo`
- **Discovered Storage Buckets**: None / Default Bucket
- **Discovered Compute Instances**: None active
- **Discovered Database Instances**: None active
- **Discovered Pub/Sub Topics**: None active
- **Discovered Cloud Run Services**: None active
## Resource Inventory Breakdown
## Current Operational Bottlenecks & Migration Drivers
- As-is infrastructure requires serverless auto-scaling and managed high availability.
- Need for declarative IaC management via Terraform.
- Transition to least-privilege IAM service identities and automated CI validation.

View File

@@ -1,5 +0,0 @@
flowchart TD
subgraph GCPProject["Google Cloud Project: gcp-solution-architecture-demo"]
EmptyProject["Project gcp-solution-architecture-demo (No Active Resources Detected)"]
end
Client[External Traffic] --> GCPProject

View File

@@ -1,15 +0,0 @@
# Pre-emptive Live GCP Environment Discovery (Project: `gcp-solution-architecture-demo`)
## Live Resource Audit
- **Target Google Cloud Project**: `gcp-solution-architecture-demo`
- **Discovered Storage Buckets**: None / Default Bucket
- **Discovered Compute Instances**: None active
- **Discovered Database Instances**: None active
- **Discovered Pub/Sub Topics**: None active
- **Discovered Cloud Run Services**: None active
## Resource Inventory Breakdown
## Current Operational Bottlenecks & Migration Drivers
- As-is infrastructure requires serverless auto-scaling and managed high availability.
- Need for declarative IaC management via Terraform.
- Transition to least-privilege IAM service identities and automated CI validation.

View File

@@ -1,5 +0,0 @@
flowchart TD
subgraph GCPProject["Google Cloud Project: gcp-solution-architecture-demo"]
EmptyProject["Project gcp-solution-architecture-demo (No Active Resources Detected)"]
end
Client[External Traffic] --> GCPProject

View File

@@ -1,217 +0,0 @@
# Google Cloud solution architecture: Event-Driven Regional Workload
## 1. Executive summary and workload overview
This document serves as the comprehensive reference architecture guide for migrating an event-driven application from a legacy pre-existing environment to a highly available, serverless Google Cloud architecture.
## 2. Requirements and current state
### 2.1. Functional requirements
See [`docs/requirements.md`](docs/requirements.md). Requirements include Functional requirements, Non-functional requirements, constraints, assumptions, and open questions.
- Accept authenticated HTTPS requests from external clients.
- Execute stateless application logic behind a versioned service endpoint.
- Asynchronously publish domain events to Pub/Sub.
- Retain raw payload records in Cloud Storage for audit and replay.
### 2.2. Non-functional requirements
- **Security**: HTTPS TLS 1.3 encryption in transit, managed encryption at rest, least-privilege IAM service accounts.
- **Reliability**: 99.9% monthly endpoint availability target, regional high availability, Pub/Sub dead-letter topics.
- **Cost**: Serverless pay-per-use scaling from zero instances to reduce idle compute expense.
- **Operations**: Centralized logging via Cloud Logging and metrics via Cloud Monitoring.
- **Performance**: Sub-500ms p95 latency for ingestion acknowledgements under peak load.
- **Sustainability**: Efficient resource utilization via auto-scaling serverless runtimes.
### 2.3. Current state (As-Is Architecture)
# Pre-emptive Live GCP Environment Discovery (Project: `gcp-solution-architecture-demo`)
## Live Resource Audit
- **Target Google Cloud Project**: `gcp-solution-architecture-demo`
- **Discovered Storage Buckets**: None / Default Bucket
- **Discovered Compute Instances**: None active
- **Discovered Database Instances**: None active
- **Discovered Pub/Sub Topics**: None active
- **Discovered Cloud Run Services**: None active
## Resource Inventory Breakdown
## Current Operational Bottlenecks & Migration Drivers
- As-is infrastructure requires serverless auto-scaling and managed high availability.
- Need for declarative IaC management via Terraform.
- Transition to least-privilege IAM service identities and automated CI validation.
```mermaid
flowchart TD
subgraph GCPProject["Google Cloud Project: gcp-solution-architecture-demo"]
EmptyProject["Project gcp-solution-architecture-demo (No Active Resources Detected)"]
end
Client[External Traffic] --> GCPProject
```
### 2.4. Dependencies
- **Internal dependencies**: Service identity bindings and event consumer subscribers.
- **External dependencies**: Client HTTP submitters and OCI container image registry.
## 3. Technical decomposition of the workload
- **Ingress & Compute Layer**: Cloud Run service processing stateless HTTP webhook calls.
- **Messaging & Decoupling Layer**: Pub/Sub topic buffering domain event messages.
- **Storage & Audit Layer**: Cloud Storage buckets for raw payload audit log retention and Firestore for structured document state.
## 4. Proposed solution architecture
### 4.1. Google Cloud products and features mapping (Selected products)
| Component | Recommended Google Cloud product/feature | Justification and citations | Alternatives considered | Pros and cons of alternatives |
| :--- | :--- | :--- | :--- | :--- |
| **Compute** | **Google Cloud Run** | Fully managed serverless execution with auto-scaling to zero ([Cloud Run Docs](https://cloud.google.com/run/docs/overview)) | GKE / Compute Engine MIGs | **Pros**: Granular cluster control <br> **Cons**: Higher operational overhead & idle costs |
| **Messaging** | **Google Cloud Pub/Sub** | Asynchronous regional event bus with at-least-once delivery ([Pub/Sub Docs](https://cloud.google.com/pubsub/docs/overview)) | Cloud Tasks / Kafka | **Pros**: Advanced queuing controls <br> **Cons**: Complex cluster management |
| **Storage** | **Google Cloud Storage & Firestore** | Durable object retention with lifecycle rules & NoSQL document database | Cloud SQL | **Pros**: Relational ACID support <br> **Cons**: Less flexible scaling for unstructured event logs |
### 4.2. Architecture diagram (Mermaid)
```mermaid
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
```
### 4.3. Architecture description
- **Data flow**: Clients send HTTPS requests to Cloud Run -> Cloud Run writes payload to Cloud Storage & publishes event to Pub/Sub -> Subscriber worker consumes event.
- **Tasks/control flow**: Client request -> Token validation -> Pub/Sub acknowledgement -> Async worker trigger.
## 5. Design and configuration recommendations
### 5.1. Security, privacy, and compliance
- **Access control**: Least-privilege IAM service accounts bound to publisher roles.
- **Data protection**: Managed encryption at rest for Pub/Sub and Storage.
- **Network Security**: Serverless VPC Access connector for isolated network egress.
### 5.2. Reliability
- **Redundant deployment**: Regional Cloud Run service and Pub/Sub multi-zone replication.
- **Backup and DR**: Cross-region bucket replication and dead-letter retry topic.
### 5.3. Operational excellence
- **Monitoring and logging**: Integrated Cloud Logging and Cloud Monitoring alerts.
- **Infrastructure as Code (IaC)**: Version-controlled Terraform HCL blueprints.
### 5.4. Cost optimization
- **Sizing and scaling**: Automatic scale-to-zero compute instances.
### 5.5. Performance efficiency
- **Caching and CDN**: Edge CDN caching for static endpoints.
### 5.6. Sustainability
- Serverless compute adoption minimizing idle carbon footprint.
## 6. Deployment guidance
### 6.1. Deployment prerequisites
- Enable required Google Cloud APIs (`run.googleapis.com`, `pubsub.googleapis.com`, `storage.googleapis.com`).
- Install Terraform >= 1.5.0 and Google Cloud SDK (`gcloud`).
### 6.2. Step-by-step deployment instructions (Terraform)
```hcl
# 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}"
}
```
Apply blueprint instructions:
```bash
terraform -chdir=terraform init
terraform -chdir=terraform plan -var='project_id=YOUR_PROJECT_ID' -var='container_image=IMAGE_URI'
terraform -chdir=terraform apply
```
## 7. Validation plan (Validation results)
# Validation Results
## Summary
- **Overall Validation Status**: PASS
- **Mermaid Diagram Syntax**: PASS
- **Terraform Structural Check**: PASS
- **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
### Verification Checklist
- Step 4 guide persistence: non-empty solution-architecture-guide.md.
- Step 5 template/workflow conformance: verified requirements, architecture, Terraform, diagram.
- Step 6 & 7 publication & remote verification: complete.
## 8. References
- [Google Cloud Architecture Framework](https://cloud.google.com/architecture/framework)
- [Cloud Run Overview](https://cloud.google.com/run/docs/overview/what-is-cloud-run)
- [Cloud Pub/Sub Overview](https://cloud.google.com/pubsub/docs/overview)

View File

@@ -1,21 +0,0 @@
# 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)
- [Google Cloud Run Architecture Guide](https://cloud.google.com/run/docs/overview/what-is-cloud-run)

View File

@@ -1,6 +0,0 @@
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

View File

@@ -1,44 +0,0 @@
# Step 0 — Requirements discovery
## Workflow request
Design an event-driven regional HTTP application that accepts incoming webhooks, validates signatures, durably enqueues payloads to Pub/Sub, and retains raw events in Cloud Storage for 30-day replay audit.
## Functional requirements
- Accept authenticated HTTPS requests from external clients.
- Execute stateless application logic behind a versioned service endpoint.
- Publish asynchronous domain events from the application.
- Process events independently and tolerate retry/redelivery.
- Persist durable objects and application state separately.
- Expose operational logs, metrics, and audit-relevant events.
- Support repeatable infrastructure changes through declarative IaC.
## Non-functional requirements
- High availability within a selected Google Cloud region.
- Horizontal scale for bursty HTTP traffic and asynchronous work.
- At-least-once event delivery with idempotent consumers.
- Encryption in transit and at rest using managed defaults initially.
- Least-privilege runtime identities and private network egress where practical.
- Observable deployments with structured logs and actionable health signals.
- Reproducible, reviewable, non-deployment validation in CI.
## Constraints
- Google Cloud is the target cloud; exact products are not selected in discovery.
- Terraform must be deployable without embedding secrets or credentials.
- The baseline must not provision resources during validation.
- A container image must be supplied by the application delivery pipeline.
- State backends, DNS ownership, identity federation, and organization policies are external concerns.
## Assumptions
- A single region is acceptable for the initial deployment.
- The application can be packaged as an OCI container listening on port 8080.
- Events can use at-least-once semantics and consumers can deduplicate.
- A dedicated Google Cloud project is available.
- Managed encryption keys and public ingress are acceptable defaults pending review.
## Open questions
- What are the actual API, event, data-retention, and compliance requirements?
- Which clients and identity provider must authenticate requests?
- What are traffic, payload-size, latency, RTO, and RPO targets?
- Which data is relational, document, object, or analytical?
**Product selection deferred:** `true` for this phase.

View File

@@ -1,14 +0,0 @@
# Validation Results
## Summary
- **Overall Validation Status**: PASS
- **Mermaid Diagram Syntax**: PASS
- **Terraform Structural Check**: PASS
- **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

View File

@@ -1,15 +0,0 @@
# Pre-emptive Live GCP Environment Discovery (Project: `gcp-solution-architecture-demo`)
## Live Resource Audit
- **Target Google Cloud Project**: `gcp-solution-architecture-demo`
- **Discovered Storage Buckets**: None / Default Bucket
- **Discovered Compute Instances**: None active
- **Discovered Database Instances**: None active
- **Discovered Pub/Sub Topics**: None active
- **Discovered Cloud Run Services**: None active
## Resource Inventory Breakdown
## Current Operational Bottlenecks & Migration Drivers
- As-is infrastructure requires serverless auto-scaling and managed high availability.
- Need for declarative IaC management via Terraform.
- Transition to least-privilege IAM service identities and automated CI validation.

View File

@@ -1,5 +0,0 @@
flowchart TD
subgraph GCPProject["Google Cloud Project: gcp-solution-architecture-demo"]
EmptyProject["Project gcp-solution-architecture-demo (No Active Resources Detected)"]
end
Client[External Traffic] --> GCPProject

Some files were not shown because too many files have changed in this diff Show More