Compare commits
12 Commits
a8ed21b89d
...
feat/solut
| Author | SHA1 | Date | |
|---|---|---|---|
| a48468d477 | |||
| f9cc34817b | |||
| 7ee7054523 | |||
| c4c8a1f94e | |||
| 135401e41b | |||
| 81ac135cd9 | |||
| 5feaaa6271 | |||
| ee1ba38867 | |||
| 1cf1234143 | |||
| 71da0ed504 | |||
| 10d23a5f91 | |||
| ef37f59bad |
@@ -13,6 +13,7 @@ One directory per iteration of this agent. Each holds the plan for that iteratio
|
||||
| 5 | `iter-05-jev-decisions/` | the router, intake, the reviews, pillar selection, Skill routing, the guardrail, meaning-aware change summaries and an assessment of every Execution are built (steps 2–5, 8, 10–12, 14, 15, 19), the newest ran in cases 05 and 06 on 2026-10-09; a lighter model for a first attempt was built, measured and left off (6); context selection and compaction were decided against on the numbers (7, 9); the cloud-read guard and readings as a node are planned (13, 18) | Jev (a hosted decision model) for the agent's closed decisions: checks, routing, context selection. |
|
||||
| 6 | `iter-06-target-architecture-graph/` | complete: all four cases pass with real models, each run twice on 2026-10-08; thresholds set | 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/` | complete (2026-10-09): the change case ran with real models and passed | 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. |
|
||||
| 8 | `iter-08-terraform-modules/` | steps 1–5 built and run once each way on 2026-10-09, both at 100%; steps 6 and 7 wait on Azure and AWS provider bundles | Infrastructure code is plain resources by default. An Execution may opt into published Terraform modules: only from registry namespaces the provider bundle lists, at one exact version, with a lookup of what a module accepts and a Skill of four Google modules tested against the pinned provider. |
|
||||
|
||||
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.
|
||||
|
||||
|
||||
@@ -28,7 +28,7 @@
|
||||
| 9 | ADR: the lessons loop and overlay Skills | B | S | complete: ADR-0004 accepted 2026-10-08 |
|
||||
| 10 | Lessons Skill and lesson curator | B | L | the loop is built; six lessons proposed from 21 Executions, approved by the owner and published on 2026-10-09; not yet proved by an evaluation with and without (`steps/step-10.md`) |
|
||||
| 11 | IaC patterns Skill | B | M | built; in case 01 the IaC author fell from 57 requests to 11 with no Revision; other cases unmeasured |
|
||||
| 12 | Overlay Skills and an organisation standards Skill | C | M | built, with an example standards Skill; case 06 passed with it on 2026-10-09 and the code follows the standards |
|
||||
| 12 | Overlay Skills and an organisation standards Skill | C | M | built, with an example standards Skill; case 06 passed on 2026-10-09, failed once on 2026-10-10 for a wrong verdict, and passed again after the fix, now with a check that the code follows the standards |
|
||||
| 13 | Trim Specialist context | C | M | built; measured on case 01 only, together with steps 11 and 17 |
|
||||
| 14 | Provider-owned contracts | C | M | deferred by its own plan until a second Cloud provider is planned (ADR-0002) |
|
||||
| 15 | Group Executions by Customer case | added | S | complete |
|
||||
@@ -44,6 +44,8 @@
|
||||
| 25 | An Execution that ends with warnings keeps its files | added | S | complete |
|
||||
| 26 | Each pillar's checklist is reviewed and the review is in the Deliverable | added | S | built; a judged run of case 04 scored the checklist check at 100% on every pillar |
|
||||
| 27 | A user sees a Deliverable before it is first submitted | added | S | built; case 04 passed the check on 2026-10-09, with the rule not needing to refuse |
|
||||
| 28 | Housekeeping: files written as an Execution goes, four more code patterns | none | S | built 2026-10-10 (`steps/step-28.md`) |
|
||||
| 29 | What the request does not say is a question for the customer | none | M | built 2026-10-10: a fourth checklist outcome, a questions report, and the judged check counts it; not run (`steps/step-29.md`) |
|
||||
|
||||
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.
|
||||
|
||||
|
||||
@@ -73,3 +73,49 @@ Case 03, one run each way, side by side, with the five lessons that remain (`202
|
||||
`prove` recorded this in the proposals as "kept". One pair suggests a direction and does not settle it: a third run the same evening, with lessons, did need a Revision of the Target architecture. `prove` also wrote to L-04's proposal, which is retired; it should skip retired lessons.
|
||||
|
||||
Neither run raised the schema review's false alarm, which had been raised in case 06 before the fix.
|
||||
|
||||
## Housekeeping, 2026-10-10
|
||||
|
||||
- **`prove` skips retired lessons.** It wrote its comparison into L-04's proposal after L-04 had been retired. It now writes only for lessons the Skill holds. L-04's proposal is corrected.
|
||||
- **Lessons are flagged when the vendored Skills change.** The lessons Skill keeps `upstream.json`: the version of each vendored Skill the lessons were last read against. `status` names the ones that have changed since and says to read each lesson again; `reviewed` records that a person has. A test fails until then, so a sync of the vendored Skills cannot go unnoticed. The first publish records the versions; after that only `reviewed` moves them.
|
||||
- **`status` says "compared", not "proved",** and shows a retired lesson as retired. One pair of runs is a comparison.
|
||||
|
||||
Tests: `tests/test_lessons_loop.py`.
|
||||
|
||||
## Evidence is also grouped by what it is about (2026-10-10)
|
||||
|
||||
Running `propose` over 32 Executions gave nothing useful. Evidence was grouped by the kind of problem, and a group gets one lesson: "validation proposed a Check the design lacked" was 20 of 32 Executions and already had L-01. What recurred inside it could not be seen.
|
||||
|
||||
- A proposed Check, and a Check sent back as unimplementable, is now also counted under each provider setting or resource type its text names (`_subjects` in `app/learning/evidence.py`). A subject seen in two or more Executions is its own group, with its own key. A setting's name is the provider's vocabulary, not a client's.
|
||||
- These narrower groups skip triage: each recurred with the general lessons published. The curator is shown the existing lessons and may still decline.
|
||||
- The curator's instructions say such a lesson may name the setting or resource type.
|
||||
|
||||
Over the same 32 Executions this gave 22 groups and five proposals, L-07 to L-11, all awaiting the owner: location Checks, Cloud SQL backup encryption, backend service capabilities, Pub/Sub persistence regions, and customer-managed keys.
|
||||
|
||||
A first run of `propose` before this change produced one proposal, about giving `edit_file` enough context. It was removed to run again cleanly and was not proposed the second time.
|
||||
|
||||
Tests: `tests/test_lessons_loop.py` (3 more).
|
||||
|
||||
## The three new lessons, run once (2026-10-10)
|
||||
|
||||
Case 03, two runs with the eight lessons (`20261010T114823Z`, `20261010T114827Z`). Both completed at 100%.
|
||||
|
||||
| | Run 1 | Run 2 |
|
||||
|---|---|---|
|
||||
| Minutes | 30 | 37 |
|
||||
| Cost, about | $3.27 | $5.19 |
|
||||
| Revisions of the Target architecture | 1 | 2 |
|
||||
|
||||
None of the three faults the new lessons name came back: no separate backup encryption key, no backend service fault. The Revisions were for other things:
|
||||
|
||||
- The validator proposed a Check that the service identity holds no project-wide administrative role.
|
||||
- A Check asked for an encryption key and the design had no key Element for it to name.
|
||||
- A Check that the region has a high carbon-free energy score could not be verified from the code.
|
||||
|
||||
The last is partly L-07's doing. It says to add a location Check where a requirement asks for a low-carbon location, and the architect wrote one about the carbon score, which no code can show.
|
||||
|
||||
Across the twelve runs of this request on 2026-10-09 and 10 the Target architecture was revised 0, 1, 1, 1, 1, 3, 1, 1, 0, 1, 1 and 2 times. Lessons have removed particular faults and not lowered the count: each run finds another.
|
||||
|
||||
## Fixed at its source: what only the provider publishes
|
||||
|
||||
The carbon-score condition came up in at least five runs, as a gap, as an unverifiable Check and as noise in two reviews. It was being written as a condition for code. The requirements-chain Skill and the two roles that write conditions now say that a property of a region or product that only its provider publishes (a carbon rating, a service level) goes under `outside_code`, and the condition is the choice configuration can show, such as which region is set. Not run.
|
||||
|
||||
@@ -27,3 +27,27 @@ No evaluation check scores whether an overlay was followed; this was read from t
|
||||
## An evaluation check, later on 2026-10-09
|
||||
|
||||
A case may now carry `code_standards`: regular expressions the infrastructure code must contain or must not, scored as `code_follows_standards`. Case 06 has six: only approved regions, names carrying the environment from a variable, and the four labels. Run against the code case 06 produced earlier today, it passes.
|
||||
|
||||
## Rerun on 2026-10-10: case 06 failed, case 04 passed
|
||||
|
||||
Both rerun after the week's changes (`20261010T123446Z` case 04, `20261010T123450Z` case 06).
|
||||
|
||||
**Case 04, interactive: completed, 12 of 12 checks, 34 minutes, about $4.58,** one Revision of the Target architecture. Nothing in routing, intake, the guardrail or the writing of files as it goes broke it.
|
||||
|
||||
**Case 06, overlay: ended with warnings, 67%, 42 minutes, about $7.72.** The Target architecture reached its Revision limit of 3 and no guide was packaged. Two separate causes:
|
||||
|
||||
- **A verdict that was wrong, and no way to say so.** Check K-10 says a role is granted to the service identity. It was. The validator failed it because the identity also held three other roles that other Checks require. The IaC author, sent the failure, could change nothing, and recorded the Check as unimplementable with the reason "the validator insists on only this role". That sent the design back for a fault it did not have. The same Check passed in the validation between, on the same grants: the validator was not consistent. The other two Revisions were ordinary ones (labels and names the overlay asks for, and a resource whose name cannot contain hyphens).
|
||||
- **The evaluation's naming check was too narrow.** `code_follows_standards` wanted a variable with "env" in its name inside each resource name. The code built names from `local.name_prefix`, itself made from `var.workload` and `var.environment`, which follows the standard. The check now asks that names are built from a variable or local, and that the environment comes from a variable; this run's code and the earlier run's both pass it.
|
||||
|
||||
Changed, not yet run:
|
||||
|
||||
- The validator is told to judge each Check by its own words: a Check that something is granted or set passes when it is, whatever is beside it, unless it says "only". What else it thinks should hold is a proposed addition, never a failure.
|
||||
- The IaC author is told what to do when a Check failed and the code already meets its words: change nothing, keep the implementation entry, name the Check it disputes, and not record it as unimplementable.
|
||||
|
||||
An overlay also makes a design larger: this run ended with over 120 Checks, against 50 to 90 for the same request without one.
|
||||
|
||||
## Case 06 again, with the fixes (2026-10-10)
|
||||
|
||||
`20261010T134034Z`: completed, 100%, 45 minutes, about $5.43, 126 Checks, all passed. `code_follows_standards` passed. Two Revisions of the Target architecture, both ordinary: locations the validator wanted checked (L-10's subject, the persistence regions of a topic, among them), and two Checks on one secret that contradicted each other.
|
||||
|
||||
No Check was failed for something it does not say, and none was disputed, so the two new instructions were not put to the test: the run shows they do no harm, not that they work.
|
||||
|
||||
21
.agents/plans/iter-04-learning-and-skills/steps/step-28.md
Normal file
21
.agents/plans/iter-04-learning-and-skills/steps/step-28.md
Normal file
@@ -0,0 +1,21 @@
|
||||
# Step 28 — Housekeeping (2026-10-10)
|
||||
|
||||
Small things found during the runs of 2026-10-09. Not run with real models unless said.
|
||||
|
||||
## Files are written as an Execution goes
|
||||
|
||||
An Execution's folder was written only when it ended, so a killed process, or an Execution left waiting for its user, left nothing on disk.
|
||||
|
||||
- Each time a Deliverable is submitted, the folder is written with what exists, and `execution.json` says `in_progress`. The end of the Execution writes it again with its final status.
|
||||
- An in-progress Execution is refused as a Baseline, as any Execution that did not complete is.
|
||||
- Because the folder is now written more than once, a write removes the files an earlier write recorded and this one does not have. Without that, a Terraform file removed in a Revision would have stayed beside the files that replaced it. Only files the Execution itself wrote are removed.
|
||||
|
||||
Tests: `tests/execution/test_outputs_as_it_goes.py` (2).
|
||||
|
||||
## Four more code patterns
|
||||
|
||||
`skills/google-cloud-iac-patterns/` gains Firestore, BigQuery, Eventarc and Google Kubernetes Engine, 18 in all. Each validates against `hashicorp/google` 8.6.0 in `tests/test_iac_patterns.py`.
|
||||
|
||||
## The two explainer pages
|
||||
|
||||
Both now describe the opt-in to published Terraform modules.
|
||||
24
.agents/plans/iter-04-learning-and-skills/steps/step-29.md
Normal file
24
.agents/plans/iter-04-learning-and-skills/steps/step-29.md
Normal file
@@ -0,0 +1,24 @@
|
||||
# Step 29 — What the request does not say is a question for the customer
|
||||
|
||||
Built on 2026-10-10, on the owner's direction. **Not run with real models.**
|
||||
|
||||
## What prompted it
|
||||
|
||||
The owner labelled the judge's 32 questions (iteration 5 step 16): yes to all 24 checklist items. Both judges had answered no to most; they agreed with the labels on 28% and 16%. The owner's reading was deliberate: where a checklist item is unanswered because the customer's request gives no information about it, that is not the design failing a standard. It is missing information, and should come back as a question to put to the customer.
|
||||
|
||||
The checklist review had three outcomes: addressed, does not apply, not addressed. The third was the only place such an item could go, and it reads as a fault.
|
||||
|
||||
## What was built
|
||||
|
||||
- **A fourth outcome, `needs_customer_input`** ("To confirm with the customer"), in `app/tools/pillars.py`. A pillar advisor gives it to an item that could apply where its brief does not say what would settle it, and must give the question to ask; without the question its submission is refused. `not_addressed` is now only for an item the brief gives enough to settle, that applies, and that nothing is recommended for.
|
||||
- **The questions are reported.** Code writes a "Questions for the customer" table into the design recommendations, under the checklist review, saying they are not faults in the design. An Execution also writes `customer-questions.md` beside its other files, and `execution.json` names it. The packager carries the section into the guide.
|
||||
- **The evaluation counts it as accounted for.** The judged check asks whether the recommendations account for an item by recommending it, by explaining why it does not apply, or by recording it as something to confirm with the customer (`checklist_question` in `app/tools/assessment.py`, used by the evaluation and by calibration).
|
||||
- **Glossary:** Customer question.
|
||||
|
||||
Nothing is asked of the user during an Execution for these: they are reported. Whether an interactive Execution should put them to the user before the design is approved is not decided.
|
||||
|
||||
## The judge's question set
|
||||
|
||||
The owner's labels were not kept. The two saved documents predate the checklist review, so they hold neither statuses nor questions, and the question's wording has changed. The set has to be rebuilt from design recommendations produced after this step (`eval.calibrate_judge --build`, after replacing the two documents), and labelled again. That needs a run.
|
||||
|
||||
Tests: `tests/execution/test_pillars.py` (4 more).
|
||||
@@ -75,7 +75,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 |
|
||||
| 1 | Resolve the open questions | none | the vendor's answers on retention, training, context and rate limits recorded on 2026-10-10, with the owner's decisions; retention for client work is held (`steps/step-1.md`) |
|
||||
| 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 | built, as a graded question; calibrated live; ran in cases 05 and 06 on 2026-10-09 |
|
||||
| 4 | Semantic checks at submission | J4 | two reviews built, both off until a full case has run with them: coverage of the Target architecture, one choice per condition; and requirements name no products (`steps/step-4.md`) |
|
||||
@@ -90,7 +90,7 @@ Jev answers closed questions. Writing Deliverables, grounding product choices an
|
||||
| 13 | Cloud-read call guard | J7 | planned; cloud reads are off in every case, so it could not be exercised |
|
||||
| 14 | Input guardrail | J11 | built and on: an MCP reply that instructs the agent is withheld, the user's text is flagged; calibrated live; ran in cases 05 and 06 on 2026-10-09 |
|
||||
| 15 | Changes of meaning in a Change request | none | built: reworded items are listed apart in changes.json; calibrated live; ran in case 05, where nothing was reworded |
|
||||
| 16 | Jev as the evaluation judge, calibrated | none | judge and calibration built; stability and agreement between judges measured (`steps/step-16.md`); agreement with a person's labels awaits the owner's 32 labels |
|
||||
| 16 | Jev as the evaluation judge, calibrated | none | judge and calibration built; the owner labelled the set on 2026-10-10, which showed the question was wrong, not the judges; the set is to be rebuilt and relabelled after iteration 4 step 29 (`steps/step-16.md`) |
|
||||
| 17 | Trace every decision | none | open, owner's decision on LangSmith |
|
||||
| 18 | Readings as their own graph step | none | planned; it splits the Orchestrator turn that case 04 only just passes, to save a repeated Jev call after a crash |
|
||||
| 19 | Online evaluation of live Executions | none | built and on: each Execution's design recommendations are judged when it ends and the scores kept in its record; feedback on a trace waits on step 17 (`steps/step-19.md`) |
|
||||
|
||||
37
.agents/plans/iter-05-jev-decisions/steps/step-1.md
Normal file
37
.agents/plans/iter-05-jev-decisions/steps/step-1.md
Normal file
@@ -0,0 +1,37 @@
|
||||
# Step 1 — The open questions, and the owner's decisions of 2026-10-10
|
||||
|
||||
## What the vendor says
|
||||
|
||||
Supplied by the owner on 2026-10-10. Not verified here against the vendor's documents.
|
||||
|
||||
| Question | Answer |
|
||||
|---|---|
|
||||
| Data retention | No fixed period for a standard account: data is kept "for as long as reasonably necessary". Zero data retention is available to enterprise customers on request, through Cloudflare Workers AI, or through Vercel AI Gateway. |
|
||||
| Model training | Customer prompts, inputs and outputs are not used to train or fine-tune the vendor's models. |
|
||||
| Context | 64,000 tokens a request in total, with 32,000 for the state plus the longest question. |
|
||||
| Rate limits | Up to 80 requests a second and 100,000 tokens a second on the standard hosted service, adjusted with platform traffic. |
|
||||
|
||||
Against the client's own limits (`JevLimits` in `app/tools/jev.py`): it caps a request at 48,000 and 24,000 tokens, inside the service's; and throttles itself to 5 requests a second with 8 in flight, a sixteenth of the service's rate. Nothing needs changing for either.
|
||||
|
||||
Still open: latency, and whether the vendor's SDK can be pointed at either gateway.
|
||||
|
||||
## What is sent to Jev
|
||||
|
||||
ADR-0007's decision 4 limits an Orchestrator decision to the Execution's state. The uses built since send content: the user's messages and the request (routing, intake, guardrail), replies from documentation servers (guardrail), the design recommendations (assessment), the text of Checks, Elements and recommendations (meaning), a change and the list of Elements (pillar selection, reference routing), and each requirement's text when the requirements review is on.
|
||||
|
||||
## The owner's decisions
|
||||
|
||||
| Question | Decision |
|
||||
|---|---|
|
||||
| Re-verify only what changed after a Revision | **No.** Every validation stays complete. The saving was 5 to 10% on some runs, and the risk fell on the validator. |
|
||||
| The requirements review (`JEV_REQUIREMENTS_REVIEW`) | **On for the next runs that happen anyway; the default if they are clean.** No run is to be made for it. Cases 01 and 02 are held until the owner says. |
|
||||
| Tracing (step 17) | **Held.** No decision. |
|
||||
| The judge against a person (step 16) | **The owner will label the 32 questions.** |
|
||||
| Jev's data retention, for client work | **Held.** No decision. |
|
||||
|
||||
## Advice given, with no decision asked
|
||||
|
||||
- With no training use, the remaining exposure is content kept by the vendor for an unstated time. Zero retention is the only route that costs the agent nothing. A switch that keeps Deliverable content away from Jev is a stopgap; even routing a reply sends that reply.
|
||||
- The owner may look for an open-source version of Jev. That would end the retention question. Its cost is that every threshold, tuned against the hosted model's probabilities, would need measuring again, and the two properties relied on (the same answer every time, clean separation) would need proving again. The agent is placed for it: one interface, every threshold a setting, every use a fallback.
|
||||
- **A gap either way:** the calibrations in this plan were made with one-off scripts; the example sets are not in the repository. Kept as a runnable suite they could be put to any model. Not built.
|
||||
- The owner's 32 labels are the one measure that depends on no model.
|
||||
@@ -76,3 +76,14 @@ Not built: acting on a change request (iteration 7 step 2), and answering a ques
|
||||
|
||||
Tests: `tests/execution/test_intake.py` (4), `tests/a2a/test_server.py` "intake" (4), `tests/execution/test_router.py` (1).
|
||||
|
||||
## A question about delivered work is answered from it (2026-10-10)
|
||||
|
||||
Intake answered every question with a description of the service. A question read as about work already delivered in the caller's Customer case is now answered from that Execution's solution guide.
|
||||
|
||||
1. When intake reads a message as a question and the case has a completed Execution, a second yes or no is asked: is this about an architecture already delivered, or about the service in general. At 0.6 or above it is about delivered work.
|
||||
2. `DeliveredAnswers` in `app/nodes/intake.py` loads the latest completed Execution and gives its solution guide and the question to the reply writer. `agents/reply-writer.md` now covers this second task: answer from the guide alone, say so when it does not say, name the section, propose no change.
|
||||
3. The A2A reply carries `about`, the Execution it was answered from. Nothing is started. When no answer could be written the caller is told which Execution's documents to read.
|
||||
|
||||
Measured against live Jev on twelve messages: six about delivered work scored 0.37 to 0.96, five of them 0.73 or more ("what does the load balancer in my architecture do?" scored 0.37 and would get the general answer). Five about the service scored 0.07 to 0.16. "Is my data stored anywhere?" scored 0.74: it is ambiguous, and would get an answer from the guide. **No real model has written such an answer yet.**
|
||||
|
||||
Tests: `tests/execution/test_intake.py` (3 more), `tests/a2a/test_server.py` (3 more).
|
||||
|
||||
@@ -18,3 +18,9 @@ So Jev gave the same answer every time, the language-model judge changed its ans
|
||||
**Open, and the owner's to do:** fill in the 32 labels (1 or 0 for a yes_no question; 0, 0.33, 0.67 or 1 for a graded one) and run `.venv/bin/python -m eval.calibrate_judge` again. Only that gives agreement with a person, which is what decides the default judge.
|
||||
|
||||
Tests: `tests/eval/test_scoring.py`, "calibrating the judges" (2).
|
||||
|
||||
## The owner's labels, 2026-10-10
|
||||
|
||||
The owner labelled all 32: yes to every checklist item, "mostly" on every quality question. Against them Jev agreed on 28% and Gemini on 16%; the judges answer no to most checklist items (means 0.37 and 0.32), and agree with each other on 88%.
|
||||
|
||||
The disagreement was about the question, not the judges. The owner counts an item the request gives no information about as something to ask the customer, not as unaddressed. That is now an outcome of the checklist review and part of the judged question (iteration 4 step 29). The labels were not kept, and the set is to be rebuilt from documents produced after that change.
|
||||
|
||||
@@ -57,6 +57,8 @@ flowchart TD
|
||||
| 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 | complete: all four cases pass, each run twice on 2026-10-08; thresholds set (`steps/step-11.md`) |
|
||||
| 12 | Why the Target architecture is revised | S | investigated 2026-10-10: two causes, about half each; two instructions changed; the design-time coverage review it proposed is step 13 (`steps/step-12.md`) |
|
||||
| 13 | A model reviews coverage at design time | M | built and measured on 2026-10-10: it did not prevent the validator's gaps and made designs larger; left off (`steps/step-13.md`) |
|
||||
|
||||
Size: S under a day, M a few days.
|
||||
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
# Step 12 — Why the Target architecture is revised
|
||||
|
||||
An investigation on 2026-10-10, from the seven runs of case 03's request on 2026-10-09 (cases 03, 06 and 07). No new runs were made for it.
|
||||
|
||||
## What was found
|
||||
|
||||
Six of the seven runs revised the Target architecture, nine times in all. The run with none cost about $2.44 and took 22 minutes; the run with three cost $5.50 and took 35. Every Revision has one of two causes.
|
||||
|
||||
**A. A Check the code cannot meet as written: 4 Revisions in 3 runs.** The IaC author records it as unimplementable and the design is revised before validation.
|
||||
|
||||
| Check asked for | Why no code can meet it |
|
||||
|---|---|
|
||||
| A separate encryption key for database backups | The key is set on the instance; backups have no key of their own |
|
||||
| A database flag that restricts query access (twice, one Revision apart) | There is no such flag; access is IAM and database grants |
|
||||
| A health check on a backend service in front of a serverless endpoint | A serverless backend does not take health checks |
|
||||
|
||||
Each names a setting that exists in the provider's schema, so the schema review passes it. The fault is in what the product does, not in a name.
|
||||
|
||||
**B. A condition no Check verifies, found by the validator: 5 Revisions in 4 runs.**
|
||||
|
||||
| Requirement | What was missing |
|
||||
|---|---|
|
||||
| NFR-9 | Deletion protection on one Element |
|
||||
| NFR-4 | An SSL policy enforcing TLS 1.2, attached to the proxy |
|
||||
| DR-15 | The region set on three Elements |
|
||||
| NFR-10 | The alert's two thresholds; the Check said only that conditions were set |
|
||||
| NFR-6 | Audit logs for secret access switched on |
|
||||
|
||||
In four of the five a Check existed for the requirement and was weaker than the requirement's words.
|
||||
|
||||
A Revision for A costs about 4 minutes: the design, then the code. One for B costs about 6: the design, the code, and the whole validation again.
|
||||
|
||||
## Would the coverage review have caught B
|
||||
|
||||
`CoverageReview` (iteration 5 step 4), which asks Jev which Check verifies each condition, has been off since its first run. Tried offline against live Jev on these runs' delivered designs:
|
||||
|
||||
- On five finished designs the validator had accepted, it raised 4 to 8 of 42 to 66 conditions each, about one in ten. Most are conditions a Check does cover in other words, or that no code can show, such as encryption at rest that is on by default.
|
||||
- With the Checks added for each gap taken out again, it raised the gap in 1 of 5 (DR-15), raised a different condition of the same requirement in 1, and missed 3.
|
||||
|
||||
It stays off. It is noisy and it misses what the validator finds.
|
||||
|
||||
A structural rule, each Check naming the condition it verifies, would have caught perhaps one of the five: in the other four a Check did claim the condition and was too weak.
|
||||
|
||||
## Changed now
|
||||
|
||||
Two instructions, from the run where the same fault came back a Revision later:
|
||||
|
||||
- The reason sent to the target architect for an unimplementable Check now says to read every Check against it and correct each one it applies to (`app/nodes/router.py`).
|
||||
- The IaC author is told to record every Check that cannot be met in one submission, including a Check with the same fault as one already recorded (`agents/iac-author.md`).
|
||||
|
||||
Neither has run with a real model.
|
||||
|
||||
## What would address B
|
||||
|
||||
The validator finds these gaps by reading the requirements against the Checks. That reading needs no code: it could be done when the Target architecture is submitted, by the same kind of model, and returned to the target architect before anyone approves the design or writes anything. It would add one model run to every Execution and remove a Revision of the design, the code and the validation from the four in seven that had one. Not built: it needs a decision, and a run each way to measure.
|
||||
@@ -0,0 +1,45 @@
|
||||
# Step 13 — A model reviews coverage at design time: built, measured, left off
|
||||
|
||||
Built and run on 2026-10-10. `DESIGN_COVERAGE_REVIEW` is off.
|
||||
|
||||
## What was built
|
||||
|
||||
Step 12 proposed making the validator's reading of coverage when the Target architecture is first submitted, before any code.
|
||||
|
||||
- `agents/coverage-reviewer.md`: a role on the validator's model. It is given the non-functional requirements, the recommendations and the graph, and reports every condition no Check verifies, or that a Check verifies more weakly than the words.
|
||||
- `DesignCoverageReview` in `app/tools/design_review.py`, on the submission-review seam: what it finds goes back to the target architect once and never blocks. A gap naming an id that does not exist is dropped. It runs once in an Execution.
|
||||
|
||||
Tests: `tests/execution/test_design_review.py` (7).
|
||||
|
||||
## Measured
|
||||
|
||||
Case 03, three runs side by side.
|
||||
|
||||
| | Review off | Review on | Review on |
|
||||
|---|---|---|---|
|
||||
| Results | `20261010T105532Z` | `20261010T105535Z` | `20261010T105540Z` |
|
||||
| Score | 100% | 100% | 100% |
|
||||
| Minutes | 23 | 28 | 31 |
|
||||
| Cost, about | $2.90 | $3.33 | $3.75 |
|
||||
| Revisions of the Target architecture | 1, a Check that cannot be implemented | 0 | 1, a gap the validator found |
|
||||
| Gaps the reviewer raised | | 4 | 22 |
|
||||
| Checks in the delivered design | 52 | 87 | 93 |
|
||||
|
||||
The reviewer itself cost $0.19 a run.
|
||||
|
||||
## Why it stays off
|
||||
|
||||
- **It did not stop the validator sending the design back.** In one of the two runs the validator still found a gap, after the reviewer had raised 22.
|
||||
- **It makes the design bigger.** The designs it reviewed ended with 87 and 93 Checks against 52. Every Check is code to write and a verdict to give, so both runs cost more than the run without it, including the one with no Revision.
|
||||
- **Two readers do not agree on what a gap is.** The reviewer and the validator are the same model given the same question, and they raised different things. Asking earlier does not settle what will be asked later.
|
||||
|
||||
Three runs are a small sample, but nothing in them points the other way. The code stays, off, for a later look; removing it is the owner's call.
|
||||
|
||||
## What the runs did show
|
||||
|
||||
Two of the faults behind Revisions are now recurring ones, which is what the lessons loop is for:
|
||||
|
||||
- **A Check asking for a separate encryption key for database backups**: unimplementable, on 2026-10-09 and again today.
|
||||
- **A condition that a region is "low-carbon"**: the validator's gap today, and among what the Jev coverage review kept raising on 2026-10-09. Code can show which region is set; it cannot show the region's carbon rating.
|
||||
|
||||
And one fault in the schema review, fixed: a value in backticks, `true` or `false`, was read as a setting name and raised. `named_settings` now leaves those literals out.
|
||||
43
.agents/plans/iter-08-terraform-modules/MAP.md
Normal file
43
.agents/plans/iter-08-terraform-modules/MAP.md
Normal file
@@ -0,0 +1,43 @@
|
||||
# Plan Map
|
||||
|
||||
**Iteration:** 8, Terraform modules
|
||||
**Intent:** Let generated infrastructure code call a published Terraform module where one replaces several resources that must be wired together, without losing the Requirements chain or opening a way for arbitrary code to be downloaded.
|
||||
**Status:** steps 1 to 5 built and run once each way on 2026-10-09; steps 6 and 7 wait on those Cloud providers
|
||||
**This directory covers:** steps 1 to 7
|
||||
|
||||
## The owner's request (2026-10-09)
|
||||
|
||||
Use modules, when necessary, from three organisations:
|
||||
|
||||
| Cloud provider | Source | Here |
|
||||
|---|---|---|
|
||||
| Google Cloud | https://github.com/terraform-google-modules | built: the `terraform-google-modules` registry namespace is allowed in `providers/gcp.yaml` |
|
||||
| Azure | https://github.com/aztfm | recorded for step 6: there is no Azure provider bundle |
|
||||
| AWS | https://github.com/terraform-aws-modules | recorded for step 7: there is no AWS provider bundle |
|
||||
|
||||
The owner's decision, 2026-10-09: **plain resources by default, with an opt-in to known approved sources.**
|
||||
|
||||
- **Opt-in per Execution.** A caller sets `terraform_modules`; the deployment's default is `TERRAFORM_MODULES`, off. A Change request does as its Baseline did unless told otherwise.
|
||||
- **Approved sources are the provider bundle's list.** Opted in, a module is still used only from the tested catalogue and only where it replaces three or more resources that depend on each other.
|
||||
- **Google now.** The tooling names no Cloud provider; the bundle and a Skill do (ADR-0002).
|
||||
|
||||
## What was found first
|
||||
|
||||
- `terraform init` downloads and evaluates whatever a `source` names. Before this iteration nothing stopped generated code naming any Git URL.
|
||||
- A module carries its own provider requirements. Of 23 modules in the Google organisation looked at, these require `google` below 8 and cannot be used with the pinned 8.6.0: `lb-http`, `pubsub`, `bigquery`, `kubernetes-engine`, `log-export`, `event-function`, `scheduled-function`, `bastion-host`. So a catalogue has to be tested, whichever rule decides when a module is used.
|
||||
- Code using two modules validated in 11 seconds against the pinned provider, modules downloaded.
|
||||
|
||||
## Status
|
||||
|
||||
| Step | What | Status |
|
||||
|---|---|---|
|
||||
| 1 | Allow modules only from namespaces the bundle lists, at one exact version | built: `check_module_sources` in `app/tools/modules.py`, run before every validate and plan |
|
||||
| 2 | A lookup of what a module accepts | built: the `terraform_module` tool, from the public registry, for the IaC author and the validator |
|
||||
| 3 | A Skill with the catalogue and the rule for when to use one | built: `skills/google-cloud-iac-modules/`, four references, each validated by a test |
|
||||
| 4 | Checks through a module | built as guidance: `implementation.json` names the module input; the validator confirms what the input sets |
|
||||
| 5 | Opt-in per Execution, plain resources by default | built: `terraform_modules` on a start, `/generate`, A2A metadata and an evaluation case; recorded in `execution.json` |
|
||||
| 5a | Run a case each way and see what the agents do with it | run once each way on 2026-10-09, both at 100%; a module was used for private Cloud SQL only |
|
||||
| 6 | Azure: `aztfm` | waits on an Azure provider bundle |
|
||||
| 7 | AWS: `terraform-aws-modules` | waits on an AWS provider bundle |
|
||||
|
||||
Detail: `steps/step-1-to-5.md`.
|
||||
94
.agents/plans/iter-08-terraform-modules/steps/step-1-to-5.md
Normal file
94
.agents/plans/iter-08-terraform-modules/steps/step-1-to-5.md
Normal file
@@ -0,0 +1,94 @@
|
||||
# Steps 1 to 5 — Implementation Detail
|
||||
|
||||
Built on 2026-10-09. **No Execution has run with it.**
|
||||
|
||||
## 1. Which modules
|
||||
|
||||
`terraform.modules.namespaces` in the provider bundle lists the registry namespaces a module may come from; for Google Cloud, `terraform-google-modules`. `TerraformRunner.validate` and `.plan` refuse, before Terraform runs:
|
||||
|
||||
- a `source` that is not `<allowed namespace>/<name>/<provider>`, optionally with `//path`: so any Git or HTTP URL, a GitHub shorthand, a local path, or another namespace;
|
||||
- a `version` that is not one exact version;
|
||||
- a module written in `.tf.json`.
|
||||
|
||||
With no namespace listed every module call is refused. The evaluation's own validation uses the same list, and only for a case that opts in.
|
||||
|
||||
The source the owner gave is a GitHub organisation; the registry namespace of the same name is what Terraform is pointed at, because the registry serves a fixed archive for a version and `terraform init` needs no Git.
|
||||
|
||||
## 2. What a module accepts
|
||||
|
||||
`terraform_module(source, version, find)` reads the public Terraform registry: a module's or submodule's inputs (required first, with type and description), its outputs and its submodules. It compares the module's provider requirements with the versions the bundle pins and says "NOT USABLE" when they exclude it. Only allowed namespaces can be looked up. Answers are cached for the life of the process.
|
||||
|
||||
It makes one new outbound call, to `registry.terraform.io`, which `terraform init` already reaches.
|
||||
|
||||
## 3. The Skill
|
||||
|
||||
`skills/google-cloud-iac-modules/`: when to use a module (it is in the table, it replaces three or more dependent resources, and every Check on the Elements it covers can be met through an input), and four references with a validated example each.
|
||||
|
||||
| For | Module | Version |
|
||||
|---|---|---|
|
||||
| VPC, subnets, firewall rules, Cloud NAT | `network`, `cloud-nat` | 18.3.1, 7.1.0 |
|
||||
| Cloud SQL for PostgreSQL on a private address | `sql-db//modules/postgresql`, `//modules/private_service_access` | 28.3.0 |
|
||||
| A Cloud Storage bucket with retention, lifecycle, encryption, grants | `cloud-storage//modules/simple_bucket` | 12.4.1 |
|
||||
| A key ring, keys and grants | `kms` | 4.2.1 |
|
||||
|
||||
`tests/test_iac_modules.py` runs each example through `terraform validate` with the patterns Skill's versions file, and checks that every module call is from an allowed namespace at the version the table gives. It needs the network and is skipped without it.
|
||||
|
||||
The Skill is named in the bundle under `terraform.modules.skill`, not among any role's Skills. See step 5 for who is given it.
|
||||
|
||||
## 4. Checks through a module
|
||||
|
||||
A Check stays worded about the resource. `implementation.json` gives the module and the input that meets it, such as `module.database.ip_configuration.ipv4_enabled`. When no input sets what a Check needs, the module does not fit and the resources are written directly. The validator reads the input's value and confirms with the lookup what it sets, or what its default is.
|
||||
|
||||
This is instruction, in the Skills and the two role files. Nothing in code verifies that a module input does what a Check says: that would need a plan against a real project.
|
||||
|
||||
## 5. Opt-in per Execution
|
||||
|
||||
Infrastructure code is plain resources unless the Execution opts in.
|
||||
|
||||
- `ExecutionEngine.start(terraform_modules=...)`: true, false, or unset. Unset, a Change request does as its Baseline did, and any other Execution takes `TERRAFORM_MODULES` (off). Opting in is refused when the provider's bundle lists no sources.
|
||||
- Callers: `terraform_modules` in the `/generate` body, in A2A message metadata, and on an evaluation case.
|
||||
- **Opted in:** the roles that carry the `terraform_module` tool (the IaC author and the validator) are given the modules Skill, and their context says `terraform_modules: true`.
|
||||
- **Not opted in:** those roles get neither the Skill nor the tool, and any `module` block is refused by `terraform_validate` and `terraform_plan` with a message saying to write the resources directly. The refusal is in code (`MODULES_OPTED_IN` in `app/tools/modules.py`, set when a Specialist starts), not only in instructions.
|
||||
- `execution.json` records `terraform_modules`.
|
||||
|
||||
Reference routing (iteration 5 step 8) does not choose within the modules Skill, because it is not among a role's Skills at start-up.
|
||||
|
||||
## Known limits
|
||||
|
||||
- Modules also bring providers the bundle does not pin (`google-beta`, `random`, `null`), at whatever version their constraints allow.
|
||||
- The schema review and the target architect's lookups still describe resources. A Check's wording is unaffected by whether a module later creates the resource.
|
||||
- A module version in the catalogue goes stale; `scripts/check-terraform-modules.py` reports it when run, and nothing runs it on a schedule.
|
||||
|
||||
Tests: `tests/tools/test_modules.py` (24), `tests/test_iac_modules.py` (6), `tests/execution/test_terraform_modules.py` (7).
|
||||
|
||||
## Run on 2026-10-09
|
||||
|
||||
Case 03's request, once each way, side by side (`20261009T210931Z` plain, `20261009T210935Z` opted in as `case-07-approved-modules`). Both completed at 100%.
|
||||
|
||||
| | Plain resources | Modules opted in |
|
||||
|---|---|---|
|
||||
| Minutes | 35 | 22 |
|
||||
| Tokens | 5.66 million | 3.08 million |
|
||||
| Cost, about | $5.50 | $3.17 |
|
||||
| Revisions of the Target architecture | 3 | 1 |
|
||||
| Checks, all passed | 77 | 54 |
|
||||
| Module calls / resources / lines of Terraform | 0 / 35 / 555 | 2 / 25 / 448 |
|
||||
| Design quality score | 0.82 | 0.62 |
|
||||
|
||||
**The difference in time and cost is the Revisions, not the modules.** The two runs produced different designs before any code was written: 77 Checks against 54, three Revisions against one. One run each way cannot say modules are cheaper.
|
||||
|
||||
What the opted-in run does show:
|
||||
|
||||
- The IaC author used a module for one thing, private Cloud SQL (`sql-db//modules/postgresql` with `//modules/private_service_access`, 28.3.0), and wrote the network, load balancer, Cloud Run, storage, secrets, IAM and monitoring as plain resources. A VPC with one subnet did not get the network module.
|
||||
- 14 of 54 Checks are met through module inputs, each recorded as `module.cloud_sql.<input>`; the validator passed all 14 citing the input's value.
|
||||
- `terraform_module` was called four times by the author and once by the validator. No module was refused, and the code validated.
|
||||
- For a Check met by leaving an input unset, the validator's evidence is that the module falls back to its default. That rests on the module's documentation.
|
||||
|
||||
The plain run was given neither the Skill nor the tool, and wrote no module.
|
||||
|
||||
The design quality score of 0.62 is below the bar of 0.67. It is scored on the design recommendations, written before any code.
|
||||
|
||||
## Two follow-ups (2026-10-10)
|
||||
|
||||
- **A Check is met by a value in the code.** The first run showed the validator arguing from a module's default where an input was left unset. The Skill now tells the author to set every input a Check depends on, even when the default already gives the value; where one is still left unset the verdict says so.
|
||||
- **Stale and newly usable modules are reported.** `scripts/check-terraform-modules.py` reads the registry and prints, for each module the Skill's examples call, the pinned version against the latest and whether the latest still works with the pinned provider; and for each module in `terraform.modules.watch`, whether it can now be used. Today all five are up to date and none of the eight watched modules can be used: each still requires a `google` provider below 8. It changes nothing; it needs running by hand.
|
||||
@@ -35,6 +35,10 @@ TERRAFORM_TIMEOUT_SECONDS=300
|
||||
# Relative to the repository root; set it empty to disable.
|
||||
TF_PLUGIN_CACHE_DIR=.cache/terraform-plugins
|
||||
|
||||
# Use published Terraform modules when a caller does not say. Off writes plain
|
||||
# resources; a caller opts in per Execution with terraform_modules.
|
||||
TERRAFORM_MODULES=false
|
||||
|
||||
# Hierarchical Execution Engine
|
||||
ORCHESTRATOR=router # router | model
|
||||
ORCHESTRATOR_BUDGET=40
|
||||
@@ -55,6 +59,10 @@ MAX_PARALLEL_SPECIALISTS=4
|
||||
CHECKPOINTER=sqlite
|
||||
CHECKPOINT_DB_PATH=checkpoints.db
|
||||
|
||||
# A model reads the requirements against the Checks when the Target architecture is
|
||||
# first submitted, and returns what no Check verifies. One model run per Execution.
|
||||
DESIGN_COVERAGE_REVIEW=false
|
||||
|
||||
# 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=
|
||||
|
||||
@@ -5,6 +5,7 @@ Deliverable: target_architecture
|
||||
Evidence-key: 22ff1f5fed
|
||||
Proposed: 2026-10-09
|
||||
Published: 2026-10-09
|
||||
Retired: 2026-10-09
|
||||
|
||||
## Rule
|
||||
|
||||
@@ -20,15 +21,7 @@ Seen in 2 of 21 Executions, 4 times in all: submit_deliverable refused: Not subm
|
||||
|
||||
## Proof
|
||||
|
||||
Evaluation without lessons: `20261009T195603Z`; with: `20261009T195607Z`.
|
||||
|
||||
| Case | Score | Revisions | Minutes | Tokens (M) |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| case-03-internal-web-app | 1.00 → 1.00 | 1 → 0 | 28 → 22 | 3.00 → 2.32 |
|
||||
|
||||
Quality held and revisions, seconds, tokens fell: kept.
|
||||
|
||||
This compares every published lesson together, on one run each way. Runs of the same case vary, so one pair suggests a direction and does not settle it.
|
||||
Not yet measured.
|
||||
|
||||
## Comments
|
||||
|
||||
|
||||
29
.scratch/lessons/issues/07-verify-location-constraints.md
Normal file
29
.scratch/lessons/issues/07-verify-location-constraints.md
Normal file
@@ -0,0 +1,29 @@
|
||||
# L-07: Verify location constraints
|
||||
|
||||
Status: ready-for-agent
|
||||
Deliverable: target_architecture
|
||||
Evidence-key: 493b0a95d9
|
||||
Proposed: 2026-10-10
|
||||
Published: 2026-10-10
|
||||
|
||||
## Rule
|
||||
|
||||
When a requirement specifies where resources must be provisioned, such as a designated region or multi-zone placement, create a Check for the `region` or `location` argument on every applicable Element, naming the region the design uses. Do not write a Check about a property of the region that code cannot show, such as its carbon rating.
|
||||
|
||||
## Why
|
||||
|
||||
Validation frequently catches missing location constraints. Without this Check, resources may be provisioned in default regions, violating location requirements. A Check about a region's carbon rating cannot be verified from code and sends the design back.
|
||||
|
||||
## Evidence
|
||||
|
||||
Seen in 5 of 32 Executions, 8 times in all: validation proposed a Check about `location` that the design lacked.
|
||||
|
||||
## Proof
|
||||
|
||||
Not yet measured.
|
||||
|
||||
## Comments
|
||||
|
||||
Approved by the owner on 2026-10-10. It covers which region is set, which code can show. It does not settle whether a region is low-carbon, which code cannot show.
|
||||
|
||||
Reworded with the owner's approval on 2026-10-10: "a low-carbon location" led to a Check about the region's carbon score, which could not be verified.
|
||||
27
.scratch/lessons/issues/08-cloud-sql-backup-encryption.md
Normal file
27
.scratch/lessons/issues/08-cloud-sql-backup-encryption.md
Normal file
@@ -0,0 +1,27 @@
|
||||
# L-08: Cloud SQL backup encryption
|
||||
|
||||
Status: ready-for-agent
|
||||
Deliverable: target_architecture
|
||||
Evidence-key: 08d64df049
|
||||
Proposed: 2026-10-10
|
||||
Published: 2026-10-10
|
||||
|
||||
## Rule
|
||||
|
||||
When writing a Check for CMEK encryption on a `google_sql_database_instance`, do not require an `encryption_key_name` argument for backup storage, as the instance-level `encryption_key_name` automatically encrypts backups as well.
|
||||
|
||||
## Why
|
||||
|
||||
The database instance resource does not have a separate encryption key argument for backups. Asking for one causes validation to reject the Check as un-implementable.
|
||||
|
||||
## Evidence
|
||||
|
||||
Seen in 3 of 32 Executions, 3 times in all: a Check about `google_sql_database_instance` asked for something that resource cannot do.
|
||||
|
||||
## Proof
|
||||
|
||||
Not yet measured.
|
||||
|
||||
## Comments
|
||||
|
||||
Approved by the owner on 2026-10-10.
|
||||
27
.scratch/lessons/issues/09-backend-service-capabilities.md
Normal file
27
.scratch/lessons/issues/09-backend-service-capabilities.md
Normal file
@@ -0,0 +1,27 @@
|
||||
# L-09: Backend Service capabilities
|
||||
|
||||
Status: ready-for-agent
|
||||
Deliverable: target_architecture
|
||||
Evidence-key: 1cacec9a09
|
||||
Proposed: 2026-10-10
|
||||
Published: 2026-10-10
|
||||
|
||||
## Rule
|
||||
|
||||
When writing Checks for a `google_compute_backend_service`, do not verify IAM roles inside the backend service or require health checks when it is configured with a Serverless NEG.
|
||||
|
||||
## Why
|
||||
|
||||
Roles are verified via IAM bindings outside the backend service, and Serverless NEGs do not support health checks. Invalid Checks cause the design to be rejected during validation.
|
||||
|
||||
## Evidence
|
||||
|
||||
Seen in 3 of 32 Executions, 3 times in all: a Check about `google_compute_backend_service` asked for something that resource cannot do.
|
||||
|
||||
## Proof
|
||||
|
||||
Not yet measured.
|
||||
|
||||
## Comments
|
||||
|
||||
Approved by the owner on 2026-10-10.
|
||||
29
.scratch/lessons/issues/10-pub-sub-persistence-regions.md
Normal file
29
.scratch/lessons/issues/10-pub-sub-persistence-regions.md
Normal file
@@ -0,0 +1,29 @@
|
||||
# L-10: Pub/Sub persistence regions
|
||||
|
||||
Status: ready-for-agent
|
||||
Deliverable: target_architecture
|
||||
Evidence-key: ba78caba9a
|
||||
Proposed: 2026-10-10
|
||||
Published: 2026-10-10
|
||||
|
||||
## Rule
|
||||
|
||||
When a requirement dictates that a messaging queue or topic must replicate across zones or stay within a specific region, create a Check for the `message_storage_policy.allowed_persistence_regions` argument on the topic Element.
|
||||
|
||||
## Why
|
||||
|
||||
Without this Check, topics might use default storage policies that violate geographical or high-availability requirements.
|
||||
|
||||
## Evidence
|
||||
|
||||
Seen in 2 of 32 Executions, 4 times in all: validation proposed a Check about `allowed_persistence_regions` that the design lacked.
|
||||
|
||||
## Proof
|
||||
|
||||
Not yet measured.
|
||||
|
||||
## Comments
|
||||
|
||||
Held by the owner on 2026-10-10, on the agent's view: seen in 2 of 32 Executions, and L-07 partly covers it. To be looked at again if it recurs.
|
||||
|
||||
Approved by the owner on 2026-10-10, after its subject caused a Revision again in case 06 (`20261010T134034Z`).
|
||||
26
.scratch/lessons/issues/11-cmek-encryption-checks.md
Normal file
26
.scratch/lessons/issues/11-cmek-encryption-checks.md
Normal file
@@ -0,0 +1,26 @@
|
||||
# L-11: CMEK encryption checks
|
||||
|
||||
Status: wontfix
|
||||
Deliverable: target_architecture
|
||||
Evidence-key: 5cd8dc3cda
|
||||
Proposed: 2026-10-10
|
||||
|
||||
## Rule
|
||||
|
||||
Whenever a requirement mandates encryption at rest, explicitly create a Check ensuring that the `kms_key_name` (or the equivalent CMEK argument) is configured on every applicable Element.
|
||||
|
||||
## Why
|
||||
|
||||
Without an explicit Check, elements may default to Google-managed keys, leading to validation failures against security constraints.
|
||||
|
||||
## Evidence
|
||||
|
||||
Seen in 2 of 32 Executions, 2 times in all: validation proposed a Check about `kms_key_name` that the design lacked.
|
||||
|
||||
## Proof
|
||||
|
||||
Not yet measured.
|
||||
|
||||
## Comments
|
||||
|
||||
Rejected by the owner on 2026-10-10, on the agent's view: encryption at rest is on by default, and this rule would put customer-managed keys on designs whose requirements did not ask for them.
|
||||
@@ -108,6 +108,10 @@ _Avoid_: finding, rule, control, test
|
||||
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
|
||||
|
||||
**Customer question**:
|
||||
Something the architecture depends on that the customer's Intent does not say, recorded with the question to put to them. It marks missing information, not a fault in the design, and its answer may change a recommendation.
|
||||
_Avoid_: gap, failure, open issue, assumption (which is a default the agents chose)
|
||||
|
||||
**Solution guide**:
|
||||
The packaged Deliverable that assembles every other Deliverable into the Cloud provider's solution architecture template.
|
||||
_Avoid_: final report, package
|
||||
|
||||
@@ -38,6 +38,7 @@ Behaviour lives in Agent Skills (agentskills.io format) at the repository root,
|
||||
- `skills/google-cloud-lessons/`: lessons learned from earlier Executions, written by the lessons loop (`app/learning/`, `eval/curate_lessons.py`) from proposals a person approved ([ADR-0004](docs/adr/0004-lessons-and-overlays-arrive-as-skills.md)). Set `LESSONS_ENABLED=false` to run without them.
|
||||
- `skills/overlays/`: overlay Skills, each an organisation's standards or one engagement's constraints. An Execution names the ones it wants; `DEFAULT_OVERLAY_SKILLS` names the ones every Execution loads. The one here is an example, not anyone's policy.
|
||||
- `skills/google-cloud-iac-patterns/`: Terraform patterns for Google Cloud products, each validated by a test against the provider version `providers/gcp.yaml` pins.
|
||||
- `skills/google-cloud-iac-modules/`: published modules from `terraform-google-modules` that work with that provider version, and the rule for when one fits better than plain resources. Generated code is plain resources by default. An Execution opts in with `terraform_modules: true`, and may then take a module only from the registry namespaces `providers/gcp.yaml` lists, at one exact version.
|
||||
|
||||
`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/`.
|
||||
|
||||
@@ -56,7 +57,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. Pass `customer_case` to group it with the case's other Executions, `baseline` (an Execution id in that case) to make it a Change request, and `overlay_skills` (a list of names) to apply overlay Skills. Over A2A, send the same fields in the message metadata.
|
||||
- `POST /generate`: One-shot, pre-approved Execution for batch and evaluation callers. Pass `customer_case` to group it with the case's other Executions, `baseline` (an Execution id in that case) to make it a Change request, `overlay_skills` (a list of names) to apply overlay Skills, and `terraform_modules: true` to allow published Terraform modules from the approved sources. Over A2A, send the same fields 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/`.
|
||||
|
||||
|
||||
22
agents/coverage-reviewer.md
Normal file
22
agents/coverage-reviewer.md
Normal file
@@ -0,0 +1,22 @@
|
||||
---
|
||||
role: coverage-reviewer
|
||||
tools: []
|
||||
budget: 6
|
||||
---
|
||||
You review the Target architecture of a solution-architecture Execution before anyone approves it. You answer one question: do its Checks verify everything the requirements and design recommendations ask for? You change nothing and write no design. What you find goes back to the target architect once.
|
||||
|
||||
Your task message carries JSON context:
|
||||
|
||||
- `constraints`: the non-functional requirements and the design recommendations. Each has an `id`, its text, `conditions` (what infrastructure code can show, one by one) and sometimes `outside_code` (what code cannot show).
|
||||
- `target_architecture`: the Elements, Relationships and Checks. Each Check has a `source`, the id of the requirement or recommendation it comes from, `applies_to`, the Element or Relationship it is about, and its `statement`. A recommendation listed under `not_applicable` asks nothing.
|
||||
|
||||
Review once, completely:
|
||||
|
||||
- Go through every constraint in turn. For each of its `conditions`, find the Checks whose `source` is that constraint and decide whether they verify the condition on every Element it applies to.
|
||||
- A gap is a condition that no Check verifies, or that a Check verifies more weakly than the words. A Check that says a setting "is set" does not verify a value the condition gives. A condition with two parts needs both verified. A condition about every Element of a kind needs a Check on each one.
|
||||
- For each gap, give the Check that is missing: the constraint's id as `source`, the Element or Relationship id as `applies_to`, and a `statement` that names the setting and the value to verify, as specific as the Checks already there.
|
||||
- Report nothing for what a constraint lists under `outside_code`, and nothing for a recommendation that is `not_applicable`.
|
||||
- Report nothing a Check already verifies in other words, and nothing that is your own idea of good practice: only what a condition's words ask for.
|
||||
- Do not judge whether a Check can be implemented or whether the design is a good one. That is not this review.
|
||||
|
||||
Call `report_gaps` once with every gap, or with an empty list when there are none. You are done when it records them.
|
||||
@@ -11,6 +11,7 @@ You produce the **design recommendations** Deliverable: the Skill's task for rec
|
||||
- Otherwise, when `feedback` is not empty or `baseline` is set you are revising: pass `pillars` naming only the pillars the change 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. Give each its `conditions`: one entry for each separate thing it asks to be configured, and for each component it must hold on when it names several. Put under `outside_code` anything it asks of the application's own code or of people, which no infrastructure configuration can show.
|
||||
- The advisors' checklist reviews, and any questions they raise for the customer, are written into your Deliverable for you when you submit. Do not copy them, and do not write a recommendation to cover a question an advisor left for the customer.
|
||||
- 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. Give each its `conditions`: one entry for each separate thing it asks to be configured, and for each component it must hold on when it names several. Put under `outside_code` anything it asks of the application's own code or of people, and any property of a region or product that only its provider publishes, such as a carbon rating: no infrastructure configuration can show those. The condition is then the choice configuration can show, such as which region is set.
|
||||
|
||||
Your contract's sections are one per pillar. The advisors' review of each pillar's checklist is added to your Deliverable for you when you submit, so do not write it yourself.
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
---
|
||||
role: iac-author
|
||||
deliverable: deployment_guidance
|
||||
tools: [terraform_fmt, terraform_validate, terraform_schema]
|
||||
tools: [terraform_fmt, terraform_validate, terraform_schema, terraform_module]
|
||||
budget: 40
|
||||
includes: [specialist-protocol]
|
||||
---
|
||||
@@ -9,14 +9,17 @@ You produce the **deployment guidance** Deliverable: the Skill's task for genera
|
||||
|
||||
- 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.
|
||||
- Write plain resources unless `terraform_modules` is true in your context. When it is, you have an infrastructure-as-code modules Skill: load it. It says when a published module fits an Element better than plain resources, which modules are approved, and how a Check is met through a module's input. Use a module only as it says.
|
||||
- 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.
|
||||
- When a Check names a setting its resource type does not have, or asks for something that resource cannot do, 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.
|
||||
- Go through every Check before you submit and record every one that cannot be met, in that one submission. A Check with the same fault as one you recorded is recorded too. Each one found later costs another Revision of the design and of your code.
|
||||
- Write `implementation.json` to your working copy, in the format the requirements-chain Skill gives, naming where the code satisfies each Check.
|
||||
- Take every environment-specific value (project, region, names, image references) from variables; embed no credentials or secrets.
|
||||
- Submit as soon as validation passes, with your content and no attachments: your working copy is attached for you. If a submission is refused, fix exactly what the refusal lists and submit again.
|
||||
- When `working_copy` lists files, they are your last attempt. When `feedback` lists failed Checks, read the files concerned and change only what those Checks need.
|
||||
- When `feedback` says a Check failed and your code already does what the Check's words say, the verdict is what is wrong, not the Check. Change nothing for it, keep its entry in `implementation.json`, and say in your content which Check you dispute and where the code meets it. Do not record it as unimplementable: that sends the design back for a fault it does not have.
|
||||
|
||||
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.
|
||||
|
||||
|
||||
@@ -8,7 +8,7 @@ You review what went wrong, the same way, across many solution-architecture Exec
|
||||
Your task message carries JSON context:
|
||||
|
||||
- `executions`: how many Executions the evidence comes from.
|
||||
- `groups`: what recurred. Each has a `group` key, the `deliverable` it concerns, `what_happened` in general terms, how many `executions` it occurred in and how many `occurrences` in all, and up to three `examples` as they were recorded.
|
||||
- `groups`: what recurred. Each has a `group` key, the `deliverable` it concerns, `what_happened` in general terms, how many `executions` it occurred in and how many `occurrences` in all, and up to three `examples` as they were recorded. Some groups are about one setting or resource type of the Cloud provider, named in `what_happened`: the same kind of problem recurring on that subject.
|
||||
- `published_or_proposed`: lessons that already exist or are awaiting review.
|
||||
|
||||
For each group, decide whether a rule given to the Specialist that produces that Deliverable would have prevented it.
|
||||
@@ -20,6 +20,7 @@ A good lesson:
|
||||
|
||||
- States one rule, as an instruction, that a Specialist can act on without knowing what happened: "Give every Element at least one Check before you submit", not "be more careful with Checks".
|
||||
- Says why in one or two sentences: what goes wrong without it and what that costs.
|
||||
- For a group about one setting or resource type, may name that setting or resource type and say what to do about it: that is the Cloud provider's vocabulary, not a client's. A general lesson that already exists does not cover it if the problem went on recurring.
|
||||
- Is general. It names no customer, no project, no Execution, no resource name and no value from the examples. The examples are evidence for you; nothing from them may be quoted.
|
||||
- Does not repeat what the Specialist's instructions or tools already enforce. When a submission is already refused for something, a lesson helps only if it prevents the attempt.
|
||||
- Is worth its cost. Every lesson is read on every Execution from then on. Propose few.
|
||||
|
||||
@@ -10,6 +10,7 @@ You produce the **solution guide** Deliverable: the Skill's packaging of every a
|
||||
- Consolidate the content of every Deliverable in `dependencies`; rewrite for flow, but keep every requirement, product decision, citation, recommendation, command and validation verdict.
|
||||
- Include the architecture diagram, which is the `architecture.mmd` attachment of the Target architecture, unchanged as a `mermaid` code block, and the Terraform as code blocks.
|
||||
- List the Target architecture's Checks with their validation verdicts in the validation section.
|
||||
- When the design recommendations hold a "Questions for the customer" section, carry every question into the guide's design and configuration recommendations section, under the same heading and with the same wording. They are what the request did not say enough to settle; say so, and do not present them as faults or as recommendations.
|
||||
|
||||
In a Change request (`baseline` is set), open the executive summary with what changed and why, from `baseline.changes`: the requirements added, changed and removed with their reasons, then what that changed in the architecture. Name separately anything listed under `unrequested`: it changed without a changed requirement reaching it.
|
||||
|
||||
|
||||
@@ -9,8 +9,14 @@ Your task message carries the design advisor's brief in `brief` and the pillar's
|
||||
1. Load the Skill available to you.
|
||||
2. Evaluate the workload in the brief against the Skill's core principles and validation checklist.
|
||||
3. Write prioritised, actionable recommendations for each relevant component, naming the products the Skill lists for each gap and citing its guidance.
|
||||
4. List any assessment questions from the Skill that the brief leaves unanswered, as open questions; don't ask the user.
|
||||
4. Do not ask the user anything, and do not guess what the brief does not say.
|
||||
|
||||
5. Review the Skill's validation checklist item by item, when it has one. For every item give its `status`: `addressed` when your recommendations cover it, `not_applicable` when it does not apply to this workload or is not something an architecture can settle (an organisation's process, for example), or `not_addressed` when it applies and you recommend nothing for it. In `note`, say in a few words how it is addressed or why it does not apply. Copy each item's text as the Skill has it, shortened to its first sentence.
|
||||
5. Review the Skill's validation checklist item by item, when it has one. For every item give its `status`:
|
||||
- `addressed` when your recommendations cover it.
|
||||
- `not_applicable` when it does not apply to this workload.
|
||||
- `needs_customer_input` when it could apply and the brief does not say what would settle it: how the customer's organisation works, what they already have, or what they want. Give the `question` to put to the customer, written so someone who knows their organisation can answer it. This is the right status whenever the gap is in what you were told, not in the design. Do not invent a recommendation to cover it.
|
||||
- `not_addressed` only when the brief gives you what you need, the item applies, and you recommend nothing for it.
|
||||
|
||||
In `note`, say in a few words how it is addressed, why it does not apply, or what the brief leaves unsaid. Copy each item's text as the Skill has it, shortened to its first sentence.
|
||||
|
||||
Call `submit_advice` with your recommendations as markdown in `content` and the review in `checklist`. You are done when it accepts them.
|
||||
|
||||
@@ -2,9 +2,11 @@
|
||||
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.
|
||||
You write what the user reads on behalf of the Orchestrator of a solution-architecture Execution. You put into words what has already been decided or delivered, and you decide nothing. Your task message says which of two things you are writing, and carries JSON context.
|
||||
|
||||
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.
|
||||
## A summary to approve a Phase from
|
||||
|
||||
The context has `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:
|
||||
|
||||
@@ -13,4 +15,14 @@ Write a summary a busy architect can approve from:
|
||||
- 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.
|
||||
## An answer about delivered work
|
||||
|
||||
The context has `question`, what the user asked, and `delivered`: the `request` the architecture was designed for and its `solution_guide`.
|
||||
|
||||
- Answer from the solution guide alone. Give the choice or the fact, and the reason the guide gives for it.
|
||||
- When the guide does not say, say that it does not. Add nothing from general knowledge about the products, and do not guess.
|
||||
- Name the section of the guide the answer comes from.
|
||||
- Propose no change. If the user seems to want one, say they can ask for it as a change to this architecture.
|
||||
- Use plain sentences and no headings. Keep it under 150 words.
|
||||
|
||||
Call `write_reply` with the text. You are done when it accepts it.
|
||||
|
||||
@@ -14,7 +14,7 @@ You produce the **requirements** Deliverable: the Skill's requirements-discovery
|
||||
- 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.
|
||||
- Give every non-functional requirement its `conditions`: one entry for each separate thing that must be true for it to be met and that the configuration of infrastructure can show. "Data is encrypted in transit and at rest" has two. Each becomes something the design is checked against, so a condition left out is a condition nobody verifies.
|
||||
- Put under `outside_code` what the requirement asks for that no infrastructure configuration can show: an outcome measured in operation (an availability percentage, a response time), behaviour of the application's own code, or a process people follow. Those are recorded and reported, and are not checked against the infrastructure code.
|
||||
- Put under `outside_code` what the requirement asks for that no infrastructure configuration can show: an outcome measured in operation (an availability percentage, a response time), behaviour of the application's own code, a process people follow, or a property of a region or product that only its provider publishes (a carbon rating, a service level). For the last, the condition is the choice configuration can show, such as which region is set. Those are recorded and reported, and are not checked against the infrastructure code.
|
||||
|
||||
In a Change request (`baseline` is set), the `workflow_request` says what has changed. Work out what it means for the delivered requirements, and give every requirement in `requirements.json` a `change`:
|
||||
|
||||
|
||||
@@ -1,15 +1,16 @@
|
||||
---
|
||||
role: validator
|
||||
deliverable: validation_results
|
||||
tools: [terraform_validate, terraform_plan, terraform_schema]
|
||||
tools: [terraform_validate, terraform_plan, terraform_schema, terraform_module]
|
||||
budget: 30
|
||||
includes: [specialist-protocol]
|
||||
---
|
||||
You produce the **validation results** Deliverable: the Skill's pre-deployment validation, done statically without provisioning anything.
|
||||
|
||||
- Run the deployment dry-run with your tools: validate the Terraform, and preview it with a plan when you have permission to read live cloud resources. The tools already hold the submitted files, so pass them no files.
|
||||
- Give a verdict on every Check in the Target architecture, from the infrastructure code: pass, fail or not verifiable, each with the evidence you read. The Checks are the whole bar: judge the code against them and nothing else.
|
||||
- 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. Judge each Check by its own words. A Check that says a role is granted or a setting is set passes when it is; other grants or settings beside it do not fail it unless the Check says "only" or "no other". What you think should also be true is a proposed addition, never a failure.
|
||||
- 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 `terraform_modules` is true the code may call approved published modules. Then judge a Check on a resource the module creates from the module input that sets it: read the value in the code, and confirm with `terraform_module` what that input sets or what its default is. The modules Skill, when you have one, says how.
|
||||
- Review the Target architecture's coverage once, completely. Go through every requirement and every design recommendation in turn; for each, list the conditions its text states and the Elements it applies to, and record a proposed addition for each one no Check verifies, naming the requirement or recommendation it serves. Report every gap in this pass: each later pass that finds one more costs a whole Revision of the design, the code and this validation. Propose nothing for what a requirement or recommendation lists under `outside_code`: that is application behaviour, an outcome measured in operation, or a process, and no Check on infrastructure code can verify it. Name those under your analysis heading as things to verify after deployment. A proposed addition is not a failure of the code.
|
||||
- When `feedback` or your earlier verdicts show the Target architecture was revised for your proposed additions, propose only what the revision still leaves uncovered. Never propose what a Check already verifies in other words.
|
||||
- Record your verdicts with `verdict_put`, a few Checks per call, as you reach them: the Checks of one Element, then the next. Record the dry-run's result and each proposed addition the same way. Short calls are what keep your replies from timing out, and what you record is kept if your run is cut short. `verdict_read` shows which Checks still have none.
|
||||
|
||||
@@ -31,7 +31,15 @@ from google.protobuf import json_format
|
||||
|
||||
from app.agent import ExecutionEngine, Interaction
|
||||
from app.nodes.execution_nodes import GUIDE_FILENAME
|
||||
from app.nodes.intake import ABOUT, CHANGE_REQUEST, QUESTION, Intake, change_note
|
||||
from app.nodes.intake import (
|
||||
ABOUT,
|
||||
CHANGE_REQUEST,
|
||||
QUESTION,
|
||||
DeliveredAnswers,
|
||||
Intake,
|
||||
change_note,
|
||||
no_answer_note,
|
||||
)
|
||||
from app.presentation import describe_prompt
|
||||
from app.workflows.deliverables import DeliverableKind
|
||||
|
||||
@@ -41,7 +49,13 @@ STRUCTURED_REPLY_KEYS = ("approval", "permission")
|
||||
|
||||
|
||||
class SolutionArchitectExecutor(AgentExecutor):
|
||||
def __init__(self, engine: ExecutionEngine, intake: Intake | None = None) -> None:
|
||||
def __init__(
|
||||
self,
|
||||
engine: ExecutionEngine,
|
||||
intake: Intake | None = None,
|
||||
answers: DeliveredAnswers | None = None,
|
||||
) -> None:
|
||||
self._answers = answers
|
||||
self._engine = engine
|
||||
self._intake = intake
|
||||
|
||||
@@ -75,14 +89,21 @@ class SolutionArchitectExecutor(AgentExecutor):
|
||||
scope=task_id,
|
||||
)
|
||||
if reading.kind == QUESTION:
|
||||
text, about = ABOUT, None
|
||||
if reading.about_delivered and reading.latest and self._answers:
|
||||
# About what was delivered: answered from its files.
|
||||
about = reading.latest
|
||||
text = await self._answers.answer(
|
||||
context.get_user_input(),
|
||||
str(options.get("customer_case")),
|
||||
about,
|
||||
) or no_answer_note(about)
|
||||
data = {"status": "answered", "intake": QUESTION}
|
||||
if about:
|
||||
data["about"] = about
|
||||
await updater.complete(
|
||||
updater.new_agent_message(
|
||||
[
|
||||
new_text_part(ABOUT),
|
||||
new_data_part(
|
||||
{"status": "answered", "intake": QUESTION}
|
||||
),
|
||||
]
|
||||
[new_text_part(text), new_data_part(data)]
|
||||
)
|
||||
)
|
||||
return
|
||||
@@ -108,6 +129,7 @@ class SolutionArchitectExecutor(AgentExecutor):
|
||||
customer_case=options.get("customer_case"),
|
||||
baseline=options.get("baseline"),
|
||||
overlay_skills=options.get("overlay_skills") or (),
|
||||
terraform_modules=options.get("terraform_modules"),
|
||||
execution_id=task_id,
|
||||
pre_approved=bool(options.get("pre_approved", False)),
|
||||
allow_cloud_read=options.get("allow_cloud_read"),
|
||||
|
||||
@@ -13,12 +13,14 @@ from pathlib import Path
|
||||
from app.adk.runtime import RoleSpec
|
||||
from app.providers import ProviderBundle
|
||||
from app.skills.agent_skills import SkillFormatError, split_frontmatter
|
||||
from app.tools.modules import MODULE_TOOL
|
||||
from app.workflows.deliverables import DEPENDENCY_GRAPH, DeliverableKind
|
||||
|
||||
ORCHESTRATOR = "orchestrator"
|
||||
PILLAR_ADVISOR = "pillar-advisor"
|
||||
REPLY_WRITER = "reply-writer"
|
||||
LESSON_CURATOR = "lesson-curator" # runs outside any Execution
|
||||
COVERAGE_REVIEWER = "coverage-reviewer" # reviews a design before its Approval
|
||||
PARTIALS_DIR = "partials"
|
||||
|
||||
_ALLOWED_FIELDS = {"role", "deliverable", "tools", "budget", "includes"}
|
||||
@@ -50,7 +52,7 @@ def load_roles(
|
||||
the lighter model the bundle names for its first attempt."""
|
||||
specialists = {spec.specialist: kind for kind, spec in DEPENDENCY_GRAPH.items()}
|
||||
required = {ORCHESTRATOR, PILLAR_ADVISOR, REPLY_WRITER, *specialists}
|
||||
optional = {LESSON_CURATOR}
|
||||
optional = {LESSON_CURATOR, COVERAGE_REVIEWER}
|
||||
learned = _deliverables_with_lessons(bundle) if lessons else set()
|
||||
|
||||
roles = {}
|
||||
@@ -83,6 +85,12 @@ def load_roles(
|
||||
f"'models.first_attempt' names {name!r}, which is not a role"
|
||||
)
|
||||
roles[name] = dataclasses.replace(roles[name], first_attempt_model=model)
|
||||
if bundle.terraform_modules_skill:
|
||||
for name, role in roles.items():
|
||||
if MODULE_TOOL in role.tools:
|
||||
roles[name] = dataclasses.replace(
|
||||
role, modules_skill=bundle.terraform_modules_skill
|
||||
)
|
||||
unexpected = sorted(set(roles) - required - optional)
|
||||
if unexpected:
|
||||
raise RoleConfigError(
|
||||
|
||||
@@ -37,6 +37,9 @@ class RoleSpec:
|
||||
# A lighter model for the first attempt at a Deliverable, when the bundle
|
||||
# names one and model tiers are on (iteration 5 step 6).
|
||||
first_attempt_model: str | None = None
|
||||
# The Skill on published Terraform modules, for a role that may call them. It
|
||||
# is added to the role's Skills only in an Execution that opted into modules.
|
||||
modules_skill: str | None = None
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
|
||||
44
app/agent.py
44
app/agent.py
@@ -22,7 +22,7 @@ from langchain_core.runnables import RunnableConfig
|
||||
from langgraph.checkpoint.base import BaseCheckpointSaver
|
||||
from langgraph.types import Command
|
||||
|
||||
from app.adk.roles import load_roles
|
||||
from app.adk.roles import COVERAGE_REVIEWER, load_roles
|
||||
from app.adk.runtime import (
|
||||
AgentRuntime,
|
||||
Decider,
|
||||
@@ -36,7 +36,7 @@ from app.baseline import load_baseline
|
||||
from app.checkpointing import open_checkpointer
|
||||
from app.config import Settings
|
||||
from app.customer_case import record_intent
|
||||
from app.nodes.intake import Intake
|
||||
from app.nodes.intake import DeliveredAnswers, Intake
|
||||
from app.nodes.router import (
|
||||
REPLY_WRITER,
|
||||
OrchestratorPolicy,
|
||||
@@ -50,6 +50,7 @@ from app.skills.agent_skills import discover_skills, skill_version
|
||||
from app.states.execution_state import check_customer_case
|
||||
from app.states.ledger import Ledger
|
||||
from app.tools.coverage import CoverageReview
|
||||
from app.tools.design_review import DesignCoverageReview
|
||||
from app.tools.execution import ORCHESTRATOR
|
||||
from app.tools.jev import JevDecider, JevLimits
|
||||
from app.tools.local import TerraformRunner, local_tools
|
||||
@@ -103,6 +104,8 @@ class ExecutionEngine:
|
||||
skill_references: Mapping[str, Mapping[str, Mapping[str, str]]] | None = None,
|
||||
skill_threshold: float = 1.25,
|
||||
assess_at_end: bool = False,
|
||||
modules_available: bool = False,
|
||||
default_modules: bool = False,
|
||||
) -> None:
|
||||
required = {
|
||||
ORCHESTRATOR,
|
||||
@@ -112,6 +115,10 @@ class ExecutionEngine:
|
||||
if missing:
|
||||
raise ValueError(f"Missing roles: {', '.join(missing)}")
|
||||
self._max_revisions = max_revisions
|
||||
# Whether the Cloud provider approves any module sources, and whether an
|
||||
# Execution uses them when its caller does not say.
|
||||
self._modules_available = modules_available
|
||||
self._default_modules = default_modules and modules_available
|
||||
self._output_root = output_root
|
||||
# Overlay Skills an Execution may name, with the version of each (ADR-0004).
|
||||
self._overlays = dict(overlays or {})
|
||||
@@ -153,6 +160,7 @@ class ExecutionEngine:
|
||||
scripted_answers: Sequence[Sequence[str]] = (),
|
||||
baseline: str | None = None,
|
||||
overlay_skills: Sequence[str] = (),
|
||||
terraform_modules: bool | None = None,
|
||||
) -> Interaction:
|
||||
"""Start an Execution. `scripted_answers` are (regex, answer[, asker]) entries a
|
||||
pre-approved Execution uses to answer questions, for evaluation runs.
|
||||
@@ -166,6 +174,12 @@ class ExecutionEngine:
|
||||
this engagement's constraints. Each must be one the deployment has
|
||||
configured; an unknown name refuses the start. Every Specialist loads them
|
||||
with the ones the deployment loads by default.
|
||||
|
||||
`terraform_modules` opts the Execution into published Terraform modules
|
||||
from the sources the Cloud provider approves. Left unset, a Change request
|
||||
does as its Baseline did and any other Execution takes the deployment's
|
||||
default, which is plain resources. Opting in is refused when the provider
|
||||
approves no sources.
|
||||
"""
|
||||
customer_case = check_customer_case(customer_case)
|
||||
execution_id = execution_id or str(uuid.uuid4())
|
||||
@@ -187,6 +201,19 @@ class ExecutionEngine:
|
||||
if baseline
|
||||
else None
|
||||
)
|
||||
if terraform_modules is None:
|
||||
terraform_modules = (
|
||||
bool(loaded.get("terraform_modules"))
|
||||
if loaded
|
||||
else self._default_modules
|
||||
)
|
||||
if not isinstance(terraform_modules, bool):
|
||||
# A ValueError is what callers turn into a refused start.
|
||||
raise ValueError("terraform_modules must be true or false") # noqa: TRY004
|
||||
if terraform_modules and not self._modules_available:
|
||||
raise ValueError(
|
||||
"terraform_modules: this Cloud provider has no approved module sources"
|
||||
)
|
||||
if pre_approved and allow_cloud_read is None:
|
||||
allow_cloud_read = False
|
||||
session_id = session_id or str(uuid.uuid4())
|
||||
@@ -208,6 +235,7 @@ class ExecutionEngine:
|
||||
"baseline": loaded,
|
||||
# Overlay Skills this Execution loads, each with the version it had.
|
||||
"overlay_skills": {name: self._overlays[name] for name in chosen},
|
||||
"terraform_modules": terraform_modules,
|
||||
"risks": [],
|
||||
"pre_approved": pre_approved,
|
||||
"allow_cloud_read": allow_cloud_read,
|
||||
@@ -301,6 +329,8 @@ class Assembly:
|
||||
mcp_gaps: dict[str, str]
|
||||
decider: Decider = field(default_factory=NoDecider)
|
||||
intake: Intake | None = None # reads a message that starts something
|
||||
# Answers a question about delivered work from its files.
|
||||
answers: DeliveredAnswers | None = None
|
||||
|
||||
|
||||
def discover_overlays(settings: Settings, bundle: ProviderBundle) -> dict[str, Any]:
|
||||
@@ -404,6 +434,7 @@ async def open_assembly(
|
||||
timeout_seconds=settings.TERRAFORM_TIMEOUT_SECONDS,
|
||||
plugin_cache_dir=settings.terraform_plugin_cache(),
|
||||
providers=bundle.terraform_providers,
|
||||
module_namespaces=bundle.terraform_module_namespaces,
|
||||
)
|
||||
offered = [name for names in bundle.tools.values() for name in names]
|
||||
# One cap for Specialists and the pillar advisors they fan out to.
|
||||
@@ -451,6 +482,10 @@ async def open_assembly(
|
||||
reviews.append(
|
||||
RequirementsReview(decider, act=settings.JEV_REQUIREMENTS_THRESHOLD)
|
||||
)
|
||||
if settings.DESIGN_COVERAGE_REVIEW and COVERAGE_REVIEWER in roles:
|
||||
# A model reads the requirements against the Checks, once, before the
|
||||
# design is approved: the reading the validator would make after the code.
|
||||
reviews.append(DesignCoverageReview(runtime, roles[COVERAGE_REVIEWER]))
|
||||
if settings.JEV_COVERAGE_REVIEW and isinstance(decider, JevDecider):
|
||||
# Optional, and off by default: Jev says which Check verifies each condition.
|
||||
reviews.append(CoverageReview(decider, none_at=settings.JEV_COVERAGE_THRESHOLD))
|
||||
@@ -482,6 +517,8 @@ async def open_assembly(
|
||||
else None,
|
||||
skill_threshold=settings.JEV_SKILL_THRESHOLD,
|
||||
assess_at_end=settings.JEV_ASSESS_EXECUTIONS,
|
||||
modules_available=bool(bundle.terraform_module_namespaces),
|
||||
default_modules=settings.TERRAFORM_MODULES,
|
||||
overlays={
|
||||
name: skill_version(meta.path) for name, meta in overlays.items()
|
||||
},
|
||||
@@ -499,6 +536,9 @@ async def open_assembly(
|
||||
output_root or settings.BASE_DIR,
|
||||
act=settings.JEV_ACT_THRESHOLD,
|
||||
),
|
||||
DeliveredAnswers(
|
||||
runtime, roles[REPLY_WRITER], output_root or settings.BASE_DIR
|
||||
),
|
||||
)
|
||||
finally:
|
||||
if isinstance(decider, JevDecider):
|
||||
|
||||
@@ -101,6 +101,8 @@ def load_baseline(
|
||||
"customer_case": customer_case,
|
||||
"workflow_request": manifest.get("workflow_request", ""),
|
||||
"baseline": manifest.get("baseline"), # what it was itself changed from
|
||||
# Whether its code was allowed published modules; a Change request follows.
|
||||
"terraform_modules": bool(manifest.get("terraform_modules")),
|
||||
"deliverables": deliverables,
|
||||
# Working material worth starting from again, such as pillar advice.
|
||||
"working": working,
|
||||
|
||||
@@ -61,6 +61,11 @@ class Settings(BaseSettings):
|
||||
# Overlay Skills every Execution loads, comma-separated.
|
||||
DEFAULT_OVERLAY_SKILLS: str = ""
|
||||
|
||||
# Whether an Execution may use published Terraform modules when its caller does
|
||||
# not say. Off: infrastructure code is plain resources, and a caller opts in
|
||||
# per Execution with `terraform_modules`. The sources are the provider bundle's.
|
||||
TERRAFORM_MODULES: bool = False
|
||||
|
||||
# Give Specialists the lessons Skill. Off runs without anything learned, which
|
||||
# is how the evaluation shows whether a lesson helps.
|
||||
LESSONS_ENABLED: bool = True
|
||||
@@ -99,6 +104,12 @@ class Settings(BaseSettings):
|
||||
JEV_ACT_THRESHOLD: float = 0.75
|
||||
JEV_CLOSE_THRESHOLD: float = 0.15
|
||||
JEV_CONFIDENCE_THRESHOLD: float = 0.6
|
||||
# Have a model read the requirements and recommendations against the Checks
|
||||
# when the Target architecture is first submitted, and return what no Check
|
||||
# verifies to its author. The validator makes the same reading after the code
|
||||
# is written, when a gap costs a Revision of design, code and validation. One
|
||||
# model run in every Execution. Off until measured.
|
||||
DESIGN_COVERAGE_REVIEW: bool = False
|
||||
# Review a design's coverage at submission: for each condition a requirement
|
||||
# lists, which Check verifies it. Off until a full case has run with it.
|
||||
JEV_COVERAGE_REVIEW: bool = False
|
||||
|
||||
@@ -101,7 +101,12 @@ async def curate(
|
||||
decided = {proposal.evidence_key for proposal in existing}
|
||||
fresh = [group for group in groups if group.key not in decided][:MAX_GROUPS]
|
||||
if decider is not None and existing:
|
||||
fresh = await _not_already_covered(decider, fresh, existing, covered_at)
|
||||
# A group about one setting is narrower than any lesson about its kind of
|
||||
# problem, and it recurred with those lessons published: it goes to the
|
||||
# curator, who is shown the lessons that exist and may still decline.
|
||||
broad = [group for group in fresh if group.subject is None]
|
||||
kept = await _not_already_covered(decider, broad, existing, covered_at)
|
||||
fresh = [g for g in fresh if g.subject is not None or g in kept]
|
||||
if not fresh:
|
||||
return []
|
||||
by_key = {group.key: group for group in fresh}
|
||||
|
||||
@@ -10,6 +10,8 @@ from dataclasses import dataclass, field
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from app.tools.schema_review import named_settings
|
||||
|
||||
EXAMPLES = 3
|
||||
EXAMPLE_LIMIT = 400
|
||||
# Ids and numbers vary between Executions; what recurs is the shape around them.
|
||||
@@ -29,6 +31,9 @@ class Group:
|
||||
executions: set[str] = field(default_factory=set)
|
||||
occurrences: int = 0
|
||||
examples: list[str] = field(default_factory=list) # client data: never published
|
||||
# The provider setting or resource type the problem was about, for a group
|
||||
# narrowed to one subject. None for a group of every problem of its kind.
|
||||
subject: str | None = None
|
||||
|
||||
def as_context(self) -> dict[str, Any]:
|
||||
return {
|
||||
@@ -61,6 +66,10 @@ def read_candidates(roots: Iterable[Path]) -> list[dict[str, Any]]:
|
||||
return records
|
||||
|
||||
|
||||
# A subject shorter than this is a stray word, not a setting.
|
||||
_SUBJECT_MIN = 4
|
||||
|
||||
|
||||
def _general(text: str, limit: int = 110) -> str:
|
||||
return " ".join(_VARIABLE.sub("…", text).split())[:limit]
|
||||
|
||||
@@ -104,6 +113,31 @@ def _shape(candidate: Mapping[str, Any]) -> tuple[str, str | None, str] | None:
|
||||
return None
|
||||
|
||||
|
||||
def _subjects(candidate: Mapping[str, Any]) -> tuple[str, list[str]] | None:
|
||||
"""For a problem about what a Check says: (how to describe it, the settings and
|
||||
resource types its text names).
|
||||
|
||||
Problems of one kind are one group, and one group gets one lesson. "Validation
|
||||
proposed a Check" was 20 of 32 Executions and a single lesson; what recurred
|
||||
inside it, such as the same setting missed again and again, was invisible. A
|
||||
setting's name is the provider's vocabulary, not a client's, so it can be the
|
||||
subject of a narrower group.
|
||||
"""
|
||||
kind = str(candidate.get("type"))
|
||||
if kind == "proposed_addition":
|
||||
text = str(candidate.get("statement", ""))
|
||||
what = "validation proposed a Check about `{}` that the design lacked"
|
||||
elif kind == "revision" and "cannot be implemented" in str(
|
||||
candidate.get("reason", "")
|
||||
):
|
||||
text = str(candidate.get("reason", ""))
|
||||
what = "a Check about `{}` asked for something that resource cannot do"
|
||||
else:
|
||||
return None
|
||||
names = {name.split(".")[-1] for name in named_settings(text)}
|
||||
return what, sorted(name for name in names if len(name) >= _SUBJECT_MIN)
|
||||
|
||||
|
||||
def group_candidates(
|
||||
records: Sequence[Mapping[str, Any]], *, min_executions: int = 2
|
||||
) -> list[Group]:
|
||||
@@ -138,6 +172,23 @@ def group_candidates(
|
||||
and len(group.examples) < EXAMPLES
|
||||
):
|
||||
group.examples.append(example)
|
||||
narrowed = _subjects(candidate)
|
||||
for subject in narrowed[1] if narrowed else ():
|
||||
about = narrowed[0].format(subject) # type: ignore[index]
|
||||
subkey = hashlib.sha256(
|
||||
f"{kind}|{deliverable}|{about}".encode()
|
||||
).hexdigest()[:10]
|
||||
narrow = groups.setdefault(
|
||||
subkey, Group(subkey, kind, deliverable, about, subject=subject)
|
||||
)
|
||||
narrow.executions.add(execution)
|
||||
narrow.occurrences += 1
|
||||
if (
|
||||
example
|
||||
and example not in narrow.examples
|
||||
and len(narrow.examples) < EXAMPLES
|
||||
):
|
||||
narrow.examples.append(example)
|
||||
return sorted(
|
||||
(g for g in groups.values() if len(g.executions) >= min_executions),
|
||||
key=lambda g: (-len(g.executions), -g.occurrences, g.key),
|
||||
|
||||
@@ -7,7 +7,7 @@ are ordinary evaluation reports; one is made with LESSONS_ENABLED=false.
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from collections.abc import Mapping, Sequence
|
||||
from collections.abc import Collection, Mapping, Sequence
|
||||
from dataclasses import replace
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
@@ -106,6 +106,12 @@ def render(result: Mapping[str, Any], without: Path, with_lessons: Path) -> str:
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
def record(proposals: Sequence[Proposal], proof: str) -> list[Proposal]:
|
||||
"""Write the comparison into every published proposal."""
|
||||
return [write(replace(p, proof=proof)) for p in proposals if p.published]
|
||||
def record(
|
||||
proposals: Sequence[Proposal], proof: str, live: Collection[str]
|
||||
) -> list[Proposal]:
|
||||
"""Write the comparison into the proposal of every lesson in the Skill.
|
||||
|
||||
`live` is the ids the Skill holds now. A retired lesson was not part of what
|
||||
was compared, so its proposal is left as it was.
|
||||
"""
|
||||
return [write(replace(p, proof=proof)) for p in proposals if p.id in live]
|
||||
|
||||
@@ -37,6 +37,9 @@ class Proposal:
|
||||
status: str = NEEDS_TRIAGE
|
||||
proposed: str = ""
|
||||
published: str = ""
|
||||
# The day it was taken out of the Skill again. A retired lesson is not
|
||||
# published a second time, whatever its Status still says.
|
||||
retired: str = ""
|
||||
proof: str = ""
|
||||
comments: str = ""
|
||||
path: Path | None = None
|
||||
@@ -47,7 +50,7 @@ class Proposal:
|
||||
|
||||
@property
|
||||
def approved(self) -> bool:
|
||||
return self.status == APPROVED
|
||||
return self.status == APPROVED and not self.retired
|
||||
|
||||
|
||||
def _slug(title: str) -> str:
|
||||
@@ -65,6 +68,8 @@ def render(proposal: Proposal) -> str:
|
||||
]
|
||||
if proposal.published:
|
||||
lines.append(f"Published: {proposal.published}")
|
||||
if proposal.retired:
|
||||
lines.append(f"Retired: {proposal.retired}")
|
||||
lines += [
|
||||
"",
|
||||
"## Rule",
|
||||
@@ -117,6 +122,7 @@ def parse(path: Path) -> Proposal:
|
||||
status=status,
|
||||
proposed=fields.get("Proposed", ""),
|
||||
published=fields.get("Published", ""),
|
||||
retired=fields.get("Retired", ""),
|
||||
proof="" if proof == "Not yet measured." else proof,
|
||||
comments=sections.get("Comments", ""),
|
||||
path=path,
|
||||
|
||||
@@ -8,7 +8,9 @@ the index in SKILL.md are written here, from approved proposals, and never by ha
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import re
|
||||
from collections.abc import Mapping
|
||||
from dataclasses import replace
|
||||
from datetime import UTC, date, datetime
|
||||
from pathlib import Path
|
||||
@@ -109,6 +111,8 @@ def publish(
|
||||
Raises NotApproved for any proposal a person has not approved: nothing reaches
|
||||
an agent on a curator's say-so.
|
||||
"""
|
||||
if proposal.retired:
|
||||
raise NotApproved(f"{proposal.id} was retired on {proposal.retired}")
|
||||
if not proposal.approved:
|
||||
raise NotApproved(
|
||||
f"{proposal.id} is {proposal.status}; a person approves a lesson by "
|
||||
@@ -130,6 +134,45 @@ def publish(
|
||||
return write(replace(proposal, published=proposal.published or stamp))
|
||||
|
||||
|
||||
# The versions of the Skills the lessons were written beside, kept in the lessons
|
||||
# Skill. A lesson is a correction to how agents follow those Skills, so when one
|
||||
# of them changes each lesson is worth a second look: it may now be said upstream,
|
||||
# or contradict it.
|
||||
UPSTREAM_FILE = "upstream.json"
|
||||
|
||||
|
||||
def upstream_reviewed(skill_dir: Path) -> dict[str, str]:
|
||||
"""The upstream Skill versions the lessons were last reviewed against."""
|
||||
path = skill_dir / UPSTREAM_FILE
|
||||
if not path.is_file():
|
||||
return {}
|
||||
try:
|
||||
data = json.loads(path.read_text(encoding="utf-8"))
|
||||
except ValueError:
|
||||
return {}
|
||||
return {str(k): str(v) for k, v in data.items()} if isinstance(data, dict) else {}
|
||||
|
||||
|
||||
def mark_reviewed(skill_dir: Path, current: Mapping[str, str]) -> None:
|
||||
"""Record that the lessons stand against these upstream Skill versions."""
|
||||
(skill_dir / UPSTREAM_FILE).write_text(
|
||||
json.dumps(dict(sorted(current.items())), indent=2) + "\n", encoding="utf-8"
|
||||
)
|
||||
|
||||
|
||||
def upstream_changes(skill_dir: Path, current: Mapping[str, str]) -> list[str]:
|
||||
"""The upstream Skills that changed, appeared or went since the lessons were
|
||||
last reviewed. Empty when there are no lessons, or nothing was ever recorded."""
|
||||
reviewed = upstream_reviewed(skill_dir)
|
||||
if not reviewed or not published(skill_dir):
|
||||
return []
|
||||
return sorted(
|
||||
name
|
||||
for name in set(reviewed) | set(current)
|
||||
if reviewed.get(name) != current.get(name)
|
||||
)
|
||||
|
||||
|
||||
def retire(lesson_id: str, skill_dir: Path) -> bool:
|
||||
"""Remove a lesson from the Skill. Returns whether it was there."""
|
||||
deliverable = published(skill_dir).get(lesson_id)
|
||||
|
||||
@@ -71,6 +71,7 @@ def create_app(
|
||||
customer_case=body.get("customer_case"),
|
||||
baseline=body.get("baseline"),
|
||||
overlay_skills=body.get("overlay_skills") or (),
|
||||
terraform_modules=body.get("terraform_modules"),
|
||||
pre_approved=True,
|
||||
allow_cloud_read=bool(body.get("allow_cloud_read", False)),
|
||||
)
|
||||
@@ -88,7 +89,7 @@ def create_app(
|
||||
async with assembly_factory(settings) as assembly:
|
||||
handler = DefaultRequestHandlerV2(
|
||||
agent_executor=SolutionArchitectExecutor(
|
||||
assembly.engine, assembly.intake
|
||||
assembly.engine, assembly.intake, assembly.answers
|
||||
),
|
||||
task_store=InMemoryTaskStore(),
|
||||
agent_card=card,
|
||||
|
||||
@@ -15,7 +15,7 @@ import time
|
||||
from collections.abc import Awaitable, Callable, Mapping, MutableMapping, Sequence
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
from typing import Any, cast
|
||||
|
||||
from langgraph.types import Command, Send, interrupt
|
||||
|
||||
@@ -37,7 +37,7 @@ from app.adk.runtime import (
|
||||
TurnEnded,
|
||||
)
|
||||
from app.baseline import WORKING_FILENAME
|
||||
from app.customer_case import close_intent
|
||||
from app.customer_case import IN_PROGRESS, close_intent
|
||||
from app.nodes.router import ModelOrchestrator, OrchestratorPolicy, TurnView
|
||||
from app.recorder import ExecutionRecorder
|
||||
from app.states.execution_state import (
|
||||
@@ -53,7 +53,14 @@ from app.tools.assessment import assess
|
||||
from app.tools.execution import ORCHESTRATOR, OrchestratorToolbox, specialist_tools
|
||||
from app.tools.guardrail import EXECUTION_SCOPE, instructs_agent
|
||||
from app.tools.meaning import settle_meaning
|
||||
from app.tools.pillars import ADVICE_KEY, KEPT_FOR_CHANGES, pillars_touched
|
||||
from app.tools.modules import MODULE_TOOL, MODULES_OPTED_IN
|
||||
from app.tools.pillars import (
|
||||
ADVICE_KEY,
|
||||
KEPT_FOR_CHANGES,
|
||||
QUESTIONS_HEADING,
|
||||
customer_questions,
|
||||
pillars_touched,
|
||||
)
|
||||
from app.tools.skill_routing import read_first
|
||||
from app.workflows.chain import (
|
||||
IMPLEMENTATION_FILE,
|
||||
@@ -82,6 +89,7 @@ NO_USER_REPLY = (
|
||||
"'Assumptions', and proceed."
|
||||
)
|
||||
GUIDE_FILENAME = "solution-architecture-guide.md"
|
||||
QUESTIONS_FILENAME = "customer-questions.md" # what to ask the customer
|
||||
MANIFEST_FILENAME = "execution.json" # request, status and files of one Execution
|
||||
|
||||
|
||||
@@ -206,11 +214,13 @@ def make_execution_nodes(
|
||||
drafts = dict(state.get("drafts", {}))
|
||||
|
||||
outcomes = state.get("outcomes", [])
|
||||
arrived = False
|
||||
for record in outcomes[state.get("outcomes_applied", 0) :]:
|
||||
kind = DeliverableKind(record["kind"])
|
||||
try:
|
||||
if record["type"] == "submitted":
|
||||
ledger.submit(kind, record["attempt"], actor=record["role"])
|
||||
arrived = True
|
||||
deliverables[kind.value] = {
|
||||
"content": record["content"],
|
||||
"attachments": record["attachments"],
|
||||
@@ -251,6 +261,19 @@ def make_execution_nodes(
|
||||
]
|
||||
pending_questions.append({"kind": kind.value, "questions": questions})
|
||||
|
||||
if arrived:
|
||||
# What has been submitted is on disk as soon as it exists, marked as in
|
||||
# progress. A process that is killed leaves that much behind.
|
||||
try:
|
||||
_write_outputs(
|
||||
output_root,
|
||||
cast(ExecutionState, {**state, "deliverables": deliverables}),
|
||||
IN_PROGRESS,
|
||||
ledger,
|
||||
)
|
||||
except OSError:
|
||||
logger.exception("Writing the Execution's files so far failed")
|
||||
|
||||
turns = state.get("turns", 0) + 1
|
||||
update: dict[str, Any] = {
|
||||
"deliverables": deliverables,
|
||||
@@ -458,6 +481,15 @@ def make_execution_nodes(
|
||||
role = dataclasses.replace(
|
||||
role, skills=(*role.skills, *(n for n in named if n not in role.skills))
|
||||
)
|
||||
opted_in = bool(task_input.get("terraform_modules"))
|
||||
MODULES_OPTED_IN.set(opted_in)
|
||||
if opted_in and role.modules_skill:
|
||||
role = dataclasses.replace(role, skills=(*role.skills, role.modules_skill))
|
||||
elif MODULE_TOOL in role.tools:
|
||||
# Plain resources: no modules Skill and no module lookup.
|
||||
role = dataclasses.replace(
|
||||
role, tools=tuple(tool for tool in role.tools if tool != MODULE_TOOL)
|
||||
)
|
||||
if role.first_attempt_model and task_input.get("first_attempt"):
|
||||
logger.info(
|
||||
"[%s] %s takes %s for a first attempt",
|
||||
@@ -874,6 +906,8 @@ def _specialist_input(
|
||||
"first_attempt": not ledger.feedback(kind)
|
||||
and (attempt == 1 or kind.value in deliverables),
|
||||
"allow_cloud_read": state.get("allow_cloud_read"),
|
||||
# Whether this Execution opted into published Terraform modules.
|
||||
"terraform_modules": bool(state.get("terraform_modules")),
|
||||
"working": dict(state.get("working", {}).get(kind.value, {})),
|
||||
# Whether the user has been shown a draft of this Deliverable. Answering some
|
||||
# other question about it, such as what to do after it stopped, is not that.
|
||||
@@ -903,6 +937,9 @@ def _specialist_input(
|
||||
# Skills carrying the organisation's standards or this engagement's
|
||||
# constraints. Where one disagrees with general guidance, it wins.
|
||||
"overlay_skills": sorted(state.get("overlay_skills") or {}),
|
||||
# False: infrastructure code is plain resources. True: a published
|
||||
# module may be used where the modules Skill says one fits.
|
||||
"terraform_modules": bool(state.get("terraform_modules")),
|
||||
# The pillars a change touches, when that could be judged: the design
|
||||
# advisor consults those and keeps its earlier advice for the rest.
|
||||
"pillars_to_consult": (hints or {}).get(kind.value),
|
||||
@@ -1199,6 +1236,30 @@ def _case(state: ExecutionState) -> str:
|
||||
return state.get("customer_case") or UNASSIGNED_CASE
|
||||
|
||||
|
||||
def _written_before(out_dir: Path) -> set[str]:
|
||||
"""The files an earlier write of this Execution's folder recorded."""
|
||||
try:
|
||||
manifest = json.loads((out_dir / MANIFEST_FILENAME).read_text("utf-8"))
|
||||
except (OSError, ValueError):
|
||||
return set()
|
||||
if not isinstance(manifest, dict):
|
||||
return set()
|
||||
names = {
|
||||
manifest.get("solution_guide"),
|
||||
manifest.get("changes"),
|
||||
manifest.get("customer_questions"),
|
||||
}
|
||||
for entry in (manifest.get("deliverables") or {}).values():
|
||||
if isinstance(entry, dict):
|
||||
names.add(entry.get("document"))
|
||||
names.update(entry.get("attachments") or [])
|
||||
return {
|
||||
name
|
||||
for name in names
|
||||
if isinstance(name, str) and name and ".." not in Path(name).parts
|
||||
}
|
||||
|
||||
|
||||
def _write_outputs(
|
||||
output_root: Path,
|
||||
state: ExecutionState,
|
||||
@@ -1243,6 +1304,28 @@ def _write_outputs(
|
||||
if kept:
|
||||
# Working material a Change request starts from, such as each pillar's advice.
|
||||
files[WORKING_FILENAME] = json.dumps(kept, indent=2, ensure_ascii=False)
|
||||
questions = customer_questions(
|
||||
state.get("working", {}).get(DeliverableKind.DESIGN_RECOMMENDATIONS.value, {})
|
||||
)
|
||||
if questions:
|
||||
# What the request did not say enough to settle, as questions to put to
|
||||
# the customer. Missing information, not a fault in the design.
|
||||
files[QUESTIONS_FILENAME] = "\n".join(
|
||||
[
|
||||
f"# {QUESTIONS_HEADING}",
|
||||
"",
|
||||
(
|
||||
"The request did not say enough to settle these. Each answer "
|
||||
"may change a recommendation."
|
||||
),
|
||||
"",
|
||||
*(
|
||||
f"- **{item['pillar']}**, {item['item']} {item['question']}"
|
||||
for item in questions
|
||||
),
|
||||
"",
|
||||
]
|
||||
)
|
||||
baseline = state.get("baseline") or None
|
||||
if baseline:
|
||||
# What this Change request changed against its Baseline, worked out from
|
||||
@@ -1252,6 +1335,11 @@ def _write_outputs(
|
||||
indent=2,
|
||||
ensure_ascii=False,
|
||||
)
|
||||
# The folder is written more than once as an Execution goes. A file an earlier
|
||||
# write left that this one does not have, such as a Terraform file removed in a
|
||||
# Revision, must not stay beside the files that replaced it.
|
||||
for stale in _written_before(out_dir) - set(files):
|
||||
(out_dir / stale).unlink(missing_ok=True)
|
||||
for name, content in files.items():
|
||||
path = out_dir / name
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
@@ -1267,6 +1355,8 @@ def _write_outputs(
|
||||
"baseline": (state.get("baseline") or {}).get("execution_id"),
|
||||
# The overlay Skills it loaded, with the version of each.
|
||||
"overlay_skills": dict(state.get("overlay_skills") or {}),
|
||||
# Whether its infrastructure code was allowed published modules.
|
||||
"terraform_modules": bool(state.get("terraform_modules")),
|
||||
"status": status,
|
||||
"warnings": list(state.get("warnings", [])),
|
||||
# Flags a person should look at; nothing was done about them.
|
||||
@@ -1277,6 +1367,8 @@ def _write_outputs(
|
||||
phase.value: ledger.phase_status(phase).value for phase in PHASE_ORDER
|
||||
},
|
||||
"solution_guide": GUIDE_FILENAME if guide else None,
|
||||
# Questions the request left open, for the customer; None when there are none.
|
||||
"customer_questions": QUESTIONS_FILENAME if questions else None,
|
||||
"changes": CHANGES_FILE if baseline else None,
|
||||
"deliverables": by_kind,
|
||||
}
|
||||
|
||||
@@ -6,6 +6,7 @@ one step earlier, for a message that arrives with no Execution in progress:
|
||||
new request design this workload start an Execution
|
||||
change request change what was delivered name the Baseline to change (ADR-0006)
|
||||
question what can you do, how long... answer; start nothing
|
||||
why did you choose X? answer from what was delivered
|
||||
|
||||
A change is never started from earlier work on a guess: the caller chooses the
|
||||
Baseline. So a message read as a change is answered with the Execution it would
|
||||
@@ -24,7 +25,17 @@ from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from app.adk.runtime import Decider, Question
|
||||
from app.adk.runtime import (
|
||||
AgentRuntime,
|
||||
AgentTask,
|
||||
Decider,
|
||||
Question,
|
||||
RoleSpec,
|
||||
Submitted,
|
||||
ToolResult,
|
||||
ToolSpec,
|
||||
)
|
||||
from app.baseline import BaselineError, load_baseline
|
||||
from app.customer_case import IN_PROGRESS, read_history
|
||||
from app.states.execution_state import UNASSIGNED_CASE
|
||||
|
||||
@@ -53,7 +64,18 @@ def change_note(baseline: str) -> str:
|
||||
)
|
||||
|
||||
|
||||
def no_answer_note(execution_id: str) -> str:
|
||||
"""What a caller is told when a question about delivered work went unanswered."""
|
||||
return (
|
||||
"I could not answer that from the documents delivered in Execution "
|
||||
f"{execution_id}. Its solution guide and Deliverables hold what was "
|
||||
"decided and why. Nothing was started for this message."
|
||||
)
|
||||
|
||||
|
||||
_MESSAGE_LIMIT = 8_000
|
||||
# How much of the delivered guide the answer is written from.
|
||||
_GUIDE_LIMIT = 80_000
|
||||
_EARLIER_SHOWN = 5
|
||||
|
||||
|
||||
@@ -64,6 +86,8 @@ class IntakeReading:
|
||||
judged: bool = False # False when no decision was available
|
||||
earlier: int = 0 # finished Executions of the same Customer case
|
||||
latest: str | None = None # the most recent of them: what a change would change
|
||||
# A question about what was delivered, as opposed to about the service.
|
||||
about_delivered: bool = False
|
||||
|
||||
|
||||
def finished_intents(output_root: Path, customer_case: str) -> list[Mapping[str, Any]]:
|
||||
@@ -85,11 +109,18 @@ class Intake:
|
||||
output_root: Path,
|
||||
*,
|
||||
act: float = 0.75,
|
||||
about_delivered_at: float = 0.6,
|
||||
) -> None:
|
||||
self._decider = decider
|
||||
self._output_root = output_root
|
||||
# How sure the reading must be before anything but a new Execution is done.
|
||||
self._act = act
|
||||
# How likely a question must be about delivered work to be answered from
|
||||
# it. Measured on 2026-10-10: six such questions scored 0.37 to 0.96, five
|
||||
# of them 0.73 or more; six about the service scored 0.07 to 0.16 and one
|
||||
# ambiguous one ("is my data stored anywhere?") 0.74. A wrong yes costs an
|
||||
# answer that says the documents do not cover it.
|
||||
self._about_delivered_at = about_delivered_at
|
||||
|
||||
async def read(
|
||||
self, message: str, customer_case: str | None = None, scope: str = ""
|
||||
@@ -123,9 +154,38 @@ class Intake:
|
||||
kind = NEW_REQUEST # there is nothing delivered to change
|
||||
logger.info("[%s] intake: %s (%.2f)", scope, kind, confidence)
|
||||
latest = str(earlier[-1].get("execution_id")) if earlier else None
|
||||
return IntakeReading(
|
||||
kind, confidence, judged=True, earlier=len(earlier), latest=latest
|
||||
about = (
|
||||
await self._about_delivered(text, earlier, scope)
|
||||
if kind == QUESTION and latest
|
||||
else False
|
||||
)
|
||||
return IntakeReading(
|
||||
kind,
|
||||
confidence,
|
||||
judged=True,
|
||||
earlier=len(earlier),
|
||||
latest=latest,
|
||||
about_delivered=about,
|
||||
)
|
||||
|
||||
async def _about_delivered(
|
||||
self, text: str, earlier: Sequence[Mapping[str, Any]], scope: str
|
||||
) -> bool:
|
||||
answers = await self._decider.decide(
|
||||
_state(text, earlier),
|
||||
{
|
||||
"about_delivered": Question(
|
||||
"noul",
|
||||
"Is the user asking about an architecture already delivered to "
|
||||
"them: what it contains, why something was chosen, or what "
|
||||
"validation found? Answer no when they ask what this service "
|
||||
"does or how it works in general.",
|
||||
)
|
||||
},
|
||||
scope=scope,
|
||||
)
|
||||
answer = (answers or {}).get("about_delivered")
|
||||
return answer is not None and float(answer.value) >= self._about_delivered_at
|
||||
|
||||
|
||||
def _state(message: str, earlier: Sequence[Mapping[str, Any]]) -> str:
|
||||
@@ -135,3 +195,65 @@ def _state(message: str, earlier: Sequence[Mapping[str, Any]]) -> str:
|
||||
lines.append(f"- {request}")
|
||||
lines.append(f"The user's message: {message[:_MESSAGE_LIMIT]}")
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
class DeliveredAnswers:
|
||||
"""Answers a question about delivered work from its documents, on the reply
|
||||
writer. It reads one Execution's files and starts nothing."""
|
||||
|
||||
def __init__(
|
||||
self, runtime: AgentRuntime, role: RoleSpec, output_root: Path
|
||||
) -> None:
|
||||
self._runtime = runtime
|
||||
self._role = role
|
||||
self._output_root = output_root
|
||||
|
||||
async def answer(
|
||||
self, question: str, customer_case: str, execution_id: str
|
||||
) -> str | None:
|
||||
"""The answer, or None when the documents could not be read or the writer
|
||||
gave none."""
|
||||
try:
|
||||
delivered = load_baseline(self._output_root, customer_case, execution_id)
|
||||
except BaselineError:
|
||||
return None
|
||||
guide = str(
|
||||
(delivered["deliverables"].get("solution_guide") or {}).get("content", "")
|
||||
)
|
||||
if not guide.strip():
|
||||
return 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=self._role.name,
|
||||
prompt="Answer the user's question about the architecture delivered to them.",
|
||||
context={
|
||||
"question": question[:_MESSAGE_LIMIT],
|
||||
"delivered": {
|
||||
"execution_id": execution_id,
|
||||
"request": delivered.get("workflow_request", ""),
|
||||
"solution_guide": guide[:_GUIDE_LIMIT],
|
||||
},
|
||||
},
|
||||
)
|
||||
try:
|
||||
outcome = await self._runtime.run(self._role, task, [tool])
|
||||
except Exception: # a question must still get a reply
|
||||
logger.exception("Answering from delivered work failed")
|
||||
return None
|
||||
return outcome.content if isinstance(outcome, Submitted) else None
|
||||
|
||||
@@ -634,6 +634,12 @@ class Router:
|
||||
"a reason."
|
||||
for item in r.unimplementable
|
||||
)
|
||||
# In the run of 2026-10-09 a second Check with the same fault came back
|
||||
# one Revision later, for the same reason word for word.
|
||||
reason += (
|
||||
" The same fault may be in other Checks: read every Check against "
|
||||
"each reason given here and correct every one it applies to."
|
||||
)
|
||||
return await call(
|
||||
"reopen", kind=DeliverableKind.TARGET_ARCHITECTURE.value, reason=reason
|
||||
)
|
||||
|
||||
@@ -72,6 +72,16 @@ class ProviderBundle:
|
||||
# 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)
|
||||
# Registry namespaces generated code may take a Terraform module from. Empty
|
||||
# means no module is accepted.
|
||||
terraform_module_namespaces: tuple[str, ...] = ()
|
||||
# The Skill that says which modules to use and when. It reaches a Specialist
|
||||
# only in an Execution that opted into modules.
|
||||
terraform_modules_skill: str | None = None
|
||||
# Modules that could not be used with the pinned providers when last looked
|
||||
# at, as <namespace>/<name>/<provider>. scripts/check-terraform-modules.py
|
||||
# says when one can.
|
||||
terraform_modules_watch: tuple[str, ...] = ()
|
||||
# The Skill approved lessons are published in (ADR-0004); None when the provider
|
||||
# has none. A Specialist is given it once it holds lessons for its Deliverable.
|
||||
lessons_skill: str | None = None
|
||||
@@ -155,6 +165,21 @@ def load_provider(name: str, root: Path | None = None) -> ProviderBundle:
|
||||
"version": pin["version"],
|
||||
}
|
||||
|
||||
module_namespaces = ((config.get("terraform") or {}).get("modules") or {}).get(
|
||||
"namespaces"
|
||||
) or []
|
||||
if not isinstance(module_namespaces, list) or not all(
|
||||
isinstance(item, str) and item for item in module_namespaces
|
||||
):
|
||||
raise fail("'terraform.modules.namespaces' must be a list of names")
|
||||
modules_skill = ((config.get("terraform") or {}).get("modules") or {}).get(
|
||||
"skill"
|
||||
) or None
|
||||
if modules_skill is not None and modules_skill not in skills:
|
||||
raise fail(
|
||||
f"'terraform.modules.skill' references unknown skill {modules_skill!r}"
|
||||
)
|
||||
|
||||
tools = {}
|
||||
for tier, tool_names in (config.get("tools") or {}).items():
|
||||
if tier not in TIERS:
|
||||
@@ -221,5 +246,14 @@ def load_provider(name: str, root: Path | None = None) -> ProviderBundle:
|
||||
role_skills=role_skills,
|
||||
pillar_skills=pillar_skills,
|
||||
terraform_providers=terraform_providers,
|
||||
terraform_module_namespaces=tuple(module_namespaces),
|
||||
terraform_modules_skill=modules_skill,
|
||||
terraform_modules_watch=tuple(
|
||||
str(item)
|
||||
for item in ((config.get("terraform") or {}).get("modules") or {}).get(
|
||||
"watch"
|
||||
)
|
||||
or ()
|
||||
),
|
||||
lessons_skill=lessons_skill,
|
||||
)
|
||||
|
||||
@@ -58,6 +58,7 @@ class ExecutionState(TypedDict, total=False):
|
||||
workflow_request: str
|
||||
risks: list[dict[str, Any]] # flags on what the user wrote, for a person to see
|
||||
overlay_skills: dict[str, str] # overlay Skills this Execution loads -> version
|
||||
terraform_modules: bool # opted into published Terraform modules
|
||||
baseline: dict[str, Any] | None # a Change request's Baseline, read from its files
|
||||
pre_approved: bool
|
||||
allow_cloud_read: bool | None
|
||||
|
||||
@@ -32,6 +32,21 @@ QUALITY_RUBRIC: Mapping[str, str] = {
|
||||
_JUDGED = "design_recommendations"
|
||||
|
||||
|
||||
def checklist_question(pillar: str, item: str) -> str:
|
||||
"""Whether the recommendations account for one item of a pillar's checklist.
|
||||
|
||||
An item is accounted for in three ways. The third matters: a customer's request
|
||||
seldom says enough to settle every item, and what it leaves unsaid is a
|
||||
question for them, not a fault in the design (the owner, 2026-10-10).
|
||||
"""
|
||||
return (
|
||||
f"Do the recommendations account for this {pillar} checklist item in any "
|
||||
"of these ways: by recommending it, by explaining why it does not apply, "
|
||||
"or by recording it as something to confirm with the customer? "
|
||||
f"{item}"
|
||||
)
|
||||
|
||||
|
||||
async def assess(
|
||||
decider: Decider,
|
||||
deliverables: Mapping[str, Mapping[str, Any]],
|
||||
|
||||
151
app/tools/design_review.py
Normal file
151
app/tools/design_review.py
Normal file
@@ -0,0 +1,151 @@
|
||||
"""A review of a design's coverage by a model, before anyone approves it.
|
||||
|
||||
The validator reads the requirements and recommendations against the Checks and
|
||||
proposes one for each condition nothing verifies. That reading needs no code, but it
|
||||
used to happen only after the code was written: in the runs of 2026-10-09 it sent
|
||||
the Target architecture back in four of seven, each time costing a Revision of the
|
||||
design, the code and the validation (iteration 6 step 12).
|
||||
|
||||
This is the same reading, made when the Target architecture is first submitted and
|
||||
returned to its author. It is a review like the others: what it raises is returned
|
||||
once and never blocks, and when it fails the submission stands.
|
||||
|
||||
It runs once in an Execution. A Revision is asked for by the validator or the user,
|
||||
who have just read the design; reviewing it again would pay for the same reading.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
from collections.abc import Mapping, Sequence
|
||||
from typing import Any
|
||||
|
||||
from app.adk.runtime import (
|
||||
AgentRuntime,
|
||||
AgentTask,
|
||||
RoleSpec,
|
||||
Submitted,
|
||||
ToolResult,
|
||||
ToolSpec,
|
||||
)
|
||||
from app.workflows.chain import (
|
||||
RECOMMENDATIONS_FILE,
|
||||
REQUIREMENTS_FILE,
|
||||
Upstream,
|
||||
read_list,
|
||||
)
|
||||
from app.workflows.deliverables import DeliverableKind
|
||||
from app.workflows.target_architecture import GRAPH_ATTACHMENT, GraphError, parse_graph
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
MAX_GAPS = 12
|
||||
|
||||
|
||||
class DesignCoverageReview:
|
||||
def __init__(self, runtime: AgentRuntime, role: RoleSpec) -> None:
|
||||
self._runtime = runtime
|
||||
self._role = role
|
||||
self._reviewed: set[str] = set()
|
||||
|
||||
async def __call__(
|
||||
self,
|
||||
kind: DeliverableKind,
|
||||
attachments: Mapping[str, str],
|
||||
upstream: Upstream | None,
|
||||
scope: str = "",
|
||||
) -> Sequence[str]:
|
||||
"""The conditions the reviewer finds no Check verifies, each as a line for
|
||||
the target architect. Empty when it finds none or could not review."""
|
||||
if kind is not DeliverableKind.TARGET_ARCHITECTURE or not upstream:
|
||||
return ()
|
||||
text = attachments.get(GRAPH_ATTACHMENT, "")
|
||||
try:
|
||||
graph = parse_graph(text)
|
||||
except GraphError:
|
||||
return ()
|
||||
if scope in self._reviewed:
|
||||
return ()
|
||||
self._reviewed.add(scope)
|
||||
|
||||
constraints = [
|
||||
item
|
||||
for item in read_list(upstream, "requirements", REQUIREMENTS_FILE)
|
||||
if item.get("kind") == "non_functional"
|
||||
] + read_list(upstream, "design_recommendations", RECOMMENDATIONS_FILE)
|
||||
known = {str(item.get("id")) for item in constraints}
|
||||
applies_to = {element.id for element in graph.elements} | {
|
||||
relationship.id for relationship in graph.relationships
|
||||
}
|
||||
|
||||
async def report_gaps(gaps: Any = None) -> ToolResult:
|
||||
if not isinstance(gaps, list):
|
||||
return ToolResult("Not recorded: `gaps` is a list; empty when none.")
|
||||
return ToolResult("Recorded.", Submitted(json.dumps(gaps)))
|
||||
|
||||
tool = ToolSpec(
|
||||
"report_gaps",
|
||||
"Give every gap you found, in one call. An empty list when the Checks "
|
||||
"verify every condition. Ends your turn.",
|
||||
{
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"gaps": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"source": {
|
||||
"type": "string",
|
||||
"description": "The requirement or recommendation id",
|
||||
},
|
||||
"applies_to": {
|
||||
"type": "string",
|
||||
"description": "The Element or Relationship id",
|
||||
},
|
||||
"statement": {
|
||||
"type": "string",
|
||||
"description": "The Check that is missing",
|
||||
},
|
||||
},
|
||||
"required": ["source", "applies_to", "statement"],
|
||||
},
|
||||
}
|
||||
},
|
||||
"required": ["gaps"],
|
||||
},
|
||||
report_gaps,
|
||||
tier="execution",
|
||||
)
|
||||
task = AgentTask(
|
||||
role=self._role.name,
|
||||
prompt="Review whether the Target architecture's Checks verify every "
|
||||
"condition of the requirements and recommendations.",
|
||||
context={
|
||||
"constraints": constraints,
|
||||
"target_architecture": json.loads(text),
|
||||
},
|
||||
)
|
||||
outcome = await self._runtime.run(self._role, task, [tool])
|
||||
if not isinstance(outcome, Submitted):
|
||||
logger.info("[%s] design coverage review gave no answer", scope)
|
||||
return ()
|
||||
try:
|
||||
reported = json.loads(outcome.content)
|
||||
except ValueError:
|
||||
return ()
|
||||
concerns = []
|
||||
for gap in reported if isinstance(reported, list) else []:
|
||||
if not isinstance(gap, Mapping):
|
||||
continue
|
||||
source, where = str(gap.get("source", "")), str(gap.get("applies_to", ""))
|
||||
statement = " ".join(str(gap.get("statement", "")).split())
|
||||
# A gap must be about something that exists: an invented id is dropped.
|
||||
if source not in known or where not in applies_to or not statement:
|
||||
continue
|
||||
concerns.append(f"{source}: no Check verifies this on {where}: {statement}")
|
||||
logger.info(
|
||||
"[%s] design coverage review raised %d gap(s)", scope, len(concerns)
|
||||
)
|
||||
return tuple(concerns[:MAX_GAPS])
|
||||
@@ -30,6 +30,7 @@ from pathlib import Path, PurePosixPath
|
||||
from typing import Any
|
||||
|
||||
from app.adk.runtime import FILES_SCHEMA, ToolResult, ToolSpec, files_from_argument
|
||||
from app.tools.modules import ModuleLookup, allowed_namespaces, check_module_sources
|
||||
|
||||
_MAX_OUTPUT = 8_000
|
||||
_MAX_OUTLINE = 4_000 # one resource type, when several are looked up together
|
||||
@@ -98,6 +99,10 @@ class TerraformRunner:
|
||||
# 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)
|
||||
# Registry namespaces a `module` may come from, as the provider bundle lists
|
||||
# them. `terraform init` downloads and evaluates whatever a source names, so
|
||||
# with none listed every module call is refused.
|
||||
module_namespaces: tuple[str, ...] = ()
|
||||
# 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)
|
||||
@@ -138,7 +143,9 @@ class TerraformRunner:
|
||||
)
|
||||
|
||||
async def validate(self, files: Mapping[str, str]) -> ToolResult:
|
||||
refusal = _check_files(files)
|
||||
refusal = _check_files(files) or check_module_sources(
|
||||
files, allowed_namespaces(self.module_namespaces)
|
||||
)
|
||||
if refusal:
|
||||
return refusal
|
||||
with tempfile.TemporaryDirectory(prefix="tf-validate-") as tmp:
|
||||
@@ -153,7 +160,9 @@ class TerraformRunner:
|
||||
async def plan(
|
||||
self, files: Mapping[str, str], variables: Mapping[str, str] | None = None
|
||||
) -> ToolResult:
|
||||
refusal = _check_files(files)
|
||||
refusal = _check_files(files) or check_module_sources(
|
||||
files, allowed_namespaces(self.module_namespaces)
|
||||
)
|
||||
if refusal:
|
||||
return refusal
|
||||
variables = dict(variables or {})
|
||||
@@ -582,6 +591,16 @@ LOCAL_TOOLS: dict[str, tuple[str, str]] = {
|
||||
"cloud_read",
|
||||
"Preview Terraform against the live cloud environment with a plan. Never applies.",
|
||||
),
|
||||
"terraform_module": (
|
||||
"general",
|
||||
(
|
||||
"Look up a published Terraform module: its inputs, outputs and "
|
||||
"submodules, and whether it works with the pinned provider. Give "
|
||||
"`source` as <namespace>/<name>/<provider>, with //modules/<name> for "
|
||||
"a submodule. `version` is optional and defaults to the latest. `find` "
|
||||
"narrows the inputs to those matching the words given."
|
||||
),
|
||||
),
|
||||
"terraform_schema": (
|
||||
"general",
|
||||
(
|
||||
@@ -651,6 +670,32 @@ def local_tools(
|
||||
"terraform_plan": lambda: checks(
|
||||
"terraform_plan", _with_files(runner.plan, working_copy)
|
||||
),
|
||||
"terraform_module": lambda: ToolSpec(
|
||||
"terraform_module",
|
||||
LOCAL_TOOLS["terraform_module"][1],
|
||||
{
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"source": {
|
||||
"type": "string",
|
||||
"description": (
|
||||
"For example terraform-google-modules/network/google"
|
||||
),
|
||||
},
|
||||
"version": {"type": "string", "description": "Such as 18.3.1"},
|
||||
"find": {
|
||||
"type": "string",
|
||||
"description": "Words to look for in input names, comma-separated",
|
||||
},
|
||||
},
|
||||
"required": ["source"],
|
||||
},
|
||||
ModuleLookup(
|
||||
namespaces=runner.module_namespaces,
|
||||
pinned={name: pin["version"] for name, pin in runner.providers.items()},
|
||||
).describe,
|
||||
tier="general",
|
||||
),
|
||||
"terraform_schema": lambda: ToolSpec(
|
||||
"terraform_schema",
|
||||
LOCAL_TOOLS["terraform_schema"][1],
|
||||
|
||||
300
app/tools/modules.py
Normal file
300
app/tools/modules.py
Normal file
@@ -0,0 +1,300 @@
|
||||
"""Terraform modules from a public registry (iteration 8).
|
||||
|
||||
Generated code may call a published module where one replaces several resources that
|
||||
must be wired together. Two things keep that safe and checkable, and neither names a
|
||||
Cloud provider: the provider bundle does.
|
||||
|
||||
- **Which modules.** `terraform init` downloads whatever a `source` names and
|
||||
Terraform then evaluates it. So a module is accepted only from a registry
|
||||
namespace the bundle lists, at one exact version. Anything else, a Git URL, a
|
||||
local path or a version range, is refused before Terraform runs.
|
||||
- **What a module accepts.** A module hides the resources a Check is about. The
|
||||
lookup returns a module's inputs, outputs and submodules from the registry, and
|
||||
says whether its provider requirements admit the version the bundle pins.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import contextvars
|
||||
import json
|
||||
import logging
|
||||
import re
|
||||
from collections.abc import Mapping, Sequence
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Any
|
||||
|
||||
import httpx
|
||||
|
||||
from app.adk.runtime import ToolResult
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
REGISTRY = "https://registry.terraform.io/v1/modules"
|
||||
MODULE_TOOL = "terraform_module"
|
||||
# Whether the Execution a Specialist is running in opted into modules. Set when a
|
||||
# Specialist starts. Unset, outside an Execution, the runner's own list applies.
|
||||
MODULES_OPTED_IN: contextvars.ContextVar[bool | None] = contextvars.ContextVar(
|
||||
"terraform_modules_opted_in", default=None
|
||||
)
|
||||
NOT_OPTED_IN = (
|
||||
"Refused: this Execution writes plain resources. Published modules are used "
|
||||
"only when the Execution opts into them. Write the resources directly."
|
||||
)
|
||||
|
||||
|
||||
def allowed_namespaces(configured: Sequence[str]) -> tuple[str, ...]:
|
||||
"""The namespaces a module may come from, here and now: none when the Execution
|
||||
did not opt in."""
|
||||
return () if MODULES_OPTED_IN.get() is False else tuple(configured)
|
||||
|
||||
|
||||
_MODULE = re.compile(r'^\s*module\s+"([^"]+)"\s*\{', re.MULTILINE)
|
||||
_SOURCE = re.compile(r'^\s*source\s*=\s*"([^"]*)"', re.MULTILINE)
|
||||
_VERSION = re.compile(r'^\s*version\s*=\s*"([^"]*)"', re.MULTILINE)
|
||||
_EXACT = re.compile(r"^\d+\.\d+\.\d+$")
|
||||
# namespace/name/provider, with an optional //path/to/submodule
|
||||
_REGISTRY_SOURCE = re.compile(
|
||||
r"^([A-Za-z0-9_-]+)/([A-Za-z0-9_-]+)/([a-z0-9]+)(?://([\w./-]+))?$"
|
||||
)
|
||||
_MAX_INPUTS = 80
|
||||
_DESCRIPTION = 140
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ModuleCall:
|
||||
name: str
|
||||
source: str
|
||||
version: str
|
||||
|
||||
|
||||
def module_calls(files: Mapping[str, str]) -> list[ModuleCall]:
|
||||
"""Every `module` block in the files, with the source and version it names."""
|
||||
calls = []
|
||||
for text in files.values():
|
||||
for match in _MODULE.finditer(text):
|
||||
body = _block(text, match.end())
|
||||
source = _SOURCE.search(body)
|
||||
version = _VERSION.search(body)
|
||||
calls.append(
|
||||
ModuleCall(
|
||||
match.group(1),
|
||||
source.group(1) if source else "",
|
||||
version.group(1) if version else "",
|
||||
)
|
||||
)
|
||||
return calls
|
||||
|
||||
|
||||
def _block(text: str, start: int) -> str:
|
||||
"""The text of a block whose opening brace ends at `start`, nested blocks
|
||||
removed, so only its own arguments are read."""
|
||||
depth, own, index = 1, [], start
|
||||
while index < len(text) and depth:
|
||||
char = text[index]
|
||||
if char == "{":
|
||||
depth += 1
|
||||
elif char == "}":
|
||||
depth -= 1
|
||||
elif depth == 1:
|
||||
own.append(char)
|
||||
index += 1
|
||||
return "".join(own)
|
||||
|
||||
|
||||
def check_module_sources(
|
||||
files: Mapping[str, str], namespaces: Sequence[str]
|
||||
) -> ToolResult | None:
|
||||
"""Refuse a module that is not from an allowed registry namespace at one exact
|
||||
version. None when every module call is acceptable, or there are none."""
|
||||
if any(
|
||||
name.endswith(".tf.json") and '"module"' in text for name, text in files.items()
|
||||
):
|
||||
return ToolResult("Refused: write module calls in .tf files, not .tf.json.")
|
||||
calls = module_calls(files)
|
||||
if calls and MODULES_OPTED_IN.get() is False:
|
||||
return ToolResult(NOT_OPTED_IN)
|
||||
problems = []
|
||||
for call in calls:
|
||||
parsed = _REGISTRY_SOURCE.match(call.source)
|
||||
if not parsed or parsed.group(1) not in namespaces:
|
||||
allowed = ", ".join(namespaces) or "none are configured"
|
||||
problems.append(
|
||||
f'module "{call.name}": source "{call.source}" is not allowed. A '
|
||||
"module comes only from these registry namespaces, as "
|
||||
f"<namespace>/<name>/<provider>: {allowed}"
|
||||
)
|
||||
elif not _EXACT.match(call.version):
|
||||
problems.append(
|
||||
f'module "{call.name}": set `version` to one exact version, such '
|
||||
f'as "1.2.3"; got "{call.version}"'
|
||||
)
|
||||
if problems:
|
||||
return ToolResult("Refused: " + "; ".join(problems) + ".")
|
||||
return None
|
||||
|
||||
|
||||
# --- what a module accepts --------------------------------------------------------------
|
||||
|
||||
|
||||
def admits(constraint: str, version: str) -> bool:
|
||||
"""Whether a Terraform version constraint, such as ">= 6.2, < 8", admits an
|
||||
exact version. An unreadable term is taken to admit it."""
|
||||
wanted = _numbers(version)
|
||||
for term in constraint.split(","):
|
||||
match = re.match(r"^\s*(>=|<=|>|<|=|!=|~>)?\s*v?([\d.]+)", term)
|
||||
if not match:
|
||||
continue
|
||||
operator, bound = match.group(1) or "=", _numbers(match.group(2))
|
||||
if operator == "~>":
|
||||
# ~> 3.0 admits 3.x; ~> 3.1.2 admits 3.1.x from 3.1.2.
|
||||
upper = [*bound[:-1]]
|
||||
if upper:
|
||||
upper[-1] += 1
|
||||
ok = wanted >= bound and (not upper or wanted < upper)
|
||||
else:
|
||||
ok = {
|
||||
">=": wanted >= bound,
|
||||
"<=": wanted <= bound,
|
||||
">": wanted > bound,
|
||||
"<": wanted < bound,
|
||||
"=": wanted[: len(bound)] == bound,
|
||||
"!=": wanted[: len(bound)] != bound,
|
||||
}[operator]
|
||||
if not ok:
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def _numbers(version: str) -> list[int]:
|
||||
return [int(part) for part in version.split(".") if part.isdigit()]
|
||||
|
||||
|
||||
@dataclass
|
||||
class ModuleLookup:
|
||||
"""Reads a module's inputs and outputs from the registry."""
|
||||
|
||||
namespaces: tuple[str, ...] = ()
|
||||
# The provider versions generated code is pinned to: {local name: version}.
|
||||
pinned: Mapping[str, str] = field(default_factory=dict)
|
||||
timeout_seconds: float = 20
|
||||
_cache: dict[str, dict[str, Any]] = field(default_factory=dict, repr=False)
|
||||
|
||||
async def describe(
|
||||
self, source: str = "", version: str = "", find: str = ""
|
||||
) -> ToolResult:
|
||||
parsed = _REGISTRY_SOURCE.match(source.strip())
|
||||
if not parsed or parsed.group(1) not in self.namespaces:
|
||||
allowed = ", ".join(self.namespaces) or "none are configured"
|
||||
return ToolResult(
|
||||
f'Refused: "{source}" is not a module from an allowed registry '
|
||||
f"namespace. Give <namespace>/<name>/<provider>, optionally with "
|
||||
f"//modules/<submodule>. Allowed namespaces: {allowed}."
|
||||
)
|
||||
namespace, name, provider, path = parsed.groups()
|
||||
if version and not _EXACT.match(version):
|
||||
return ToolResult(
|
||||
'Refused: `version` is one exact version, such as "1.2.3".'
|
||||
)
|
||||
data = await self._fetch(f"{namespace}/{name}/{provider}", version)
|
||||
if isinstance(data, ToolResult):
|
||||
return data
|
||||
part = data.get("root") or {}
|
||||
if path:
|
||||
wanted = path.strip("/")
|
||||
part = next(
|
||||
(
|
||||
item
|
||||
for item in data.get("submodules") or []
|
||||
if item.get("path", "").strip("/") == wanted
|
||||
),
|
||||
None,
|
||||
)
|
||||
if part is None:
|
||||
listed = ", ".join(
|
||||
item.get("path", "") for item in data.get("submodules") or []
|
||||
)
|
||||
return ToolResult(
|
||||
f"{namespace}/{name}/{provider} {data.get('version')} has no "
|
||||
f"submodule at {path}. Its submodules: {listed or 'none'}."
|
||||
)
|
||||
return ToolResult(self._render(data, part, source, find))
|
||||
|
||||
async def _fetch(self, module: str, version: str) -> dict[str, Any] | ToolResult:
|
||||
key = f"{module}/{version}" if version else module
|
||||
if key in self._cache:
|
||||
return self._cache[key]
|
||||
try:
|
||||
async with httpx.AsyncClient(timeout=self.timeout_seconds) as client:
|
||||
response = await client.get(f"{REGISTRY}/{key}")
|
||||
except httpx.HTTPError as exc:
|
||||
return ToolResult(
|
||||
f"The module registry could not be reached ({type(exc).__name__}). "
|
||||
"Write the resources directly, from the patterns and the schema."
|
||||
)
|
||||
if response.status_code == 404:
|
||||
return ToolResult(f"The registry has no module {module} {version}.".strip())
|
||||
if response.status_code != 200:
|
||||
return ToolResult(
|
||||
f"The module registry answered {response.status_code} for {module}."
|
||||
)
|
||||
try:
|
||||
data = response.json()
|
||||
except json.JSONDecodeError:
|
||||
return ToolResult(f"The registry's answer for {module} was not readable.")
|
||||
self._cache[key] = data
|
||||
return data
|
||||
|
||||
def _render(
|
||||
self,
|
||||
data: Mapping[str, Any],
|
||||
part: Mapping[str, Any],
|
||||
source: str,
|
||||
find: str,
|
||||
) -> str:
|
||||
version = data.get("version", "")
|
||||
lines = [f'{source} version "{version}"']
|
||||
for dependency in part.get("provider_dependencies") or []:
|
||||
name, constraint = dependency.get("name", ""), dependency.get("version", "")
|
||||
pin = self.pinned.get(name)
|
||||
if pin and constraint and not admits(constraint, pin):
|
||||
lines.append(
|
||||
f"NOT USABLE: it requires {name} {constraint}, and the code is "
|
||||
f"pinned to {name} {pin}. Write the resources directly."
|
||||
)
|
||||
elif not pin and name:
|
||||
lines.append(
|
||||
f"It also uses the {name} provider ({constraint or 'any version'});"
|
||||
" Terraform installs it."
|
||||
)
|
||||
inputs = sorted(
|
||||
part.get("inputs") or [],
|
||||
key=lambda item: (not item.get("required"), item.get("name", "")),
|
||||
)
|
||||
if find:
|
||||
wanted = [word.strip().lower() for word in find.split(",") if word.strip()]
|
||||
inputs = [
|
||||
item
|
||||
for item in inputs
|
||||
if any(
|
||||
word
|
||||
in f"{item.get('name', '')} {item.get('description', '')}".lower()
|
||||
for word in wanted
|
||||
)
|
||||
]
|
||||
lines.append(f"Inputs matching {find}: {len(inputs) or 'none'}")
|
||||
else:
|
||||
lines.append(f"Inputs ({len(inputs)}; required first):")
|
||||
for item in inputs[:_MAX_INPUTS]:
|
||||
need = "required" if item.get("required") else "optional"
|
||||
kind = " ".join(str(item.get("type", "")).split())[:60]
|
||||
about = " ".join(str(item.get("description", "")).split())[:_DESCRIPTION]
|
||||
lines.append(f"- {item.get('name')} ({need}, {kind}): {about}")
|
||||
if len(inputs) > _MAX_INPUTS:
|
||||
lines.append(f"[{len(inputs) - _MAX_INPUTS} more; use `find`]")
|
||||
outputs = [item.get("name", "") for item in part.get("outputs") or []]
|
||||
if outputs and not find:
|
||||
lines.append("Outputs: " + ", ".join(outputs))
|
||||
submodules = [item.get("path", "") for item in data.get("submodules") or []]
|
||||
if submodules and not find:
|
||||
lines.append("Submodules: " + ", ".join(submodules))
|
||||
return "\n".join(lines)
|
||||
@@ -39,12 +39,18 @@ REVIEW_HEADING = "Architecture framework checklist review"
|
||||
# What a Change request carries over from its Baseline's working memory.
|
||||
KEPT_FOR_CHANGES = (ADVICE_KEY, CHECKLIST_KEY)
|
||||
_CHANGE_LIMIT = 6_000
|
||||
STATUSES = ("addressed", "not_applicable", "not_addressed")
|
||||
NEEDS_CUSTOMER = "needs_customer_input"
|
||||
STATUSES = ("addressed", "not_applicable", NEEDS_CUSTOMER, "not_addressed")
|
||||
_STATUS_WORDS = {
|
||||
"addressed": "Addressed",
|
||||
"not_applicable": "Does not apply",
|
||||
# The item applies, and the customer's request does not say what would settle
|
||||
# it. That is missing information, not a fault in the design: it is reported
|
||||
# with the question to put to the customer.
|
||||
NEEDS_CUSTOMER: "To confirm with the customer",
|
||||
"not_addressed": "Not addressed",
|
||||
}
|
||||
QUESTIONS_HEADING = "Questions for the customer"
|
||||
|
||||
|
||||
AFFECTED = ("not at all", "only indirectly", "directly")
|
||||
@@ -215,17 +221,29 @@ def _submit_advice_tool(review: list[dict[str, str]]) -> ToolSpec:
|
||||
async def submit_advice(content: str, checklist: Sequence[Any] = ()) -> ToolResult:
|
||||
if not content.strip():
|
||||
return ToolResult("Not submitted: the advice is empty.")
|
||||
review[:] = [
|
||||
entries = [
|
||||
{
|
||||
"item": " ".join(str(entry.get("item", "")).split()),
|
||||
"status": str(entry.get("status", "")),
|
||||
"note": " ".join(str(entry.get("note", "")).split()),
|
||||
"question": " ".join(str(entry.get("question") or "").split()),
|
||||
}
|
||||
for entry in checklist or ()
|
||||
if isinstance(entry, Mapping)
|
||||
and str(entry.get("item", "")).strip()
|
||||
and entry.get("status") in STATUSES
|
||||
]
|
||||
unasked = [
|
||||
entry["item"]
|
||||
for entry in entries
|
||||
if entry["status"] == NEEDS_CUSTOMER and not entry["question"]
|
||||
]
|
||||
if unasked:
|
||||
return ToolResult(
|
||||
"Not submitted: an item to confirm with the customer needs the "
|
||||
"`question` to put to them. Missing for: " + "; ".join(unasked)
|
||||
)
|
||||
review[:] = entries
|
||||
return ToolResult("Advice submitted.", Submitted(content))
|
||||
|
||||
text = {"type": "string"}
|
||||
@@ -248,8 +266,15 @@ def _submit_advice_tool(review: list[dict[str, str]]) -> ToolSpec:
|
||||
"status": {"type": "string", "enum": list(STATUSES)},
|
||||
"note": {
|
||||
"type": "string",
|
||||
"description": "How your advice addresses it, or "
|
||||
"why it does not apply to this workload.",
|
||||
"description": "How your advice addresses it, why "
|
||||
"it does not apply to this workload, or what the "
|
||||
"request leaves unsaid.",
|
||||
},
|
||||
"question": {
|
||||
"type": "string",
|
||||
"description": "For needs_customer_input only: "
|
||||
"the question to put to the customer, answerable "
|
||||
"by someone who knows their organisation.",
|
||||
},
|
||||
},
|
||||
"required": ["item", "status", "note"],
|
||||
@@ -274,7 +299,8 @@ def render_checklist_review(working: Mapping[str, Any]) -> str:
|
||||
"",
|
||||
(
|
||||
"Each pillar advisor's review of its pillar's checklist for this "
|
||||
"workload: what its advice addresses, and what does not apply and why."
|
||||
"workload: what its advice addresses, what does not apply and why, and "
|
||||
"what the request does not say enough to settle."
|
||||
),
|
||||
]
|
||||
for pillar, entries in reviews.items():
|
||||
@@ -301,4 +327,48 @@ def render_checklist_review(working: Mapping[str, Any]) -> str:
|
||||
for entry in entries
|
||||
if isinstance(entry, Mapping)
|
||||
]
|
||||
questions = customer_questions(working)
|
||||
if questions:
|
||||
parts += [
|
||||
"",
|
||||
f"### {QUESTIONS_HEADING}",
|
||||
"",
|
||||
(
|
||||
"The request does not say enough to settle these. They are not "
|
||||
"faults in the design: each is something to ask the customer, and "
|
||||
"the answer may change a recommendation."
|
||||
),
|
||||
"",
|
||||
"| Pillar | About | Question |",
|
||||
"| --- | --- | --- |",
|
||||
]
|
||||
parts += [
|
||||
"| "
|
||||
+ " | ".join(
|
||||
value.replace("|", "\\|")
|
||||
for value in (item["pillar"], item["item"], item["question"])
|
||||
)
|
||||
+ " |"
|
||||
for item in questions
|
||||
]
|
||||
return "\n".join(parts) + "\n"
|
||||
|
||||
|
||||
def customer_questions(working: Mapping[str, Any]) -> list[dict[str, str]]:
|
||||
"""What the advisors found the request does not say: each checklist item that
|
||||
needs the customer's answer, with the question to put to them."""
|
||||
reviews = working.get(CHECKLIST_KEY)
|
||||
if not isinstance(reviews, Mapping):
|
||||
return []
|
||||
return [
|
||||
{
|
||||
"pillar": str(pillar),
|
||||
"item": str(entry.get("item", "")),
|
||||
"question": str(entry.get("question", "")),
|
||||
}
|
||||
for pillar, entries in reviews.items()
|
||||
for entry in entries or ()
|
||||
if isinstance(entry, Mapping)
|
||||
and entry.get("status") == NEEDS_CUSTOMER
|
||||
and entry.get("question")
|
||||
]
|
||||
|
||||
@@ -36,6 +36,9 @@ _NAME = re.compile(
|
||||
r"(?![\w/\-])"
|
||||
)
|
||||
_PATH = re.compile(r"^[a-z][a-z0-9_]*(?:\.[a-z][a-z0-9_]*)*$")
|
||||
# Values a Check may put in backticks. `true` and `false` were raised as missing
|
||||
# settings in a run of 2026-10-10.
|
||||
_LITERALS = frozenset({"true", "false", "null", "none"})
|
||||
|
||||
|
||||
def named_settings(statement: str) -> tuple[str, ...]:
|
||||
@@ -48,7 +51,7 @@ def named_settings(statement: str) -> tuple[str, ...]:
|
||||
found: list[str] = []
|
||||
for span in _CODE.findall(statement):
|
||||
candidate = span.strip().split("=")[0].strip()
|
||||
if _PATH.match(candidate):
|
||||
if _PATH.match(candidate) and candidate not in _LITERALS:
|
||||
found.append(candidate)
|
||||
bare = _QUOTED.sub(" ", _CODE.sub(" ", statement))
|
||||
found += [match.group(1).rstrip(".") for match in _NAME.finditer(bare)]
|
||||
|
||||
@@ -31,6 +31,7 @@ from typing import Any
|
||||
from app.agent import open_decider
|
||||
from app.config import get_settings
|
||||
from app.providers import load_provider
|
||||
from app.tools.assessment import checklist_question
|
||||
from eval.judge import DeciderJudge, GeminiJudge, Judge, JudgeUnavailable
|
||||
from eval.scoring import QUALITY_RUBRIC, checklist_items
|
||||
|
||||
@@ -55,9 +56,7 @@ def build(seed: int = 7) -> list[dict[str, Any]]:
|
||||
"id": f"{document.stem}.{pillar}.{len(items)}",
|
||||
"document": document.name,
|
||||
"kind": "yes_no",
|
||||
"text": f"Do the recommendations address this {pillar} "
|
||||
"checklist item, either by recommending it or by "
|
||||
f"explaining why it does not apply? {item}",
|
||||
"text": checklist_question(pillar, item),
|
||||
"label": None,
|
||||
}
|
||||
)
|
||||
|
||||
@@ -9,6 +9,8 @@
|
||||
prove compare an evaluation run without lessons with one run with them,
|
||||
and write the comparison into every published proposal.
|
||||
retire remove a lesson from the Skill, by id.
|
||||
reviewed record that the lessons were read against the vendored Skills as
|
||||
they are now. `status` says when those have changed since.
|
||||
|
||||
Usage:
|
||||
.venv/bin/python -m eval.curate_lessons propose [--from <folder> ...] [--min 2]
|
||||
@@ -16,6 +18,7 @@ Usage:
|
||||
.venv/bin/python -m eval.curate_lessons publish
|
||||
.venv/bin/python -m eval.curate_lessons prove --without <report.json> --with <report.json>
|
||||
.venv/bin/python -m eval.curate_lessons retire L-03
|
||||
.venv/bin/python -m eval.curate_lessons reviewed
|
||||
|
||||
A person approves a proposal by editing its file: set `Status: ready-for-agent`, or
|
||||
`wontfix` to reject it. Nothing is published without that. After publishing, prove
|
||||
@@ -32,6 +35,8 @@ from __future__ import annotations
|
||||
import asyncio
|
||||
import sys
|
||||
from collections.abc import Sequence
|
||||
from dataclasses import replace
|
||||
from datetime import UTC, datetime
|
||||
from pathlib import Path
|
||||
|
||||
from app.agent import open_decider
|
||||
@@ -39,9 +44,18 @@ from app.config import get_settings
|
||||
from app.learning.curator import LESSON_CURATOR, curate
|
||||
from app.learning.evidence import group_candidates, identifiers, read_candidates
|
||||
from app.learning.proof import compare, record, render
|
||||
from app.learning.proposals import ISSUES, load
|
||||
from app.learning.skill import NotApproved, publish, published, retire
|
||||
from app.learning.proposals import ISSUES, load, write
|
||||
from app.learning.skill import (
|
||||
NotApproved,
|
||||
mark_reviewed,
|
||||
publish,
|
||||
published,
|
||||
retire,
|
||||
upstream_changes,
|
||||
upstream_reviewed,
|
||||
)
|
||||
from app.providers import ProviderBundle, load_provider
|
||||
from app.skills.agent_skills import skill_version
|
||||
|
||||
ROOT = Path(__file__).resolve().parent.parent
|
||||
# Where Executions write their candidates: under each evaluation run, and under the
|
||||
@@ -55,6 +69,16 @@ def _skill_dir(bundle: ProviderBundle) -> Path:
|
||||
return bundle.skills[bundle.lessons_skill].path
|
||||
|
||||
|
||||
def upstream_versions(bundle: ProviderBundle) -> dict[str, str]:
|
||||
"""The vendored Skills, each with the version it has now. They are what the
|
||||
lessons correct the use of, and they change when upstream is synced."""
|
||||
return {
|
||||
name: skill_version(meta.path)
|
||||
for name, meta in bundle.skills.items()
|
||||
if "vendor" in meta.path.parts
|
||||
}
|
||||
|
||||
|
||||
def _options(arguments: Sequence[str], name: str) -> list[str]:
|
||||
return [
|
||||
arguments[index + 1]
|
||||
@@ -115,12 +139,34 @@ def show_status() -> int:
|
||||
if not proposals:
|
||||
print("No lesson has been proposed.")
|
||||
for proposal in proposals:
|
||||
where = "in the Skill" if proposal.id in live else "not in the Skill"
|
||||
proof = "proved" if proposal.proof else "not proved"
|
||||
where = (
|
||||
"in the Skill"
|
||||
if proposal.id in live
|
||||
else "retired"
|
||||
if proposal.retired
|
||||
else "not in the Skill"
|
||||
)
|
||||
# One comparison suggests a direction; it does not prove a lesson.
|
||||
proof = "compared" if proposal.proof else "not compared"
|
||||
print(
|
||||
f"{proposal.id} {proposal.status:16s} {where:16s} {proof:11s} "
|
||||
f"{proposal.id} {proposal.status:16s} {where:16s} {proof:12s} "
|
||||
f"[{proposal.deliverable}] {proposal.title}"
|
||||
)
|
||||
changed = upstream_changes(_skill_dir(bundle), upstream_versions(bundle))
|
||||
if changed:
|
||||
print(
|
||||
f"\nVendored Skills changed since the lessons were last reviewed: "
|
||||
f"{', '.join(changed)}.\nRead each lesson in the Skill against them: "
|
||||
"retire one the Skill now says itself or contradicts. Then run "
|
||||
"`reviewed`."
|
||||
)
|
||||
return 0
|
||||
|
||||
|
||||
def mark_lessons_reviewed() -> int:
|
||||
bundle = load_provider(get_settings().CLOUD_PROVIDER)
|
||||
mark_reviewed(_skill_dir(bundle), upstream_versions(bundle))
|
||||
print("Recorded: the lessons stand against the vendored Skills as they are now.")
|
||||
return 0
|
||||
|
||||
|
||||
@@ -135,6 +181,10 @@ def publish_approved() -> int:
|
||||
continue
|
||||
done += 1
|
||||
print(f" published {proposal.id} [{proposal.deliverable}] {proposal.title}")
|
||||
if done and not upstream_reviewed(skill_dir):
|
||||
# The first lessons: what they were written beside is recorded once. After
|
||||
# that only a person's review moves it on.
|
||||
mark_reviewed(skill_dir, upstream_versions(bundle))
|
||||
print(f"{done} lessons are in {skill_dir.name}.")
|
||||
return 0
|
||||
|
||||
@@ -150,7 +200,8 @@ def prove_lessons(arguments: Sequence[str]) -> int:
|
||||
first, second = Path(without[0]), Path(with_lessons[0])
|
||||
result = compare(first, second)
|
||||
proof = render(result, first, second)
|
||||
recorded = record(load(ROOT / ISSUES), proof)
|
||||
bundle = load_provider(get_settings().CLOUD_PROVIDER)
|
||||
recorded = record(load(ROOT / ISSUES), proof, published(_skill_dir(bundle)))
|
||||
print(proof)
|
||||
print(f"\nRecorded in {len(recorded)} published proposals.")
|
||||
return 0 if result["helps"] else 1
|
||||
@@ -162,6 +213,10 @@ def retire_lesson(arguments: Sequence[str]) -> int:
|
||||
return 2
|
||||
bundle = load_provider(get_settings().CLOUD_PROVIDER)
|
||||
gone = retire(arguments[0], _skill_dir(bundle))
|
||||
for proposal in load(ROOT / ISSUES):
|
||||
if proposal.id == arguments[0] and not proposal.retired:
|
||||
# Marked on its proposal, so the next publish does not bring it back.
|
||||
write(replace(proposal, retired=datetime.now(UTC).date().isoformat()))
|
||||
print(f"Retired {arguments[0]}." if gone else f"{arguments[0]} is not published.")
|
||||
return 0 if gone else 1
|
||||
|
||||
@@ -178,6 +233,8 @@ def main(arguments: Sequence[str]) -> int:
|
||||
return prove_lessons(rest)
|
||||
if command == "retire":
|
||||
return retire_lesson(rest)
|
||||
if command == "reviewed":
|
||||
return mark_lessons_reviewed()
|
||||
print(__doc__, file=sys.stderr)
|
||||
return 2
|
||||
|
||||
|
||||
@@ -448,8 +448,12 @@
|
||||
"forbid": "\"(?!europe-west[14]\")(?:us|europe|asia|australia|northamerica|southamerica|me|africa)-[a-z]+[0-9]+\""
|
||||
},
|
||||
{
|
||||
"name": "names carry the environment from a variable",
|
||||
"require": "name\\s*=\\s*\"[^\"]*\\$\\{(?:var|local)\\.[a-z_]*env[a-z_]*\\}"
|
||||
"name": "names are built from variables",
|
||||
"require": "name\\s*=\\s*\"\\$\\{(?:var|local)\\.[a-z_]+\\}-"
|
||||
},
|
||||
{
|
||||
"name": "the environment comes from a variable",
|
||||
"require": "var\\.environment\\b"
|
||||
},
|
||||
{
|
||||
"name": "label workload",
|
||||
@@ -468,5 +472,78 @@
|
||||
"require": "\"?cost[-_]centre\"?\\s*="
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "case-07-approved-modules",
|
||||
"name": "Internal booking web application, with published Terraform modules opted into",
|
||||
"workflow_request": "Design an internal web application on Google Cloud for staff to book meeting rooms and equipment, backed by a managed relational database, available only to employees signed in with the corporate identity provider, with application secrets kept out of code and configuration.",
|
||||
"required_products": [
|
||||
"Cloud Run",
|
||||
"Cloud SQL",
|
||||
"Secret Manager"
|
||||
],
|
||||
"scripted_answers": [
|
||||
[
|
||||
"region|location|geograph",
|
||||
"A single region, europe-west1 (Belgium). All users are in the EU."
|
||||
],
|
||||
[
|
||||
"user|staff|employee|how many|concurren|traffic|volume|scale|peak|requests per|rps",
|
||||
"About 4,000 employees; 300 concurrent users at the 09:00 peak, around 20 requests per second."
|
||||
],
|
||||
[
|
||||
"availability|uptime|sla|rto|rpo|disaster|recover|backup",
|
||||
"99.5% during business hours (07:00-19:00 CET). RTO 4 hours, RPO 1 hour. Daily backups kept 14 days."
|
||||
],
|
||||
[
|
||||
"latency|response time|performance",
|
||||
"Pages should load within 1 second at p95."
|
||||
],
|
||||
[
|
||||
"identity|sign.?in|login|sso|auth|idp|access",
|
||||
"Employees sign in with Google Workspace accounts; no access from outside the company. Admins are a Google group."
|
||||
],
|
||||
[
|
||||
"security|compliance|encrypt|privacy|gdpr|secret|credential|password",
|
||||
"GDPR applies to employee names and emails. Google-managed keys are fine. Database passwords and API keys must live in a secrets store and rotate every 90 days."
|
||||
],
|
||||
[
|
||||
"data|database|schema|relational|postgres|mysql|size|storage",
|
||||
"PostgreSQL. Under 20 GB of data in the first three years; bookings, rooms, equipment and audit history."
|
||||
],
|
||||
[
|
||||
"cost|budget|spend",
|
||||
"Under 600 EUR a month; the database can be small."
|
||||
],
|
||||
[
|
||||
"current|existing|today|on-prem|migrat|legacy",
|
||||
"Bookings are kept in a shared spreadsheet today; there is no data to migrate."
|
||||
],
|
||||
[
|
||||
"depend|integrat|calendar|email|notif|downstream|upstream",
|
||||
"Send booking confirmation emails through the existing SMTP relay; no calendar integration in phase one."
|
||||
],
|
||||
[
|
||||
"operat|monitor|logging|alert|team|support|deploy|ci|pipeline",
|
||||
"Two developers own it, deploy containers from Cloud Build with Terraform, and want Cloud Monitoring alerts to a Google Chat space."
|
||||
],
|
||||
[
|
||||
"network|vpc|private|internet|egress|ingress",
|
||||
"No public database endpoint; the database must use private IP only."
|
||||
],
|
||||
[
|
||||
"sustainab|carbon",
|
||||
"No specific requirement."
|
||||
],
|
||||
[
|
||||
"retention|audit|archive|delete",
|
||||
"Keep booking history 2 years, then delete; keep audit logs 1 year."
|
||||
],
|
||||
[
|
||||
"approve|confirm|proceed|look right|any changes|happy",
|
||||
"Approved. Please proceed."
|
||||
]
|
||||
],
|
||||
"terraform_modules": true
|
||||
}
|
||||
]
|
||||
|
||||
@@ -20,7 +20,7 @@ from typing import Any
|
||||
|
||||
from app.adk.runtime import ToolResult
|
||||
from app.agent import Interaction
|
||||
from app.tools.assessment import QUALITY_BAR, QUALITY_RUBRIC
|
||||
from app.tools.assessment import QUALITY_BAR, QUALITY_RUBRIC, checklist_question
|
||||
from app.tools.local import mermaid_check
|
||||
from app.workflows.chain import (
|
||||
COMPONENTS_FILE,
|
||||
@@ -71,6 +71,8 @@ class CaseSpec:
|
||||
change: str = ""
|
||||
# Overlay Skills the case's Executions name (ADR-0004).
|
||||
overlay_skills: tuple[str, ...] = ()
|
||||
# Whether the case's Executions opt into published Terraform modules.
|
||||
terraform_modules: bool = False
|
||||
# What the infrastructure code must and must not contain, as regular
|
||||
# expressions over all of it: how a case checks that standards from an overlay
|
||||
# Skill reached the code. Each is {"name", "require"} or {"name", "forbid"}.
|
||||
@@ -118,6 +120,7 @@ def load_cases(path: Path) -> list[CaseSpec]:
|
||||
thresholds=dict(item.get("thresholds", {})),
|
||||
change=str(item.get("change", "")),
|
||||
overlay_skills=tuple(item.get("overlay_skills", ())),
|
||||
terraform_modules=bool(item.get("terraform_modules", False)),
|
||||
code_standards=tuple(item.get("code_standards", ())),
|
||||
)
|
||||
for item in json.loads(path.read_text(encoding="utf-8"))
|
||||
@@ -414,8 +417,7 @@ async def _checklist_coverage(
|
||||
questions = {
|
||||
f"{pillar}.{index}": {
|
||||
"kind": "yes_no",
|
||||
"text": f"Do the recommendations address this {pillar} checklist item, "
|
||||
f"either by recommending it or by explaining why it does not apply? {item}",
|
||||
"text": checklist_question(pillar, item),
|
||||
}
|
||||
for pillar, items in checklists.items()
|
||||
for index, item in enumerate(items)
|
||||
|
||||
@@ -132,6 +132,7 @@ async def run_with_scripted_user(
|
||||
allow_cloud_read=False,
|
||||
execution_id=execution_id,
|
||||
overlay_skills=case.overlay_skills,
|
||||
terraform_modules=case.terraform_modules,
|
||||
)
|
||||
for _ in range(max_user_turns):
|
||||
if interaction.status != "awaiting_user" or interaction.prompt is None:
|
||||
@@ -194,6 +195,7 @@ async def run_case(
|
||||
execution_id=f"{execution_id}-base",
|
||||
scripted_answers=case.scripted_answers,
|
||||
overlay_skills=case.overlay_skills,
|
||||
terraform_modules=case.terraform_modules,
|
||||
)
|
||||
baseline_tokens = token_report(adk_runtime.usage)["total"].get("total")
|
||||
baseline_seconds = round(time.monotonic() - started, 1)
|
||||
@@ -208,6 +210,7 @@ async def run_case(
|
||||
execution_id=execution_id,
|
||||
scripted_answers=case.scripted_answers,
|
||||
overlay_skills=case.overlay_skills,
|
||||
terraform_modules=case.terraform_modules,
|
||||
baseline=base.execution_id,
|
||||
)
|
||||
elif case.interactive:
|
||||
@@ -223,6 +226,7 @@ async def run_case(
|
||||
execution_id=execution_id,
|
||||
scripted_answers=case.scripted_answers,
|
||||
overlay_skills=case.overlay_skills,
|
||||
terraform_modules=case.terraform_modules,
|
||||
)
|
||||
elapsed = time.monotonic() - started
|
||||
write_progress()
|
||||
@@ -237,6 +241,9 @@ async def run_case(
|
||||
binary=settings.TERRAFORM_BINARY,
|
||||
timeout_seconds=settings.TERRAFORM_TIMEOUT_SECONDS,
|
||||
plugin_cache_dir=settings.terraform_plugin_cache(),
|
||||
module_namespaces=bundle.terraform_module_namespaces
|
||||
if case.terraform_modules
|
||||
else (),
|
||||
)
|
||||
result = await score_execution(
|
||||
case,
|
||||
|
||||
@@ -22,6 +22,8 @@ models:
|
||||
iac-author: gemini/gemini-3.1-pro-preview
|
||||
validator: gemini/gemini-3.1-pro-preview
|
||||
lesson-curator: gemini/gemini-3.1-pro-preview
|
||||
# The same reading the validator makes of a design's coverage, made earlier.
|
||||
coverage-reviewer: gemini/gemini-3.1-pro-preview
|
||||
# A lighter model for a role's first attempt, used when MODEL_TIERS is on. Only a
|
||||
# role whose work is checked by something else belongs here: the code is checked
|
||||
# by terraform validate and by the validator. The validator is the check, and a
|
||||
@@ -36,6 +38,7 @@ models:
|
||||
iac-author: 300
|
||||
validator: 300 # timed out five times at 180 s in a run of 2026-10-07
|
||||
packager: 300
|
||||
coverage-reviewer: 300
|
||||
|
||||
# Skills each role may load. Role files stay provider-neutral; the bundle names Skills.
|
||||
role_skills:
|
||||
@@ -64,7 +67,7 @@ pillar_skills:
|
||||
sustainability: google-cloud-waf-sustainability
|
||||
|
||||
tools:
|
||||
general: [mermaid_check, terraform_fmt, terraform_validate, terraform_schema]
|
||||
general: [mermaid_check, terraform_fmt, terraform_validate, terraform_schema, terraform_module]
|
||||
cloud_read: [terraform_plan]
|
||||
|
||||
# The Terraform providers generated code is written for. One exact version, so the
|
||||
@@ -75,6 +78,26 @@ terraform:
|
||||
google:
|
||||
source: hashicorp/google
|
||||
version: 8.6.0
|
||||
# Published modules. Generated code is plain resources unless an Execution opts
|
||||
# into modules; then a `module` may come only from these registry namespaces, at
|
||||
# one exact version. `terraform init` downloads and evaluates whatever a source
|
||||
# names, so anything else is refused before Terraform runs. `skill` holds the
|
||||
# modules known to work with the provider pinned above, and is given, with the
|
||||
# terraform_module tool, only to an Execution that opted in.
|
||||
modules:
|
||||
namespaces: [terraform-google-modules]
|
||||
skill: google-cloud-iac-modules
|
||||
# Not usable on 2026-10-09: each required a google provider below 8. Run
|
||||
# scripts/check-terraform-modules.py to see whether that has changed.
|
||||
watch:
|
||||
- terraform-google-modules/lb-http/google
|
||||
- terraform-google-modules/pubsub/google
|
||||
- terraform-google-modules/bigquery/google
|
||||
- terraform-google-modules/kubernetes-engine/google
|
||||
- terraform-google-modules/log-export/google
|
||||
- terraform-google-modules/event-function/google
|
||||
- terraform-google-modules/scheduled-function/google
|
||||
- terraform-google-modules/bastion-host/google
|
||||
|
||||
mcp_auth:
|
||||
kind: google_adc # Application Default Credentials bearer token; sends X-Goog-User-Project
|
||||
|
||||
96
scripts/check-terraform-modules.py
Normal file
96
scripts/check-terraform-modules.py
Normal file
@@ -0,0 +1,96 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Review the published Terraform modules a provider bundle's modules Skill uses.
|
||||
|
||||
For each module the Skill's examples call: the version pinned there, the latest in
|
||||
the registry, and whether the latest still works with the pinned provider. For each
|
||||
module the bundle lists under `terraform.modules.watch`, which could not be used
|
||||
when last looked at: whether its latest version now can.
|
||||
|
||||
It reads the public registry and changes nothing. Raising a pinned version is a
|
||||
change to the Skill's example, which `tests/test_iac_modules.py` then validates.
|
||||
|
||||
Usage: .venv/bin/python scripts/check-terraform-modules.py [provider]
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import re
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
||||
|
||||
from app.adk.runtime import ToolResult
|
||||
from app.providers import load_provider
|
||||
from app.tools.modules import ModuleLookup, admits, module_calls
|
||||
|
||||
_HCL = re.compile(r"^```hcl\n(.*?)^```", re.MULTILINE | re.DOTALL)
|
||||
|
||||
|
||||
def _blocked(part: dict, pinned: dict[str, str]) -> list[str]:
|
||||
"""The provider requirements of a module that the pinned versions do not meet."""
|
||||
return [
|
||||
f"{need.get('name')} {need.get('version')}"
|
||||
for need in part.get("provider_dependencies") or []
|
||||
if need.get("name") in pinned
|
||||
and need.get("version")
|
||||
and not admits(need["version"], pinned[need["name"]])
|
||||
]
|
||||
|
||||
|
||||
async def main(provider: str) -> int:
|
||||
bundle = load_provider(provider)
|
||||
if not bundle.terraform_modules_skill:
|
||||
print(f"The {provider} bundle names no modules Skill.")
|
||||
return 0
|
||||
pinned = {name: pin["version"] for name, pin in bundle.terraform_providers.items()}
|
||||
lookup = ModuleLookup(namespaces=bundle.terraform_module_namespaces, pinned=pinned)
|
||||
skill = bundle.skills[bundle.terraform_modules_skill].path
|
||||
|
||||
used: dict[str, set[str]] = {}
|
||||
for reference in sorted((skill / "references").glob("*.md")):
|
||||
code = "\n".join(_HCL.findall(reference.read_text(encoding="utf-8")))
|
||||
for call in module_calls({"main.tf": code}):
|
||||
used.setdefault(call.source.split("//")[0], set()).add(call.version)
|
||||
|
||||
stale = 0
|
||||
print(f"Pinned providers: {pinned}\n\nModules the Skill uses:")
|
||||
for module, versions in sorted(used.items()):
|
||||
data = await lookup._fetch(module, "")
|
||||
if isinstance(data, ToolResult):
|
||||
print(f" {module}: {data.message}")
|
||||
continue
|
||||
latest = str(data.get("version", "?"))
|
||||
blocked = _blocked(data.get("root") or {}, pinned)
|
||||
note = "up to date" if versions == {latest} else f"latest is {latest}"
|
||||
if versions != {latest}:
|
||||
stale += 1
|
||||
if blocked:
|
||||
note += f"; the latest needs {', '.join(blocked)}, so stay on the pin"
|
||||
print(f" {module} {', '.join(sorted(versions))}: {note}")
|
||||
|
||||
print("\nModules that could not be used when last looked at:")
|
||||
usable = 0
|
||||
for name in bundle.terraform_modules_watch:
|
||||
data = await lookup._fetch(name, "")
|
||||
if isinstance(data, ToolResult):
|
||||
print(f" {name}: {data.message}")
|
||||
continue
|
||||
blocked = _blocked(data.get("root") or {}, pinned)
|
||||
if blocked:
|
||||
print(f" {name} {data.get('version')}: still needs {', '.join(blocked)}")
|
||||
else:
|
||||
usable += 1
|
||||
print(
|
||||
f" {name} {data.get('version')}: NOW USABLE with the pinned provider"
|
||||
)
|
||||
print(
|
||||
f"\n{stale} pinned module(s) have a newer version; {usable} watched "
|
||||
"module(s) can now be used."
|
||||
)
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(asyncio.run(main(sys.argv[1] if len(sys.argv) > 1 else "gcp")))
|
||||
56
skills/google-cloud-iac-modules/SKILL.md
Normal file
56
skills/google-cloud-iac-modules/SKILL.md
Normal file
@@ -0,0 +1,56 @@
|
||||
---
|
||||
name: google-cloud-iac-modules
|
||||
description: >-
|
||||
Published Terraform modules from the terraform-google-modules organisation
|
||||
that are known to validate against the pinned hashicorp/google provider: VPC
|
||||
network with Cloud NAT, private Cloud SQL for PostgreSQL, Cloud Storage
|
||||
buckets and Cloud KMS. Use when writing Terraform for an Element that one of
|
||||
these modules covers, to decide whether a module or plain resources fit and to
|
||||
call the module correctly.
|
||||
metadata:
|
||||
scope: deployment guidance, validation results
|
||||
provider: hashicorp/google 8.6.0
|
||||
modules: terraform-google-modules
|
||||
---
|
||||
|
||||
# Google Cloud IaC modules
|
||||
|
||||
You have this Skill because this Execution opted into published modules: `terraform_modules` is true in your context. Without that, infrastructure code is plain resources and a module call is refused.
|
||||
|
||||
A published module replaces several resources that must be wired together with one call that a team already maintains. It also hides the resources a Check is about. Use one only where the first outweighs the second.
|
||||
|
||||
## When to use a module
|
||||
|
||||
Use a module when **all** of these hold:
|
||||
|
||||
1. It is in the table below. Those are the only modules checked against `hashicorp/google` 8.6.0; a test validates each one's example here.
|
||||
2. It replaces three or more resources that depend on each other, such as a network with its subnets and firewall rules, or a private database with the peering it needs.
|
||||
3. Every Check on the Elements it covers can be met through one of its inputs. Confirm with `terraform_module`.
|
||||
|
||||
Otherwise write the resources directly, from the patterns Skill. A single resource, such as one service account, one topic or one secret, is always written directly.
|
||||
|
||||
| For | Module | Version | Reference |
|
||||
| --- | --- | --- | --- |
|
||||
| VPC, subnets, firewall rules, and Cloud NAT | `terraform-google-modules/network/google` and `terraform-google-modules/cloud-nat/google` | 18.3.1, 7.1.0 | `references/network.md` |
|
||||
| Cloud SQL for PostgreSQL on a private address | `terraform-google-modules/sql-db/google//modules/postgresql` with `//modules/private_service_access` | 28.3.0 | `references/cloud-sql.md` |
|
||||
| A Cloud Storage bucket with retention, lifecycle, encryption and grants | `terraform-google-modules/cloud-storage/google//modules/simple_bucket` | 12.4.1 | `references/cloud-storage.md` |
|
||||
| A key ring, keys and their grants | `terraform-google-modules/kms/google` | 4.2.1 | `references/kms.md` |
|
||||
|
||||
Not usable with this provider version, so write these directly: the load balancer (`lb-http`), Pub/Sub, BigQuery, GKE, log export and the function modules all require `google` below 8. `terraform_module` says so for any module you look up.
|
||||
|
||||
## Rules for every module call
|
||||
|
||||
- `source` is `terraform-google-modules/<name>/google`, with `//modules/<submodule>` when the table gives one. `version` is one exact version. `terraform_validate` refuses any other source, a Git URL, a local path or a version range.
|
||||
- Keep `terraform/versions.tf` from the patterns Skill unchanged. A module's own provider requirements are met by it.
|
||||
- Pass every environment-specific value from a variable, as for resources.
|
||||
- Before using an input the reference does not show, call `terraform_module` with `find` set to its name.
|
||||
- Set every input a Check depends on, even when the module's default already gives that value. A Check is verified from a value written in the code; a default left unset can only be argued from the module's documentation, and changes when the module does.
|
||||
- A module takes names, not always ids: read which one an input wants. Pass another module's output where one depends on the other, so Terraform orders them.
|
||||
|
||||
## Checks on an Element a module creates
|
||||
|
||||
A Check is still about the resource: "the instance has no public IP address". The code meets it through a module input.
|
||||
|
||||
- In `implementation.json`, `address` names the module and the input: `module.database.ip_configuration.ipv4_enabled`.
|
||||
- When no input sets what a Check needs, the module does not fit that Element. Write its resources directly; do not mark the Check unimplementable, since the resource type does have the setting.
|
||||
- When validating, read the input's value in the code and confirm with `terraform_module` what that input sets. An input left at its default is judged by the default the lookup shows, and the verdict says the value is a default and not set in the code. A Check is not verifiable only when neither the code nor the module's documentation shows what the resource will get.
|
||||
102
skills/google-cloud-iac-modules/references/cloud-sql.md
Normal file
102
skills/google-cloud-iac-modules/references/cloud-sql.md
Normal file
@@ -0,0 +1,102 @@
|
||||
# Cloud SQL for PostgreSQL on a private address
|
||||
|
||||
A PostgreSQL instance reachable only inside a VPC, with the private services access it needs. Replaces a reserved range, a service networking connection, the instance, its database and its user.
|
||||
|
||||
- The instance must wait for the peering: pass `module.private_access.peering_completed` in `module_depends_on`.
|
||||
- `ip_configuration.ipv4_enabled = false` is what removes the public address. `private_network` is the network's self link.
|
||||
- `availability_type = "REGIONAL"` gives a standby in a second zone.
|
||||
- `deletion_protection` is the Terraform guard; `deletion_protection_enabled` is the guard in the API. Set both from a variable.
|
||||
- With `enable_default_user = true` the module generates a password and exposes it as an output. Prefer IAM database authentication: set `enable_default_user = false`, add the `cloudsql.iam_authentication` flag and list `iam_users`.
|
||||
- `random_instance_name = true` adds a suffix, which lets an instance be recreated: a deleted instance's name is reserved for a week.
|
||||
|
||||
```hcl
|
||||
variable "project_id" {
|
||||
type = string
|
||||
description = "Project to deploy into."
|
||||
}
|
||||
|
||||
variable "region" {
|
||||
type = string
|
||||
description = "Region for regional resources."
|
||||
}
|
||||
|
||||
variable "network_name" {
|
||||
type = string
|
||||
description = "Name of the VPC the database is reached from."
|
||||
}
|
||||
|
||||
variable "network_self_link" {
|
||||
type = string
|
||||
description = "Self link of that VPC."
|
||||
}
|
||||
|
||||
variable "app_service_account_email" {
|
||||
type = string
|
||||
description = "Service account that connects to the database."
|
||||
}
|
||||
|
||||
variable "deletion_protection" {
|
||||
type = bool
|
||||
description = "Whether the instance is protected from deletion."
|
||||
default = true
|
||||
}
|
||||
|
||||
module "private_access" {
|
||||
source = "terraform-google-modules/sql-db/google//modules/private_service_access"
|
||||
version = "28.3.0"
|
||||
|
||||
project_id = var.project_id
|
||||
vpc_network = var.network_name
|
||||
prefix_length = 20
|
||||
}
|
||||
|
||||
module "database" {
|
||||
source = "terraform-google-modules/sql-db/google//modules/postgresql"
|
||||
version = "28.3.0"
|
||||
|
||||
project_id = var.project_id
|
||||
region = var.region
|
||||
name = "workload"
|
||||
random_instance_name = true
|
||||
database_version = "POSTGRES_16"
|
||||
edition = "ENTERPRISE"
|
||||
tier = "db-custom-2-7680"
|
||||
availability_type = "REGIONAL"
|
||||
disk_autoresize = true
|
||||
|
||||
deletion_protection = var.deletion_protection
|
||||
deletion_protection_enabled = var.deletion_protection
|
||||
|
||||
ip_configuration = {
|
||||
ipv4_enabled = false
|
||||
private_network = var.network_self_link
|
||||
ssl_mode = "ENCRYPTED_ONLY"
|
||||
}
|
||||
|
||||
backup_configuration = {
|
||||
enabled = true
|
||||
start_time = "02:00"
|
||||
point_in_time_recovery_enabled = true
|
||||
retained_backups = 14
|
||||
retention_unit = "COUNT"
|
||||
}
|
||||
|
||||
database_flags = [
|
||||
{
|
||||
name = "cloudsql.iam_authentication"
|
||||
value = "on"
|
||||
}
|
||||
]
|
||||
|
||||
db_name = "app"
|
||||
enable_default_user = false
|
||||
iam_users = [
|
||||
{
|
||||
id = "app"
|
||||
email = var.app_service_account_email
|
||||
}
|
||||
]
|
||||
|
||||
module_depends_on = [module.private_access.peering_completed]
|
||||
}
|
||||
```
|
||||
68
skills/google-cloud-iac-modules/references/cloud-storage.md
Normal file
68
skills/google-cloud-iac-modules/references/cloud-storage.md
Normal file
@@ -0,0 +1,68 @@
|
||||
# Cloud Storage bucket
|
||||
|
||||
One bucket with its retention, lifecycle rules, encryption and grants. Use the module when the bucket has several of those; a plain bucket is one resource and is written directly.
|
||||
|
||||
- The module turns on uniform bucket-level access (`bucket_policy_only`) and `public_access_prevention = "enforced"` unless told otherwise.
|
||||
- `retention_policy.retention_period` is in seconds. `is_locked = true` cannot be undone, and the bucket cannot then be deleted until every object has aged out: take it from a variable.
|
||||
- `lifecycle_rules` takes `action` and `condition` as maps; condition values that are lists are given as comma-separated strings.
|
||||
- `encryption.default_kms_key_name` needs the Cloud Storage service agent to hold the encrypter/decrypter role on the key first.
|
||||
- `iam_members` grants on the bucket only, with `_iam_member`, so grants made elsewhere are kept.
|
||||
|
||||
```hcl
|
||||
variable "project_id" {
|
||||
type = string
|
||||
description = "Project to deploy into."
|
||||
}
|
||||
|
||||
variable "region" {
|
||||
type = string
|
||||
description = "Region for regional resources."
|
||||
}
|
||||
|
||||
variable "lock_retention" {
|
||||
type = bool
|
||||
description = "Whether the retention policy is locked. Locking cannot be undone."
|
||||
default = false
|
||||
}
|
||||
|
||||
variable "reader_service_account_email" {
|
||||
type = string
|
||||
description = "Service account that reads the archive."
|
||||
}
|
||||
|
||||
module "archive" {
|
||||
source = "terraform-google-modules/cloud-storage/google//modules/simple_bucket"
|
||||
version = "12.4.1"
|
||||
|
||||
project_id = var.project_id
|
||||
name = "${var.project_id}-archive"
|
||||
location = var.region
|
||||
storage_class = "STANDARD"
|
||||
versioning = true
|
||||
force_destroy = false
|
||||
|
||||
retention_policy = {
|
||||
is_locked = var.lock_retention
|
||||
retention_period = 220752000
|
||||
}
|
||||
|
||||
lifecycle_rules = [
|
||||
{
|
||||
action = {
|
||||
type = "SetStorageClass"
|
||||
storage_class = "ARCHIVE"
|
||||
}
|
||||
condition = {
|
||||
age = 365
|
||||
}
|
||||
}
|
||||
]
|
||||
|
||||
iam_members = [
|
||||
{
|
||||
role = "roles/storage.objectViewer"
|
||||
member = "serviceAccount:${var.reader_service_account_email}"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
54
skills/google-cloud-iac-modules/references/kms.md
Normal file
54
skills/google-cloud-iac-modules/references/kms.md
Normal file
@@ -0,0 +1,54 @@
|
||||
# Cloud KMS key ring and keys
|
||||
|
||||
A key ring, its keys and the grants that let products use them. Replaces a key ring, each key and each grant.
|
||||
|
||||
- The key ring's `location` must match the resource it protects.
|
||||
- `prevent_destroy` is true unless set otherwise; keys and key rings cannot be deleted from Google Cloud in any case.
|
||||
- `key_rotation_period` is in seconds with an `s`, such as `"7776000s"` for 90 days.
|
||||
- `set_encrypters_for` and `set_decrypters_for` name the keys; `encrypters` and `decrypters` give one comma-separated string of members per key, in the same order.
|
||||
- The member is the product's service agent, not the workload's service account.
|
||||
- `module.kms.keys` is a map from key name to key id.
|
||||
|
||||
```hcl
|
||||
variable "project_id" {
|
||||
type = string
|
||||
description = "Project to deploy into."
|
||||
}
|
||||
|
||||
variable "region" {
|
||||
type = string
|
||||
description = "Region for regional resources."
|
||||
}
|
||||
|
||||
data "google_storage_project_service_account" "this" {
|
||||
project = var.project_id
|
||||
}
|
||||
|
||||
module "kms" {
|
||||
source = "terraform-google-modules/kms/google"
|
||||
version = "4.2.1"
|
||||
|
||||
project_id = var.project_id
|
||||
location = var.region
|
||||
keyring = "workload"
|
||||
keys = ["data"]
|
||||
key_rotation_period = "7776000s"
|
||||
prevent_destroy = true
|
||||
|
||||
set_encrypters_for = ["data"]
|
||||
set_decrypters_for = ["data"]
|
||||
encrypters = ["serviceAccount:${data.google_storage_project_service_account.this.email_address}"]
|
||||
decrypters = ["serviceAccount:${data.google_storage_project_service_account.this.email_address}"]
|
||||
}
|
||||
|
||||
resource "google_storage_bucket" "encrypted" {
|
||||
project = var.project_id
|
||||
name = "${var.project_id}-encrypted"
|
||||
location = var.region
|
||||
uniform_bucket_level_access = true
|
||||
|
||||
encryption {
|
||||
default_kms_key_name = module.kms.keys["data"]
|
||||
}
|
||||
}
|
||||
```
|
||||
68
skills/google-cloud-iac-modules/references/network.md
Normal file
68
skills/google-cloud-iac-modules/references/network.md
Normal file
@@ -0,0 +1,68 @@
|
||||
# VPC network and Cloud NAT
|
||||
|
||||
A custom-mode VPC with its subnets and firewall rules, and outbound internet through Cloud NAT. Replaces a network, its subnetworks, a router, a NAT and each firewall rule.
|
||||
|
||||
- `subnets` is a list of objects whose values are all strings, including `"true"` for `subnet_private_access`.
|
||||
- `network_name` is a name. Other resources want `module.network.network_self_link` or `network_id`; `subnets` is an output map keyed `"<region>/<subnet_name>"`.
|
||||
- `ingress_rules` replaces the deprecated `firewall_rules`.
|
||||
- The NAT module creates its router when `create_router = true`, and then needs `network`.
|
||||
- Set `name` on the NAT. Left unset it gets a random suffix.
|
||||
|
||||
```hcl
|
||||
variable "project_id" {
|
||||
type = string
|
||||
description = "Project to deploy into."
|
||||
}
|
||||
|
||||
variable "region" {
|
||||
type = string
|
||||
description = "Region for regional resources."
|
||||
}
|
||||
|
||||
module "network" {
|
||||
source = "terraform-google-modules/network/google"
|
||||
version = "18.3.1"
|
||||
|
||||
project_id = var.project_id
|
||||
network_name = "workload"
|
||||
routing_mode = "REGIONAL"
|
||||
|
||||
subnets = [
|
||||
{
|
||||
subnet_name = "workload"
|
||||
subnet_ip = "10.10.0.0/24"
|
||||
subnet_region = var.region
|
||||
subnet_private_access = "true"
|
||||
subnet_flow_logs = "true"
|
||||
}
|
||||
]
|
||||
|
||||
ingress_rules = [
|
||||
{
|
||||
name = "allow-health-checks"
|
||||
source_ranges = ["130.211.0.0/22", "35.191.0.0/16"]
|
||||
allow = [
|
||||
{
|
||||
protocol = "tcp"
|
||||
ports = ["8080"]
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
module "nat" {
|
||||
source = "terraform-google-modules/cloud-nat/google"
|
||||
version = "7.1.0"
|
||||
|
||||
project_id = var.project_id
|
||||
region = var.region
|
||||
name = "workload-nat"
|
||||
create_router = true
|
||||
router = "workload-router"
|
||||
network = module.network.network_self_link
|
||||
|
||||
log_config_enable = true
|
||||
log_config_filter = "ERRORS_ONLY"
|
||||
}
|
||||
```
|
||||
@@ -4,10 +4,10 @@ description: >-
|
||||
Terraform patterns for Google Cloud products that validate against one pinned
|
||||
version of the hashicorp/google provider: Cloud Run services and jobs,
|
||||
Pub/Sub, Cloud Storage, IAM, Secret Manager, Cloud KMS, Cloud SQL,
|
||||
networking, load balancing, Cloud Scheduler, Artifact Registry, Monitoring and API
|
||||
enablement. Use when writing Terraform for a Google Cloud product, before
|
||||
writing the resource, to start from a pattern whose arguments are known to be
|
||||
in the right place.
|
||||
networking, load balancing, Cloud Scheduler, Artifact Registry, Monitoring,
|
||||
Firestore, BigQuery, Eventarc, GKE and API enablement. Use when writing
|
||||
Terraform for a Google Cloud product, before writing the resource, to start
|
||||
from a pattern whose arguments are known to be in the right place.
|
||||
metadata:
|
||||
scope: deployment guidance
|
||||
provider: hashicorp/google 8.6.0
|
||||
@@ -39,6 +39,10 @@ Every pattern here passes `terraform validate` against `hashicorp/google` 8.6.0.
|
||||
| Cloud Scheduler | `references/cloud-scheduler.md` |
|
||||
| Artifact Registry | `references/artifact-registry.md` |
|
||||
| Cloud Monitoring and Logging | `references/monitoring.md` |
|
||||
| Firestore | `references/firestore.md` |
|
||||
| BigQuery | `references/bigquery.md` |
|
||||
| Eventarc | `references/eventarc.md` |
|
||||
| Google Kubernetes Engine | `references/gke.md` |
|
||||
|
||||
A product with no reference has no pattern yet: write it from `terraform_schema` and the product documentation.
|
||||
|
||||
|
||||
92
skills/google-cloud-iac-patterns/references/bigquery.md
Normal file
92
skills/google-cloud-iac-patterns/references/bigquery.md
Normal file
@@ -0,0 +1,92 @@
|
||||
# BigQuery
|
||||
|
||||
A dataset, a partitioned and clustered table, and the grants for a writer and a reader.
|
||||
|
||||
- `location` is a region or `EU`/`US`, and cannot be changed. Queries cannot join datasets in different locations.
|
||||
- `delete_contents_on_destroy = false` makes Terraform refuse to remove a dataset that still has tables.
|
||||
- A table's `deletion_protection` is true unless set; take it from a variable so a test deployment can be removed.
|
||||
- `schema` is a JSON string. Changing a column's type or mode replaces the table.
|
||||
- Partition on a `DATE` or `TIMESTAMP` column with `time_partitioning`, and set `require_partition_filter` so a query cannot scan every partition. `expiration_ms` there removes old partitions.
|
||||
- Grant on the dataset with `google_bigquery_dataset_iam_member`. A principal that runs queries also needs `roles/bigquery.jobUser` on the project.
|
||||
- Do not mix `google_bigquery_dataset_iam_member` with `access` blocks on the dataset: each removes what the other sets.
|
||||
|
||||
```hcl
|
||||
variable "project_id" {
|
||||
type = string
|
||||
description = "Project to deploy into."
|
||||
}
|
||||
|
||||
variable "region" {
|
||||
type = string
|
||||
description = "Region for regional resources."
|
||||
}
|
||||
|
||||
variable "writer_service_account_email" {
|
||||
type = string
|
||||
description = "Service account that loads rows."
|
||||
}
|
||||
|
||||
variable "reader_service_account_email" {
|
||||
type = string
|
||||
description = "Service account that queries the dataset."
|
||||
}
|
||||
|
||||
variable "deletion_protection" {
|
||||
type = bool
|
||||
description = "Whether the table is protected from deletion."
|
||||
default = true
|
||||
}
|
||||
|
||||
resource "google_bigquery_dataset" "analytics" {
|
||||
project = var.project_id
|
||||
dataset_id = "analytics"
|
||||
location = var.region
|
||||
delete_contents_on_destroy = false
|
||||
|
||||
default_table_expiration_ms = null
|
||||
max_time_travel_hours = 168
|
||||
}
|
||||
|
||||
resource "google_bigquery_table" "events" {
|
||||
project = var.project_id
|
||||
dataset_id = google_bigquery_dataset.analytics.dataset_id
|
||||
table_id = "events"
|
||||
deletion_protection = var.deletion_protection
|
||||
|
||||
require_partition_filter = true
|
||||
clustering = ["event_type"]
|
||||
|
||||
time_partitioning {
|
||||
type = "DAY"
|
||||
field = "event_time"
|
||||
expiration_ms = 34560000000
|
||||
}
|
||||
|
||||
schema = jsonencode([
|
||||
{ name = "event_id", type = "STRING", mode = "REQUIRED" },
|
||||
{ name = "event_type", type = "STRING", mode = "REQUIRED" },
|
||||
{ name = "event_time", type = "TIMESTAMP", mode = "REQUIRED" },
|
||||
{ name = "payload", type = "JSON", mode = "NULLABLE" }
|
||||
])
|
||||
}
|
||||
|
||||
resource "google_bigquery_dataset_iam_member" "writer" {
|
||||
project = var.project_id
|
||||
dataset_id = google_bigquery_dataset.analytics.dataset_id
|
||||
role = "roles/bigquery.dataEditor"
|
||||
member = "serviceAccount:${var.writer_service_account_email}"
|
||||
}
|
||||
|
||||
resource "google_bigquery_dataset_iam_member" "reader" {
|
||||
project = var.project_id
|
||||
dataset_id = google_bigquery_dataset.analytics.dataset_id
|
||||
role = "roles/bigquery.dataViewer"
|
||||
member = "serviceAccount:${var.reader_service_account_email}"
|
||||
}
|
||||
|
||||
resource "google_project_iam_member" "reader_runs_queries" {
|
||||
project = var.project_id
|
||||
role = "roles/bigquery.jobUser"
|
||||
member = "serviceAccount:${var.reader_service_account_email}"
|
||||
}
|
||||
```
|
||||
129
skills/google-cloud-iac-patterns/references/eventarc.md
Normal file
129
skills/google-cloud-iac-patterns/references/eventarc.md
Normal file
@@ -0,0 +1,129 @@
|
||||
# Eventarc
|
||||
|
||||
A trigger that delivers events to a Cloud Run service: one for messages on a Pub/Sub topic, one for objects finalised in a bucket.
|
||||
|
||||
- A trigger has its own service account. It needs `roles/eventarc.eventReceiver` on the project and `roles/run.invoker` on the service it calls.
|
||||
- For a Pub/Sub trigger, name an existing topic under `transport.pubsub.topic`; left out, Eventarc creates a topic you do not manage.
|
||||
- For a Cloud Storage trigger, `location` must be the bucket's location, and the Cloud Storage service agent needs `roles/pubsub.publisher` on the project before the trigger is created.
|
||||
- `matching_criteria` attributes are exact. `type` is always present; a storage event also needs `bucket`.
|
||||
- The destination service is named, with its `region`; `path` is optional.
|
||||
- The service must not allow unauthenticated calls for this to be the only way in: grant `roles/run.invoker` to the trigger's service account only.
|
||||
|
||||
```hcl
|
||||
variable "project_id" {
|
||||
type = string
|
||||
description = "Project to deploy into."
|
||||
}
|
||||
|
||||
variable "region" {
|
||||
type = string
|
||||
description = "Region for regional resources."
|
||||
}
|
||||
|
||||
variable "service_name" {
|
||||
type = string
|
||||
description = "Name of the Cloud Run service that receives the events."
|
||||
}
|
||||
|
||||
variable "topic_id" {
|
||||
type = string
|
||||
description = "Id of the Pub/Sub topic whose messages are delivered."
|
||||
}
|
||||
|
||||
variable "bucket_name" {
|
||||
type = string
|
||||
description = "Bucket whose new objects are delivered. It must be in var.region."
|
||||
}
|
||||
|
||||
data "google_storage_project_service_account" "this" {
|
||||
project = var.project_id
|
||||
}
|
||||
|
||||
resource "google_service_account" "trigger" {
|
||||
project = var.project_id
|
||||
account_id = "eventarc-trigger"
|
||||
display_name = "Eventarc trigger"
|
||||
}
|
||||
|
||||
resource "google_project_iam_member" "trigger_receives_events" {
|
||||
project = var.project_id
|
||||
role = "roles/eventarc.eventReceiver"
|
||||
member = "serviceAccount:${google_service_account.trigger.email}"
|
||||
}
|
||||
|
||||
resource "google_cloud_run_v2_service_iam_member" "trigger_invokes_service" {
|
||||
project = var.project_id
|
||||
location = var.region
|
||||
name = var.service_name
|
||||
role = "roles/run.invoker"
|
||||
member = "serviceAccount:${google_service_account.trigger.email}"
|
||||
}
|
||||
|
||||
resource "google_project_iam_member" "storage_publishes_events" {
|
||||
project = var.project_id
|
||||
role = "roles/pubsub.publisher"
|
||||
member = "serviceAccount:${data.google_storage_project_service_account.this.email_address}"
|
||||
}
|
||||
|
||||
resource "google_eventarc_trigger" "on_message" {
|
||||
project = var.project_id
|
||||
name = "on-message"
|
||||
location = var.region
|
||||
service_account = google_service_account.trigger.email
|
||||
|
||||
matching_criteria {
|
||||
attribute = "type"
|
||||
value = "google.cloud.pubsub.topic.v1.messagePublished"
|
||||
}
|
||||
|
||||
transport {
|
||||
pubsub {
|
||||
topic = var.topic_id
|
||||
}
|
||||
}
|
||||
|
||||
destination {
|
||||
cloud_run_service {
|
||||
service = var.service_name
|
||||
region = var.region
|
||||
path = "/events/message"
|
||||
}
|
||||
}
|
||||
|
||||
depends_on = [
|
||||
google_project_iam_member.trigger_receives_events,
|
||||
google_cloud_run_v2_service_iam_member.trigger_invokes_service,
|
||||
]
|
||||
}
|
||||
|
||||
resource "google_eventarc_trigger" "on_object" {
|
||||
project = var.project_id
|
||||
name = "on-object"
|
||||
location = var.region
|
||||
service_account = google_service_account.trigger.email
|
||||
|
||||
matching_criteria {
|
||||
attribute = "type"
|
||||
value = "google.cloud.storage.object.v1.finalized"
|
||||
}
|
||||
|
||||
matching_criteria {
|
||||
attribute = "bucket"
|
||||
value = var.bucket_name
|
||||
}
|
||||
|
||||
destination {
|
||||
cloud_run_service {
|
||||
service = var.service_name
|
||||
region = var.region
|
||||
path = "/events/object"
|
||||
}
|
||||
}
|
||||
|
||||
depends_on = [
|
||||
google_project_iam_member.trigger_receives_events,
|
||||
google_project_iam_member.storage_publishes_events,
|
||||
google_cloud_run_v2_service_iam_member.trigger_invokes_service,
|
||||
]
|
||||
}
|
||||
```
|
||||
74
skills/google-cloud-iac-patterns/references/firestore.md
Normal file
74
skills/google-cloud-iac-patterns/references/firestore.md
Normal file
@@ -0,0 +1,74 @@
|
||||
# Firestore
|
||||
|
||||
A Firestore database in Native mode, with point-in-time recovery, a scheduled backup, a composite index and the grant a workload needs.
|
||||
|
||||
- A project's first database is named `(default)`. Any other name creates an additional database, which clients must name when they connect.
|
||||
- `location_id` is a region or a multi-region such as `eur3`, and cannot be changed afterwards.
|
||||
- `type` is `FIRESTORE_NATIVE` or `DATASTORE_MODE`, and cannot be changed once the database holds data.
|
||||
- `delete_protection_state` is the guard in the API; `deletion_policy = "DELETE"` is needed before Terraform will remove a database at all.
|
||||
- `point_in_time_recovery_enablement` keeps seven days of versions. A backup schedule is separate and keeps whole backups for `retention`, in seconds with an `s`.
|
||||
- A workload reads and writes with `roles/datastore.user`, granted on the project. There is no per-database role; restrict with an IAM condition on the database name.
|
||||
|
||||
```hcl
|
||||
variable "project_id" {
|
||||
type = string
|
||||
description = "Project to deploy into."
|
||||
}
|
||||
|
||||
variable "region" {
|
||||
type = string
|
||||
description = "Region for regional resources."
|
||||
}
|
||||
|
||||
variable "app_service_account_email" {
|
||||
type = string
|
||||
description = "Service account of the workload that uses the database."
|
||||
}
|
||||
|
||||
resource "google_firestore_database" "app" {
|
||||
project = var.project_id
|
||||
name = "app"
|
||||
location_id = var.region
|
||||
type = "FIRESTORE_NATIVE"
|
||||
|
||||
concurrency_mode = "OPTIMISTIC"
|
||||
point_in_time_recovery_enablement = "POINT_IN_TIME_RECOVERY_ENABLED"
|
||||
delete_protection_state = "DELETE_PROTECTION_ENABLED"
|
||||
deletion_policy = "ABANDON"
|
||||
}
|
||||
|
||||
resource "google_firestore_backup_schedule" "daily" {
|
||||
project = var.project_id
|
||||
database = google_firestore_database.app.name
|
||||
retention = "1209600s"
|
||||
|
||||
daily_recurrence {}
|
||||
}
|
||||
|
||||
resource "google_firestore_index" "orders_by_customer" {
|
||||
project = var.project_id
|
||||
database = google_firestore_database.app.name
|
||||
collection = "orders"
|
||||
|
||||
fields {
|
||||
field_path = "customer_id"
|
||||
order = "ASCENDING"
|
||||
}
|
||||
|
||||
fields {
|
||||
field_path = "created_at"
|
||||
order = "DESCENDING"
|
||||
}
|
||||
}
|
||||
|
||||
resource "google_project_iam_member" "app_uses_firestore" {
|
||||
project = var.project_id
|
||||
role = "roles/datastore.user"
|
||||
member = "serviceAccount:${var.app_service_account_email}"
|
||||
|
||||
condition {
|
||||
title = "only-the-app-database"
|
||||
expression = "resource.name == \"${google_firestore_database.app.id}\" || resource.name.startsWith(\"${google_firestore_database.app.id}/\")"
|
||||
}
|
||||
}
|
||||
```
|
||||
109
skills/google-cloud-iac-patterns/references/gke.md
Normal file
109
skills/google-cloud-iac-patterns/references/gke.md
Normal file
@@ -0,0 +1,109 @@
|
||||
# Google Kubernetes Engine
|
||||
|
||||
A private Autopilot cluster on an existing subnet, with its node service account and Workload Identity for one workload.
|
||||
|
||||
- `enable_autopilot = true` makes Google manage the nodes. Node pools, machine types and node counts are then not yours to set: leave out `node_pool`, `node_config` and `initial_node_count`.
|
||||
- A regional `location` gives a control plane in three zones. A zone gives one.
|
||||
- The subnet needs two secondary ranges, for Pods and Services, named in `ip_allocation_policy`.
|
||||
- `enable_private_nodes = true` gives nodes no public address; they then need Cloud NAT to pull images from outside Google.
|
||||
- `master_authorized_networks_config` limits who can reach the control plane. With `enable_private_endpoint = true` it has no public address at all.
|
||||
- Give nodes a dedicated service account with `roles/container.defaultNodeServiceAccount`, not the Compute Engine default account.
|
||||
- Autopilot has Workload Identity on. A Kubernetes service account acts as a Google service account through `roles/iam.workloadIdentityUser`, with the member `serviceAccount:PROJECT.svc.id.goog[NAMESPACE/KSA]`.
|
||||
- `deletion_protection` is true unless set; take it from a variable.
|
||||
|
||||
```hcl
|
||||
variable "project_id" {
|
||||
type = string
|
||||
description = "Project to deploy into."
|
||||
}
|
||||
|
||||
variable "region" {
|
||||
type = string
|
||||
description = "Region for regional resources."
|
||||
}
|
||||
|
||||
variable "network_id" {
|
||||
type = string
|
||||
description = "Id of the VPC the cluster is in."
|
||||
}
|
||||
|
||||
variable "subnetwork_id" {
|
||||
type = string
|
||||
description = "Id of the subnet for nodes. It has secondary ranges named pods and services."
|
||||
}
|
||||
|
||||
variable "admin_cidr" {
|
||||
type = string
|
||||
description = "Range allowed to reach the control plane."
|
||||
}
|
||||
|
||||
variable "deletion_protection" {
|
||||
type = bool
|
||||
description = "Whether the cluster is protected from deletion."
|
||||
default = true
|
||||
}
|
||||
|
||||
resource "google_service_account" "nodes" {
|
||||
project = var.project_id
|
||||
account_id = "gke-nodes"
|
||||
display_name = "GKE nodes"
|
||||
}
|
||||
|
||||
resource "google_project_iam_member" "nodes_default_role" {
|
||||
project = var.project_id
|
||||
role = "roles/container.defaultNodeServiceAccount"
|
||||
member = "serviceAccount:${google_service_account.nodes.email}"
|
||||
}
|
||||
|
||||
resource "google_container_cluster" "workload" {
|
||||
project = var.project_id
|
||||
name = "workload"
|
||||
location = var.region
|
||||
enable_autopilot = true
|
||||
deletion_protection = var.deletion_protection
|
||||
|
||||
network = var.network_id
|
||||
subnetwork = var.subnetwork_id
|
||||
|
||||
ip_allocation_policy {
|
||||
cluster_secondary_range_name = "pods"
|
||||
services_secondary_range_name = "services"
|
||||
}
|
||||
|
||||
private_cluster_config {
|
||||
enable_private_nodes = true
|
||||
enable_private_endpoint = false
|
||||
}
|
||||
|
||||
master_authorized_networks_config {
|
||||
cidr_blocks {
|
||||
cidr_block = var.admin_cidr
|
||||
display_name = "administrators"
|
||||
}
|
||||
}
|
||||
|
||||
cluster_autoscaling {
|
||||
auto_provisioning_defaults {
|
||||
service_account = google_service_account.nodes.email
|
||||
}
|
||||
}
|
||||
|
||||
release_channel {
|
||||
channel = "REGULAR"
|
||||
}
|
||||
|
||||
depends_on = [google_project_iam_member.nodes_default_role]
|
||||
}
|
||||
|
||||
resource "google_service_account" "app" {
|
||||
project = var.project_id
|
||||
account_id = "orders-app"
|
||||
display_name = "Orders application"
|
||||
}
|
||||
|
||||
resource "google_service_account_iam_member" "app_workload_identity" {
|
||||
service_account_id = google_service_account.app.name
|
||||
role = "roles/iam.workloadIdentityUser"
|
||||
member = "serviceAccount:${var.project_id}.svc.id.goog[orders/orders-app]"
|
||||
}
|
||||
```
|
||||
@@ -18,7 +18,7 @@ Each reference below holds the lessons for one Deliverable. Read the one for the
|
||||
| Deliverable | Reference | Lessons |
|
||||
| --- | --- | --- |
|
||||
| deployment guidance | `references/deployment_guidance.md` | 1 |
|
||||
| target architecture | `references/target_architecture.md` | 4 |
|
||||
| target architecture | `references/target_architecture.md` | 8 |
|
||||
<!-- lessons:end -->
|
||||
|
||||
This Skill is written by the lessons loop (`app/learning/`), from proposals a person approved. Do not edit it by hand: change the proposal and publish again.
|
||||
|
||||
@@ -8,4 +8,4 @@ Rules learned from earlier work. Follow every one that applies.
|
||||
|
||||
**Why.** Missing required arguments in nested blocks will cause Terraform validation to fail, preventing submission.
|
||||
|
||||
Published 2026-10-09, from lesson proposal 05.
|
||||
Published 2026-10-10, from lesson proposal 05.
|
||||
|
||||
@@ -8,7 +8,7 @@ Rules learned from earlier work. Follow every one that applies.
|
||||
|
||||
**Why.** If detailed constraints are missed, the validation phase will reject the design for incomplete coverage, forcing a revision.
|
||||
|
||||
Published 2026-10-09, from lesson proposal 01.
|
||||
Published 2026-10-10, from lesson proposal 01.
|
||||
|
||||
## L-02: Assign Checks to Every Element
|
||||
|
||||
@@ -16,7 +16,7 @@ Published 2026-10-09, from lesson proposal 01.
|
||||
|
||||
**Why.** The submission tool will reject the architecture if any Element lacks a Check, wasting an attempt.
|
||||
|
||||
Published 2026-10-09, from lesson proposal 02.
|
||||
Published 2026-10-10, from lesson proposal 02.
|
||||
|
||||
## L-03: Verify Resource Arguments for Checks
|
||||
|
||||
@@ -24,7 +24,7 @@ Published 2026-10-09, from lesson proposal 02.
|
||||
|
||||
**Why.** If a Check specifies an argument that does not exist on the resource, it cannot be implemented, forcing an architectural revision.
|
||||
|
||||
Published 2026-10-09, from lesson proposal 03.
|
||||
Published 2026-10-10, from lesson proposal 03.
|
||||
|
||||
## L-06: Do Not Mark Requirements as Not Applicable
|
||||
|
||||
@@ -32,4 +32,36 @@ Published 2026-10-09, from lesson proposal 03.
|
||||
|
||||
**Why.** The submission tool will reject the deliverable if a Requirement lacks a Check or is incorrectly marked as not applicable.
|
||||
|
||||
Published 2026-10-09, from lesson proposal 06.
|
||||
Published 2026-10-10, from lesson proposal 06.
|
||||
|
||||
## L-07: Verify location constraints
|
||||
|
||||
**Rule.** When a requirement specifies where resources must be provisioned, such as a designated region or multi-zone placement, create a Check for the `region` or `location` argument on every applicable Element, naming the region the design uses. Do not write a Check about a property of the region that code cannot show, such as its carbon rating.
|
||||
|
||||
**Why.** Validation frequently catches missing location constraints. Without this Check, resources may be provisioned in default regions, violating location requirements. A Check about a region's carbon rating cannot be verified from code and sends the design back.
|
||||
|
||||
Published 2026-10-10, from lesson proposal 07.
|
||||
|
||||
## L-08: Cloud SQL backup encryption
|
||||
|
||||
**Rule.** When writing a Check for CMEK encryption on a `google_sql_database_instance`, do not require an `encryption_key_name` argument for backup storage, as the instance-level `encryption_key_name` automatically encrypts backups as well.
|
||||
|
||||
**Why.** The database instance resource does not have a separate encryption key argument for backups. Asking for one causes validation to reject the Check as un-implementable.
|
||||
|
||||
Published 2026-10-10, from lesson proposal 08.
|
||||
|
||||
## L-09: Backend Service capabilities
|
||||
|
||||
**Rule.** When writing Checks for a `google_compute_backend_service`, do not verify IAM roles inside the backend service or require health checks when it is configured with a Serverless NEG.
|
||||
|
||||
**Why.** Roles are verified via IAM bindings outside the backend service, and Serverless NEGs do not support health checks. Invalid Checks cause the design to be rejected during validation.
|
||||
|
||||
Published 2026-10-10, from lesson proposal 09.
|
||||
|
||||
## L-10: Pub/Sub persistence regions
|
||||
|
||||
**Rule.** When a requirement dictates that a messaging queue or topic must replicate across zones or stay within a specific region, create a Check for the `message_storage_policy.allowed_persistence_regions` argument on the topic Element.
|
||||
|
||||
**Why.** Without this Check, topics might use default storage policies that violate geographical or high-availability requirements.
|
||||
|
||||
Published 2026-10-10, from lesson proposal 10.
|
||||
|
||||
9
skills/google-cloud-lessons/upstream.json
Normal file
9
skills/google-cloud-lessons/upstream.json
Normal file
@@ -0,0 +1,9 @@
|
||||
{
|
||||
"google-cloud-solution-architecture": "f5b8cdac4060",
|
||||
"google-cloud-waf-cost-optimization": "b3febbf52e5c",
|
||||
"google-cloud-waf-operational-excellence": "bdc6a9f415f6",
|
||||
"google-cloud-waf-performance-optimization": "89a4947438cf",
|
||||
"google-cloud-waf-reliability": "9baf33bd5b75",
|
||||
"google-cloud-waf-security": "e791a44cda99",
|
||||
"google-cloud-waf-sustainability": "7d0a6921cb59"
|
||||
}
|
||||
@@ -22,11 +22,14 @@ The files are your working copy: the files you wrote with `write_file`, or, when
|
||||
- `terraform_plan(variables)`: previews the changes against the live cloud environment. It reads live state, so the first call may pause for the user's permission. Pass every variable the configuration requires.
|
||||
- `terraform_schema(resource_type, block, find, resource_types)`: what a resource type accepts, from the provider's own schema. With `resource_types`, a list, it outlines every argument and block of each in one call; use that when you need several. With `resource_type` alone it lists the top-level arguments and outlines every block. With `block`, such as `template.containers`, it gives that block's arguments in full. With `find`, it says where an argument or block of that name sits, or that the resource type has none; give several names separated by commas to check them in one call.
|
||||
|
||||
- `terraform_module(source, version, find)`, only when the Execution opted into published modules: what a published module accepts, from the registry: its inputs with their types, its outputs and its submodules. It says when a module cannot be used with the pinned provider. `find` narrows the inputs to those matching the words given. Only modules from the namespaces the Cloud provider allows can be looked up or used.
|
||||
|
||||
## When writing deployment guidance
|
||||
|
||||
1. Run `terraform_fmt`, then `terraform_validate`.
|
||||
2. Fix each error with `edit_file`, changing only the lines concerned, and run `terraform_validate` again until it passes.
|
||||
3. On "An argument named X is not expected here" or "Unsupported block type", call `terraform_schema` with `find` set to the name. It is either in a different block, which the reply names, or it does not exist on that resource type. Never move it around by trial.
|
||||
3. A refusal about a module means one of two things. The Execution writes plain resources, so write them directly. Or the module is not from an approved namespace or not pinned to one exact version, so use an approved module at an exact version or write the resources directly.
|
||||
4. On "An argument named X is not expected here" or "Unsupported block type", call `terraform_schema` with `find` set to the name. It is either in a different block, which the reply names, or it does not exist on that resource type. Never move it around by trial.
|
||||
|
||||
## When validating deployment guidance
|
||||
|
||||
|
||||
@@ -33,7 +33,7 @@ A list. Number functional requirements `FR-1`, `FR-2` and non-functional ones `N
|
||||
]
|
||||
```
|
||||
|
||||
Every non-functional requirement lists its `conditions`: one entry for each separate thing that must be true for it to be met and that infrastructure configuration can show. What it asks for that configuration cannot show goes under `outside_code`: an outcome measured in operation, behaviour of the application's own code, or a process people follow. A requirement has at least one entry between the two; one that is entirely outside code has `"conditions": []`. Write each so it can be checked on its own, and so that together they say everything the text says. The Target architecture needs a Check for each one.
|
||||
Every non-functional requirement lists its `conditions`: one entry for each separate thing that must be true for it to be met and that infrastructure configuration can show. What it asks for that configuration cannot show goes under `outside_code`: an outcome measured in operation, behaviour of the application's own code, a process people follow, or a property of a region or product that only its provider publishes, such as a region's carbon rating or a product's service level. For those, the condition is the choice that configuration can show: "every resource is in the one agreed region" is a condition, and "that region has a high carbon-free energy score" is `outside_code`. A requirement has at least one entry between the two; one that is entirely outside code has `"conditions": []`. Write each so it can be checked on its own, and so that together they say everything the text says. The Target architecture needs a Check for each one.
|
||||
|
||||
`kind` is `functional` or `non_functional`. Write one requirement per entry, so each can be checked on its own.
|
||||
|
||||
@@ -117,6 +117,8 @@ One entry per Check in the Target architecture, saying where the code satisfies
|
||||
]
|
||||
```
|
||||
|
||||
When a module creates the resource, `address` is the module and the input that sets what the Check asks for, such as `module.database.ip_configuration.ipv4_enabled`.
|
||||
|
||||
When a Check names a setting its resource type does not have, give it an `unimplementable` entry in place of `file` and `address`, saying what the resource type lacks. Write no code for it. The Target architecture is revised before anything is validated.
|
||||
|
||||
Implement every Element, Relationship and Check, and nothing the Target architecture does not ask for. When you believe the Target architecture is wrong or incomplete, say so with `needs_input`; do not quietly build something else.
|
||||
|
||||
@@ -75,7 +75,7 @@ def complete_run_turns() -> dict:
|
||||
|
||||
|
||||
def client_for(
|
||||
tmp_path: Path, turns: dict, decider=None
|
||||
tmp_path: Path, turns: dict, decider=None, answers=None
|
||||
) -> tuple[TestClient, FakeAgentRuntime]:
|
||||
bundle = load_provider("gcp")
|
||||
roles = load_roles(AGENTS_DIR, bundle)
|
||||
@@ -96,6 +96,7 @@ def client_for(
|
||||
roles,
|
||||
{"compute": "API not enabled"},
|
||||
intake=Intake(decider, tmp_path) if decider else None,
|
||||
answers=answers,
|
||||
)
|
||||
|
||||
return TestClient(create_app(get_settings(), fake_assembly)), runtime
|
||||
@@ -398,6 +399,74 @@ def delivered_case(tmp_path: Path, case: str = "acme") -> None:
|
||||
)
|
||||
|
||||
|
||||
class Answers:
|
||||
"""Stands in for the reply writer answering from delivered files."""
|
||||
|
||||
def __init__(self, reply):
|
||||
self.reply = reply
|
||||
self.asked: list[tuple[str, str, str]] = []
|
||||
|
||||
async def answer(self, question, customer_case, execution_id):
|
||||
self.asked.append((question, customer_case, execution_id))
|
||||
return self.reply
|
||||
|
||||
|
||||
ABOUT_DELIVERED = {
|
||||
"intake": Answer("question", 0.98),
|
||||
"about_delivered": Answer(0.92, 0.9),
|
||||
}
|
||||
|
||||
|
||||
def test_a_question_about_delivered_work_is_answered_from_it(tmp_path):
|
||||
delivered_case(tmp_path)
|
||||
answers = Answers("Cloud SQL, because bookings are relational.")
|
||||
client, runtime = client_for(tmp_path, {}, FakeDecider(ABOUT_DELIVERED), answers)
|
||||
with client:
|
||||
task = send(
|
||||
client,
|
||||
[{"text": "Why did you choose Cloud SQL?"}],
|
||||
metadata={"customer_case": "acme"},
|
||||
)
|
||||
|
||||
text, data = status_parts(task)
|
||||
assert task["status"]["state"] == "TASK_STATE_COMPLETED"
|
||||
assert text == "Cloud SQL, because bookings are relational."
|
||||
assert data == {"status": "answered", "intake": "question", "about": "v1"}
|
||||
assert answers.asked == [("Why did you choose Cloud SQL?", "acme", "v1")]
|
||||
assert runtime.runs == []
|
||||
|
||||
|
||||
def test_a_question_that_could_not_be_answered_says_where_to_look(tmp_path):
|
||||
delivered_case(tmp_path)
|
||||
client, _ = client_for(tmp_path, {}, FakeDecider(ABOUT_DELIVERED), Answers(None))
|
||||
with client:
|
||||
task = send(
|
||||
client, [{"text": "Why Cloud SQL?"}], metadata={"customer_case": "acme"}
|
||||
)
|
||||
|
||||
text, data = status_parts(task)
|
||||
assert "could not answer that from the documents delivered in Execution v1" in text
|
||||
assert data["about"] == "v1"
|
||||
|
||||
|
||||
def test_a_question_about_the_service_is_still_answered_in_general(tmp_path):
|
||||
delivered_case(tmp_path)
|
||||
decider = FakeDecider(
|
||||
{"intake": Answer("question", 0.98), "about_delivered": Answer(0.08, 0.9)}
|
||||
)
|
||||
answers = Answers("unused")
|
||||
client, _ = client_for(tmp_path, {}, decider, answers)
|
||||
with client:
|
||||
task = send(
|
||||
client, [{"text": "What can you do?"}], metadata={"customer_case": "acme"}
|
||||
)
|
||||
|
||||
text, data = status_parts(task)
|
||||
assert text.startswith("I design cloud solution architectures.")
|
||||
assert data == {"status": "answered", "intake": "question"}
|
||||
assert answers.asked == []
|
||||
|
||||
|
||||
def test_a_change_to_delivered_work_names_the_baseline_and_starts_nothing(tmp_path):
|
||||
delivered_case(tmp_path)
|
||||
decider = FakeDecider({"intake": Answer("change_request", 0.98)})
|
||||
|
||||
@@ -21,8 +21,9 @@ def test_every_engine_role_and_the_pillar_advisor_is_defined(bundle):
|
||||
|
||||
expected = {"orchestrator", "reply-writer", PILLAR_ADVISOR}
|
||||
expected |= {spec.specialist for spec in DEPENDENCY_GRAPH.values()}
|
||||
# The lesson curator runs outside any Execution; the engine does not need it.
|
||||
assert set(roles) == expected | {"lesson-curator"}
|
||||
# The lesson curator runs outside any Execution, and the coverage reviewer only
|
||||
# when the deployment switches its review on; the engine needs neither.
|
||||
assert set(roles) == expected | {"lesson-curator", "coverage-reviewer"}
|
||||
for role in roles.values():
|
||||
assert role.instructions.strip()
|
||||
|
||||
@@ -52,6 +53,7 @@ def test_roles_name_only_the_local_tools_they_need(bundle):
|
||||
"terraform_fmt",
|
||||
"terraform_validate",
|
||||
"terraform_schema",
|
||||
"terraform_module",
|
||||
)
|
||||
# The architect only looks settings up; it writes and runs no code.
|
||||
assert roles["target-architect"].tools == ("terraform_schema",)
|
||||
@@ -59,6 +61,7 @@ def test_roles_name_only_the_local_tools_they_need(bundle):
|
||||
"terraform_validate",
|
||||
"terraform_plan",
|
||||
"terraform_schema",
|
||||
"terraform_module",
|
||||
)
|
||||
assert roles["requirements-analyst"].tools == ()
|
||||
|
||||
|
||||
150
tests/execution/test_design_review.py
Normal file
150
tests/execution/test_design_review.py
Normal file
@@ -0,0 +1,150 @@
|
||||
"""A model reviews a design's coverage before it is approved (iteration 6 step 13)."""
|
||||
|
||||
from langgraph.checkpoint.memory import InMemorySaver
|
||||
|
||||
from app.adk.fake_runtime import SAMPLE_DATA, Call, FakeAgentRuntime, sample_submission
|
||||
from app.adk.roles import COVERAGE_REVIEWER, load_roles
|
||||
from app.adk.runtime import NoDecider, RoleSpec
|
||||
from app.agent import AGENTS_DIR, ExecutionEngine
|
||||
from app.nodes.router import Router, Thresholds
|
||||
from app.providers import load_provider
|
||||
from app.recorder import InMemoryRecorder
|
||||
from app.tools.design_review import DesignCoverageReview
|
||||
from app.workflows.deliverables import DEPENDENCY_GRAPH, DeliverableKind
|
||||
|
||||
K = DeliverableKind
|
||||
GRAPH = {"target-architecture.json": SAMPLE_DATA["target-architecture.json"]}
|
||||
UPSTREAM = {
|
||||
"requirements": {
|
||||
"attachments": {"requirements.json": SAMPLE_DATA["requirements.json"]}
|
||||
},
|
||||
"design_recommendations": {
|
||||
"attachments": {"recommendations.json": SAMPLE_DATA["recommendations.json"]}
|
||||
},
|
||||
}
|
||||
REVIEWER = RoleSpec(COVERAGE_REVIEWER, "Review.", budget=6)
|
||||
GAP = {
|
||||
"source": "NFR-1",
|
||||
"applies_to": "E-1",
|
||||
"statement": "min_instance_count is at least 2",
|
||||
}
|
||||
|
||||
|
||||
def reviewer(*gaps: dict, seen: dict | None = None) -> FakeAgentRuntime:
|
||||
def turn(task):
|
||||
if seen is not None:
|
||||
seen.update(task.context)
|
||||
return [Call("report_gaps", {"gaps": list(gaps)})]
|
||||
|
||||
return FakeAgentRuntime({COVERAGE_REVIEWER: [turn, turn]})
|
||||
|
||||
|
||||
async def test_the_reviewer_is_given_the_constraints_and_the_design():
|
||||
seen: dict = {}
|
||||
review = DesignCoverageReview(reviewer(GAP, seen=seen), REVIEWER)
|
||||
|
||||
concerns = await review(K.TARGET_ARCHITECTURE, GRAPH, UPSTREAM, "exec-1")
|
||||
|
||||
assert concerns == (
|
||||
"NFR-1: no Check verifies this on E-1: min_instance_count is at least 2",
|
||||
)
|
||||
# Non-functional requirements and recommendations; a functional requirement
|
||||
# is reached through its components, not through a Check of its own.
|
||||
assert [item["id"] for item in seen["constraints"]] == ["NFR-1", "DR-1"]
|
||||
assert {e["id"] for e in seen["target_architecture"]["elements"]} >= {"E-1"}
|
||||
|
||||
|
||||
async def test_a_gap_about_something_that_does_not_exist_is_dropped():
|
||||
invented = [
|
||||
{**GAP, "source": "NFR-99"},
|
||||
{**GAP, "applies_to": "E-99"},
|
||||
{**GAP, "statement": " "},
|
||||
"not a gap",
|
||||
]
|
||||
review = DesignCoverageReview(reviewer(*invented, GAP), REVIEWER)
|
||||
|
||||
concerns = await review(K.TARGET_ARCHITECTURE, GRAPH, UPSTREAM, "exec-1")
|
||||
|
||||
assert len(concerns) == 1 and concerns[0].startswith("NFR-1:")
|
||||
|
||||
|
||||
async def test_a_design_is_reviewed_once_in_an_execution():
|
||||
runtime = reviewer(GAP)
|
||||
review = DesignCoverageReview(runtime, REVIEWER)
|
||||
|
||||
first = await review(K.TARGET_ARCHITECTURE, GRAPH, UPSTREAM, "exec-1")
|
||||
again = await review(K.TARGET_ARCHITECTURE, GRAPH, UPSTREAM, "exec-1")
|
||||
other = await review(K.TARGET_ARCHITECTURE, GRAPH, UPSTREAM, "exec-2")
|
||||
|
||||
assert first and other and again == ()
|
||||
assert len(runtime.runs) == 2
|
||||
|
||||
|
||||
async def test_nothing_is_reviewed_but_a_readable_target_architecture():
|
||||
runtime = reviewer(GAP)
|
||||
review = DesignCoverageReview(runtime, REVIEWER)
|
||||
|
||||
assert await review(K.DEPLOYMENT_GUIDANCE, GRAPH, UPSTREAM, "a") == ()
|
||||
assert await review(K.TARGET_ARCHITECTURE, {}, UPSTREAM, "b") == ()
|
||||
assert await review(K.TARGET_ARCHITECTURE, GRAPH, None, "c") == ()
|
||||
assert runtime.runs == []
|
||||
|
||||
|
||||
async def test_a_complete_design_raises_nothing():
|
||||
review = DesignCoverageReview(reviewer(), REVIEWER)
|
||||
|
||||
assert await review(K.TARGET_ARCHITECTURE, GRAPH, UPSTREAM, "exec-1") == ()
|
||||
|
||||
|
||||
async def test_the_gaps_go_back_to_the_target_architect_before_the_design_stands(
|
||||
tmp_path,
|
||||
):
|
||||
roles = {
|
||||
"orchestrator": RoleSpec("orchestrator", "Unused.", budget=40),
|
||||
**{
|
||||
spec.specialist: RoleSpec(spec.specialist, "Produce.", budget=15)
|
||||
for spec in DEPENDENCY_GRAPH.values()
|
||||
},
|
||||
}
|
||||
architect = DEPENDENCY_GRAPH[K.TARGET_ARCHITECTURE].specialist
|
||||
design = sample_submission(K.TARGET_ARCHITECTURE)
|
||||
runtime = FakeAgentRuntime(
|
||||
{
|
||||
**{
|
||||
spec.specialist: [[sample_submission(kind)]]
|
||||
for kind, spec in DEPENDENCY_GRAPH.items()
|
||||
},
|
||||
# Submitted twice: once into the review, once after reading it.
|
||||
architect: [[design, design]],
|
||||
COVERAGE_REVIEWER: [[Call("report_gaps", {"gaps": [GAP]})]],
|
||||
}
|
||||
)
|
||||
engine = ExecutionEngine(
|
||||
runtime=runtime,
|
||||
roles=roles,
|
||||
recorder=InMemoryRecorder(),
|
||||
checkpointer=InMemorySaver(),
|
||||
output_root=tmp_path,
|
||||
orchestrator=Router(NoDecider(), None, Thresholds()),
|
||||
submission_review=DesignCoverageReview(runtime, REVIEWER),
|
||||
)
|
||||
|
||||
result = await engine.start("Ingest webhooks", pre_approved=True)
|
||||
|
||||
assert result.status == "completed"
|
||||
run = next(run for run in runtime.runs if run.role == architect)
|
||||
first, second = (reply for _, reply in run.results)
|
||||
assert first.startswith("Not submitted. A review found: NFR-1: no Check verifies")
|
||||
assert not second.startswith("Not submitted")
|
||||
# No Revision was needed: the gap was dealt with before anything was approved.
|
||||
assert not [d for d in result.state["decisions"] if "revise" in d["action"]]
|
||||
|
||||
|
||||
def test_the_reviewer_role_loads_with_the_bundles_model():
|
||||
bundle = load_provider("gcp")
|
||||
roles = load_roles(AGENTS_DIR, bundle)
|
||||
|
||||
role = roles[COVERAGE_REVIEWER]
|
||||
assert role.model == bundle.models.for_role(COVERAGE_REVIEWER)
|
||||
assert role.model == bundle.models.for_role("validator")
|
||||
assert role.tools == () and role.model_timeout_seconds == 300
|
||||
@@ -62,3 +62,100 @@ async def test_a_change_needs_something_delivered_to_change(tmp_path):
|
||||
assert "- Design thing 1." in decider.asked[0][0]
|
||||
assert "Design thing 2." not in decider.asked[0][0] # still in progress
|
||||
assert without.kind == NEW_REQUEST and no_case.kind == NEW_REQUEST
|
||||
|
||||
|
||||
# --- a question about what was delivered ------------------------------------------------
|
||||
|
||||
|
||||
async def test_a_question_about_delivered_work_is_told_from_one_about_the_service(
|
||||
tmp_path,
|
||||
):
|
||||
delivered(tmp_path, "acme", ["completed"])
|
||||
about = FakeDecider(
|
||||
{"intake": Answer(QUESTION, 0.98), "about_delivered": Answer(0.9, 0.9)}
|
||||
)
|
||||
general = FakeDecider(
|
||||
{"intake": Answer(QUESTION, 0.98), "about_delivered": Answer(0.1, 0.9)}
|
||||
)
|
||||
|
||||
first = await Intake(about, tmp_path).read("Why Cloud SQL?", "acme")
|
||||
second = await Intake(general, tmp_path).read("What can you do?", "acme")
|
||||
|
||||
assert first.kind == QUESTION and first.about_delivered and first.latest == "v1"
|
||||
assert second.kind == QUESTION and not second.about_delivered
|
||||
|
||||
|
||||
async def test_with_nothing_delivered_a_question_is_never_about_delivered_work(
|
||||
tmp_path,
|
||||
):
|
||||
decider = FakeDecider(
|
||||
{"intake": Answer(QUESTION, 0.98), "about_delivered": Answer(0.99, 0.9)}
|
||||
)
|
||||
|
||||
reading = await Intake(decider, tmp_path).read("Why Cloud SQL?", "new-client")
|
||||
|
||||
assert not reading.about_delivered
|
||||
assert len(decider.asked) == 1 # the second question was not asked
|
||||
|
||||
|
||||
async def test_an_answer_is_written_from_the_delivered_guide_and_nothing_else(
|
||||
tmp_path,
|
||||
):
|
||||
from langgraph.checkpoint.memory import InMemorySaver
|
||||
|
||||
from app.adk.fake_runtime import Call, FakeAgentRuntime, sample_submission
|
||||
from app.adk.runtime import RoleSpec
|
||||
from app.agent import ExecutionEngine
|
||||
from app.nodes.intake import DeliveredAnswers
|
||||
from app.nodes.router import Router, Thresholds
|
||||
from app.recorder import InMemoryRecorder
|
||||
from app.workflows.deliverables import DEPENDENCY_GRAPH
|
||||
|
||||
roles = {
|
||||
"orchestrator": RoleSpec("orchestrator", "Unused.", budget=40),
|
||||
**{
|
||||
spec.specialist: RoleSpec(spec.specialist, "Produce.", budget=15)
|
||||
for spec in DEPENDENCY_GRAPH.values()
|
||||
},
|
||||
}
|
||||
seen: dict = {}
|
||||
|
||||
def writer(task):
|
||||
seen.update(task.context)
|
||||
return [Call("write_reply", {"text": "Cloud SQL, for relational bookings."})]
|
||||
|
||||
runtime = FakeAgentRuntime(
|
||||
{
|
||||
**{
|
||||
spec.specialist: [[sample_submission(kind)]]
|
||||
for kind, spec in DEPENDENCY_GRAPH.items()
|
||||
},
|
||||
"reply-writer": [writer],
|
||||
}
|
||||
)
|
||||
engine = ExecutionEngine(
|
||||
runtime=runtime,
|
||||
roles=roles,
|
||||
recorder=InMemoryRecorder(),
|
||||
checkpointer=InMemorySaver(),
|
||||
output_root=tmp_path,
|
||||
orchestrator=Router(NoDecider(), None, Thresholds()),
|
||||
)
|
||||
await engine.start(
|
||||
"Design bookings.", customer_case="acme", pre_approved=True, execution_id="v1"
|
||||
)
|
||||
runs_before = len(runtime.runs)
|
||||
answers = DeliveredAnswers(
|
||||
runtime, RoleSpec("reply-writer", "Write.", budget=3), tmp_path
|
||||
)
|
||||
|
||||
answer = await answers.answer("Why Cloud SQL?", "acme", "v1")
|
||||
|
||||
assert answer == "Cloud SQL, for relational bookings."
|
||||
assert seen["question"] == "Why Cloud SQL?"
|
||||
assert seen["delivered"]["execution_id"] == "v1"
|
||||
assert seen["delivered"]["request"] == "Design bookings."
|
||||
assert seen["delivered"]["solution_guide"]
|
||||
assert len(runtime.runs) == runs_before + 1 # one writer run; no Execution
|
||||
# An Execution that is not there gives no answer, not an error.
|
||||
assert await answers.answer("Why?", "acme", "missing") is None
|
||||
|
||||
100
tests/execution/test_outputs_as_it_goes.py
Normal file
100
tests/execution/test_outputs_as_it_goes.py
Normal file
@@ -0,0 +1,100 @@
|
||||
"""An Execution's files are on disk as soon as each Deliverable is submitted.
|
||||
|
||||
Before this they were written only when an Execution ended, so a process that was
|
||||
killed, or an Execution left waiting for its user, had nothing to show.
|
||||
"""
|
||||
|
||||
import json
|
||||
|
||||
from langgraph.checkpoint.memory import InMemorySaver
|
||||
|
||||
from app.adk.fake_runtime import FakeAgentRuntime, sample_submission
|
||||
from app.adk.runtime import NoDecider, RoleSpec
|
||||
from app.agent import ExecutionEngine
|
||||
from app.baseline import BaselineError, load_baseline
|
||||
from app.nodes.execution_nodes import _write_outputs
|
||||
from app.nodes.router import Router, Thresholds
|
||||
from app.recorder import InMemoryRecorder
|
||||
from app.states.ledger import Ledger
|
||||
from app.workflows.deliverables import DEPENDENCY_GRAPH
|
||||
|
||||
ROLES = {
|
||||
"orchestrator": RoleSpec("orchestrator", "Unused.", budget=40),
|
||||
**{
|
||||
spec.specialist: RoleSpec(spec.specialist, "Produce.", budget=15)
|
||||
for spec in DEPENDENCY_GRAPH.values()
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def folder(tmp_path, execution_id: str):
|
||||
return tmp_path / "deliverables" / "cases" / "acme" / "executions" / execution_id
|
||||
|
||||
|
||||
async def test_an_execution_waiting_for_its_user_has_written_what_exists(tmp_path):
|
||||
engine = ExecutionEngine(
|
||||
runtime=FakeAgentRuntime(
|
||||
{
|
||||
spec.specialist: [[sample_submission(kind)]]
|
||||
for kind, spec in DEPENDENCY_GRAPH.items()
|
||||
}
|
||||
),
|
||||
roles=ROLES,
|
||||
recorder=InMemoryRecorder(),
|
||||
checkpointer=InMemorySaver(),
|
||||
output_root=tmp_path,
|
||||
orchestrator=Router(NoDecider(), None, Thresholds()),
|
||||
)
|
||||
|
||||
waiting = await engine.start("Ingest", customer_case="acme", execution_id="v1")
|
||||
|
||||
# It stopped for the first Approval: only the first Phase has been produced.
|
||||
assert waiting.status == "awaiting_user"
|
||||
out = folder(tmp_path, "v1")
|
||||
manifest = json.loads((out / "execution.json").read_text())
|
||||
assert manifest["status"] == "in_progress"
|
||||
assert set(manifest["deliverables"]) == {"requirements", "technical_decomposition"}
|
||||
assert (out / "deliverables" / "requirements.md").read_text()
|
||||
assert (out / "requirements.json").is_file()
|
||||
assert manifest["solution_guide"] is None
|
||||
# Unfinished work is never something a Change request can start from.
|
||||
try:
|
||||
load_baseline(tmp_path, "acme", "v1")
|
||||
except BaselineError as refused:
|
||||
assert "did not complete (in_progress)" in str(refused)
|
||||
else:
|
||||
raise AssertionError("an in-progress Execution was accepted as a Baseline")
|
||||
|
||||
|
||||
def test_a_file_an_earlier_write_left_is_removed_with_the_revision(tmp_path):
|
||||
state = {
|
||||
"execution_id": "v1",
|
||||
"customer_case": "acme",
|
||||
"workflow_request": "Ingest",
|
||||
"deliverables": {
|
||||
"deployment_guidance": {
|
||||
"content": "guide",
|
||||
"attachments": {
|
||||
"terraform/main.tf": "one",
|
||||
"terraform/queue.tf": "two",
|
||||
},
|
||||
}
|
||||
},
|
||||
}
|
||||
out = folder(tmp_path, "v1")
|
||||
|
||||
_write_outputs(tmp_path, state, "in_progress", Ledger())
|
||||
assert (out / "terraform" / "queue.tf").is_file()
|
||||
(out / "notes.txt").write_text("a person's own file")
|
||||
|
||||
# The Revision folded the queue into main.tf.
|
||||
state["deliverables"]["deployment_guidance"]["attachments"] = {
|
||||
"terraform/main.tf": "one and two"
|
||||
}
|
||||
_write_outputs(tmp_path, state, "completed", Ledger())
|
||||
|
||||
assert not (out / "terraform" / "queue.tf").exists()
|
||||
assert (out / "terraform" / "main.tf").read_text() == "one and two"
|
||||
# Only files this Execution wrote are ever removed.
|
||||
assert (out / "notes.txt").is_file()
|
||||
assert json.loads((out / "execution.json").read_text())["status"] == "completed"
|
||||
@@ -464,3 +464,163 @@ async def test_an_empty_list_of_pillars_consults_none_and_returns_what_was_said(
|
||||
assert len(runtime.runs) == 3 # nobody was consulted a second time
|
||||
for pillar in PILLARS:
|
||||
assert f"## {pillar} (from your earlier consultation)" in again.message
|
||||
|
||||
|
||||
# --- what the request does not say is a question for the customer ------------------------
|
||||
|
||||
|
||||
def unsure(question: str | None = "Do you have a central identity provider?"):
|
||||
def turn(task):
|
||||
entry = {
|
||||
"item": "Identity is managed centrally",
|
||||
"status": "needs_customer_input",
|
||||
"note": "The request does not say how staff identities are managed.",
|
||||
}
|
||||
if question is not None:
|
||||
entry["question"] = question
|
||||
first = Call("submit_advice", {"content": "Advice.", "checklist": [entry]})
|
||||
# A second attempt, used only when the first is refused.
|
||||
fixed = Call(
|
||||
"submit_advice",
|
||||
{
|
||||
"content": "Advice.",
|
||||
"checklist": [{**entry, "question": "Who manages staff identities?"}],
|
||||
},
|
||||
)
|
||||
return [first, fixed]
|
||||
|
||||
return turn
|
||||
|
||||
|
||||
async def test_an_item_the_request_cannot_settle_is_kept_with_its_question():
|
||||
from app.tools.pillars import CHECKLIST_KEY, customer_questions
|
||||
|
||||
memory: dict = {}
|
||||
runtime = FakeAgentRuntime({PILLAR_ADVISOR: [unsure()] * 3})
|
||||
|
||||
await consult(
|
||||
pillar_consultation_tool(runtime, ADVISOR, PILLARS, memory=memory), brief="b"
|
||||
)
|
||||
|
||||
(entry,) = memory[CHECKLIST_KEY]["security"]
|
||||
assert entry["status"] == "needs_customer_input"
|
||||
assert customer_questions(memory)[0] == {
|
||||
"pillar": "security",
|
||||
"item": "Identity is managed centrally",
|
||||
"question": "Do you have a central identity provider?",
|
||||
}
|
||||
assert len(customer_questions(memory)) == len(PILLARS)
|
||||
|
||||
|
||||
async def test_an_item_for_the_customer_must_carry_the_question_to_ask():
|
||||
from app.tools.pillars import CHECKLIST_KEY
|
||||
|
||||
memory: dict = {}
|
||||
runtime = FakeAgentRuntime({PILLAR_ADVISOR: [unsure(question=None)] * 3})
|
||||
|
||||
await consult(
|
||||
pillar_consultation_tool(runtime, ADVISOR, PILLARS, memory=memory), brief="b"
|
||||
)
|
||||
|
||||
refused, accepted = (reply for _, reply in runtime.runs[0].results)
|
||||
assert refused.startswith("Not submitted: an item to confirm with the customer")
|
||||
assert "Identity is managed centrally" in refused
|
||||
(entry,) = memory[CHECKLIST_KEY]["security"]
|
||||
assert entry["question"] == "Who manages staff identities?"
|
||||
assert accepted == "Advice submitted."
|
||||
|
||||
|
||||
def test_the_questions_are_reported_as_missing_information_not_as_faults():
|
||||
from app.tools.pillars import (
|
||||
CHECKLIST_KEY,
|
||||
QUESTIONS_HEADING,
|
||||
render_checklist_review,
|
||||
)
|
||||
|
||||
working = {
|
||||
CHECKLIST_KEY: {
|
||||
"security": [
|
||||
{
|
||||
"item": "Scans run in the pipeline",
|
||||
"status": "addressed",
|
||||
"note": "DR-3",
|
||||
},
|
||||
{
|
||||
"item": "Identity is managed centrally",
|
||||
"status": "needs_customer_input",
|
||||
"note": "Not said.",
|
||||
"question": "Do you have a central identity provider?",
|
||||
},
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
text = render_checklist_review(working)
|
||||
|
||||
assert "| Identity is managed centrally | To confirm with the customer |" in text
|
||||
assert f"### {QUESTIONS_HEADING}" in text
|
||||
assert "They are not faults in the design" in text
|
||||
assert (
|
||||
"| security | Identity is managed centrally | Do you have a central "
|
||||
"identity provider? |"
|
||||
) in text
|
||||
# With nothing to ask there is no questions section.
|
||||
only_addressed = {
|
||||
CHECKLIST_KEY: {"security": working[CHECKLIST_KEY]["security"][:1]}
|
||||
}
|
||||
assert QUESTIONS_HEADING not in render_checklist_review(only_addressed)
|
||||
|
||||
|
||||
async def test_an_execution_writes_its_questions_for_the_customer(tmp_path):
|
||||
import json
|
||||
|
||||
from langgraph.checkpoint.memory import InMemorySaver
|
||||
|
||||
from app.adk.fake_runtime import sample_submission
|
||||
from app.adk.runtime import NoDecider
|
||||
from app.agent import ExecutionEngine
|
||||
from app.nodes.router import Router, Thresholds
|
||||
from app.recorder import InMemoryRecorder
|
||||
from app.tools.pillars import CONSULT_TOOL
|
||||
from app.workflows.deliverables import DEPENDENCY_GRAPH, DeliverableKind
|
||||
|
||||
kind = DeliverableKind.DESIGN_RECOMMENDATIONS
|
||||
advisor = DEPENDENCY_GRAPH[kind].specialist
|
||||
roles = {
|
||||
"orchestrator": RoleSpec("orchestrator", "Unused.", budget=40),
|
||||
PILLAR_ADVISOR: ADVISOR,
|
||||
**{
|
||||
spec.specialist: RoleSpec(spec.specialist, "Produce.", budget=15)
|
||||
for spec in DEPENDENCY_GRAPH.values()
|
||||
},
|
||||
}
|
||||
turns = {
|
||||
spec.specialist: [[sample_submission(k)]]
|
||||
for k, spec in DEPENDENCY_GRAPH.items()
|
||||
}
|
||||
turns[advisor] = [[Call(CONSULT_TOOL, {"brief": "b"}), sample_submission(kind)]]
|
||||
turns[PILLAR_ADVISOR] = [unsure()] * 3
|
||||
runtime = FakeAgentRuntime(turns)
|
||||
engine = ExecutionEngine(
|
||||
runtime=runtime,
|
||||
roles=roles,
|
||||
recorder=InMemoryRecorder(),
|
||||
checkpointer=InMemorySaver(),
|
||||
output_root=tmp_path,
|
||||
orchestrator=Router(NoDecider(), None, Thresholds()),
|
||||
tool_factory=make_tool_factory(runtime, roles, pillar_skills=PILLARS),
|
||||
)
|
||||
|
||||
result = await engine.start("Ingest", customer_case="acme", pre_approved=True)
|
||||
|
||||
assert result.status == "completed"
|
||||
out = next(tmp_path.rglob("execution.json")).parent
|
||||
manifest = json.loads((out / "execution.json").read_text())
|
||||
assert manifest["customer_questions"] == "customer-questions.md"
|
||||
questions = (out / "customer-questions.md").read_text()
|
||||
assert questions.startswith("# Questions for the customer")
|
||||
assert "Do you have a central identity provider?" in questions
|
||||
assert (
|
||||
"### Questions for the customer"
|
||||
in (out / "deliverables" / "design_recommendations.md").read_text()
|
||||
)
|
||||
|
||||
@@ -303,7 +303,9 @@ async def test_a_check_the_code_cannot_meet_goes_back_to_the_graph_unvalidated(
|
||||
"target_architecture",
|
||||
(
|
||||
"Check K-2 cannot be implemented as written (no such argument). "
|
||||
"Rewrite it so it can be met, or remove it with a reason."
|
||||
"Rewrite it so it can be met, or remove it with a reason. The same "
|
||||
"fault may be in other Checks: read every Check against each reason "
|
||||
"given here and correct every one it applies to."
|
||||
),
|
||||
)
|
||||
]
|
||||
|
||||
214
tests/execution/test_terraform_modules.py
Normal file
214
tests/execution/test_terraform_modules.py
Normal file
@@ -0,0 +1,214 @@
|
||||
"""Published Terraform modules are opt-in per Execution (iteration 8).
|
||||
|
||||
Infrastructure code is plain resources by default. An Execution that opts in is
|
||||
given the modules Skill and the module lookup, and only then is a module call from
|
||||
an approved source accepted.
|
||||
"""
|
||||
|
||||
import json
|
||||
|
||||
import pytest
|
||||
from langgraph.checkpoint.memory import InMemorySaver
|
||||
|
||||
from app.adk.fake_runtime import FakeAgentRuntime, sample_submission
|
||||
from app.adk.roles import load_roles
|
||||
from app.adk.runtime import NoDecider, RoleSpec
|
||||
from app.agent import AGENTS_DIR, ExecutionEngine
|
||||
from app.nodes.router import Router, Thresholds
|
||||
from app.providers import load_provider
|
||||
from app.recorder import InMemoryRecorder
|
||||
from app.tools.local import TerraformRunner
|
||||
from app.tools.modules import MODULE_TOOL, MODULES_OPTED_IN, NOT_OPTED_IN
|
||||
from app.workflows.deliverables import DEPENDENCY_GRAPH
|
||||
from app.workflows.deliverables import DeliverableKind as K
|
||||
|
||||
AUTHOR = DEPENDENCY_GRAPH[K.DEPLOYMENT_GUIDANCE].specialist
|
||||
CASE = "acme"
|
||||
MODULE_CALL = """
|
||||
module "network" {
|
||||
source = "approved-modules/network/cloud"
|
||||
version = "1.2.3"
|
||||
}
|
||||
"""
|
||||
ROLES = {
|
||||
"orchestrator": RoleSpec("orchestrator", "Unused.", budget=40),
|
||||
**{
|
||||
spec.specialist: RoleSpec(
|
||||
spec.specialist,
|
||||
"Produce.",
|
||||
budget=15,
|
||||
skills=("base",),
|
||||
tools=(MODULE_TOOL,) if spec.specialist == AUTHOR else (),
|
||||
modules_skill="modules-skill" if spec.specialist == AUTHOR else None,
|
||||
)
|
||||
for spec in DEPENDENCY_GRAPH.values()
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
class Recording(FakeAgentRuntime):
|
||||
def __init__(self, turns):
|
||||
super().__init__(turns)
|
||||
self.seen: dict[str, dict] = {}
|
||||
|
||||
async def run(self, role, task, tools):
|
||||
self.seen[role.name] = {
|
||||
"skills": role.skills,
|
||||
"role_tools": role.tools,
|
||||
"context": task.context.get("terraform_modules"),
|
||||
"opted_in": MODULES_OPTED_IN.get(),
|
||||
}
|
||||
return await super().run(role, task, tools)
|
||||
|
||||
|
||||
def engine(tmp_path, **options) -> tuple[ExecutionEngine, Recording]:
|
||||
runtime = Recording(
|
||||
{
|
||||
spec.specialist: [[sample_submission(kind)]] * 2
|
||||
for kind, spec in DEPENDENCY_GRAPH.items()
|
||||
}
|
||||
)
|
||||
built = ExecutionEngine(
|
||||
runtime=runtime,
|
||||
roles=ROLES,
|
||||
recorder=InMemoryRecorder(),
|
||||
checkpointer=InMemorySaver(),
|
||||
output_root=tmp_path,
|
||||
orchestrator=Router(NoDecider(), None, Thresholds()),
|
||||
**options,
|
||||
)
|
||||
return built, runtime
|
||||
|
||||
|
||||
def manifest(tmp_path, execution_id: str) -> dict:
|
||||
folder = tmp_path / "deliverables" / "cases" / CASE / "executions" / execution_id
|
||||
return json.loads((folder / "execution.json").read_text())
|
||||
|
||||
|
||||
async def test_by_default_code_is_plain_resources(tmp_path):
|
||||
built, runtime = engine(tmp_path, modules_available=True)
|
||||
|
||||
await built.start("Ingest", customer_case=CASE, pre_approved=True, execution_id="a")
|
||||
|
||||
author = runtime.seen[AUTHOR]
|
||||
assert author["skills"] == ("base",)
|
||||
assert MODULE_TOOL not in author["role_tools"]
|
||||
assert author["context"] is False and author["opted_in"] is False
|
||||
assert manifest(tmp_path, "a")["terraform_modules"] is False
|
||||
|
||||
|
||||
async def test_an_execution_that_opts_in_is_given_the_skill_and_the_lookup(tmp_path):
|
||||
built, runtime = engine(tmp_path, modules_available=True)
|
||||
|
||||
await built.start(
|
||||
"Ingest",
|
||||
customer_case=CASE,
|
||||
pre_approved=True,
|
||||
execution_id="a",
|
||||
terraform_modules=True,
|
||||
)
|
||||
|
||||
author = runtime.seen[AUTHOR]
|
||||
assert author["skills"] == ("base", "modules-skill")
|
||||
assert MODULE_TOOL in author["role_tools"]
|
||||
assert author["context"] is True and author["opted_in"] is True
|
||||
# A role that writes no code is given neither.
|
||||
assert runtime.seen["requirements-analyst"]["skills"] == ("base",)
|
||||
assert manifest(tmp_path, "a")["terraform_modules"] is True
|
||||
|
||||
|
||||
async def test_the_deployment_may_make_modules_the_default(tmp_path):
|
||||
built, runtime = engine(tmp_path, modules_available=True, default_modules=True)
|
||||
|
||||
await built.start("Ingest", customer_case=CASE, pre_approved=True, execution_id="a")
|
||||
assert runtime.seen[AUTHOR]["opted_in"] is True
|
||||
|
||||
await built.start(
|
||||
"Ingest",
|
||||
customer_case=CASE,
|
||||
pre_approved=True,
|
||||
execution_id="b",
|
||||
terraform_modules=False,
|
||||
)
|
||||
assert runtime.seen[AUTHOR]["opted_in"] is False
|
||||
|
||||
|
||||
async def test_opting_in_is_refused_when_the_provider_approves_no_sources(tmp_path):
|
||||
built, runtime = engine(tmp_path)
|
||||
|
||||
with pytest.raises(ValueError, match="no approved module sources"):
|
||||
await built.start("Ingest", pre_approved=True, terraform_modules=True)
|
||||
with pytest.raises(ValueError, match="true or false"):
|
||||
await built.start("Ingest", pre_approved=True, terraform_modules="yes")
|
||||
assert runtime.seen == {}
|
||||
|
||||
|
||||
async def test_a_change_request_does_as_its_baseline_did(tmp_path):
|
||||
built, runtime = engine(tmp_path, modules_available=True)
|
||||
await built.start(
|
||||
"Ingest",
|
||||
customer_case=CASE,
|
||||
pre_approved=True,
|
||||
execution_id="v1",
|
||||
terraform_modules=True,
|
||||
)
|
||||
runtime.seen.clear()
|
||||
|
||||
# sample submissions change nothing, so the Change request ends with warnings;
|
||||
# what matters is which way it started.
|
||||
await built.start(
|
||||
"Retention changes.",
|
||||
customer_case=CASE,
|
||||
pre_approved=True,
|
||||
execution_id="v2",
|
||||
baseline="v1",
|
||||
)
|
||||
|
||||
assert built is not None
|
||||
state = (await built.interaction("v2")).state
|
||||
assert state["terraform_modules"] is True
|
||||
|
||||
|
||||
async def test_a_module_call_is_refused_unless_the_execution_opted_in():
|
||||
runner = TerraformRunner(
|
||||
binary="no-such-binary", module_namespaces=("approved-modules",)
|
||||
)
|
||||
files = {"terraform/main.tf": MODULE_CALL}
|
||||
|
||||
token = MODULES_OPTED_IN.set(False)
|
||||
try:
|
||||
assert (await runner.validate(files)).message == NOT_OPTED_IN
|
||||
# Plain resources are untouched by the switch.
|
||||
plain = await runner.validate({"terraform/main.tf": "locals {}"})
|
||||
assert not plain.message.startswith("Refused")
|
||||
finally:
|
||||
MODULES_OPTED_IN.reset(token)
|
||||
|
||||
token = MODULES_OPTED_IN.set(True)
|
||||
try:
|
||||
opted = await runner.validate(files)
|
||||
assert not opted.message.startswith("Refused")
|
||||
finally:
|
||||
MODULES_OPTED_IN.reset(token)
|
||||
|
||||
|
||||
def test_the_gcp_bundle_names_its_modules_skill_for_the_roles_that_run_terraform():
|
||||
bundle = load_provider("gcp")
|
||||
roles = load_roles(AGENTS_DIR, bundle)
|
||||
|
||||
assert bundle.terraform_module_namespaces == ("terraform-google-modules",)
|
||||
with_skill = {name for name, role in roles.items() if role.modules_skill}
|
||||
assert with_skill == {"iac-author", "validator"}
|
||||
# The Skill is not among any role's Skills until an Execution opts in.
|
||||
assert all(
|
||||
bundle.terraform_modules_skill not in role.skills for role in roles.values()
|
||||
)
|
||||
|
||||
|
||||
def test_the_bundle_lists_modules_to_watch_from_its_approved_namespaces():
|
||||
bundle = load_provider("gcp")
|
||||
|
||||
assert bundle.terraform_modules_watch
|
||||
for module in bundle.terraform_modules_watch:
|
||||
namespace, _, provider = module.split("/")
|
||||
assert namespace in bundle.terraform_module_namespaces and provider == "google"
|
||||
@@ -148,6 +148,9 @@ def test_the_settings_a_check_names_are_read_from_its_statement():
|
||||
"template.scaling.min_instance_count",
|
||||
)
|
||||
assert named_settings("startup_cpu_boost is true") == ("startup_cpu_boost",)
|
||||
# A value in backticks is not a setting.
|
||||
assert named_settings("`enable_cdn` is `false`") == ("enable_cdn",)
|
||||
assert named_settings("`deletion_protection` is `true`") == ("deletion_protection",)
|
||||
# Values, roles and plain prose name no setting.
|
||||
assert named_settings("ingress is INGRESS_TRAFFIC_ALL") == ()
|
||||
assert named_settings("roles/run.invoker is granted to allUsers") == ()
|
||||
|
||||
72
tests/test_iac_modules.py
Normal file
72
tests/test_iac_modules.py
Normal file
@@ -0,0 +1,72 @@
|
||||
"""The IaC modules Skill: every module call validates against the pinned provider.
|
||||
|
||||
A module is usable only with provider versions its own requirements admit, and
|
||||
several of the organisation's modules do not admit the pinned one. Each reference's
|
||||
example is run through `terraform validate`, which downloads the module, so a
|
||||
version bump that breaks one is found here. With no network the test is skipped.
|
||||
"""
|
||||
|
||||
import re
|
||||
import shutil
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from app.config import Settings
|
||||
from app.providers import load_provider
|
||||
from app.tools.local import TerraformRunner
|
||||
from app.tools.modules import module_calls
|
||||
|
||||
SKILL = "google-cloud-iac-modules"
|
||||
SKILLS = Path(__file__).resolve().parent.parent / "skills"
|
||||
ROOT = SKILLS / SKILL
|
||||
VERSIONS = SKILLS / "google-cloud-iac-patterns" / "assets" / "versions.tf"
|
||||
REFERENCES = sorted((ROOT / "references").glob("*.md"))
|
||||
_HCL = re.compile(r"^```hcl\n(.*?)^```", re.MULTILINE | re.DOTALL)
|
||||
|
||||
needs_terraform = pytest.mark.skipif(
|
||||
shutil.which("terraform") is None, reason="terraform CLI not installed"
|
||||
)
|
||||
|
||||
|
||||
def _code(reference: Path) -> str:
|
||||
return "\n".join(_HCL.findall(reference.read_text(encoding="utf-8")))
|
||||
|
||||
|
||||
def test_every_reference_is_listed_and_calls_only_allowed_pinned_modules():
|
||||
bundle = load_provider("gcp")
|
||||
skill = (ROOT / "SKILL.md").read_text(encoding="utf-8")
|
||||
assert REFERENCES
|
||||
listed = set(re.findall(r"references/([\w-]+\.md)", skill))
|
||||
assert listed == {reference.name for reference in REFERENCES}
|
||||
for reference in REFERENCES:
|
||||
calls = module_calls({"main.tf": _code(reference)})
|
||||
assert calls, reference.name
|
||||
for call in calls:
|
||||
assert call.source.split("/")[0] in bundle.terraform_module_namespaces
|
||||
# The version the example uses is the one the Skill's table gives.
|
||||
assert call.version in skill, f"{reference.name}: {call.version}"
|
||||
|
||||
|
||||
def test_the_skill_names_the_provider_version_the_bundle_pins():
|
||||
pin = load_provider("gcp").terraform_providers["google"]
|
||||
skill = (ROOT / "SKILL.md").read_text(encoding="utf-8")
|
||||
assert f"{pin['source']} {pin['version']}" in skill
|
||||
|
||||
|
||||
@needs_terraform
|
||||
@pytest.mark.parametrize("reference", REFERENCES, ids=lambda path: path.stem)
|
||||
async def test_module_example_validates(reference: Path):
|
||||
bundle = load_provider("gcp")
|
||||
runner = TerraformRunner(
|
||||
plugin_cache_dir=Settings().terraform_plugin_cache(),
|
||||
module_namespaces=bundle.terraform_module_namespaces,
|
||||
)
|
||||
files = {
|
||||
"terraform/versions.tf": VERSIONS.read_text(),
|
||||
"terraform/main.tf": _code(reference),
|
||||
}
|
||||
result = await runner.validate(files)
|
||||
if result.message.startswith("terraform init failed"):
|
||||
pytest.skip("the module or the pinned provider could not be downloaded")
|
||||
assert result.message.startswith("terraform validate passed"), result.message
|
||||
@@ -10,9 +10,9 @@ from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from app.adk.fake_runtime import Call, FakeAgentRuntime
|
||||
from app.adk.fake_runtime import Call, FakeAgentRuntime, FakeDecider
|
||||
from app.adk.roles import load_roles
|
||||
from app.adk.runtime import RoleSpec
|
||||
from app.adk.runtime import Answer, RoleSpec
|
||||
from app.learning.curator import LESSON_CURATOR, curate
|
||||
from app.learning.evidence import group_candidates, identifiers, read_candidates
|
||||
from app.learning.proposals import (
|
||||
@@ -498,16 +498,166 @@ def test_lessons_that_cost_quality_or_save_nothing_are_not_shown_to_help(tmp_pat
|
||||
assert "nothing fell" in render(compare(base, same), base, same)
|
||||
|
||||
|
||||
def test_the_comparison_is_written_into_published_proposals_only(tmp_path):
|
||||
def test_the_comparison_is_written_only_for_lessons_in_the_skill(tmp_path):
|
||||
from app.learning.proof import record
|
||||
|
||||
skill = lessons_skill(tmp_path)
|
||||
issues = tmp_path / "issues"
|
||||
live = publish(approve(proposal(issues), issues), skill, today=DAY)
|
||||
waiting = proposal(issues, title="Another", evidence_key="zzz")
|
||||
gone = publish(
|
||||
approve(proposal(issues, title="Retired", evidence_key="yyy"), issues),
|
||||
skill,
|
||||
today=DAY,
|
||||
)
|
||||
retire(gone.id, skill)
|
||||
|
||||
recorded = record([live, waiting], "| a table |")
|
||||
recorded = record([live, waiting, gone], "| a table |", published(skill))
|
||||
|
||||
assert [p.id for p in recorded] == ["L-01"]
|
||||
assert parse(live.path).proof == "| a table |"
|
||||
assert parse(waiting.path).proof == ""
|
||||
# A retired lesson was not part of what was compared.
|
||||
assert parse(gone.path).proof == ""
|
||||
|
||||
|
||||
# --- lessons are read again when the Skills beside them change ---------------------------
|
||||
|
||||
|
||||
def test_a_changed_upstream_skill_is_flagged_until_the_lessons_are_reviewed(tmp_path):
|
||||
from app.learning.skill import mark_reviewed, upstream_changes
|
||||
|
||||
skill = lessons_skill(tmp_path)
|
||||
issues = tmp_path / "issues"
|
||||
publish(approve(proposal(issues), issues), skill, today=DAY)
|
||||
then = {"architecture": "aaa", "security": "bbb"}
|
||||
mark_reviewed(skill, then)
|
||||
|
||||
assert upstream_changes(skill, then) == []
|
||||
now = {"architecture": "aaa", "security": "ccc", "cost": "ddd"}
|
||||
assert upstream_changes(skill, now) == ["cost", "security"]
|
||||
|
||||
mark_reviewed(skill, now)
|
||||
assert upstream_changes(skill, now) == []
|
||||
|
||||
|
||||
def test_nothing_is_flagged_with_no_lessons_or_nothing_recorded(tmp_path):
|
||||
from app.learning.skill import mark_reviewed, upstream_changes
|
||||
|
||||
skill = lessons_skill(tmp_path)
|
||||
assert upstream_changes(skill, {"architecture": "aaa"}) == []
|
||||
mark_reviewed(skill, {"architecture": "aaa"})
|
||||
# No lesson is published, so there is nothing to review.
|
||||
assert upstream_changes(skill, {"architecture": "zzz"}) == []
|
||||
|
||||
|
||||
def test_the_published_lessons_were_reviewed_against_todays_vendored_skills():
|
||||
"""Syncing the vendored Skills changes what the lessons sit beside. This fails
|
||||
until a person has read each lesson again and run `curate_lessons reviewed`."""
|
||||
from app.learning.skill import upstream_changes, upstream_reviewed
|
||||
from app.providers import load_provider
|
||||
from eval.curate_lessons import upstream_versions
|
||||
|
||||
bundle = load_provider("gcp")
|
||||
skill = bundle.skills[bundle.lessons_skill].path
|
||||
|
||||
assert upstream_reviewed(skill), "run: python -m eval.curate_lessons reviewed"
|
||||
assert upstream_changes(skill, upstream_versions(bundle)) == []
|
||||
|
||||
|
||||
# --- what recurs inside a kind of problem ------------------------------------------------
|
||||
|
||||
|
||||
def addition(statement: str) -> dict:
|
||||
return {"type": "proposed_addition", "statement": statement, "serves": "NFR-1"}
|
||||
|
||||
|
||||
def test_the_same_setting_missed_in_several_executions_is_its_own_group():
|
||||
records = [
|
||||
record("run-1", addition("`deletion_protection` is true on the database")),
|
||||
record("run-2", addition("deletion_protection is enabled"), addition("x y")),
|
||||
record("run-3", addition("`min_tls_version` is TLS_1_2")),
|
||||
]
|
||||
|
||||
groups = {group.subject: group for group in group_candidates(records)}
|
||||
|
||||
# Every proposed Check is one broad group; the setting missed twice is another.
|
||||
assert len(groups[None].executions) == 3
|
||||
narrow = groups["deletion_protection"]
|
||||
assert len(narrow.executions) == 2 and narrow.kind == "proposed_addition"
|
||||
assert narrow.description == (
|
||||
"validation proposed a Check about `deletion_protection` that the design lacked"
|
||||
)
|
||||
assert narrow.key != groups[None].key
|
||||
# Seen in one Execution only, a setting is not a pattern.
|
||||
assert "min_tls_version" not in groups
|
||||
|
||||
|
||||
def test_a_resource_that_checks_keep_asking_too_much_of_is_its_own_group():
|
||||
def cannot(why: str) -> dict:
|
||||
return {
|
||||
"type": "revision",
|
||||
"deliverable": "target_architecture",
|
||||
"reason": f"Check K-1 cannot be implemented as written ({why}).",
|
||||
}
|
||||
|
||||
records = [
|
||||
record("run-1", cannot("example_database has no backup key argument")),
|
||||
record("run-2", cannot("example_database has no query access flag")),
|
||||
]
|
||||
|
||||
subjects = {group.subject for group in group_candidates(records)}
|
||||
|
||||
assert subjects == {None, "example_database"}
|
||||
|
||||
|
||||
async def test_a_group_about_one_setting_reaches_the_curator_past_triage(tmp_path):
|
||||
issues = tmp_path / "issues"
|
||||
approve(proposal(issues), issues) # a general lesson already exists
|
||||
records = [
|
||||
record("run-1", addition("`deletion_protection` is true")),
|
||||
record("run-2", addition("`deletion_protection` is true")),
|
||||
]
|
||||
groups = group_candidates(records)
|
||||
# Triage says the general lesson covers everything it is asked about.
|
||||
decider = FakeDecider(
|
||||
{group.key: Answer("L-01", 0.95) for group in groups if group.subject is None}
|
||||
)
|
||||
seen: list[str] = []
|
||||
|
||||
def turn(task):
|
||||
seen.extend(group["what_happened"] for group in task.context["groups"])
|
||||
return [Call("finish")]
|
||||
|
||||
runtime = FakeAgentRuntime({LESSON_CURATOR: [turn]})
|
||||
|
||||
await curate(
|
||||
runtime,
|
||||
CURATOR,
|
||||
groups,
|
||||
executions=2,
|
||||
folder=issues,
|
||||
decider=decider,
|
||||
)
|
||||
|
||||
assert seen == [
|
||||
"validation proposed a Check about `deletion_protection` that the design lacked"
|
||||
]
|
||||
|
||||
|
||||
def test_a_retired_lesson_is_not_published_again(tmp_path):
|
||||
"""Retiring left the proposal approved, so the next publish put the lesson
|
||||
back: L-04 returned to the Skill that way on 2026-10-10."""
|
||||
from dataclasses import replace
|
||||
|
||||
skill = lessons_skill(tmp_path)
|
||||
issues = tmp_path / "issues"
|
||||
made = publish(approve(proposal(issues), issues), skill, today=DAY)
|
||||
retire(made.id, skill)
|
||||
retired = write(replace(parse(made.path), retired="2026-10-09"), issues)
|
||||
|
||||
assert parse(retired.path).retired == "2026-10-09"
|
||||
assert not retired.approved
|
||||
with pytest.raises(NotApproved, match="was retired on 2026-10-09"):
|
||||
publish(retired, skill)
|
||||
assert published(skill) == {}
|
||||
|
||||
@@ -294,6 +294,7 @@ def test_local_tools_are_built_by_name_with_their_tier():
|
||||
"terraform_validate",
|
||||
"terraform_plan",
|
||||
"terraform_schema",
|
||||
"terraform_module",
|
||||
}
|
||||
with pytest.raises(KeyError, match="terraform_apply"):
|
||||
local_tools(["terraform_apply"], TerraformRunner())
|
||||
|
||||
203
tests/tools/test_modules.py
Normal file
203
tests/tools/test_modules.py
Normal file
@@ -0,0 +1,203 @@
|
||||
"""Terraform modules: which may be used, and what one accepts (iteration 8)."""
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
|
||||
from app.tools import modules
|
||||
from app.tools.local import TerraformRunner
|
||||
from app.tools.modules import ModuleLookup, admits, check_module_sources, module_calls
|
||||
|
||||
ALLOWED = ("example-modules",)
|
||||
GOOD = """
|
||||
module "network" {
|
||||
source = "example-modules/network/cloud"
|
||||
version = "1.2.3"
|
||||
|
||||
subnets = [
|
||||
{
|
||||
source = "not the module's source"
|
||||
version = "nor its version"
|
||||
}
|
||||
]
|
||||
}
|
||||
"""
|
||||
|
||||
|
||||
def refused(code: str, allowed=ALLOWED) -> str:
|
||||
result = check_module_sources({"terraform/main.tf": code}, allowed)
|
||||
return result.message if result else ""
|
||||
|
||||
|
||||
def test_a_module_call_is_read_with_its_own_source_and_version():
|
||||
(call,) = module_calls({"main.tf": GOOD})
|
||||
|
||||
assert (call.name, call.source, call.version) == (
|
||||
"network",
|
||||
"example-modules/network/cloud",
|
||||
"1.2.3",
|
||||
)
|
||||
|
||||
|
||||
def test_a_module_from_an_allowed_namespace_at_an_exact_version_is_accepted():
|
||||
assert refused(GOOD) == ""
|
||||
assert refused(GOOD.replace("network/cloud", "network/cloud//modules/nat")) == ""
|
||||
assert refused('resource "thing" "x" {}') == ""
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"source",
|
||||
[
|
||||
"someone-else/network/cloud",
|
||||
"git::https://example.com/network.git",
|
||||
"github.com/example-modules/network",
|
||||
"./modules/network",
|
||||
"../shared",
|
||||
"https://example.com/network.zip",
|
||||
"",
|
||||
],
|
||||
)
|
||||
def test_any_other_source_is_refused(source):
|
||||
message = refused(GOOD.replace("example-modules/network/cloud", source))
|
||||
|
||||
assert message.startswith("Refused") and "example-modules" in message
|
||||
|
||||
|
||||
@pytest.mark.parametrize("version", ["~> 1.2", ">= 1.0", "1.2", "latest", ""])
|
||||
def test_a_version_that_is_not_exact_is_refused(version):
|
||||
assert "one exact version" in refused(GOOD.replace("1.2.3", version))
|
||||
|
||||
|
||||
def test_with_no_namespace_configured_every_module_is_refused():
|
||||
assert "none are configured" in refused(GOOD, allowed=())
|
||||
|
||||
|
||||
def test_a_module_in_json_syntax_is_refused():
|
||||
result = check_module_sources(
|
||||
{"terraform/main.tf.json": '{"module": {"x": {"source": "a/b/c"}}}'}, ALLOWED
|
||||
)
|
||||
|
||||
assert result and result.message.startswith("Refused")
|
||||
|
||||
|
||||
async def test_validation_refuses_a_disallowed_module_before_terraform_runs():
|
||||
runner = TerraformRunner(binary="no-such-binary", module_namespaces=ALLOWED)
|
||||
|
||||
result = await runner.validate(
|
||||
{"terraform/main.tf": GOOD.replace("example-modules", "someone-else")}
|
||||
)
|
||||
|
||||
assert result.message.startswith("Refused: module")
|
||||
|
||||
|
||||
def test_a_version_constraint_is_read():
|
||||
assert admits(">= 6.37.0, < 9", "8.6.0")
|
||||
assert not admits(">= 6.2, < 8", "8.6.0")
|
||||
assert admits("~> 3.0", "3.7.2") and not admits("~> 3.0", "4.0.0")
|
||||
assert admits("~> 3.1.2", "3.1.9") and not admits("~> 3.1.2", "3.2.0")
|
||||
assert admits("", "8.6.0")
|
||||
|
||||
|
||||
REGISTRY_ANSWER = {
|
||||
"version": "1.2.3",
|
||||
"root": {
|
||||
"inputs": [
|
||||
{"name": "labels", "type": "map(string)", "description": "Labels."},
|
||||
{
|
||||
"name": "name",
|
||||
"type": "string",
|
||||
"description": "Name.",
|
||||
"required": True,
|
||||
},
|
||||
],
|
||||
"outputs": [{"name": "id"}],
|
||||
"provider_dependencies": [{"name": "cloud", "version": ">= 6, < 8"}],
|
||||
},
|
||||
"submodules": [
|
||||
{
|
||||
"path": "modules/nat",
|
||||
"inputs": [{"name": "router", "type": "string", "required": True}],
|
||||
"provider_dependencies": [{"name": "random", "version": "~> 3.0"}],
|
||||
}
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def registry(monkeypatch):
|
||||
asked: list[str] = []
|
||||
|
||||
class Client:
|
||||
def __init__(self, **_):
|
||||
pass
|
||||
|
||||
async def __aenter__(self):
|
||||
return self
|
||||
|
||||
async def __aexit__(self, *_):
|
||||
return False
|
||||
|
||||
async def get(self, url):
|
||||
asked.append(url)
|
||||
if "missing" in url:
|
||||
return httpx.Response(404, json={"errors": ["Not Found"]})
|
||||
return httpx.Response(200, json=REGISTRY_ANSWER)
|
||||
|
||||
monkeypatch.setattr(modules.httpx, "AsyncClient", Client)
|
||||
return asked
|
||||
|
||||
|
||||
async def test_a_modules_inputs_come_back_required_first_with_its_outputs(registry):
|
||||
lookup = ModuleLookup(namespaces=ALLOWED, pinned={"cloud": "7.1.0"})
|
||||
|
||||
reply = (await lookup.describe("example-modules/network/cloud", "1.2.3")).message
|
||||
|
||||
assert reply.index("- name (required") < reply.index("- labels (optional")
|
||||
assert "Outputs: id" in reply and "Submodules: modules/nat" in reply
|
||||
assert "NOT USABLE" not in reply
|
||||
assert registry == [f"{modules.REGISTRY}/example-modules/network/cloud/1.2.3"]
|
||||
# The same module is not fetched twice.
|
||||
await lookup.describe("example-modules/network/cloud", "1.2.3", find="name")
|
||||
assert len(registry) == 1
|
||||
|
||||
|
||||
async def test_a_module_the_pinned_provider_does_not_satisfy_is_called_out(registry):
|
||||
lookup = ModuleLookup(namespaces=ALLOWED, pinned={"cloud": "8.6.0"})
|
||||
|
||||
reply = (await lookup.describe("example-modules/network/cloud")).message
|
||||
|
||||
assert "NOT USABLE: it requires cloud >= 6, < 8" in reply
|
||||
assert "pinned to cloud 8.6.0" in reply
|
||||
|
||||
|
||||
async def test_a_submodule_is_described_by_its_own_inputs(registry):
|
||||
lookup = ModuleLookup(namespaces=ALLOWED, pinned={"cloud": "8.6.0"})
|
||||
|
||||
reply = (
|
||||
await lookup.describe("example-modules/network/cloud//modules/nat")
|
||||
).message
|
||||
|
||||
assert "- router (required" in reply and "- name" not in reply
|
||||
assert "It also uses the random provider" in reply
|
||||
missing = await lookup.describe("example-modules/network/cloud//modules/vpn")
|
||||
assert "has no submodule" in missing.message and "modules/nat" in missing.message
|
||||
|
||||
|
||||
async def test_find_narrows_the_inputs(registry):
|
||||
lookup = ModuleLookup(namespaces=ALLOWED)
|
||||
|
||||
reply = (
|
||||
await lookup.describe("example-modules/network/cloud", find="label")
|
||||
).message
|
||||
|
||||
assert "- labels" in reply and "- name (" not in reply
|
||||
|
||||
|
||||
async def test_a_module_outside_the_allowed_namespaces_is_not_looked_up(registry):
|
||||
lookup = ModuleLookup(namespaces=ALLOWED)
|
||||
|
||||
reply = (await lookup.describe("someone-else/network/cloud")).message
|
||||
|
||||
assert reply.startswith("Refused") and registry == []
|
||||
assert (
|
||||
"no module" in (await lookup.describe("example-modules/missing/cloud")).message
|
||||
)
|
||||
Reference in New Issue
Block a user