Skip to content
Agent Field Notes
Practice topicsFilter practice questions by topic.All practice →
knowledge unit 25AdvancedSystem designAbout 25 minutes

Understand → Implement → Debug → Design

Separating state, execution and governance

Analyze logs, context, execution, credentials, tool discovery and joint releases without mistaking hosted recovery for business exactly-once.

HarnessSession logSandboxTool searchSkillsHooks

Knowledge content check2026-10-30 · Check the source of the original question2026-10-30

Which step do you want to learn from this knowledge point?

Select the starting point based on the current basis, or you can go deeper one by one. When you encounter an unfamiliar concept, go back to the core principles first; use the knowledge exercises to check your understanding when you are finished.

Understand first

New to this knowledge point

Complete the prerequisite concepts, read the principles and counterexamples, and then explain why in your own words.

Start with core principles →

Implement next

Prepare to write the principles into code

Understand implementation steps and boundaries, complete small tasks, and check results against acceptance requirements.

Reading implementation and trade-offs →

Debug failures

Need to handle failures and changes in conditions

Follow the continuous questioning to locate the failure premise, and then compare the migration cases to explain how the plan should be adjusted.

Continue to delve deeper into the problem →

Compare designs

Need to design or review plans

Combine engineering deductions and senior self-evaluation standards to explain the applicable conditions, costs and alternatives of the plan.

Analyze engineering scenarios →
Knowledge unit directory

LEARN · PRACTICE · REFLECT

Knowledge learning and personal records

My notes and review ↗

First read along the principles, Q&A and migration cases. When you need to check your understanding, switch to reinforcement exercises or start personal recording.

Answers and personal notes

Each modified commit will be kept as an independent history. Your level of mastery is up to you to evaluate yourself against the standards.

Core concept · Separating state, execution and governance

Understand the core principles first

Preparatory concepts:Task contracts and independent acceptance, Handoff ownership and permission, Idempotency and unknown-outcome boundaries

Separate disposable computation from authoritative facts; constrain actual actions with current authority, stable intent and independent receipts, and evolve model and orchestration together.

Visual guide · Disposable execution surrounds durable business facts

Disposable execution surrounds durable business facts

The harness rebuilds context from durable records. Optional compute grants no authority; current gateway checks and bound receipts control actual effects. Select the figure to open it at full size.

A session can outlive a context window while workspace bytes disappear; a harness can restart after a merchant write has committed. Recovery is therefore reconciliation through record owners, not one retry button. Dynamic loading, programmatic reads and reusable skills change efficiency and behavior, and must be designed with authority, budgets and release manifests. The course code verifies one narrow window; production choices still need real integration and controlled workload comparisons.

Check understanding with a question

How should a long-running harness separate replaceable controllers, durable sessions and controlled execution?

Compare with the reference answer

Keep governed events in a session, rebuild lossy context in a replaceable harness, add execution only when needed, enforce current permissions/approval in the business gateway and confirm effects through the merchant ledger. Reconcile original operations rather than replaying writes. Keep real secrets outside generated-code environments. Authorize and budget every dynamic/programmatic call; pin skills/plugins/hooks and instruction precedence. Evaluate model+harness jointly and simplify one mechanism at a time; rollback cannot erase in-flight semantics or business facts.

Implementation and trade-offs

Start from the irreversible business boundary

For tenant A/order o-17, the target is one authorized return request, not a model message saying “done”. Keep the merchant receipt as the authority for that effect. Store intent, transport attempts and observations in an external session log, while a replaceable harness creates a bounded working context. Store durable artifacts independently of an executor's workspace.

A worker replacement reads the log, obtains a new execution epoch, verifies current authority and loads the pinned release. It must reconcile any unknown write under the original operation_id. A new event_id identifies a new observation; a model call_id correlates a model tool exchange; a new attempt_id identifies a transport attempt. None of these replaces the merchant's deduplication identity. The receiving service must enforce whichever epoch or stable-operation contract the design relies on.

