


Build an AI Code Review-and-Fix Tool Without Losing User Code
Use when an AI works on a tool that runs AI code reviews and fixes in the background. It reads the build and owner docs first, blocks commands from untrusted branches, protects running jobs, and stops unsafe pushes or releases.
To use this AI rule
## Read the Build Files and Owner Docs Before Changing Code
Read the repository's entrypoint, package map, build definition, and ownership documents before changing code. Treat generated copies and convenience summaries as pointers, not competing sources of truth.
### Repository Orientation
- Locate executable entrypoints, implementation packages, shared infrastructure, and the build system.
- Use the build definition for the current command list instead of copying commands into guidance that can drift.
- Identify which document or source file owns each public behavior, configuration key, environment variable, and operational invariant.
- Keep host-specific adapters explicit. Pin assumptions about external CLI versions and use stable API fallbacks when worktree state makes high-level commands unreliable.
### Verification Gates
- Format and lint before handoff, including generated-artifact drift checks.
- Run focused tests while iterating, then the authoritative unit, integration, race, and end-to-end suites required by the changed boundary.
- Prefer end-to-end tests for process, I/O, configuration, Git, daemon, and recorded-fixture behavior; unit-test pure helpers for speed and localization.
- Build the real executable after non-trivial changes.
- Use test-driven development for bug fixes and features, and keep unresolved work in the issue tracker rather than hiding it in unrelated edits.
## Stop Every Child Process on Cancel and Pass the Git Directory Explicitly
Long-running automation must own its cancellation, descendants, shared state, and filesystem effects across every supported operating system.
### Process Discipline
- Thread cancellation contexts through long-running, subprocess, and network work.
- Derive bounded timeouts for cleanup, probes, and HTTP calls.
- Put cancellable subprocesses in a process-tree boundary so cancellation terminates descendants, not only the direct child.
- Reap process groups on clean exit and error as well as cancellation; inherited pipes and leaked grandchildren must not outlive a run.
- Apply platform-specific child-process hardening through one idempotent wrapper so background work never opens unwanted consoles.
- Protect shared mutable state with standard synchronization primitives and make ownership of goroutines, channels, worktrees, and temporary directories explicit.
### Filesystem and Git Discipline
- Use platform path helpers, application-owned state roots, and documented file modes.
- Resolve symlinks when platform aliases can make equivalent paths compare differently.
- Route bare-repository Git operations through a helper that passes the Git directory explicitly; never rely on current-directory discovery under hardened Git settings.
- Remove or replace state only when ownership and lifecycle records prove that it is safe.
## Let Only the Trusted Branch Decide Which Commands Run
Configuration that selects commands or executable agents is code. Load it only from a trusted revision, while treating contributor-controlled configuration and instructions as untrusted data.
### Trusted Inputs
- Resolve the trusted default branch by a fresh fetch and pin the exact commit before reading code-executing settings.
- Abort when the trusted commit or its present configuration cannot be fetched, read, or parsed. A readable trusted tree with no configuration may be valid if the contract allows it.
- Read command selectors, agent selectors, documentation policy, project-instruction opt-outs, and repository-command permission only from the trusted copy.
- Default repository-command permission to disabled. A pushed branch must never enable its own execution privileges or weaken trusted policy.
- Keep non-executing feature settings separate so branch-specific behavior does not cross the execution boundary.
### Fail-Closed Handling
- Sanitize adversarial control text and redact secrets before placing user or repository content into agent prompts.
- Verify that any instruction-suppression option is effective for the selected adapter before launching it.
- Never fabricate trust after a fetch, parse, or authorization failure.
- Add regression tests proving that pushed content cannot self-authorize commands, replace trusted policy, or bypass fail-closed behavior.
## Run One Background Service at a Time and Refuse Stops During Active Jobs
Machine-wide services need independent defenses for singleton ownership, socket safety, recovery, and destructive lifecycle commands.
### Singleton and Recovery
- Acquire an exclusive operating-system lock before recovery work or socket binding, and hold it for the process lifetime.
- Treat a held kernel lock as proof of a live owner; do not invent staleness heuristics for it.
- Probe an existing socket before removing it, and bound connection and health-check timeouts independently.
- Start service execution only through an explicit mode. Inherited environment variables must not reinterpret ordinary probes as workers.
- Make startup cleanup state-aware: never remove a worktree or resource whose job record is pending or running.
### Lifecycle Controls
- Refuse stop, restart, and update while active jobs exist unless the operator supplies the explicit destructive override.
- Do not let non-interactive confirmation flags bypass the active-job guard.
- List blocking jobs and audit each lifecycle invocation with process and parent attribution.
- Treat CI monitoring limits as idle timeouts: re-arm only on verified upstream progress, never shorten the existing deadline, and fail safely when progress cannot be checked.
- Make orphan-abort operations idempotent, and keep awaiting-agent timestamps observational: set them only while a gate is actually parked and never use them to change gate resolution.
## Keep Review and Fix Sessions Separate and Compare Changes to the Stated Goal
Review must compare the complete change against source-verifiable intent without allowing untrusted text, delivery timing, or fixer rationale to distort the decision.
### Intent and Findings
- Preserve intent provenance. Treat an explicit intent as authoritative acceptance criteria and an inferred intent only as a low-confidence hint.
- Apply the same sanitization, secret redaction, and non-execution guard to both forms.
- Convert a fixer change that contradicts explicit criteria into an ask-user finding that parks the run.
- During pre-delivery review, exclude only outcomes owned by later pipeline stages; continue enforcing external or pre-existing lifecycle requirements.
- Fail closed when a finding action is absent or unknown: classify it as ask-user, never as automatically fixable.
### Session and Fix Discipline
- Keep one durable reviewer session per run and a separate durable fixer session; roles must never share state.
- Reuse sessions only for the review loop, persist minimal identity metadata, and never persist prompts or transcripts.
- If resume is unsupported or fails, discard that identity and repeat the same role's turn cold. Do not retry after cancellation.
- Every rereview remains a full adversarial review of the complete branch diff.
- In a fix round, apply all fixes first and run one focused verification limited to the changed area. Leave authoritative full-suite test and lint gates to their dedicated stages.
## Regenerate Docs from Their Source and Keep Prompts and Code Out of Usage Stats
Keep one owner for each fact, regenerate derived guidance from its source, and separate local diagnostic evidence from bounded remote analytics.
### Documentation and Generated Content
- Keep overview documents concise; put detailed reference facts in their designated owner and link to them from guides.
- Update ownership maps when responsibility moves.
- Edit the source of generated agent guidance, regenerate the artifact through the approved build, and let lint fail on drift.
- Change source guidance and point-of-use command output together when both express the same operational contract.
- If one agent pass combines documentation and lint duties, consume each result exactly once and fall back to an independent pass whenever output is skipped, invalid, or untrusted.
- Limit documentation edits to material made stale by the current change; do not reintroduce exhaustive corpus sweeps.
### Privacy-Safe Observability
- Read-only surfaces must emit no pageview; gate their remote command event by state change and a bounded interval.
- Keep mutation events full fidelity while storing detailed performance evidence locally only.
- Never store prompts, outputs, diffs, secrets, or raw command arguments in invocation metrics, and never send run identifiers, paths, session identities, or per-invocation records to remote analytics.
- Send only bounded aggregate counts on terminal events.
- Give metric definitions and timing boundaries one authoritative implementation. Represent unavailable values as null, not fabricated zero, and compute per-round usage from cumulative session deltas when necessary.
## Check the Remote Before a Force Push and Sign Every Release Build
The primary invariant is to preserve user code. Refuse an unsafe synchronization or delivery rather than attempting clever recovery that can overwrite unobserved work.
### Repository and Branch Safety
- Keep pull-request base routing separate from an optional fork push target. When a host cannot support fork routing end to end, skip creation rather than opening an incorrect self-request.
- Limit ordinary synchronization to a clean strict fast-forward or a proven equivalent-divergence move anchored to the exact pipeline head.
- Passive status must not fetch or mutate. Blocked paths must not reset, stash, merge, rebase, force, switch, delete, or update an external remote.
- Persist the exact pushed commit, credential-free target identity, and generation, then recheck all mutable assumptions immediately before applying a synchronization.
- Preserve unpublished terminal work under a recovery reference. Recovery may move a clean worktree only by strict fast-forward; keeping local work must update the gate through compare-and-swap without triggering a new pipeline.
- Derive rebase bases from freshly fetched authoritative remote references. Park when unpushed default-branch commits would silently widen a change.
- Before force-pushing, reread the remote head and proceed only for a new branch, an equal head, an unchanged previously observed head, or remotely added commits already proven equivalent by patch identity. Any lookup or proof failure must fail closed.
- Keep the lease anchor as the last head the run actually observed, never a tip fetched immediately before forcing.
### Release and Dependency Safety
- For a platform with a permanent signing contract, sign every official artifact with the fixed application identity, hardened runtime, and secure timestamp before archiving or checksumming.
- Keep signing credentials scoped to the release job, import them into ephemeral storage, and remove them on success and failure.
- Fail release verification on a missing or ambiguous signature, wrong identity or architecture, mutable identity requirement, missing hardening, or missing timestamp.
- Treat notarization, packaging formats, and universal binaries as separate scope unless the release contract includes them.
- Before adding a dependency, consult its current authoritative documentation and discuss the change with the user.
- Do not claim readiness until formatting, linting, focused tests, integration tests, the full suite, build checks, documentation checks, and release-specific verification have actual results.
