18 Commits

Author SHA1 Message Date
b66d18fe94 docs: record the first run of the work breakdown structure and of stated choices reaching Checks
Some checks failed
validation / verify (push) Failing after 10s
Case 08: a plan of 9 work packages and 15 activities, 7.2 weeks against a
10-week window, with the customer's carrier circuit on the critical path. The
stated topology was built this time. The owner keeps the estimates as they
are: one experienced engineer, no contingency.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-11 21:04:28 +01:00
f54af24169 feat: a work breakdown structure with a computed timeline (iteration 10)
Some checks failed
validation / verify (push) Failing after 10s
A new Deliverable in the packaging Phase, produced by a delivery planner
after validation.

- The planner writes the plan as data: work packages that name the Elements
  they deliver, and activities with days, what each follows, and whether the
  team or the customer owns it.
- Code checks the plan against the design: every Element belongs to a work
  package, and the activities can be scheduled.
- Code computes the schedule, with no more of the team's activities at once
  than the team has people, and the critical path.
- Code writes the WBS dictionary (a work package is done when the Checks on
  its Elements pass), the activity sequence and a timeline on a relative axis
  from Day 0.
- The plan is checked against the delivery window from the agreed scope; over
  it, the Deliverable says by how much and names the critical path.
- With a start date it also gives calendar dates and a Mermaid Gantt chart.
- The timeline is added to the solution guide, and the plan's length is in
  execution.json and the packaging Approval.

Not run with real models.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-11 19:54:17 +01:00
0f80cb642f feat: a stated choice must reach a requirement, and only pinned providers (iteration 9 step 3)
Some checks failed
validation / verify (push) Failing after 11s
Case 08 named the customer's stated topology in its design and did not build
it; every Check passed because none asked for it.

- The catalogue marks the 26 fields that bind a design. The agreed scope lists
  the ones the customer stated; what was assumed for them does not bind.
- A requirement says what it comes from. A submission of requirements is
  refused when one of the customer's own requirements, or a stated binding
  field, is named by none, or when the requirement carrying a choice is not a
  constraint with a condition. The existing chain then owes it a Check.
- Generated code may use only the providers the bundle pins: a resource or a
  required_providers entry of any other is refused before Terraform runs.
- The guide opens with how much of the design the customer stated, how much
  was assumed and how much is unknown.

Not run with real models.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-11 19:36:12 +01:00
c26b744b26 fix: a product the customer's scope spec names is not a leak; record the first scoping runs
Case 08 failed requirements_name_no_products for "Shared VPC", which the
spec's stated topology names. Records cases 03 and 08 on the scoping branch.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-11 19:27:51 +01:00
545097530b feat: scoping is the first Phase, completed in conversation (iteration 9 step 2)
Some checks failed
validation / verify (push) Failing after 10s
Every Execution now begins by agreeing the scope, before requirements.

- A new Phase and Deliverable, produced by a scope analyst with two tools:
  scope_read shows what is settled and what is not; scope_set records fields
  with where each value came from (the request, the customer's answer, or an
  assumption with its reason). Code checks each value against the catalogue.
- With someone present the analyst asks for what is missing; with nobody
  present it assumes it, visibly. With no spec it drafts one from the request.
  A value the customer stated in the file is changed only by their own answer.
- A submission cannot leave an essential field unknown. Code writes the
  completed spec, the data every later Specialist reads, and the information
  register, from what was recorded.
- The spec's status follows the Execution: under review, approved, then
  locked as a Baseline. A Change request starts from the delivered scope.
- The requirements analyst derives from the agreed scope and no longer asks
  for what it settles.

About 80 tests assumed requirements came first; tests/scoped.py runs scoping
ahead of a test's own script, and tests about order and counts are updated.
Not run with real models.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-11 18:17:32 +01:00
afe78640f8 feat: start an Execution from a scope spec (ADR-0008, iteration 9 step 1)
Some checks failed
validation / verify (push) Failing after 10s
A scope spec is a YAML file of what the customer wants and the facts a design
depends on, complete or partly filled. It sits beside the Intent, which stays
in the customer's words.

- skills/scoping holds a provider-neutral catalogue of 63 fields; the Cloud
  provider's bundle supplies the values it allows for the fields left to it.
- app/scope.py reads a spec against the catalogue with no model: it refuses an
  unknown field or a value of the wrong type, and yields what is stated, what
  is left to the agent, what is unknown and how pressing each gap is. A field
  may say ask, decide or not_applicable.
- ExecutionEngine.start(scope=...), /generate, A2A metadata and evaluation
  cases accept one. Its statement is the request, its engagement reference
  names the Customer case, and its run options apply. A pre-approved start is
  refused when an essential field is not settled.
- The spec as supplied is kept unaltered beside a completed copy with
  assumptions, gaps, provenance, readiness and a status.
- Every Specialist is shown the spec and given the Skill: a stated choice
  binds, exclusions are out of scope.
- Covers workloads and platform foundations; case-08-landing-zone starts from
  a benchmark spec.

Plans for scoping (iteration 9) and the work breakdown structure (iteration
10, nothing built), and the design spec they come from. Not run with real
models.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-11 17:53:00 +01:00
a48468d477 feat: what a request does not say is a question for the customer
Some checks failed
validation / verify (push) Failing after 11s
A pillar's checklist item the request gives no information about was marked
"not addressed", which reads as a fault in the design. It is missing
information. The checklist review gains a fourth outcome, to confirm with the
customer, which must carry the question to ask. The questions are written
into the design recommendations and the guide, and to customer-questions.md;
the evaluation's judged check counts such an item as accounted for.

Records the owner's decisions of 2026-10-10 and the vendor's answers on Jev's
retention, training, context and rate limits (iteration 5 step 1), and the
owner's labels, which showed the judged question was wrong, not the judges.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-10 19:30:12 +01:00
f9cc34817b feat: lesson L-10 approved and published (Pub/Sub persistence regions)
Held for thin evidence, then its subject caused a Revision again in case 06.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-10 16:01:11 +01:00
7ee7054523 docs: record case 06 passing after the verdict and naming fixes
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-10 15:23:34 +01:00
c4c8a1f94e fix: a Check is judged by its own words, and a wrong verdict can be disputed
Some checks failed
validation / verify (push) Failing after 10s
Case 06 reached its Revision limit because the validator failed a Check that
a role is granted, for the identity also holding other roles, and the IaC
author could only answer by recording the Check as unimplementable. The
validator is told what its own words require; the author is told to dispute
such a verdict and change nothing.

The evaluation's naming standard for case 06 accepted only a variable inside
each name; it now accepts names built from a local as well.

Records the reruns: case 04 passed at 12 of 12, case 06 ended with warnings.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-10 14:40:31 +01:00
135401e41b feat: module follow-ups, and L-07 reworded
- A Check met through a module is met by a value in the code: the modules
  Skill tells the author to set every input a Check depends on.
- scripts/check-terraform-modules.py reports catalogued modules with a newer
  version, and watched modules that can now be used with the pinned provider.
- L-07 no longer mentions a low-carbon location, which led to a Check about a
  region's carbon score that code cannot show. Reworded with the owner's
  approval.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-10 13:34:45 +01:00
81ac135cd9 fix: what only the provider publishes is outside code, not a condition
A requirement for a "low-carbon region" was written as a condition for code
to meet, and came back in at least five runs as a gap, an unverifiable Check
or review noise. The requirements-chain Skill and the two roles that write
conditions now put a carbon rating or a service level under outside_code;
the condition is the choice configuration can show, such as the region set.

Records the first runs with lessons L-07 to L-09: the faults they name did
not recur, and Revisions did not fall.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-10 13:31:48 +01:00
5feaaa6271 feat: lessons from what recurs about one setting, and three more approved
Some checks failed
validation / verify (push) Failing after 10s
Evidence was grouped only by the kind of problem, and a group gets one lesson,
so what kept recurring inside "validation proposed a Check" could not be
seen. A proposed or unimplementable Check is now also counted under each
provider setting or resource type it names; a subject seen in two or more
Executions is its own group and reaches the curator past triage.

Over 32 Executions that gave five proposals. The owner approved three, now
published: L-07 location Checks, L-08 Cloud SQL backup encryption, L-09
backend service capabilities. L-10 is held for more evidence and L-11
rejected.

Also: retiring a lesson marks its proposal, so publish no longer brings a
retired lesson back. L-04 had returned to the Skill that way.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-10 12:47:18 +01:00
ee1ba38867 feat: a design-time coverage review, measured and left off
A reviewer role reads the requirements and recommendations against the Checks
when the Target architecture is first submitted. Three runs of case 03: it did
not stop the validator sending the design back, and the designs it reviewed
ended with 87 and 93 Checks against 52, so they cost more. It stays behind
DESIGN_COVERAGE_REVIEW, off (iteration 6 step 13).

Also: the schema review no longer reads `true` or `false` in backticks as a
setting name.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-10 12:33:06 +01:00
1cf1234143 fix: an unimplementable Check is corrected everywhere it applies, in one Revision
The reason sent back to the target architect says to read every Check against
it, and the IaC author records every Check that cannot be met in one
submission. Records the investigation of why the Target architecture is
revised: two causes, about half each (iteration 6 step 12).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-10 11:51:46 +01:00
71da0ed504 chore: housekeeping from the runs of 2026-10-09
Some checks failed
validation / verify (push) Failing after 12s
- An Execution's files are written as each Deliverable is submitted, marked
  in_progress, so a killed process or one waiting for its user leaves them on
  disk. A write removes files an earlier write left that it no longer has.
- A question about delivered work is answered from that Execution's solution
  guide by the reply writer; a question about the service is answered as
  before. Nothing is started for either.
- Lessons: prove writes only for lessons the Skill holds; the Skill records
  the vendored Skill versions the lessons were read against, status names any
  that changed, and a test fails until they are reviewed.
- Four more code patterns: Firestore, BigQuery, Eventarc and GKE.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-10 11:44:38 +01:00
10d23a5f91 docs: record the first runs with and without Terraform modules
Case 03's request once each way, both at 100%. Opted in, a module was used
for private Cloud SQL only and 14 Checks were met through its inputs. The
difference in time and cost between the two runs is their Revisions, not
the modules.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 22:47:09 +01:00
ef37f59bad feat: opt-in published Terraform modules from approved sources (iteration 8)
Infrastructure code is plain resources by default. An Execution may opt in
with terraform_modules; the deployment default is TERRAFORM_MODULES, off.

- A module is accepted only from the registry namespaces the provider bundle
  lists (terraform-google-modules), at one exact version. Any other source is
  refused before Terraform runs; until now nothing stopped generated code
  naming any source for terraform init to download.
- terraform_module looks up a module's inputs, outputs and submodules from
  the registry and says when it cannot be used with the pinned provider.
- skills/google-cloud-iac-modules: when a module fits, and four modules with
  examples a test validates against hashicorp/google 8.6.0.
- Opted in, the IaC author and validator get the Skill and the lookup. Not
  opted in, they get neither and a module block is refused in code.
- A Change request follows its Baseline. execution.json records the choice.
- case-07 runs case 03's request with modules opted into.

Azure (aztfm) and AWS (terraform-aws-modules) sources are recorded in the
plan for when those Cloud providers are added. No case has run with this.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 22:09:29 +01:00
131 changed files with 8793 additions and 190 deletions

View File

@@ -13,6 +13,9 @@ 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. |
| 9 | `iter-09-scoping/` | steps 1–3 and 6 built on 2026-10-11; cases 03 and 08 ran on steps 1 and 2; steps 4 and 5 planned; ADR-0008 accepted | An engagement is scoped from a scope spec: a structured file, complete or partly filled, read against a catalogue in code, completed in conversation and approved before requirements begin. Covers workloads and platform foundations. |
| 10 | `iter-10-work-breakdown/` | steps 1–4 built on 2026-10-11, without milestones; not run with real models | A work breakdown structure as a Deliverable: work packages traced to Elements and Checks, activities in sequence, and a timeline on a relative day axis computed and drawn by code. |
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.

View File

@@ -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.

View File

@@ -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.

View File

@@ -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.

View 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.

View 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).

View File

@@ -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`) |

View 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.

View File

@@ -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).

View File

@@ -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.

View File

@@ -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.

View File

@@ -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.

View File

@@ -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.

View 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`.

View 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.

View File

@@ -0,0 +1,34 @@
# Plan Map
**Iteration:** 9, Scoping
**Intent:** Scope an engagement from a scope spec: a structured file that may arrive complete, partly filled or not at all, completed in conversation and approved by the customer before requirements begin. So that a design's quality no longer rests on what the agents had to assume.
**Status:** steps 1, 2, 3 and 6 built on 2026-10-11; steps 1 and 2 ran in cases 03 and 08; step 3 not run; steps 4 and 5 planned
**This directory covers:** steps 1 to 6
## Sources of truth
- `docs/adr/0008-scoping-starts-from-a-scope-spec.md`: the decisions.
- `.scratch/scoping-and-work-breakdown/spec.md`: the design, including the draft spec, the owner's own example and how the two were combined.
- `skills/scoping/assets/catalogue.yaml`: every field a scope spec may hold.
## Status
| Step | What | Status |
|---|---|---|
| 1 | The catalogue, reading and validating a spec, the gap list, the two files beside the Intent, run options from the spec, the spec shown to every Specialist | built 2026-10-11 (`steps/step-1.md`); not run with real models |
| 2 | The conversation that fills gaps and writes answers into the completed copy; scoping as a Phase with its Deliverable and Approval; a spec drafted from a sentence | built 2026-10-11 (`steps/step-2.md`); not run with real models |
| 3 | Requirements traced to the customer's requirement ids and to spec fields, in `requirements.json`, with a stated choice refused unless a requirement carries it; readiness in the solution guide | built 2026-10-11 (`steps/step-3.md`); not run with real models |
| 4 | An edited spec as a Change request, compared field by field | planned |
| 5 | Evaluation cases as specs, replacing answers matched by pattern | planned; `case-08-landing-zone` is the first |
| 6 | The status `BASELINE_LOCKED` set when the Execution completes | built with step 2 |
## Dependency graph
- Step 1: no dependencies
- Step 2: depends on step 1
- Step 3: depends on step 1
- Step 4: depends on step 1, iteration 7
- Step 5: depends on step 1
- Step 6: depends on step 2
The work breakdown structure is iteration 10 and uses the spec's `delivery` section from step 1.

View File

@@ -0,0 +1,20 @@
# Step 1 — Implementation Detail
Built on 2026-10-11. **Not run with real models.**
1. **The catalogue** is `skills/scoping/assets/catalogue.yaml`: 63 fields as dotted paths, each with a type, a tier (which may differ by kind of engagement), the question to ask and guidance for a default. It names no Cloud provider. `providers/gcp.yaml` adds, under `scope.values`, what Google Cloud allows for the four fields left to a provider: the provider itself, encryption type, network topology and the kind of hybrid connection.
2. **Reading a spec** is `read_scope` in `app/scope.py`, with no model. It refuses, naming every problem: YAML that does not parse, a field the catalogue does not have, a value of the wrong type, and an engagement reference and a customer case that disagree. A whole section may be marked `ask`, `decide` or `not_applicable` at once.
3. **What it yields:** the stated values; the gaps, most pressing first, each with its question and a severity (HIGH essential, MEDIUM important, LOW optional); the assumptions, one per `decide`, with the default to take and what a wrong one would change; a count of each; and a status.
4. **Starting from a spec:** `ExecutionEngine.start(scope=...)`, `scope` in the `/generate` body and in A2A metadata, and on an evaluation case. The spec's statement is the request when none is given, its engagement reference names the Customer case, and its `run` section applies where the caller gave nothing. A pre-approved start is refused when an essential field is not settled.
5. **The two files** are written beside the Intent: `NNN.scope.yaml`, the spec as supplied, byte for byte; and `NNN.scope.completed.yaml`, every field of the catalogue with the agent's sections (`inferred_assumptions`, `discovery_gaps`, `provenance`, `readiness`) and `metadata.status`. `history.json` names both. A completed copy can be supplied again as a spec; the agent's sections are replaced.
6. **Every Specialist is shown the spec** as `scope` in its context (what is stated, what is theirs to decide, what is unknown) and is given the scoping Skill. The protocol says a stated choice binds, an exclusion is out of scope, and the customer's requirement ids are to be named. The requirements analyst is told to derive from it and ask only for what it leaves unknown.
7. **For a person:** `python -m app.scope check <file>` says what a spec settles and what it lacks; `python -m app.scope template <kind>` prints one to fill in.
8. **A benchmark spec:** `eval/datasets/specs/landing-zone.yaml`, a fictional regulated payment platform, and `case-08-landing-zone` which starts from it.
Interim, until step 2 (now built; see `step-2.md`):
- **Gaps are asked by the requirements analyst,** who is handed them, not by a scoping Phase. Answers are not written back into the completed copy.
- **Status** is set once, at the start: `DRAFT` with gaps to ask, `UNDER_REVIEW` when complete and someone is present, `APPROVED` when pre-approved. `BASELINE_LOCKED` is not set.
- **A caller's `pre_approved` wins over the spec's** when both are given. `/generate` is always pre-approved.
Tests: `tests/test_scope.py` (18), `tests/execution/test_scope_spec.py` (8).

View File

