بازگشت به مهندسی مدرن و کار با هوش مصنوعی · فصل ۲ — شکستن کار و چرخهی کنترلشدهی AI · 13
A controlled AI coding loop — from request to accept or reject
Run an AI-assisted code change through a controlled request-context-plan-change-evidence-human-decision loop. AI Work Record تولید میکند که request، context، candidate change، evidence و decision را نگه میدارد.
چرخهی کنترلشدهی کار با AI — از درخواست تا پذیرش یا رد — fa-IR
Lesson summary
Run an AI-assisted code change through a controlled request-context-plan-change-evidence-human-decision loop.
AI Work Record تولید میکند که request، context، candidate change، evidence و decision را نگه میدارد.
This lesson produces
AI Work Record تولید میکند که request، context، candidate change، evidence و decision را نگه میدارد.
Who it is for
Foundation
Shared task-list filter case + visible artifact structure + concept-guided worked example.
Repair
Use exact B02 confusion/failure contract for the fragile concept.
Experienced
Less explanation; harder dependency/ambiguity/change/evidence case with fewer hints.
Prerequisites
A generated change is not enough; you must be able to control and judge it
An approved vertical slice for the unfinished-task filter is ready. If you only tell an agent “implement the filter” and later see changed files and green tests, you still do not know whether the agent expanded scope, invented a requirement, performed unrelated refactoring, or produced enough evidence for acceptance.
In this lesson you build AI Work Record v1 and move one work unit through five stations:
AI task contract → Context and plan gate → Bounded execution → Evidence bundle and diff review → Human accept/reject and record
The output is not a chat log. It is a reviewable record that keeps goal, context, constraints, plan, change surface, evidence, deviations, and the human decision connected.
This lesson does not teach deep reading of an unfamiliar repository; that belongs to FND-004. Here we assume the context needed for the bounded work unit can be gathered and focus on controlling the run.
Estimated active time: 65 minutes.
This lesson is for you if: you have a defined vertical slice and want to execute an AI-assisted code change without hidden scope expansion, self-certification, or automatic acceptance.
This lesson is not for: deep repository reading, delegating final acceptance to AI/CI, unrelated refactoring, or confusing environment permission with engineering scope.
Hard prerequisite — FND-002: you can reconstruct a bounded Vertical Slice Plan v1 without hidden decisions.
Short prerequisite probe
Read this packet:
- Spec: the user can switch between
AllandUnfinished. AC-01: Unfinished shows unfinished tasks only.AC-02: returning to All restores the normal view.- Constraint: schema and status semantics do not change.
- Work unit:
WU-01 — Vertical Slice - Outcome: observable end-to-end
All ↔ Unfinishedbehavior. - Evidence: mixed-status, return-to-All, all-completed.
- Rollback boundary: the selection/filter path only.
- Next unit: verification support for constraint/regression.
In a few lines explain why WU-01 is a smallest useful vertical slice, what dependency/evidence it needs, and where the rollback boundary sits.
PASS: reconstruct outcome, criterion, evidence, and rollback without adding a requirement.
If this packet is not clear, repair only the fragile FND-002 skill. An AI run must not hide decomposition ambiguity.
Choose the amount of support you need
Every route produces the same AI Work Record v1, completes the same lab, and meets the same evidence bar.
Five-concept route probe
- What must an
AI task contractexpose before a run? - What does the Context and plan gate stop before editing?
- Why is sandbox/permission not the same as a change boundary?
- What must an evidence bundle contain beyond “tests are green”?
- Why does final acceptance remain human even with green CI?
5/5 → Fast Path; 3–4/5 → targeted repair; 0–2/5 → foundation route.
- Foundation: task-filter example + visible record template + guided lab.
- Repair: only the misconception for the fragile concept.
- Experienced/Fast Path: go directly to the independent case with deviations and false-green evidence; the acceptance bar does not change.
Mental model: AI Work Record is a chain of control
A request alone is insufficient. Every stage must establish something for the next stage:
- AI task contract — bounds goal, context, constraints, and done/evidence.
- Context and plan gate — before editing, the agent inspects necessary context, records uncertainty, and proposes a plan for review.
- Bounded execution and change boundary — only the approved plan is executed; actual diff is compared with scope and deviations are recorded.
- Evidence bundle and diff review — diff, test/build output, and behavioral observations are linked to criteria/constraints.
- Human accept/reject and record — a human records
ACCEPT / MODIFY / REJECTwith rationale, residual uncertainty, and next action.
Key distinction: permission says what the environment technically allows the agent to do; the change boundary says what this task authorizes as part of the solution.
The five foundation concepts
1. AI task contract
A short but complete start packet: goal, relevant context, constraints, non-goals, allowed change surface, and done/evidence. A good contract is not necessarily long; it is low-ambiguity and scope-aware.
2. Context and plan gate
For the complex or ambiguous task in this lesson, editing stops before inspection and plan review. The agent may inspect relevant files and behavior, report uncertainty, and propose a plan; a human approves or revises it.
Boundary with FND-001-P04: that lesson teaches the plan-review and plan-revision skill itself. FND-003 uses that upstream skill inside an end-to-end coding run as the plan gate: inspect the required context, review the plan against the spec, record a human APPROVE or REVISE, and only then begin bounded execution. This lesson does not replace or re-teach FND-001-P04.
3. Bounded execution and change boundary
After plan approval, run in a reversible branch/worktree or equivalent environment. Compare every actual file/behavior change with the approved plan and boundary. Unrelated refactoring or cleanup is explained and, when out of scope, reverted.
4. Evidence bundle and diff review
Code output is not evidence by itself. Evidence covers behavior and boundary/regression risk: relevant tests, build/check outputs, diff review, behavioral observations, and trace from criteria/constraints to evidence.
5. Human accept/reject and record
AI or CI may produce signals, but final acceptance in this lesson is human-owned. The record includes spec/version, evidence, remaining risk or uncertainty, verdict, and next action.
Fill in AI Work Record v1
The record has seven sections:
A. Record identity
- Work Record ID
- Spec/Slice ID and version
- repository/worktree identity
- reviewer/decision owner
B. AI task contract
- bounded goal
- relevant context
- constraints
- non-goals
- allowed change surface
- required done/evidence
C. Context and plan gate
- inspected context
- uncertainties/assumptions
- proposed plan
- expected files/behaviors touched
- human plan decision:
APPROVE / REVISE
D. Bounded execution
- commands/actions actually run
- files/behaviors actually changed
- deviations from approved plan
- deviation disposition: explained / reverted / re-approved
E. Evidence bundle
- criterion/constraint
- evidence type
- exact evidence/result
- source/command/observation
- gap or unresolved item
F. Diff review
- expected vs actual change surface
- unrelated-edit check
- regression-risk review
- rollback readiness
G. Human decision record
ACCEPT / MODIFY / REJECT- rationale
- residual uncertainty/risk
- next action
AI may propose plans, code/test candidates, or evidence gaps. It does not define hidden requirements, become the evidence oracle, or own final acceptance.
Worked case: the unfinished-task filter
Task contract
- Goal: execute
WU-01forAll ↔ Unfinished. - Constraint: schema/status semantics do not change.
- Non-goal: persistence, redesign, unrelated cleanup.
- Done: AC-01 and AC-02 + preservation checks + diff review.
Context/plan gate
After inspection the agent proposes a small migration to simplify state. That proposal conflicts with the constraint.
Human plan decision: REVISE
The plan is narrowed to the view-selection/filter path and tests for that behavior; migration is removed.
Bounded execution
The agent makes the change in a local worktree. Actual diff touches only files related to filter behavior and tests. If an unrelated rename appears, it is reverted before progression.
Evidence bundle
- AC-01 → mixed-status test/observation.
- AC-02 → return-to-All test/observation.
- Constraint → schema diff inspection.
- Regression risk → existing list behavior + all-completed + empty-state.
- Boundary → actual diff compared with approved change surface.
Human decision
If all required evidence exists and the diff is bounded: ACCEPT. If a criterion/evidence item is missing: MODIFY. If scope is violated or a critical criterion fails: REJECT.
The reason and remaining uncertainty stay in the record; “AI says done” is not acceptance evidence.
Five common failure modes
Failure 1: ambiguous prompt
“Implement it however you think best.” Repair: bound goal, constraints, non-goals, and done/evidence before the run.
Failure 2: decorative plan
The agent emits a plan but starts editing before review. Repair: for this lesson's task, the plan gate must actually stop progression.
Failure 3: permission treated as scope
Because the agent has write access, it performs a broad rename. Repair: record the allowed change surface independently of sandbox permission.
Failure 4: false green
Existing tests are green while the diff deletes an unrelated file or a critical criterion was never tested. Repair: combine test signal, diff review, and criterion/evidence mapping.
Failure 5: self-certification
The agent says “everything is correct” and closes the record as ACCEPT. Repair: the AI report is an input; final verdict and rationale are human-owned.
Experienced bridge: deviations and evidence that is green but insufficient
In real runs, plan and actual work are not always identical. The goal is not zero deviation; the goal is no hidden deviation.
Suppose the plan predicts two files, but a config file also appears necessary for the build. Three outcomes are possible:
- the deviation is outside scope → revert it;
- it is necessary and still inside the goal → explain/re-approve it before acceptance;
- uncertainty remains → stop and revise the plan.
Likewise, a green suite may be insufficient. If it does not check no-schema-change or a failure path, an evidence gap remains. Fast Path records more precisely; it does not remove gates.
Options and trade-offs
- Direct edit for a tiny, fully clear task: faster, but this lesson keeps a plan gate for its bounded complex task.
- Plan-first: slightly more startup cost, but hidden assumptions and scope drift surface earlier.
- Broad context: may reveal more dependencies but increases noise and unnecessary access.
- Minimal context: improves focus but can omit evidence needed for a correct plan.
- AI-generated tests: useful candidate coverage, but tests from the same agent are not the sole oracle.
- CI: an important signal, but not complete domain/scope acceptance.
Tools differ. The invariant is vendor-neutral: clear contract, reviewed plan, bounded execution, independent evidence, and human decision.
Guided practice and independent execution
Guided case — Order search
Approved slice:
- exact order-number search
- no fuzzy/customer-name search
- order schema unchanged
- existing list preserved
- AC-01 exact match
- AC-02 clear no-match
- AC-03 list regression-free
Write an AI Work Record v1: task contract, context to inspect, plan-gate criteria, allowed change surface, evidence bundle, and human-decision conditions. Then diagnose a bad plan that also adds customer-name search and repair only that scope violation.
Programming Run & Read Bridge — use it if basic syntax is still unfamiliar
This section is skippable. If you can explain the fixture below without help, run its test command, read the failure, and identify which branch owns the behavior, go directly to LAB-01. Otherwise use the actual lab fixture as the bridge; you do not need a separate language course or a separate project.
1) See values, names, and basic kinds in the real fixture
The tests contain data like this:
TASKS = [
{"id": 1, "title": "A", "completed": False},
{"id": 2, "title": "B", "completed": True},
{"id": 3, "title": "C", "completed": False},
]
1 and 3 are numbers, "A" is a string, and False/True are boolean values. The name TASKS is bound to a list. Each list item is a record/dict whose fields are reached through keys such as "id" and "completed". In task["completed"], the name task refers to one record during that iteration.
For this bridge, the useful model is simply name → value. A list holds ordered values; a record groups named fields. You do not need an advanced memory model yet.
Conversion is not validation. Conversion deliberately changes a representation; for example, int("2") attempts to turn a numeric string into a number. Validation asks whether the current value already satisfies the expected shape or constraint. int("two") also shows that not every value can be converted. This lab does not require conversion; keep the two claims separate from the beginning.
2) Function, parameter, local name, and return
The real lab starter is:
def filter_tasks(tasks, mode="all"):
if mode == "all":
return list(tasks)
if mode == "unfinished":
# starter defect
return list(tasks)
raise ValueError("unsupported mode")
filter_tasksis a function: callable behavior.tasksandmodeare parameters: inputs that receive values for a call.mode="all"supplies a default when the caller does not pass the second argument.returnsends a result back to the caller and ends that call.- A name created inside the function, such as
result = [], is a local name for that computation.
A call can look like:
visible = filter_tasks(TASKS, "unfinished")
Here visible is bound to the returned value. The function works through its parameters and returns another value.
3) Comparison, if, and one simple iteration/filter pattern
if mode == "unfinished": evaluates a comparison. The comparison produces a boolean, and if executes its branch only when the condition is true.
Do not memorize a repair; understand the flow. An explicit filtering pattern can look like:
result = []
for task in tasks:
if task["completed"] is False:
result.append(task)
return result
for visits list items one at a time. if selects unfinished records. append keeps the selected record. return sends the new list back. More compact syntax can express the same idea later; the bridge needs the visible flow: iterate → compare → keep/reject → return.
4) Import means reusing a name defined in another module/file
The real test contains:
from src.filtering import filter_tasks
The test does not redefine the function; it imports the name from src/filtering.py. At this stage, that is enough of an import model: make a name from another module available in this file. Package-resolution details belong to later tooling/environment lessons.
5) Do not confuse a source file, a data file, and an in-memory value
src/filtering.pyis a source file: code text you edit.- A JSON fixture or a constant such as
TASKSrepresents sample data. - During execution, Python constructs objects/values in memory. The
tasksparameter is a runtime value, not the file itself.
After editing source, rerun the program/tests to observe new behavior. A saved edit is not evidence of behavior by itself.
6) Learn only the minimum command/run cycle
From lab/LAB-01/learner/fixture, run:
python -m unittest discover -s tests -v
If your environment uses a different Python executable name, use that interpreter; memorizing an executable spelling is not the skill. Locate three things:
- the working directory from which the command was run;
- which test reports
ok,FAIL, orERROR; - the first useful message that exposes expected-versus-actual behavior or the failing location.
Use this loop:
edit → run → observe → diagnose → repair → rerun
Never replace the final rerun with “it looks fixed.”
7) Distinguish four beginner failure families
This classification is sufficient here:
- syntax/parse failure: the interpreter cannot read the code structure, often before behavioral tests run;
- import/setup failure: the test cannot reach a module/path/dependency, so you have not yet measured function behavior;
- runtime error: execution starts but raises an exception;
- assertion/test failure: execution completed far enough to compare an observed value with an expected value, and they differ.
Each family suggests a different repair. A PASS means only that the oracles executed in that run did not object; it is not proof of broad mastery or product correctness.
8) Read unittest as expected-versus-actual evidence
A real test expects:
result = filter_tasks(TASKS, "unfinished")
self.assertEqual([t["id"] for t in result], [1, 3])
The right side, [1, 3], is this test's expected behavior. The left side comes from the actual function execution. The starter currently returns the full list for unfinished, so this oracle must expose a mismatch. Do not memorize the error text. Learn the chain:
test → expected → actual → responsible branch → bounded edit → rerun.
Micro-readiness check — before entering LAB-01
Without copying a prepared answer:
- explain the roles of
tasks,mode, andresult/visiblein one sentence each; - predict what
completed is Falsedoes for{"id": 2, "completed": True}; - explain why
src/filtering.pyis source while the function's input value is not the file itself; - run the tests and locate the first useful failure;
- before editing, state which branch is the smallest change surface for
unfinishedand which tests must be rerun afterward.
If you can do all five, the bridge is closed; enter LAB-01. If not, reread only the uncertain item and repeat the probe. The LAB-01 evidence bar is unchanged: this bridge closes a hidden prerequisite; task contract, bounded execution, diff review, and human verdict still remain mandatory.
Independent execution — LAB-01
In the synthetic repository under labs/LAB-01/fixture/, execute the task-filter slice with an AI coding assistant or by role-playing agent/human roles.
Requirements:
- record
AI Work Record v1and the plan gate before editing; - keep changes inside the local fixture;
- run the visible tests and record evidence;
- inspect the diff for unrelated edits;
- inspect no-schema-change separately;
- issue a human
ACCEPT / MODIFY / REJECTwith rationale, residual uncertainty, and next action; - never use AI output as the oracle or final decision.
If an AI tool is unavailable, run the same loop with a manual candidate change. The skill under test is workflow/evidence control, not a vendor brand.
When is the AI Work Record acceptable?
Before ACCEPT, verify:
- goal/context/constraints/done were extractable before the run;
- editing did not begin before plan review for this lesson's complex task;
- actual change surface was compared with approved plan/scope;
- deviations were explained, reverted, or re-approved;
- evidence covers behavior and boundary/regression risk;
- criteria/constraints map to specific evidence;
- diff was read for unrelated edits;
- AI report or CI alone did not become final acceptance;
- a human recorded verdict, rationale, residual uncertainty, and next action;
- the FND-004 boundary remains intact.
Machine checks are necessary but not sufficient.
Assessment and transfer
Assessment has five layers: retrieval, application/run, diagnosis, human decision, and transfer.
To pass blocking items:
- all five concepts are visible in the record;
- the task contract and plan gate are real, not decorative prose;
- change boundary stays distinct from permission;
- evidence includes diff plus behavior/constraint evidence;
- final verdict is human-owned and defensible;
- the same invariants survive in a new domain without copying filter-case wording.
Final evidence is AI Work Record v1 + LAB-01 run/evidence + the human decision record.
Technical references and current status
ISO/IEC/IEEE 29148:2018 remains the published Edition 2, while ISO currently marks it “to be revised.” Edition 3 remains a Draft International Standard under development and has not yet replaced the published 2018 edition.
Current OpenAI Codex guidance emphasizes useful context, repository guidance, running relevant tests/checks, and diff review before accepting work. GitHub Copilot task guidance emphasizes well-scoped tasks, acceptance criteria, research/planning before changes, and build/test/validation. Claude Code documents plan mode before editing and running/verifying tests.
These sources show that several current tools support similar context, planning, and verification practices. No vendor workflow is treated as universal engineering authority here. The five concepts and AI Work Record v1 come from this lesson's frozen authority.
Assessment
There is no answer key in this lesson pack; answer it yourself and mark honestly. "Needs review" sends the lesson to your review queue.
Q1 retrieval
Distinguish AI task contract, Context and plan gate, Bounded execution/change boundary, Evidence bundle/diff review, and Human accept/reject. For each, state what it controls and its protected confusion pair. Explicitly explain (a) why a good AI task contract is complete, low-ambiguity, and scope-aware rather than merely a long prompt, and (b) how this lesson uses the FND-001-P04 plan-review skill inside an end-to-end coding run instead of replacing or re-teaching that upstream skill.
Q2 application
Using LAB-01, complete one full run for WU-01 and submit AI Work Record v1. The record must contain the task contract, context/plan gate before editing, actual commands/files changed, deviation register, evidence for AC-01/AC-02/no-schema-change/regression, diff review, and a human ACCEPT/MODIFY/REJECT with rationale, residual uncertainty, and next action. Any edit outside the fixture or approved change boundary must be recorded and reverted/replanned.
Q3 diagnosis
Diagnose this run: the agent edited before plan review; because sandbox write was allowed it performed an unrelated rename; the test suite is green but no-schema-change and the failure path were not checked; finally the agent wrote verdict=ACCEPT itself. For each defect, name the violated concept and one bounded repair.
Q4 decision
The evidence packet says AC-01 and AC-02 pass and the build is green, but the diff contains a rename outside the approved plan and no no-schema-change inspection was performed. Choose ACCEPT/MODIFY/REJECT and record rationale, residual uncertainty, disposition of the rename, missing evidence, and next action. The decision must be human-owned.
Q5 transfer
Transfer — Avatar refresh. Use `assessment/transfer/Q5_AVATAR_REFRESH_PACKET.json` as the complete synthetic local context/candidate-run/evidence set. First, use only `spec_slice` and `context_inventory` to construct a bounded AI task contract and select the necessary context. Then review `plan_gate_input` against the spec and record a human `APPROVE` or `REVISE` decision with rationale. Next, compare the candidate run with your contract/plan and complete AI Work Record v1 with change-boundary review, evidence mapping, deviation handling, rollback readiness, and a human `ACCEPT/MODIFY/REJECT` verdict with rationale, residual uncertainty, and next action. Do not invent repository files, commands, tests, evidence, or results, and do not copy task-filter wording.
Assessment rubric
این projection فقط از expected_evidence موجود در assessment candidate ساخته شده است و معیار جدیدی اضافه نمیکند.
This projection is generated only from existing expected_evidence fields and adds no new criterion.
Q1 — retrieval
- Blocking: no
- FA: پنج تمایز bounded، شامل تفاوت اجباری prompt بلند با task contract کامل/کمابهام/scope-aware و نیز تفاوت plan review در FND-001-P04 با plan gate end-to-end این درس.
- EN: Five bounded concept distinctions, including the required long-prompt vs scope-aware task-contract distinction and the FND-001-P04 plan-review vs this lesson's end-to-end plan-gate distinction.
Q2 — application
- Blocking: yes
- FA: یک run record مستقل و قابل review که هر پنج مفهوم را عملی نشان دهد و acceptance را به evidence و تصمیم انسانی وصل کند.
- EN: An independently reviewable run record that operationalizes all five concepts and ties acceptance to evidence and human judgment.
Q3 — diagnosis
- Blocking: yes
- FA: plan-gate violation، permission/scope confusion، evidence insufficiency و human-acceptance violation دقیق تشخیص داده شوند.
- EN: Correct diagnosis of plan-gate violation, permission/scope confusion, insufficient evidence, and human-acceptance violation.
Q4 — decision
- Blocking: yes
- FA: بدون evidence کامل و با scope deviation حلنشده ACCEPT بدون شرط مجاز نیست؛ پاسخ باید disposition و next action روشن داشته باشد.
- EN: Unconditional ACCEPT is not valid with missing evidence and an unresolved scope deviation; the response includes clear disposition and next action.
Q5 — transfer
- Blocking: yes
- FA: یک transfer record فقط بر پایه packet supplied که شامل task contract ساختهشده توسط learner، تصمیم انسانی plan gate، تطبیق invariantهای workflow با domain آواتار، disposition صریح deviation خارج از boundary، evidence trace، rollback readiness و final judgment انسانی باشد.
- EN: A transfer record grounded only in the supplied packet, including a learner-constructed task contract, a human plan-gate decision, adaptation of the workflow invariants to the avatar domain, explicit disposition of the out-of-boundary deviation, evidence trace, rollback readiness, and human final judgment.
References & freshness
Case studies
Lab files
Use only this local synthetic fixture. The lab ships with its own read-only baseline snapshot and deterministic state tool; no Git setup or external repository metadata is required.
Goal
Implement the approved vertical slice that makes filter_tasks(..., mode="unfinished") return only unfinished tasks while preserving mode="all".
Supplied reversible state
- Working fixture:
fixture/ - Read-only baseline snapshot:
baseline/fixture/ - Baseline hashes/policy:
BASELINE_MANIFEST.json - State tool:
tools/lab_state.py
Before editing, run from this LAB-01 directory:
python tools/lab_state.py verify-baseline
The command must return PASS. python tools/lab_state.py diff compares the working fixture with the supplied baseline and reports every added/deleted/modified file plus unified text diffs. python tools/lab_state.py rollback-check proves what would be restored. If you need to revert, python tools/lab_state.py rollback restores the entire fixture to the supplied baseline.
Do not edit baseline/, BASELINE_MANIFEST.json, tools/lab_state.py, or fixture/tests/test_filtering.py.
Required workflow
- Create
AI Work Record v1before editing. - Inspect the fixture and propose a plan.
- Record human
APPROVEorREVISE. - Make only bounded changes needed for the slice. The implementation change surface is
src/filtering.py;tests/test_filtering.pyis a read-only oracle and must not be edited. - Run:
python -S -B -m unittest discover -s tests -vfromfixture/. - Return to
LAB-01/and runpython tools/lab_state.py diff; compare the reported change surface with the approved plan/scope and confirm no data/schema format was changed. - Run
python tools/lab_state.py rollback-checkand record rollback readiness. If a scope deviation must be reverted, use the supplied rollback command and re-run the evidence steps. - Record evidence for AC-01, AC-02, preservation/regression, change-boundary integrity, and the no-schema-change constraint.
- Issue a human
ACCEPT / MODIFY / REJECTwith rationale, residual uncertainty, and next action.
No solution/reference diff is included. Do not add network calls, credentials, privileged operations, or production dependencies.