# Agent Memory Setup — Instructions for a Claude Code Agent

> **How to use this file (read this, human):** save it anywhere, open Claude Code, and say:
> *"Read agent-memory-setup.md and set up the agent memory bus on this machine. Interview me first."*
> Everything below is written **to the agent**. It contains every file the agent needs to create,
> verbatim. Nothing else is required.
>
> Source: TKC Group (tkcgroup.co/resources). This is the same system we run in production —
> ~12 Claude Code agents, 24/7, across two machines and a NAS — reduced to its portable core.

---

## Part 0 — What you are building (context before action)

You are setting up a **file-based coordination bus** so that multiple Claude Code agents (or the
same agent across many sessions) can work simultaneously without interfering, hand off work
cleanly, and message each other. There is no server, no database, no daemon. It is a folder with
rules. That is what makes it durable.

Two names for the same layout:

- **LAM — Local Agent Memory.** The bus on one machine (a plain local folder). This is the
  default build.
- **GAM — Global Agent Memory.** The same bus on shared storage (network drive, file server, or a
  NAS reached over a mesh VPN like Tailscale) so agents on *different machines* share it.

The bus has exactly three moving parts:

| Primitive | What it is | The rule that makes it safe |
|---|---|---|
| **Shard** | One append-only markdown log per agent/workspace — its heartbeat. Each session prepends a dated block: what shipped, what's open, what's blocked. | Prepend-only, newest first. **Never** edit or delete old blocks. |
| **Fridge** | One inbox folder per agent. To tell another agent something, you write a small markdown file into *its* fridge. | Unique filenames (timestamp + author + slug) so simultaneous writers never collide. |
| **Thread lifecycle** | Two commands: `/thread-start` (inhale: read your shard + fridge before working) and `/thread-close` (exhale: write your heartbeat + drop any messages). | Every session begins and ends with them. All coordination happens at these two moments. |

Why this works when "just be careful" doesn't: agents don't share memory between sessions and
can't see each other's context windows. The bus turns coordination into **files with formats**,
which every agent can read, and **rules**, which every agent can follow. State lives on disk,
not in anyone's head.

---

## Part 1 — Interview the user (do this first)

Ask these four questions before touching the filesystem. Do not skip the interview.

1. **How many agents / workspaces?** One repo with occasional parallel sessions, or several
   long-running agents? → This decides how many shards to create up front (it's fine to start
   with one or two; shards are created on first write).
2. **One machine or several?** One machine → **Tier 1 (local)**. Multiple machines with a shared
   folder (Dropbox/Drive/SMB share) → **Tier 2**. Multiple machines + a NAS or always-on server,
   ideally over Tailscale → **Tier 3**.
3. **Where is the code root?** The bus must live *outside every git repository* (e.g. at
   `~/Code/.agent-memory` when repos live under `~/Code/<project>`). Confirm the parent folder.
4. **What should each agent be called?** Short lowercase slugs, one per workspace/agent —
   e.g. `api`, `web`, `ops`, or repo names. These become shard names.

Record the answers, then build the matching tier below.

---

## Part 2 — Build the bus

### Tier 1 — Local (one machine) — the default

```bash
BUS="$HOME/Code/.agent-memory"    # adjust the parent to the user's code root
mkdir -p "$BUS/shards" "$BUS/fridge/all"
# one fridge per agent slug from the interview, e.g.:
mkdir -p "$BUS/fridge/api" "$BUS/fridge/web"
```

Then write the protocol file at `$BUS/README.md` — the contents are in **Part 3**. The README
*is* the single source of truth: any future agent pointed at the folder reads it and can operate
with no other knowledge.

### Tier 2 — Shared folder (multiple machines, no NAS)

Identical layout; the root moves into the shared folder, e.g.
`~/Dropbox/agent-memory/` or a mounted SMB share. Two extra cautions:

- Sync services can produce "conflicted copy" files. The unique-filename rule (Part 4, rule 2)
  makes this survivable, but tell the user: **never have two agents edit the *same* file** —
  shards are the only shared-write files, and they're prepend-only, one agent per shard.
- If sync lags, a fridge message may arrive minutes late. That's fine — this bus is for
  handoffs and directives, not real-time locking.

### Tier 3 — NAS / server over Tailscale (the full GAM)

The production shape. The bus lives on the NAS; each machine mounts it.

```bash
# macOS example — mount an SMB share exposed through Tailscale
open "smb://USER@<tailscale-ip-or-magicdns-name>/shared"   # then it appears under /Volumes
BUS="/Volumes/shared/agent-memory"
```

Extra rules for Tier 3:

- **Verify the mount before trusting it.** Check `mount | grep -i <share>` — do **not** rely on
  listing `/Volumes`, which can show stale ghost directories after a disconnect.
- **Keep a local mirror.** Each machine also keeps a Tier-1 bus (e.g. `~/Code/.agent-memory`) as
  an offline buffer. When the NAS is down, agents read/write the mirror and flag
  *"NAS offline — cross-agent state is local-only"* in their briefing. When it returns, sync UP:
  prepend any shard blocks the NAS lacks (dedup by the timestamp header), copy fridge files
  if-absent (unique names make this idempotent), then keep the mirror as a warm cache.
