Construction Phase -- Stage Reference (3.1-3.7)
Phase Overview
The Construction phase transforms design artifacts from Inception into working, tested software. It covers seven stages (3.1 through 3.7) that span functional design, non-functional requirements and design, infrastructure design, code generation, build/test verification, and CI pipeline configuration.
Construction is the fourth of five phases in the AI-DLC methodology. The
compiled scope grid determines which stages execute and which are skipped.
Runtime Unit batches come from unit-of-work-dependency.md (stage 2.7).
Delivery Planning (Stage 2.9) produces the approved Bolt plan — planning
content, not the walk source.
All stages follow stage-protocol.md for approval gates, question format,
completion messages, and state tracking.
Path convention. Each workflow's artifacts live under its intent record dir —
aidlc/spaces/<space>/intents/<YYMMDD>-<label>/(where<space>isdefaultunless a non-default space is in play, and<YYMMDD>-<label>is the intent directory: a compact UTC date prefix like260624plus a short kebab-case label so records sort chronologically). Below,<record>/is shorthand for that dir; e.g.<record>/construction/{unit-name}/functional-design/expands toaidlc/spaces/default/intents/<YYMMDD>-<label>/construction/{unit-name}/functional-design/. The dir name is a human-readable label; the canonical identity is the UUIDv7 stored in theintents.jsonregistry row. (Projects created before the per-intent layout used a flat tree; the engine migrates them on first run.)
Construction walk
A Bolt is the planned delivery slice recorded in
Delivery Planning: one or more Units with a Definition of Done, confidence
hypothesis, and ownership. Runtime order follows unit-of-work-dependency.md
and the recorded iteration choice, not the grouping in bolt-plan.md.
New solo workflows that include Unit decomposition and an in-scope
source-producing per-unit stage default to Construction Checkpoints: enabled,
Construction Iteration: unit-major, and Construction Execution: serial.
They complete one Unit's applicable design and source-producing stages before
the next. Preserve an explicit stage-major choice. Design-only and no-Unit
workflows retain their existing stage flow; team-owned work uses unit_gate.
Existing workflows without the checkpoint setting keep the legacy first-stage
review and late per-stage gate cascade.
For eligible checkpoint work with skeleton-on, the first DAG Unit is the smallest working integrated slice. It completes its applicable stages, including Code Generation, before later Units even with stage-major selected. Its real end-to-end project check must pass, and a human must approve that verified skeleton. A legacy first Construction-stage approval is only a stage review; it does not establish that an integrated skeleton has been built.
All Unit/batch checkpoints reuse the intent's recorded, human-authorized
Construction Verification Command. Delivery Planning proposes it from the
project scan. Before presenting the command, write it to
<record>/verification-command.txt with the harness's file-write tool
(Write/edit), never a shell echo or heredoc. Repo-derived command text must never
be interpolated into a shell line, where substitutions could execute before
approval. Use the invoking SessionStart session ID: both log decision and
log answer require
--checkpoint verification-command --command-file verification-command.txt --session "<session ID>".
Copy the complete canonical command exactly from the command field in the
decision tool's JSON output into the verification-command question's code span;
never abbreviate it. Choose a delimiter that preserves any command backticks.
The human can also open <record>/verification-command.txt. The canonical
command is a nonblank single line of at most 1024 characters. Control characters
and display-spoofing characters (Unicode format characters, including zero-width
and bidi controls, line/paragraph separators, and no-break space U+00A0) are refused.
The human's exact Approve / Request Changes reply in that session binds
the answer to the pending command. Only Approve authorizes the receipt;
an unrelated reply, Request Changes, or a reply from another session does not.
Never write --details "Approve" unless the human chose it; only then run
state set-construction-verification-command --command-file verification-command.txt to write the matching Runtime
State field. A human may defer when no runnable
check exists yet; the first checkpoint then asks. The current approval receipt,
not the field alone, authorizes execution. Changing it requires a new receipt
and typed setter, never generic state set or an automatic choice.
Skeleton-off offers Continue automatically / Review each checkpoint at Construction entry; skeleton-on offers it after the real skeleton checkpoint. Only an emitted offer with no recorded choice prompts automatically. On-demand requests can change the choice during Construction. The answer controls ordinary completion questions; it never grants Plan Approval, verification command selection, an enabled summary confirmation, or successful verification of a failed check.
Eligible new source-producing solo Unit workflow:
Default: unit-major + serial + verified Unit checkpoints
Skeleton-on: first whole integrated Unit → real check → human approval
When offered: Continue automatically / Review each checkpoint
Remaining Units: applicable stages → checks → completion per recorded policy
Completion-only stage directives: bookkeeping over recorded Unit approvals
Existing, design-only, no-Unit, or team-owned workflow:
Preserve its recorded path and applicable stage or Unit-gate policy
After the per-unit work:
Build and Test, then CI Pipeline if included, run once across the solution
Route checkpoints before bodies. A construction_checkpoint directive
verifies and approves existing Unit work; it does not rerun Code Generation.
With command_authorized: false, ask the verification-command question before
any verify, complete the human decision/answer/setter flow, then call next.
Show "Verified with <full command> (exit 0)" in the approval question;
verification_command is the full canonical recorded command, never an abbreviated label.
A swarm_checkpoint handles a completed batch before later batch work. After
verification, approval, or rejection, call next, never approve the whole stage for one Unit or batch.
Only after verify reports verified: true and the current checkpoint has
ready: true, open the human Unit/skeleton approval question with
aidlc engine bolt checkpoint --action ask --unit "<unit>" --kind <unit|skeleton> --session "<session ID>";
ask refuses an unready or unverified checkpoint. For a human batch question,
only after status reports ready: true, run
aidlc engine bolt swarm-checkpoint --action ask --batch <N> --units "<Units>" --session "<session ID>".
Then present Approve / Request Changes and wait. The human's exact reply
in that session, to this checkpoint question, authorizes the matching action;
an unrelated reply, another session's reply, or a reply to a different question
does not. Pass that same --session on approval/rejection and never pass
--user-input the human did not choose. Consent is one-shot and bound to the
current checkpoint fingerprint, verification proof ID, and authorized command
digest (batch questions bind the fingerprint and per-Unit Command SHA-256 set).
Re-running verify or swarm finalize withdraws every open checkpoint question
and captured checkpoint response for this intent, in any session. Re-verify,
confirm verified: true (batch: ready: true after source landing), and ask again;
an older response cannot approve the new evidence. Automatic approval
(human_required: false) needs no ask and no --user-input; human rejection
always needs this verified question-and-answer flow.
A stage with construction_policy.completion_only: true and
human_completion_required: false skips body, questions, reviewer, and learnings
prompt, then reports awaiting-approval and approved without invented user
input. Other completion gates follow human_completion_required; the legacy
path without policy retains its existing human-gate procedure.
Version-4 checkpoint proofs retain the command's command_sha256 and full
canonical command in command_label, plus exit status, full stdout/stderr byte
counts and SHA-256 digests, and the last 2 KiB of each stream in stdout_tail and
stderr_tail. These tails also appear in checkpoint CLI JSON. They are decoded
as UTF-8 after dropping a leading partial multibyte sequence, with control
characters other than newline and tab replaced by U+FFFD; full output is not
retained. Project check commands must not print secrets: tails are not
secret-redacted. Use the tails to explain a failure; any further diagnostics use
the same authorized project check, not a newly chosen command. Legacy version-1
through version-3 proofs require re-verification with
aidlc engine bolt checkpoint --action verify --unit "<unit>" --kind <unit|skeleton>
before the Unit can be approved. GATE_APPROVED binds Verification Command SHA-256
to the proof's digest.
The verifier records a tool-owned CHECKPOINT_VERIFICATION_RECORDED receipt
alongside the proof file, and approval requires that receipt; a hand-written
proof file cannot verify a Unit.
Code Generation's Plan Approval remains a human stop before generation for every
Unit. Grouped Plan Approval may present the exact live swarm Unit set together,
but still records individual receipts. Pre-generation summary confirmation is
required only when directive.ceremony.summary_confirmation === "on". See
Construction commands
for the checkpoint and approval commands.
Iteration and execution are separate. Unit-major is serial. To choose swarm
explicitly for eligible checkpoint work, select stage-major and then
Construction Execution: swarm; guided and automatic completion are both
supported. An autonomy answer does not change execution or iteration order.
Already approved inline Units are not rebuilt by a later swarm. Legacy workflows
without the execution setting retain their existing autonomy-based swarm route.
Team-owned gates. With Unit Ownership: team, the per-stage rhythm gates
each settled (stage, Unit) before that Unit advances; unit-end gates once
after its final applicable per-unit stage. These remain separate from the solo
checkpoint policy. The engine refreshes Unit Progress, and each gate report
names its Unit so decisions and receipt floors remain scoped to that work.
Team-mode claims use claim/<intent-id8>/<unit> refs with compare-and-swap
updates. A successful claim writes a gitignored checkout stamp; that checkout
routes only the stamped Unit and carries the claim generation on lifecycle,
review, gate, and fork evidence. Unscoped main emits a terminal fan-out notice
while claims are live. aidlc-unit.ts release <unit> writes a tombstone instead
of deleting the ref, invalidating stale attempts while preserving history. A
participant clone opts into the guided claim picker once with
aidlc-unit.ts participate; facilitator main deliberately omits that marker.
Scoped routing and receipt writes are offline-first: the claim-time stamp is
authoritative. Registry liveness is rechecked only at claim-sensitive
boundaries such as fork/release; an unavailable remote warns and proceeds from
the stamp, while an online stale or released attempt is refused.
Completed teams commit and run aidlc unit publish <unit>. Unscoped main then
pins the exact claim-ref OID, validates its artifacts/receipts/gates/reviews and
Plan Approval without materializing a worktree, records one human merge gate,
and lands the candidate through aidlc unit land. Git content lands before the
Unit row is folded; main-owned state/runtime markers are retained, the team's
new audit shard transports its attempt-keyed receipts, and UNIT_MERGED marks
the row. Source conflicts abort before state mutation. After the final merged
row, Build and Test and CI Pipeline route once on main.
Per-unit batch waves (optional, stage-major only). On a recorded
stage-major path, the engine MAY emit directive.wave for one of the four
inline design stages (3.1–3.4). The wave comes from one healed DAG snapshot;
the conductor does not read runtime-graph.json or derive sibling paths.
Code Generation (3.5, workspace_requires: true) is NEVER wave-eligible:
concurrent builders would collide writing into the shared workspace (the
swarm path's per-unit worktrees exist for exactly this isolation), and its
initial Plan Approval is a mandatory stop in every execution mode: the engine's
question to the person cannot fold into a builder's return message. The stop is the conductor's:
under a relaxed or off Guard Policy the plan-approval fence stands aside
for undirected work and records GUARD_STOOD_ASIDE instead of refusing.
After approval, content edits for the same target and attempt follow the
effective-fence rule in Code Generation below; a lowered fence permits
continuation without another Plan Approval stop.
Each entry carries kind-resolved consumes, explicit absent consumes, all
produces, the applicable required subset, a Unit-local diary path, build state,
paired-review state, and whether its wave completion receipt is still required.
Builders receive the parent stage file, inline context roster, warnings, and
exact accumulated steering content. A blocked builder withholds an applicable
required path, not an optional or kind-exempt path. After build and review,
unit complete --wave verifies the live entry, fans Unit diary entries into the
parent diary idempotently, and emits UNIT_COMPLETED. The engine holds the
current batch until every applicable Unit has all of that evidence, then permits
a dependent batch or the single stage gate. Waves never apply under
Construction Iteration: unit-major; harnesses without a parallel dispatch
primitive process the entries serially. See
stage-protocol-construction.md § "Per-unit batch waves" for the full contract.
Parallel batches. Follow the exact dependency-ready Units emitted by the
engine. Explicit stage-major/swarm execution can dispatch eligible Code
Generation Units concurrently. In checkpoint-enabled workflows, each completed
batch returns a swarm_checkpoint for guided or automatic completion before
later work. Legacy swarm settlement retains its existing stage gate.
BOLT_STARTED / BOLT_COMPLETED are per Unit/worktree on the swarm path;
SWARM_COMPLETED closes the batch. Serial inline work uses its Unit lifecycle
and checkpoint receipts.
Each new Bolt worktree is .aidlc/worktrees/bolt-<id8>_<slug> on branch
bolt-<id8>_<slug>. The intent registry UUID suffix <id8> is shared with
Unit claims, so parallel intents can reuse Unit slugs without sharing branches
or retained/parked refs. Creation refuses an intent without a registry UUID;
adopt or re-create the intent before Construction. See
Bolt identity
for naming and the provenance checks that let pre-upgrade legacy Bolts finish
without creating new Bolts in the old shape. Cleanup refuses a branch checked
out at another worktree path and preserves that owner's branch and refs.
A submodule the main checkout has initialized is set up in each new Bolt
worktree too, at the commit the base records, cloned from the main checkout's
own copy (no network or credentials). An uninitialized submodule stays an empty
directory. Landing keeps the worktree, and names the submodule, when its copy
there has uncommitted changes or a commit the main checkout's copy lacks. The
committed-source check reads an initialized submodule the way the live source
walk does, its commit plus its files, so a clean checkout with a submodule
matches its own HEAD.
Before initial protected prepare, all Units undergo a read-only preflight of current approval or permitted postapproval continuation, plus committed, reproducible parent application source. This applies to legacy autonomy and new checkpoints. An uncommitted approved source snapshot is refused before any child is created: obtain explicit authorization to commit it, then retry. The inline skeleton's approved source must be committed before a later parallel batch; prepare never makes that commit automatically.
A rejected batch with resume_existing: true uses prepare --resume-existing.
If rejection retired the prior approval, obtain fresh Plan Approval for the
revision. Retries after that approval may use lowered-fence continuation for
the same intent, target, and attempt: execution_allowed: true permits it even
with ok: false, without reviving an older attempt's approval.
Surviving worktrees retain source and archive prior
metadata. If native source landing removed a child, the tool can recreate it from
the already-landed parent source when the required landing evidence exists,
retaining the rejection revision. It does not promise preservation of every
post-merge child. See Swarm prepare.
Failure handling. A Code Generation failure always halts Construction
regardless of autonomy mode. Options are retry (re-run just the failed
Unit), skip (mark [S] and continue — dependents may also fail), or abort.
Successful siblings in a parallel batch keep their [x] status and
artifacts. See stage-protocol-construction.md §§ "Unit and skeleton checkpoints" and
"Halt-and-ask on failure" for the canonical procedures.
The ordinary failure-prompt Abort pauses Construction with the worktree
preserved. A stale-review recovery abort explicitly carrying --discard instead
parks tracked and non-ignored untracked files and reviewed source refs, then
removes the live checkout and branch. After obtaining the human's selection,
execute the returned abort command unchanged. When present, the abort result's
restore_operation has route worktree and exact args selecting the saved
slug, stamp, and repository (--repo <name> or --repo .), followed by
--intent <record-dir-name> --space <space> so recovery stays bound to that
intent after the active intent changes. On a human
restore request, invoke {{INVOKE}} engine worktree <args...> with each listed
arg passed exactly as a separate argv argument, never joined into a shell
command. Restoration recovers files in .aidlc/restored/bolt-<id8>_<slug>-<stamp> on
restore/bolt-<id8>_<slug>-<stamp>, without overwriting a new live Bolt or reviving the
old attempt's review authority. restore_hint is optional human display text
only, not execution input. If safe rendering fails, the hint is omitted and
restore_hint_error explains why while the operation remains. Offer restoration
based on the operation, not the hint. If only review evidence remained, the
evidence-only descriptor has no restoration operation, hint, hint error, or
exclusions: no working files were saved, restore refuses, and doctor offers
purge only.
The recovery walkthrough
explains what was set aside, the exclusions, exact restore selection, and
informational doctor listings and purge options. Legacy restores retain the
legacy name and require the selected intent's exact WORKTREE_DISCARDED
Parked ref provenance.
Stage Summary Table
| Stage | Name | Execution | Condition | Lead Agent | Support Agents | Mode | Per-Unit |
|---|---|---|---|---|---|---|---|
| 3.1 | Functional Design | CONDITIONAL | New data models, complex business logic, or business rules need design | aidlc-architect-agent | aidlc-developer-agent | inline | Yes |
| 3.2 | NFR Requirements | CONDITIONAL | Performance, security, scalability, reliability, or observability requirements needed, or tech stack selection needed | aidlc-architect-agent | aidlc-devsecops-agent, aidlc-compliance-agent, aidlc-quality-agent | inline | Yes |
| 3.3 | NFR Design | CONDITIONAL | NFR Requirements was executed and NFR patterns need design | aidlc-architect-agent | aidlc-aws-platform-agent | inline | Yes |
| 3.4 | Infrastructure Design | CONDITIONAL | Infrastructure services need mapping, deployment architecture required, or cloud resources needed | aidlc-aws-platform-agent | aidlc-devsecops-agent, aidlc-compliance-agent | inline | Yes |
| 3.5 | Code Generation | ALWAYS | Always executes for every unit in the execution plan | aidlc-developer-agent | (none) | subagent (aidlc-developer-agent) | Yes |
| 3.6 | Build and Test | ALWAYS | Always executes once after all per-unit stages are finished | aidlc-quality-agent | aidlc-devsecops-agent | inline | No |
| 3.7 | CI Pipeline | CONDITIONAL | Execute when CI pipeline needs creation or significant modification | aidlc-pipeline-deploy-agent | (none) | inline | No |
Stage 3.1: Functional Design
Metadata
| Property | Value |
|---|---|
| Stage | 3.1 |
| Phase | Construction |
| Execution | CONDITIONAL (per execution plan) |
| Condition | New data models, complex business logic, or business rules need design. Skip if simple logic changes with no new business logic. |
| Per-Unit | Yes |
| Lead Agent | aidlc-architect-agent |
| support_agents | aidlc-developer-agent |
| mode | inline |
| Inputs | unit-of-work.md, unit-of-work-story-map.md, requirements.md, domain design artifacts |
| Outputs | <record>/construction/{unit-name}/functional-design/ -- functional-spec.md, rules.md, entities.md, CONDITIONAL: frontend-components.md |
Purpose
Design the business logic, domain model, and rules for a single unit of work. The aidlc-architect-agent leads with the aidlc-developer-agent providing technical feasibility input.
Inputs
- Unit definition from
<record>/inception/units-generation/unit-of-work.md - Assigned stories from
<record>/inception/units-generation/unit-of-work-story-map.md - Requirements from
<record>/inception/requirements-analysis/requirements.md - Domain design artifacts from
<record>/inception/domain-design/
Steps
-
Read Unit Context -- Read the unit definition, assigned stories, requirements, and domain design artifacts.
-
Create Functional Design Plan -- Analyze the unit's scope and create a questions file at
<record>/construction/{unit-name}/functional-design/functional-design-questions.mdwith context-appropriate questions using[Answer]:tags. Focus areas: - Business logic workflows and algorithms
- Domain models and entity relationships
- Business rules, constraints, and validation logic
- Data flow and transformations
- Integration points with other units or external systems
- Error handling and edge cases
- Frontend components (component hierarchy, props/state, interaction flows, form validation)
-
Business scenarios (end-to-end user journeys, happy/unhappy paths, concurrency edge cases)
-
Collect and Analyze Answers -- Collect answers following stage-protocol.md question flow (offer interaction mode choice, collect answers, write back to file). Perform MANDATORY ambiguity analysis:
- Identify vague answers ("mix of", "not sure", "depends", "probably")
- Check for contradictions between answers
- Flag missing details needed for artifact generation
-
If ANY ambiguity found: create follow-up questions and resolve before proceeding
-
Generate Artifacts -- Generate the following in
<record>/construction/{unit-name}/functional-design/: - functional-spec.md: Detailed algorithms, workflows, data transformations, processing sequences, and decision trees for the unit's business logic
- rules.md: Decision rules, validation logic, constraints, policies, conditional behavior, and business invariants
- entities.md: Entities, relationships, data structures, attributes, lifecycle states, and entity interaction patterns
-
frontend-components.md (CONDITIONAL -- only if unit includes frontend/UI): Component hierarchy, props/state design, interaction flows, form validation rules, API integration points
-
Prepare Completion -- Verify the unit's Functional Design artifacts. Do not edit state; report the gate outcome through
aidlc-orchestrate.ts. -
Completion -- Present completion message and approval gate.
Outputs
| Artifact | Description |
|---|---|
| functional-spec.md | Algorithms, workflows, data transformations, processing sequences, decision trees |
| rules.md | Decision rules, validation logic, constraints, policies, conditional behavior |
| entities.md | Entities, relationships, data structures, attributes, lifecycle states |
| frontend-components.md | (CONDITIONAL) Component hierarchy, props/state, interaction flows, form validation, API integration |
Approval Gate
Strictly 2-option: Approve / Request Changes.
Notes
- The questions file is co-located with stage artifacts at
<record>/construction/{unit-name}/functional-design/functional-design-questions.md. - frontend-components.md is only produced when the unit includes frontend/UI work.
- All questions use the tri-mode interaction flow (Guide me / I'll edit the file / Chat).
Stage 3.2: NFR Requirements
Metadata
| Property | Value |
|---|---|
| Stage | 3.2 |
| Phase | Construction |
| Execution | CONDITIONAL (per execution plan) |
| Condition | Performance, security, scalability, reliability, or observability requirements needed, or tech stack selection needed. Skip if no NFR requirements and tech stack already determined. |
| Per-Unit | Yes |
| Lead Agent | aidlc-architect-agent |
| support_agents | aidlc-devsecops-agent, aidlc-compliance-agent, aidlc-quality-agent |
| mode | inline |
| Inputs | functional design artifacts, requirements.md, RE artifacts |
| Outputs | <record>/construction/{unit-name}/nfr-requirements/ -- performance-requirements.md, security-requirements.md, scalability-requirements.md, reliability-requirements.md, observability-requirements.md, tech-stack-decisions.md |
Purpose
Define non-functional requirements across performance, security, scalability, reliability, observability, and technology selection for a single unit. The aidlc-architect-agent leads, with the aidlc-devsecops-agent providing security input, the aidlc-compliance-agent providing regulatory input, and the aidlc-quality-agent providing testability and measurability input.
Inputs
- Functional design artifacts from
<record>/construction/{unit-name}/functional-design/(if they exist) - Requirements from
<record>/inception/requirements-analysis/requirements.md - Reverse engineering artifacts from
aidlc/spaces/<active-space>/codekb/<repo>/(if they exist)
Steps
-
Read Prior Artifacts -- Read functional design artifacts (if they exist), requirements, and reverse engineering artifacts.
-
Assess NFR Categories -- Analyze the unit across NFR categories:
- Performance: Response times, throughput, latency targets, resource utilization
- Security: Authentication, authorization, data protection, compliance requirements
- Scalability: Load handling, growth projections, scaling strategies
- Reliability: Availability targets, fault tolerance, disaster recovery, data durability
-
Observability: Monitoring, logging, alerting, tracing requirements
-
Generate Questions -- Create a questions file at
<record>/construction/{unit-name}/nfr-requirements/nfr-requirements-questions.mdfor unclear NFR areas using[Answer]:tags. Focus on quantifiable targets and specific constraints. -
Collect and Analyze Answers -- Collect answers following stage-protocol.md question flow. Perform MANDATORY ambiguity analysis:
- Identify vague answers ("fast enough", "highly available", "secure")
- Check for contradictions between NFR targets
- Flag missing quantitative targets
-
If ANY ambiguity found: create follow-up questions and resolve before proceeding
-
Generate Artifacts -- Generate the following in
<record>/construction/{unit-name}/nfr-requirements/: - performance-requirements.md: Response time targets, throughput requirements, latency budgets, resource constraints, benchmarks
- security-requirements.md: Authentication requirements, authorization model, data protection, compliance, threat considerations
- scalability-requirements.md: Load projections, scaling triggers, capacity planning, data growth, concurrency targets
- reliability-requirements.md: Availability targets (SLA/SLO), fault tolerance requirements, backup/recovery, graceful degradation
- observability-requirements.md: Monitoring requirements, logging standards, distributed tracing needs, alerting thresholds, dashboard requirements, SLI/SLO definitions
-
tech-stack-decisions.md: Technology selections and rationale -- languages, frameworks, databases, infrastructure tools, and justification for each choice
-
Prepare Completion -- Verify the unit's NFR Requirements artifacts. Do not edit state; report the gate outcome through
aidlc-orchestrate.ts. -
Completion -- Present completion message and approval gate.
Outputs
| Artifact | Description |
|---|---|
| performance-requirements.md | Response times, throughput, latency budgets, resource constraints, benchmarks |
| security-requirements.md | Authentication, authorization, data protection, compliance, threats |
| scalability-requirements.md | Load projections, scaling triggers, capacity planning, concurrency |
| reliability-requirements.md | Availability targets (SLA/SLO), fault tolerance, backup/recovery |
| observability-requirements.md | Monitoring, logging, tracing, alerting, dashboards, SLI/SLO definitions |
| tech-stack-decisions.md | Technology selections with rationale for each choice |
Approval Gate
Strictly 2-option: Approve / Request Changes.
Notes -- NFR Granularity Expansion
This stage produces 6 artifact files, expanded from the upstream reference which defines only 2 files for NFR Requirements. This is a deliberate deviation documented in SKILL.md ("Deliberate Deviations from Reference"). The finer granularity improves traceability and allows per-concern review without overloading a single document. The six files separate performance, security, scalability, reliability, and observability into dedicated artifacts, and add a dedicated tech-stack-decisions.md for technology selection rationale.
Stage 3.3: NFR Design
Metadata
| Property | Value |
|---|---|
| Stage | 3.3 |
| Phase | Construction |
| Execution | CONDITIONAL (only if NFR Requirements was executed) |
| Condition | NFR Requirements was executed and NFR patterns need design. Skip if NFR Requirements was skipped. |
| Per-Unit | Yes |
| Lead Agent | aidlc-architect-agent |
| support_agents | aidlc-aws-platform-agent |
| mode | inline |
| Inputs | NFR requirements artifacts, functional design artifacts |
| Outputs | <record>/construction/{unit-name}/nfr-design/ -- performance-design.md, security-design.md, scalability-design.md, reliability-design.md, observability-design.md, logical-components.md |
Purpose
Translate NFR requirements into concrete design patterns and architectural solutions. The aidlc-architect-agent leads with the aidlc-aws-platform-agent providing infrastructure and platform input.
Inputs
- NFR requirements from
<record>/construction/{unit-name}/nfr-requirements/ - Functional design artifacts from
<record>/construction/{unit-name}/functional-design/(if they exist) - Domain design from
<record>/inception/domain-design/for architectural context
Steps
-
Read Prior Artifacts -- Read NFR requirements, functional design artifacts (if they exist), and domain design for architectural context.
-
Generate Design Questions -- Create a questions file at
<record>/construction/{unit-name}/nfr-design/nfr-design-questions.mdwith context-appropriate questions using[Answer]:tags. Focus areas: - Resilience patterns (circuit breakers, bulkheads, fallback strategies)
- Scalability patterns (horizontal vs vertical, data partitioning, caching tiers)
- Performance optimization (latency budgets, throughput targets, resource pooling)
- Security approach (defense in depth, zero trust, encryption standards)
- Observability approach (metrics and SLI/SLO targets, structured logging, tracing depth, alerting philosophy, dashboard needs)
-
Logical component boundaries (service isolation, failure domains, blast radius)
-
Collect and Analyze Answers -- Collect answers following stage-protocol.md question flow. Perform MANDATORY ambiguity analysis:
- Identify vague answers ("mix of", "not sure", "depends", "probably")
- Check for contradictions between answers
- Flag missing details needed for artifact generation
-
If ANY ambiguity found: create follow-up questions and resolve before proceeding
-
Design NFR Solutions -- Design concrete solutions for each NFR category:
- Performance: Caching strategies, query optimization, connection pooling, async processing, CDN usage, lazy loading, pagination
- Security: Authentication flows, authorization model, encryption (at rest and in transit), input validation, CSRF/XSS protection, secrets management, audit logging
- Scalability: Horizontal/vertical scaling approach, load balancing, data partitioning/sharding, queue-based decoupling, stateless design
- Reliability: Circuit breakers, retry policies with backoff, health checks, graceful degradation, failover strategies, data replication
-
Observability: Metrics collection strategy, structured logging design, distributed tracing architecture, alerting rules, dashboard specifications, SLI/SLO tracking, correlation ID propagation
-
Generate Artifacts -- Generate the following in
<record>/construction/{unit-name}/nfr-design/: - performance-design.md: Caching architecture, optimization strategies, resource pooling, async patterns, performance budgets
- security-design.md: Authentication/authorization architecture, encryption design, input validation strategy, security headers, compliance controls
- scalability-design.md: Scaling architecture, load distribution, data partitioning strategy, capacity thresholds, auto-scaling rules
- reliability-design.md: Resilience patterns, circuit breaker configuration, retry policies, health check design, failover procedures, backup strategy
- observability-design.md: Metrics collection architecture, structured logging design, distributed tracing strategy, alerting rules and escalation, dashboard specifications, SLI/SLO definitions, correlation ID propagation
-
logical-components.md: Logical infrastructure component inventory -- service boundaries, failure domains, blast radius mapping, component isolation strategy, shared resource identification. Bridges NFR design decisions with Infrastructure Design by providing a component-level view of where NFR patterns apply.
-
Prepare Completion -- Verify the unit's NFR Design artifacts. Do not edit state; report the gate outcome through
aidlc-orchestrate.ts. -
Completion -- Present completion message and approval gate.
Outputs
| Artifact | Description |
|---|---|
| performance-design.md | Caching architecture, optimization strategies, resource pooling, async patterns |
| security-design.md | Auth architecture, encryption design, input validation, security headers |
| scalability-design.md | Scaling architecture, load distribution, data partitioning, auto-scaling rules |
| reliability-design.md | Resilience patterns, circuit breakers, retry policies, failover procedures |
| observability-design.md | Metrics, structured logs, tracing, alerts, dashboards, SLI/SLO definitions |
| logical-components.md | Component inventory, service boundaries, failure domains, blast radius mapping |
Approval Gate
Strictly 2-option: Approve / Request Changes.
Notes -- NFR Design Granularity
This stage produces 6 artifact files (5 NFR-specific designs plus logical-components.md), expanded from the upstream reference which defines only 2 files for NFR Design. This is a deliberate deviation documented in SKILL.md ("Deliberate Deviations from Reference"). The logical-components.md artifact serves as a bridge between NFR design and Infrastructure Design (Stage 3.4) by mapping where NFR patterns apply at the component level.
Stage 3.4: Infrastructure Design
Metadata
| Property | Value |
|---|---|
| Stage | 3.4 |
| Phase | Construction |
| Execution | CONDITIONAL (per execution plan) |
| Condition | Infrastructure services need mapping, deployment architecture required, or cloud resources needed. Skip if no infrastructure changes and infrastructure already defined. |
| Per-Unit | Yes |
| Lead Agent | aidlc-aws-platform-agent |
| support_agents | aidlc-devsecops-agent, aidlc-compliance-agent |
| mode | inline |
| Inputs | NFR design artifacts, domain design, functional design |
| Outputs | <record>/construction/{unit-name}/infrastructure-design/ -- infrastructure-specification.md (deployment + services + CONDITIONAL shared), monitoring-design.md, cicd-pipeline.md |
Purpose
Design the infrastructure, deployment architecture, monitoring, and CI/CD pipeline for a single unit. The aidlc-aws-platform-agent leads, with the aidlc-devsecops-agent ensuring infrastructure security and the aidlc-compliance-agent checking data residency and regulatory constraints.
Inputs
- NFR design from
<record>/construction/{unit-name}/nfr-design/(if exists) - Functional design from
<record>/construction/{unit-name}/functional-design/(if exists) - Domain design from
<record>/inception/domain-design/ - NFR requirements from
<record>/construction/{unit-name}/nfr-requirements/(if exists)
Steps
-
Read Prior Artifacts -- Read all prior design artifacts for context: NFR design, functional design, domain design, NFR requirements.
-
Generate Infrastructure Questions -- Create a questions file at
<record>/construction/{unit-name}/infrastructure-design/infrastructure-design-questions.mdwith context-appropriate questions using[Answer]:tags. Focus areas: - Deployment strategy (containerized, serverless, hybrid, multi-region)
- Compute/storage/networking (sizing, topology, latency requirements)
- Monitoring approach (metrics, logging, tracing, alerting thresholds)
- CI/CD pipeline (build stages, deployment strategy, rollback procedures)
- Secrets management (vault, environment variables, rotation policy)
-
Scaling policy (auto-scaling triggers, capacity limits, cost constraints)
-
Collect and Analyze Answers -- Collect answers following stage-protocol.md question flow. Perform MANDATORY ambiguity analysis:
- Identify vague answers ("cloud-based", "auto-scale", "standard monitoring")
- Check for contradictions between answers
- Flag missing details needed for artifact generation
-
If ANY ambiguity found: create follow-up questions and resolve before proceeding
-
Design Infrastructure -- Design infrastructure across four areas:
- Deployment Architecture: Compute model (containers, serverless, VMs), networking topology, storage strategy, environment layout (dev/staging/prod)
- Infrastructure Services: Databases (type, sizing, replication), caches (strategy, eviction), message queues, search services, CDN, DNS, load balancers
- Monitoring & Observability: Metrics collection, log aggregation, distributed tracing, alerting rules, dashboards, SLI/SLO tracking
-
CI/CD Pipeline: Build stages, test stages, deployment stages, environment promotion, rollback strategy, feature flags, artifact management
-
Generate Artifacts -- Generate the following in
<record>/construction/{unit-name}/infrastructure-design/. Keep the content tabular (deployment, services, shared, and monitoring are tables): - infrastructure-specification.md: the core infra design — a Deployment table (compute, networking, storage, environments, IaC, sizing), an Infrastructure Services table (databases, caches, messaging, integrations, service discovery), and a CONDITIONAL Shared Infrastructure table (shared resources across units + ownership/access boundaries), all in one document
- monitoring-design.md: the monitoring that implements NFR Design's observability-design strategy, tabular — metrics/KPIs, alerts, SLIs/SLOs, plus log-aggregation and tracing configuration and dashboard specifications
-
cicd-pipeline.md: pipeline stages, build configuration, test automation integration, deployment strategy (blue-green, canary, rolling), rollback procedures, environment promotion, secrets management in CI/CD
-
Prepare Completion -- Verify the unit's Infrastructure Design artifacts. Do not edit state; report the gate outcome through
aidlc-orchestrate.ts. -
Completion -- Present completion message and approval gate.
Outputs
| Artifact | Description |
|---|---|
| infrastructure-specification.md | Deployment (compute/networking/storage/environments/IaC), infrastructure services, and CONDITIONAL shared resources — tabular |
| monitoring-design.md | Metrics, alerts, SLIs/SLOs, logs, tracing, dashboards — tabular where possible |
| cicd-pipeline.md | Pipeline stages, build config, deployment strategy, rollback procedures |
Approval Gate
Strictly 2-option: Approve / Request Changes.
Notes -- Infrastructure Design Consolidation
This stage produces 3 artifact files. Deployment, infrastructure services,
and shared resources were consolidated into a single tabular
infrastructure-specification.md (closer to the upstream reference's single
infra doc), while monitoring-design.md and cicd-pipeline.md stay dedicated
artifacts because downstream Operation stages consume them independently
(observability-setup reads monitoring; deployment-pipeline reads the CI/CD
design). Shared infrastructure is a CONDITIONAL section of the specification,
present only when multiple units share resources.
Stage 3.5: Code Generation
Metadata
| Property | Value |
|---|---|
| Stage | 3.5 |
| Phase | Construction |
| Execution | ALWAYS (per-unit) |
| Condition | Always executes for every unit in the execution plan. |
| Per-Unit | Yes |
| Lead Agent | aidlc-developer-agent |
| support_agents | (none -- focused implementation) |
| mode | subagent (Task tool subagent_type: aidlc-developer-agent) |
| Inputs | ALL prior design artifacts for this unit |
| Outputs | application code (workspace root) + <record>/construction/{unit-name}/code-generation/ -- code-generation-plan.md, code-generation-questions.md, unit-test-instructions.md, code-summary.md, traceability.json, plus engine-required companion source-manifest.json |
Purpose
Generate all application code, tests, and configuration for a single unit of
work. This is the only stage that always executes for every unit regardless of
the execution plan. Code is written to the workspace root, never to
<record>/.
Critical Rules
- Application code goes to workspace root, NEVER to
<record>/ - Brownfield: modify files in-place. NEVER create duplicates like
ClassName_modified.java - Add
data-testidattributes to interactive UI elements for test automation - Before review, write the engine-required companion
source-manifest.jsonlisting every application-source path this unit created, modified, or deleted, including files written by shell commands, scaffolding, or generators - Measurable quality targets from NFR Requirements, NFR Design, and the Testing Contract coverage floor are inputs, not suggestions. NEVER relax, lower, or disable a defined target, including threshold settings in test or build configuration, to make a step pass; surface the gap instead.
Inputs
- Functional design from
<record>/construction/{unit-name}/functional-design/(if exists) - NFR requirements from
<record>/construction/{unit-name}/nfr-requirements/(if exists) - NFR design from
<record>/construction/{unit-name}/nfr-design/(if exists) - Infrastructure design from
<record>/construction/{unit-name}/infrastructure-design/(if exists) - Domain design from
<record>/inception/domain-design/ - Unit definition from
<record>/inception/units-generation/unit-of-work.md - Story map from
<record>/inception/units-generation/unit-of-work-story-map.md
Steps
This stage has a two-part structure: planning followed by generation.
PART 1 -- Planning (Steps 1-3)
-
Read All Unit Artifacts -- Read all design artifacts for the current unit (functional design, NFR requirements, NFR design, infrastructure design, domain design, unit definition, story map).
-
Create Code Generation Plan -- Create a detailed plan at
<record>/construction/{unit-name}/code-generation/code-generation-plan.mdwith checkboxes for each implementation step. Include story-to-code-step traceability -- map each plan step back to the user story it implements.
Run aidlc-testing-posture.ts render and paste its complete
## Testing Contract JSON block into the plan. The resolver reads
org/team/project Testing Posture sections additively: a project coverage or
integration note remains applicable but does not erase a team methodology;
a contradictory narrower methodology is rejected.
The contract supplies a methodology-specific plan profile:
- TDD -- Red/Green/Refactor for every applicable testable layer: data, repository, business logic, API, and frontend.
- BDD -- executable behavior scenarios before an observable feature slice, followed by cross-layer implementation, green scenarios, and refactoring. It is not converted to layer-local TDD.
- ATDD -- executable acceptance tests before the complete cross-layer feature implementation, followed by acceptance-green and refactoring.
- Custom/mixed -- the exact affirmed ordering is preserved, including combinations such as scenario-first BDD with lower-level unit tests after implementation.
- Test-after -- implementation then tests for every applicable testable layer.
Greenfield plans bootstrap a minimal runnable test command before the first Red/scenario/acceptance step; brownfield plans verify the existing command first. The selected Test Strategy supplies volume/types and the scope adds its floor (coverage/CI, targeted regression, or no additional floor); neither obligation replaces the other. Under Minimal, a bug/security targeted regression may add one integration/E2E test when that is the narrowest level that reproduces the defect.
Test files are MANDATORY in the plan. The plan MUST include steps for: - Unit test files (one per component/module with key behavior coverage) - Test configuration (vitest.config, jest.config, or equivalent)
If the plan omits test file steps, they must be added before presenting to the user. Tests are not deferred to Build and Test -- that stage verifies and extends, not creates from scratch.
Number each plan step sequentially (Step 1, Step 2, etc.) for clear execution ordering and traceability.
Resolve one code-generation record directory from the directive:
<record>/construction/<directive.unit>/code-generation/ when
directive.unit is present, otherwise the zero-Unit stage directory
<record>/construction/code-generation/. Also create
unit-test-instructions.md there before Plan Approval. Match the active test
strategy:
- Minimal: Requirement-driven unit tests (1 test per requirement,
happy-path floor per component), approximately 5-15 tests total
- Standard: 5-8 tests per component, with key behavior coverage
- Comprehensive: 10-15 tests per component, with thorough coverage
Include test framework setup and configuration, the exact runnable command
available before the first test-first cycle, expected coverage targets,
mocking/stubbing guidance, and test data management. Every run command MUST
be scoped to this unit using exact test file paths or an exact unit filter.
A bare project-wide command such as npm test is not acceptable because
Build and Test executes every unit's commands.
The plan opens with a short ## Summary (Builds, Touches, Tests lines) that
the engine shows the person when it asks for approval.
- Plan Approval -- the engine asks. When both files are written, the
conductor runs
next. A ready plan (non-empty plan and instructions, a valid and current Testing Contract, a readable workspace source) makesnextreturn aplan-approvalask instead of the build: the question, each target's summary and plan path, and Approve Plan, Request Changes, and I'll edit the files. The engine writescode-generation-questions.md(the question, both tags, and a blank[Answer]:) and records the question in the protected runtime directory; the conductor shows it and ends the turn. The human-turn hook reads the reply in the person's own words, from any chat on this piece of work, takes the fingerprint of the files as they are then, and writes the answer, the receipt, and thePLAN_APPROVAL_RECORDEDrow. The nextnextreturns the run-stage withplan_approval.status: "approved"(build),revise(with the person's words),repair(a Testing Contract an edit broke), orplan(finish the files). In edit mode the person changes the files or writes their answer in the questions file and says done; the guard refuses the conductor's writes to those files meanwhile. A plan that is not ready is never asked about:nextnames the repair instead.
A postapproval plan, instruction, or Testing Contract edit for the same
target and attempt asks again when the effective plan-approval fence is on
(strict by default or explicit guard.plan-approval on). If lowered by
relaxed, off, or guard.plan-approval off, the build continues with the
updated content. Preserve the original evidence; the edited content was not
thereby approved. Testing Posture, scope, strategy, or project type changes
follow that same rule. Other code moving after approval never asks again on
any Guard Policy: the build continues with one change_notices line naming
the files. A different intent or target, a new attempt, or missing actual
initial approval still requires its own approval. After a rejected gate (the
Code Generation completion gate, a Unit checkpoint, or a swarm batch
checkpoint), while the plan is still the one approved before, next first
returns revise with the person's words from that gate, so the question
that follows shows the revised plan. Re-running next, or a
reissued directive for the same target and attempt, never reopens it. A
forwarding-loop continuation is never approval.
testing-posture verify reports execution_allowed: true with exit 0 when
continuation is permitted, even if ok: false says the current content is
not approved. Use that execution result; begin and brief honor it too.
The friendly reason explains continuation; approval_reason keeps the
stale binding detail and is not a new approval stop. When both content and
source changed, read-only verify also previews the source change in
change_notices. Generation start, including guard dispatch and swarm
preparation, records and announces the accepted source change and
re-baselines source provenance under the lowered fence. The original
approval fingerprint, answer, and session remain unchanged. Existing delegated
workers follow the live fence of their verified parent intent, including
later lowering or raising.
Missing artifacts or malformed or structurally incomplete Testing Contracts
need repair before execution, not an automatic new approval ceremony.
obligations.strategy must match test_strategy; both strategy_volume
and scope_floor must contain nonblank obligations.
A lowered fence also leaves execution provenance mandatory: before generation
starts, an unbindable source or a failed runtime/audit publication blocks the
operation. Repair that operational failure and retry with the same approval
and fence setting. A valid human-issued break-glass receipt retains its
existing source-binding exception.
Lowering the per-work fence does not replace genuine initial approval,
executable artifacts, or current target/attempt authority. Direct writes and
developer dispatch validate every selected target before publishing any
generation start. Repairing the plan records remains available while those
execution requirements are unmet.
A dispatch selecting multiple targets holds the generation authority locks
across the whole start. If any target fails or source changes during
publication, every receipt newly started by that dispatch is restored.
Retry then checks the current source again; the original approvals and
lowered fence settings remain unchanged.
PART 2 -- Generation (Steps 4-7)
- Generate Code -- Before delegating, display to the user: "Generating code for [N] plan steps. This may take several minutes depending on project complexity. I'll show a summary when complete."
Delegate to Task tool with the aidlc-developer-agent subagent (subagent_type="aidlc-developer-agent").
Context passed to subagent:
- First, verbatim, the output of aidlc-testing-posture.ts brief --unit
<unit> (or --stage-level). Its first line is the exact target marker,
AIDLC-UNIT: <directive.unit> for unit work or
AIDLC-STAGE: code-generation for a zero-Unit directive; its second line
is AIDLC-TESTING-CONTRACT: <contract_sha256> from the current plan. With
its fence on, the dispatch guard rejects missing, different, or stale
hashes. Contextual dependencies do not receive additional target markers.
- The lead agent's persona from agents/aidlc-developer-agent.md and knowledge
from .claude/knowledge/aidlc-developer-agent/ (included in the prompt
since subagents cannot access conversation history)
- Design artifacts for the CURRENT UNIT ONLY (not all units)
- A 1-2 line summary of each inception-phase artifact with its file path
(requirements summary, stories summary, app design summary) -- the
subagent can Read specific files if it needs full content
- The current plan and unit-test-instructions.md, which that
output already carries using the approval-content projection: the plan
with a terminal ## Review appendix removed, task markers reset, and
spacing normalized, plus the instructions byte for byte. The fingerprint
excludes the appendix, so it is not work to execute; with its fence on,
the dispatch guard refuses a handoff that quotes it. After permitted
postapproval edits, use the current brief without calling the edits approved
- Project workspace details (languages, frameworks, conventions from
aidlc-state.md)
- Instructions to execute each plan step sequentially and mark checkboxes
as completed
- The Testing Contract in the current brief is authoritative. The subagent
does not independently re-resolve memory; it executes that contract's TDD, BDD, ATDD,
test-after, or custom/mixed profile exactly.
- Measurable quality targets from NFR Requirements, NFR Design, and the
Testing Contract coverage floor are inputs, not suggestions. The subagent
must NEVER relax, lower, or disable a defined target, including threshold
settings in test or build configuration, to make a step pass; it must
surface the gap instead.
Context budget: Pass only the current unit's design artifacts, not all units. Summarize inception artifacts with file paths rather than embedding full content. The subagent generates all code, test files, and configuration artifacts in the workspace.
- Generate Code Summary and Source Manifest -- After the subagent
completes, create
<record>/construction/{unit-name}/code-generation/code-summary.mddocumenting: - Files created/modified
- Key implementation decisions
- Test coverage summary
- Any deviations from the plan
Also create
<record>/construction/{unit-name}/code-generation/source-manifest.json.
This is a strict version-1 JSON companion file, not a declared produces[]
artifact. It records stage: "code-generation", the exact unit name, and a
writes array containing every application-source path the unit created,
modified, or deleted, including shell-, scaffolding-, and generator-written
files. Paths are POSIX-relative and use no globs or ..; a trailing /
claims a generated directory tree. In a main-workspace multi-repo run every
entry names its recorded repo; inside the worktree hosting the Bolt, paths are relative
to that selected repo and omit repo.
The engine validates this schema and refuses to record a terminal per-unit
review without it. Its bytes and claims join the Unit Source Fingerprint;
changed stage-source paths outside all fresh reviewed manifests block
completion.
-
Prepare Completion -- Verify the unit's code and summary artifacts. Do not edit state; report the gate outcome through
aidlc-orchestrate.ts. -
Completion -- Present completion message and approval gate.
Outputs
| Artifact | Description |
|---|---|
| code-generation-plan.md | Detailed plan with checkboxes, story traceability, step sequencing |
| code-generation-questions.md | Persisted Plan Approval question and explicit human answer |
| unit-test-instructions.md | Per-unit setup, scoped run commands, coverage, mocks, and test data |
| code-summary.md | Files created/modified, decisions, test coverage, plan deviations |
| traceability.json | Structured coverage of assigned upstream IDs by code/test targets |
| source-manifest.json | Engine-required strict companion attribution index; deliberately not in produces[] |
| (application code) | All source code, tests, and config written to workspace root |
Approval Gate
Strictly 2-option: Approve / Request Changes.
Notes
- Two-part structure: The planning phase (Steps 1-3) runs inline with user interaction and plan approval. The generation phase (Steps 4-7) delegates to the aidlc-developer-agent subagent via the Task tool. This is different from most Construction stages which run entirely inline.
- Developer-agent subagent: Code generation uses
subagent_type="aidlc-developer-agent"(delegated via Task tool), not inline execution. This is the only Construction stage that uses a subagent. The subagent inherits the full session toolset (the aidlc-developer-agent declares notools:allowlist), so it reaches Read, Edit, Write, Glob, Grep, Bash, AskUserQuestion, and the inherited MCP tools. - Context budget: Only the current unit's design artifacts are passed to the subagent. Inception-phase artifacts are summarized in 1-2 lines with file paths so the subagent can selectively Read what it needs.
- Mandatory test file inclusion: Test files MUST be part of the code generation plan. Stage 3.6 (Build and Test) verifies and extends tests but does not create them from scratch.
- Source-manifest enforcement:
source-manifest.jsonis engine-validated, not a Markdownrequired-sectionstarget. Its strict schema andUnit Source Fingerprintbind every exact/directory source claim; the engine refuses the terminal review when it is absent or invalid and refuses stage completion for changed source outside the fresh reviewed claims union. - Unit-scoped execution: Each per-unit test instruction file uses exact test paths or an exact unit filter so the cross-unit execution stage does not rerun the project-wide suite for every unit.
- Brownfield awareness: In brownfield projects, the subagent modifies existing files in-place rather than creating duplicates.
Stage 3.6: Build and Test
Metadata
| Property | Value |
|---|---|
| Stage | 3.6 |
| Phase | Construction |
| Execution | ALWAYS (after ALL units complete) |
| Condition | Always executes once after all per-unit stages are finished. |
| Per-Unit | No (runs once for all units) |
| Lead Agent | aidlc-quality-agent |
| support_agents | aidlc-devsecops-agent |
| mode | inline |
| Inputs | ALL code generation outputs across all units |
| Outputs | <record>/construction/build-and-test/ -- build-instructions.md, integration-test-instructions.md, performance-test-instructions.md, security-test-instructions.md, build-and-test-summary.md, test-results.md, plus conditional test instruction files |
Purpose
Generate cross-unit test instructions, consume the per-unit unit test instructions, then actually execute the build and tests via Bash. This stage operates across ALL units -- it is NOT per-unit. The aidlc-quality-agent leads with the aidlc-devsecops-agent providing security testing expertise.
Inputs
- Code generation outputs across all units from
<record>/construction/*/code-generation/code-summary.md - Per-unit test instructions from
<record>/construction/*/code-generation/unit-test-instructions.md - Every applicable artifact under each unit's
nfr-requirements/andnfr-design/directory - Every current
## Testing Contractin the stage-level or per-unitcode-generation-plan.md, including postapproval edits permitted by a lowered plan-approval fence; those edits are not described as human-approved
Steps
-
Analyze Testing Requirements -- Read code generation summaries and per-unit test instructions across all units. Build a source-complete inventory of every measurable target from NFR Requirements, NFR Design, and every current Testing Contract. For each target, record a stable ID, source path/section, expected value, the check that produces its actual value, and any later validation stage that owns it. Catalog all required test types.
-
Generate Build Instructions -- Create
<record>/construction/build-and-test/build-instructions.md: - Dependency installation steps
- Environment setup (env vars, config files, local services)
- Build commands (compile, bundle, transpile)
- Build verification steps
- Troubleshooting common build issues
3-7. Generate Additional Test Instructions -- Consult the active test
strategy and generate the matching cross-unit instruction files:
- Minimal: Generate no additional files. Unit tests are covered
per-unit by Code Generation.
- Standard: Generate integration-test-instructions.md for key
boundaries and cross-unit interactions.
- Comprehensive: Generate integration instructions, plus
performance-test-instructions.md when performance NFRs exist and
security-test-instructions.md when security NFRs exist.
- At any strategy, add specifically named contract, E2E, accessibility, or
other instruction files when the project context requires them.
All files go in <record>/construction/build-and-test/.
Each file includes framework setup, run commands and filters, coverage
targets, and test data or environment setup.
- Generate Build and Test Summary -- Create
<record>/construction/build-and-test/build-and-test-summary.md: - Overall build status and prerequisites
- Test type inventory (which test types were generated)
- Coverage expectations per unit
- A Target Verification Matrix with Target ID, Source, Expected, Actual, Evidence, Owning Stage, and Verdict
- Applicable targets begin
Pending;N/Ais valid only when the source-complete inventory found no applicable measurable target - Readiness assessment (build-ready, test-ready, deployment-ready)
-
Known limitations or outstanding items
-
Execute Build and Tests -- Attempt to execute the build and test commands documented in the instruction files via Bash:
a. Build: Run the build commands from build-instructions.md via Bash. Capture output. b. Unit tests: Collect commands from every per-unit
code-generation/unit-test-instructions.md, deduplicate identical commands, and run each distinct command once. Commands should be unit-scoped; if a file contains a project-wide command, run it once, never once per unit. Report per-unit pass/fail without double counting. c. Integration tests (if applicable): Run integration test commands. Capture results. d. Other applicable checks: Run every applicable command from performance, security, contract, E2E, accessibility, and other generated instruction files. Defer only a check that requires a deployed or production-like environment and has a named owning validation stage in the current execution plan. Record that stage and its expected evidence path; the target remainsUnverifiedand cannot make this stage successful. Without a scheduled owning stage, it is simplyUnverified. e. Finalize and report results: Create or update<record>/construction/build-and-test/test-results.mdandbuild-and-test-summary.mdon every exit path with: - Build status (success/failure + output) - Test results (total, passed, failed, skipped) - Failure details (test name, assertion, stack trace) - Coverage report (if test framework supports it) - The finalized Target Verification Matrix. Every applicable target has an actual value, evidence, owning stage, and finalMet,Not Met, orUnverifiedverdict. NoPendingverdict remains after Step 9. -## Loop-Back Log(only when the failure ladder's rung 3 or 4 fires a loop-back): one### Loop-back N -- <ISO timestamp>entry per attempt (Diagnosis / Root-cause stage / Planned fix / Estimated impact). Append-only; survives re-runs (Modify, never Redo, on loop-back re-entry).Failure-escalation ladder: The stage has failed when a build or test command fails or an applicable target is
Not MetorUnverified. Finalize the matrix and summary before entering the same ladder for every failure kind. Lowering, relaxing, or disabling a target is never an acceptable fix.- In-stage fix (max 2 attempts) -- for root causes inside this stage's own remit (test config, build scripts, environment setup, or an executable target check): read the evidence, identify the failing configuration or scaffolding, apply the fix, re-run the failing step, and refresh the target matrix.
- Classify and estimate impact -- when in-stage attempts are exhausted or the diagnosis points upstream: decide whether the root cause lies in generated source or test code -- regardless of defect size -- or a code-generation approach choice (library/version, container image, instance type, algorithm, flag); find a fix in a swappable dimension and ESTIMATE ITS IMPACT (effort, financial cost, risk). Never declare a feasible path out of scope on an impact-unestimated effort assumption.
- Autonomous bounded loop-back -- if
Construction Autonomy Mode: autonomous, an impact-estimated fix exists, and fewer than 3 entries exist under## Loop-Back Log: record the diagnosis + impact-estimated fix, jump back to code-generation via the engine, and replay forward through its settlement-aware route per the construction protocol module (aidlc-common/protocols/stage-protocol-construction.md), "Build-and-Test failure loop-back". The failed run's gate is not presented; its enabled learnings ritual defers to the eventual passing run. When thelearningsmodule is absent, no diary or ritual runs. - Halt-and-ask -- gated/unset mode, bound exhausted, or no
identifiable fix: log the failure and present the halt-and-ask
question from the construction protocol module
(
aidlc-common/protocols/stage-protocol-construction.md) -- the impact-estimated 3-option variant (Retry with fix [estimated impact] / Accept failure / Abort) when a candidate fix exists, or the no-fix 2-option variant (Accept failure / Abort) when rung 2 found none.
Loop-back replay routing: If Code Generation never used unit lifecycle receipts, preserved artifacts can take the all-covered
gate: truefast path; apply the planned fix and deterministic Modify/Keep decisions before that gate. Once any lifecycle row exists, receipt mode is sticky and the jump re-emits per-Unit work: re-mintunit start/unit complete, apply Modify to targeted Units and Keep to the rest, and run the declared reviewer per Unit. Both paths MUST record a fresh current-attemptREVIEW_COMPLETEDfor every applicable Unit before the settle/approval gate becauseSTAGE_JUMPEDinvalidates all earlier reviews. Under unit-major the swarm never fires; replay follows the serial per-Unit walk. A revised Code Generation plan still requires fresh human Plan Approval.The replay repairs the Code Generation plan under a NEW stage attempt, so the prior approval no longer applies. Record the delta in the Loop-Back Log and write the repaired plan;
nextthen asks the person for Plan Approval again before any fix generation. The gated "Retry with fix" choice authorizes the jump; it is not approval of the revised plan.Swarm cheap path: A jump creates a new exact stage-attempt
Run floorboundary token, so stale convergence rows cannot count. Park/discard stale worktrees/branches and run a freshprepare; they cannot be adopted into the new attempt becausefinalizerequires its current prepare stamp. The saved abort result's or doctor'srestore_operation, when present, recovers parked files separately, not their current-attempt authority. Invoke itsworktreeengine route with each listed arg exactly as argv, never joined into a shell command. Hints and rendered commands are human display text only; rendering errors do not remove typed operations. Evidence-only attempts have no restore operation or files to restore. Runcheckfirst. A green Unit can skip a builder turn, but it still needs a terminal current-attempt reviewer receipt in the fresh worktree before it entersfinalize --claimed;finalizeverifies that receipt's current artifact fingerprint as well as the attempt stamp.Single-stage runs (
--single) stop at rung 2 -- there is no main-workflow position to move; the impact-estimated options are logged and presented in that run's isolated-run summary.On success: A successful readiness result requires every command to pass and every applicable target to be
Met, or the single explanatoryN/Arow when no target applies. -
Prepare Completion -- Verify the build/test evidence. Do not edit stage or phase state; the reported gate outcome owns the transition.
-
Completion -- Present completion message and approval gate.
Outputs
| Artifact | Description | Condition |
|---|---|---|
| build-instructions.md | Dependency install, env setup, build commands, troubleshooting | Always |
| integration-test-instructions.md | Prerequisites, cross-unit testing, external deps, data setup | Standard/Comprehensive |
| performance-test-instructions.md | Load testing, NFR scenarios, baselines, stress/soak tests | If NFR perf exists |
| security-test-instructions.md | SAST/DAST, auth testing, injection testing, compliance | If NFR sec exists |
| contract-test-instructions.md | Consumer-driven contracts, schema validation, API compat | If microservices |
| e2e-test-instructions.md | Browser automation, user journeys, cross-browser | If UI-driven |
| accessibility-test-instructions.md | WCAG compliance, screen reader, keyboard nav | If user-facing UI |
| build-and-test-summary.md | Overall status, test inventory, coverage, readiness assessment | Always |
| test-results.md | Actual build/test execution results, pass/fail, coverage | Always |
Approval Gate
Strictly 2-option: Approve / Request Changes.
Notes
- Actual Bash execution: This stage does not just document test instructions -- it actually runs the build and test commands via Bash and captures real results. This is one of the few stages that executes real commands against the codebase.
- Quality target evidence: The source-complete matrix is finalized on every
exit path. Deployed-environment checks may name a later owning stage, but
remain
Unverified;Not MetandUnverifiedboth enter the failure ladder. - Failure-escalation ladder: In-stage fixes are bounded at 2 attempts;
when the root cause lies upstream in generated code or a code-generation
approach choice, the stage classifies and estimates the impact of a fix, then either runs
the bounded autonomous loop-back to code-generation (max 3, counted by the
append-only
## Loop-Back Login test-results.md) or presents the impact-estimated halt-and-ask question. See the construction protocol module (aidlc-common/protocols/stage-protocol-construction.md), "Build-and-Test failure loop-back". Re-entry is settlement-aware, preserves the approved plan, and cannot reach its gate until every applicable Code Generation Unit has a fresh current-attempt review. - Conditional test types: Performance tests, security tests, contract tests, E2E tests, and accessibility tests are only generated when relevant conditions are met (NFR requirements exist, microservice architecture, UI-driven application, user-facing interfaces).
- Cross-unit scope: Unlike stages 3.1-3.5 which are per-unit, Build and Test runs once across all code produced by all units. It validates the integrated codebase, not individual units.
- Phase completion: This stage (along with 3.7 if applicable) marks the end of the Construction phase. The final approved report makes the engine mark Construction complete and route to Operation atomically.
Stage 3.7: CI Pipeline
Metadata
| Property | Value |
|---|---|
| Stage | 3.7 |
| Phase | Construction |
| Execution | CONDITIONAL (skip if CI already exists and is adequate) |
| Condition | Execute when CI pipeline needs creation or significant modification |
| Per-Unit | No (runs once for all units) |
| Lead Agent | aidlc-pipeline-deploy-agent |
| support_agents | (none) |
| mode | inline |
| Inputs | Code generation output from Stage 3.5, build/test results from Stage 3.6 |
| Outputs | <record>/construction/ci-pipeline/ -- ci-config.md, quality-gates.md, ci-pipeline-questions.md |
Purpose
Configure the CI (Continuous Integration) pipeline with quality gates, artifact management, and build/test automation. The aidlc-pipeline-deploy-agent leads with no support agents.
Inputs
- Build/test results from
<record>/construction/build-and-test/ - Infrastructure design from
<record>/construction/infrastructure-design/(if exists) - Workspace profile for existing CI configuration
Steps
-
Load Prior Context -- Read build/test results, infrastructure design (if exists), and workspace profile for existing CI configuration.
-
Generate Clarifying Questions -- Create
<record>/construction/ci-pipeline/ci-pipeline-questions.mdwith questions: - What CI tool is in use (CodePipeline, CodeBuild, GitHub Actions, Jenkins)?
- What is the branch strategy?
- What quality gates are required before merge?
- What artifact repositories are used (ECR, CodeArtifact, S3)?
Follow stage-protocol.md question flow.
-
Collect and Analyze Answers -- Validate CI choices against existing infrastructure and team capabilities.
-
Generate Artifacts -- Create CI pipeline configuration (buildspec.yml, workflow YAML, or equivalent), quality gate definitions, and artifact repository configuration.
-
Phase Boundary Verification -- Run Construction-to-Operation verification check:
- Architecture-to-code-to-tests alignment
- All code traces to design
- Test coverage against acceptance criteria
-
Write results to
<record>/verification/phase-check-construction.md -
Prepare Completion -- Verify the CI and boundary artifacts. Do not edit stage or phase state; the reported gate outcome owns the transition.
-
Completion -- Present completion message and approval gate.
Outputs
| Artifact | Description |
|---|---|
| ci-config.md | CI pipeline configuration (buildspec, workflow YAML, etc.) |
| quality-gates.md | Quality gate definitions for merge/promotion |
| ci-pipeline-questions.md | Clarifying questions with answers |
Approval Gate
Strictly 2-option: Approve / Request Changes.
Notes
- Phase boundary verification: This is the last stage of the Construction
phase. It performs the Construction-to-Operation phase boundary verification
check (per stage-protocol-governance.md section 13), validating that architecture traces
to code and code traces to tests. Results are written to
<record>/verification/phase-check-construction.md. - Conditional execution: This stage is skipped if the project already has an adequate CI pipeline. The execution plan from Delivery Planning determines whether it runs.
- Post-unit execution: Like Stage 3.6, this stage runs once after all per-unit work is complete, not per-unit.
Phase Summary
The Construction phase transforms Inception designs into working software through a phased construction flow:
Per-unit stages (3.1-3.5): - 3.1 Functional Design -- Business logic, domain models, rules (architect-led) - 3.2 NFR Requirements -- Performance, security, scalability, reliability, observability, tech stack (architect-led) - 3.3 NFR Design -- Concrete patterns for NFR categories (architect-led) - 3.4 Infrastructure Design -- Deployment, services, monitoring, CI/CD (aws-platform-led) - 3.5 Code Generation -- Two-part planning + generation via subagent (developer-led)
Post-unit stages (3.6-3.7): - 3.6 Build and Test -- Instruction generation + actual Bash execution with failure diagnosis (quality-led) - 3.7 CI Pipeline -- CI configuration + phase boundary verification (pipeline-deploy-led)
Key characteristics: - Stages 3.1-3.4 are CONDITIONAL; 3.5-3.6 ALWAYS execute; 3.7 is CONDITIONAL - All conditional stages follow the execution plan from Delivery Planning - New source-producing solo Unit workflows default to unit-major, serial execution and verified Unit checkpoints. Preserve explicit iteration choices and the existing legacy, design-only, no-Unit, and team-owned paths. - NFR artifacts use expanded granularity (6 files for requirements, 6 for design) compared to the upstream reference - Infrastructure Design is expanded to 5 artifacts with dedicated monitoring and CI/CD files - Code generation uses the aidlc-developer-agent subagent with context budget controls - Build and Test performs actual command execution and automated failure diagnosis - CI Pipeline includes phase boundary verification before transitioning to Operation
Deliberate deviations from upstream reference: - NFR Requirements: 6 files (expanded from 2 in reference) - NFR Design: 6 files including logical-components.md (expanded from 2 in reference) - Infrastructure Design: 3 files — a consolidated infrastructure-specification.md (deployment + services + shared) plus dedicated monitoring-design.md and cicd-pipeline.md - Plan/question file co-location with stage artifacts