@@ -0,0 +1,55 @@
# Step 2 — Implementation Detail
Built on 2026-10-11. **Not run with real models.**
1. **Scoping is the first Phase.** `PhaseId.SCOPING` comes before requirements discovery, with one Deliverable, `scope`, produced by a new Specialist, the scope analyst (`agents/scope-analyst.md`). Requirements depend on it. Every Execution now begins with it, whether or not a spec was supplied, and the customer approves it before requirements begin.
2. **The scope analyst completes the spec with two tools** (`app/tools/scoping.py`). `scope_read` shows what is settled and what is not, with the question to ask for each. `scope_set` records fields, each with where its value came from: `request` (the customer's request says it), `answered` (they said so in conversation) or `assumed` (the analyst chose, and must say why). Code checks every value against the catalogue as it is recorded.
3. **What the customer stated in the file stays.** The analyst cannot overwrite a supplied value by assumption; only the customer's own answer changes it.
4. **The conversation.** With someone present the analyst asks, through `needs_input`, for the essential fields and the important ones that most change a design, up to eight at a time. An answer is recorded as answered; "you decide" becomes an assumption; a skipped field stays unknown. With nobody present it assumes the essential and important fields from the catalogue's guidance and what the request implies.
5. **A spec drafted from a sentence.** With no spec supplied the analyst starts from an empty one, records what the request states and settles the rest the same way.
6. **A submission cannot leave an essential field unknown.** It is refused, naming the fields.
7. **The Deliverable is written by code from what was recorded.** The analyst writes the scope statement. Code writes the two files (`scope.yaml`, the completed spec; `scope.json`, what every later Specialist reads) and appends the information register, the assumptions with what each would change, and what is still to confirm.
8. **Every later Specialist reads the agreed scope**, as `scope` in its context: what the customer stated, what was assumed for them (shown apart), and what is unknown. The requirements analyst derives from it and no longer asks for what it settles.
9. **Status is kept current** in the Execution's `scope.yaml` and in the copy beside the Intent: `UNDER_REVIEW` once submitted, `APPROVED` when the Phase is approved, `BASELINE_LOCKED` when the Execution completes (which closes step 6). `execution.json` carries the status and the readiness count.
10. **A Change request starts from the scope that was delivered,** with where each value came from, and the analyst records only what the change reaches. A Baseline delivered before scoping existed has no scope; the analyst then completes one from the change and the delivered requirements.
11. **The Approval summary** for scoping says how much was assumed and what is unknown.
What it changed elsewhere:
- About 80 existing tests assumed requirements came first. `tests/scoped.py` holds helpers that run scoping ahead of a test's own script, so tests about later Phases start where they always did. Tests about order, counts and first prompts were updated to the new truth.
- `workflow.yaml` gains the Phase.
Not done here:
- **No real model has run the scope analyst.** How well it drafts from a sentence, how many questions it asks, and what it costs are unknown. Every evaluation case now begins with it.
- **Answers are parsed by the model**, not by code, before `scope_set` checks their type. Nothing reads a value back to the customer other than the draft they approve.
- A re-supplied file part-way through a conversation is not handled; the customer answers in chat.
Tests: `tests/execution/test_scope_spec.py` (12), and the existing suites as updated.
## First runs with real models, 2026-10-11
Two cases side by side (`20261011T172837Z` case 03, `20261011T172840Z` case 08). Both completed.
| | Case 03, a one-sentence request | Case 08, the landing-zone spec |
|---|---|---|
| Score | 100% | 91%; the one failure was the evaluation's, now fixed |
| Minutes | 38 | 55 |
| Cost, about | $5.42 | $8.76 |
| Revisions | 1 of the Target architecture | 2 of the Target architecture, 1 of the code |
| The scope analyst | 64 seconds, 12 requests, $0.07 | 96 seconds, 9 requests, $0.08 |
| The scope | 6 stated, 21 assumed | 44 stated, 11 assumed, 4 not applicable |
| The design | 22 Elements, 81 Checks | 49 Elements, 101 Checks, 718 lines of Terraform |
**Scoping works and is cheap:** about a minute and under ten cents. From one sentence the analyst recorded the six things the sentence says as the customer's and 21 as assumptions, each with a reason; nothing was presented as stated that was not. No essential field was left unknown in either.
**The landing zone, the agent's first platform foundation, came out as one:** folders, organisation policies, a service perimeter, an interconnect with four attachments, routers, customer-managed keys, workload identity federation for the pipelines, a workforce pool for sign-in, audit sinks. The customer's four requirement ids are each cited in the requirements. Nothing excluded was built: no container workloads. Regions and encryption are as stated. Sixteen questions for the customer were written out.
**What it shows is missing:**
- **A stated choice is not checked.** The spec says `shared_vpc_hub_and_spoke`. The design names a "Spoke Shared VPC" and builds a transit network and a spoke network, with no Shared VPC host project and nothing connecting hub to spoke. All 101 Checks passed, because no Check asks for the topology the customer stated. "A stated choice binds" is an instruction; nothing in code holds a design to it. This is what step 3 has to close: a stated field that shapes the design must be traceable to a Check.
- **The code brought in a provider the bundle does not pin.** A `github_repository` Element led to `integrations/github` in the Terraform. Validation downloads whatever provider the code names, as it once did modules.
- **The scope statement added an exclusion the customer did not state** (changes to on-premises systems). The analyst is told to use only what the spec holds.
- **The evaluation scored a stated choice as a leaked product.** "Shared VPC" in the requirements failed `requirements_name_no_products`, though the customer's spec names that topology. The check now counts what the spec states as the customer's.
Case 03's cost and its one Revision are in the range seen before scoping existed; one run cannot say what scoping changed downstream.

View File

@@ -0,0 +1,40 @@
# Step 3 — Implementation Detail
Built on 2026-10-11. **Not run with real models.**
## What a stated choice now has to reach
Case 08 showed a stated topology named in a design and not built, with every Check passed. A stated choice was an instruction; nothing held a design to it.
1. **The catalogue marks the fields that bind a design** (`binds: true`, 26 of them): regions and residency, availability and recovery targets, compliance frameworks and classification, encryption, audit logging, every networking field, identity, environments, and required and forbidden products.
2. **The agreed scope lists the binding fields the customer stated,** as `binding` in `scope.json`. A field assumed for them is not among them: an assumption is not the customer's decision.
3. **A requirement says what it comes from,** in `from`: the customer's own requirement ids and the scope fields it carries.
4. **A submission of requirements is refused** (`_carries_the_scope` in `app/workflows/chain.py`) when:
- one of the customer's own requirements is named by no requirement;
- a binding field is named by no requirement;
- a requirement that carries a binding field is not non-functional, or has no entry in `conditions`.
5. **From there the existing chain does the rest.** A non-functional requirement's conditions each need a Check on the Target architecture, and validation gives each Check a verdict. So a stated choice now reaches a Check, in code, at every link.
What this does not prove: that the condition the analyst writes says what the customer meant, or that the Check the architect writes verifies it. It guarantees a stated choice cannot be silently dropped; whether it is honoured well is still judged by the validator.
## Readiness in the guide
The packager is told to open the executive summary with what the design rests on: how much the customer stated, how much was assumed, how much is unknown. An instruction, not a check.
## Also closed, from the same run
- **Only the pinned providers.** `check_providers` in `app/tools/local.py` refuses, before Terraform runs, a resource or data source of a provider the bundle does not pin, and a `required_providers` entry for one. The target architect is told that something outside the Cloud provider's own provider is not an Element. A module's own providers are untouched: they are declared inside the module.
- **The scope statement names only the customer's exclusions.**
Not done: `intent.exclusions` are free text, so nothing in code checks that an excluded thing was not built. The Specialists are told; in case 08 they complied.
Tests: `tests/execution/test_requirements_chain.py` (6 more), `tests/tools/test_local.py` (5 more).
## First run with real models, 2026-10-11
`case-08-landing-zone` again, results `20261011T185421Z`: completed, 91%, 60 minutes, about $11.94.
- **The stated topology was built this time.** `networking.topology` is carried by NFR-2, whose first condition is that a Shared VPC host project is connected to service projects across the environment tiers. The code has a host project and the connections. The run before had neither and passed every Check.
- **Only the pinned provider is in the code.** The run before brought in the GitHub provider.
- **It cost more:** $11.94 against $8.76, with three Revisions of the Target architecture and three of the code, against two and one. Two of them were two Checks that contradicted each other on one key's role, sending the code back and forth before the design was corrected. That is the design's fault, not this step's, but a stricter chain gives a large design more to get wrong.
- **One evaluation check failed, and it is a real finding:** the requirements name "Cloud KMS". The customer asked for keys they control; the product was the analyst's addition.

View File

@@ -0,0 +1,23 @@
# Plan Map
**Iteration:** 10, Work breakdown structure
**Intent:** Deliver a plan for building the Target architecture: work packages traced to its Elements and Checks, activities in sequence, and a timeline on a relative day axis that code computes and draws.
**Status:** steps 1 to 4 built on 2026-10-11, without milestones; not run with real models
**This directory covers:** steps 1 to 4
## Sources of truth
- `.scratch/scoping-and-work-breakdown/spec.md`, section "The work breakdown structure".
- `docs/adr/0005-the-target-architecture-is-an-explicit-graph.md`: the ids it traces to.
- Iteration 9 step 1: the scope spec's `delivery` section (team size, window, commercial model).
## Status
| Step | What | Status |
|---|---|---|
| 1 | The Deliverable, its Specialist and its data file; every Element in a work package, checked in code | built 2026-10-11 (`steps/step-1-to-4.md`) |
| 2 | The schedule computed in code: start and finish day, critical path, team size as a limit | built 2026-10-11 (`steps/step-1-to-4.md`) |
| 3 | The three views written by code: WBS dictionary, activity sequence list, timeline on a relative axis | built 2026-10-11 (`steps/step-1-to-4.md`) |
| 4 | The delivery window checked; assumptions the plan depends on shown on the timeline; milestones | built 2026-10-11, without milestones (`steps/step-1-to-4.md`) |
Decisions the owner accepted on 2026-10-11: after validation, in the packaging Phase; grouped by component; the technical build only.

View File

@@ -0,0 +1,43 @@
# Steps 1 to 4 — Implementation Detail
Built on 2026-10-11. **Not run with real models.**
1. **A new Deliverable, `work_breakdown`,** in the packaging Phase, after validation, produced by a new Specialist, the delivery planner (`agents/delivery-planner.md`, on the larger model). It is given the Target architecture and the deployment guidance in full.
2. **The planner writes the plan as data,** `work-breakdown.json`: work packages (a hierarchy, each naming the Elements it delivers, its scope, what it produces and the skills it needs) and activities (work package, days, what each comes after, and whether the team or the customer owns it).
3. **Code checks the plan against the design** (`check_work_breakdown` in `app/workflows/work_breakdown.py`). A submission is refused when an Element belongs to no work package, a work package names an Element that does not exist, an activity follows one that does not exist, activities depend on each other in a circle, a duration is not above zero or is over 120 days, or a work package holds neither an activity nor another work package.
4. **Code computes the schedule** (`schedule`). An activity starts when everything it follows has finished. The team's activities also wait for a free person: no more run at once than the team has people, with the longest remaining chain placed first. What the customer owns takes nobody from the team. The critical path is every activity with no slack.
5. **Code writes the three views** into the Deliverable when it is submitted, as it writes the architecture's tables:
- the **WBS dictionary**, each work package with the Checks on its Elements as what makes it done, read from the Target architecture;
- the **activity sequence**, with each activity's start and finish day and whether it is critical;
- the **timeline**, a chart in text along a relative axis from Day 0, the team's work and the customer's drawn differently and the critical path marked.
6. **The delivery terms come from the agreed scope:** team size, working week, delivery window and start date. A team size the scope does not give is 2, and the Deliverable says it was assumed.
7. **The plan is checked against the delivery window.** Over it, the Deliverable says by how much and names the critical path. Nothing shortens an estimate to fit.
8. **What the customer owns is listed** with its lead time and the assumption behind it.
9. **With a start date in the scope** the activity sequence also gives calendar dates, skipping weekends, and a Mermaid Gantt chart is attached as `timeline.mmd`. Without one there are no dates to draw, and the text chart is the timeline.
10. **The guide carries the timeline.** The guide and the plan are produced side by side, so neither reads the other; when an Execution's files are written, the plan's timeline is added to the guide as "Delivery plan". `execution.json` records the plan's length, team, whether it fits the window and its critical path, and the packaging Approval says the same.
Differs from the spec:
- **Milestones for fixed-price work are not built.**
- **An assumption in the scope is not linked to an activity by id.** An activity the customer owns carries its own assumption as text.
- **The timeline chart is text.** A Mermaid Gantt chart needs dates, so one is drawn only when the scope gives a start date.
- **The guide does not depend on the plan.** Making it wait would have put the plan on the path of every Execution's last step; adding the timeline in code keeps them independent.
Durations are a model's estimates. The Deliverable says so.
Tests: `tests/execution/test_work_breakdown.py` (16).
## First run with real models, 2026-10-11
`case-08-landing-zone`, results `20261011T185421Z`. The delivery planner made one model request, about $0.32.
- **The plan:** 9 work packages under one parent and 15 activities. Every one of the design's Elements is in a work package, and each work package lists the Checks that make it done.
- **The schedule:** 36 working days, 7.2 weeks, with the team of 3 the scope states. Inside the 10-week window with 2.8 weeks to spare.
- **The critical path is the customer's:** ordering the interconnect circuits, 30 days, then the routers and attachments, then validation in the three environments the scope names. The team's own work is done by about Day 13 and waits.
- **The timeline was added to the solution guide** and its numbers are in `execution.json`.
To look at:
- **The estimates look short for an enterprise landing zone.** Two days for the hub and spoke networks, one for the pipeline and state, two for the resource hierarchy. The planner was told to estimate for one engineer who knows the provider and not to pad, and it did. Whether to ask for a contingency, or a range, is the owner's call.
- **The plan's length rests on one assumed number,** the 30-day carrier lead time, which the planner chose. It is shown as the customer's and as an assumption.
- No start date was in the spec, so there are no calendar dates and no Mermaid chart.

View File

@@ -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=

View File

@@ -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

View 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.

View 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.

View 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.

View 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`).

View 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.

View File

@@ -0,0 +1,364 @@
# Spec: Scoping from a scope spec, and a work breakdown structure
Status: ready-for-agent
Accepted by the owner on 2026-10-11. Stage 1 is built; `.agents/plans/iter-09-scoping/` says what is done.
- Glossary: [`CONTEXT.md`](../../CONTEXT.md). New terms this would add are in **Language** below.
- Builds on: [ADR-0005](../../docs/adr/0005-the-target-architecture-is-an-explicit-graph.md) (ids along the Requirements chain), [ADR-0006](../../docs/adr/0006-a-change-request-starts-from-a-baseline-execution.md) (Change requests), [ADR-0002](../../docs/adr/0002-skills-are-the-portable-unit-of-behaviour.md) (behaviour in Skills).
- Would need: one new ADR, for a new first Phase and a new start to the Requirements chain.
## Problem
The Intent is the customer's request, saved word for word. For case 06 it is one sentence. Everything else a design needs (how many users, what availability, which region, what budget, which compliance regime, what exists today) is assumed by the requirements analyst or, in the evaluation, supplied by pattern-matched answers.
Three days of runs trace most downstream trouble to what nobody stated: Checks the validator asks for on topics the customer never raised, checklist items the request cannot settle, a "low-carbon region" no code can show. Nothing tells the customer at the start how much of their design rests on assumption, and a requirement does not record whether the customer stated it or the agent assumed it.
Separately, the agent delivers a design and its code but no plan for building it.
## Decisions taken
The owner accepted these defaults on 2026-10-11.
1. **Scoping is a Phase the customer approves,** before requirements discovery.
2. **Its centre is a scope spec:** a YAML file that may arrive complete, partly filled or not at all.
3. **Architects write the spec,** the owner and colleagues, not end customers. Field names may be technical.
4. **A small set of fields is essential** and always settled before work starts. Which they are depends on the kind of engagement.
5. **Two files.** The file supplied is never altered. A completed copy is written beside it.
6. **The run options live in the spec,** so one file starts an Execution.
7. **Where the spec and the prose request disagree, the spec wins** and the customer is shown the conflict.
8. **The work breakdown structure is a new Deliverable,** after validation, in the packaging Phase, grouped by component as the technical decomposition is, covering the technical build.
9. **Scoping is built before the work breakdown structure.**
## Language
Terms to add to `CONTEXT.md` when built:
- **Scope spec:** the structured statement of what the customer wants and the facts a design depends on, as a file. It sits beside the Intent, which stays in the customer's words.
- **Scoping:** the Phase that completes the scope spec and has the customer approve it.
- **Work breakdown structure:** the Deliverable that divides building the Target architecture into work packages and activities, with a timeline.
- **Work package:** a unit of work that delivers named Elements and is done when their Checks pass.
Already in the glossary and used here: Intent, Customer question, Change request, Baseline, Requirements chain.
## The scope spec
### What a field can say
Every field holds a value or one of three words:
| Written | Meaning | What the agent does |
|---|---|---|
| a value | The customer states this | Uses it. Recorded as `supplied`. |
| `ask`, or the field left out | Not known yet | Asks, when someone is present. Otherwise treats it as `decide` and lists it under `discovery_gaps`. |
| `decide` | You choose | Picks a default, recorded as `assumed` with the default and what it affects. |
| `not_applicable` | Does not apply | Asks nothing and assumes nothing. |
A field name the catalogue does not have is an error that names the field. Nothing is silently ignored.
### Tiers
| Tier | When it is settled |
|---|---|
| essential | Always, before any work: asked when someone is present, and refused with a list when nobody is and it is neither supplied nor `decide`. |
| important | Asked when someone is present; defaulted otherwise. |
| optional | Defaulted unless supplied. |
### The draft
Revised on 2026-10-11 to combine the first draft with the owner's own example, an engagement spec for a regulated landing zone. What each brought is listed under **How the two were combined**. Essential fields are marked; which are essential depends on `engagement.kind`. Values shown are from the owner's example.
```yaml
schema_version: 1 # the catalogue this file is written against
metadata:
customer_case: fintech-global-landing-zone # essential: groups this work's Executions
engagement_reference: ENG-2026-UK-084 # yours; carried through, never interpreted
client_name: FinTech Global UK
author: Pre-Sales Engineering
revision: "1.1.0" # yours: the version of this document
status: DRAFT # written by the agent; see Status below
engagement:
kind: platform_foundation # essential: workload | platform_foundation | migration
# 1. What the customer said. The source of truth; nothing here is rewritten.
intent:
statement: | # essential: verbatim, or consolidated from calls and documents
We are a UK-regulated payment platform expanding into Google Cloud. We need an
enterprise-grade landing zone ready in under 10 weeks ...
requirements: # what the customer stated outright, with their ids
- id: REQ-01
category: Timeline
statement: Platform foundation must be ready for workload ingestion within 10 weeks.
- id: REQ-03
category: Networking
statement: 10Gbps on-premises hybrid connectivity; centralized Palo Alto inspection for egress.
exclusions:
- Application container deployment (managed by app squads).
- Active-active secondary region in phase 1 (warm standby acceptable).
success_criteria: decide
# 2. Where it runs.
estate:
cloud_provider: gcp # essential; must be a provider this deployment has
mode: greenfield # essential: greenfield | brownfield_expansion | migration
regions:
primary: europe-west2 # essential
secondary: europe-west1
resiliency_tier: warm_standby
data_residency: United Kingdom # essential
existing_systems: ask
# 3. Who uses it and how hard. Essential for kind workload; not_applicable for a foundation.
workload:
users: {who: not_applicable, count: not_applicable, peak_concurrent: not_applicable}
availability: {target: ask, hours: always, recovery_time: ask, recovery_point: ask}
# 4. Regulation and governance.
compliance:
industry: financial_services
frameworks: [DORA, ISO27001, PCI_DSS_v4] # essential; an empty list means none apply
data_classification: confidential # essential
encryption: {type: cmek, key_rotation_days: 90}
audit_logging: {retention_days: 365, immutable_retention_policy: true}
# 5. Network.
networking:
exposure: internal_only # internal_only | internet_facing
topology: shared_vpc_hub_and_spoke # allowed values come from the Cloud provider's catalogue
hybrid_connectivity: {enabled: true, type: cloud_interconnect, bandwidth_gbps: 10}
egress_control: {model: centralized_appliance, appliance_vendor: palo_alto}
cidr_allocations: ask
# 6. Identity, environments and operations.
governance:
identity_source_of_truth: entra_id
pipeline_authentication: workload_identity_federation
environment_tiers:
- {name: development, archetype: corp_workload}
- {name: staging, archetype: corp_workload}
- {name: production, archetype: pci_regulated_workload}
operations:
operating_model: central_platform_broker
support_hours: decide
monitoring: decide
integrations: []
# 7. How it will be delivered. The work breakdown structure is built from this.
delivery:
target_start_date: 2026-11-01
window_weeks: 10 # essential when the customer has a deadline
commercial_model: fixed_price_milestone
iac_tooling: terraform
ci_cd: github_actions
team_size: ask
working_days_per_week: 5
cost:
monthly_budget: ask # essential for kind workload
currency: GBP
# 8. How to run the agent.
run:
pre_approved: false
allow_cloud_read: false
overlay_skills: []
terraform_modules: false
```
### Sections the agent writes
Only in the completed copy. The supplied file never has to carry them, and if it does they are read as the last run's and replaced.
```yaml
inferred_assumptions:
- id: ASSUMP-01
field: networking.hybrid_connectivity
category: Network Telecom
statement: Assumes the client manages the carrier circuit lead time for the 10Gbps interconnect.
impact_if_invalid: Blocks the hybrid routing test; delays every activity after it.
discovery_gaps:
- field: networking.cidr_allocations
prompt: Specify IP subnet sizes for spoke workloads, for example /22 per environment.
severity: HIGH # HIGH is an essential field; MEDIUM important; LOW optional
provenance: # where every settled value came from
estate.regions.primary: supplied
cost.monthly_budget: answered
operations.monitoring: assumed
readiness: {supplied: 34, answered: 3, assumed: 6, unknown: 2}
```
`provenance` is one of `supplied`, `answered`, `discovered` (read from the customer's cloud environment), `assumed`, `unknown`. Every `assumed` field has an entry in `inferred_assumptions`, and every `unknown` one in `discovery_gaps`.
### Status
The owner's example carries a status. The agent sets it in the completed copy from what has happened; a status written by the author is not trusted.
| Status | Means |
|---|---|
| `DRAFT` | Gaps remain, or the conversation is still filling them. |
| `UNDER_REVIEW` | Complete, and waiting for the scoping Approval. |
| `APPROVED` | The customer approved it; requirements and the later Phases run from it. |
| `BASELINE_LOCKED` | Its Execution completed. This copy is the record a Change request starts from, and is never altered. |
### How the two were combined
| From the owner's example | How it is kept |
|---|---|
| The request, verbatim, inside the spec | `intent.statement`. It is also still saved as the Intent, as today. |
| The customer's stated requirements, with ids | `intent.requirements`. The agent's requirements trace to these ids, so the Requirements chain starts at what the customer wrote. |
| Stated exclusions | `intent.exclusions`. The design is checked for nothing built that is excluded. |
| Engagement metadata and status | `metadata`, with the status set by the agent. |
| Estate, compliance, networking and governance sections | Kept as written. |
| Start date, delivery window, commercial model, tooling | `delivery`. The window becomes a limit the plan is checked against. |
| Assumptions with their impact, and gaps with a prompt and a severity | The two agent-written sections, in place of the first draft's flat provenance table. Severity is the tier. |
| From the first draft | How it is kept |
|---|---|
| `ask`, `decide` and `not_applicable` | Unchanged. The example had no way to say "not known" other than omission. |
| Tiers | Kept, as the severity of a gap. |
| Two files | Kept. The author's file is untouched; the agent's sections go in the completed copy. |
| Where each value came from | Kept, as `provenance`. |
| Users, scale, availability target, budget | Kept under `workload` and `cost`, and essential only for a workload. |
| Run options | Kept under `run`. |
### Where the two pull apart
Four tensions, each with the resolution proposed. They are the owner's to confirm.
1. **The example states solution choices; the agent keeps requirements free of them.** A hub-and-spoke topology, an interconnect, customer-managed keys and a named inspection appliance are design decisions. The rule that requirements name no products exists so the agents do not pick a design before the design Phase. It should not stop a customer who has already decided. Proposed: a choice the spec states is a constraint the design must honour and may not change, recorded as supplied. The agents still add none of their own.
2. **The example is a landing zone; the agent has only designed workloads.** Every benchmark case is an application. A platform foundation has no users or response times, and has an organisation hierarchy, shared networking and environment archetypes the cases have never exercised. `engagement.kind` lets one spec serve both, but a platform foundation is a new kind of work for the agent and needs its own evaluation case before it is relied on.
3. **The example uses one Cloud provider's vocabulary in general fields.** `shared_vpc_hub_and_spoke`, `cloud_interconnect` and `cmek` are Google Cloud's terms. Proposed: the general catalogue says a field such as `networking.topology` exists; the Cloud provider's bundle supplies its allowed values. A second provider then brings its own list and the spec's shape does not change.
4. **"Engagement" is a word the glossary avoids.** The agent's term is Customer case. Proposed: `customer_case` stays the key the agent groups by, and `engagement_reference` carries the owner's own number untouched. If the owner would rather the agent's term became Engagement, that is a glossary change to make before this is built.
### Where the catalogue lives
A provider-neutral Skill holds the catalogue: each field's type, tier by engagement kind, the question to ask, and guidance for the default. A Cloud provider's bundle adds its allowed values and any fields of its own. An overlay Skill may raise a field's tier, so an organisation can make `compliance.encryption` essential. Code validates a spec against the catalogue; no model decides what is missing.
## How scoping runs
| What arrives | What happens |
|---|---|
| A complete spec | Validated. No gaps, no questions. With `pre_approved` the Phase passes without stopping. |
| A partly filled spec, someone present | Gaps are asked for, essential first, a few related fields at a time, with a count of how many are settled. |
| A partly filled spec, nobody present | Essential gaps refuse the start, with the list. Others are defaulted and recorded. |
| Only a sentence | A model drafts a spec from it, marking everything it did not find as `ask`. It is then a partly filled spec. |
In conversation an answer is a value, "you decide", or "skip". A skipped field becomes `unknown` and a Customer question in the output. A free-text answer is turned into the field's value and read back before it is written. The customer may supply an edited file at any point in place of answering.
The Phase ends when the customer approves the completed spec.
### What it writes
Under the Customer case, beside the Intent:
```
intent/
001.md # the request, in the customer's words (as today)
001.scope.yaml # the spec as supplied, unaltered; absent when none was
001.scope.completed.yaml # the completed copy: status, assumptions, gaps, provenance, readiness
```
The scoping Deliverable is a short document written from the completed copy: the scope statement, the information register as a table, and the readiness summary. The solution guide opens with that summary.
### What it changes downstream
- **The requirements analyst derives; it no longer asks or assumes.** Each requirement names the stated requirement (`REQ-03`) or the spec field it comes from, so the Requirements chain starts at what the customer wrote. A requirement from an `assumed` field says so.
- **A stated choice binds the design.** A product, topology or setting the spec states is carried to the design as a constraint, and a design that departs from it is refused.
- **Exclusions are checked.** Nothing in `intent.exclusions` may appear in the Target architecture.
- **Customer questions** from the pillar checklists (built 2026-10-10) are joined by the `unknown` fields.
- **A Change request may be an edited spec.** Code compares the two specs field by field, and that list is what changed. A sentence still works, as now.
- **An evaluation case becomes a spec,** replacing the pattern-matched answers.
## The work breakdown structure
A new Deliverable in the packaging Phase, produced by a new Specialist after validation, summarised in the solution guide.
### Its data file
```json
{
"work_packages": [
{"id": "WP-1", "name": "Network foundation", "parent": null,
"components": ["C-2"], "elements": ["E-1", "E-2"],
"scope": "The VPC, its subnet and outbound access.",
"produces": ["a private network the services attach to"],
"skills": ["network engineering"]}
],
"activities": [
{"id": "A-1", "work_package": "WP-1", "name": "Create the VPC and subnet",
"days": 1, "after": []},
{"id": "A-2", "work_package": "WP-1", "name": "Configure outbound access",
"days": 1, "after": ["A-1"]}
]
}
```
### What code checks and computes
- Every Element belongs to a work package, and every work package to a component or a parent. A design cannot be left out of the plan.
- A work package's acceptance criteria are the Checks on its Elements. They are read from the Target architecture, not written again.
- Activities form no cycle, and every `after` names an activity that exists.
- **The plan is checked against the delivery window.** When `delivery.window_weeks` is set and the computed total exceeds it, the Deliverable says so and names the critical path; it does not shorten estimates to fit.
- **An assumption can hold up the plan.** An entry in `inferred_assumptions` that an activity depends on, such as a carrier's lead time, appears as a dependency the customer owns, so its `impact_if_invalid` is visible on the timeline.
- **Milestones.** With a `commercial_model` of fixed price by milestone, each top-level work package ends in a milestone.
- **The schedule is computed, not written.** From each activity's days and what it comes after, code works out its earliest start and finish, the critical path and the total. With `delivery.team_size` it limits how many activities run at once.
### What it renders
Three views, all written by code from the data file, as the architecture diagram is:
- **WBS dictionary:** the hierarchy, each work package with its scope, what it produces, its Elements, its acceptance Checks and the skills it needs.
- **Activity sequence list:** each activity with its days, what it follows, its start and finish day, and whether it is on the critical path.
- **Timeline** on a relative axis, Day 0 to Day N:
```
Activity Day 0 5 10 15 18
A-1 Create the VPC and subnet ██
A-2 Configure outbound access ██
A-3 Provision the database █████
A-4 Deploy the application ████
A-5 Load balancer and access ███
A-6 Monitoring and alerts ██
A-7 Validation in test ████
```
The chart format is to be settled when built: a Mermaid Gantt chart if it can show a relative day axis, and otherwise a drawn table like the one above.
### What it says about itself
Durations are a model's estimates. The Deliverable states their basis (working days, the team size from the spec) and that they are indicative. The timeline stays on a relative day axis; when `delivery.target_start_date` is set, the activity list also gives calendar dates.
## Order of work
| Stage | What | Usable on its own |
|---|---|---|
| 1 | The catalogue, validation, the gap list, the two files saved beside the Intent, the run options read from the spec | Yes: a complete spec starts a pre-approved Execution |
| 2 | The conversation that fills gaps; scoping as a Phase with its Deliverable and Approval; a spec drafted from a sentence | Yes |
| 3 | Requirements traced to spec fields; readiness in the guide | Yes |
| 4 | An edited spec as a Change request | Yes |
| 5 | The work breakdown structure | Yes, with stage 1 for `delivery` |
| 6 | Evaluation cases as specs | Yes |
## Not in this spec
- Attaching documents (a statement of work, a diagram) as a source for the spec.
- Reading the customer's cloud environment to fill `current_estate`. The `discovered` source is reserved for it.
- Delivery activities beyond the technical build, such as security review, user acceptance and cutover.
- Cost of the work, or named people.
## Open questions
1. The four tensions under **Where the two pull apart**: are the proposed resolutions right?
2. Which fields are essential for each engagement kind? The draft marks them; the owner's example suggests the delivery window and compliance frameworks matter more than budget for a foundation.
3. In `pre_approved` runs an essential gap refuses the start. Is that right, or should it default and warn?
4. Should the scoping Approval be skippable when the spec arrived complete and someone is present?
5. Is a platform foundation in scope now, with its own evaluation case, or should scoping be built against workloads first?
## Comments
- 2026-10-11, the owner: a platform foundation is in scope now; an engagement name and a Customer case are equivalent references; the implementation will eventually be provider-agnostic. The other tensions and open questions were taken as proposed: a stated choice binds the design; an essential gap refuses a pre-approved start; the scoping Approval is not skipped. Recorded in ADR-0008.

View File

@@ -19,13 +19,21 @@ A caller-supplied grouping of Executions. A Session never feeds earlier outputs
_Avoid_: conversation, context
**Customer case**:
A caller-supplied grouping of the Executions run for one customer workload, identified by a short slug. Every Execution belongs to one; an Execution started without one belongs to `unassigned`. A Customer case ties each request to the Deliverables generated for it. It feeds one Execution's outputs into another only when the caller starts a Change request and names the Baseline.
_Avoid_: engagement, project, account, tenant
A caller-supplied grouping of the Executions run for one customer engagement, identified by a short slug. An engagement and a Customer case are the same thing: a reference such as `ENG-2026-UK-084` names the case `eng-2026-uk-084`. Every Execution belongs to one; an Execution started without one belongs to `unassigned`. A Customer case ties each request to the Deliverables generated for it. It feeds one Execution's outputs into another only when the caller starts a Change request and names the Baseline.
_Avoid_: project, account, tenant
**Intent**:
What the customer wants from a Customer case, in their own words and at a high level. Each Workflow request made in the case is a statement of it, and the statements are kept in order as its history. The Intent is the customer's; requirements are what the agents derive from it.
_Avoid_: brief, ask, requirements (which are the derived Deliverable)
**Scope spec**:
The structured statement of what the customer wants and the facts a design depends on, as a file. It may arrive complete or partly filled. It sits beside the Intent, which stays in the customer's words, and a value it states is the customer's decision.
_Avoid_: brief, questionnaire, requirements (which are derived from it)
**Scoping**:
Completing the scope spec, from what was supplied, what the customer answers and what the agent is left to decide, and having the customer approve it before requirements begin.
_Avoid_: discovery (which reads a cloud environment), intake (which reads a message)
**Change request**:
An Execution started to say how the customer's Intent has changed. It begins from a Baseline and delivers the full updated Deliverables with an account of what changed and why.
_Avoid_: amendment, update run, iteration, re-run
@@ -35,7 +43,7 @@ The completed Execution, in the same Customer case, that a Change request starts
_Avoid_: parent, previous run, source Execution
**Phase**:
A named grouping of Deliverables: requirements discovery, solution architecture (the design, ending with the Target architecture), solution implementation, solution validation, or packaging. A Phase is complete when all its Deliverables are submitted and the user has granted the Phase's Approval.
A named grouping of Deliverables: scoping, requirements discovery, solution architecture (the design, ending with the Target architecture), solution implementation, solution validation, or packaging. A Phase is complete when all its Deliverables are submitted and the user has granted the Phase's Approval.
_Avoid_: step, node, stage, pipeline
**Approval**:
@@ -81,7 +89,7 @@ _Avoid_: custom prompt, override, plugin
### Outputs
**Deliverable**:
A document an Execution produces: requirements, technical decomposition, product selection, design recommendations, the Target architecture, architecture description, deployment guidance, validation results, or the Solution guide. Each Deliverable depends on others being approved first.
A document an Execution produces: the scope, requirements, technical decomposition, product selection, design recommendations, the Target architecture, architecture description, deployment guidance, validation results, the Work breakdown structure, or the Solution guide. Each Deliverable depends on others being approved first.
_Avoid_: artifact, output file
**Dependency**:
@@ -108,6 +116,18 @@ _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)
**Work breakdown structure**:
The Deliverable that divides building the Target architecture into Work packages and the activities within them, with a timeline on a relative axis of working days. Its schedule is computed from the activities' durations and dependencies, never written.
_Avoid_: project plan, roadmap, schedule (which is one view of it)
**Work package**:
A unit of the build that delivers named Elements, and is done when the Checks on those Elements pass.
_Avoid_: task, epic, phase (which groups Deliverables), workstream
**Solution guide**:
The packaged Deliverable that assembles every other Deliverable into the Cloud provider's solution architecture template.
_Avoid_: final report, package

View File

@@ -10,14 +10,19 @@ Vocabulary is defined in [CONTEXT.md](CONTEXT.md), decisions in [docs/adr/](docs
### 1. Orchestrator and Specialists (`agents/`)
One Orchestrator coordinates an Execution and is the only agent that talks to the user. It is a router ([ADR-0007](docs/adr/0007-jev-is-the-orchestrators-decision-point.md)): code reads the Execution's state, a decision model (Jev) answers the closed questions that need judgement, and a playbook in code picks the action. A language model only writes what the user reads. It delegates each Deliverable to one Specialist, and independent Deliverables run in parallel:
- **Scoping:** `scope-analyst`, which completes the scope spec with the customer.
- **Requirements discovery:** `requirements-analyst`, `decomposer`.
- **Solution architecture (design):** `product-selector`, `design-advisor` (which consults one `pillar-advisor` per architecture-framework pillar), `target-architect`.
- **Solution implementation:** `describer`, `iac-author`.
- **Solution validation:** `validator`.
- **Packaging:** `packager`.
- **Packaging:** `delivery-planner`, which plans the build as a work breakdown structure, and `packager`.
Each Phase needs the user's explicit Approval before work that depends on it starts. A pre-approved mode serves batch and evaluation runs.
An Execution may start from a **scope spec** ([ADR-0008](docs/adr/0008-scoping-starts-from-a-scope-spec.md)): a YAML file of what the customer wants and the facts a design depends on, complete or partly filled. Code reads it against a catalogue and refuses a field it does not know. Scoping, the first Phase, completes it: the scope analyst asks for what is missing when someone is present and assumes it, visibly, when nobody is. With no spec it drafts one from the request. The customer approves the result before requirements begin, and a completed copy is kept beside their request with what was assumed and what is still unknown. `python -m app.scope template platform_foundation` prints one to fill in, and `python -m app.scope check <file>` says what a spec lacks. Pass it as `scope` to `/generate` or in A2A metadata.
The **work breakdown structure** divides building the design into work packages and activities. The planner writes it as data; code checks that every Element belongs to a work package, computes each activity's start and finish from its days and what it follows, finds the critical path, and draws the timeline on a relative axis from Day 0. The plan is checked against the delivery window the scope gives.
A **Change request** ([ADR-0006](docs/adr/0006-a-change-request-starts-from-a-baseline-execution.md)) starts from a completed Execution in the same Customer case, its Baseline, and delivers the full updated Deliverables with `changes.json`: what changed, what was only reworded, and anything changed that nobody asked for.
The design Phase ends with the **Target architecture**: one explicit graph of Elements, Relationships and Checks ([ADR-0005](docs/adr/0005-the-target-architecture-is-an-explicit-graph.md)). The user approves it before any infrastructure code is written. The diagram is drawn from it by code, the Terraform must account for every Check, and validation gives a verdict per Check. Requirements, components, products and recommendations each carry ids in a data file, so every requirement can be traced through to its verdict; a submission with a missing link is refused.
@@ -38,6 +43,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 +62,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/`.

View 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.

View File

@@ -0,0 +1,46 @@
---
role: delivery-planner
deliverable: work_breakdown
tools: []
budget: 20
includes: [specialist-protocol]
---
You produce the **work breakdown structure** Deliverable: a plan for building the Target architecture that has been designed and validated. You change nothing in the design. You say how the work divides, in what order it goes, and how long each piece takes.
You write the plan as data. The WBS dictionary, the activity sequence, the schedule and the timeline are computed and written from it for you when you submit, so write none of them yourself.
Attach `work-breakdown.json`:
```json
{
"work_packages": [
{"id": "WP-1", "name": "Network foundation", "parent": null,
"elements": ["E-1", "E-2"],
"scope": "The network, its subnets and outbound access.",
"produces": ["a private network the services attach to"],
"skills": ["network engineering"]}
],
"activities": [
{"id": "A-1", "work_package": "WP-1", "name": "Create the network and subnets", "days": 1, "after": []},
{"id": "A-2", "work_package": "WP-1", "name": "Order the carrier circuit", "days": 30, "after": [],
"owner": "customer", "assumption": "The customer manages the carrier's lead time."}
]
}
```
Work packages:
- Group them as the technical decomposition groups the design: one for each component, or for a few components that are built together, with a parent work package where several belong to one area.
- Every Element of the Target architecture belongs to exactly one work package. A submission is refused while any Element belongs to none.
- A work package is done when the Checks on its Elements pass. Do not write acceptance criteria: they are read from the Target architecture.
- Add a work package only for the technical build. Reviews, acceptance testing and cut-over are not part of this plan.
Activities:
- Each is one piece of work one person does, of between half a day and about ten days. Anything longer is several activities.
- `days` is working days of effort for one engineer who knows the Cloud provider. Estimate from what the infrastructure code actually contains: a resource written from a pattern is hours, a network joined to another site is days. Do not pad, and do not shorten to fit a deadline: the plan is checked against the delivery window after you submit, and it is more useful honest than fitting.
- `after` lists the activities that must finish first. Give a dependency only where one is real: what the code in one needs from another. Leaving independent work unordered is what lets it run in parallel.
- `owner` is `team`, the default, or `customer` for something the customer or their supplier must do that the team waits on, such as ordering a circuit or granting access. Give its lead time as `days` and say in `assumption` what you assumed.
- Include the activities that make the build usable: enabling the provider's APIs, the pipeline that applies the code, and running the validation in each environment the scope names.
Your content is one section, under its heading: the approach in a few sentences, saying how the work is ordered and why, what runs in parallel, what the plan waits on from the customer, and the assumptions behind the estimates. Read the delivery facts from `scope`: the team size, the delivery window, the environments and the commercial model.

View File

@@ -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.

View File

@@ -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.

View File

@@ -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.

View File

@@ -10,6 +10,9 @@ 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.
- Write no timeline, schedule or estimate of your own. The delivery plan is a Deliverable of its own, and its timeline is added to the guide for you.
- Open the executive summary with what the design rests on, from the scope: how many of its facts the customer stated, how many were assumed for them, and how many are still unknown, naming the assumptions that most shape the design. A reader must be able to tell an agreed design from an indicative one.
- 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.

View File

@@ -13,6 +13,7 @@ Your task message carries JSON context:
- `working_copy`: what your own tools already hold from your earlier attempts, or `null`. Start from it; do not start again.
- `baseline`: set only in a Change request, where the user has said how their requirements changed since an architecture was delivered. `deliverable` is that delivered version of your own Deliverable, and `changes` is what has changed so far: the requirements added, changed and removed, with the reason, and everything already revised from them. `null` otherwise.
- `read_first`: references of your Skills that this task was judged to need, each as a Skill and a resource. Read these first with `load_skill_resource`. It is where to start, not a limit: read anything else you find you need.
- `scope`: what the customer's scope spec says, when they supplied one. `stated` is theirs and binds your Deliverable; `assumed` was chosen for them and may change when they answer; `to_ask` is unknown. Load the scoping Skill for the rules. Honour every stated choice, build nothing under `stated.intent.exclusions`, and name the customer's own requirement id when your work serves one.
- `overlay_skills`: Skills that carry the user's organisation's standards or this engagement's constraints. Load each one and apply it. Where an overlay disagrees with the Cloud provider's general guidance, the overlay wins; where it disagrees with a requirement the user stated, follow the requirement and say so.
- `pre_approved`: `true` when no user is available.

View File

@@ -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.

View File

@@ -2,15 +2,29 @@
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:
- Say what the Phase produced and what approving it commits them to. For the design Phase, say that no infrastructure code is written until they approve it.
- For the scoping Phase, `facts.scope` says which fields were assumed for them and which are still unknown. Say how many of each, name the ones that most shape a design, and say that requirements are derived from this scope once they approve it.
- For the packaging Phase, `facts.delivery_plan` gives the plan's length in weeks, the team it assumes and whether it fits the delivery window. Say so plainly; when it is over the window, say by how much the plan is over and that the critical path is in the work breakdown structure.
- State every number in `facts` that bears on the decision, exactly as given. Add no fact that is not there.
- Name anything they should look at before approving: failed or unverifiable Checks, open gaps, recommendations treated as not applicable, Deliverables that were revised.
- Use plain sentences and no headings. Keep it under 120 words.
Call `write_reply` with the summary. You are done when it accepts it.
## 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.

View File

@@ -7,14 +7,16 @@ includes: [specialist-protocol]
You produce the **requirements** Deliverable: the Skill's requirements-discovery gathering and its resolution of ambiguities and contradictions.
- Cover functional requirements, non-functional requirements (security, privacy, compliance, reliability, disaster recovery, cost, operations, performance, sustainability), current state, and dependencies.
- The user states what they want at a high level; the detail is your job. When a non-functional requirement is missing, propose a default for it from the Cloud provider's architecture framework and record it under `Assumptions` with what it decides: availability tiers, scaling, cost budgets, resource types and security posture. Ask the user to confirm the whole set in one question.
- Ask an open question only where no sensible default can be inferred from the request, such as the region, a compliance regime or a budget ceiling.
- The scope has been agreed before you start: `scope` holds what the customer stated, what was assumed for them and what is still unknown. The detail is your job. Derive the requirements from it; do not ask again for anything it settles.
- Where a non-functional requirement needs something the scope does not hold, propose a default from the Cloud provider's architecture framework and record it under `Assumptions` with what it decides. Carry every entry of `scope.assumed` into `Assumptions` too, so a reader of the requirements sees what rests on one.
- Ask a question only for something the scope leaves unknown that you cannot write a requirement without.
- Name every ambiguity or contradiction, explain why the conflicting goals can't both hold, and ask the user to choose. When they delegate the choice, propose one and ask them to approve it.
- When the user runs workloads in a cloud environment today, use your cloud discovery tools to describe the current state from what actually exists, and record anything you couldn't read as a discovery gap.
- Name no products, services or architectures. This Deliverable describes the problem, not the solution.
- Name no products, services or architectures of your own choosing. This Deliverable describes the problem, not the solution. A product or design choice the customer stated in `scope` is theirs: record it as a constraint, in their words.
- Give each requirement its `from`, as the requirements-chain Skill describes. Cover every entry of `scope.stated.intent.requirements`, the customer's own requirements, by id. Carry every field under `scope.binding`, a choice the customer stated, in a non-functional requirement whose conditions say what must exist or be set for it to have been honoured. A stated choice that reaches no requirement reaches no Check, and can then be named in the design without being built. List what `scope.to_ask` still holds under `Open questions`.
- 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`:

24
agents/scope-analyst.md Normal file
View File

@@ -0,0 +1,24 @@
---
role: scope-analyst
deliverable: scope
tools: []
budget: 30
includes: [specialist-protocol]
---
You produce the **scope** Deliverable: the agreed statement of what the customer wants and the facts a design depends on, as a completed scope spec. You design nothing and choose no products. Load the scoping Skill: it says what each field means.
The scope spec is kept for you. `scope_read` shows what is settled, what is not, and the question to ask for each field. `scope_set` records fields, several per call.
1. Call `scope_read`. When the customer supplied a spec, most of it is already there, and what they stated stays as they stated it.
2. Read `workflow_request`. Record what it states and the spec does not yet hold, with `source` `request`: the statement itself, word for word, under `intent.statement`; the kind of engagement; and any fact it gives. Record only what the words say. Do not infer a number or a choice the customer did not give.
3. Settle what is not settled, the essential fields first.
- **When you may ask the user** (`pre_approved` is `false`): call `needs_input` with the questions for the essential fields, and the important ones that most change a design, at most eight in one call, each in the catalogue's words. Tell them they may answer, say "you decide", or skip one. Record each answer with `source` `answered`. For "you decide", choose a value and record it with `source` `assumed` and a `note`. Leave a skipped field as it is. Ask a second batch only for what is still essential.
- **When you may not ask** (`pre_approved` is `true`): for each essential or important field not settled, choose a value from the catalogue's default guidance and what the request implies, and record it with `source` `assumed` and a `note` saying why. Leave optional fields alone.
- A field marked `decide` is yours: choose, and record it as assumed with a note.
- A field that cannot apply to this kind of engagement is `not_applicable`.
4. Call `scope_read` again. Every essential field must be settled before you can submit.
5. Submit. Your content is the scope statement under its heading: three to six sentences saying what the customer wants, what is in scope, what is out of scope, and what success looks like, in plain words and using only what the spec holds. Name as out of scope only what `intent.exclusions` lists; do not add an exclusion of your own. The completed spec, the information register, the assumptions and the questions still open are written for you from what you recorded. Pass no attachments.
Never record a product, a region, a number or a regulation the customer did not state as though they had: that is `assumed`, with its note. An assumption the customer can see is useful; one presented as their decision is a fault.
In a Change request (`baseline` is set), the spec you start from is the one that was delivered, and `workflow_request` says what has changed. Record only the fields the change reaches, with `source` `answered`: the customer has now said so. Leave every other field as it was. When no spec was delivered with the Baseline, complete one as above, from `workflow_request` and from the requirements in `baseline`.

View File

@@ -8,6 +8,7 @@ includes: [specialist-protocol]
You produce the **Target architecture** Deliverable: the solution as one explicit graph of Elements, Relationships and Checks. It is agreed before any infrastructure code is written, and the diagram, the description, the code and the validation are all derived from it.
- Load the requirements-chain Skill for the graph's format and how to derive it.
- Every Element is a resource of the Cloud provider's own Terraform provider. Something outside it that the design depends on, such as a source repository or a third party's service, is not an Element: say in the design rationale that it is needed and who provides it.
- Build the graph with `graph_put` in a handful of calls of ten to twenty items each: all the Elements, then all the Relationships, then the Checks in batches. A call for every Element, or for every few Checks, uses up your tool calls before the graph is finished; a single call with everything is a reply long enough to time out.
- Give every component an Element with the product selected for it, and add the supporting Elements the design needs, such as identities, policies and networks.
- Give every connection between Elements a Relationship.

View File

@@ -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.

View File

@@ -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,8 +129,10 @@ 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"),
scope=options.get("scope"),
execution_id=task_id,
pre_approved=bool(options.get("pre_approved", False)),
pre_approved=options.get("pre_approved"),
allow_cloud_read=options.get("allow_cloud_read"),
)
else:

View File

@@ -37,6 +37,16 @@ Turn = Sequence[Call] | Callable[[AgentTask], Sequence[Call]]
# One small, coherent Requirements chain, so sample submissions pass every link.
SAMPLE_DATA: dict[str, str] = {
"scope.yaml": "engagement:\n kind: workload\nintent:\n statement: Accept events.\n",
"scope.json": json.dumps(
{
"kind": "workload",
"stated": {"intent": {"statement": "Accept events."}},
"to_decide": [],
"to_ask": [],
"not_applicable": [],
}
),
"requirements.json": json.dumps(
[
{"id": "FR-1", "kind": "functional", "text": "Accept events."},
@@ -105,6 +115,37 @@ SAMPLE_DATA: dict[str, str] = {
{"check": "K-2", "file": "terraform/main.tf", "address": "example.sa"},
]
),
"work-breakdown.json": json.dumps(
{
"work_packages": [
{
"id": "WP-1",
"name": "Ingress",
"parent": None,
"elements": ["E-1", "E-2"],
"scope": "The service and its identity.",
"produces": ["a running service"],
"skills": ["platform engineering"],
}
],
"activities": [
{
"id": "A-1",
"work_package": "WP-1",
"name": "Create the identity",
"days": 1,
"after": [],
},
{
"id": "A-2",
"work_package": "WP-1",
"name": "Deploy the service",
"days": 2,
"after": ["A-1"],
},
],
}
),
"verdicts.json": json.dumps(
{
"dry_run": {"verdict": "pass", "evidence": "terraform validate passed."},

View File

@@ -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(

View File

@@ -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)

View File

@@ -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,
@@ -46,16 +46,19 @@ from app.nodes.router import (
)
from app.providers import ProviderBundle, load_provider
from app.recorder import DatabaseRecorder, ExecutionRecorder
from app.scope import ESSENTIAL, Catalogue, Scope, read_scope, slug
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
from app.tools.mcp import McpCatalog, auth_from_config
from app.tools.requirements_review import RequirementsReview
from app.tools.schema_review import Reviews, SchemaReview
from app.tools.scoping import Scoping, to_working
from app.tools.skill_routing import routable
from app.tools.toolkit import make_tool_factory
from app.workflows.deliverables import DEPENDENCY_GRAPH
@@ -103,6 +106,11 @@ 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,
scope_catalogue: Catalogue | None = None,
scope_values: Mapping[str, Sequence[str]] | None = None,
scope_skill: str | None = None,
) -> None:
required = {
ORCHESTRATOR,
@@ -112,6 +120,15 @@ class ExecutionEngine:
if missing:
raise ValueError(f"Missing roles: {', '.join(missing)}")
self._max_revisions = max_revisions
# The catalogue a scope spec is read against (ADR-0008); None when this
# deployment's Cloud provider has none.
self._scope_catalogue = scope_catalogue
self._scope_values = dict(scope_values or {})
self._scope_skill = scope_skill
# 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 {})
@@ -139,6 +156,9 @@ class ExecutionEngine:
skill_references=skill_references,
skill_threshold=skill_threshold,
assess_at_end=assess_at_end,
scoping=Scoping(scope_catalogue, dict(scope_values or {}), scope_skill)
if scope_catalogue is not None
else None,
).compile(checkpointer=checkpointer)
async def start(
@@ -147,12 +167,14 @@ class ExecutionEngine:
*,
session_id: str | None = None,
customer_case: str | None = None,
pre_approved: bool = False,
pre_approved: bool | None = None,
allow_cloud_read: bool | None = None,
execution_id: str | None = None,
scripted_answers: Sequence[Sequence[str]] = (),
baseline: str | None = None,
overlay_skills: Sequence[str] = (),
terraform_modules: bool | None = None,
scope: str | Mapping[str, Any] | 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,7 +188,56 @@ 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.
`scope` is a scope spec (ADR-0008), as YAML text or already parsed. It may
be complete or partly filled. The start is refused when it names a field
the catalogue does not have or holds a value of the wrong type, and, for a
pre-approved Execution, when an essential field is not settled: nobody is
there to ask. What the spec states under `run` applies where the caller
gave no value of their own. Its statement of intent is the request when
none is given.
"""
read = self._read_scope(scope) if scope is not None else None
if read is not None:
run = read.values
if pre_approved is None:
pre_approved = bool(run.get("run.pre_approved", False))
if allow_cloud_read is None and "run.allow_cloud_read" in run:
allow_cloud_read = bool(run["run.allow_cloud_read"])
if terraform_modules is None and "run.terraform_modules" in run:
terraform_modules = bool(run["run.terraform_modules"])
overlay_skills = [*overlay_skills, *run.get("run.overlay_skills", [])]
if (
customer_case
and read.customer_case
and slug(customer_case) != (read.customer_case)
):
raise ValueError(
f"The scope spec is for {read.customer_case}, and this was "
f"started for {customer_case}."
)
customer_case = customer_case or read.customer_case
# The spec's statement is the customer's; it is what gets recorded.
workflow_request = read.statement or workflow_request
missing = read.gaps(ESSENTIAL)
if pre_approved and missing:
raise ValueError(
"The scope spec leaves essential fields unsettled, and a "
"pre-approved Execution has nobody to ask: "
+ ", ".join(gap["field"] for gap in missing)
+ ". Give each a value, or `decide` to leave it to the agent."
)
pre_approved = bool(pre_approved)
if not workflow_request.strip():
raise ValueError(
"A request is needed: text, or a scope spec with a statement."
)
customer_case = check_customer_case(customer_case)
execution_id = execution_id or str(uuid.uuid4())
if await self._exists(execution_id):
@@ -187,6 +258,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())
@@ -197,6 +281,8 @@ class ExecutionEngine:
session_id=session_id,
workflow_request=workflow_request,
baseline=baseline or None,
scope_supplied=scope if isinstance(scope, str) else None,
scope_completed=read.completed(read.status(pre_approved)) if read else None,
)
initial: dict[str, Any] = {
"execution_id": execution_id,
@@ -208,6 +294,18 @@ 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,
# What the customer's scope spec settles and leaves open; None without one.
"scope": {
"skill": self._scope_skill,
"status": read.status(pre_approved),
"readiness": read.readiness(),
"context": read.for_context(),
# What the scope analyst starts from and completes.
"working": to_working(read),
}
if read
else None,
"risks": [],
"pre_approved": pre_approved,
"allow_cloud_read": allow_cloud_read,
@@ -246,6 +344,13 @@ class ExecutionEngine:
await self._graph.ainvoke(initial, self._config(execution_id))
return await self.interaction(execution_id)
def _read_scope(self, supplied: str | Mapping[str, Any]) -> Scope:
if self._scope_catalogue is None:
raise ValueError("This deployment has no scope spec catalogue.")
return read_scope(
supplied, self._scope_catalogue, provider_values=self._scope_values
)
async def resume(self, execution_id: str, reply: Mapping[str, Any]) -> Interaction:
"""Answer the Execution's current prompt: {"reply"} | {"approval"} | {"permission"}."""
current = await self.interaction(execution_id)
@@ -301,6 +406,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 +511,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 +559,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 +594,11 @@ async def open_assembly(
else None,
skill_threshold=settings.JEV_SKILL_THRESHOLD,
assess_at_end=settings.JEV_ASSESS_EXECUTIONS,
scope_catalogue=bundle.scope_catalogue() if bundle.scope_skill else None,
scope_values=bundle.scope_values,
scope_skill=bundle.scope_skill,
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 +616,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):

View File

@@ -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,

View File

@@ -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

View File

@@ -14,15 +14,20 @@ nothing was delivered for it. history.json is the index of the case.
from __future__ import annotations
import json
from collections.abc import Mapping
from datetime import UTC, datetime
from pathlib import Path
from typing import Any
import yaml
from app.states.execution_state import case_dir
INTENT_DIR = "intent"
HISTORY_FILENAME = "history.json"
IN_PROGRESS = "in_progress"
SCOPE_SUPPLIED = ".scope.yaml"
SCOPE_COMPLETED = ".scope.completed.yaml"
def intent_dir(output_root: Path, customer_case: str) -> Path:
@@ -50,6 +55,8 @@ def record_intent(
session_id: str,
workflow_request: str,
baseline: str | None = None,
scope_supplied: str | None = None,
scope_completed: Mapping[str, Any] | None = None,
) -> int:
"""Record a new statement of the customer's intent and return its version.
@@ -71,6 +78,19 @@ def record_intent(
f"## What the customer wants\n\n{workflow_request.strip()}\n",
encoding="utf-8",
)
scope_files = None
if scope_completed is not None:
# The spec as supplied, unaltered, and the completed copy beside it.
scope_files = {"completed": f"{INTENT_DIR}/{version:03d}{SCOPE_COMPLETED}"}
(folder / f"{version:03d}{SCOPE_COMPLETED}").write_text(
yaml.safe_dump(dict(scope_completed), sort_keys=False, allow_unicode=True),
encoding="utf-8",
)
if scope_supplied:
scope_files["supplied"] = f"{INTENT_DIR}/{version:03d}{SCOPE_SUPPLIED}"
(folder / f"{version:03d}{SCOPE_SUPPLIED}").write_text(
scope_supplied, encoding="utf-8"
)
history["intents"].append(
{
"version": version,
@@ -82,6 +102,7 @@ def record_intent(
"status": IN_PROGRESS,
"execution": None,
"baseline": baseline,
"scope": scope_files,
}
)
_write_history(folder, history)

View File

@@ -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}

View File

@@ -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),

View File

@@ -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]

View File

@@ -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,

View File

@@ -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)

View File

@@ -62,8 +62,10 @@ def create_app(
except ValueError:
body = {}
workflow_request = str(body.get("request") or "").strip()
if not workflow_request:
return JSONResponse({"error": "'request' is required"}, status_code=400)
if not workflow_request and not body.get("scope"):
return JSONResponse(
{"error": "'request' or a 'scope' spec is required"}, status_code=400
)
try:
interaction = await assembly.engine.start(
workflow_request,
@@ -71,6 +73,8 @@ 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"),
scope=body.get("scope"),
pre_approved=True,
allow_cloud_read=bool(body.get("allow_cloud_read", False)),
)
@@ -88,7 +92,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,

View File

@@ -7,6 +7,7 @@ append outcomes that the next Orchestrator turn applies in order.
from __future__ import annotations
import asyncio
import copy
import dataclasses
import json
import logging
@@ -15,8 +16,9 @@ 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
import yaml
from langgraph.types import Command, Send, interrupt
from app.adk.runtime import (
@@ -37,26 +39,42 @@ 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,
SCOPE_COMPLETED,
close_intent,
intent_dir,
)
from app.nodes.router import ModelOrchestrator, OrchestratorPolicy, TurnView
from app.recorder import ExecutionRecorder
from app.scope import APPROVED, CASE_FIELD, LOCKED, UNDER_REVIEW
from app.states.execution_state import (
UNASSIGNED_CASE,
ExecutionState,
execution_dir,
lessons_file,
)
from app.states.ledger import DeliverableStatus, Ledger, LedgerRefusal
from app.states.ledger import DeliverableStatus, Ledger, LedgerRefusal, PhaseStatus
from app.states.lessons import collect_lesson_candidates, refusal
from app.tools import workspace
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.scoping import SCOPE_KEY, Scoping, working_from_completed
from app.tools.skill_routing import read_first
from app.workflows.chain import (
IMPLEMENTATION_FILE,
SCOPE_DATA_FILE,
SCOPE_FILE,
VERDICTS_FILE,
unimplementable_checks,
validation_outcome,
@@ -66,9 +84,11 @@ from app.workflows.deliverables import (
DEPENDENCY_GRAPH,
PHASE_ORDER,
DeliverableKind,
PhaseId,
dependencies_for,
)
from app.workflows.target_architecture import GRAPH_ATTACHMENT
from app.workflows.work_breakdown import summary as plan_summary
logger = logging.getLogger(__name__)
@@ -82,6 +102,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
@@ -124,6 +145,7 @@ def make_execution_nodes(
skill_references: Mapping[str, Mapping[str, Mapping[str, str]]] | None = None,
skill_threshold: float = 1.25,
assess_at_end: bool = False,
scoping: Scoping | None = None,
) -> ExecutionNodes:
tool_factory = tool_factory or _no_tools
# How an Orchestrator turn is decided. The default drives the tools from the
@@ -206,11 +228,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 +275,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 +495,19 @@ def make_execution_nodes(
role = dataclasses.replace(
role, skills=(*role.skills, *(n for n in named if n not in role.skills))
)
scope_skill = scoping.skill if scoping else task_input.get("scope_skill")
if scope_skill and scope_skill not in role.skills:
# An Execution with a scope spec: every Specialist can read what it means.
role = dataclasses.replace(role, skills=(*role.skills, scope_skill))
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",
@@ -476,6 +526,16 @@ def make_execution_nodes(
_start_from(kind, before, working, task_input.get("baseline_basis"))
# And from its working material: the advice it was written from.
working.update(task_input.get("baseline_working") or {})
if kind is DeliverableKind.SCOPE and scoping and SCOPE_KEY not in working:
# The spec the customer supplied, or an empty one to draft into.
delivered = ((before or {}).get("attachments") or {}).get(SCOPE_FILE)
working[SCOPE_KEY] = (
# A Change request starts from the scope that was delivered.
(working_from_completed(delivered, scoping) if delivered else None)
or copy.deepcopy(
task_input.get("scope_working") or {"values": {}, "states": {}}
)
)
source = DEPENDENCY_GRAPH[kind].working_copy
if source and source is not kind:
# The tools work on the files as they were last submitted.
@@ -535,6 +595,7 @@ def make_execution_nodes(
library=task_input.get("library"),
review=review if submission_review else None,
baseline=before,
scoping=scoping,
# With a user present, their first sight of a Deliverable comes
# before it is submitted, whatever the Specialist intends.
confirm_first=confirm_drafts
@@ -874,6 +935,12 @@ 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")),
"scope_skill": (state.get("scope") or {}).get("skill"),
# The spec as supplied, for the scope analyst to complete; with the Customer
# case the Execution belongs to, which is not the customer's to restate.
"scope_working": _scope_seed(state) if kind is DeliverableKind.SCOPE else None,
"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 +970,13 @@ 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 {}),
# What the customer's scope spec states, leaves to the agent, and
# leaves unknown. None when no spec was supplied.
"scope": _agreed_scope(deliverables)
or (state.get("scope") or {}).get("context"),
# 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),
@@ -963,6 +1037,32 @@ def _requirement_changes(
)
def _scope_seed(state: ExecutionState) -> dict[str, Any]:
"""The scope spec the analyst starts from: what was supplied, and the Customer
case this Execution already belongs to."""
seed = copy.deepcopy(
(state.get("scope") or {}).get("working") or {"values": {}, "states": {}}
)
seed.setdefault("values", {}).setdefault(CASE_FIELD, _case(state))
return seed
def _agreed_scope(
deliverables: Mapping[str, Mapping[str, Any]],
) -> dict[str, Any] | None:
"""The scope every later Specialist reads: the scope Deliverable's data file."""
text = (
(deliverables.get(DeliverableKind.SCOPE.value) or {})
.get("attachments", {})
.get(SCOPE_DATA_FILE, "")
)
try:
data = json.loads(text) if text else None
except ValueError:
return None
return data if isinstance(data, dict) else None
async def _reading_hints(
state: ExecutionState,
ledger: Ledger,
@@ -1199,6 +1299,46 @@ def _case(state: ExecutionState) -> str:
return state.get("customer_case") or UNASSIGNED_CASE
def _scope_with_status(text: str, status: str) -> tuple[str, dict[str, Any] | None]:
"""A completed scope spec with its status set, and what the Execution's record
says of it. Unchanged, with no record, when it cannot be read."""
try:
document = yaml.safe_load(text)
except yaml.YAMLError:
return text, None
if not isinstance(document, dict):
return text, None
document.setdefault("metadata", {})["status"] = status
return (
yaml.safe_dump(document, sort_keys=False, allow_unicode=True),
{"status": status, "readiness": document.get("readiness")},
)
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 +1383,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 +1414,44 @@ def _write_outputs(
indent=2,
ensure_ascii=False,
)
plan = deliverables.get(DeliverableKind.WORK_BREAKDOWN.value)
plan_record: dict[str, Any] | None = None
if plan:
plan_record = plan_summary(plan.get("attachments", {}), deliverables) or None
timeline = str(plan.get("content", "")).partition("\n## Timeline\n")[2]
if guide and timeline:
# The guide and the plan are written side by side, so neither holds the
# other. The plan's timeline is added to the guide here, from the plan.
appendix = (
"\n\n## Delivery plan\n\n"
f"From the work breakdown structure (`deliverables/"
f"{DeliverableKind.WORK_BREAKDOWN.value}.md`), which has the work "
"packages and the full activity sequence.\n\n" + timeline.strip() + "\n"
)
files[GUIDE_FILENAME] = files[GUIDE_FILENAME].rstrip() + appendix
guide_document = f"deliverables/{DeliverableKind.SOLUTION_GUIDE.value}.md"
files[guide_document] = files[guide_document].rstrip() + appendix
scope_record: dict[str, Any] | None = None
if SCOPE_FILE in files:
# The completed scope spec says where it stands, here and beside the Intent.
approved = ledger.phase_status(PhaseId.SCOPING) is PhaseStatus.APPROVED
files[SCOPE_FILE], scope_record = _scope_with_status(
files[SCOPE_FILE],
LOCKED if status == "completed" else APPROVED if approved else UNDER_REVIEW,
)
version = state.get("intent_version")
if version:
copy_path = (
intent_dir(output_root, customer_case)
/ f"{int(version):03d}{SCOPE_COMPLETED}"
)
copy_path.parent.mkdir(parents=True, exist_ok=True)
copy_path.write_text(files[SCOPE_FILE], encoding="utf-8")
# 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 +1467,12 @@ 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")),
# Where the agreed scope stands and how much of it the customer stated.
"scope": scope_record,
# The plan in a few numbers: its length, and whether it fits the window.
"delivery_plan": plan_record,
"status": status,
"warnings": list(state.get("warnings", [])),
# Flags a person should look at; nothing was done about them.
@@ -1277,6 +1483,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,
}

