4 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
37 changed files with 1658 additions and 26 deletions

View File

@@ -14,8 +14,8 @@ One directory per iteration of this agent. Each holds the plan for that iteratio
| 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, 2 and 6 built on 2026-10-11, not run with real models; steps 3–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/` | planned; nothing built | 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. |
| 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

@@ -2,7 +2,7 @@
**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 and 6 built on 2026-10-11, not run with real models; steps 3 to 5 planned
**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
@@ -17,7 +17,7 @@
|---|---|---|
| 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`; readiness in the solution guide | planned |
| 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 |

View File

@@ -26,3 +26,30 @@ Not done here:
- 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

@@ -2,7 +2,7 @@
**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:** planned; nothing built
**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
@@ -15,9 +15,9 @@
| Step | What | Status |
|---|---|---|
| 1 | The Deliverable, its Specialist and its data file; every Element in a work package, checked in code | planned |
| 2 | The schedule computed in code: start and finish day, critical path, team size as a limit | planned |
| 3 | The three views written by code: WBS dictionary, activity sequence list, timeline on a relative axis | planned |
| 4 | The delivery window checked; assumptions the plan depends on shown on the timeline; milestones | planned |
| 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

@@ -89,7 +89,7 @@ _Avoid_: custom prompt, override, plugin
### Outputs
**Deliverable**:
A document an Execution produces: the scope, 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**:
@@ -120,6 +120,14 @@ _Avoid_: traceability matrix, lineage
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

@@ -15,12 +15,14 @@ One Orchestrator coordinates an Execution and is the only agent that talks to th
- **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.

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

@@ -10,6 +10,8 @@ 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

@@ -12,6 +12,7 @@ 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.

View File

@@ -13,7 +13,7 @@ You produce the **requirements** Deliverable: the Skill's requirements-discovery
- 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 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.
- Cover every entry of `scope.stated.intent.requirements`, the customer's own requirements, and name its id in the requirement that covers it. List what `scope.to_ask` still holds under `Open questions`.
- 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, 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.

View File

@@ -17,7 +17,7 @@ The scope spec is kept for you. `scope_read` shows what is settled, what is not,
- 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. The completed spec, the information register, the assumptions and the questions still open are written for you from what you recorded. Pass no attachments.
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.

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

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

@@ -88,6 +88,7 @@ from app.workflows.deliverables import (
dependencies_for,
)
from app.workflows.target_architecture import GRAPH_ATTACHMENT
from app.workflows.work_breakdown import summary as plan_summary
logger = logging.getLogger(__name__)
@@ -1413,6 +1414,23 @@ 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.
@@ -1453,6 +1471,8 @@ def _write_outputs(
"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.

View File

@@ -46,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__)
@@ -761,6 +762,12 @@ def approval_facts(phase: PhaseId, view: TurnView, r: Readings) -> dict[str, Any
],
"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()
@@ -796,6 +803,21 @@ 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(

View File

@@ -82,6 +82,9 @@ class FieldSpec:
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):
@@ -118,6 +121,7 @@ def load_catalogue(path: Path) -> Catalogue:
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)),
@@ -248,6 +252,13 @@ class Scope:
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": [

View File

@@ -61,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__)
@@ -404,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.

View File

@@ -143,8 +143,10 @@ class TerraformRunner:
)
async def validate(self, files: Mapping[str, str]) -> ToolResult:
refusal = _check_files(files) or check_module_sources(
files, allowed_namespaces(self.module_namespaces)
refusal = (
_check_files(files)
or check_providers(files, self.providers)
or check_module_sources(files, allowed_namespaces(self.module_namespaces))
)
if refusal:
return refusal
@@ -160,8 +162,10 @@ class TerraformRunner:
async def plan(
self, files: Mapping[str, str], variables: Mapping[str, str] | None = None
) -> ToolResult:
refusal = _check_files(files) or check_module_sources(
files, allowed_namespaces(self.module_namespaces)
refusal = (
_check_files(files)
or check_providers(files, self.providers)
or check_module_sources(files, allowed_namespaces(self.module_namespaces))
)
if refusal:
return refusal
@@ -363,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.")

View File

@@ -213,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]:

View File

@@ -35,6 +35,7 @@ from app.workflows.chain import (
)
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):
@@ -62,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"
@@ -200,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,
@@ -234,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

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

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

View File

@@ -24,6 +24,8 @@ models:
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
@@ -39,6 +41,7 @@ models:
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:
@@ -52,6 +55,7 @@ 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

View File