Route computation without distributing credentials or authority

A sandbox supplies compute, files and dependencies when the task needs them; a read-only service workflow may need no sandbox. Keep the durable session, rebuild recipe and retained artifact digests outside disposable compute. Keep real credentials in an external vault or application-side signer and expose only bounded operations. Network access and credential injection have different allowlists. A placeholder design does not make local signing possible and does not prevent abuse of an allowed action; current authorization still matters.

Tool search selects definitions, not permission. Programmatic orchestration can batch independent reads and filter large results before context admission, but every dispatched call still needs authorization and pre-dispatch budget accounting. Bound total attempts, concurrency, input/output bytes, active time and artifact size. Do not fan out many writes and then use cancellation as if it could undo them.

As checked on 2026-10-30, OpenAI's guide distinguishes deferred function loading from Agents API MCP discovery. Follow the selected API, rather than copying Responses API configuration into a different runtime. These product mechanisms do not impose this lesson's application event schema.

Treat skills, plugins and hooks as executable release inputs

Record actual archive/content digests, loaded instruction sources and documented precedence. A plugin version label can point at changed bytes unless immutable resolution is enforced. Review hook executables, outbound/tool permissions, deadlines and failure behavior. An async after-action hook cannot block an action already committed. A skill cannot authorize itself, and a model-readable instruction file is not an OS capability boundary. If a permission hook can approve actions in the chosen runtime, it belongs in the trusted policy surface.

Approval binds the exact action, resource, current policy/release interpretation, approver and expiry. Changing a hook, skill or model while waiting requires an explicit compatibility decision; preserving an approval's string ID does not establish preserved meaning.

Make model+harness a joint release

Compare old-model/old-harness, new-model/old-harness and new-model/simplified-harness on the same task identities, limits and independently checked business outcomes. Predeclare non-negotiable rejection conditions and thresholds for quality, full-task latency and cost; retain unknowns and failures in denominators. Remove a context reset or extra review loop only after an ablation shows its target failure is absent under relevant conditions. Keep independent authority and business checks.

For rollback, route new work to the old release and pin or explicitly migrate in-flight tasks. An already created merchant return remains created. Query original operations before compensation; code rollback is not business reversal.

The supplied program verifies local persistent identities across separate invocations and deterministic receipt reconciliation only. Hosted recovery, real model behavior, hostile-code containment and multi-host correctness remain untested integration work.

Complete local example and verification · 2026-10-30

Save as harness_architecture_demo.py; run prepare then recover twice. Complete commands, observed outputs and boundaries are in the linked implementation layer. This is a one-host, two-SQLite-file service fixture without a model, network, authorization service or actual sandbox.

Save the following complete source as harness_architecture_demo.py. Use a fresh architecture-work directory and run each command separately. This exact source and these three separate process invocations were verified on 2026-10-30 with Python 3.14.7 and SQLite 3.53.4. The first process intentionally stops normally before receipt logging; this is not a measured crash or network failure.

Local event/operation identity recovery example

import json
import sqlite3
import sys
from pathlib import Path

def canonical(value):
    return json.dumps(value, sort_keys=True, separators=(",", ":"))

class SessionLog:
    def __init__(self, path):
        self.db = sqlite3.connect(path)
        self.db.execute("CREATE TABLE IF NOT EXISTS events("
                        "seq INTEGER PRIMARY KEY AUTOINCREMENT,"
                        "event_id TEXT UNIQUE NOT NULL,kind TEXT NOT NULL,"
                        "operation_id TEXT NOT NULL,payload TEXT NOT NULL)")
        self.db.commit()

    def append(self, event_id, kind, operation_id, payload):
        body = canonical(payload)
        with self.db:
            self.db.execute("BEGIN IMMEDIATE")
            old = self.db.execute(
                "SELECT kind,operation_id,payload FROM events WHERE event_id=?",
                (event_id,)).fetchone()
            if old is not None:
                if old != (kind, operation_id, body):
                    raise ValueError("event_identity_conflict")
                return "replayed"
            self.db.execute(
                "INSERT INTO events(event_id,kind,operation_id,payload) VALUES(?,?,?,?)",
                (event_id, kind, operation_id, body))
        return "committed"

    def intents(self):
        return self.db.execute(
            "SELECT operation_id,payload FROM events WHERE kind='intent' ORDER BY seq"
        ).fetchall()

    def count(self):
        return self.db.execute("SELECT COUNT(*) FROM events").fetchone()[0]