View File

@@ -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

View File

@@ -14,6 +14,7 @@ tools, so the Ledger refuses anything that is not allowed, whatever was decided.
from __future__ import annotations
import json
import logging
import re
from collections.abc import Awaitable, Callable, Mapping, Sequence
@@ -37,6 +38,7 @@ from app.workflows.chain import (
IMPLEMENTATION_FILE,
RECOMMENDATIONS_FILE,
REQUIREMENTS_FILE,
SCOPE_DATA_FILE,
VERDICTS_FILE,
read_graph,
read_list,
@@ -44,6 +46,7 @@ from app.workflows.chain import (
validation_outcome,
)
from app.workflows.deliverables import DEPENDENCY_GRAPH, DeliverableKind, PhaseId
from app.workflows.work_breakdown import summary as plan_summary
logger = logging.getLogger(__name__)
@@ -634,6 +637,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
)
@@ -735,6 +744,30 @@ def approval_facts(phase: PhaseId, view: TurnView, r: Readings) -> dict[str, Any
),
}
facts["counts"] = {name: count for name, count in counts.items() if count}
scope = (view.deliverables.get(DeliverableKind.SCOPE.value) or {}).get(
"attachments", {}
)
if phase is PhaseId.SCOPING and scope.get(SCOPE_DATA_FILE):
# What approving the scope commits to: how much the customer stated, how
# much was assumed for them, and what is still unknown.
try:
agreed = json.loads(scope[SCOPE_DATA_FILE])
except ValueError:
agreed = {}
facts["scope"] = {
"kind": agreed.get("kind"),
"assumed": [item.get("field") for item in agreed.get("assumed", [])],
"left_to_decide": [
item.get("field") for item in agreed.get("to_decide", [])
],
"unknown": [item.get("field") for item in agreed.get("to_ask", [])],
}
plan = view.deliverables.get(DeliverableKind.WORK_BREAKDOWN.value)
if plan and phase is PhaseId.PACKAGING:
# How long the build is planned to take, and whether that fits.
facts["delivery_plan"] = plan_summary(
plan.get("attachments", {}), view.deliverables
)
graph = read_graph(view.deliverables)
if graph is not None:
facts["target_architecture"] = graph.summary()
@@ -770,6 +803,29 @@ def assembled_summary(phase: PhaseId, facts: Mapping[str, Any]) -> str:
lines.append(
", ".join(f"{count} {name}" for name, count in counts.items()) + "."
)
plan = facts.get("delivery_plan")
if plan:
fits = plan.get("within_window")
lines.append(
f"Delivery plan: {plan['activities']} activities in "
f"{plan['work_packages']} work packages, {plan['weeks']} weeks with a "
f"team of {plan['team_size']}"
+ (
""
if fits is None
else f", {'inside' if fits else 'over'} the "
f"{plan['window_weeks']}-week window"
)
+ "."
)
scope = facts.get("scope")
if scope:
lines.append(
f"Scope of a {scope.get('kind') or 'workload'}: "
f"{len(scope['assumed'])} fields assumed, "
f"{len(scope['unknown'])} still unknown. Requirements are derived "
"from it once you approve."
)
graph = facts.get("target_architecture")
if graph:
lines.append(

View File

@@ -14,6 +14,7 @@ from typing import Any
import yaml
from app.scope import Catalogue, load_catalogue
from app.skills.agent_skills import SkillFormatError, SkillMeta, discover_skills
TIERS = ("general", "cloud_read")
@@ -72,9 +73,30 @@ 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
# The Skill that holds the scope spec's catalogue (ADR-0008), and the values
# this provider allows for the fields the catalogue leaves to a provider.
scope_skill: str | None = None
scope_values: Mapping[str, tuple[str, ...]] = field(default_factory=dict)
def scope_catalogue(self) -> Catalogue:
if not self.scope_skill:
raise ProviderConfigError(f"The {self.name} bundle names no scope Skill.")
return load_catalogue(
self.skills[self.scope_skill].path / "assets" / "catalogue.yaml"
)
def mcp_servers_for_role(
self, role: str, include_preview: bool = True
@@ -155,6 +177,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:
@@ -208,6 +245,15 @@ def load_provider(name: str, root: Path | None = None) -> ProviderBundle:
if lessons_skill is not None and lessons_skill not in skills:
raise fail(f"'lessons_skill' references unknown skill {lessons_skill!r}")
scope = config.get("scope") or {}
scope_skill = scope.get("skill") or None
if scope_skill is not None and scope_skill not in skills:
raise fail(f"'scope.skill' references unknown skill {scope_skill!r}")
scope_values = {
str(path): tuple(str(value) for value in values or ())
for path, values in (scope.get("values") or {}).items()
}
return ProviderBundle(
name=name,
skills_dirs=skills_dirs,
@@ -221,5 +267,16 @@ 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,
scope_skill=scope_skill,
scope_values=scope_values,
)

501
app/scope.py Normal file
View File

@@ -0,0 +1,501 @@
"""The scope spec: what the customer wants and the facts a design depends on, as a
file (ADR-0008).
A spec may arrive complete, partly filled or not at all. This reads one against the
catalogue of fields a Skill holds, and says exactly what is settled and what is not.
No model is involved: whether a field is filled is a fact.
a value the customer states it supplied
ask, or absent not known yet a gap, with its question
decide the customer leaves the choice to the agent an assumption
not_applicable does not apply nothing asked or assumed
The file supplied is never altered. `Scope.completed()` is the copy written beside
it, with the sections the agent writes: assumptions, gaps, where each value came
from, and a count of each.
.venv/bin/python -m app.scope check <spec.yaml> [provider]
.venv/bin/python -m app.scope template [kind]
"""
from __future__ import annotations
import datetime as dt
import re
import sys
from collections.abc import Mapping, Sequence
from dataclasses import dataclass, field
from pathlib import Path
from typing import Any
import yaml
ASK, DECIDE, NOT_APPLICABLE = "ask", "decide", "not_applicable"
MARKERS = (ASK, DECIDE, NOT_APPLICABLE)
SUPPLIED, ASSUMED, UNKNOWN = "supplied", "assumed", "unknown"
# Where a settled value came from: the spec file, the customer's request in prose,
# an answer they gave in conversation, or the agent's own choice.
REQUEST, ANSWERED = "request", "answered"
SOURCES = (SUPPLIED, REQUEST, ANSWERED, ASSUMED)
ESSENTIAL, IMPORTANT, OPTIONAL = "essential", "important", "optional"
_SEVERITY = {ESSENTIAL: "HIGH", IMPORTANT: "MEDIUM", OPTIONAL: "LOW"}
DRAFT, UNDER_REVIEW, APPROVED, LOCKED = (
"DRAFT",
"UNDER_REVIEW",
"APPROVED",
"BASELINE_LOCKED",
)
KIND_FIELD = "engagement.kind"
CASE_FIELD = "metadata.customer_case"
STATEMENT_FIELD = "intent.statement"
# What the agent writes into the completed copy. A supplied file may still carry
# them from an earlier run; they are read as that run's and replaced.
_AGENT_WRITTEN = (
"schema_version",
"inferred_assumptions",
"discovery_gaps",
"provenance",
"readiness",
)
_AGENT_FIELDS = ("metadata.status",)
_SLUG = re.compile(r"[^a-z0-9]+")
class ScopeError(ValueError):
"""A scope spec that cannot be used, with every problem found in it."""
def __init__(self, problems: Sequence[str]) -> None:
self.problems = list(problems)
super().__init__("scope spec: " + "; ".join(self.problems))
@dataclass(frozen=True)
class FieldSpec:
path: str
type: str = "string"
tier: Any = OPTIONAL # a tier, or {kind: tier}
question: str = ""
default: Any = None
affects: str = ""
values: tuple[str, ...] = ()
provider_values: bool = False
keys: tuple[str, ...] = ()
optional_keys: tuple[str, ...] = ()
aliases: tuple[str, ...] = ()
# A choice a design must honour. Stated by the customer, it has to be carried
# by a requirement, and so by a Check on the Target architecture.
binds: bool = False
def tier_for(self, kind: str | None) -> str:
if isinstance(self.tier, Mapping):
return str(self.tier.get(kind, OPTIONAL))
return str(self.tier)
@dataclass(frozen=True)
class Catalogue:
schema_version: int
kinds: tuple[str, ...]
fields: Mapping[str, FieldSpec]
def aliases(self) -> dict[str, str]:
return {
alias: spec.path for spec in self.fields.values() for alias in spec.aliases
}
def load_catalogue(path: Path) -> Catalogue:
data = yaml.safe_load(path.read_text(encoding="utf-8")) or {}
fields = {}
for name, raw in (data.get("fields") or {}).items():
raw = raw or {}
fields[name] = FieldSpec(
path=name,
type=str(raw.get("type", "string")),
tier=raw.get("tier", OPTIONAL),
question=" ".join(str(raw.get("question", "")).split()),
default=raw.get("default"),
affects=str(raw.get("affects", "")),
values=tuple(str(v) for v in raw.get("values") or ()),
provider_values=bool(raw.get("provider_values")),
keys=tuple(raw.get("keys") or ()),
optional_keys=tuple(raw.get("optional_keys") or ()),
aliases=tuple(raw.get("aliases") or ()),
binds=bool(raw.get("binds")),
)
return Catalogue(
schema_version=int(data.get("schema_version", 1)),
kinds=tuple(data.get("kinds") or ()),
fields=fields,
)
@dataclass
class Scope:
"""A scope spec read against the catalogue."""
catalogue: Catalogue
kind: str | None
values: dict[str, Any] = field(default_factory=dict) # field -> stated value
states: dict[str, str] = field(default_factory=dict) # field -> marker
supplied_text: str = ""
# Where each value came from, when it was not the spec file; and what was said
# about it: the reason for an assumption, the question an answer was given to.
sources: dict[str, str] = field(default_factory=dict)
notes: dict[str, str] = field(default_factory=dict)
def source(self, path: str) -> str:
return self.sources.get(path, SUPPLIED)
@property
def customer_case(self) -> str | None:
value = self.values.get(CASE_FIELD)
return str(value) if value else None
@property
def statement(self) -> str:
return str(self.values.get(STATEMENT_FIELD) or "").strip()
def tier(self, path: str) -> str:
return self.catalogue.fields[path].tier_for(self.kind)
def gaps(self, *tiers: str) -> list[dict[str, str]]:
"""What is not known, most pressing first: each with the question to ask."""
wanted = tiers or (ESSENTIAL, IMPORTANT, OPTIONAL)
found = [
{
"field": path,
"prompt": self.catalogue.fields[path].question or f"What is {path}?",
"severity": _SEVERITY[self.tier(path)],
}
for path, state in self.states.items()
if state == ASK and self.tier(path) in wanted
]
order = {"HIGH": 0, "MEDIUM": 1, "LOW": 2}
return sorted(found, key=lambda gap: order[gap["severity"]])
def assumptions(self) -> list[dict[str, str]]:
"""What the customer left to the agent, each with the default to take and
what a wrong choice would change."""
found: list[dict[str, str]] = []
for path in self.catalogue.fields:
chosen = path in self.values and self.source(path) == ASSUMED
if not chosen and self.states.get(path) != DECIDE:
continue
spec = self.catalogue.fields[path]
if chosen:
statement = f"Assumed {path} is {self.values[path]}."
if self.notes.get(path):
statement += f" {self.notes[path]}"
else:
default = spec.default if spec.default is not None else "its choice"
statement = (
f"The customer left {path} to the agent. Default: {default}."
)
found.append(
{
"id": f"ASSUMP-{len(found) + 1:02d}",
"field": path,
"statement": statement,
"impact_if_invalid": f"Changes {spec.affects}."
if spec.affects
else "Local to this field.",
}
)
return found
def readiness(self) -> dict[str, int]:
states = list(self.states.values())
came = [self.source(path) for path in self.values]
return {
SUPPLIED: came.count(SUPPLIED) + came.count(REQUEST),
ANSWERED: came.count(ANSWERED),
ASSUMED: came.count(ASSUMED) + states.count(DECIDE),
UNKNOWN: states.count(ASK),
NOT_APPLICABLE: states.count(NOT_APPLICABLE),
}
def status(self, pre_approved: bool = False) -> str:
"""Where the spec stands. With nobody to ask, what is important and unknown
is defaulted and listed, so only an essential gap keeps it a draft."""
if pre_approved:
return DRAFT if self.gaps(ESSENTIAL) else APPROVED
return DRAFT if self.gaps(ESSENTIAL, IMPORTANT) else UNDER_REVIEW
def completed(self, status: str) -> dict[str, Any]:
"""The completed copy: every field of the catalogue, and the agent's
sections."""
document: dict[str, Any] = {"schema_version": self.catalogue.schema_version}
for path in self.catalogue.fields:
value = self.values.get(path, self.states.get(path, ASK))
_put(document, path, value)
_put(document, "metadata.status", status)
provenance = {path: self.source(path) for path in self.values}
provenance |= {
path: {DECIDE: ASSUMED, ASK: UNKNOWN, NOT_APPLICABLE: NOT_APPLICABLE}[state]
for path, state in self.states.items()
}
document["inferred_assumptions"] = self.assumptions()
document["discovery_gaps"] = self.gaps()
document["provenance"] = dict(sorted(provenance.items()))
document["readiness"] = self.readiness()
return document
def for_context(self) -> dict[str, Any]:
"""What a Specialist is shown: what the customer stated, what is theirs to
choose, and what is unknown."""
stated: dict[str, Any] = {}
for path, value in self.values.items():
if path.startswith(("run.", "metadata.")) or self.source(path) == ASSUMED:
continue
_put(stated, path, value)
return {
"kind": self.kind,
"stated": stated,
# The stated fields a design must honour: each has to be carried by a
# requirement, which the requirements are checked for.
"binding": [
path
for path in self.values
if self.catalogue.fields[path].binds and self.source(path) != ASSUMED
],
# What the agent chose where the customer did not say. Not the
# customer's decision: it may be revisited when they answer.
"assumed": [
{"field": path, "value": value, "why": self.notes.get(path, "")}
for path, value in self.values.items()
if self.source(path) == ASSUMED and not path.startswith("run.")
],
"to_decide": [
{
"field": path,
"default": self.catalogue.fields[path].default,
"affects": self.catalogue.fields[path].affects,
}
for path, state in self.states.items()
if state == DECIDE and not path.startswith("run.")
],
"to_ask": [
gap for gap in self.gaps() if not gap["field"].startswith("run.")
],
"not_applicable": sorted(
path for path, state in self.states.items() if state == NOT_APPLICABLE
),
}
def _put(document: dict[str, Any], path: str, value: Any) -> None:
*parents, last = path.split(".")
node = document
for part in parents:
node = node.setdefault(part, {})
node[last] = value
def slug(reference: str) -> str:
"""A Customer case id from an engagement reference: `ENG-2026-UK-084` and
`eng-2026-uk-084` name the same case."""
return _SLUG.sub("-", reference.strip().lower()).strip("-")[:64]
def read_scope(
supplied: str | Mapping[str, Any],
catalogue: Catalogue,
*,
provider_values: Mapping[str, Sequence[str]] | None = None,
) -> Scope:
"""Read a scope spec. Raises ScopeError naming every problem: YAML that does not
parse, a field the catalogue does not have, a value of the wrong type."""
text = supplied if isinstance(supplied, str) else yaml.safe_dump(dict(supplied))
try:
data = yaml.safe_load(text) if isinstance(supplied, str) else dict(supplied)
except yaml.YAMLError as exc:
raise ScopeError([f"not valid YAML ({exc})"]) from exc
if not isinstance(data, Mapping):
raise ScopeError(["the spec must be a mapping of sections"])
problems: list[str] = []
leaves: dict[str, Any] = {}
aliases = catalogue.aliases()
prefixes = {
".".join(path.split(".")[:depth])
for path in catalogue.fields
for depth in range(1, len(path.split(".")))
}
def walk(node: Any, path: str) -> None:
target = aliases.get(path, path)
if path in _AGENT_FIELDS or path in _AGENT_WRITTEN:
return
if target in catalogue.fields:
if target in leaves and leaves[target] != node and path != target:
problems.append(f"{path} and {target} name the same thing and differ")
leaves[target] = node
return
if path in prefixes:
if isinstance(node, Mapping):
for key, value in node.items():
walk(value, f"{path}.{key}")
elif node in MARKERS or node is None:
# A whole section marked at once applies to every field in it.
for name in catalogue.fields:
if name.startswith(path + "."):
leaves.setdefault(name, node)
else:
problems.append(f"{path} is a section, not a value")
return
problems.append(f"{path} is not a field of the scope spec")
for key, value in data.items():
walk(value, str(key))
kind = leaves.get(KIND_FIELD)
kind = str(kind) if kind in catalogue.kinds else None
scope = Scope(catalogue, kind, supplied_text=text)
extra = dict(provider_values or {})
for path, spec in catalogue.fields.items():
value = leaves.get(path)
if value is None or value == ASK:
scope.states[path] = ASK
elif value in (DECIDE, NOT_APPLICABLE):
scope.states[path] = value
else:
fault = _fault(spec, value, extra.get(path, ()))
if fault:
problems.append(f"{path}: {fault}")
else:
scope.values[path] = _plain(value)
case = scope.values.get(CASE_FIELD)
if case is not None:
scope.values[CASE_FIELD] = slug(str(case))
if not scope.values[CASE_FIELD]:
problems.append(f"{CASE_FIELD}: needs letters or digits")
if problems:
raise ScopeError(problems)
return scope
def _plain(value: Any) -> Any:
"""A value as plain data: YAML reads a date as a date, and state must be JSON."""
if isinstance(value, (dt.date, dt.datetime)):
return value.isoformat()
if isinstance(value, Mapping):
return {str(k): _plain(v) for k, v in value.items()}
if isinstance(value, (list, tuple)):
return [_plain(item) for item in value]
return value
def _fault(spec: FieldSpec, value: Any, provider_values: Sequence[str]) -> str:
"""Why a value does not fit its field; "" when it does."""
kind = spec.type
if kind in ("string", "text"):
return "" if isinstance(value, (str, int, float)) else "must be text"
if kind == "integer":
ok = isinstance(value, int) and not isinstance(value, bool)
return "" if ok else "must be a whole number"
if kind == "number":
ok = isinstance(value, (int, float)) and not isinstance(value, bool)
return "" if ok else "must be a number"
if kind == "boolean":
return "" if isinstance(value, bool) else "must be true or false"
if kind == "date":
if isinstance(value, (dt.date, dt.datetime)):
return ""
try:
dt.date.fromisoformat(str(value))
except ValueError:
return "must be a date, as YYYY-MM-DD"
return ""
if kind == "enum":
allowed = (*spec.values, *provider_values)
if not allowed or str(value) in allowed:
return ""
return f"must be one of {', '.join(allowed)}"
if kind == "list":
return "" if isinstance(value, list) else "must be a list"
if kind == "records":
if not isinstance(value, list):
return "must be a list of entries"
known = {*spec.keys, *spec.optional_keys}
for number, entry in enumerate(value, start=1):
if not isinstance(entry, Mapping):
return f"entry {number} must have named fields"
missing = [key for key in spec.keys if not entry.get(key)]
if missing:
return f"entry {number} needs {', '.join(missing)}"
unknown = sorted(set(map(str, entry)) - known)
if unknown:
return f"entry {number} has unknown fields {', '.join(unknown)}"
return ""
return f"has an unknown type {kind} in the catalogue"
def render_template(catalogue: Catalogue, kind: str | None = None) -> str:
"""A scope spec with every field set to ask, to fill in."""
document: dict[str, Any] = {}
for path, spec in catalogue.fields.items():
if path == KIND_FIELD and kind:
_put(document, path, kind)
elif spec.tier_for(kind) != OPTIONAL or kind is None:
_put(document, path, ASK)
header = (
"# Scope spec. Give each field a value, or: ask (not known yet), decide\n"
"# (you choose), not_applicable. A field left out is read as ask.\n"
)
return header + yaml.safe_dump(document, sort_keys=False, allow_unicode=True)
def render_reading(scope: Scope) -> str:
"""What a spec settles and what it leaves open, for a person."""
counts = scope.readiness()
lines = [
f"Engagement kind: {scope.kind or 'not stated'}",
(
f"{counts[SUPPLIED]} supplied, {counts[ASSUMED]} left to the agent, "
f"{counts[UNKNOWN]} unknown, {counts[NOT_APPLICABLE]} not applicable."
),
]
for severity, title in (
("HIGH", "Essential, needed before work can start"),
("MEDIUM", "Important, asked when someone is present"),
):
gaps = [gap for gap in scope.gaps() if gap["severity"] == severity]
if gaps:
lines += ["", f"{title}:"]
lines += [f" {gap['field']}: {gap['prompt']}" for gap in gaps]
return "\n".join(lines)
def main(arguments: Sequence[str]) -> int:
from app.config import get_settings
from app.providers import load_provider
command, rest = (arguments[0], arguments[1:]) if arguments else ("", [])
if command == "template":
bundle = load_provider(get_settings().CLOUD_PROVIDER)
print(render_template(bundle.scope_catalogue(), rest[0] if rest else None))
return 0
if command == "check" and rest:
bundle = load_provider(
rest[1] if len(rest) > 1 else get_settings().CLOUD_PROVIDER
)
try:
scope = read_scope(
Path(rest[0]).read_text(encoding="utf-8"),
bundle.scope_catalogue(),
provider_values=bundle.scope_values,
)
except ScopeError as refused:
print("This spec cannot be used:")
for problem in refused.problems:
print(f" {problem}")
return 1
print(render_reading(scope))
return 0
print(__doc__, file=sys.stderr)
return 2
if __name__ == "__main__":
sys.exit(main(sys.argv[1:]))

View File

@@ -58,6 +58,10 @@ 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
# The customer's scope spec as read at the start: its Skill, status, readiness
# and what a Specialist is shown of it. None when no spec was supplied.
scope: dict[str, Any] | None
baseline: dict[str, Any] | None # a Change request's Baseline, read from its files
pre_approved: bool
allow_cloud_read: bool | None

View File

@@ -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
View 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])