@@ -37,6 +37,19 @@ Every non-functional requirement lists its `conditions`: one entry for each sepa
`kind` is `functional` or `non_functional`. Write one requirement per entry, so each can be checked on its own.
When the customer's scope is in your context, a requirement says what it comes from in `from`: the ids of the customer's own requirements, and the scope fields it carries.
```json
{"id": "NFR-4", "kind": "non_functional",
"text": "The network is a hub with spokes, joined to on-premises over a private 10Gbps connection.",
"conditions": ["A hub network is connected to every spoke network.", "A dedicated 10Gbps connection joins the hub to on-premises."],
"from": ["REQ-03", "networking.topology", "networking.hybrid_connectivity.type", "networking.hybrid_connectivity.bandwidth_gbps"]}
```
- Every requirement the customer wrote (`scope.stated.intent.requirements`) is named in the `from` of the requirement that covers it.
- Every field under `scope.binding` is a choice the customer stated that the design must honour. Each is named in the `from` of a non-functional requirement with at least one condition that shows it was honoured. Write the condition about what must exist or be set, in terms a Check can verify: "a hub network is connected to every spoke network", not "the topology is hub and spoke".
- One requirement may carry several fields that belong together. A submission is refused while any is carried by none.
### `components.json` (technical decomposition)
A list of components and the requirement ids each serves. Every functional requirement must be served by at least one component.

View File

@@ -5,7 +5,8 @@
# before any work), important (asked when someone is present) or optional. A tier
# may differ by the kind of engagement. `question` is what to ask the customer for
# it. `default` guides the choice when the customer says "decide". `affects` says
# what a wrong assumption would change.
# what a wrong assumption would change. `binds: true` marks a choice a design must
# honour: stated by the customer, it has to reach a requirement and its Checks.
#
# This catalogue names no Cloud provider. A provider's bundle adds allowed values
# for the fields marked `provider_values`.
@@ -66,15 +67,18 @@ fields:
tier: essential
question: Is this a new estate, an extension of an existing one, or a migration?
estate.regions.primary:
binds: true
type: string
tier: essential
question: Which region should it run in?
estate.regions.secondary:
binds: true
type: string
question: Is there a second region, and which?
default: None, unless availability or recovery targets need one.
affects: resilience design and cost
estate.regions.resiliency_tier:
binds: true
type: enum
values: [single_region, warm_standby, active_active]
tier: important
@@ -82,6 +86,7 @@ fields:
default: single_region
affects: resilience design and cost
estate.data_residency:
binds: true
type: string
tier: essential
question: Where must data stay?
@@ -108,6 +113,7 @@ fields:
default: A tenth of the user count.
affects: scaling limits and cost
workload.availability.target:
binds: true
type: string
tier: {workload: essential, migration: essential, platform_foundation: important}
question: What availability is required, as a percentage?
@@ -121,12 +127,14 @@ fields:
default: always
affects: scaling to zero and support
workload.availability.recovery_time:
binds: true
type: string
tier: important
question: How quickly must it recover from a failure?
default: 4 hours
affects: backup and standby design
workload.availability.recovery_point:
binds: true
type: string
tier: important
question: How much recent data may be lost in a failure?
@@ -137,15 +145,18 @@ fields:
type: string
question: "Which industry is the customer in?"
compliance.frameworks:
binds: true
type: list
tier: essential
question: Which regulations or standards apply? An empty list if none.
compliance.data_classification:
binds: true
type: enum
values: [public, internal, confidential, restricted]
tier: essential
question: How sensitive is the data?
compliance.encryption.type:
binds: true
type: enum
values: [provider_managed, customer_managed]
provider_values: true
@@ -154,21 +165,25 @@ fields:
default: provider_managed
affects: key management design
compliance.encryption.key_rotation_days:
binds: true
type: integer
question: How often must keys rotate, in days?
default: 90
compliance.audit_logging.retention_days:
binds: true
type: integer
tier: important
question: How long must audit logs be kept, in days?
default: 365
affects: storage cost and log design
compliance.audit_logging.immutable_retention_policy:
binds: true
type: boolean
question: Must audit logs be undeletable for that time?
default: false
networking.exposure:
binds: true
type: enum
values: [internal_only, internet_facing]
tier: important
@@ -176,6 +191,7 @@ fields:
default: internal_only
affects: perimeter design
networking.topology:
binds: true
type: enum
provider_values: true
tier: {platform_foundation: important}
@@ -183,28 +199,34 @@ fields:
default: The simplest topology that meets the requirements.
affects: the whole network design
networking.hybrid_connectivity.enabled:
binds: true
type: boolean
tier: {platform_foundation: important, migration: important}
question: Must it connect privately to on-premises or another cloud?
default: false
affects: network design and lead time
networking.hybrid_connectivity.type:
binds: true
type: enum
provider_values: true
question: By what kind of connection?
networking.hybrid_connectivity.bandwidth_gbps:
binds: true
type: number
question: At what bandwidth, in Gbps?
networking.egress_control.model:
binds: true
type: enum
values: [direct, provider_managed, centralized_appliance]
question: How must traffic to the internet be controlled?
default: provider_managed
affects: network design and cost
networking.egress_control.appliance_vendor:
binds: true
type: string
question: Which inspection appliance, if one is mandated?
networking.cidr_allocations:
binds: true
type: text
tier: {platform_foundation: important}
question: Which IP ranges are allocated, and how large per environment?
@@ -212,16 +234,19 @@ fields:
affects: every network resource
governance.identity_source_of_truth:
binds: true
type: string
tier: important
question: Which identity provider do people sign in with?
default: The Cloud provider's own identities.
affects: access design
governance.pipeline_authentication:
binds: true
type: string
question: How do delivery pipelines authenticate?
default: Short-lived federated credentials, no stored keys.
governance.environment_tiers:
binds: true
type: records
keys: [name]
optional_keys: [archetype]
@@ -294,10 +319,12 @@ fields:
default: "USD"
constraints.products_required:
binds: true
type: list
question: Which products has the customer mandated?
default: None.
constraints.products_forbidden:
binds: true
type: list
question: Which products are ruled out?
default: None.