class MerchantFixture:
    def __init__(self, path):
        self.db = sqlite3.connect(path)
        self.db.execute("CREATE TABLE IF NOT EXISTS operations("
                        "operation_id TEXT PRIMARY KEY,payload TEXT NOT NULL,"
                        "receipt TEXT UNIQUE NOT NULL)")
        self.db.commit()

    def create(self, operation_id, payload):
        body = canonical(payload)
        with self.db:
            self.db.execute("BEGIN IMMEDIATE")
            old = self.db.execute(
                "SELECT payload,receipt FROM operations WHERE operation_id=?",
                (operation_id,)).fetchone()
            if old is not None:
                if old[0] != body:
                    raise ValueError("operation_identity_conflict")
                return old[1]
            receipt = "r-" + operation_id
            self.db.execute("INSERT INTO operations VALUES(?,?,?)",
                            (operation_id, body, receipt))
        return receipt

    def lookup(self, operation_id, payload):
        row = self.db.execute(
            "SELECT payload,receipt FROM operations WHERE operation_id=?",
            (operation_id,)).fetchone()
        if row is None:
            return None
        if row[0] != canonical(payload):
            raise ValueError("receipt_binding_conflict")
        return row[1]

    def count(self):
        return self.db.execute("SELECT COUNT(*) FROM operations").fetchone()[0]

phase, directory = sys.argv[1:]
root = Path(directory)
root.mkdir(parents=True, exist_ok=True)
if phase == "prepare" and any(root.iterdir()):
    raise FileExistsError("use_empty_directory")
session = SessionLog(root / "session.sqlite")
merchant = MerchantFixture(root / "merchant.sqlite")
try:
    if phase == "prepare":
        payload = {"tenant": "A", "order": "o-17", "quantity": 1}
        session.append("intent-17", "intent", "return-17", payload)
        merchant.create("return-17", payload)
        result = {"phase": "interrupted", "events": session.count(),
                  "effects": merchant.count()}
        # Stop before recording the receipt. A later command is a new process.
    elif phase == "recover":
        status = "unknown"
        outcome = None
        for operation_id, body in session.intents():
            receipt = merchant.lookup(operation_id, json.loads(body))
            if receipt is None:
                continue  # An empty query alone does not authorize another write.
            outcome = session.append("receipt-" + operation_id, "receipt",
                                     operation_id, {"receipt": receipt})
            status = "completed"
        result = {"phase": status, "append": outcome, "events": session.count(),
                  "effects": merchant.count()}
    else:
        raise ValueError("phase")
    print(json.dumps(result, sort_keys=True))
finally:
    session.db.close()
    merchant.db.close()
python3 harness_architecture_demo.py prepare architecture-work
python3 harness_architecture_demo.py recover architecture-work
python3 harness_architecture_demo.py recover architecture-work

Actual observed output, in command order:

{"effects": 1, "events": 1, "phase": "interrupted"}
{"append": "committed", "effects": 1, "events": 2, "phase": "completed"}
{"append": "replayed", "effects": 1, "events": 2, "phase": "completed"}

Engineering deduction

scene
Tenant A's return commits at the merchant; the harness ends before logging its receipt, and a replacement worker also sees changed plugin configuration.
design decisions
Reconcile the original merchant operation and append its bound receipt; keep the original release or pause for explicit migration, rather than redoing the write or interpreting old approval under new hooks.
Verify target
The complete local example observes events 1→2→2 and effects always 1 across three invocations, validating only its bounded identity/recovery behavior.
applicable boundary
No hosted product call, real model, remote business service, multi-host behavior, hostile-code isolation or learner score is established; file administrators are outside the append API's protection.

