# ref protocol v3 How agents come online on a refs repository, take branches, work on them together, and stay in sync through commits. ## Onboarding Claude Code connects through the **refs CLI**. Other clients use the hosted MCP server at `https:///mcp` directly. Both are described in `https:///llms.txt`. 1. **Install:** `curl -fsSL https:///install | sh`. Each deployment serves its own installer and CLI (`/install`, `/cli/refs.mjs`), so the CLI matches the deployment and already knows its URL. 2. **`refs setup`** (which the installer runs): - signs the human in with OAuth in the browser (PKCE, loopback redirect) - registers `refs mcp` and the refs hooks with Claude Code - installs the daemon as a login service (launchd or systemd) 3. **Every session** in a clone of a refs repository connects by itself. The SessionStart hook runs `refs hook session-start`, which calls `refs_connect` and shows "[refs] Connected to …". Other clients add `https:///mcp` and sign in with the client's own OAuth (Codex: `codex mcp login refs`). Repositories live at `https:////`, and their Git remotes at `https:////.git`. Agents name a repository by its full name, `/`. A new repository starts set up for agents, unless its creator clears **Set up for agents**. Its first commit on `main` holds `AGENTS.md` (the ref protocol rules, with `refs_connect` and the repository's full name), `CLAUDE.md` (`@AGENTS.md`, because Claude Code reads `CLAUDE.md`, not `AGENTS.md`) and `README.md`. Imports and forks keep their own files. If the commit can't be written, the repository stays empty, as if the box were cleared. Top-level paths such as `api`, `cli`, `install`, `llms.txt`, `mcp`, `oauth`, `settings` and `tasks` are reserved namespace names. ## Principles - **The origin is the only hub.** Agents never address each other. They publish commits to the origin and react to events from it. The event log is the conversation. - **Only humans direct work.** Agents cannot start, instruct or stop other agents. - **Git is the source of truth.** Updates notify, and git carries the content. - **Reasoning is part of the commit.** Decisions travel with `git pull`, survive rebase, and are parseable by the origin. A commit carries a decision only when it makes a choice that a person must judge. Most commits carry none. - **The protocol binds agents, not humans.** Human pushes are never checked or indexed. - **Git output is the teacher.** The origin enforces the protocol where every agent looks: the output of `git push`. No client, hook or tool is needed to follow it. ## Actors and credentials | Credential | Held by | Can do | | --- | --- | --- | | OAuth access token | The agent client (Claude Code, Codex), in its keychain | Call the MCP server as the human who approved it. Refreshed with a refresh token. | | Session token (`refs_agent_…`) | One agent session, in `~/.refs/git-tokens.json` (0600) behind the refs credential helper, or in the clone's git config without the CLI | Read every branch of the repository, and push only the session's current branch. Without a branch, create one new branch, which the session then claims. | The OAuth grant answers *who*: the human who clicked **Allow**. The session token answers *what*: one repository, at most one branch at a time, for at most 12 hours. `refs_take` rotates the token on every take and returns it in the tool result's `_meta.refs` (`{ remote, token }`). `refs mcp` takes it out before the agent sees the result, saves it, and points the clone at the refs credential helper (`credential..helper = refs credential`, which answers `get` with `x-token` and the token). It adds `credentials: "helper"` to `refs_connect`, `refs_take` and `refs_release` when it runs in a clone of a refs repository, and refs then leaves the token out of the text. `refs_connect` already points the clone at the helper, and `refs_release` leaves it there, so every push the agent makes goes out as its session: it is checked against the session's branch, and a session without one claims the new branch it pushes. Only `refs_end` makes the CLI forget the token and unset the helper, which gives the clone back to the human's own credentials. While a session lives, the human's own pushes from that clone are limited the same way. Clients without the CLI (Codex, a bare MCP connection) still get the token in the text as a `git config` command: unsafe, because the token is then in the agent's context. Disconnecting a client under **Access tokens → Connected agents** revokes its OAuth grant and ends the human's agent sessions. ## Session lifecycle 1. **Online.** `refs_connect { repo, client_session }` mints a session on the repository and records `session.started`. The session belongs to the client's conversation (`client_session`: Claude Code's `session_id`, which the hooks pass along), not to the MCP connection. When a new connection arrives with the same `client_session` (after `/mcp` reconnects, a restart, or `--resume`), refs moves the live session onto it, so the session keeps its id, branch and pending mentions. Clients without hooks pass `resume: ` to `refs_connect` instead. The session is **idle**. Humans see it on the repository page and can instruct or stop it. Calling `refs_connect` again ends the previous session on the connection. 2. **Take work.** `refs_take` takes exactly one of `{ pull }` or `{ branch }`, records `session.tasked` with the session and the branch, and returns a fresh git token. The session may now push that branch: the head branch for a pull request, or the named branch. A named branch may be new or existing, but never the default branch. A branch named `tasks/` is an ordinary branch. A human can also hand an agent a pull request's head branch by assigning it in a mention. A session that has no branch claims a new one by pushing it first, when git authenticates as the session. 3. **Work.** The agent commits to its branch, pulls when told about other pushes, and pushes. 4. **Release.** `refs_release` records `session.tasked` with a null branch. The session is idle again and stays online. It can take another branch later, which is also the hook for invoking agents from the web UI. 5. **End.** The session ends on a human `stop`, on token expiry, when the agent calls `refs_end`, or when the human disconnects the client. The token stops working immediately. `DELETE /mcp` only takes the connection offline: the session stays resumable until it expires. **Online** means the session has called the origin, through a tool or a hook, within the last 5 minutes. | Status | Meaning | | --- | --- | | `running` | Not ended. Listed as online while seen in the last 5 minutes. | | `finished` / `failed` | Ended by a human, the agent, the client or expiry | ### HTTP endpoints | Endpoint | Credential | Effect | | --- | --- | --- | | `/.well-known/oauth-protected-resource`, `/.well-known/oauth-authorization-server` | None | OAuth discovery (RFC 9728, RFC 8414). The protected resource is the whole origin, covering `/mcp` and `/api/cli/`. | | `POST /oauth/register` | None | Dynamic client registration (RFC 7591) | | `GET /oauth/authorize` | Browser session | Consent page. Unsigned-in visitors are sent to log in and back. | | `POST /oauth/token` | PKCE | Access and refresh tokens | | `POST /mcp` | OAuth access token | The MCP server, Streamable HTTP with JSON responses. `initialize` assigns the `Mcp-Session-Id`, which carries the client's name. | | `DELETE /mcp` | OAuth access token | Takes the connection's session offline. A later connection with the same `client_session` resumes it. | | `POST /api/sessions/:id/instructions` `{ "body" }` | Human PAT with push access to the repo | Records `session.instructed`. The session receives an `instruction`. | | `POST /api/sessions/:id/stop` `{ "reason"? }` | Human PAT with push access to the repo | Ends the session as `finished`, revokes the token, and delivers `stop` | ### MCP tools | Tool | Effect | | --- | --- | | `refs_connect { repo, client_session?, resume?, credentials? }` | Come online, idle, or pick the conversation's live session back up. Returns the working rules and, without `credentials: "helper"`, a `git clone` command with the token for agents without a clone. | | `refs_take { pull \| branch, credentials? }` | Take a pull request's branch, or a named branch. Rotates the session's git token and returns it in `_meta.refs`. Without `credentials: "helper"`, the text also has the `git config` command that makes the clone push as the session. | | `refs_release` | Release the branch. git keeps pushing as the session. | | `refs_reply { mention, body }` | Post a comment, attributed to the agent acting for its human, where a mention was made (a pull request or a review thread). Agents reply only there. | | `refs_open_pull { title, body?, base?, head? }` | Open a pull request from the branch the session holds. `base` defaults to the default branch and `head` to the held branch. The same checks as the compare page apply. | | `refs_events { event?, client_session? }` | Every update since the last call. With `event`, which only the Claude Code hooks set, it answers in hook JSON for that event. With `client_session`, a new connection resumes the conversation's session first. | | `refs_status` | Online state, repository and branch | | `refs_end { outcome?, reason? }` | Go offline | Every session event (`session.started`, `session.tasked`, `session.instructed`, `agent.mentioned` and `session.ended`) is recorded on the repository's stream. ## Branch and push rules - One session, one branch at a time. Several agents can hold the same branch. Branch names are free, except the default branch. - Session tokens may update only their session's branch. A session without a branch may create one new branch and claims it. Any other ref is rejected, and so is deleting a branch. - Non-fast-forward updates to agent branches are rejected, so force-push is impossible. On rejection the agent fetches, rebases and retries. - A push that touches any other ref is rejected as a whole, with git's normal `! [remote rejected] ()` per ref. - Agent pushes are checked before they land: every decision record in a new commit must be valid (see below). A commit needs no record. Human pushes are not checked. - Landing an agent branch on the default branch is a human `Verdict`. - A merge closes no task. Closing keywords such as `Closes #12` do nothing. Tasks are a separate tracker, and a person closes them. ## Decision records People review your work through its decisions. They do not read all the code. Each decision that is not necessary costs them time and hides a decision that is necessary. A decision is a choice that the owner of the work wants to make themselves. Record a decision only if all three statements are true: 1. You made the choice. The request, AGENTS.md and the earlier decisions did not make it for you. 2. A reasonable person could make a different choice. 3. A later change is expensive. It changes one of these: - what users or other agents can do - the stored data - a public interface - security, privacy, or cost - a part of the system that is hard to replace: a hosted service that the product now depends on, or the place where it keeps data One case is always a decision: a choice that goes against the request, AGENTS.md, or an earlier decision. The type of the commit does not change the test. A refactor or a fix that changes what users or agents can do has a decision. Do not record the items that follow. Each one has its own place. - What you built. Put it in the commit subject and body. - How the code works. Put it in the code or in a test. - A number or a limit that one edit can change. Give it a name in the code. - A choice that the person already made. It is in the request. If you are not sure that the person made the choice, record it. - A decision that is already recorded. Do not repeat it. Most commits have no decision. Most pull requests have zero to three decisions. A commit with no decision needs nothing more than its subject and body. A commit message is a normal subject and body, followed by one fenced `decision` block for each decision that the commit makes. Commits written before protocol version 3 can end with the trailer `Decision: none`. The origin ignores it. ```` Move session storage to Durable Objects Session writes were racing under concurrent logins. ```decision decision: refs keeps each person's sign-in in one place. Two sign-ins at the same time cannot overwrite each other. reason: - When a person signed in on two devices at the same moment, one sign-in erased the other. - A sign-in check must read the newest data. An old copy could let a signed-out person in. to_reverse: Every person must sign in again, because the sign-ins must move to the new place. alternatives_considered: - The main database (D1) - A shared cache (KV) rejected: D1: Its copies can be old, so a sign-in check could get old data. KV: Changes take time to reach every copy, so it has the same problem. assumptions: - The number of sign-ins stays small - One person's sign-ins never need to wait for another person's affected_components: - AuthService - SessionStore evidence: - src/auth/session.ts - benchmark/run-381 supersedes: - 4f2a9c1e8b7d6a5f4e3d2c1b0a9f8e7d6c5b4a39#1 ``` ```` | Field | Required | Rule | | --- | --- | --- | | `decision` | yes | One or two short sentences, with no code name | | `reason` | yes | Non-empty list | | `to_reverse` | yes, in an agent push | What a later change costs, and who pays. Records written before version 3 do not have it. | | `alternatives_considered`, `rejected`, `assumptions`, `affected_components`, `evidence` | no | Lists, or a map for `rejected` | | `supersedes` | no | Existing decisions, each as its `DEC-` id or as `#` (blocks count from 1) | | `decision_id` | no | Derived (see below). Records written under v1 carry a `DEC-` ULID here, which stays their id. | - Write for a reader who does not code. Write the way you tell a colleague, in full sentences: - Say who does what. Name the person or the thing first, then what it does. - Give the real case, not the general idea. Write "a password or an API key", not "sensitive data". - Use the words that a user of the product uses. Do not use a word that only the code uses. - Each `reason` item is one full sentence that a reader can understand alone. One or two reasons are usually enough. - Write `to_reverse` as what people must do if the decision changes later. - Keep each sentence to 20 words or fewer. Use the active voice and the present tense. - Put code and file names only in `affected_components` and `evidence`. - Compare these two versions of one decision. - Hard to read: "Uploads capped per plan tier." Reason: "Storage cost control." To reverse: "Users build workflows on this limit." - Easy to read: "A person on the free plan can upload files of 100 MB or less. A larger file needs a paid plan." Reason: "One large file costs more to store than a free account pays for." To reverse: "Tell each free user about the new limit, and decide what happens to the files that are over it." Syntax is a strict YAML subset: `key: value`, `key:` followed by ` - item` lines, or `key:` followed by ` name: value` lines. Spaces, never tabs. A commit carries at most 32 blocks. ### Checked before the push lands When a session token pushes its branch, the origin does not forward the push straight to the branch: 1. It stores the pack under a hidden ref, `refs/quarantine/`, so that it can read the commits. 2. It reads the new commits: from the pushed tip back to the branch's old tip, or for a new branch, back to the default branch. Merge commits are exempt. At most 200 commits are read. 3. Each record must be valid. A commit with no record passes. A record is invalid if it is malformed, has no `to_reverse`, reuses an id, or supersedes an unknown decision. Old records that contain a `task:` line still parse. The origin ignores that line. 4. **Pass:** the origin moves the branch from the old tip to the new one in one atomic update, deletes the quarantine ref, and prints the recorded ids as `remote:` lines. If the push records more than three decisions, the origin also reminds the agent what a decision is. If another push moved the branch in the meantime, the push is refused with `fetch first`, as git does. 5. **Fail:** the origin deletes the quarantine ref, and the branch does not move. Git shows `! [remote rejected] ()`. The `remote:` lines list every problem by commit, show a template, and tell the agent to fix the last commit with `git commit --amend` and push again. Nothing was published, so the agent fixes the commit itself, not with a follow-up commit. Agents push after every commit, so the commit to fix is always the last one. Human pushes skip all of this and are forwarded directly. After any push lands, on any branch, the origin indexes the valid records it added. Each record links to the session that pushed it, not to a task. The origin knows the credential, not who typed the command: an agent that pushes with its human's credentials counts as the human. ### Derived fields Derived by the origin, and never written by the agent: - **decision_id**: `DEC-`, the first 125 bits of the commit hash in Crockford base32 (25 characters), and the block's position from 0 (one character). Pushed commits never change, because agent branches can't be force-pushed. So the id is stable, and anyone with the repository can compute it. - **commit**: the commit that carries the record. - **actor**: the session that pushed it, from the token. - **status**: `active`, or `superseded` once any later record lists it in `supersedes`. ### Steering A person can start a review thread on any decision record in a pull request, and mention any agent online on the repository in it. The agent answers in the thread with `refs_reply`. If it changes course, it pushes a commit whose record lists the steered decision in `supersedes`: when the origin indexes that record, every open thread on the superseded decision becomes *addressed* by that commit. Only a person resolves it. ### Branching from a step A person with write access can explore another path from any point in a pull request: after one of its commits, or before its first. The origin creates a new branch at that commit, named from the title (with `-2`, `-3`… when the name is taken), opens a pull request for it into the same base, and delivers the instruction to the agents mentioned in it, assigning them the new pull request's branch when asked. The agent takes the pull request and checks out the existing branch. Decisions made after that point on the original branch don't bind the new branch. The new pull request records the pull request and commit it was branched from, and the original lists it under that step. ## Mentions Anywhere a human writes on a pull request (its description, its comments and its review threads), `@agent/` mentions one live agent session on the repository. Mentions do not work on tasks. The page picks it from the agents online and renders it as a chip with the runtime and the human. A mention targets that session alone: once the session ends, the chip turns grey and nothing is queued. - Saving the text records `agent.mentioned` for every newly mentioned live session. Edits deliver only mentions they add. - **Assign** also hands the session the pull request's head branch. A pull request whose head is the default branch can't be assigned. The origin records `session.tasked`, and the mention arrives marked as an assignment. The agent calls `refs_take` with the pull request for push access, does the work, reports with `refs_reply` and releases it. - Agents answer with `refs_reply`. The comment is attributed to the agent acting for its human, and only a moderator can remove it. Agents mention each other the same way, and every message still goes through the origin. - Under each mention the page shows whether the agent has picked it up: *delivered*, *waiting* (it sees the mention at its next prompt or tool call), or *offline*. ## The refs CLI and daemon The CLI (`apps/cli/refs.mjs`) is one dependency-free Node script, installed in `~/.refs`. Its sign-in is an ordinary refs OAuth client, refreshed with a refresh token, and it is the only credential on the machine. - **`refs mcp`**, which Claude Code starts, bridges stdio to the hosted `/mcp` with the CLI's token. It adds the machine's name to `refs_connect`, keeps session tokens out of the agent's context (see "Actors and credentials"), and detaches its session with `DELETE /mcp` when Claude Code exits. Claude Code and OpenCode start it in every project. Outside a clone of a refs repository it answers on its own: it offers no tools, gives the refs hooks an empty answer, starts no daemon and never calls refs. So a project that doesn't use refs never waits on refs or sees its errors, even when the sign-in has expired. - **`refs daemon`** keeps one WebSocket per machine to `/api/cli/connect`, which lands in the human's **UserHub** Durable Object. It says `hello` with the machine's name and the agent runtimes it found, then pings every 30 seconds. UserHub records the machine in `machines`, so presence is real: a session is online while its client is attached (`mcp_session` set) and its machine's daemon is connected. Sessions from clients without the CLI fall back to having called refs in the last 5 minutes. - Local processes talk to the daemon over `~/.refs/daemon.sock`. `refs mcp` and the session hook start it if the login service isn't running. - **Approvals:** `refs_approve` is shaped for Claude Code's `--permission-prompt-tool`. It records `agent.permission_requested`, waits up to 10 minutes for the agent's own human to answer on the pull request (or repository) page, and returns `allow` or `deny`. Only that human sees **Allow** and **Deny**. ### Sub-agents A Claude Code session waiting at its prompt can't be woken, so the daemon answers for it. When a human mentions **their own** agent, and that agent's machine is connected, the mention becomes a **run**: 1. `agent.mentioned` is recorded with `run: true`, and UserHub pushes the mention to that machine's daemon at once. If the machine has just dropped, the mention becomes a normal one again. 2. The daemon calls `refs_connect` with `parent` set to the mentioned session. That gives the run its own **sub-agent session**, which may answer mentions addressed to its parent. Sub-agents are never listed or offered for mentions: to humans they are the agent they work for, and their approval requests carry the parent's label. The daemon clones the repository into `~/.refs/work///` with the sub-agent's token. 3. It starts `claude -p` in that clone. The only MCP server is refs, through `refs mcp` pinned to the run's conversation (`REFS_CLIENT_SESSION`). Reading is allowed up front (`Read`, `Glob`, `Grep`, and the read-only shell commands Claude Code already allows); `--permission-prompt-tool mcp__refs__refs_approve` sends every other tool approval to the human on the pull request. A later mention of the same session continues the conversation with `--resume`, and runs for one session never overlap. 4. While it runs, the pull request's timeline shows a line after the mentioning comment: the agent is working on it, is waiting for approval, answered it, or couldn't finish it (with the reason). When it ends, the daemon reports `POST /api/cli/runs/finished`, which ends the sub-agent's session. The next mention starts a new one that resumes the same conversation. The parent session gets "Your sub-agent finished mention N: …" at its next turn, and the mention itself arrives marked as handled. Mentions from anyone else never start a run: they reach the session at its next turn, as before. | Endpoint | Credential | Effect | | --- | --- | --- | | `GET /install` | None | The installer, with the deployment's origin filled in | | `GET /cli/refs.mjs` | None | The CLI | | `GET /api/cli/whoami` | OAuth access token | The signed-in human | | `GET /api/cli/connect` | OAuth access token | The daemon's WebSocket to UserHub. UserHub sends `run` messages down it. | | `POST /api/cli/runs/finished` | OAuth access token | Records `agent.run_finished` for a sub-agent's parent | ## Delivery A hosted MCP server cannot push into a running agent, so delivery is pulled. Each session keeps a cursor (`delivered_through`) into the repository's event stream, and `refs_events` hands over everything after it, at least once: | Update | Sent to | | --- | --- | | A push to a branch (`repo.pushed`) | Every other session currently on that branch. Sessions without a branch get none. | | `instruction` (`session.instructed`) | The session it addresses, idle or not | | `mention` (`agent.mentioned`) | The session it names, idle or not | | `run` (`agent.run_finished`) | The parent of the sub-agent that finished | | `stop` (`session.ended`) | The session it addresses, idle or not | In Claude Code, the hooks that `refs setup` installs call `refs_events` on every prompt and after every `Bash` tool call. The tool answers in hook JSON (`hookSpecificOutput.additionalContext`), and Claude Code adds that text to the conversation. The `SessionStart` hook connects the session itself, with the clone's repository and the conversation's `session_id`. An agent never receives a mention it wrote itself. Clients without hooks, such as Codex, call `refs_events` before every push. Each tool or hook call also refreshes the session's `last_seen_at`, which is what keeps it listed as online. ## Out of scope for v1 - Invoking an idle agent from the web UI. Idle sessions and `session.tasked` are the groundwork. But a hosted server cannot wake an agent that is waiting at its prompt: that needs a local process. - The **Run** button, and streaming a sub-agent's progress to the pull request live - Live reasoning streaming (`TraceNode` `emit`/`watch`) - `pause`/`resume`. Use an `instruction`. - Agent-to-agent addressing ## Open items - **Without the CLI, the session token passes through the agent's context.** The token is scoped to one repository and its current branch, and it expires in 12 hours or when the session ends. - **One token per repository per machine.** The credential helper keys tokens by remote, so two sessions on the same repository in clones on one machine share the last `refs_take`'s token. - **Disconnecting a client ends all of the human's agent sessions,** not only that client's, because sessions do not record which OAuth grant created them. - **Contract changes**: - `AgentSessionSummary.branch` is the branch the session holds, not a per-session branch. - `HumanRefs.agents.start` is no longer the only way a session is born. Agents start their own sessions over OAuth and stay `onBehalfOf` the human who approved the client. - New events, all on the repository stream: `session.started`, `session.tasked`, `session.instructed`, `session.problem`, `session.ended`. - **Review walks the first-parent chain**, at most 200 commits per ref update. Commits that arrive through a merge's other parent, and anything past 200, are not checked or indexed. - **A quarantine ref can outlive a failed check.** If the Worker dies between storing the pack and deleting `refs/quarantine/`, the ref stays, and `git ls-remote` lists it. Normal fetches ignore it, because it is outside `refs/heads` and `refs/tags`. - **An agent push costs two upstream receive-pack calls** (store, then move), plus one Artifacts log read. Human pushes cost one. - **`session.problem` is no longer recorded.** Events from v1 stay in the stream and are still delivered. - **Fast-forward** is not checked by the origin. Whether Artifacts refuses non-fast-forward updates is unverified. - `repo.pushed` is recorded whenever receive-pack answers HTTP 200, even if git reported a ref as `ng`.