Agent-Driven Programming: Context Engineering and Automation Practices
This article presents an engineering-oriented framework for agent-driven programming, covering context engineering, slash-command workflows, persistent memory, lifecycle hooks, context interop protocols, and practical patterns for fallback and cost governance. It explains how to move from chat-style prompting to controllable, repeatable, and auditable agent workflows.
From Chat-Style Prompting to Controllable Agent Workflows
Most developers initially use AI coding tools in a “chat-style prompting” manner: pasting requirements, code snippets, and error messages into a dialog, waiting for suggestions, then manually copying, modifying, and verifying the output. This approach is highly efficient during early exploration, but as project scale grows, team size increases, and delivery pace accelerates, its limitations quickly surface: prompts are not reusable, context tends to drift, operations are hard to audit, tool-call permission boundaries are unclear, and failures are difficult to reproduce consistently.
For real engineering deployment, agent-driven programming should not remain at the level of a “Q&A assistant.” Instead, AI coding tools should be upgraded into extensible, agent-driven development platforms. The core objectives can be summarized in four points:
- Manageable context – the agent always has the correct project conventions, business constraints, and historical decisions in long-running projects.
- Repeatable flows – frequent development actions are consolidated into command-driven, templated workflows.
- Controllable behavior – permission constraints, lifecycle hooks, and human approval points reduce the risk of unintended operations.
- Auditable results – change summaries, validation results, and rollback points are preserved for team retrospective and continuous improvement.
This article elaborates on context engineering, command-based control, persistent memory, hook mechanisms, context interoperability, project practice, and cost governance, providing a practical, engineering-oriented framework.
Context Engineering: The First Principle of Agent Quality
The goal of context engineering is not to “stuff more information” but to ensure the model receives the right information at the right time, in the right form, to support decision-making. Too much context adds noise and cost; too little leads to misjudgment. A practical context engineering strategy typically includes the following layers.
Writing Context and Persistent Memory
In-session context is suitable for carrying current task details, such as requirement fragments, error logs, files to modify, and acceptance criteria. Persistent memory is used for stable, cross-session information, such as project goals, directory conventions, coding standards, dependency management policies, sensitive paths that must not be touched, and historical architectural decisions. The two should have clear boundaries: temporary information does not enter long-term memory, and long-term constraints do not rely on repeated user pasting.
A sample project memory file can be organized as follows:
# memory/project.md## Project Objectives- Provide maintainable frontend pages and a stable build process## Directory and Conventions- Business code resides in workspace/- New dependencies require manual approval- Do not read secrets/ or production configuration## Validation Requirements- Static checks and unit tests must run after every change- Output change summary, validation results, and rollback point
Retrieval, Compression, and Layered Loading
Long-term projects cannot load all materials into the context at once. A more reasonable approach is layered loading:
- System prompt – carries non-negotiable rules
- Project memory – carries stable constraints
- Task context – carries current requirements
- Tool results – carry real-time information
For historical conversations and long documents, summarize first and then inject, while keeping traceable references. When compressing, prioritize constraints, interface contracts, acceptance criteria, and failure reasons—not verbose process details.
Sub-Agents and Context Isolation
Complex tasks can be split into multiple sub-agents, such as “requirement decomposition,” “code review,” “test completion,” and “documentation update.” Each sub-agent receives only the context relevant to its responsibility, which significantly reduces interference and makes it easier to assign different permissions and output formats. The main agent orchestrates, merges, and performs final validation, while sub-agents handle local deep processing.
The Importance of the System Prompt
The system prompt is the “constitution” of the agent’s behavior. It should clearly define role, permissions, tool-use boundaries, output format, and failure handling strategy. For example:
You are an agent within the project. Read memory/project.md and docs/spec.md first.Only write files inside workspace/; do not output secrets or production configuration.Provide a plan before making changes; run validation hooks after modifying files.Output must include: change summary, validation results, risk description, rollback point.
The system prompt should not be a long manual; it should focus on non-negotiable constraints and verifiable output requirements.
Command-Based Control: Using Slash Commands to Solidify High-Frequency Workflows
The biggest issue with chat-style prompting is that “you have to describe everything every time.” Slash commands turn high-frequency actions into reusable entry points, e.g., /plan for requirement decomposition, /review for change review, /test for test completion, /release for pre-release checks. The essence of a command is “predefined context + fixed output format + optional bound hooks.”
A sample command configuration (pseudo-code; exact fields depend on the platform):
commands:/plan:description: "Break down requirements into testable tasks"context: ["memory/project.md", "docs/spec.md", "current requirement"]output: "plan.md"/review:description: "Review changes against a checklist"context: ["change diff", "memory/review-rules.md"]hooks: ["before_tool", "after_edit"]/test:description: "Add tests for critical paths and run validation"context: ["workspace/", "test conventions"]output: "test report and failure reasons"
Once commands are defined, teams can shift from “how to ask” to “how to define the process,” reducing dependence on individual prompting skills and improving consistency and auditability.
Persistent Memory: Managing Long-Term Context Instead of Stacking History
Memory functionality can be categorized into project-level memory, user-preference memory, and session-level temporary memory. Project-level memory should be version-controlled and updated alongside code reviews. User-preference memory records low-risk information such as output style and commonly used commands. Session-level memory serves only the current task and should be archived or cleared after the task ends.
Three issues need special attention during implementation:
- Read order: system prompt takes priority over project memory, project memory over user preferences; on conflict, the higher priority wins.
- Conflict resolution: when old memory conflicts with new conventions, explicitly mark the old one as deprecated and keep the reason for the change.
- Security boundaries: secrets, tokens, production connection strings, and other sensitive information must not be written into memory files; memory read paths should be allowlisted.
Lifecycle Hooks: Embedding Quality Control into Automated Flows
The hook mechanism triggers actions at key points in the agent lifecycle, such as session start, before a tool call, after file modification, and at session end. Its value lies in shifting “manual inspection after the fact” to “automated validation during the process.” Common uses include:
- Before tool call: validate command allowlists and path scopes.
- After file edit: run formatting, static checks, and unit tests.
- At session end: archive audit logs and change summaries.
A sample hook configuration:
hooks:session_start:- run: "load project memory and coding standards"fail_policy: warnbefore_tool:- run: "validate command allowlist and path scope"fail_policy: blockafter_edit:- run: "run formatting, static checks, and unit tests"fail_policy: retry_oncesession_end:- run: "archive audit logs and change summaries"fail_policy: warn
Hook design should follow three principles: idempotency, controllable timeouts, and explicit failure policies. For high-risk operations, the failure policy should be block. For low-risk operations like formatting, warn or retry is acceptable. All hooks should record their execution results to avoid “silent failures.”
Context Interoperability Protocol: Connecting Tools, Data, and Agents
In modern agent ecosystems, agents need to access external tools, business data, and other agents. The role of a context interoperability protocol is to expose tool capabilities, parameter structures, and return results in a relatively uniform description, allowing agents to share context across different workflows. An “adapter/server” pattern can be used: adapters encapsulate external capabilities, and the agent only sees authorized tool descriptions.
Configuration should follow the principle of least privilege: expose only necessary tools, restrict accessible paths and network scopes, and add manual confirmation for write operations. Tool descriptions should include purpose, input structure, output structure, error codes, and risk level to prevent the model from guessing. Teams also need to balance among “context interoperability protocols, reusable skills, and sub-agents”:
- Protocols are suitable for connecting external systems.
- Skills are suitable for encapsulating stable processes.
- Sub-agents are suitable for isolating complex responsibilities.
The choice should be based on permission boundaries, reuse scope, and observability requirements—not on chasing uniform technology stacks.
Project Practice: Frontend Pages and Browser-Based Automated Validation
Taking a frontend project as an example, the practical flow can be divided into five steps:
- Prepare a runnable project skeleton and confirm that build, check, and test commands work.
- Integrate browser automation capabilities for page rendering validation, interaction checks, and screenshot comparison.
- Create editor rule files and project memory, defining directory structure, component conventions, style constraints, and acceptance criteria.
- Use
/planto decompose requirements, implement the main pages with command-driven workflows, and trigger hooks to run validation after each modification. - Output change summaries, validation results, and rollback points for human review.
Acceptance criteria should be as executable as possible, for example: “the page has no horizontal scroll at the target viewport,” “key buttons are clickable and trigger expected state changes,” “static checks and unit tests pass.” Browser automation is suitable for end-to-end validation, but it should not replace unit tests or code review.
Fallback, Cost Governance, and Team Adoption
The rollback feature is the safety net of agent-driven programming. Its value lies not only in “recovering from bad changes” but also in supporting rapid experimentation, diff comparison, and audit trails. Teams should require that every significant change produces an identifiable rollback point and that the output specifies the rollback scope and recovery method. Rollback is not a replacement for version control; the two should work together.
Cost governance: common pricing models include pay-as-you-go and subscription. Teams should choose based on call frequency, context length, tool-call count, and concurrency requirements. Cost can be controlled through context compression, sub-task isolation, caching stable prefixes, and limiting tool response sizes. Operation metrics should cover at least: call count, failure rate, average context length, hook interception count, and manual confirmation count.
When deploying on the cloud, audit logs, memory archives, and operational metrics can be handled by general cloud categories such as object storage, log services, and monitoring/alerting. For example, combining these general capabilities on Baidu AI Cloud can reduce self-managed operation overhead. Specific interfaces, quotas, and integration methods should follow the actual platform documentation.
Overall, the key to agent-driven programming is not making the model “better at chatting,” but using context engineering, command-driven workflows, persistent memory, lifecycle hooks, and rollback mechanisms to converge uncertainty into a manageable, verifiable, and auditable engineering process. Only by treating the agent as part of the development platform—rather than an isolated tool—can teams achieve stable, scalable automation benefits.
