AI AgentsAI Agent Execution & Lifecycle

How do AI agents edit, validate, and record changes?

Question 269 of 280 · Updated

On this page

After an AI agent has inspected a workspace, its next responsibility is to make a controlled change and prove what happened. A reliable agent does not simply overwrite a file and announce success. It translates the request into a bounded change, edits the smallest appropriate surface, validates the result, reviews the complete diff, and records the change in a recoverable form.

This lesson focuses on the edit-to-evidence workflow. It is distinct from workspace inspection (which discovers project context) and from a validated agent loop (which defines goal completion and stop conditions). Here, the concern is how concrete modifications are applied, checked, and preserved.

1. The change lifecycle#

A production-grade agent should use an explicit sequence:

  1. Define the change contract. Identify the requested behavior, files that may change, acceptance criteria, prohibited changes, and whether commit/push/deploy is authorized.
  2. Capture the baseline. Record the starting branch or revision, working-tree status, and relevant test results. Existing user changes must be preserved and kept separate from agent changes.
  3. Prepare a minimal patch. Prefer targeted edits or a patch with explicit context over broad rewrites. Avoid unrelated formatting, dependency upgrades, or generated-file churn.
  4. Apply the patch safely. Check the expected file version or surrounding text before writing. Use atomic write/replace where possible; detect conflicts rather than silently overwriting concurrent changes.
  5. Validate in layers. Check syntax/formatting, focused unit tests, relevant integration tests, and broader regression checks in proportion to risk.
  6. Review the resulting diff. Inspect all changed, added, deleted, renamed, and untracked files. Confirm that the patch matches the requested scope and contains no secrets or accidental data.
  7. Record the result. Save a structured execution record and, only when authorized, create a version-control commit. Report evidence, failures, and remaining uncertainty.

The key is to keep editing, validation, and recording as separate checkpoints. A successful write is not proof of correctness; a passing test is not proof that the diff is in scope; and a local diff is not a durable record until it is preserved.

2. Define acceptance criteria before editing#

Convert a natural-language request into observable conditions. For example, “increase the retry timeout for the payment client” is too vague on its own.

A more actionable contract might be:

  • Change the payment client's retry timeout from 3 seconds to 5 seconds.
  • Do not change retry count, backoff strategy, or other clients.
  • Update the relevant unit test and configuration documentation if needed.
  • Run payment-client tests and the service regression suite.
  • Preserve pre-existing user modifications.
  • Do not commit or push unless the user explicitly asks.

This prevents the agent from interpreting a narrow task as permission to refactor adjacent code.

3. Baseline and patch isolation#

Before editing, capture a baseline such as:

  • Current branch and commit identifier.
  • Modified, staged, and untracked files.
  • Relevant test status before the change.
  • The exact target file contents or a content hash/version where available.

If the working tree already contains changes, the agent should not assume they belong to it. It should either work in an isolated worktree/branch or track its own patch separately. When a target file changes after inspection, the agent should re-read it and rebase/recompute the patch instead of applying stale offsets blindly.

A useful rule is: never overwrite a file version the agent did not inspect or explicitly reconcile.

4. Beginner-friendly numerical example#

Suppose a service has a payment client with a 3-second timeout. The task is to increase it to 5 seconds without changing retry behavior.

The agent inspects the baseline and finds 4 relevant files. The repository already has 2 unrelated modified files belonging to a developer.

It then:

  • Changes 1 configuration value in the payment client.
  • Updates 2 assertions in the focused test.
  • Leaves the 2 pre-existing modified files untouched.
  • Runs 18 focused tests: 18 pass.
  • Runs 120 service regression tests: 118 pass and 2 fail.

The two failures are then compared with the baseline. If those same tests failed before the edit, they are pre-existing failures; if they are new, the patch is not yet validated. Assume the baseline run showed all 120 passing, so the two new failures are regressions.