View File

@@ -22,6 +22,14 @@ from app.adk.runtime import (
)
from app.states.ledger import Ledger, LedgerRefusal, PhaseStatus
from app.tools.pillars import REVIEW_HEADING, render_checklist_review
from app.tools.scoping import (
REGISTER_HEADING,
Scoping,
render_register,
scope_tools,
unsettled,
)
from app.tools.scoping import attachments as scope_attachments
from app.tools.workspace import (
FILES,
basis_of,
@@ -53,6 +61,12 @@ from app.workflows.target_architecture import (
render_mermaid,
render_tables,
)
from app.workflows.work_breakdown import (
DICTIONARY_HEADING,
TIMELINE_FILE,
)
from app.workflows.work_breakdown import mermaid as plan_mermaid
from app.workflows.work_breakdown import render as render_plan
ORCHESTRATOR = "orchestrator"
logger = logging.getLogger(__name__)
@@ -284,6 +298,7 @@ def specialist_tools(
review: Callable[[Mapping[str, str]], Awaitable[Sequence[str]]] | None = None,
confirm_first: bool = False,
baseline: Mapping[str, Any] | None = None,
scoping: Scoping | None = None,
) -> list[ToolSpec]:
"""A Specialist's tools: submit, ask, its working copy, and its role's tools with
the cloud-read gate.
@@ -298,6 +313,8 @@ def specialist_tools(
this Deliverable: a submission is then refused until the Specialist has put its
draft to them. A rule, because an instruction alone was not always followed.
`baseline` is the Baseline's version of this Deliverable in a Change request.
`scoping` is the scope spec's catalogue; with it the scope Deliverable's two
files and its information register are written from what was recorded.
"""
working = {} if working is None else working
is_graph = kind is DeliverableKind.TARGET_ARCHITECTURE
@@ -310,12 +327,30 @@ def specialist_tools(
if is_validation:
working_verdicts(working, basis) # drops verdicts given on other code
graph_now = read_graph(upstream)
is_scope = kind is DeliverableKind.SCOPE and scoping is not None
async def submit_deliverable(content: str, attachments: Any = None) -> ToolResult:
try:
attachments = files_from_argument(attachments)
except TypeError as exc:
return _refused(f"attachments: {exc}")
if is_scope and scoping is not None:
# Nothing essential may be left unknown, and the files are written
# from what was recorded: they cannot disagree with it.
missing_fields = unsettled(working, scoping)
if missing_fields:
return ToolResult(
"Not submitted. Essential fields of the scope spec are not "
"settled: " + ", ".join(missing_fields) + ". Ask the user for "
"each with `needs_input`; when you may not ask, choose a value "
"and record it with `source` assumed and a note."
)
attachments = scope_attachments(working, scoping)
content = (
content.split(f"\n## {REGISTER_HEADING}")[0].rstrip()
+ "\n\n"
+ render_register(working, scoping)
)
# The working copy is the submission; a file passed here replaces its copy.
if own_files:
attachments = {**working_files(working), **attachments}
@@ -375,6 +410,16 @@ def specialist_tools(
content = content.split(f"\n## {REVIEW_HEADING}")[0].rstrip() + "\n"
if checklist_review:
content += "\n" + checklist_review
if kind is DeliverableKind.WORK_BREAKDOWN:
# The dictionary, the sequence and the timeline are views of the plan,
# computed and written here: they cannot disagree with it.
views = render_plan(attachments, upstream)
content = content.split(f"\n## {DICTIONARY_HEADING}")[0].rstrip() + "\n"
if views:
content += "\n" + views
chart = plan_mermaid(attachments, upstream)
if chart:
attachments[TIMELINE_FILE] = chart
if is_graph:
# The tables and the diagram are views of the graph, so the engine
# writes them: they cannot disagree with it.
@@ -455,6 +500,7 @@ def specialist_tools(
if library
else ()
),
*(scope_tools(working, scoping) if is_scope and scoping else ()),
*(graph_tools(working) if is_graph else ()),
*(
verdict_tools(working, basis, graph_now.check_ids if graph_now else ())

View File

@@ -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,11 @@ class TerraformRunner:
)
async def validate(self, files: Mapping[str, str]) -> ToolResult:
refusal = _check_files(files)
refusal = (
_check_files(files)
or check_providers(files, self.providers)
or check_module_sources(files, allowed_namespaces(self.module_namespaces))
)
if refusal:
return refusal
with tempfile.TemporaryDirectory(prefix="tf-validate-") as tmp:
@@ -153,7 +162,11 @@ 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_providers(files, self.providers)
or check_module_sources(files, allowed_namespaces(self.module_namespaces))
)
if refusal:
return refusal
variables = dict(variables or {})
@@ -354,6 +367,45 @@ class TerraformRunner:
return process.returncode or 0, stdout.decode(errors="replace")
_BLOCK_TYPE = re.compile(
r'^\s*(?:resource|data)\s+"([a-z0-9]+)_[a-z0-9_]*"', re.MULTILINE
)
_PROVIDER_SOURCE = re.compile(r'^\s*source\s*=\s*"([\w.-]+/[\w.-]+)"\s*$', re.MULTILINE)
# Built into Terraform itself: terraform_data and the terraform_remote_state source.
_BUILT_IN = frozenset({"terraform"})
def check_providers(
files: Mapping[str, str], pinned: Mapping[str, Mapping[str, str]]
) -> ToolResult | None:
"""Refuse code that uses a provider the bundle does not pin.
`terraform init` downloads whatever provider the code names, at whatever
version is current. A design with a source repository in it brought the GitHub
provider into generated code that way on 2026-10-11. With nothing pinned there
is nothing to hold code to, and it passes.
"""
if not pinned:
return None
names = set(pinned) | _BUILT_IN
sources = {pin["source"] for pin in pinned.values()}
code = "\n".join(text for name, text in files.items() if name.endswith(".tf"))
foreign = sorted({m.group(1) for m in _BLOCK_TYPE.finditer(code)} - names)
undeclared = sorted({m.group(1) for m in _PROVIDER_SOURCE.finditer(code)} - sources)
if not foreign and not undeclared:
return None
found = [f"resources of the {name} provider" for name in foreign]
found += [f"the provider {source}" for source in undeclared]
return ToolResult(
"Refused: the code uses "
+ ", ".join(found)
+ ". Only these providers may be used: "
+ ", ".join(sorted(sources))
+ ". Write resources of those alone, and describe anything outside them in "
"the deployment guidance as a step the user takes."
)
def _check_files(files: Mapping[str, str]) -> ToolResult | None:
if not files:
return ToolResult("Refused: provide at least one Terraform file.")
@@ -582,6 +634,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 +713,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
View 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)

View File

@@ -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")
]