View File

@@ -820,3 +820,29 @@ async def test_a_case_with_no_standards_has_no_such_check():
result = await score_execution(CASE, execution(), HEADINGS, passing_terraform)
assert all(c.name != "code_follows_standards" for c in result.checks)
async def test_a_product_the_customers_scope_spec_names_may_appear_in_requirements():
"""Case 08: the spec said shared_vpc_hub_and_spoke, and "Shared VPC" in the
requirements was scored as a product leaking in."""
named = {
"content": "## Functional requirements\nUse the Shared VPC topology stated.\n"
"## Current state\nNone.",
"attachments": {"requirements.json": SAMPLE_DATA["requirements.json"]},
}
with_spec = dataclasses.replace(
CASE,
required_products=("Shared VPC",),
scope="networking:\n topology: shared_vpc_hub_and_spoke\n",
)
without = dataclasses.replace(CASE, required_products=("Shared VPC",))
stated = await score_execution(
with_spec, execution(requirements=named), HEADINGS, passing_terraform
)
leaked = await score_execution(
without, execution(requirements=named), HEADINGS, passing_terraform
)
assert check(stated, "requirements_name_no_products").passed
assert not check(leaked, "requirements_name_no_products").passed

View File

@@ -103,9 +103,14 @@ def test_inputs_are_earlier_phases_plus_indirect_dependencies_in_graph_order():
assert inputs_of(DeliverableKind.DEPLOYMENT_GUIDANCE) == design
assert inputs_of(DeliverableKind.ARCHITECTURE_DESCRIPTION) == design
assert inputs_of(DeliverableKind.TARGET_ARCHITECTURE) == design[:5]
# The plan is produced beside the guide, not before it: neither reads the other.
assert set(inputs_of(DeliverableKind.SOLUTION_GUIDE)) == set(DeliverableKind) - {
DeliverableKind.SOLUTION_GUIDE
DeliverableKind.SOLUTION_GUIDE,
DeliverableKind.WORK_BREAKDOWN,
}
assert DeliverableKind.SOLUTION_GUIDE not in inputs_of(
DeliverableKind.WORK_BREAKDOWN
)
def sections_missing(kind: DeliverableKind, content: str) -> list[str]:

View File

@@ -247,7 +247,7 @@ def test_finish_is_allowed_only_once_packaging_is_approved():
through_phase_three(ledger)
assert not ledger.can_finish()
produce(ledger, K.SOLUTION_GUIDE)
produce(ledger, K.WORK_BREAKDOWN, K.SOLUTION_GUIDE)
approve(ledger, P.PACKAGING)
assert ledger.can_finish()

View File

