AI Agent Engineering: Persistent Memory, Cost Control, and Automation

    This article breaks down the engineering practices that turn an AI agent from a chat wrapper into a stateful execution system. It covers moving context out of the session into a local database, layered memory and structured event logs, credential handling, model routing and a code-first principle for cost governance, always-on execution on low-power devices, a plain-text knowledge hub, skill packaging with acceptance criteria, and a four-step rollout plan with risk controls. Readers will find SQL and Python snippets, a Markdown note template, and concrete design constraints for each layer.

    1. Where the Problem Starts: Why Agents Feel Unusable

    Most teams hit the same set of symptoms the first time they build an AI agent: any minor process fault forces a full restart, and the context built up before the restart is gone; users have to paste the same background description and the same credentials over and over; model call volume looks modest, yet the bill climbs fast. On the surface this is an engineering stability problem. In reality the architecture is positioned wrong — the agent is treated as a “chat shell” rather than a computing system with state, tools, and an execution plan.

    Conversation capability handles “understanding and expression.” The real value of an agent is “continuous execution.” Three things sit between the two: state, determinism, and cost structure. Without state, it cannot remember task progress. Without determinism, the same instruction can drift to a different result on every run. Without cost constraints, high-frequency model polling pushes marginal cost to an unacceptable level. The five sections below fill those gaps one by one.

    2. Persistent Memory: Moving Context Out of the Session and Into a Database

    Session context is a volatile resource that disappears when the process ends. The common engineering answer is to externalize state into a local embedded relational database and record an event stream per task.

    There are three design points. First, layered memory: short-term memory holds intermediate results for the current task, while long-term memory holds user preferences, past conclusions, and validated parameters. The two use different table structures so they do not pollute each other. Second, structured logs: every tool call and every model output writes one record containing the task identifier, timestamp, input summary, output summary, and status, which is what makes post-incident review possible. Third, sensitive data handling: credentials should never be written to the memory store in plaintext; reference them through environment variables or a dedicated secrets management service, and keep only the reference identifier in the database.

    A sketch of the schema and write path:

    1. CREATE TABLE task_event (
    2. id INTEGER PRIMARY KEY AUTOINCREMENT,
    3. task_id TEXT NOT NULL,
    4. role TEXT NOT NULL, -- user / agent / tool
    5. content TEXT NOT NULL,
    6. created_at TEXT NOT NULL
    7. );
    8. CREATE INDEX idx_task ON task_event(task_id, created_at);
    9. CREATE TABLE long_term_fact (
    10. key TEXT PRIMARY KEY,
    11. value TEXT NOT NULL,
    12. updated_at TEXT NOT NULL
    13. );
    1. def remember(task_id, role, content, conn):
    2. conn.execute(
    3. "INSERT INTO task_event(task_id, role, content, created_at) "
    4. "VALUES (?, ?, ?, ?)",
    5. (task_id, role, content, now_iso()),
    6. )
    7. conn.commit()

    What memory buys is accumulability, not automatic intelligence. Accuracy gains come from two things stacked together: past conclusions get reused, which cuts repeated trial and error; and failure cases get recorded, forming a searchable library of counterexamples. For retrieval, recall by keyword or vector first, then rank with time decay, and keep the token volume injected into the prompt under control.

    3. Cost Governance: Layered Routing and the Code-First Principle

    Cost overruns usually come from two sources: sending every task to the strongest model, and letting the model do work that code could finish deterministically.

    The first fix is layered model routing. Grade tasks by complexity: simple classification, format conversion, and summary extraction go to lightweight models or free-tier quota, while complex reasoning and long-chain planning escalate to high-capability models. The routing layer should decide dynamically based on task type, input length, and historical failure count, and keep a manual override switch.

    The second fix matters more: for deterministic tasks, have the agent generate code first and then execute it, instead of looping back to the model repeatedly. For example, “summarize several data sources every day and produce a metrics table” should take the shape of a repeatable script plus one result check, not a fresh round of field-by-field reasoning from the model each day.

    1. def route(task):
    2. if task.kind in ("format", "classify", "extract"):
    3. return "light_model"
    4. if task.estimated_tokens > 8000 or task.retry_count >= 2:
    5. return "strong_model"
    6. return "mid_model"
    7. def solve(task):
    8. if task.deterministic:
    9. code = plan_as_code(task) # emit a script, not natural-language steps
    10. return run_and_verify(code) # execute + assert on the result
    11. return call_model(route(task), task.prompt)

    Combined with caching (reuse the conclusion for identical inputs), batching (merge small requests), and budget caps (a daily threshold with a circuit breaker), the cost curve typically shifts from linear growth to step-wise growth.

    4. Always-On on the Device: An Execution Body on Low-Power Hardware

    To handle real-world events, an agent must be able to reach real-world signals. Compared with waiting for external pushes on a server, placing the execution body on a device you carry has one clear advantage: it can read device-side event sources directly — notifications, SMS verification codes, battery and network status, sensor readings — which enables hardware-level triggering.

    The engineering constraints need to be settled in advance. First, power: use event-driven rather than polling, and sleep when no event arrives. Second, permissions and compliance: capabilities such as reading messages or accessing notifications require explicit user authorization and must follow platform policy and local regulations. Third, safety boundaries: the on-device execution body needs an action allowlist and a second confirmation step to avoid accidentally triggering irreversible actions. Fourth, observability: on-device logs must be either shipped back or retained locally so issues can be traced.

    A minimal always-on loop:

    1. while True:
    2. event = wait_for_event(timeout=None) # block instead of busy-spinning
    3. if event.type == "verification_code":
    4. code = extract_code(event.text)
    5. submit(code) # must match an allowlisted action
    6. elif event.type == "battery_low":
    7. defer_non_urgent_tasks()
    8. log(event) # persist everything for review
    9. sleep_idle()

    Running publishing scripts directly on the device also reduces how often external interfaces are needed, lowering the uncertainty that comes from interface policy changes. That does not mean platform rules can be bypassed: content compliance and rate limits still apply.

    5. A Structured Knowledge Hub: Plain Text Files as the Control Panel

    A chat interface is good for triggering work and bad at carrying structured information. As the number of tasks grows, chat history quickly becomes a source of noise and information overload. A more reliable approach is a local plain-text note library as the knowledge hub: the agent writes daily summaries, schedules, to-do lists, and stage conclusions as well-formed marked-up text files, organized into directories by date and topic — human-readable, version-controllable, and full-text searchable.

    A recommended minimal convention: a unified frontmatter block recording date, tags, and source; a single source of truth, where one conclusion is maintained in exactly one place and referenced by link elsewhere; sortable names, for example YYYY-MM-DD-topic; and a change trail that history can be inspected through version control.

    1. ---
    2. date: 2026-08-26
    3. tags: [daily, summary]
    4. source: agent
    5. ---
    6. ## Conclusions Today
    7. - The metrics aggregation task is now scripted; average daily calls dropped significantly
    8. ## To-Do
    9. - [ ] Review the on-device allowlist of actions

    After two or three weeks of continuously feeding this layer, the agent’s model of the user’s rhythm becomes noticeably more accurate, and it starts producing structured output proactively instead of waiting to be asked. The payoff of this layer is making implicit context explicit, so knowledge becomes transferable and auditable.

    6. Skill Packaging: Turning Repeated Friction into Reusable Capability

    The last piece is methodological. Skill packaging means identifying friction points that recur in daily work — periodic report reconciliation, inventory and meal pairing, expense receipt organization, information aggregation sweeps — and encapsulating each class of friction as a skill module with clear boundaries and explicit inputs and outputs.

    A qualified skill has four elements: trigger conditions, an input contract, execution steps, and acceptance criteria. Anything deterministic in the steps is pushed down into code; only the parts that require judgment call the model. Acceptance criteria should be written as automatically executable assertions, such as field completeness, numeric ranges, and format validity.

    1. def skill_expense_audit(receipts):
    2. assert all(r.amount >= 0 for r in receipts) # acceptance: valid amounts
    3. rows = [normalize(r) for r in receipts] # deterministic processing
    4. summary = call_model("mid_model", summarize(rows)) # model only for judgment
    5. return {"rows": rows, "summary": summary}

    The real return on skill packaging is freed-up cognitive bandwidth: people stop repeating mechanical judgments and focus on defining goals and acceptance criteria. The skill library itself becomes a reusable asset — migrating to a new scenario only requires swapping the input contract.

    7. Rollout Path and Risk Controls

    A four-step progression works well. Step one, externalize memory: move state from the session into a database first, since this step pays off fastest and carries the lowest risk. Step two, layer cost: build routing, caching, and a budget circuit breaker. Step three, always-on at the edge or on-device: start with read-only events and open write operations gradually, keeping human confirmation at every step. Step four, accumulate skills: package high-frequency flows one by one and fill in automated acceptance checks.

    Three bottom lines hold for risk control: no plaintext credentials, external actions must be rollback-able, and the full chain must be observable. If cloud hosting is involved, a combination of general cloud capabilities works — a container platform to host the execution body, object storage to hold structured output, logging and monitoring with alerting for runtime observability, and a message queue to decouple events. That leaves stability and elasticity to the infrastructure and keeps business determinism in the skill layer. In general engineering practice on cloud platforms such as Baidu AI Cloud, this same “externalized state + layered scheduling + observability” combination is a common pattern.

    In the end, agent maturity does not depend on how strong the model is. It depends on three things: whether state is persistent, whether execution is deterministic, and whether cost is controllable. Make those three into infrastructure, and high-frequency tasks genuinely settle into low-cost deterministic automation.