- **Optionally add a `standards/` folder** at the bus root for protocol docs every agent must
  read on start — the place future protocol upgrades propagate from, so you never have to edit
  every machine's config again.

---

## Part 3 — Write the protocol README

Create `$BUS/README.md` with exactly this content (fill in the agent slugs from the interview):

````markdown
# .agent-memory — the agent coordination bus

> Any agent told "use the bus at <this folder>" reads THIS file and can operate fully.
> No agent-specific knowledge required.

## 30-second onboarding
1. Identify your shard (see the map below).
2. On session START: read `shards/<you>.md` (newest block is at the top). Skim
   `fridge/<you>/` and `fridge/all/` for messages. Act on any with `action_required: yes`,
   then move handled files to `fridge/<you>/.processed/`.
3. On session CLOSE: PREPEND a heartbeat block to `shards/<you>.md`. Write any messages
   for other agents to `fridge/<them>/`; broadcasts to `fridge/all/`.

## Shard map
| Workspace / repo | Shard |
|---|---|
| <repo-or-workspace> | <slug> |
<!-- one row per agent from the interview -->

## Structure
```
.agent-memory/
├── README.md              ← this file (the protocol)
├── shards/<shard>.md      ← append-only heartbeat log, NEWEST-FIRST
└── fridge/
    ├── <shard>/           ← per-agent inbox  (+ .processed/ for handled)
    └── all/               ← broadcasts to every agent
```
Shards and fridge dirs are created on first write — no setup needed per new agent.

## Shard heartbeat block (prepend under the title line)
```markdown
## [YYYY-MM-DD HH:MM TZ] — <shard> · <agent> (<session>) — <one-line topic>

**Shipped:** …
**Open for next thread:** …
**Blocked / needs human:** …
```

## Fridge file
Filename: `<YYYY-MM-DD>T<HH-MM>-<from-agent>-<slug>.md` (unique → zero collisions).
```markdown
---
from: <agent/shard>
to: <target shard>            # or "all"
priority: low | normal | high | P0
action_required: yes | no
created: <ISO timestamp + TZ>
---
<the message, with file paths and context so it is pickup-able cold>
```

## Rules (non-negotiable)
1. Shards are APPEND-ONLY, newest-first. Never rewrite or delete a prior block.
2. Unique fridge filenames. Never overwrite someone else's file; add your own.
3. Stamp WHO and WHEN on everything.
4. NO SECRETS. Plaintext bus — keys/tokens/passwords never go here; reference them by name.
5. This folder stays OUTSIDE every git repo. Never commit it.
6. Verify other agents' claims. If a shard says "done" but the artifact isn't on disk,
   treat it as unverified and check before building on it.
7. If you drop a fridge message that requests action, WATCH for the reply — check the
   target's response before treating the send as complete. Never drop-and-forget.
8. Scope: this bus is a handoff relay. Durable per-repo work lives in each repo's own
   docs; the bus points at those files, it does not duplicate them.
````

---

## Part 4 — Install the lifecycle commands

Create these two files. They make the protocol automatic instead of remembered.
(For project-scoped installs use `.claude/commands/` inside the repo; for user-global use
`~/.claude/commands/`. Prefer user-global so every repo inherits them.)

### `~/.claude/commands/thread-start.md`

````markdown
---
description: Inhale — read the agent memory bus before starting work
---

You are starting a new working session (a "thread"). Before any task work:

1. Resolve the bus root: `$HOME/Code/.agent-memory` (or the NAS path if mounted —
   verify with `mount | grep`, never by listing /Volumes). If using a NAS with a local
   mirror and the NAS is down, use the mirror and say so in your briefing.
2. Identify your shard from the bus README's shard map (match your working directory).
3. Read the top ~40 lines of `shards/<you>.md` — the last session's heartbeat.
4. List `fridge/<you>/` and `fridge/all/` (newest first). Read anything new. If a file
   has `action_required: yes`, plan to act on it this session; move handled files to
   `fridge/<you>/.processed/`.
5. Read the repo's own progress docs if present (e.g. PROGRESS.md).
6. Give the user a 5-10 line briefing: last heartbeat age + summary, inbox items found,
   what you plan to do this session. Flag anything stale or blocked.

Do not skip steps. If the bus doesn't exist yet, offer to create it per its README.
````

### `~/.claude/commands/thread-close.md`

````markdown
---
description: Exhale — write your heartbeat and messages to the agent memory bus
---

You are closing this working session. Do not just summarize in chat — write the files:

1. Resolve the bus root and your shard (same as /thread-start).
2. PREPEND a heartbeat block to `shards/<you>.md` — title line stays first, your new
   block second, all prior blocks untouched below. Never truncate the file; write your
   block to a temp file and concatenate if needed. Format per the bus README: timestamp,
   shard · agent · session, one-line topic, then **Shipped / Open for next thread /
   Blocked**.
