
Summary
Key points of this document
- What we want to reduce is human round trips, not judgment responsibility.
- Do not create long-running loops; use CI completion events as the next clock.
- Upon receiving an event, narrowly validate the target PR.
Overview
Every time CI fails, the round trip of developers reading logs, committing fixes, and waiting for re-execution takes time. However, granting unlimited modification rights to AI creates other problems: conflicts with parallel work, dangerous file changes, cost overruns, and infinite loops. This article organizes a design that attempts only one small fix per failure event, without making AI the authority for judgment.
What we want to reduce is human round trips, not judgment responsibility.
Responding to CI failures is an iterative process: finding the failed job and step, narrowing down potential causes from logs, fixing related source code, and waiting for the same validation. Even for failures where the cause and scope of correction can be limited, such as type errors or small implementation omissions, this round trip interrupts the developer's work.
On the other hand, AI being able to read failure logs and being able to push safely are separate issues. Strings that look like commands can be embedded in logs and source code. A PR's head can change during analysis, duplicate events can be delivered, and multiple jobs can contend for the same budget or branch. If corrections are made solely based on model responses, the problems of authority and contention cannot be solved.
The design goal is not to make AI the authority for CI results or branch status. A trusted control plane determines the target, state, cost, diff, and pushability, while AI is only responsible for cause classification and patch candidate generation within those boundaries. Safely stopping when automation is not possible and providing necessary evidence to humans is as important as successful repair.
- Targets for automation: CI failures where the cause is localized and can be fixed with small changes to a few existing files.
- Human responsibilities: Change boundaries, budget, permissions, quality gates, exception handling, operations after merge.
- Safe default: If there is insufficient information for judgment, do not fix; stop as needs_human or control system failure.
Do not create long-running loops; use CI completion events as the next clock.
The entry point is GitHub Actions workflow completion events. A trusted orchestrator matches events with live APIs and asynchronously launches a repair job in the cloud only if the conclusion is failure or timed_out. "Cancelled" is not included because it may not be a code failure and could be due to human operation or concurrency control.
The repair job executes only one repair cycle per event. It finishes after log acquisition, cause determination, patch generation, validation, and push, and does not long-poll the subsequent CI. If the CI re-executed by the fix commit fails, that new completion event triggers the next cycle. This structure avoids holding jobs during wait times and clarifies event-based re-execution and auditing.
If the CI after the fix succeeds, the repair job is not launched; only a notification process to close the corresponding chain as green is performed. "Green" does not mean permission to merge. Automatic merge, release, and deployment remain separate responsibilities and go through normal review and branch protection.
- failure or timed_out → Target validation → Asynchronously launch one repair cycle.
- Push patch → End job → Normal CI validates the new commit.
- Re-failure → New completion event triggers the next cycle.
- success → repair is not launched, green is notified. cancelled → recorded as out of scope.
Upon receiving an event, narrowly validate the target PR.
Even if the event contains PR information, repair does not start based solely on its content. The target is limited to open PRs created from the same repository and directed towards an allowed base branch. PRs originating from forks, branches used for promotion or release, base branches outside the allowlist, or runs that cannot be uniquely mapped to a PR are excluded.
The orchestrator matches the workflow identifier and definitions on the default branch against an allowlist. This workflow itself does not check out PR code or execute scripts or actions within the PR. It separates the CI that executes untrusted code from the privileged control plane that receives failures, ensuring that arguments or permissions for cloud jobs do not change based on commands written in failure logs.
Fixed inputs passed to a cloud job are the PR number, the head SHA at the time of the event, and the workflow run ID. If distinguishing between workflow reruns, the run attempt is also fixed. If you determine the target by searching for the branch name or the latest run later, you might mistakenly analyze a different push or rerun. These fixed inputs are used as correlation keys for subsequent claims, log acquisition, attempts, commit trailers, and notifications.
- Allowed: Same repository, open PR, allowed base branch, trusted workflow.
- Rejected: Fork, promotion/release branches, cancelled, runs where PR cannot be identified, unauthorized workflow.
- Fixed inputs: PR number, head SHA at start, workflow run ID. Include run attempt if handling reruns.
Match fixed inputs with live status to read only accurate failure logs.
At job start, re-fetch the PR and workflow run from the GitHub API. Check if the PR is open, if the base is allowed, if the head repository is the same, if the current head SHA matches the fixed input, if the run corresponds to that SHA and PR, and if the conclusion is targeted. If any cannot be confirmed, stop without calling the model, with a status of stale or needs_human.
Failure logs are obtained from the job and step belonging to the fixed workflow run ID. We do not substitute by searching for "latest run of PR" or another workflow with the same name. For reruns, the attempt is also identified, ensuring that which run and which failure was analyzed can be traced from audit records.
Log body, source, diff, Issue/PR body, and model output are all untrusted data. Do not treat strings like "Ignore this constraint" in logs as instructions; pass them as data within structured delimiters. Redact secret-like values before sending to the model, and limit input size and target steps.
- Event values are activation requests, and the re-validation results of live PRs and runs are the authority.
- Obtain failed jobs/steps from fixed run ID and run attempt, do not mix logs from different executions.
- The content of logs, source, diff, and model output cannot extend permissions or change boundaries.
Control duplication and stopping with state machines and object generation conditions.
States are received, claimed, analyzing, patchready, validated, pushed, awaitingci-like progress states, and terminal states of green, needshuman, stale, budgetstopped, control_error. Each transition is checked against an allowlist to prevent duplicate side effects even if the same event is re-delivered or the job is retried.
If using Google Cloud Storage for state persistence, object generation and the ifGenerationMatch condition can be used as compare-and-swap. New claims are created with ifGenerationMatch=0, conditional on no live object existing. Extending leases or taking over expired claims updates only if the read generation has not changed. Attempt and pushed SHA are also confirmed with conditional updates to the same chain state, preventing older jobs from rolling back newer states.
Leases should have not only an owner but also a fencing token that changes with each takeover. Immediately before proceeding to external side effects such as model calls, artifact confirmation, or push requests, re-verify the current owner, token, expiration, and generation. It is an invariant that even if an old worker returns after expiration, it cannot update the new owner's state or request a push.
Costs update a single budget ledger, including daily and rolling period remaining amounts, with generation conditions. This avoids appearing to update multiple objects simultaneously; if concurrent requests contend on the same ledger generation, only one succeeds. If more complex cross-transaction is needed, choose a transaction-aware storage. Object generation is a conditional update of a single object and does not broadly interpret the scope of atomicity in design.
Issues and PR comments are audit views for humans to read the progress, not the source of truth for the state. The source of truth only retains the state, time, SHA, run ID, fingerprint, usage, and limited references and digests to artifacts. Secrets, log bodies, and patch bodies are not stored; necessary audit artifacts are separated into a different protected area with a short retention period.
- claim: unique per event. Duplicate deliveries read existing claims and converge to the same result.
- lease: has owner, expiration, and fencing token; takes over only if generation matches even after expiration. Reconfirms ownership immediately before external side effects.
- attempt: conditionally finalizes chain, attempt number, run ID, start SHA, and result.
- Source of truth: object state. Issues and comments are audit displays and are not used for processing decisions.
Determine deterministic fingerprint first and pre-reserve model costs.
First, create a deterministic failure fingerprint from the main error lines, excluding fluctuations specific to the workflow, failed job/step, exit code, and execution environment. Failures requiring changes to known environmental issues, insufficient permissions, external service failures, or protected areas are sent to 'needs_human' at this stage. Only if a deterministic classification does not yield a conclusion, proceed to model-based cause classification and patch generation.
Correction commits are tagged with trailers indicating the chain, attempt, and originating run. For example, using machine-readable keys like AI-Repair-Chain, AI-Repair-Attempt, AI-Repair-Run allows new CI failures to be associated with the same chain. However, since PRs can create trailers with the same name, trailers are limited to auditing and correlation assistance, and the source of truth for attempts and chains is placed in conditionally updated state objects. Stop after a maximum of three attempts; if the same fingerprint recurs after correction, it is moved to 'needs_human' as no progress, even if attempts remain.
Before calling an LLM, the maximum estimated cost of that call is accounted for as a reservation against both daily and rolling period limits. After completion, it is settled with actual usage, and the difference is returned. If the consistency of limit reading, reservation, and settlement cannot be confirmed, it fails-closed and stops, without assuming a remaining balance.
- Do not use LLMs for failures that can be classified by deterministic inspection.
- Maximum of three attempts. Repeated identical fingerprints are considered no progress and transferred to human intervention.
- Reserve the maximum amount before LLM call, settle with actual usage after completion.
- Do not initiate new calls in case of control system failures such as inability to read budget status, conflicts, or inability to settle.
Do not overwrite human intermediate changes with stale head check just before push.
Even if the head SHA matches at the start of analysis, a human or another automation can push during patch generation and validation. Therefore, immediately before pushing, re-fetch the PR and reconfirm that it is open, the base is allowed, the head repository is the same, and the remote head exactly matches the starting SHA.
If the remote head has changed, even if the generated patch seems applicable to the new code, do not rebase or regenerate; stop as stale. Wait for the CI results for the new head and start a separate cycle from that failure event. This prevents overwriting human fixes or other job corrections with old analysis results.
Only allow normal non-force pushes. Do not circumvent push rejections with force pushes; re-read the remote state and classify as stale, insufficient permissions, branch protection, or control system failure. After success, record the commit SHA that actually reached the remote in the state, and treat only the CI for that SHA as the next event in the chain.
- At start: Check PR open, allowed base, same repository, head SHA match.
- Just before push: Re-check same conditions and remote head.
- Mid-push: Discard patch, stop as stale, defer judgment to new CI event.
- On rejection: Do not force push, implicitly rebase, or push by re-validating.
Only allow existing files shown to the model as small diffs.
Before passing to the model, a small number of existing files related to candidate causes are deterministically selected. The model returns only their allowed paths as modification candidates, keeping within the total of added and deleted lines, and the maximum patch byte size. Creation, deletion, renaming, binary, symlink, submodule, file mode changes, force pushes, and changes that bypass validation are rejected.
Authentication, OAuth, cookies, CORS, secrets, database migrations, Terraform, GitHub Actions workflows, Cloud Build, lockfiles, package manifests, generated files, and production configurations are always handed over to humans, even if they appear to be local fixes. Changes to tests, snapshots, and coverage settings are also prohibited. This is to distinguish between weakening the failing inspection to make it green, and fixing product code to pass inspection.
Model output is received in limited formats such as unified diff, and first passed through git apply --check. After application, git diff --check, allowed paths, change types, added and deleted lines, byte counts, additional literals resembling credentials, and validation skip or assertion weakening are mechanically inspected. Finally, only validated paths are explicitly staged, and broad paths or 'all' specifications for git add are not used.
After static inspection of the patch, existing allowlisted validations corresponding to failed checks are executed. Any shell commands returned by the model are not executed; a trusted harness outside the repository determines the commands and timeouts. During validation, credentials for push, model, and state storage are not passed, and after completion, it is reconfirmed that the staged diff matches the inspected digest.
- Allowed: A small number of existing product code explicitly specified to the model, local changes within limits.
- Always rejected: Creation, deletion, renaming, binary, symlink, submodule, mode changes, force push, validation bypass.
- Always handed over: Authentication, OAuth, cookies, CORS, secrets, migration, Terraform, workflow, Cloud Build, production configuration.
- Always handed over: Changes to lockfiles, package manifests, generated files, tests, snapshots, coverage.
- Inspection: git apply --check, git diff --check, credentials, paths, change types, scale, explicit staging.
Separate permissions for event reception, cloud execution, and Git push.
The orchestrator on the GitHub Actions side only executes definitions on trusted default branches and does not check out PR code. Its role is limited to event validation, creation of fixed inputs, and asynchronous initiation of cloud jobs. The boundary is not evaluating actions, scripts, or configurations originating from PR code in a privileged context.
On the cloud side, identity is separated for event reception, remediation control, untrusted code validation, and push. The reception side only initiates jobs, the control side only has target state objects, necessary artifacts, and the model API, and validation workers only have short-lived read environments. While validation workers execute PR tools and tests, credentials for the model, state storage, and push are not passed, and outbound communication is limited to necessary destinations.
Push is separated to a trusted broker, and only after the broker reconfirms the digest of the inspected diff, the lease's fencing token, the live state of the PR, and the initial head SHA, is a normal push performed with short-lived GitHub App credentials. Even if configuration cannot be separated, at least credentials are removed during untrusted code execution and issued with limited repository and duration just before pushing. Long-term tokens are not left in the environment while tests are run.
Even with credentials that can write to Git, the scope of application does not rely solely on application-side inspections. On the GitHub side, branch protection, allowed branches, prohibition of force pushes, and separation of merge permissions are maintained. When application guards fail, external permission boundaries serve as the last line of defense.
- GitHub Actions: Does not execute PR code, passes only validated fixed inputs to the cloud.
- Reception identity: job launch only. Control identity: state, artifact, model API only. Verification identity: read-only. Push identity: short-lived write to target repository only.
- GitHub: Maintain short-lived credentials, non-force pushes, branch protection, and separation of merge permissions.
Notifications should be limited to states that require human judgment; intermediate attempts should be left for auditing.
Notifying all internal transitions will bury important reasons for stoppage. Notifications should be limited to when CI turns green after a fix, when it moves to needs_human, when it stops due to budget limits or inability to determine budget, or when control systems like claims, leases, APIs, or state updates fail. The start of intermediate attempts, fingerprints, model usage, and patch rejection reasons will be left in audit records.
Metrics to observe are: time from failure event to fix push, percentage of green on first fix, average attempts per chain, human handover rate, and cost per PR. These not only indicate how fast automation is, but also help determine what types of failures are resolved within boundaries, and if costs balance with human review burden.
Numerical values are not set as success rates before introduction. We use distributions obtained from observe and canary as a baseline, and read them separately for each workflow, language, and failure classification. Even if green, the possibility remains that tests are weak, permissions are too broad, or changes that should have been handed over were passed, so a single success rate is not treated as quality assurance.
- Notifications: green, needs_human, budget stop, control system failure.
- Audit: event, claim, lease, attempt, fingerprint, input digest, patch inspection, cost reservation and settlement.
- Metrics: time to fix push, green on first attempt, average attempts, human handover rate, cost per PR.
- Do not automatically merge, release, or deploy even after green.
Introduce incrementally in the order of off, observe, limited canary, repair.
Initially, start with 'off', preparing only the state object, permissions, budget limits, protected paths, and stop methods. In the next 'observe' phase, actual failure events are read, target determination, fingerprinting, model classification, and the expected patch and cost are recorded, but not applied or pushed to the working tree. This allows observation of misclassifications and rejection conditions beforehand.
In 'limited canary', further narrow down target workflows, base branches, repositories, failure classifications, and allowed paths, enabling repair only for small, human-verified scopes. After confirming the operation of stale stops, budget reservations, patch guards, notifications, and rollbacks in canary, expand the repair targets. Stages should be reversible with feature flags, and in case of control system failure, revert to 'observe' or 'off'.
Regression fixtures include: duplicate deliveries of the same delivery, re-acquisition after lease expiration, budget reservation conflicts by multiple jobs, human pushes during analysis, rejection of non-force pushes, protected path requests, prompt injection in logs, credential-like diffs, and stopping upon reaching three attempts. Not only success cases, but also 'doing nothing' and 'handing over to a human' are expected outcomes for tests.
- Off: Prepare boundaries and stopping mechanisms while stopping external side effects.
- Observe: Record target determination, classification, patch candidates, and costs, but do not apply.
- Limited canary: Narrow down workflows, branches, failure classifications, and paths, and verify up to non-force push.
- Repair: Expand scope based on observations, ensuring ability to revert to observe at any time.
The scope of automated repair is determined by impact, not ease of fixing.
Event-driven approaches can reduce waiting jobs and long polling, but require state design that spans multiple events. Without deduplication, time-limited leases, chain association, and success-time termination processing, simply splitting into short jobs will leave concurrency issues. For small CIs, it may be simpler for a human to fix it once than to operate a state infrastructure.
Strict patch boundaries increase safety but reduce failures that can be automatically repaired. Especially authentication, migration, infrastructure, workflow, dependency updates, and test changes, even if they appear to be local one-line fixes, can change system-wide contracts. The decision to hand over to a human should be based on impact on permissions, data, distribution channels, and quality standards, not on the smallness of the change.
Even high-performance models won't solve flaky tests, external service failures, hidden requirements, or weak tests. The prerequisites for automated repair are reproducible CI, logs that can identify failed steps, branch protection, explicit protected paths, and cost limits. If these are ambiguous, it's more effective to first use observation to classify failures and organize human judgment.
- Easy to apply: The cause is limited, it involves small diffs in existing product code, and it can be fixed without weakening existing verification.
- Should be transferred: Changes permissions, authentication, data structure, infrastructure, distribution, dependencies, and testing standards.
- Record the decision not to automate as an achievement, and use the reasons for rejection to improve the next boundary.
A safe AI repair loop is determined by its stop boundaries, not by the model.
When automatically repairing CI failures in a PR, the focus should not be on continuous AI execution. It's a structure that confines a single failure event to a single short cycle, correlates a fixed combination of PR, head SHA, and run with the live state, and waits for the post-fix CI as the next event.
Furthermore, we layer claims and leases through object generation, pre-reservation of costs, stopping after a maximum of three attempts and identical fingerprints, stale head checks just before push, and guards for protected paths and diff size. Instead of making it safe with just one check, the same erroneous operation is stopped at separate boundaries: events, state, cost, Git, and permissions.
The practical decision-making criteria to take away are not whether the AI can explain the failure, but whether it can create only authorized small diffs, stop doing anything if the state changes, and hand over evidence to a human if it cannot make a judgment. By starting incrementally within the scope that meets these conditions, we can reduce human back-and-forth while leaving the ultimate responsibility for judgment with humans and the normal development process.