View File

@@ -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)]

322
app/tools/scoping.py Normal file
View File

@@ -0,0 +1,322 @@
"""The scope analyst's tools: completing the scope spec (ADR-0008).
The spec is kept in the scope Deliverable's working memory as plain data, seeded
from what the customer supplied. The analyst reads what is settled and what is
not, and records each value it settles with where the value came from. Code checks
every value against the catalogue as it is recorded, and writes the completed copy
and the information register from what is there when the Deliverable is submitted:
the spec the customer approves cannot disagree with what was recorded.
"""
from __future__ import annotations
import json
from collections.abc import Mapping, MutableMapping, Sequence
from dataclasses import dataclass, field
from typing import Any
import yaml
from app.adk.runtime import ToolResult, ToolSpec
from app.scope import (
ANSWERED,
ASK,
ASSUMED,
DECIDE,
ESSENTIAL,
IMPORTANT,
MARKERS,
NOT_APPLICABLE,
REQUEST,
SOURCES,
SUPPLIED,
UNDER_REVIEW,
Catalogue,
Scope,
ScopeError,
_fault,
_plain,
read_scope,
)
from app.workflows.chain import SCOPE_DATA_FILE, SCOPE_FILE
SCOPE_KEY = "scope_spec" # working memory: the spec as it is being completed
REGISTER_HEADING = "Information register"
@dataclass(frozen=True)
class Scoping:
"""What reading and completing a scope spec needs."""
catalogue: Catalogue
provider_values: Mapping[str, Sequence[str]] = field(default_factory=dict)
skill: str | None = None
def to_working(scope: Scope) -> dict[str, Any]:
"""A spec as working memory: plain data that survives a checkpoint."""
return {
"kind": scope.kind,
"values": dict(scope.values),
"states": dict(scope.states),
"sources": dict(scope.sources),
"notes": dict(scope.notes),
}
def from_working(memory: Mapping[str, Any], catalogue: Catalogue) -> Scope:
values = dict(memory.get("values") or {})
states = {
path: (memory.get("states") or {}).get(path, ASK)
for path in catalogue.fields
if path not in values
}
kind = values.get("engagement.kind")
return Scope(
catalogue,
str(kind) if kind in catalogue.kinds else None,
values=values,
states=states,
sources=dict(memory.get("sources") or {}),
notes=dict(memory.get("notes") or {}),
)
def working_from_completed(text: str, scoping: Scoping) -> dict[str, Any] | None:
"""A completed scope spec as working memory, with where each value came from.
None when it cannot be read: a Change request then drafts the scope afresh."""
try:
scope = read_scope(
text, scoping.catalogue, provider_values=scoping.provider_values
)
document = yaml.safe_load(text) or {}
except (ScopeError, yaml.YAMLError):
return None
recorded = document.get("provenance") if isinstance(document, Mapping) else None
scope.sources = {
path: str(source)
for path, source in (recorded or {}).items()
if path in scope.values and source in SOURCES
}
return to_working(scope)
def working_scope(working: MutableMapping[str, Any]) -> dict[str, Any]:
return working.setdefault(SCOPE_KEY, {"values": {}, "states": {}})
def unsettled(working: Mapping[str, Any], scoping: Scoping) -> list[str]:
"""The essential fields a submission may not leave unknown."""
scope = from_working(working.get(SCOPE_KEY) or {}, scoping.catalogue)
return [gap["field"] for gap in scope.gaps(ESSENTIAL)]
def attachments(working: Mapping[str, Any], scoping: Scoping) -> dict[str, str]:
"""The Deliverable's two files, written from what was recorded."""
scope = from_working(working.get(SCOPE_KEY) or {}, scoping.catalogue)
return {
SCOPE_FILE: yaml.safe_dump(
scope.completed(UNDER_REVIEW), sort_keys=False, allow_unicode=True
),
SCOPE_DATA_FILE: json.dumps(scope.for_context(), indent=2, ensure_ascii=False),
}
_FROM = {
SUPPLIED: "the scope spec",
REQUEST: "the request",
ANSWERED: "the customer's answer",
ASSUMED: "assumed",
}
def render_register(working: Mapping[str, Any], scoping: Scoping) -> str:
"""The information register, readiness and open questions, as markdown written
by code from what was recorded."""
scope = from_working(working.get(SCOPE_KEY) or {}, scoping.catalogue)
counts = scope.readiness()
lines = [
f"## {REGISTER_HEADING}",
"",
(
f"{counts[SUPPLIED]} stated by the customer, {counts[ANSWERED]} answered "
f"in conversation, {counts[ASSUMED]} assumed, {counts['unknown']} "
f"unknown, {counts[NOT_APPLICABLE]} not applicable."
),
"",
"| Field | Value | From |",
"| --- | --- | --- |",
]
for path, value in scope.values.items():
if path.startswith(("run.", "metadata.")):
continue
shown = (
json.dumps(value, ensure_ascii=False)
if isinstance(value, (list, dict))
else str(value)
)
shown = " ".join(shown.split()).replace("|", "\\|")
lines.append(f"| {path} | {shown[:200]} | {_FROM[scope.source(path)]} |")
assumed = scope.assumptions()
if assumed:
lines += [
"",
"### Assumptions",
"",
"| Id | Assumption | If it is wrong |",
"| --- | --- | --- |",
]
lines += [
f"| {item['id']} | {item['statement']} | {item['impact_if_invalid']} |"
for item in assumed
]
gaps = scope.gaps(ESSENTIAL, IMPORTANT)
if gaps:
lines += [
"",
"### Still to confirm with the customer",
"",
"| Field | Question | Severity |",
"| --- | --- | --- |",
]
lines += [
f"| {gap['field']} | {gap['prompt']} | {gap['severity']} |" for gap in gaps
]
return "\n".join(lines) + "\n"
def scope_tools(working: MutableMapping[str, Any], scoping: Scoping) -> list[ToolSpec]:
catalogue = scoping.catalogue
async def scope_read() -> ToolResult:
scope = from_working(working_scope(working), catalogue)
counts = scope.readiness()
lines = [
f"Kind of engagement: {scope.kind or 'not settled'}",
(
f"{counts[SUPPLIED]} stated, {counts[ANSWERED]} answered, "
f"{counts[ASSUMED]} assumed, {counts['unknown']} unknown."
),
]
for severity, title in (("HIGH", "Essential"), ("MEDIUM", "Important")):
gaps = [gap for gap in scope.gaps() if gap["severity"] == severity]
if gaps:
lines.append(f"{title}, not settled:")
lines += [f" {gap['field']}: {gap['prompt']}" for gap in gaps]
left = [
path
for path, state in scope.states.items()
if state == DECIDE and not path.startswith("run.")
]
if left:
lines.append("Left to you to decide: " + ", ".join(left))
lines.append("Settled: " + (", ".join(scope.values) or "nothing yet"))
return ToolResult("\n".join(lines))
async def scope_set(entries: Any = None) -> ToolResult:
if not isinstance(entries, list) or not entries:
return ToolResult("Refused: `entries` is a list of fields to record.")
memory = working_scope(working)
values, states = (
memory.setdefault("values", {}),
memory.setdefault("states", {}),
)
sources, notes = (
memory.setdefault("sources", {}),
memory.setdefault("notes", {}),
)
problems, done = [], []
for entry in entries:
if not isinstance(entry, Mapping):
problems.append("each entry needs a field")
continue
path = str(entry.get("field", ""))
spec = catalogue.fields.get(path)
if spec is None:
problems.append(f"{path} is not a field of the scope spec")
continue
source, value = str(entry.get("source", "")), entry.get("value")
note = " ".join(str(entry.get("note") or "").split())
if value in MARKERS:
if path in values and sources.get(path, SUPPLIED) == SUPPLIED:
problems.append(f"{path} was stated in the scope spec; it stays")
continue
values.pop(path, None)
states[path] = value
done.append(path)
continue
if source not in SOURCES or source == SUPPLIED:
problems.append(
f"{path}: `source` is request (the customer's request says it), "
"answered (they told you) or assumed (you chose)"
)
continue
if (
path in values
and sources.get(path, SUPPLIED) == SUPPLIED
and source != ANSWERED
):
problems.append(
f"{path} was stated in the scope spec; only the customer's own "
"answer changes it"
)
continue
if source == ASSUMED and not note:
problems.append(f"{path}: an assumption needs a note saying why")
continue
fault = _fault(spec, value, scoping.provider_values.get(path, ()))
if fault:
problems.append(f"{path}: {fault}")
continue
values[path] = _plain(value)
states.pop(path, None)
sources[path] = source
if note:
notes[path] = note
done.append(path)
message = f"Recorded {len(done)}: {', '.join(done) or 'none'}."
if problems:
message += " Not recorded: " + "; ".join(problems) + "."
return ToolResult(message)
return [
ToolSpec(
"scope_read",
"What the scope spec settles so far, and what is not settled, with the "
"question to ask for each.",
{"type": "object", "properties": {}, "required": []},
scope_read,
tier="execution",
),
ToolSpec(
"scope_set",
"Record fields of the scope spec. Each entry has `field`, `value`, "
"`source` (request, answered or assumed) and, for an assumption, a "
"`note` saying why. A `value` of ask, decide or not_applicable marks the "
"field instead. Record several fields in one call.",
{
"type": "object",
"properties": {
"entries": {
"type": "array",
"items": {
"type": "object",
"properties": {
"field": {"type": "string"},
"value": {},
"source": {
"type": "string",
"enum": [REQUEST, ANSWERED, ASSUMED],
},
"note": {"type": "string"},
},
"required": ["field", "value"],
},
}
},
"required": ["entries"],
},
scope_set,
tier="execution",
),
]

