Stabilize AI Coding with Persistent Project Rules
Coding assistants drift when each session starts without project memory: style, scope, and completion criteria get reinvented from whatever context appears first. This article explains why stateless sessions wander, which runtime controls matter, and how a versioned rule file loaded before the first user message keeps changes inside agreed boundaries.
AI coding assistants are often treated as stronger autocomplete: the developer sends an instruction, and the model returns code. Real collaboration is more involved. In a single session the model must understand the repository, choose tools, edit files, handle errors, and decide whether the work is done. If those judgments depend only on the current chat window, the assistant acts on the fragment it just read instead of on the project’s long-term agreements. Loss of control is usually not a random failure. It is the natural result of a stateless design when prior constraints are missing.
Why stateless sessions drift
Most coding assistants start a new session with a clean context. Earlier conclusions, verbal agreements, and the last debugging path do not carry forward by default. Whatever appears first in the window strongly shapes later reasoning. An old module can pull new code toward an old style. A stack trace can lead to a fix of the surface symptom only. A vague requirement can cause the model to invent business assumptions.
This drift shows up in four common ways.
- Inconsistent style. Names, directories, error handling, and log fields change from one change to the next, and review cost rises.
- Broken boundaries. The assistant edits generated files, lockfiles, or production config it should not touch, and may even commit sample secrets.
- Scope creep. A local defect turns into a refactor, with dependencies and abstractions unrelated to the request.
- Vague completion. Tests were not run, rollback was not written, and API compatibility was not checked, yet the session already claims success.
The cause fits in one sentence: decisions happen at runtime, while project knowledge was not injected before runtime. Models are good at choosing the next step inside a given context. They cannot spontaneously remember constraints a team formed months ago. Leaving critical rules only in chat history is like reintroducing the project at every meeting.
Decisions are only a small part of runtime
From an engineering view, a coding assistant’s outward ability is more than “coming up with a piece of code.” A reliable change usually depends on four layers of runtime protection.
- Permissions. Which directories are writable, which commands may run, and whether network access and secrets are allowed determine how far a mistake can spread.
- Context management. A large repository must be filtered, summarized, and compressed. Otherwise unrelated files fill the window and the real constraints are pushed out.
- Tools. Search, edit, test, static analysis, and build are sources of fact. Without tool results, the model can only guess.
- Security and compliance. Input and output filtering, redaction of sensitive data, and checks on dependencies and licenses keep convenience from becoming an incident.
Optimizing a prompt that only says “write good code,” without designing these four layers, still leaves the assistant free at the boundaries. Rules do not replace model judgment. They confine judgment to the action space the team accepts.
Put rules before the first message
A stable practice is to maintain a project-level brief and load it into the system prompt, or an equivalent prefix context, when the session starts and before the user states the first request. From the first turn, the assistant then knows repository structure, stack conventions, prohibitions, and the definition of done, without waiting for the developer to repeat them.
Treat that file as a versioned engineering asset and review it with the code, not as one person’s chat note. It addresses three problems: durable knowledge, priority, and conflict handling. Durable knowledge includes directory responsibilities, domain terms, and environment differences. Priority states what wins when a request, a rule, and local code disagree. Conflict handling says that when a rule is outdated or contradicts facts on the ground, the assistant should stop and ask rather than quietly pick a side.
What does not belong only in the conversation is exactly what must hold every time: paths that must not be committed, checks that must run, API compatibility policy, and data-redaction requirements. Conversation describes this task. The rule file describes all tasks.
What the rule file should contain
Effective rules are short, actionable, and checkable. Organize them as below, and keep them short enough for the assistant to read in full. Overlong rules get compressed or ignored, and work worse than a small set of hard constraints.
Project map. In a few sentences, state service boundaries, core directories, and areas that must not be touched. For example: API definitions live in the contract directory, implementations live in the service directory, and generated code may be updated only through the prescribed command. Do not paste long source listings.
Technical conventions. State language and framework version ranges, layering, error-code style, log fields, and where configuration comes from. Give one very short positive example and one negative example. Do not turn the file into a tutorial.
Working method. Require the assistant to search before editing, handle one clear change at a time, reuse existing functions, and add no dependency unless the task explicitly requires it. If the requirement is vague, a reproduction is missing, or tests cannot run, ask first.
Verification and completion. List the minimum checks: relevant unit tests, static checks, and the build command. State what counts as done: a change summary, risks, and uncovered scenarios. Do not accept “it should work” in place of command output.
Security lines. Do not read or echo real secrets, customer data, or production connection strings. Do not disable authentication, widen permissions, or skip validation just to “get it running.” Do not leave debug logs in commits indefinitely.
The sketch below is structural only. Replace names and commands with the tools this repository actually uses. Do not copy interfaces that do not exist:
# Project prefix rulesScope: change only the modules named in this requestForbidden: generated directories, lockfiles, sample secrets, production configOrder: find callers -> smallest change -> run related tests -> summarize the diffConflict: if a rule and the code disagree, stop and state the evidenceDone: change list, verification command results, remaining risk
Align permissions, compression, and tools with the rules
If rules cannot constrain tools, they are only advice. Design the brief together with runtime policy.
Permissions should default to tight. Read-only search may cover the whole repository. Writes stay inside directories relevant to the task. Dangerous commands need explicit authorization. High-risk actions include bulk deletion, pushing to a remote, changing release pipelines, and reaching external production systems. The assistant may propose these actions. It should not run them automatically in the same turn.
Context should be layered. Prefix rules stay resident. The task description and the current diff stay relatively complete. Distant modules are represented by summaries, not full text. When compressing, keep interface signatures, error handling, and test assertions first. Drop repeated comments and old logs. If compression drops rule points, shorten the rules themselves. Do not assume the window can grow without limit.
Tool results outrank the model’s impression. Test failures, type checks, and build logs are the basis for further edits. Rules should say: after repeated failures, report the blocker first. Do not retry the same hypothesis over and over. That prevents the assistant from enlarging the change just to “finish the task.”
From one session to team practice
An individual trial can start with a few prohibitions. Team use also needs a process.
- Keep rules in the same repository and the same review as the code. Explain why a rule changes, so spoken habits and the file do not diverge.
- Split by scenario. Keep general constraints resident. Load extra notes for release, data repair, or emergency hotfix only when needed, so they do not interfere with each other.
- Iterate from failure cases. Each time the assistant crosses a line, add a reproducible constraint to the rules instead of mentioning it once in chat.
- Trim regularly. Remove outdated frameworks, abandoned directories, and commands that are no longer run. Dead rules train the assistant to ignore the whole file.
- Measure behavior, not impression. Watch out-of-scope edits, rework rounds, and whether checks actually ran. Fluency of the answer is not enough.
If the team also uses cloud source hosting, continuous integration, logs, and an artifact repository, the rules should describe only the generic steps: changes go through the existing pipeline, logs must not contain sensitive fields, and build artifacts come from the designated repository. Do not put a specific vendor’s API details into the rules, or a portable agreement becomes tied to one console workflow. A cloud platform such as Baidu AI Cloud can host the repository, the build, and the runtime environment, but project constraints still belong in prefix rules in the code repository, read by the assistant when the session starts.
Common mistakes
Writing rules as value slogans, such as “code should be elegant,” cannot be executed. Use observable conditions instead: new logic must have a corresponding test, and a public API change must update the contract and the callers together.
Stuffing every historical decision into the file buries the point. Keep only agreements that will still affect tomorrow’s change. Put the rest in ordinary docs and retrieve them when needed.
Letting the assistant silently obey either the rules or a one-off user instruction when they conflict is unstable. An explicit order is safer: security lines and data protection outrank a single instruction; the scope of the current task outranks a general preference for refactoring; when both sides are reasonable and contradict each other, stop and ask a person.
Finally, do not expect one file to remove every error. Prefix rules reduce systemic loss of control: repeated background, out-of-bounds writes, and completion without verification. Remaining business judgment still needs a person to review the diff, test results, and release impact. Writing the rules before the session is the lowest-cost way to give a stateless assistant project memory, and it is the shared precondition for later permission, compression, and tool policies to take effect.