3. If any other agent needs to know or do something, write a fridge file to
   `fridge/<target>/` with the required frontmatter (unique filename:
   date T time - your-slug - topic). Broadcasts go to `fridge/all/`.
4. If you dropped a message with `action_required: yes`, note in your heartbeat that a
   reply is pending, so the next session re-arms the watch.
5. If work is uncommitted, either commit it (if the user approves) or record exactly
   what is dirty and why in the heartbeat.
6. Confirm to the user: heartbeat written (show the header line), fridge drops written
   (list filenames), open loops carried forward.
````

---

## Part 5 — Wire it into CLAUDE.md

Append this to the user's `~/.claude/CLAUDE.md` (create it if missing), adjusting paths:

```markdown
## Agent Memory Bus
- The coordination bus lives at `~/Code/.agent-memory` (protocol: its README.md).
- Every session: run /thread-start before task work, /thread-close before ending.
- Shards are append-only. Fridge messages use unique timestamped filenames. No secrets
  on the bus. The bus never gets committed to git.
- Verify other agents' claims against the filesystem before building on them.
```

If the user runs multiple *named* agents, also give each workspace its own repo-level
`CLAUDE.md` line declaring which shard it owns ("You are <slug>; your shard is
`shards/<slug>.md`") so identity is never ambiguous.

---

## Part 6 — Running agents simultaneously without collisions

The bus handles *coordination*. Simultaneous *editing* needs one more discipline — pick one
per pair of agents, strongest first:

1. **Separate clones or git worktrees (recommended).** Each long-running agent gets its own
   working tree (`git worktree add ../repo-agent-b branch-b`). Same repo, zero file-level
   interference, merges happen through git like any two human developers. This is the answer
   to "do I just need to keep them off the same files?" — don't manage it socially; make
   collision structurally impossible.
2. **Same tree, disjoint ownership.** Two agents may share one working tree only if their
   file sets genuinely never overlap (e.g. `api/**` vs `web/**`) — declare the split in
   CLAUDE.md so both agents know the boundary. Beware the shared git index: a plain
   `git commit` can sweep up files the *other* agent staged. Commit with explicit pathspecs
   (`git commit -- <your paths>`) or stagger commits via fridge coordination.
3. **Same files, never simultaneously.** Baton-pass through the bus: agent A closes
   (/thread-close, heartbeat says "handing off X"), agent B starts (/thread-start, picks it
   up). The bus makes the baton explicit.

Also set expectations on **permissions**: long-running autonomous agents work best with broad
edit permissions *inside their own worktree* and hard rules (the bus README + CLAUDE.md)
instead of per-action prompts. Keep destructive operations (deploys, deletes, publishing)
gated on explicit human approval regardless of tier.

---

## Part 7 — Optional power-ups (only if the user asks)

- **Monitors:** after dropping an `action_required: yes` fridge file for another live agent,
  poll that agent's reply inbox (your own fridge) on an interval instead of forgetting it —
  baseline the directory listing, re-check every ~60s, diff for new files.
- **Loops:** a recurring prompt (e.g. Claude Code's `/loop` or a cron-launched headless
  session) that runs /thread-start → a small work budget → /thread-close. This is how a
  fleet runs "24/7" — many short, clean threads, not one immortal session.
- **Task inbox:** a `tasks/` folder on the bus (`pending/` → `claimed/` → `done/`) where any
  agent or the human drops work items; idle agents claim by moving the file (a move is
  atomic — that's the lock).

---

## Part 8 — Verify before you report done (agent: do not skip)

Run every check; show the user the output:

```bash
BUS="$HOME/Code/.agent-memory"   # or the tier-2/3 path
test -f "$BUS/README.md"                  && echo "✓ protocol README"
test -d "$BUS/shards"                     && echo "✓ shards/"
test -d "$BUS/fridge/all"                 && echo "✓ fridge/all/"
ls ~/.claude/commands/thread-start.md \
   ~/.claude/commands/thread-close.md     && echo "✓ lifecycle commands"
grep -q "Agent Memory Bus" ~/.claude/CLAUDE.md && echo "✓ CLAUDE.md wired"
# the bus must NOT be inside a git repo:
cd "$BUS" && git rev-parse --git-dir 2>/dev/null && echo "✗ INSIDE A GIT REPO — move it" || echo "✓ outside git"
```

Then do one real round-trip as proof: prepend a first heartbeat to your own shard
("bus initialized"), drop a `fridge/all/` broadcast announcing the bus, and read both back.
A bus that hasn't carried one message is not verified.

Finally, tell the user how to onboard every other agent: point it at the bus and say
*"read the README at <bus path> and follow it — run /thread-start."* That's the whole
onboarding. The system is the folder.

---

*From the team at [TKC Group](https://tkcgroup.co) — we run this exact architecture in
production. The visual companion PDF and the full write-up live at
[tkcgroup.co/resources](https://tkcgroup.co/resources).*