View File

@@ -33,6 +33,8 @@ PRODUCTS_FILE = "products.json"
RECOMMENDATIONS_FILE = "recommendations.json"
IMPLEMENTATION_FILE = "implementation.json"
VERDICTS_FILE = "verdicts.json"
SCOPE_FILE = "scope.yaml" # the completed scope spec
SCOPE_DATA_FILE = "scope.json" # what every Specialist reads of it
REQUIREMENT_KINDS = ("functional", "non_functional")
VERDICTS = ("pass", "fail", "not_verifiable")
@@ -211,9 +213,87 @@ def check_requirements(
problems += _lacking_conditions(
[item for item in items if item["kind"] == "non_functional"], name
)
problems += _carries_the_scope(items, name, upstream)
return problems
def agreed_scope(upstream: Upstream | None) -> dict[str, Any]:
"""The agreed scope, as every Specialist reads it; empty when there is none."""
text = (
((upstream or {}).get("scope") or {})
.get("attachments", {})
.get(SCOPE_DATA_FILE, "")
)
try:
data = json.loads(text) if text else {}
except ValueError:
return {}
return data if isinstance(data, dict) else {}
def sources_of(item: Mapping[str, Any]) -> tuple[str, ...]:
"""What a requirement comes from: the customer's own requirement ids and the
scope spec's fields, as its `from` lists them."""
listed = item.get("from")
return tuple(str(s) for s in listed) if isinstance(listed, list) else ()
def _carries_the_scope(
items: Sequence[Mapping[str, Any]], name: str, upstream: Upstream | None
) -> list[str]:
"""What the customer stated has to reach the requirements, by name (ADR-0008).
Each requirement the customer wrote, and each choice they stated that a design
must honour, is named in the `from` of a requirement. A choice is carried by a
non-functional requirement with a condition, so the Target architecture owes it
a Check. Before this a stated topology could be named in a design and not built:
case 08 on 2026-10-11 passed all 101 Checks with no Check asking for it.
"""
scope = agreed_scope(upstream)
if not scope:
return []
stated = scope.get("stated") or {}
theirs = [
str(entry.get("id"))
for entry in ((stated.get("intent") or {}).get("requirements") or [])
if isinstance(entry, Mapping) and entry.get("id")
]
binding = [str(path) for path in scope.get("binding") or []]
cited = {source for item in items for source in sources_of(item)}
problems = [
f"{name}: the customer's requirement {reference} is covered by no "
"requirement; name it in the `from` of the one that covers it"
for reference in theirs
if reference not in cited
]
problems += [
f"{name}: the customer stated {path} and no requirement carries it; add a "
f"non-functional requirement whose `from` names {path}, with the condition "
"that shows it was honoured"
for path in binding
if path not in cited
]
for item in items:
carried = [source for source in sources_of(item) if source in binding]
if carried and (
item.get("kind") != "non_functional" or not conditions_of_listed(item)
):
problems.append(
f"{name}: {item.get('id')} carries {', '.join(carried)}, a choice "
"the customer stated; it must be non_functional with at least one "
"entry in `conditions`, so the design is checked against it"
)
return problems
def conditions_of_listed(item: Mapping[str, Any]) -> tuple[str, ...]:
"""The conditions a requirement lists outright, with no fallback to its text."""
listed = item.get("conditions")
if not isinstance(listed, list):
return ()
return tuple(c.strip() for c in listed if isinstance(c, str) and c.strip())
def check_components(
attachments: Mapping[str, str], upstream: Upstream | None
) -> list[str]:
@@ -343,6 +423,19 @@ def _split_implementation(text: str, name: str) -> tuple[str, str]:
return json.dumps(met), json.dumps(cannot)
def check_scope(attachments: Mapping[str, str], upstream: Upstream | None) -> list[str]:
"""The scope a Specialist reads: what the customer stated, what was left to the
agent, and what is unknown."""
name = SCOPE_DATA_FILE
try:
data = json.loads(attachments[name])
except ValueError as exc:
return [f"{name}: not valid JSON ({exc})"]
if not isinstance(data, dict) or not isinstance(data.get("stated"), dict):
return [f"{name}: must be an object with what the customer stated"]
return []
def check_implementation(
attachments: Mapping[str, str], upstream: Upstream | None
) -> list[str]:

View File

@@ -19,6 +19,8 @@ from app.workflows.chain import (
PRODUCTS_FILE,
RECOMMENDATIONS_FILE,
REQUIREMENTS_FILE,
SCOPE_DATA_FILE,
SCOPE_FILE,
VERDICTS_FILE,
Upstream,
check_components,
@@ -26,15 +28,20 @@ from app.workflows.chain import (
check_products,
check_recommendations,
check_requirements,
check_scope,
check_target_architecture,
check_verdicts,
graph_structure,
)
from app.workflows.changes import check_requirement_changes
from app.workflows.target_architecture import GRAPH_ATTACHMENT
from app.workflows.work_breakdown import WORK_BREAKDOWN_FILE, check_work_breakdown
class PhaseId(StrEnum):
# Scoping: what the customer wants and the facts a design depends on, agreed
# before requirements are derived from it (ADR-0008).
SCOPING = "scoping"
REQUIREMENTS_DISCOVERY = "requirements_discovery"
# Design: ends with the Target architecture, approved before any code is written.
SOLUTION_ARCHITECTURE = "solution_architecture"
@@ -47,6 +54,7 @@ PHASE_ORDER: tuple[PhaseId, ...] = tuple(PhaseId)
class DeliverableKind(StrEnum):
SCOPE = "scope"
REQUIREMENTS = "requirements"
TECHNICAL_DECOMPOSITION = "technical_decomposition"
PRODUCT_SELECTION = "product_selection"
@@ -55,6 +63,8 @@ class DeliverableKind(StrEnum):
ARCHITECTURE_DESCRIPTION = "architecture_description"
DEPLOYMENT_GUIDANCE = "deployment_guidance"
VALIDATION_RESULTS = "validation_results"
# The plan for building what was designed and validated (iteration 10).
WORK_BREAKDOWN = "work_breakdown"
SOLUTION_GUIDE = "solution_guide"
@@ -92,10 +102,20 @@ _K = DeliverableKind
DEPENDENCY_GRAPH: Mapping[DeliverableKind, DeliverableSpec] = {
spec.kind: spec
for spec in (
DeliverableSpec(
_K.SCOPE,
PhaseId.SCOPING,
"scope-analyst",
sections=("Scope statement",),
# The completed scope spec, for people and for reuse; and what every
# later Specialist reads of it.
attachments=(SCOPE_FILE, SCOPE_DATA_FILE),
),
DeliverableSpec(
_K.REQUIREMENTS,
PhaseId.REQUIREMENTS_DISCOVERY,
"requirements-analyst",
depends_on=(_K.SCOPE,),
sections=(
"Functional requirements",
"Non-functional requirements",
@@ -183,6 +203,16 @@ DEPENDENCY_GRAPH: Mapping[DeliverableKind, DeliverableSpec] = {
attachments=(VERDICTS_FILE,),
working_copy=_K.DEPLOYMENT_GUIDANCE,
),
DeliverableSpec(
_K.WORK_BREAKDOWN,
PhaseId.PACKAGING,
"delivery-planner",
depends_on=(_K.VALIDATION_RESULTS,),
sections=("Approach",),
attachments=(WORK_BREAKDOWN_FILE,),
# A plan covers the design and how it is built: the graph and the code.
reads_in_full=(_K.TARGET_ARCHITECTURE, _K.DEPLOYMENT_GUIDANCE),
),
DeliverableSpec(
_K.SOLUTION_GUIDE,
PhaseId.PACKAGING,
@@ -209,6 +239,7 @@ DATA_CHECKS: Mapping[
DeliverableKind,
tuple[str, Callable[[Mapping[str, str], Upstream | None], list[str]]],
] = {
_K.SCOPE: (SCOPE_DATA_FILE, check_scope),
_K.REQUIREMENTS: (REQUIREMENTS_FILE, check_requirements),
_K.TECHNICAL_DECOMPOSITION: (COMPONENTS_FILE, check_components),
_K.PRODUCT_SELECTION: (PRODUCTS_FILE, check_products),
@@ -216,6 +247,7 @@ DATA_CHECKS: Mapping[
_K.TARGET_ARCHITECTURE: (GRAPH_ATTACHMENT, check_target_architecture),
_K.DEPLOYMENT_GUIDANCE: (IMPLEMENTATION_FILE, check_implementation),
_K.VALIDATION_RESULTS: (VERDICTS_FILE, check_verdicts),
_K.WORK_BREAKDOWN: (WORK_BREAKDOWN_FILE, check_work_breakdown),
}

View File

@@ -30,6 +30,7 @@ from app.nodes.execution_nodes import make_execution_nodes
from app.nodes.router import OrchestratorPolicy
from app.recorder import ExecutionRecorder
from app.states.execution_state import ExecutionState
from app.tools.scoping import Scoping
def build_execution_graph(
@@ -53,6 +54,7 @@ def build_execution_graph(
skill_references: Mapping[str, Mapping[str, Mapping[str, str]]] | None = None,
skill_threshold: float = 1.25,
assess_at_end: bool = False,
scoping: Scoping | None = None,
) -> StateGraph:
nodes = make_execution_nodes(
runtime=runtime,
@@ -74,6 +76,7 @@ def build_execution_graph(
skill_references=skill_references,
skill_threshold=skill_threshold,
assess_at_end=assess_at_end,
scoping=scoping,
)
graph = StateGraph(ExecutionState)

View File

@@ -0,0 +1,559 @@
"""The work breakdown structure: a plan for building the Target architecture.
A Specialist divides the build into work packages and activities and estimates each
activity's days. Everything after that is code, as it is for the architecture
diagram: the plan is checked against the design, the schedule is computed from the
days and the dependencies, and the three views a reader sees are written from the
result. So the timeline cannot disagree with the plan, and no part of the design can
be left out of it.
work packages a hierarchy; each delivers named Elements, and is done when the
Checks on those Elements pass
activities what is done, in which work package, for how many days, after
which other activities, and by whom
schedule each activity's start and finish day, on a relative axis from
Day 0, with no more of the team's activities at once than the
team has people; and the critical path
"""
from __future__ import annotations
import datetime as dt
import json
import math
from collections.abc import Mapping, Sequence
from dataclasses import dataclass
from typing import Any
from app.workflows.chain import Upstream, agreed_scope, read_graph
WORK_BREAKDOWN_FILE = "work-breakdown.json"
TIMELINE_FILE = "timeline.mmd"
DICTIONARY_HEADING = "WBS dictionary"
TEAM, CUSTOMER = "team", "customer"
OWNERS = (TEAM, CUSTOMER)
DEFAULT_TEAM_SIZE = 2
DEFAULT_WEEK = 5
MAX_DAYS = 120 # one activity; anything longer is a work package, not an activity
_CHART_WIDTH = 60
@dataclass(frozen=True)
class Scheduled:
id: str
start: float
finish: float
critical: bool
def _text(value: Any) -> str:
return " ".join(str(value or "").split())
def _list(value: Any) -> list[str]:
return [str(item) for item in value] if isinstance(value, list) else []
def parse(text: str) -> tuple[list[dict[str, Any]], list[dict[str, Any]], list[str]]:
"""(work packages, activities, problems) from the data file."""
name = WORK_BREAKDOWN_FILE
try:
data = json.loads(text)
except ValueError as exc:
return [], [], [f"{name}: not valid JSON ({exc})"]
if not isinstance(data, Mapping):
return [], [], [f"{name}: must be an object with work_packages and activities"]
packages = [p for p in data.get("work_packages") or [] if isinstance(p, Mapping)]
activities = [a for a in data.get("activities") or [] if isinstance(a, Mapping)]
return [dict(p) for p in packages], [dict(a) for a in activities], []
def check_work_breakdown(
attachments: Mapping[str, str], upstream: Upstream | None
) -> list[str]:
name = WORK_BREAKDOWN_FILE
packages, activities, problems = parse(attachments.get(name, ""))
if problems:
return problems
if not packages:
return [f"{name}: lists no work packages"]
if not activities:
return [f"{name}: lists no activities"]
ids = [str(p.get("id", "")) for p in packages]
problems += [f"{name}: a work package has no id"] if "" in ids else []
problems += [
f"{name}: work package id {dup} is used more than once"
for dup in sorted({i for i in ids if i and ids.count(i) > 1})
]
known = set(ids)
parents = {str(p.get("id")): p.get("parent") for p in packages}
for package in packages:
ident, parent = str(package.get("id")), package.get("parent")
if not _text(package.get("name")):
problems.append(f"{name}: {ident} has no name")
if parent is not None and str(parent) not in known:
problems.append(
f"{name}: {ident} has parent {parent}, which does not exist"
)
seen, node = {ident}, parent
while node is not None and str(node) in parents:
if str(node) in seen:
problems.append(f"{name}: {ident} is its own ancestor")
break
seen.add(str(node))
node = parents[str(node)]
graph = read_graph(upstream)
if graph is not None:
elements = {element.id for element in graph.elements}
covered: set[str] = set()
for package in packages:
listed = _list(package.get("elements"))
covered.update(listed)
problems += [
f"{name}: {package.get('id')} delivers {element}, which is not an "
"Element of the Target architecture"
for element in listed
if element not in elements
]
left = sorted(elements - covered)
if left:
problems.append(
f"{name}: no work package delivers {', '.join(left)}; every Element "
"of the Target architecture belongs to one"
)
activity_ids = [str(a.get("id", "")) for a in activities]
problems += [
f"{name}: activity id {dup} is used more than once"
for dup in sorted({i for i in activity_ids if i and activity_ids.count(i) > 1})
]
known_activities = set(activity_ids)
with_work = set()
for activity in activities:
ident = str(activity.get("id", ""))
if not ident or not _text(activity.get("name")):
problems.append(f"{name}: an activity needs an id and a name")
continue
within = str(activity.get("work_package", ""))
if within not in known:
problems.append(f"{name}: {ident} is in {within}, not a work package")
with_work.add(within)
days = activity.get("days")
if isinstance(days, bool) or not isinstance(days, (int, float)) or days <= 0:
problems.append(f"{name}: {ident} needs `days`, a number above 0")
elif days > MAX_DAYS:
problems.append(
f"{name}: {ident} is {days} days; split anything over {MAX_DAYS}"
)
problems += [
f"{name}: {ident} comes after {before}, which is not an activity"
for before in _list(activity.get("after"))
if before not in known_activities
]
if activity.get("owner", TEAM) not in OWNERS:
problems.append(f"{name}: {ident} owner must be one of {', '.join(OWNERS)}")
has_children = {str(parent) for parent in parents.values() if parent is not None}
problems += [
f"{name}: {ident} has no activity and no work package beneath it"
for ident in ids
if ident and ident not in with_work and ident not in has_children
]
if not problems and _cycle(activities):
problems.append(
f"{name}: activities depend on each other in a circle: "
+ " -> ".join(_cycle(activities))
)
return problems
def _cycle(activities: Sequence[Mapping[str, Any]]) -> list[str]:
"""Activities that depend on each other in a circle; empty when none do."""
after = {str(a["id"]): _list(a.get("after")) for a in activities}
state: dict[str, int] = {}
def visit(node: str, path: list[str]) -> list[str]:
state[node] = 1
for before in after.get(node, ()):
if state.get(before) == 1:
return (
[*path[path.index(before) :], before]
if before in path
else [before, node]
)
if state.get(before, 0) == 0:
found = visit(before, [*path, before])
if found:
return found
state[node] = 2
return []
for node in after:
if state.get(node, 0) == 0:
found = visit(node, [node])
if found:
return found
return []
def schedule(
activities: Sequence[Mapping[str, Any]], team_size: int = DEFAULT_TEAM_SIZE
) -> dict[str, Scheduled]:
"""Each activity's start and finish day, from Day 0.
An activity starts when everything it comes after has finished. The team's own
activities also wait for a free person: no more run at once than `team_size`.
What the customer owns, such as a supplier's lead time, takes nobody from the
team. The critical path is every activity with no slack: delay it and the end
moves.
"""
team_size = max(1, int(team_size))
by_id = {str(a["id"]): a for a in activities}
after = {ident: _list(a.get("after")) for ident, a in by_id.items()}
days = {ident: float(a["days"]) for ident, a in by_id.items()}
# The longest chain of work that follows an activity: what to start first when
# people are short.
followers: dict[str, list[str]] = {ident: [] for ident in by_id}
for ident, befores in after.items():
for before in befores:
followers[before].append(ident)
tail: dict[str, float] = {}
def remaining(ident: str) -> float:
if ident not in tail:
tail[ident] = days[ident] + max(
(remaining(f) for f in followers[ident]), default=0.0
)
return tail[ident]
start: dict[str, float] = {}
finish: dict[str, float] = {}
busy: list[tuple[float, float]] = [] # the team's activities already placed
pending = set(by_id)
while pending:
ready = [i for i in pending if all(b in finish for b in after[i])]
ready.sort(key=lambda i: (-remaining(i), i))
ident = min(
ready,
key=lambda i: (
max((finish[b] for b in after[i]), default=0.0),
-remaining(i),
i,
),
)
earliest = max((finish[b] for b in after[ident]), default=0.0)
if by_id[ident].get("owner", TEAM) == TEAM:
candidates = sorted({earliest, *(end for _, end in busy if end > earliest)})
for moment in candidates:
overlapping = sum(
1 for s, e in busy if s < moment + days[ident] and e > moment
)
if overlapping < team_size:
earliest = moment
break
busy.append((earliest, earliest + days[ident]))
start[ident], finish[ident] = earliest, earliest + days[ident]
pending.discard(ident)
end = max(finish.values(), default=0.0)
latest: dict[str, float] = {}
def latest_finish(ident: str) -> float:
if ident not in latest:
latest[ident] = min(
(latest_finish(f) - days[f] for f in followers[ident]), default=end
)
return latest[ident]
return {
ident: Scheduled(
ident,
start[ident],
finish[ident],
critical=latest_finish(ident) - finish[ident] < 1e-6,
)
for ident in by_id
}
# --- what the plan is checked against, from the agreed scope ----------------------------
def _scoped(scope: Mapping[str, Any], path: str) -> Any:
"""A field of the agreed scope, stated or assumed; None when it is neither."""
node: Any = scope.get("stated") or {}
for part in path.split("."):
node = node.get(part) if isinstance(node, Mapping) else None
if node is not None:
return node
for item in scope.get("assumed") or []:
if isinstance(item, Mapping) and item.get("field") == path:
return item.get("value")
return None
def delivery_terms(upstream: Upstream | None) -> dict[str, Any]:
"""Team size, working week, window and start date, from the agreed scope."""
scope = agreed_scope(upstream)
def number(path: str, default: int) -> int:
value = _scoped(scope, path)
ok = (
isinstance(value, (int, float))
and not isinstance(value, bool)
and value > 0
)
return int(value) if ok else default
window = _scoped(scope, "delivery.window_weeks")
start = _scoped(scope, "delivery.target_start_date")
try:
start_date = dt.date.fromisoformat(str(start)) if start else None
except ValueError:
start_date = None
return {
"team_size": number("delivery.team_size", DEFAULT_TEAM_SIZE),
"team_size_stated": _scoped(scope, "delivery.team_size") is not None,
"week": number("delivery.working_days_per_week", DEFAULT_WEEK),
"window_weeks": window if isinstance(window, (int, float)) else None,
"start": start_date,
}
# --- the three views --------------------------------------------------------------------
def _day(value: float) -> str:
return str(int(value)) if float(value).is_integer() else f"{value:.1f}"
def _calendar(start: dt.date, day: float, week: int) -> dt.date:
"""The calendar date of a working day counted from `start`."""
weeks, days = divmod(math.floor(day), week)
return start + dt.timedelta(days=weeks * 7 + days)
def render(attachments: Mapping[str, str], upstream: Upstream | None) -> str:
"""The WBS dictionary, the activity sequence and the timeline, as markdown
written from the data file. "" when the file cannot be read."""
packages, activities, problems = parse(attachments.get(WORK_BREAKDOWN_FILE, ""))
if problems or not packages or not activities:
return ""
terms = delivery_terms(upstream)
plan = schedule(activities, terms["team_size"])
graph = read_graph(upstream)
checks: dict[str, list[str]] = {}
for check in graph.checks if graph else ():
checks.setdefault(check.applies_to, []).append(check.id)
parents = {str(p["id"]): p.get("parent") for p in packages}
def depth(ident: str) -> int:
level, node = 0, parents.get(ident)
while node is not None and str(node) in parents and level < 10:
level, node = level + 1, parents.get(str(node))
return level
effort: dict[str, float] = {}
for activity in activities:
effort[str(activity["work_package"])] = effort.get(
str(activity["work_package"]), 0.0
) + float(activity["days"])
def cell(value: Any) -> str:
return _text(value).replace("|", "\\|") or "-"
lines = [
f"## {DICTIONARY_HEADING}",
"",
"Each work package, what it delivers, and the Checks that say it is done.",
"",
"| Id | Work package | Scope | Produces | Elements | Done when these pass | Skills | Days |",
"| --- | --- | --- | --- | --- | --- | --- | --- |",
]
for package in packages:
ident = str(package["id"])
elements = _list(package.get("elements"))
accepted = [c for element in elements for c in checks.get(element, [])]
lines.append(
"| "
+ " | ".join(
[
ident,
("&nbsp;&nbsp;" * depth(ident)) + cell(package.get("name")),
cell(package.get("scope")),
cell("; ".join(_list(package.get("produces")))),
cell(", ".join(elements)),
cell(", ".join(accepted)),
cell(", ".join(_list(package.get("skills")))),
_day(effort[ident]) if ident in effort else "-",
]
)
+ " |"
)
ordered = sorted(activities, key=lambda a: (plan[str(a["id"])].start, str(a["id"])))
dated = terms["start"] is not None
lines += [
"",
"## Activity sequence",
"",
"| Id | Activity | Work package | Days | After | Start | Finish |"
+ (" Dates |" if dated else "")
+ " Owner | Critical |",
"| --- | --- | --- | --- | --- | --- | --- |"
+ (" --- |" if dated else "")
+ " --- | --- |",
]
for activity in ordered:
item = plan[str(activity["id"])]
row = [
str(activity["id"]),
cell(activity.get("name")),
str(activity.get("work_package")),
_day(float(activity["days"])),
cell(", ".join(_list(activity.get("after")))),
f"Day {_day(item.start)}",
f"Day {_day(item.finish)}",
]
if dated:
begins = _calendar(terms["start"], item.start, terms["week"])
ends = _calendar(terms["start"], max(item.finish - 1e-9, 0), terms["week"])
row.append(f"{begins.isoformat()} to {ends.isoformat()}")
row += [str(activity.get("owner", TEAM)), "yes" if item.critical else ""]
lines.append("| " + " | ".join(row) + " |")
total = max(item.finish for item in plan.values())
weeks = total / terms["week"]
lines += [
"",
"## Timeline",
"",
"```text",
*_chart(ordered, plan, total),
"```",
"",
]
summary = (
f"{_day(total)} working days, about {weeks:.1f} weeks, with a team of "
f"{terms['team_size']}"
+ (
""
if terms["team_size_stated"]
else " (assumed; the scope gives no team size)"
)
+ f" and a {terms['week']}-day week."
)
lines.append(summary)
window = terms["window_weeks"]
if window is not None:
if weeks <= window + 1e-9:
lines.append(
f"That is inside the {window}-week delivery window, with "
f"{window - weeks:.1f} weeks to spare."
)
else:
path = [str(a["id"]) for a in ordered if plan[str(a["id"])].critical]
lines.append(
f"**That is {weeks - window:.1f} weeks over the {window}-week delivery "
f"window.** The critical path is {' -> '.join(path)}: only shortening "
"or removing work on it, or adding people where it waits for them, "
"brings the end in."
)
theirs = [a for a in ordered if a.get("owner", TEAM) == CUSTOMER]
if theirs:
lines += ["", "The customer owns these, and the plan waits on them:"]
lines += [
f"- {a['id']} {_text(a.get('name'))}: {_day(float(a['days']))} days"
+ (f". {_text(a.get('assumption'))}" if _text(a.get("assumption")) else "")
for a in theirs
]
lines += [
"",
(
"Durations are estimates made without knowing the team, and are "
"indicative. Days are working days counted from Day 0, the day work "
"starts; each of the team's activities takes one person."
),
]
return "\n".join(lines) + "\n"
def _chart(
ordered: Sequence[Mapping[str, Any]], plan: Mapping[str, Scheduled], total: float
) -> list[str]:
"""The timeline as text: one row per activity along a relative day axis."""
scale = min(1.0, _CHART_WIDTH / total) if total else 1.0
labels = [f"{a['id']} {_text(a.get('name'))}"[:38] for a in ordered]
width = max(len(label) for label in labels) + 2
step = max(1, math.ceil(total / 6 / 5.0) * 5)
axis = [" "] * (int(total * scale) + 8)
for day in range(0, int(total) + 1, step):
mark = str(day)
at = int(day * scale)
axis[at : at + len(mark)] = mark
rows = [" " * width + "Day " + "".join(axis).rstrip()]
for label, activity in zip(labels, ordered, strict=True):
item = plan[str(activity["id"])]
begin = round(item.start * scale)
length = max(1, round((item.finish - item.start) * scale))
block = "░" if activity.get("owner", TEAM) == CUSTOMER else "█"
flag = " *" if item.critical else ""
rows.append(f"{label.ljust(width)} {' ' * begin}{block * length}{flag}")
rows += ["", "█ the team ░ the customer * on the critical path"]
return rows
def mermaid(attachments: Mapping[str, str], upstream: Upstream | None) -> str:
"""A Mermaid Gantt chart on calendar dates, when the scope gives a start date.
"" otherwise: a relative plan has no dates to draw."""
packages, activities, problems = parse(attachments.get(WORK_BREAKDOWN_FILE, ""))
terms = delivery_terms(upstream)
if problems or not activities or terms["start"] is None:
return ""
plan = schedule(activities, terms["team_size"])
names = {str(p["id"]): _text(p.get("name")) for p in packages}
lines = ["gantt", " dateFormat YYYY-MM-DD", " excludes weekends"]
for package in packages:
own = [
a for a in activities if str(a.get("work_package")) == str(package["id"])
]
if not own:
continue
lines.append(f" section {names[str(package['id'])].replace(':', ' ')}")
for activity in sorted(own, key=lambda a: plan[str(a["id"])].start):
item = plan[str(activity["id"])]
begins = _calendar(terms["start"], item.start, terms["week"])
tag = "crit, " if item.critical else ""
label = _text(activity.get("name")).replace(":", " ")
lines.append(
f" {label} :{tag}{activity['id']}, {begins.isoformat()}, "
f"{max(1, math.ceil(float(activity['days'])))}d"
)
return "\n".join(lines) + "\n"
def summary(
attachments: Mapping[str, str], upstream: Upstream | None
) -> dict[str, Any]:
"""The plan in a few numbers, for an Approval and for the Execution's record."""
packages, activities, problems = parse(attachments.get(WORK_BREAKDOWN_FILE, ""))
if problems or not activities:
return {}
terms = delivery_terms(upstream)
plan = schedule(activities, terms["team_size"])
total = max(item.finish for item in plan.values())
weeks = round(total / terms["week"], 1)
return {
"work_packages": len(packages),
"activities": len(activities),
"working_days": round(total, 1),
"weeks": weeks,
"team_size": terms["team_size"],
"window_weeks": terms["window_weeks"],
"within_window": None
if terms["window_weeks"] is None
else weeks <= terms["window_weeks"],
"critical_path": [i for i, item in plan.items() if item.critical],
}

View File

@@ -0,0 +1,50 @@
---
status: accepted
---
# Scoping starts from a scope spec
An Execution began from the customer's request, a sentence or two saved word for word, and the requirements analyst filled everything else with assumptions. Most of what went wrong downstream traced to what nobody had stated, and nothing told the customer how much of their design rested on assumption. We decide that an engagement is scoped from a **scope spec**: a structured file that states what the customer wants and the facts a design depends on, which may arrive complete, partly filled or not at all, and which the customer approves before requirements begin.
The Intent stays the customer's own words. The scope spec sits beside it as the agreed, structured form.
## What the spec is
- **A file of fields from a catalogue.** A Skill holds the catalogue: each field's type, when it must be settled, the question to ask for it, and guidance for a default. The catalogue names no Cloud provider. A provider's bundle supplies the allowed values for the fields it leaves to a provider, in that provider's terms.
- **Every field says one of four things.** A value is the customer's statement. `ask`, or the field left out, means not known. `decide` leaves the choice to the agent, recorded as an assumption. `not_applicable` asks and assumes nothing.
- **Whether a field is settled is read by code.** No model decides what is missing.
- **Fields are essential, important or optional,** and which is which depends on the kind of engagement: a workload, a platform foundation or a migration.
- **It carries the customer's own words and requirements:** the statement verbatim, the requirements they stated with their own ids, and what they excluded.
- **It carries how to run the agent,** so one file starts an Execution.
## Decisions
Accepted by the owner on 2026-10-11, with each of these:
1. **The file supplied is never altered.** The agent writes a completed copy beside it, with what it assumed, what is still unknown, where each value came from, and a status.
2. **A choice the customer states binds the design.** A product, a topology or a setting written in the spec is a constraint every Specialist honours. The rule that requirements name no products is about what the agents introduce, not what the customer has already decided.
3. **A platform foundation is in scope,** alongside the application workloads the agent was built on.
4. **An engagement and a Customer case are the same thing.** A spec may name either; an engagement reference is turned into the case's id.
5. **The spec is provider-agnostic in shape.** Provider vocabulary enters only as values a provider's bundle allows.
6. **An essential field that is not settled refuses a start that has nobody to ask.** With someone present it is asked for.
7. **Scoping becomes a Phase the customer approves,** before requirements discovery.
8. **Where the spec and a prose request disagree, the spec wins.**
## Considered Options
- **Judge the free-text request against a list of topics** with a model or Jev: the first proposal. Rejected once a spec was on the table: a field that is filled or not is a fact, and a judgement about prose is not.
- **One file the agent completes in place:** rejected. An author must be able to see that what they wrote is what was used.
- **Keep product names out of the spec, as out of requirements:** rejected. A customer who has decided on an interconnect or a named appliance has stated a constraint; refusing to record it would lose it.
- **A separate spec for platform foundations:** rejected. One catalogue with tiers by kind serves both, and a migration is usually some of each.
## Consequences
- The Requirements chain gains a start: a requirement traces to the customer's own requirement id or to a spec field.
- The requirements analyst stops being where questions are asked and assumptions made. That moves to scoping.
- A Change request may be an edited spec, compared field by field in code.
- An evaluation case may be a spec, in place of answers matched by pattern.
- The glossary gains **Scope spec** and **Scoping**, and Customer case says that an engagement is the same thing.
- A platform foundation is new work for the agents. It needs its own evaluation case before it is relied on.
- The spec holds client names and details. Like lesson candidates it is client data: kept with the Customer case, never in the repository, apart from the fictional benchmark specs.
This is built in stages; `.agents/plans/iter-09-scoping/` says which are done.

View File

@@ -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,
}
)

View File

@@ -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

View File

@@ -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,94 @@
"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
},
{
"id": "case-08-landing-zone",
"name": "A regulated platform foundation, started from a scope spec",
"scope": "landing-zone.yaml",
"required_products": [
"Cloud Interconnect",
"Shared VPC",
"Cloud KMS"
],
"scripted_answers": [
[
".*",
"Proceed on the scope spec as supplied. Where it says decide, choose a sensible default and record it as an assumption."
]
]
}
]

View File

@@ -0,0 +1,117 @@
# A benchmark scope spec: a regulated platform foundation. A fictional customer.
schema_version: 1
metadata:
engagement_id: case-08-landing-zone
client_name: Example Payments UK
author: Evaluation
revision: "1.0.0"
engagement:
kind: platform_foundation
intent:
statement: |
We are a UK-regulated payment platform expanding into Google Cloud. We need an
enterprise-grade landing zone ready in under 10 weeks to support our core payments
engine. All payment processing must comply with DORA and PCI-DSS v4.0. We have
existing on-premises systems that require private, low-latency connectivity over a
10Gbps dedicated interconnect. We use Entra ID for corporate single sign-on and
GitHub Actions for our delivery pipelines. Security requires that all egress
traffic flows through centralised inspection appliances before touching the public
internet, and customer data must be encrypted with keys we control.
requirements:
- id: REQ-01
category: Timeline
statement: Platform foundation must be ready for workload ingestion within 10 weeks.
- id: REQ-02
category: Compliance
statement: Must achieve DORA resiliency alignment and PCI-DSS v4.0 perimeter isolation.
- id: REQ-03
category: Networking
statement: 10Gbps on-premises hybrid connectivity; centralised inspection appliances for egress.
- id: REQ-04
category: Identity and security
statement: Workload identity federation with GitHub Actions; Entra ID single sign-on; customer-managed encryption keys.
exclusions:
- Application container deployment; workloads are managed by application squads.
- An active-active secondary region in phase 1; warm standby is acceptable.
success_criteria: decide
estate:
cloud_provider: gcp
mode: greenfield
regions:
primary: europe-west2
secondary: europe-west1
resiliency_tier: warm_standby
data_residency: United Kingdom and European Union
existing_systems: On-premises payment systems that stay in place and connect over the interconnect.
workload:
users: not_applicable
availability:
target: decide
hours: always
recovery_time: decide
recovery_point: decide
compliance:
industry: financial_services
frameworks: [DORA, ISO27001, PCI_DSS_v4]
data_classification: confidential
encryption:
type: cmek
key_rotation_days: 90
audit_logging:
retention_days: 365
immutable_retention_policy: true
networking:
exposure: internal_only
topology: shared_vpc_hub_and_spoke
hybrid_connectivity:
enabled: true
type: cloud_interconnect
bandwidth_gbps: 10
egress_control:
model: centralized_appliance
appliance_vendor: decide
cidr_allocations: decide
governance:
identity_source_of_truth: Entra ID
pipeline_authentication: workload identity federation
environment_tiers:
- {name: development, archetype: corp_workload}
- {name: staging, archetype: corp_workload}
- {name: production, archetype: pci_regulated_workload}
operations:
operating_model: central platform team brokering access for application squads
support_hours: always
monitoring: decide
change_process: decide
integrations: decide
delivery:
window_weeks: 10
commercial_model: fixed_price_milestone
iac_tooling: terraform
ci_cd: GitHub Actions
team_size: 3
working_days_per_week: 5
cost:
monthly_budget: decide
currency: GBP
constraints:
products_required: decide
products_forbidden: decide
run:
pre_approved: true
allow_cloud_read: false
terraform_modules: false

View File

@@ -18,9 +18,11 @@ from dataclasses import dataclass, field
from pathlib import Path
from typing import Any
import yaml
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 +73,10 @@ 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
# A scope spec (ADR-0008), as YAML text, that the case's Execution starts from.
scope: str = ""
# 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"}.
@@ -104,12 +110,27 @@ class CaseResult:
return self.score >= PASS_THRESHOLD
def _scope_of(path: Path, item: Mapping[str, Any]) -> str:
"""The text of the scope spec a case names, from the specs folder beside the
dataset; "" when it names none."""
name = item.get("scope")
return (path.parent / "specs" / str(name)).read_text("utf-8") if name else ""
def _request_of(item: Mapping[str, Any], scope: str) -> str:
"""A case's request: its own, or the statement of intent in its scope spec."""
if item.get("workflow_request"):
return str(item["workflow_request"])
spec = yaml.safe_load(scope) if scope else {}
return str(((spec or {}).get("intent") or {}).get("statement", "")).strip()
def load_cases(path: Path) -> list[CaseSpec]:
return [
CaseSpec(
id=item["id"],
name=item["name"],
workflow_request=item["workflow_request"],
workflow_request=_request_of(item, _scope_of(path, item)),
required_products=tuple(item["required_products"]),
scripted_answers=tuple(
tuple(pair) for pair in item.get("scripted_answers", [])
@@ -118,6 +139,8 @@ 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)),
scope=_scope_of(path, item),
code_standards=tuple(item.get("code_standards", ())),
)
for item in json.loads(path.read_text(encoding="utf-8"))
@@ -262,11 +285,13 @@ async def score_execution(
)
requirements = content(DeliverableKind.REQUIREMENTS)
# What the customer named themselves, in the request or in their scope spec. A
# choice they stated is a constraint to record, not a product leaking in.
stated = case.workflow_request + "\n" + case.scope.replace("_", " ")
leaked = [
product
for product in case.required_products
if _mentions(requirements, product)
and not _mentions(case.workflow_request, product)
if _mentions(requirements, product) and not _mentions(stated, product)
]
checks.append(
Check(
@@ -414,8 +439,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)

View File

@@ -132,6 +132,8 @@ async def run_with_scripted_user(
allow_cloud_read=False,
execution_id=execution_id,
overlay_skills=case.overlay_skills,
terraform_modules=case.terraform_modules,
scope=case.scope or None,
)
for _ in range(max_user_turns):
if interaction.status != "awaiting_user" or interaction.prompt is None:
@@ -194,6 +196,8 @@ 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,
scope=case.scope or None,
)
baseline_tokens = token_report(adk_runtime.usage)["total"].get("total")
baseline_seconds = round(time.monotonic() - started, 1)
@@ -208,6 +212,8 @@ async def run_case(
execution_id=execution_id,
scripted_answers=case.scripted_answers,
overlay_skills=case.overlay_skills,
terraform_modules=case.terraform_modules,
scope=case.scope or None,
baseline=base.execution_id,
)
elif case.interactive:
@@ -223,6 +229,8 @@ async def run_case(
execution_id=execution_id,
scripted_answers=case.scripted_answers,
overlay_skills=case.overlay_skills,
terraform_modules=case.terraform_modules,
scope=case.scope or None,
)
elapsed = time.monotonic() - started
write_progress()
@@ -237,6 +245,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,

View File

@@ -22,6 +22,10 @@ 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
# Dividing and estimating the build is judgement about the whole design.
delivery-planner: 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,10 +40,13 @@ 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
delivery-planner: 300
# Skills each role may load. Role files stay provider-neutral; the bundle names Skills.
role_skills:
orchestrator: [google-cloud-solution-architecture]
scope-analyst: [scoping]
requirements-analyst: [google-cloud-solution-architecture, requirements-chain, cloud-discovery]
decomposer: [google-cloud-solution-architecture, requirements-chain]
product-selector: [google-cloud-solution-architecture, requirements-chain]
@@ -48,12 +55,24 @@ role_skills:
target-architect: [google-cloud-solution-architecture, requirements-chain]
iac-author: [google-cloud-solution-architecture, requirements-chain, iac-validation, google-cloud-iac-patterns]
validator: [google-cloud-solution-architecture, requirements-chain, iac-validation]
delivery-planner: [requirements-chain]
packager: [google-cloud-solution-architecture]
# Where approved lessons are published (ADR-0004). A Specialist is given this Skill
# once it holds lessons for that Specialist's Deliverable.
lessons_skill: google-cloud-lessons
# The scope spec (ADR-0008). `skill` holds its catalogue, which names no Cloud
# provider. `values` are what this provider allows for the fields the catalogue
# leaves to a provider, in this provider's own terms.
scope:
skill: scoping
values:
estate.cloud_provider: [gcp]
compliance.encryption.type: [cmek, cmek_hsm]
networking.topology: [single_vpc, shared_vpc, shared_vpc_hub_and_spoke]
networking.hybrid_connectivity.type: [cloud_vpn, cloud_interconnect, partner_interconnect]
# One advisor per architecture-framework pillar; each loads only its pillar's Skill.
pillar_skills:
security: google-cloud-waf-security
@@ -64,7 +83,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 +94,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

View 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")))

View 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.

View 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]
}
```

View 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}"
}
]
}
```

View 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"]
}
}
```

View 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"
}
```

View File

@@ -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.

View 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}"
}
```

View 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,
]
}
```

View 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}/\")"
}
}
```

View 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]"
}
```

View File

@@ -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.

View File

@@ -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.

View File

@@ -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.

View 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"
}

View File

@@ -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

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