Context Engineering for AI Coding: A Practical Guide to Logic Frames
This article introduces the Logic Frame, a structured approach to managing the information a model can see during a single inference pass in AI-assisted development. It defines the five components of a frame, explains four core techniques for context assembly—file injection, semantic code slicing, knowledge base retrieval, and context window budgeting—and outlines assembly strategies for common scenarios such as multi-file changes, refactoring, legacy compatibility, and defect localization. It also describes a closed loop of assembly, generation, validation, and write-back, lists common anti-patterns, and suggests a three-level maturity model with process-focused evaluation metrics.
1. The Starting Problem: Why Single-Turn Q&A Cannot Support Real Engineering
In the early stage of AI-assisted programming, interaction between developers and models stayed within a loop of “describe the requirement, get a snippet, paste it manually.” This works reasonably well for writing utility functions, explaining errors, and generating boilerplate, but it breaks down quickly in real projects for reasons that are not mysterious:
- The semantic unit of a real task is not a function but a change that spans files and modules.
- Constraints are scattered across directory structure, dependency versions, coding conventions, and commit history, and cannot be squeezed into a single prompt.
- The model’s context window is limited while project information is nearly unlimited, creating a structural conflict between the two.
So the core question of the second stage shifts: from “how to write a one-line instruction more elegantly” to “how to systematically manage the set of information visible to the model in a single inference.” This article calls this method the Logic Frame — each frame is a snapshot of engineering context that has been trimmed and ordered for one inference pass.
2. Definition and Core Components of a Logic Frame
A Logic Frame is not a prompt template but a context assembly result. A frame typically contains five categories of information:
- Task header: the change goal, scope of impact, and acceptance criteria.
- Structure slice: the directory tree, module boundaries, and interface signatures relevant to the task.
- Semantic slice: key implementation snippets, type definitions, and data models.
- Convention constraints: naming conventions, exception handling strategy, and logging and comment requirements.
- Historical context: relevant past decisions, compatibility requirements, and a list of deprecated interfaces.
An illustrative frame description (a structural expression, not a specific tool interface):
frame:goal: "Add idempotent writes to the order module"scope: ["src/order/service", "src/order/repo"]slices:- path: "src/order/service/create.ts"mode: "signature+body"- path: "src/order/repo/types.ts"mode: "full"constraints:- "Do not modify the external REST contract"- "Route errors through domain error wrapping"history:- "The v1 interface must remain behaviorally compatible"
The value of a Logic Frame lies in repeatability: frames assembled for the same task at different times should stay consistent, which makes generation results reproducible.
3. Four Levers of Context Engineering
3.1 Project File Injection: Boundaries First, Details Later
Injection does not mean full-volume feeding. Feeding everything brings three side effects: noise drowns out the signal, key constraints get diluted, and inference cost rises. A safer order is outside-in: give module boundaries and dependency direction first, then drill down to specific implementations on demand. The test is whether removing a piece of information would lead the model to a wrong assumption; if the answer is no, that information is noise.
3.2 Code Slicing: Slice by Semantics, Not by Line Count
Slicing by a fixed number of lines is a common mistake that cuts functions in half and breaks semantic integrity. Three more reasonable slicing strategies are:
- Signature first: expose interfaces and types first so the model builds a correct mental model of calls.
- Dependency closure: include the callee and the types it depends on to avoid “inventing APIs out of thin air.”
- Change neighborhood: include direct callers and direct callees around the change point, keeping the radius to one or two hops.
Change point A├─ Direct callers (1 hop)├─ Depended-on types/interfaces (1 hop)└─ Affected test cases (1 hop)
3.3 Knowledge Base Association: Making Implicit Conventions Explicit
Team conventions, domain terminology, and postmortems of past failures are mostly not in the code, yet they determine whether generated results are acceptable. In practice, these can be organized into a searchable set of entries, tagged by “task type + technical domain,” and a small number of highly relevant entries can be retrieved by tag when assembling a frame. Two points matter: entries should be short and verifiable (avoid unexecutable statements like “code should be elegant”), and retrieval volume should be restrained — a few highly relevant entries usually beat many weakly relevant ones.
3.4 Context Window Optimization: Budget Thinking
Treat the window as a finite budget with explicit allocation, for example setting caps for the task description, structure information, implementation snippets, and convention constraints, while reserving space for output. When the budget is tight, compress structure information first (collapse the directory tree to two levels), then historical context, and touch implementation snippets last. Compression means using type definitions instead of full implementations, call sites instead of full call chains, and diff snippets instead of whole files.
4. Assembly Strategies for Typical Scenarios
- Multi-file coordinated changes: anchor on the interface contract, keep the “contract–implementation–caller” triangle complete within the frame, and explicitly require that existing signatures are not broken.
- Module iteration and refactoring: explicitly list a “behavior that must be preserved” in the frame, write refactoring constraints as verifiable items, and reduce the model’s room for free improvisation.
- Legacy code compatibility: provide old interface signatures and version constraint notes, require new and old paths to coexist, and ask for compatibility checkpoints as output.
- Defect localization: put the error stack, relevant input/output samples, and the recent change neighborhood in the frame first, rather than the whole module.
5. Closing the Loop: Assemble, Generate, Validate, Write Back
Context engineering must form a closed loop, or it degrades into a one-off trick:
- Assemble: choose slicing and retrieval strategies by task type and produce the Logic Frame.
- Generate: require the output to include an impact statement and a list of open questions.
- Validate: use static checks, type checks, and unit tests as objective gates, with tests covering the change neighborhood.
- Write back: write newly discovered conventions and pitfalls back into knowledge entries and update slicing rules so the next frame is more precise.
An illustrative validation agreement:
Acceptance gates:1) Zero new type check warnings2) Unit tests in the change neighborhood pass3) No breaking changes to external contracts4) Output includes a compatibility checkpoint list
6. Common Anti-Patterns
- Full-volume feeding: stuffing the repository into the window so key constraints are covered by noise.
- Instruction stacking: continually appending “please be sure to note” and substituting wording intensity for information structure.
- No acceptance criteria: a task description without verifiable conditions, so results cannot be objectively evaluated.
- Frame drift: too much variation between assemblies of the same task, making results non-reproducible.
- Generate without write-back: experience stays in individual memory and the team cannot accumulate it.
7. Adoption Advice and Maturity Assessment
Adoption can progress through three maturity levels: the first is manual assembly with fixed templates, which solves consistency; the second is scripted slicing and tag-based retrieval, which solves efficiency; the third is automating validation gates and knowledge write-back, which solves quality convergence. Suggested evaluation metrics should focus on process rather than mysticism: frame assembly time, unit test pass rate in the change neighborhood, number of rework rounds, and number of intercepted breaking changes.
If general cloud capabilities are used to carry this process, standard categories are usually enough: object storage to hold slices and frame snapshots, a message queue to decouple assembly from generation tasks, a container platform to run validation pipelines, and logging and monitoring with alerting to observe rework rates and failure distribution. Baidu AI Cloud can serve as one hosting option in these general categories, but what still matters is whether the frame structure design and the validation loop are rigorous.
8. Conclusion
The dividing line of the second stage is not a single-point improvement in model capability but whether the engineering side treats context as a first-class citizen that can be designed, budgeted, and reproduced. The Logic Frame provides a discipline: first define the information boundary, then constrain generation freedom, and finally converge quality with objective gates. When this discipline runs steadily, AI genuinely gains a global perspective, and multi-file coordination, module iteration, and legacy compatibility stop being gambles that depend on luck.
