Originally published on tamiz.pro.
AI coding agents are becoming autonomous collaborators, but their most important infrastructure is often missing. They can edit files, run commands, and call APIs, yet each session often starts from the same blank slate. The agent forgets architectural decisions, repeats completed work, and conflicts with parallel tasks because no shared, durable model of the workspace exists.
The answer is not simply a larger context window. It is an agent workspace protocol: a local-first contract for representing tasks, project state, observations, and coordination between agents. This deep dive explains the architecture of such a protocol, why shared state matters more than chat history, and how to build a working implementation in Python and SQLite.
- 1. The Context Loss Problem
- 2. What the Agent Workspace Protocol Provides
- 3. Core Architecture
- 4. Designing the State Model
- 5. Building a Local-First Workspace
- 6. Implementing the Task Queue
- 7. Implementing Durable Memory
- 8. Connecting an AI Coding Agent
- 9. Concurrency and Coordination
- 10. Git Integration and Recovery
- 11. Production Best Practices
- 12. Frequently Asked Questions
1. The Context Loss Problem
A typical AI coding workflow looks like this:
- A developer asks an agent to investigate a performance issue.
- The agent reads several files and discovers that a background worker was intentionally moved to a separate process.
- The session ends.
- A new agent session receives the task, "optimize the worker startup time."\n5. The agent sees the worker implementation and "optimizes" it by merging it back into the request path.
The second agent did not fail because of a bad prompt. It failed because the first agent's discovery existed only in a transient transcript.
This problem worsens with multiple agents. Suppose three agents work concurrently:
- Agent A migrates the authentication module.
- Agent B adds tests for the authentication module.
- Agent C updates deployment documentation.
Without coordination, Agent B may test the old interface while Agent A is editing it. Agent C may document behavior that no longer exists. A shared chat history would not solve this reliably either: transcripts are unstructured, grow quickly, and provide no atomic mechanism for claiming work.
Why context windows are not a workspace
A context window is a read buffer, not a coordination system. It has four structural limitations:
| Limitation | Consequence |
|---|---|
| Session-scoped | Critical information disappears when the session ends |
| Linear | Unrelated observations compete for attention |
| Implicit | The agent must infer what matters from raw conversation |
| Non-transactional | Two agents cannot atomically claim or update a task |
A workspace flips these properties. It stores facts as typed records, tasks as queue entries, and file changes as versioned events. Agents can query only what they need, recover state after restarts, and coordinate through explicit operations.
A durable workspace turns "what did I tell the agent?" into "what does the project know?"
2. What the Agent Workspace Protocol Provides
The Agent Workspace Protocol is not a universal standard yet; it is a practical design pattern for agent infrastructure. At its core, it defines how agents exchange information through a workspace directory or service.
A useful protocol has four layers:
2.1 Identity and capability
Every agent needs a stable identity, a declared role, and explicit capabilities. An identity might be backend-implementer, while its capabilities might include python, sql, and pytest.
This enables the scheduler to route tasks appropriately and prevents an agent from silently performing work outside its remit.
2.2 State
State includes both project facts and agent observations:
- Architecture decisions
- Conventions and constraints
- Completed and pending work
- Test results
- Failed approaches
- External service information
State must be local-first: the canonical copy lives on the developer's machine or in a repository, and remote synchronization is optional.
2.3 Task coordination
Agents need a queue with explicit lifecycle states, atomic claims, leases, and dependencies. A task is not a prompt. It is a structured unit of work with acceptance criteria, an owner, and a completion signal.
2.4 Auditability
Every meaningful action should leave a trace. When an agent changes a file, claims a task, records a decision, or encounters an error, that event should be attributable and replayable.
Without the audit layer, shared state becomes an opaque cache that nobody trusts.
3. Core Architecture
The architecture separates durable data from ephemeral execution:
┌─────────────────────────┐
│ Human / CLI / IDE │
└────────────┬────────────┘
│
┌────────────▼────────────┐
│ Agent Runtime Layer │
│ planner, tools, LLM API │
└────────────┬────────────┘
│
┌─────────────────▼─────────────────┐
│ Agent Workspace Protocol │
│ │
│ ┌──────────┐ ┌──────────────┐ │
│ │ Tasks │ │ Memory │ │
│ └────┬─────┘ └──────┬───────┘ │
│ │ │ │
│ ┌────▼─────┐ ┌──────▼───────┐ │
│ │ Events │ │ File Locks │ │
│ └──────────┘ └──────────────┘ │
└─────────────────┬─────────────────┘
│
┌────────────▼────────────┐
│ Local Repository + SQLite│
└─────────────────────────┘
│
optional remote sync / CI
The agent runtime remains replaceable. Claude Code, Codex, Aider, Continue, or a custom agent can all use the same workspace contract.
The protocol boundary
The workspace should expose operations, not raw database tables. A minimal interface looks like this:
class Workspace(Protocol):
def enqueue(self, task: TaskInput) -> Task: ...
def claim(self, agent_id: str, capabilities: list[str]) -> Task | None: ...
def complete(self, task_id: str, agent_id: str, summary: str) -> None: ...
def remember(self, agent_id: str, memory: MemoryInput) -> MemoryRecord: ...
def recall(self, query: str, limit: int = 10) -> list[MemoryRecord]: ...
def log_event(self, event: EventInput) -> None: ...
This boundary matters because it lets you replace SQLite with PostgreSQL, add a remote relay, or swap in a vector store without rewriting every agent.
4. Designing the State Model
A good state model separates four concerns that are often incorrectly merged into one "notes" table.
4.1 Tasks represent executable work
A task should include:
- A stable identifier
- A title and detailed description
- Acceptance criteria
- Required capabilities
- Dependencies
- Lifecycle status
- Owner and lease expiration
- Priority
The acceptance criteria are particularly important. They let another agent verify the result instead of trusting a prose summary.
4.2 Memory represents retained knowledge
Memory entries are scoped and typed:
{
"scope": "architecture",
"key": "worker-isolation",
"content": "Background workers run in separate processes to avoid blocking the request path.",
"source": {"type": "file", "path": "docs/architecture.md"},
"confidence": 0.95,
"expires_at": null
}
Useful scopes include:
-
architecture: structural decisions -
convention: coding standards -
constraint: non-negotiable project rules -
discovery: findings from investigation -
failure: approaches that did not work -
environment: local tooling and service details
4.3 Events represent history
Events are append-only facts such as task.claimed, memory.created, file.modified, or test.failed. They support debugging, replay, and derived metrics.
4.4 Artifacts represent outputs
Large outputs—logs, patches, test reports, and generated files—should live as artifacts referenced by events. The database should hold metadata and pointers, not megabytes of JSON.
5. Building a Local-First Workspace
We will implement a small, working protocol using Python's standard library plus SQLite. The workspace lives inside the repository under .agent/, making it easy to inspect, back up, and optionally version.
5.1 Prerequisites
- Python 3.11 or newer
- A Git repository
-
sqlite3is included with Python; no additional package is required
5.2 Project layout
my-project/
├── .agent/
│ └── workspace.db
├── src/
├── tests/
└── pyproject.toml
The database is local-first, but it should usually be ignored by Git because it contains machine-specific leases and transient state:
.agent/
Durable knowledge that belongs in the repository—such as architecture decisions—can be exported to Markdown and committed separately.
5.3 Database schema
Create workspace.py:
from __future__ import annotations
import json
import sqlite3
import time
import uuid
from dataclasses import asdict, dataclass
from pathlib import Path
from typing import Any, Protocol
@dataclass(frozen=True)
class Task:
id: str
title: str
description: str
acceptance_criteria: list[str]
required_capabilities: list[str]
status: str
owner: str | None
lease_expires_at: float | None
priority: int
@dataclass(frozen=True)
class MemoryRecord:
id: str
scope: str
key: str
content: str
source: dict[str, Any]
confidence: float
created_at: float
class Workspace(Protocol):
def enqueue(self, title: str, description: str, **kwargs: Any) -> Task: ...
def claim(self, agent_id: str, capabilities: list[str]) -> Task | None: ...
def complete(self, task_id: str, agent_id: str, summary: str) -> None: ...
def remember(self, scope: str, key: str, content: str, **kwargs: Any) -> MemoryRecord: ...
def recall(self, scope: str | None = None, limit: int = 10) -> list[MemoryRecord]: ...
def log_event(self, kind: str, actor: str, payload: dict[str, Any]) -> None: ...
class SQLiteWorkspace:
def __init__(self, root: Path) -> None:
self.root = root.resolve()
self.agent_dir = self.root / ".agent"
self.agent_dir.mkdir(parents=True, exist_ok=True)
self.db_path = self.agent_dir / "workspace.db"
self._initialize()
def _connect(self) -> sqlite3.Connection:
conn = sqlite3.connect(self.db_path, timeout=10, isolation_level=None)
conn.row_factory = sqlite3.Row
conn.execute("PRAGMA journal_mode=WAL")
conn.execute("PRAGMA foreign_keys=ON")
conn.execute("PRAGMA busy_timeout=10000")
return conn
def _initialize(self) -> None:
with self._connect() as conn:
conn.executescript(
"""
CREATE TABLE IF NOT EXISTS tasks (
id TEXT PRIMARY KEY,
title TEXT NOT NULL,
description TEXT NOT NULL,
acceptance_criteria TEXT NOT NULL,
required_capabilities TEXT NOT NULL,
dependencies TEXT NOT NULL DEFAULT '[]',
status TEXT NOT NULL DEFAULT 'pending',
owner TEXT,
lease_expires_at REAL,
priority INTEGER NOT NULL DEFAULT 0,
created_at REAL NOT NULL
);
CREATE TABLE IF NOT EXISTS memory (
id TEXT PRIMARY KEY,
scope TEXT NOT NULL,
key TEXT NOT NULL,
content TEXT NOT NULL,
source TEXT NOT NULL,
confidence REAL NOT NULL DEFAULT 1.0,
created_at REAL NOT NULL,
expires_at REAL
);
CREATE INDEX IF NOT EXISTS idx_memory_scope
ON memory(scope, created_at DESC);
CREATE TABLE IF NOT EXISTS events (
id INTEGER PRIMARY KEY AUTOINCREMENT,
kind TEXT NOT NULL,
actor TEXT NOT NULL,
payload TEXT NOT NULL,
created_at REAL NOT NULL
);
CREATE INDEX IF NOT EXISTS idx_events_created
ON events(created_at DESC);
"""
)
def enqueue(self, title: str, description: str, **kwargs: Any) -> Task:
task_id = kwargs.pop("task_id", None) or str(uuid.uuid4())
criteria = kwargs.pop("acceptance_criteria", [])
required = kwargs.pop("required_capabilities", [])
dependencies = kwargs.pop("dependencies", [])
priority = kwargs.pop("priority", 0)
if kwargs:
raise TypeError(f"Unsupported task fields: {', '.join(kwargs)}")
now = time.time()
with self._connect() as conn:
conn.execute(
"""
INSERT INTO tasks (
id, title, description, acceptance_criteria,
required_capabilities, dependencies, priority, created_at
) VALUES (?, ?, ?, ?, ?, ?, ?, ?)
""",
(
task_id,
title,
description,
json.dumps(criteria),
json.dumps(required),
json.dumps(dependencies),
priority,
now,
),
)
self.log_event("task.enqueued", "system", {"task_id": task_id})
return self.get_task(task_id)
def get_task(self, task_id: str) -> Task:
with self._connect() as conn:
row = conn.execute(
"SELECT * FROM tasks WHERE id = ?", (task_id,)
).fetchone()
if row is None:
raise KeyError(f"Unknown task: {task_id}")
return Task(
id=row["id"],
title=row["title"],
description=row["description"],
acceptance_criteria=json.loads(row["acceptance_criteria"]),
required_capabilities=json.loads(row["required_capabilities"]),
status=row["status"],
owner=row["owner"],
lease_expires_at=row["lease_expires_at"],
priority=row["priority"],
)
def remember(
self,
scope: str,
key: str,
content: str,
**kwargs: Any,
) -> MemoryRecord:
source = kwargs.pop("source", {})
confidence = kwargs.pop("confidence", 1.0)
expires_at = kwargs.pop("expires_at", None)
if kwargs:
raise TypeError(f"Unsupported memory fields: {', '.join(kwargs)}")
record = MemoryRecord(
id=str(uuid.uuid4()),
scope=scope,
key=key,
content=content,
source=source,
confidence=confidence,
created_at=time.time(),
)
with self._connect() as conn:
conn.execute(
"""
INSERT INTO memory (
id, scope, key, content, source,
confidence, created_at, expires_at
) VALUES (?, ?, ?, ?, ?, ?, ?, ?)
""",
(
record.id,
scope,
key,
content,
json.dumps(source),
confidence,
record.created_at,
expires_at,
),
)
self.log_event(
"memory.created",
"system",
{"memory_id": record.id, "scope": scope, "key": key},
)
return record
def recall(
self,
scope: str | None = None,
limit: int = 10,
) -> list[MemoryRecord]:
if limit < 1 or limit > 100:
raise ValueError("limit must be between 1 and 100")
query = "SELECT * FROM memory"
params: list[Any] = []
if scope is not None:
query += " WHERE scope = ?"
params.append(scope)
query += " ORDER BY created_at DESC LIMIT ?"
params.append(limit)
with self._connect() as conn:
rows = conn.execute(query, params).fetchall()
return [
MemoryRecord(
id=row["id"],
scope=row["scope"],
key=row["key"],
content=row["content"],
source=json.loads(row["source"]),
confidence=row["confidence"],
created_at=row["created_at"],
)
for row in rows
]
def log_event(
self,
kind: str,
actor: str,
payload: dict[str, Any],
) -> None:
with self._connect() as conn:
conn.execute(
"""
INSERT INTO events (kind, actor, payload, created_at)
VALUES (?, ?, ?, ?)
""",
(kind, actor, json.dumps(payload), time.time()),
)
This is deliberately boring infrastructure. The important design choice is that memory and tasks are separate resources with separate lifecycles.
6. Implementing the Task Queue
A queue without atomic claims is just a list of suggestions. SQLite supports transactional updates that let multiple processes compete safely.
Add these methods to SQLiteWorkspace:
def claim(
self,
agent_id: str,
capabilities: list[str],
lease_seconds: int = 900,
) -> Task | None:
now = time.time()
lease_until = now + lease_seconds
with self._connect() as conn:
conn.execute("BEGIN IMMEDIATE")
try:
rows = conn.execute(
"""
SELECT id, required_capabilities, dependencies
FROM tasks
WHERE status = 'pending'
AND (lease_expires_at IS NULL OR lease_expires_at < ?)
ORDER BY priority DESC, created_at ASC
""",
(now,),
).fetchall()
selected_id = None
for row in rows:
required = set(json.loads(row["required_capabilities"]))
if not required.issubset(capabilities):
continue
dependencies = json.loads(row["dependencies"])
if dependencies:
placeholders = ",".join("?" for _ in dependencies)
blocked = conn.execute(
f"""
SELECT COUNT(*) FROM tasks
WHERE id IN ({placeholders})
AND status != 'completed'
""",
dependencies,
).fetchone()[0]
if blocked:
continue
selected_id = row["id"]
break
if selected_id is None:
conn.execute("COMMIT")
return None
cursor = conn.execute(
"""
UPDATE tasks
SET status = 'in_progress',
owner = ?,
lease_expires_at = ?
WHERE id = ?
AND status = 'pending'
AND (lease_expires_at IS NULL OR lease_expires_at < ?)
""",
(agent_id, lease_until, selected_id, now),
)
if cursor.rowcount != 1:
conn.execute("ROLLBACK")
return None
conn.execute("COMMIT")
except Exception:
conn.execute("ROLLBACK")
raise
self.log_event(
"task.claimed",
agent_id,
{"task_id": selected_id, "lease_expires_at": lease_until},
)
return self.get_task(selected_id)
def heartbeat(
self,
task_id: str,
agent_id: str,
lease_seconds: int = 900,
) -> None:
with self._connect() as conn:
cursor = conn.execute(
"""
UPDATE tasks
SET lease_expires_at = ?
WHERE id = ?
AND owner = ?
AND status = 'in_progress'
""",
(time.time() + lease_seconds, task_id, agent_id),
)
if cursor.rowcount != 1:
raise PermissionError("Task is not owned by this agent")
def complete(
self,
task_id: str,
agent_id: str,
summary: str,
) -> None:
with self._connect() as conn:
cursor = conn.execute(
"""
UPDATE tasks
SET status = 'completed',
owner = ?,
lease_expires_at = NULL
WHERE id = ?
AND owner = ?
AND status = 'in_progress'
""",
(agent_id, task_id, agent_id),
)
if cursor.rowcount != 1:
raise PermissionError("Task is not owned by this agent")
self.log_event(
"task.completed",
agent_id,
{"task_id": task_id, "summary": summary},
)
def fail(
self,
task_id: str,
agent_id: str,
reason: str,
) -> None:
with self._connect() as conn:
cursor = conn.execute(
"""
UPDATE tasks
SET status = 'pending',
owner = NULL,
lease_expires_at = NULL
WHERE id = ?
AND owner = ?
AND status = 'in_progress'
""",
(task_id, agent_id),
)
if cursor.rowcount != 1:
raise PermissionError("Task is not owned by this agent")
self.log_event(
"task.failed",
agent_id,
{"task_id": task_id, "reason": reason},
)
The BEGIN IMMEDIATE transaction acquires SQLite's write lock before reading candidates. This prevents two agents from selecting the same task and then racing to update it.
Why leases instead of permanent locks
A permanent task lock is fragile. The owning process may crash, be terminated, or lose network connectivity. A lease expires automatically, allowing another agent to retry the task.
Long-running agents should call heartbeat() periodically. The lease duration should exceed the maximum interval between heartbeats, not the expected task duration.
7. Implementing Durable Memory
The recall() method above uses scoped retrieval, which is predictable and inexpensive. As memory grows, you will likely want hybrid retrieval: exact scope filters, lexical matching, and optional semantic embeddings.
A practical progression is:
- Scoped lookup for conventions and architecture decisions
- Full-text search for incident-specific notes
- Vector similarity for semantically related discoveries
- Recency and confidence ranking to resolve noisy entries
SQLite supports FTS5:
def _initialize(self) -> None:
with self._connect() as conn:
# Existing schema omitted for brevity.
conn.executescript(
"""
CREATE VIRTUAL TABLE IF NOT EXISTS memory_fts
USING fts5(
memory_id UNINDEXED,
scope,
key,
content,
tokenize = 'porter unicode61'
);
"""
)
When creating a memory record, insert the corresponding FTS row in the same transaction:
with self._connect() as conn:
conn.execute("BEGIN IMMEDIATE")
try:
conn.execute(
"""
INSERT INTO memory (
id, scope, key, content, source,
confidence, created_at, expires_at
) VALUES (?, ?, ?, ?, ?, ?, ?, ?)
""",
(
record.id,
scope,
key,
content,
json.dumps(source),
confidence,
record.created_at,
expires_at,
),
)
conn.execute(
"""
INSERT INTO memory_fts (memory_id, scope, key, content)
VALUES (?, ?, ?, ?)
""",
(record.id, scope, key, content),
)
conn.execute("COMMIT")
except Exception:
conn.execute("ROLLBACK")
raise
Then add lexical search:
def search(self, query: str, limit: int = 10) -> list[MemoryRecord]:
with self._connect() as conn:
rows = conn.execute(
"""
SELECT m.*
FROM memory_fts f
JOIN memory m ON m.id = f.memory_id
WHERE memory_fts MATCH ?
ORDER BY bm25(memory_fts)
LIMIT ?
""",
(query, limit),
).fetchall()
return [
MemoryRecord(
id=row["id"],
scope=row["scope"],
key=row["key"],
content=row["content"],
source=json.loads(row["source"]),
confidence=row["confidence"],
created_at=row["created_at"],
)
for row in rows
]
Memory should be selective
Do not save every tool result. A useful memory entry is:
- Likely to matter in a future session
- Not already obvious from the repository
- Attached to a stable scope and key
- Traceable to a source
- Clear enough to act on
Examples worth saving:
Architecture: Authentication callbacks run asynchronously.
Constraint: API responses must not expose internal stack identifiers.
Failure: Replacing the connection pool with a global client caused test interference.
Environment: Integration tests require Docker and a local PostgreSQL instance.
Examples usually not worth saving:
The agent listed 14 files in the repository.
A command exited with status 1.
The user asked whether a function was async.
8. Connecting an AI Coding Agent
The workspace should be exposed to the model as a small set of explicit tools. Do not expose arbitrary SQL execution; it defeats the protocol's safety boundary.
A practical tool schema includes:
[
{
"name": "workspace_claim_task",
"description": "Atomically claim the next eligible task for this agent.",
"input_schema": {
"type": "object",
"properties": {
"capabilities": {
"type": "array",
"items": {"type": "string"}
}
},
"required": ["capabilities"]
}
},
{
"name": "workspace_recall",
"description": "Retrieve durable project knowledge before planning work.",
"input_schema": {
"type": "object",
"properties": {
"scope": {"type": "string"},
"query": {"type": "string"},
"limit": {"type": "integer", "minimum": 1, "maximum": 20}
}
}
},
{
"name": "workspace_remember",
"description": "Persist a durable discovery or decision.",
"input_schema": {
"type": "object",
"properties": {
"scope": {"type": "string"},
"key": {"type": "string"},
"content": {"type": "string"},
"confidence": {"type": "number", "minimum": 0, "maximum": 1}
},
"required": ["scope", "key", "content"]
}
},
{
"name": "workspace_complete_task",
"description": "Complete an owned task with a verification summary.",
"input_schema": {
"type": "object",
"properties": {
"task_id": {"type": "string"},
"summary": {"type": "string"}
},
"required": ["task_id", "summary"]
}
}
]
The correct agent loop
A workspace-aware agent should follow this sequence:
from dataclasses import asdict
import json
def run_agent(
workspace: SQLiteWorkspace,
agent_id: str,
capabilities: list[str],
llm: object,
) -> None:
while True:
# 1. Recover relevant durable knowledge.
memories = workspace.recall(limit=20)
# 2. Claim work atomically.
task = workspace.claim(agent_id, capabilities)
if task is None:
break
# 3. Build a bounded context from the task and memory.
context = {
"task": asdict(task),
"memory": [asdict(m) for m in memories],
}
# 4. Execute the task through your agent runtime.
result = llm.execute(context) # Your runtime-specific implementation.
# 5. Verify before completion.
if not result.passed:
workspace.fail(task.id, agent_id, result.reason)
continue
# 6. Persist useful discoveries.
for discovery in result.discoveries:
workspace.remember(
scope=discovery.scope,
key=discovery.key,
content=discovery.content,
source={"type": "agent", "agent_id": agent_id},
confidence=discovery.confidence,
)
# 7. Close the task with an auditable result.
workspace.complete(task.id, agent_id, result.summary)
The llm.execute() method is intentionally abstract. It could invoke a model API, run an existing coding agent, or execute a deterministic workflow. The protocol does not depend on a particular model vendor.
Context assembly matters
Retrieving every memory record and placing it in the prompt is not durable context—it is context pollution. Build a compact context package:
- Task description and acceptance criteria
- Matching conventions and constraints
- Architecture decisions relevant to the files involved
- Recent failures involving the same component
- Explicit pointers to source files
Use file paths and identifiers instead of copying entire files into memory. The agent can read the current source when needed.
9. Concurrency and Coordination
Task ownership prevents duplicate work, but it does not prevent semantic conflicts. Two agents can own different tasks that modify the same file.
9.1 File-level locks
Add a resource table and acquire locks when a task touches a path:
CREATE TABLE IF NOT EXISTS resource_locks (
resource TEXT PRIMARY KEY,
task_id TEXT NOT NULL,
owner TEXT NOT NULL,
acquired_at REAL NOT NULL,
expires_at REAL NOT NULL
);
Before editing a file, the agent calls acquire_lock(path, task_id, owner). The operation should be transactional and fail if another live lease owns the resource.
9.2 Scope locks versus file locks
File locks are precise but can be too narrow. If one agent is refactoring a module's public interface, another agent editing a test in the same module may still conflict.
Use hierarchical resource keys:
repo:backend
repo:backend/auth
file:backend/auth/login.py
A shared-read or exclusive-write model can express most requirements:
- Multiple agents may read a scope.
- One agent may write a scope exclusively.
- Acquiring a parent scope conflicts with a child scope.
This is a resource-lock tree, similar to Git's index but independent of Git's commit graph.
9.3 Optimistic concurrency for files
Locks alone are insufficient if an external editor changes a file. Record a content hash when the task begins:
import hashlib
from pathlib import Path
def file_digest(path: Path) -> str:
return hashlib.sha256(path.read_bytes()).hexdigest()
Before writing, compare the current hash with the expected hash. If it differs, the agent must re-read the file and reconcile the change.
For AI-generated patches, this is particularly important. A stale patch can silently overwrite a human fix or another agent's work.
9.4 Dependency-aware execution
Tasks should declare dependencies, but dependency graphs introduce deadlock and cycle risks. The queue implementation above simply skips tasks whose dependencies are incomplete.
Before enqueuing a graph, validate it:
def assert_acyclic(dependencies: dict[str, list[str]]) -> None:
visiting: set[str] = set()
visited: set[str] = set()
def visit(node: str) -> None:
if node in visiting:
raise ValueError(f"Dependency cycle detected at {node}")
if node in visited:
return
visiting.add(node)
for dependency in dependencies.get(node, []):
visit(dependency)
visiting.remove(node)
visited.add(node)
for task_id in dependencies:
visit(task_id)
10. Git Integration and Recovery
The workspace coordinates agents; Git coordinates durable code changes. They solve different problems and should remain complementary.
10.1 Isolate work in branches
Each task should have a predictable branch:
git switch -c agent/<task-id>-<short-slug>
When the task completes:
git add -p
git commit -m "feat: <task title>"
The branch name can be derived from the task ID, making recovery straightforward:
git branch --list 'agent/<task-id>*'
10.2 Do not store the database in Git
SQLite databases are binary, environment-specific, and difficult to merge. Commit durable knowledge in a text format instead:
docs/agent-memory/
├── architecture.md
├── conventions.md
├── constraints.md
└── failures.md
An export command can convert workspace memory into Markdown:
from pathlib import Path
def export_memory(workspace: SQLiteWorkspace, output: Path) -> None:
records = workspace.recall(limit=100)
grouped: dict[str, list[MemoryRecord]] = {}
for record in records:
grouped.setdefault(record.scope, []).append(record)
for scope, items in grouped.items():
path = output / f"{scope}.md"
path.parent.mkdir(parents=True, exist_ok=True)
lines = [f"# {scope.title()}", ""]
for item in items:
lines.append(f"## {item.key}")
lines.append("")
lines.append(item.content)
lines.append("")
if item.source:
lines.append(f"Source: `{item.source}`")
lines.append("")
path.write_text("\n".join(lines), encoding="utf-8")
This gives you two representations with different purposes:
- SQLite: fast, mutable, machine-oriented workspace state
- Markdown: reviewable, versioned, human-oriented project knowledge
10.3 Recover from interrupted agents
When an agent crashes, its task lease eventually expires. Another agent can claim it, but it should first inspect:
- The task's branch
- Uncommitted changes
- Recent workspace events
- Test output stored as an artifact
A recovery routine can surface abandoned work:
def abandoned_tasks(workspace: SQLiteWorkspace) -> list[Task]:
# In a real implementation, query tasks whose lease has expired.
# This helper demonstrates the intended inspection flow.
with workspace._connect() as conn:
rows = conn.execute(
"""
SELECT id FROM tasks
WHERE status = 'in_progress'
AND lease_expires_at < ?
""",
(time.time(),),
).fetchall()
return [workspace.get_task(row["id"]) for row in rows]
The private connection method is shown for brevity; in production, expose a public list_tasks(status=...) method instead.
11. Production Best Practices
11.1 Keep the protocol narrow
Start with five operations:
- Claim a task
- Read relevant memory
- Write a memory record
- Complete or fail a task
- Log an event
Add capabilities only after observing real coordination failures. Every additional tool increases the model's decision surface and the chance of inconsistent state.
11.2 Require verification before completion
A task should not be marked complete because the agent says it is done. Verify acceptance criteria:
- Tests pass
- Type checks pass
- Lint rules pass
- Required files exist
- No forbidden paths changed
Store the verification summary in the completion event. Future agents can use it as evidence rather than repeating the work.
11.3 Separate durable memory from transient observations
Use events for transient observations and memory for durable knowledge. If every tool call becomes memory, retrieval quality collapses.
A useful retention policy is:
- Tasks: retain until archived
- Events: retain for debugging and metrics
- Memory: retain until superseded or expired
- Artifacts: move to object storage or delete after a retention period
11.4 Version the schema
Add a schema version to the workspace metadata:
CREATE TABLE IF NOT EXISTS metadata (
key TEXT PRIMARY KEY,
value TEXT NOT NULL
);
Then write migrations before evolving columns. Agents may be running older clients against the same local database, so backward compatibility matters.
11.5 Treat memory as untrusted input
Memory may contain stale, incorrect, or malicious instructions. It is data about the project, not automatically an authoritative system prompt.
Apply these rules:
- Memory cannot override tool permissions.
- Memory cannot grant shell or network access.
- High-impact actions still require explicit validation.
- Source and confidence fields help distinguish verified decisions from guesses.
11.6 Add observability
Track at least these metrics:
- Task claim latency
- Task completion rate
- Lease expiration rate
- Retry count
- Memory retrieval hit rate
- Verification failure rate
- Conflicts per file
Events provide the raw data. Derived metrics should be computed outside the hot path so logging never blocks task execution.
11.7 Design for remote synchronization carefully
Local-first does not mean local-only. Remote synchronization is useful for CI agents, hosted coding platforms, and team visibility. However, synchronizing a SQLite file is a poor multi-user strategy.
Prefer one of these models:
| Model | Best fit | Trade-off |
|---|---|---|
| SQLite + file sync | One developer, multiple local agents | Conflict handling is manual |
| PostgreSQL service | Multiple machines and users | Requires hosted infrastructure |
| Event log + projections | Offline-first and audit-heavy | More implementation complexity |
| Repository-backed Markdown | Portable, reviewable knowledge | Weak concurrency semantics |
If agents run on separate machines, use a centralized task service while keeping code and large artifacts in Git or object storage.
11.8 Avoid the "memory everything" trap
The strongest workspace is not the one with the most records. It is the one that surfaces the right constraint at the right moment.
A useful retrieval score combines:
score = semantic_similarity
+ scope_match
+ source_reliability
+ confidence
+ recency_weight
- contradiction_penalty
The exact weights are less important than tracking whether retrieved memory actually helped. Instrument the outcome: did the agent avoid a repeated failure? Did it violate a known convention? Did the task complete without human correction?
11.9 Give agents explicit stopping conditions
An agent should stop when:
- No eligible task can be claimed
- Verification fails repeatedly
- Required information is missing
- A conflicting human edit is detected
- The task exceeds its time or token budget
Stopping must update the task state. Silently ending a session leaves an ambiguous lease and blocks progress until expiration.
12. Frequently Asked Questions
How is this different from AGENTS.md or a system prompt?\n
AGENTS.md and system prompts provide static or session-scoped instructions. A workspace provides structured, mutable, transactional state: tasks can be claimed atomically, memories can be queried by scope, and actions can be audited. Static instruction files still help, but they cannot replace coordination and durable state.
Should every AI coding agent use the same workspace database?\n
Locally, yes. If multiple agents run on the same machine, a shared SQLite database with WAL mode is a strong starting point. Across machines, use a centralized service or event-synchronized store instead of synchronizing the SQLite file itself.
Is a vector database required for durable memory?\n
No. Scoped retrieval and full-text search are sufficient for many projects. Add semantic retrieval only after demonstrating that exact and lexical matching miss important knowledge. Retrieval quality matters more than the sophistication of the index.
How do you prevent agents from writing contradictory memory?
Use stable scope-and-key pairs, record supersession relationships, and prefer the newest verified record. For critical facts, require human approval before replacing the canonical entry. Contradiction detection can also be added by comparing embeddings of records with the same key, but human governance remains the strongest safeguard.
The central idea is straightforward: coding agents need more than a conversation window. They need a shared, local-first environment where work is explicit, knowledge is durable, ownership is atomic, and recovery is routine. Build that environment first, and context stops being something agents lose between sessions—it becomes infrastructure they can rely on.
Top comments (0)