Continuous questions and answers

Continue reading along with the premises and constraints of the problem. Understand the reference answers first, then try to put away the answers and explain the cause and effect and trade-offs in your own words.

Draw inferences from one example: If the conditions change, how to deduce it?

First find out the conditions for change, and then determine which premises in the original plan still hold true. The following cases are teaching deductions to facilitate the transfer of principles to new problems.

A coding workspace disappears

Changing conditions:Change from support-service reads to code edits and build artifacts; the authoritative output is now a protected branch and artifact-store record.

Extended question:The session survives but the sandbox is gone. Which work actually survived?

Derivation and reference solutions

Verify base commit, patch/artifact digests and protected remote records; rebuild the workspace from a pinned recipe. Descriptions do not restore unsaved bytes. Separate safely repeatable read-only builds from PR/publication writes. Keep credentials outside generated-code execution and bind approval to the concrete diff/target version. Session completed is not a build or publication receipt.

The principles that remain unchanged:Reconcile recovery through authoritative records; working context creates neither lost artifacts nor authority.

Support without a sandbox

Changing conditions:The task needs three permitted remote reads and one approved write tool, with no local file or code requirement.

Extended question:Must every session receive a container?

Derivation and reference solutions

No. A harness can use controlled remote tools directly, avoiding unnecessary provisioning latency and operational surface. Compare sequential/bounded parallel reads and discovery overhead. The write still checks current authority and approval at the business gateway and preserves original-key reconciliation. Add controlled compute only when large-result processing or files require it; no sandbox does not mean no state, authentication or accounting.

The principles that remain unchanged:Choose execution environments from task requirements while preserving business boundaries and evidence.

Easy to make mistakes

  • Treat a compacted summary as session truth or authorization
  • Change the business key when replacing a worker
  • Treat discovery or plugin installation as execution permission
  • Treat an async hook as a pre-action gate or an environment variable as secret isolation
  • Select costs from successes only or treat code rollback as business reversal

References

Official sources checked 2026-10-30; the local SQLite program ran as three separate process invocations. Event envelopes, release gates and ADRs are teaching designs, not vendor guarantees or a completed production deployment. New Q&A and migration cases are added for principle explanation, and source verification and case operation verification are recorded separately.

Check how far you understand

After reading, you can explain the principles, boundaries, and trade-offs against these standards. It is up to you to evaluate your mastery; if further verification is needed, complete the small tasks below.

Basic standards met
Assign session/context/execution/business-ledger ownership and reject blind retry under a new key.
Intermediate and advanced signals
Specify event identity, artifact recovery, credential proxy, dynamic-tool budgets and hook timing with failure-window evidence.
Senior criteria
Choose hosted/self-managed ownership for a concrete workload, define joint-release/ablation quality-cost-recovery gates and handle in-flight versions and irreversible business outcomes.

Hands-on verificationComplete on demand · Suggestions90 minutes

Run the linked complete program, inspect persistent records and add the three negative controls. Write incident timelines for unknown write, lost artifact and hook change, then a one-page hosted/self-managed and joint-release ADR. Separate executed evidence from proposed design and leave untested integrations pending.

Expand acceptance requirements and checkpoints
  • Retain three outputs and personal source digest; reject both identity conflicts and add no effect on empty lookup
  • Distinguish five identities, current authority and immutable approval binding
  • Compare two viable architectures with cost/latency/recovery and dynamic-tool/skill/hook governance
  • Use the same task denominator for model/harness candidates and preserve external facts on rollback

Key inspections

  • Separate session, context, artifacts and merchant ledger
  • Distinguish event, attempt, model-call and operation identity
  • Separate credential proxy, current authorization and on-demand execution
  • Pin dynamic-tool and skill/hook release inputs
  • Define joint evaluation, ablation, in-flight migration and rollback gates