@@ -767,3 +767,113 @@ def test_a_constraint_with_conditions_still_needs_a_check():
)
assert gaps == ("Requirement NFR-2 has no Check",)
# --- what the customer stated reaches the requirements (ADR-0008) ------------------------
def scoped_upstream(**scope) -> dict:
import json
return {"scope": {"attachments": {"scope.json": json.dumps(scope)}}}
def requirement_problems(requirements: list[dict], **scope) -> list[str]:
import json
from app.workflows.chain import check_requirements
return check_requirements(
{"requirements.json": json.dumps(requirements)}, scoped_upstream(**scope)
)
STATED = {
"stated": {
"intent": {
"requirements": [{"id": "REQ-01", "statement": "Ready in 10 weeks."}]
},
"networking": {"topology": "hub_and_spoke"},
},
"binding": ["networking.topology"],
}
FUNCTIONAL = {"id": "FR-1", "kind": "functional", "text": "Accept events."}
CARRIED = {
"id": "NFR-1",
"kind": "non_functional",
"text": "The network is hub and spoke, ready in ten weeks.",
"conditions": ["A hub network is connected to each spoke network."],
"from": ["REQ-01", "networking.topology"],
}
def test_requirements_that_carry_everything_the_customer_stated_are_accepted():
assert requirement_problems([FUNCTIONAL, CARRIED], **STATED) == []
def test_a_customers_own_requirement_must_be_covered_by_name():
uncited = {**CARRIED, "from": ["networking.topology"]}
(problem,) = requirement_problems([FUNCTIONAL, uncited], **STATED)
assert "the customer's requirement REQ-01 is covered by no requirement" in problem
def test_a_stated_choice_must_be_carried_by_a_requirement():
"""Case 08: a stated topology was named in the design and not built, and every
Check passed, because nothing asked for it."""
uncarried = {**CARRIED, "from": ["REQ-01"]}
(problem,) = requirement_problems([FUNCTIONAL, uncarried], **STATED)
assert "the customer stated networking.topology and no requirement carries it" in (
problem
)
def test_a_stated_choice_is_carried_as_a_constraint_the_design_is_checked_against():
as_functional = {**CARRIED, "kind": "functional", "conditions": []}
outside_code_only = {
**CARRIED,
"conditions": [],
"outside_code": ["The topology is reviewed by the network team."],
}
for weak in (as_functional, outside_code_only):
problems = requirement_problems([FUNCTIONAL, weak], **STATED)
assert any(
"must be non_functional with at least one entry in `conditions`" in p
for p in problems
), weak
def test_with_no_scope_or_nothing_binding_requirements_are_as_before():
from app.workflows.chain import check_requirements
plain = [FUNCTIONAL]
import json
assert check_requirements({"requirements.json": json.dumps(plain)}, None) == []
assert requirement_problems(plain, stated={"intent": {"statement": "x"}}) == []
def test_what_was_assumed_for_the_customer_does_not_bind_the_design():
from app.scope import Catalogue, FieldSpec, Scope
catalogue = Catalogue(
1,
("workload",),
{
"net.topology": FieldSpec("net.topology", binds=True),
"net.region": FieldSpec("net.region", binds=True),
"notes": FieldSpec("notes"),
},
)
scope = Scope(
catalogue,
"workload",
values={"net.topology": "hub", "net.region": "x", "notes": "n"},
sources={"net.region": "assumed"},
)
assert scope.for_context()["binding"] == ["net.topology"]

View File