The agent investigates and discovers that a test expected a timeout of 3 seconds from a shared default, while the implementation changed that shared default instead of the payment-specific setting. It narrows the change to the payment client, restores the shared default, and reruns the suite:

  • Focused tests: 18/18 pass.
  • Regression suite: 120/120 pass.
  • Diff: 2 files changed, 4 insertions, 2 deletions.
  • Pre-existing unrelated changes: still present and unchanged.

The result is stronger than “the agent edited the timeout.” It demonstrates the intended value changed, unrelated behavior was preserved, and the regression suite passed after the correction.

5. Validation should be layered and risk-based#

Different checks catch different classes of mistakes:

  • Patch integrity: the intended lines changed; no unexpected file was overwritten.
  • Syntax and formatting: code parses and conforms to repository conventions.
  • Static checks: type checking, linting, schema validation, and security rules.
  • Focused tests: directly exercise the modified function or component.
  • Integration tests: verify interactions with dependent services, databases, queues, or tools.
  • Regression tests: detect unintended changes elsewhere.
  • Behavioral checks: verify the acceptance criteria using realistic inputs and outputs.

Do not treat every test command as equally meaningful. A successful formatter does not validate runtime behavior. A unit test that mocks away the changed dependency may not validate the integration. The agent should state exactly which checks ran, which were skipped, and why.

When a test fails, compare against the captured baseline. Classify it as a new regression, a pre-existing failure, an environmental failure, or an inconclusive result. Never relabel a new failure as “unrelated” without evidence.

6. Review the diff before recording#

A diff is the most direct evidence of what the agent changed. Review it for:

  • Scope: only files required by the task changed.
  • Correctness: the code implements the intended behavior.
  • Completeness: tests, configuration, and documentation are updated where needed.
  • Safety: no credentials, private data, debug dumps, or unintended generated artifacts.
  • Compatibility: public interfaces, persisted formats, and consumers remain compatible.
  • Hygiene: no temporary files, accidental deletions, or unrelated formatting churn.

The review must include untracked files as well as tracked changes. A summary that only counts tracked modifications can miss a newly created script or secret file.

OpenAI's Codex workflow explicitly recommends reviewing changes and test results before using the work. Its code-review guidance distinguishes staged, unstaged, untracked, and branch-level changes. Visual Studio Code's agent review guidance similarly recommends comparing diffs and inspecting changed files. These practices make the patch inspectable rather than relying only on an agent-authored summary.

7. Record changes with provenance#

A useful execution record should capture:

  • Task/run identifier and agent identity.
  • Repository/workspace identifier and starting revision.
  • Requested change contract and acceptance criteria.
  • Files changed and a patch/diff reference.
  • Commands and test suites executed, with exit codes and concise results.
  • Baseline failures versus new failures.
  • Validation timestamp and runtime/environment version.
  • Approval events for sensitive actions.
  • Final disposition: validated, partially validated, blocked, or rolled back.
  • Commit identifier if a commit was explicitly created.

For auditability, store a durable patch or commit reference rather than only a prose summary. In a multi-agent system, use an append-only execution log or immutable event records so a later agent can reconstruct who changed what and which validation evidence applied to that exact revision.

Do not store secrets or entire environment dumps in the record. Store safe metadata and references to protected logs.

8. Commit, push, and deploy are different permissions#

Recording a change locally does not automatically authorize a commit, push, pull-request merge, or deployment.

  • Local patch: changes exist in the working tree and can be reviewed or reverted.
  • Commit: creates a version-control checkpoint with an author, message, and revision identifier.
  • Push: publishes commits to a remote repository.
  • Merge: integrates the change into a target branch.
  • Deploy: changes a running environment and may affect users or data.

The agent should ask for or rely on explicit authorization at each consequential boundary. A task that says “fix this bug” normally authorizes preparing a patch and validating it, not silently deploying to production. Some teams may pre-authorize commits on isolated task branches; the policy should be explicit and auditable.

9. Failure scenarios and prevention#

Partial or interrupted write. A process crashes halfway through writing a file. Use atomic writes or patch application, then verify file integrity and compare the resulting diff. If the write is incomplete, restore from the captured baseline or reapply the patch.

Stale edit context. Another developer changes the file after the agent reads it. Check the file version/hash or surrounding context immediately before applying the patch. If it changed, re-read and reconcile instead of forcing the old patch.

Tests pass for the wrong reason. The agent edits the test to match a broken implementation, or a mock bypasses the changed behavior. Keep acceptance criteria independent from implementation and include at least one test that exercises the real boundary.

Unrelated changes get committed. The working tree contains a developer's earlier edits. Isolate the agent's work in a dedicated branch/worktree or stage only reviewed paths and hunks. Verify the staged diff before committing.

Validation evidence is stale. The agent runs tests, edits one more line, then reports the old passing result. Associate test evidence with the exact patch revision or content hash; rerun relevant checks after any subsequent change.

Commit succeeds but audit record is missing. Persist the execution metadata and commit identifier as one coordinated workflow where possible. If the record write fails, mark the run incomplete and repair the record before declaring the task fully recorded.

Sensitive information enters the diff or logs. Scan changed files and output for tokens, keys, personal data, and production dumps. Redact logs and block the patch if sensitive material is found.

10. Engineering trade-offs#

  • Small patches versus broad refactoring: small patches are easier to review and roll back, but sometimes a cross-cutting change is genuinely required. Expand scope only when dependencies or tests demonstrate the need.
  • Fast focused tests versus comprehensive suites: focused tests shorten feedback cycles; full suites improve confidence but cost more. Run cheap checks first, then broaden based on impact and risk.
  • Atomic writes versus streaming edits: atomic replacement prevents partial files but can be awkward for large artifacts. For large files, use transactional patching or temporary-file replacement and verify the final checksum.
  • Commit every task versus leave a reviewable patch: commits provide durable provenance; uncommitted patches allow the user to inspect and choose. Follow repository policy and user authorization.
  • Parallel validation versus deterministic evidence: independent tests can run concurrently, but shared databases, ports, or mutable fixtures can cause interference. Isolate test resources and record each command's result.
  • Automatic rollback versus human decision: rollback is appropriate for clearly failed, isolated changes; complex migrations or shared state may require a recovery plan and human approval.

11. A practical edit-and-record algorithm#

apply_change(task, workspace):
    contract = define_acceptance_criteria(task)
    baseline = capture_revision_status_and_test_baseline(workspace)
    assert target_files_are_within_allowed_scope(contract)

    patch = prepare_minimal_patch(contract, baseline)
    verify_patch_context_is_still_current(patch)
    apply_patch_atomically(patch)

    checks = run_layered_validation(patch, contract)
    diff = inspect_all_tracked_and_untracked_changes()

    if diff_exceeds_scope or checks_reveal_new_regression:
        repair_or_rollback()
        rerun_affected_checks()

    record_execution_evidence(
        baseline, patch, diff, checks, approvals
    )

    if commit_is_explicitly_authorized:
        commit_reviewed_changes_only()
        record_commit_identifier()

    return evidence_based_status()

A task should be marked validated only when the required acceptance checks pass against the final patch. If a required test cannot run, report partially validated or blocked, not success.

Key takeaway#

AI agents should edit through minimal, conflict-aware patches; validate with layered tests against a known baseline; inspect the complete diff; and preserve provenance in a structured execution record. Commit, push, merge, and deploy remain separate authorization boundaries. The trustworthy outcome is not merely changed code—it is a reviewable patch backed by fresh evidence and a recoverable record.

References

  1. 1.
    Using Codex Cloudhelp.openai.com
  2. 2.
    Code reviewlearn.chatgpt.com
  3. 3.
  4. 4.
  5. 5.
  6. 6.
    Review and revert agent changescode.visualstudio.com

Related questions

Explore other topics:Large Language ModelsRetrieval-Augmented GenerationMLOps