@@ -14,6 +14,7 @@ from app.providers import load_provider
from app.recorder import InMemoryRecorder
from app.workflows.deliverables import DEPENDENCY_GRAPH
from app.workflows.deliverables import DeliverableKind as K
from tests.scoped import carrying
ROLES = {
"orchestrator": RoleSpec("orchestrator", "Unused.", budget=40),
@@ -45,6 +46,15 @@ run: {pre_approved: true, terraform_modules: false}
"""
STATED_CHOICES = [
"estate.regions.primary",
"estate.data_residency",
"compliance.frameworks",
"compliance.data_classification",
"networking.topology",
]
class Recording(FakeAgentRuntime):
def __init__(self, turns):
super().__init__(turns)
@@ -62,8 +72,13 @@ def engine(tmp_path) -> tuple[ExecutionEngine, Recording]:
bundle = load_provider("gcp")
runtime = Recording(
{
spec.specialist: [[sample_submission(kind)]]
for kind, spec in DEPENDENCY_GRAPH.items()
**{
spec.specialist: [[sample_submission(kind)]]
for kind, spec in DEPENDENCY_GRAPH.items()
},
# The requirements carry every choice SPEC states, and a Check holds
# the design to them.
**carrying(STATED_CHOICES),
}
)
built = ExecutionEngine(

View File

@@ -0,0 +1,308 @@
"""The work breakdown structure: a plan checked, scheduled and drawn by code."""
import json
from langgraph.checkpoint.memory import InMemorySaver
from app.adk.fake_runtime import SAMPLE_DATA, Call, FakeAgentRuntime, sample_submission
from app.adk.runtime import NoDecider, RoleSpec
from app.agent import ExecutionEngine
from app.nodes.router import Router, Thresholds
from app.recorder import InMemoryRecorder
from app.workflows.deliverables import DEPENDENCY_GRAPH
from app.workflows.deliverables import DeliverableKind as K
from app.workflows.work_breakdown import (
check_work_breakdown,
mermaid,
render,
schedule,
summary,
)
GRAPH = SAMPLE_DATA["target-architecture.json"] # Elements E-1 and E-2
PLANNER = DEPENDENCY_GRAPH[K.WORK_BREAKDOWN].specialist
def upstream(**delivery) -> dict:
scope = {"stated": {"delivery": delivery}, "assumed": []}
return {
"target_architecture": {"attachments": {"target-architecture.json": GRAPH}},
"scope": {"attachments": {"scope.json": json.dumps(scope)}},
}
def plan(packages=None, activities=None) -> dict[str, str]:
data = json.loads(SAMPLE_DATA["work-breakdown.json"])
if packages is not None:
data["work_packages"] = packages
if activities is not None:
data["activities"] = activities
return {"work-breakdown.json": json.dumps(data)}
def activity(ident: str, days: float, *after: str, **more) -> dict:
return {
"id": ident,
"work_package": "WP-1",
"name": f"Do {ident}",
"days": days,
"after": list(after),
**more,
}
PACKAGE = json.loads(SAMPLE_DATA["work-breakdown.json"])["work_packages"][0]
# --- the plan is checked against the design ---------------------------------------------
def test_a_plan_that_covers_the_design_is_accepted():
assert check_work_breakdown(plan(), upstream()) == []
def test_every_element_of_the_design_belongs_to_a_work_package():
only_one = [{**PACKAGE, "elements": ["E-1"]}]
invented = [{**PACKAGE, "elements": ["E-1", "E-2", "E-9"]}]
(left_out,) = check_work_breakdown(plan(only_one), upstream())
(unknown,) = check_work_breakdown(plan(invented), upstream())
assert "no work package delivers E-2" in left_out
assert "WP-1 delivers E-9, which is not an Element" in unknown
def test_a_plan_that_cannot_be_scheduled_is_refused_with_the_reason():
def problems(*activities):
return check_work_breakdown(plan(activities=list(activities)), upstream())
assert any(
"depend on each other in a circle" in p
for p in problems(activity("A-1", 1, "A-2"), activity("A-2", 1, "A-1"))
)
assert any(
"comes after A-9, which is not an activity" in p
for p in problems(activity("A-1", 1, "A-9"))
)
assert any(
"needs `days`, a number above 0" in p for p in problems(activity("A-1", 0))
)
assert any("split anything over" in p for p in problems(activity("A-1", 400)))
assert any(
"owner must be one of" in p
for p in problems(activity("A-1", 1, owner="vendor"))
)
assert any(
"is in WP-7, not a work package" in p
for p in problems({**activity("A-1", 1), "work_package": "WP-7"})
)
def test_a_work_package_holds_work_or_other_work_packages():
parent = {**PACKAGE, "id": "WP-0", "elements": []}
child = {**PACKAGE, "parent": "WP-0"}
idle = {**PACKAGE, "id": "WP-2", "elements": []}
assert check_work_breakdown(plan([parent, child]), upstream()) == []
assert any(
"WP-2 has no activity and no work package beneath it" in p
for p in check_work_breakdown(
plan([child | {"parent": None}, idle]), upstream()
)
)
assert any(
"has parent WP-9, which does not exist" in p
for p in check_work_breakdown(plan([{**PACKAGE, "parent": "WP-9"}]), upstream())
)
# --- the schedule is computed -----------------------------------------------------------
def test_an_activity_starts_when_what_it_follows_has_finished():
placed = schedule(
[activity("A-1", 2), activity("A-2", 3, "A-1"), activity("A-3", 1, "A-2")]
)
assert [(p.start, p.finish) for p in placed.values()] == [(0, 2), (2, 5), (5, 6)]
assert all(p.critical for p in placed.values())
def test_independent_work_runs_at_once_up_to_the_size_of_the_team():
work = [activity("A-1", 4), activity("A-2", 4), activity("A-3", 4)]
two = schedule(work, team_size=2)
three = schedule(work, team_size=3)
assert max(p.finish for p in two.values()) == 8
assert sorted(p.start for p in two.values()) == [0, 0, 4]
assert max(p.finish for p in three.values()) == 4
def test_what_the_customer_owns_takes_nobody_from_the_team():
work = [
activity("A-1", 10, owner="customer"),
activity("A-2", 3),
activity("A-3", 2, "A-1", "A-2"),
]
placed = schedule(work, team_size=1)
# The lead time and the team's work run together; the end waits on the longer.
assert placed["A-2"].start == 0 and placed["A-3"].start == 10
assert placed["A-1"].critical and placed["A-3"].critical
assert not placed["A-2"].critical
def test_when_people_are_short_the_longest_chain_goes_first():
work = [activity("A-1", 1), activity("A-2", 1), activity("A-3", 5, "A-2")]
placed = schedule(work, team_size=1)
assert placed["A-2"].start == 0 and placed["A-1"].start > 0
# --- the views are written from the plan ------------------------------------------------
def test_the_three_views_are_written_from_the_data():
text = render(plan(), upstream(team_size=2))
assert "## WBS dictionary" in text
# Acceptance is the Checks on the work package's Elements, read from the design.
assert (
"| WP-1 | Ingress | The service and its identity. | a running service | E-1, E-2 | K-1, K-2 |"
in text
)
assert (
"| A-2 | Deploy the service | WP-1 | 2 | A-1 | Day 1 | Day 3 | team | yes |"
in text
)
assert "## Timeline" in text and "Day 0" in text
assert "3 working days, about 0.6 weeks, with a team of 2 and a 5-day week." in text
assert "indicative" in text
def test_a_plan_over_the_delivery_window_says_so_and_names_the_critical_path():
long = plan(activities=[activity("A-1", 20), activity("A-2", 15, "A-1")])
over = render(long, upstream(team_size=2, window_weeks=4))
inside = render(long, upstream(team_size=2, window_weeks=10))
assert "**That is 3.0 weeks over the 4-week delivery window.**" in over
assert "The critical path is A-1 -> A-2" in over
assert "inside the 10-week delivery window, with 3.0 weeks to spare" in inside
assert summary(long, upstream(window_weeks=4))["within_window"] is False
def test_an_assumed_team_size_is_said_to_be_assumed():
assert "(assumed; the scope gives no team size)" in render(plan(), upstream())
def test_a_customers_lead_time_is_shown_as_theirs():
waiting = plan(
activities=[
activity(
"A-1", 30, owner="customer", assumption="The carrier takes six weeks."
),
activity("A-2", 2, "A-1"),
]
)
text = render(waiting, upstream(team_size=2))
assert "The customer owns these, and the plan waits on them:" in text
assert "- A-1 Do A-1: 30 days. The carrier takes six weeks." in text
assert "░" in text and "█" in text
def test_calendar_dates_and_a_chart_appear_only_with_a_start_date():
dated = upstream(team_size=2, target_start_date="2026-11-02") # a Monday
assert mermaid(plan(), upstream(team_size=2)) == ""
assert "Dates" not in render(plan(), upstream(team_size=2))
chart = mermaid(plan(), dated)
assert chart.startswith("gantt\n dateFormat YYYY-MM-DD")
assert "Deploy the service :crit, A-2, 2026-11-03, 2d" in chart
assert "| 2026-11-03 to 2026-11-04 |" in render(plan(), dated)
def test_a_week_of_working_days_skips_the_weekend():
week = plan(activities=[activity("A-1", 5), activity("A-2", 1, "A-1")])
text = render(week, upstream(team_size=1, target_start_date="2026-11-02"))
# Five working days from Monday end on Friday; the next starts on Monday.
assert "| 2026-11-02 to 2026-11-06 |" in text
assert "| 2026-11-09 to 2026-11-09 |" in text
# --- in an Execution --------------------------------------------------------------------
async def test_an_execution_delivers_a_plan_and_adds_its_timeline_to_the_guide(
tmp_path,
):
roles = {
"orchestrator": RoleSpec("orchestrator", "Unused.", budget=40),
**{
spec.specialist: RoleSpec(spec.specialist, "Produce.", budget=15)
for spec in DEPENDENCY_GRAPH.values()
},
}
runtime = FakeAgentRuntime(
{
spec.specialist: [[sample_submission(kind)]]
for kind, spec in DEPENDENCY_GRAPH.items()
}
)
engine = ExecutionEngine(
runtime=runtime,
roles=roles,
recorder=InMemoryRecorder(),
checkpointer=InMemorySaver(),
output_root=tmp_path,
orchestrator=Router(NoDecider(), None, Thresholds()),
)
result = await engine.start("Ingest", customer_case="acme", pre_approved=True)
assert result.status == "completed"
out = next(tmp_path.rglob("execution.json")).parent
breakdown = (out / "deliverables" / "work_breakdown.md").read_text()
assert "## WBS dictionary" in breakdown and "## Activity sequence" in breakdown
assert (out / "work-breakdown.json").is_file()
guide = (out / "solution-architecture-guide.md").read_text()
assert "## Delivery plan" in guide and "A-2 Deploy the service" in guide
manifest = json.loads((out / "execution.json").read_text())
assert manifest["delivery_plan"]["working_days"] == 3
assert manifest["delivery_plan"]["critical_path"] == ["A-1", "A-2"]
# The planner was given the design and the code to plan from, in full.
planner = next(run for run in runtime.runs if run.role == PLANNER)
given = planner.task.context["dependencies"]
assert "content" in given["target_architecture"]
assert "content" in given["deployment_guidance"]
async def test_a_plan_that_leaves_an_element_out_is_returned_to_the_planner(tmp_path):
from app.tools.execution import specialist_tools
(submit,) = (
tool
for tool in specialist_tools(
K.WORK_BREAKDOWN, (), allow_cloud_read=False, upstream=upstream()
)
if tool.name == "submit_deliverable"
)
partial = Call(
"submit_deliverable",
{
"content": "## Approach\nIn order.\n",
"attachments": plan([{**PACKAGE, "elements": ["E-1"]}]),
},
)
refused = await submit.handler(**partial.args)
assert refused.outcome is None
assert "no work package delivers E-2" in refused.message

View File

@@ -386,7 +386,8 @@ def test_the_validator_reads_the_code_whole_and_the_graph_as_data():
def test_the_solution_guide_is_assembled_from_every_deliverable_whole():
given = dependencies_for(K.SOLUTION_GUIDE, submitted())
assert len(given) == len(DEPENDENCY_GRAPH) - 1
# Every Deliverable but the guide itself and the plan produced beside it.
assert len(given) == len(DEPENDENCY_GRAPH) - 2
assert all("content" in deliverable for deliverable in given.values())

View File

@@ -4,10 +4,15 @@ Every Execution now begins with the scoping Phase (ADR-0008). A test about
requirements, design or validation is not about that, so these run scoping ahead
of the test's own script and leave the test where it always started: requirements
ready, nothing recorded of how the scope was agreed.
The work breakdown structure (iteration 10) is produced beside the solution guide.
A script written before it existed delegates the guide alone; here the plan is
delegated with it, and planned without a script.
"""
from __future__ import annotations
import dataclasses
from typing import Any
from app.adk.fake_runtime import FakeAgentRuntime, sample_submission
@@ -16,9 +21,28 @@ from app.agent import ExecutionEngine, Interaction
from app.workflows.deliverables import DEPENDENCY_GRAPH, DeliverableKind, PhaseId
SCOPE_ANALYST = DEPENDENCY_GRAPH[DeliverableKind.SCOPE].specialist
PLANNER = DEPENDENCY_GRAPH[DeliverableKind.WORK_BREAKDOWN].specialist
ORCHESTRATOR = "orchestrator"
def _with_the_plan(tool): # type: ignore[no-untyped-def]
"""`delegate`, delegating the work breakdown structure whenever the solution
guide is delegated."""
if tool.name != "delegate":
return tool
guide, plan = (
DeliverableKind.SOLUTION_GUIDE.value,
DeliverableKind.WORK_BREAKDOWN.value,
)
async def delegate(kinds, **rest): # type: ignore[no-untyped-def]
if guide in kinds and plan not in kinds:
kinds = [*kinds, plan]
return await tool.handler(kinds=kinds, **rest)
return dataclasses.replace(tool, handler=delegate)
class ScopedRuntime(FakeAgentRuntime):
"""A scripted runtime that first has the scope produced and its Approval asked
for, outside the script and outside `runs`."""
@@ -29,6 +53,11 @@ class ScopedRuntime(FakeAgentRuntime):
async def run(self, role, task, tools): # type: ignore[no-untyped-def]
by_name = {tool.name: tool for tool in tools}
if role.name == PLANNER and not self.remaining(PLANNER):
call = sample_submission(DeliverableKind.WORK_BREAKDOWN)
return Submitted(call.args["content"], call.args["attachments"])
if role.name == ORCHESTRATOR and "delegate" in by_name:
tools = [_with_the_plan(tool) for tool in tools]
if role.name == SCOPE_ANALYST and not self.remaining(SCOPE_ANALYST):
# Submitted as it stands: a test about a later Deliverable's draft is
# not asking whether the scope's draft was shown first.
@@ -78,3 +107,61 @@ def scoped_ledger(**options: Any): # type: ignore[no-untyped-def]
if ledger.phase_status(PhaseId.SCOPING) is PhaseStatus.AWAITING_APPROVAL:
ledger.approve(PhaseId.SCOPING, actor="user")
return ledger
def carrying(sources: list[str]) -> dict[str, list]:
"""Scripted turns for the Specialists along the Requirements chain, in which one
more requirement, NFR-2, carries what the customer stated (`sources`), and a
Check, K-3, holds the design to it."""
import json
from app.adk.fake_runtime import SAMPLE_DATA, Call
def submission(kind: DeliverableKind, **files: str) -> Call:
call = sample_submission(kind)
return Call(
call.tool,
{**call.args, "attachments": {**call.args["attachments"], **files}},
)
requirements = json.loads(SAMPLE_DATA["requirements.json"])
requirements.append(
{
"id": "NFR-2",
"kind": "non_functional",
"text": "The design honours what the customer stated.",
"conditions": ["Each stated choice is configured as stated."],
"from": sources,
}
)
components = json.loads(SAMPLE_DATA["components.json"])
components[0]["requirements"].append("NFR-2")
graph = json.loads(SAMPLE_DATA["target-architecture.json"])
graph["checks"].append(
{
"id": "K-3",
"applies_to": "E-1",
"source": "NFR-2",
"statement": "the stated choices are configured",
}
)
implementation = json.loads(SAMPLE_DATA["implementation.json"])
implementation.append(
{"check": "K-3", "file": "terraform/main.tf", "address": "example.run"}
)
verdicts = json.loads(SAMPLE_DATA["verdicts.json"])
verdicts["checks"].append(
{"check": "K-3", "verdict": "pass", "evidence": "Configured as stated."}
)
K = DeliverableKind
files = {
K.REQUIREMENTS: {"requirements.json": json.dumps(requirements)},
K.TECHNICAL_DECOMPOSITION: {"components.json": json.dumps(components)},
K.TARGET_ARCHITECTURE: {"target-architecture.json": json.dumps(graph)},
K.DEPLOYMENT_GUIDANCE: {"implementation.json": json.dumps(implementation)},
K.VALIDATION_RESULTS: {"verdicts.json": json.dumps(verdicts)},
}
return {
DEPENDENCY_GRAPH[kind].specialist: [[submission(kind, **attached)]]
for kind, attached in files.items()
}

View File

@@ -383,3 +383,72 @@ def test_the_cache_setting_resolves_under_the_repository_and_can_be_disabled():
).terraform_plugin_cache()
== "/var/cache/tf"
)
# --- only the providers the bundle pins ---------------------------------------------------
PINNED = {"cloud": {"source": "example/cloud", "version": "1.2.3"}}
def provider_refusal(code: str, pinned=PINNED) -> str:
from app.tools.local import check_providers
result = check_providers({"terraform/main.tf": code}, pinned)
return result.message if result else ""
def test_code_of_the_pinned_provider_alone_is_accepted():
code = """
terraform {
required_providers {
cloud = {
source = "example/cloud"
version = "1.2.3"
}
}
}
resource "cloud_service" "web" {}
data "cloud_project" "this" {}
resource "terraform_data" "marker" {}
module "network" {
source = "example-modules/network/cloud"
version = "1.0.0"
}
"""
assert provider_refusal(code) == ""
def test_a_resource_of_a_provider_that_is_not_pinned_is_refused():
message = provider_refusal('resource "sourcehost_repository" "infra" {}')
assert message.startswith("Refused: the code uses resources of the sourcehost")
assert "Only these providers may be used: example/cloud" in message
def test_declaring_another_provider_is_refused():
declared = """
terraform {
required_providers {
sourcehost = {
source = "integrations/sourcehost"
}
}
}
"""
assert "the provider integrations/sourcehost" in provider_refusal(declared)
def test_with_nothing_pinned_there_is_nothing_to_hold_code_to():
assert provider_refusal('resource "anything_at_all" "x" {}', pinned={}) == ""
async def test_validation_refuses_a_foreign_provider_before_terraform_runs():
runner = TerraformRunner(binary="no-such-binary", providers=PINNED)
result = await runner.validate(
{"terraform/main.tf": 'resource "sourcehost_repository" "infra" {}'}
)
assert result.message.startswith("Refused: the code uses")

View File

@@ -37,7 +37,8 @@ phases:
approval: required
- id: packaging
input: [validation_results]
deliverables: [solution_guide]
deliverables: [work_breakdown, solution_guide]
attachments: [work-breakdown.json]
output: solution-architecture-guide.md
approval: required
verification: