# Grapevine: talking to a running pic
Status: accepted; stage 1 landed (with `pic attach`'s read side of stage 2; see [the inbox](../dev/inbox.md))
Grapevine lets one process reach a conversation that another pic process is working: send it a
command, read what it has done, and get an answer back. It follows [keel](keel.md) and comes before
tether (remote control of a running pic, ticket ed086ebc04), which carries it to other machines. The
messaging ticket is ea67853621.
The short form: **the journal carries messages and a kernel file watch wakes the receiver.** A
message is a row in the receiving workspace's journal, committed before anything acts on it, and
the conversation's lease holder delivers it in one transaction. There are no sockets, no listener,
no broker and no daemon. The wire format is Pi's RPC command and event JSON, unchanged.
Tier: core (the inbox, its delivery, the watch seam), bundled (`pic attach`, peer wording, the send
tool, the wake policy). Clock: durability, os, pi. Record: a `pic_inbox` row per message, the sender
on what it caused. Default: on; waking an idle conversation off.
## What it is for
1. **An editor or script steers a running session.** A tool sends a steer, a follow-up or an abort
to a conversation that a `pic --mode rpc` or a terminal session is running, and reads the
answer. Today it can only start its own `pic --mode rpc` child.
2. **Observe a running session.** `pic attach` prints Pi's events for a conversation another
process runs, from any point in its history, and keeps following it. A dashboard, a test or a
second terminal reads the run without touching it.
3. **The terminal attaches to a session another process runs.** The terminal already knows a run
only through Pi's JSON events from a child. Spawning `pic attach` in place of `pic --json` lets
it show and steer a conversation an editor started, or one left running in another window.
4. **One session messages another.** A conversation hands work or a finding to another, in the same
workspace or another, as a message the receiver reads after its running request.
5. **Tether.** A phone or browser is one more sender and observer; tether adds the network around
the same inbox and read path (below).
Subagents are not part of this note. pic has no subagent code today, and they need spawning,
waiting and cancelling a tree of conversations; they get their own design note, built on this
inbox.
Pi has nothing to copy here. Its RPC mode is a parent driving a child over stdin and stdout
(`modes/rpc/rpc-client.ts` spawns the child); a second process cannot reach a running session, and
extensions run in-process. Pi's Chord package links objects across worker processes, which is an
application framework, not a session protocol. pic's shared journal already does what grapevine
needs: several processes open it, each conversation has exactly one live owner, and that owner is
found by trying a lock, not by looking up an address.
## Transport and discovery
### The journal, not a socket
A message is an `INSERT` into the receiving workspace's journal. The sender needs no lease, because
the row changes no request; the lease holder turns it into the change. So [the shared-store
rules](shared-store.md) stand as they are: everything that changes a request still happens under
its lease.
There is no socket because there is often no process that could own one. `pic --mode rpc` idles
with the journal closed, and the terminal runs each request as a child, so an idle conversation has
no listener. Beyond that:
- Nothing on a socket survives a crash, so every message would be journaled anyway; the socket
would carry only the news that a row exists, which a file watch carries.
- Socket files go stale after a crash and need cleanup with races of its own. Lease files cannot go
stale: the kernel drops the lock.
- `sun_path` holds 104 bytes on macOS, which deep workspace paths exceed.
- A second path that bypasses the journal is a second thing [durability](../dev/durability.md)
would have to cover.
A socket belongs to tether, behind `pic attach` on stdio.
### Addresses
A conversation's address is its workspace and its conversation id. A conversation's name
(`pic_session.name`) is resolved to an id when the message is sent, never when it is delivered, so a
rename cannot redirect a message.
Discovery needs no endpoint registry:
- `pic sessions` already lists a workspace's conversations and marks those a live pic works (by
trying the lease shared for an instant).
- For other workspaces (stage 4), `~/.pic/pic.sqlite` gains `picu_workspace(path, journal_id,
seen_ms)`, written when a journal is opened. `pic sessions --all` lists them; a row whose path no
longer holds that journal (by `journal_id`, a random id this change adds to `pic_meta`) is dropped
when it is read.
Nothing needs cleaning after a crash: an inbox row is either committed or not, a lease is either
held or not, and a workspace row is checked when used.
### The narrow open
The sender does not use `pic_open`. It opens the receiving journal with a narrow open that takes the
journal lock shared, never runs `recover_abandoned`, never creates or migrates the schema, and
refuses when the journal's `schema_version` is not the one it was built for. A sender therefore
never recovers or migrates someone else's journal; it inserts one row and closes. Delivery is then
one transaction in one database, so there is no spool and no handoff between files.
### Waking: the bell and the watch
A process waiting for messages must notice a new row without opening the journal in a loop (every
open takes the write lock for a moment). After committing, the sender rings the conversation's
bell, `journal.sqlite.pic-leases/ID.bell`: it increments a counter in the file (a few bytes,
rewritten in place). Like lease files, bell files are never removed.
`pic_platform` gains one member, `watch(path)`, which returns a descriptor that becomes readable
when the file changes: kqueue with `EVFILT_VNODE` on macOS, inotify on Linux. A waiting process
watches its bell and reads its inbox when the descriptor fires. A platform with no watch returns -1,
and the caller stats the bell every 200 ms instead, comparing the counter rather than the mtime, so
two rings within one mtime tick are not mistaken for one.
The net layer's side descriptor (`pic_side_fd` in `src/net.c`) is a single slot that `pic --mode
rpc` already uses for stdin, so waits gain a second descriptor slot for the watch.
The bell is advisory. A sender that dies between its commit and the ring leaves a message that is
still delivered: at the next turn boundary, when the conversation is next opened, or at the
30-second fallback read a waiting process makes regardless.
The bell rings only for sends. A follower (`pic attach`, `pic send --wait`) notices the owner's
commits by holding a read connection open and polling `PRAGMA data_version`, which costs no lock
and no I/O beyond the WAL index; watching the WAL file is the alternative where polling costs too
much.
## Protocol
A message is **one Pi RPC command line**, stored verbatim, with an envelope in the row's columns.
The lease holder hands it to `pic_commands_line` in `src/commands.c`, the command table both `pic
--json --commands` and `pic --mode rpc` use, through a response sink that captures the response
line Pi would have printed instead of writing it to stdout. (`command()` in `src/rpc.c` is static
and bound to that process's stdout, so it is not the entry point.) Grapevine adds no command
vocabulary; a client that speaks Pi's RPC mode already speaks it.
The inbox takes `steer`, `follow_up` and `abort` in the first landing, and `prompt` from stage 3.
Queries (`get_state`, `get_messages`, `get_entries`, `get_tree`, `get_session_stats`,
`get_last_assistant_text`) need no inbox: `pic attach` answers them itself from the journal. Every
other command is answered by `pic attach` with an error naming the command as not available on an
attached session; each is added to the inbox when someone needs it.
| Column | Meaning |
|---|---|
| `msg_key` | the idempotency key, unique per journal; the sender chooses it |
| `command_hash` | SHA3-256 of the command line, to tell a retry from a conflict |
| `session_id` | the receiving conversation |
| `sender` | `cli`, `attach`, `session:JOURNAL_ID/CONVERSATION` or, later, `remote:DEVICE` |
| `command` | the RPC command line; NULL once the row is pruned |
| `hops` | 0 from a person or a script; the sending request's hops plus one from a peer |
| `target` | `abort` only: the request that was running when it was sent |
| `expires_ms` | after this, the message is expired instead of delivered; never NULL |
| `state` | `pending`, `delivered`, `refused` or `expired` |
| `response` | the RPC response line, written when the state leaves `pending` |
| `submission_id`, `queued_id` | what delivery made: a new request, or a queued steer or follow-up |
Every message expires. The default is 10 minutes for `steer` and `abort` and 24 hours for
`follow_up`; `pic send --expires SECS` overrides it, within a 7-day ceiling. A steer meant for this
run is never delivered days later into another.
Delivery follows Pi's rules for the same command on stdin: a steer joins the running request after
its turn's tool results, a follow-up runs after the request ends, and an abort is journaled as
Ctrl-C's cancel. A message to a conversation with no running request stays **pending**: it cannot
become a `pic_queued` row (`pic_queued.submission_id` is NOT NULL), and `pic --mode rpc` holds idle
steers in memory, not in the journal. It is delivered when a request next runs there, or it
expires. Through stage 3 nothing is started to deliver it.
Events go the other way through the journal too. `pic attach` reads committed rows in
`pic_entry.seq` order and prints Pi's events for them: `agent_start` and `agent_end` from the
request's status, `message_end` per entry, `tool_execution_start` and `tool_execution_end` from the
effect's states. Streamed text is not journaled. From stage 3 the owner appends it to
`journal.sqlite.pic-leases/ID.live`, an append-only file of the reply's text a follower reads
([remote control](../dev/remote.md) has its form); the owner removes it when the reply ends. It is
not durable and promises nothing.
## Durability
The promise in [durability](../dev/durability.md) is unchanged and extends to messages: **a message
that was accepted is delivered once, or reported as not delivered; it is never delivered twice.**
| What | Journaled | Guarantee |
|---|---|---|
| an inbox message | yes, its row | exactly once, by key |
| its response | yes, on its row | read any number of times while kept |
| what an observer sees | already journaled (entries, effects, requests) | at least once; the observer deduplicates by seq |
| the bell | no | may be lost; the fallback read covers it |
| streamed text (stage 3) | no | at most once; may be skipped |
- **Accepting.** One `IMMEDIATE` transaction through the narrow open. A new key inserts. A known key
with the same `command_hash` changes nothing and returns that row's state, so a sender unsure
whether its insert landed sends again: at-least-once sending becomes exactly-once acceptance. A
known key with a different command is refused as a conflict and writes nothing. When `pic send`
returns 0 the row is committed.
- **Delivering.** Under the lease, in one transaction: the row's state, its response and what it
made (the `pic_queued` row, the admitted request, or the cancel) commit together. A crash before
the commit leaves the row pending; after it, delivered. There is no state in between, so recovery
has nothing new to do: a pending row is not abandoned work but simply waiting, and the
conversation's next owner delivers it as part of normal work.
- **Order.** Messages to one conversation are delivered in commit order, so one sender's messages
arrive in the order it sent them.
- **Stale commands.** An expired row is marked `expired`, never run. An abort runs only if its
`target` request is still the running one; otherwise its response says there was nothing to
abort.
- **The sender's crash.** Either the row committed or it did not; retrying with the key is safe. A
peer's send tool derives its key from its own effect (`fx:JOURNAL_ID:EFFECT_ID`), so the send is
replay-safe in the recovery table's sense: a replay inserts nothing new.
- **The receiver's crash or restart.** Pending rows stay pending, delivered rows stay delivered, and
what delivery made recovers as any request or queued message does today.
`pic check` gains these invariants: a delivered row has its response and at most one of
`submission_id` or `queued_id` (none for an abort); a pending row has no response and neither; a
`queued_id` names a row of the same conversation; `expires_ms` is set on every row.
Dev builds gain fault points `inbox_accept` and `inbox_deliver`, each before and after its commit.
### Retention
`src/prune.c` prunes image bytes only, so the inbox has its own retention, run where pic prunes
today. A row that left `pending` more than 7 days ago loses its `command` and `response`; its
`msg_key`, `command_hash`, `state` and `session_id` stay. A key is never forgotten while its
journal exists, so a retry that arrives after its row was pruned still finds the key and cannot
deliver twice. A kept key costs under 100 bytes.
## Limits and loops
- **Size.** A command line may be as long as `pic --mode rpc` accepts on stdin (`LINE_CAP`, 16 MB),
so images travel inline as Pi's `images` field, as they do on stdin. Pending bytes per
conversation are capped at 64 MB and pending rows at 100; beyond either, the insert is refused
with a message and nothing is written.
- **Hops.** A peer's message carries the sending request's hops plus one, and a request started or
extended by a message inherits its hops. Over `grapevine.maxHops` (default 8) a message is
refused. Two sessions answering each other cannot loop forever, the same way an IP packet's TTL
ends.
- **Wakes.** From stage 4, each conversation counts the requests messages started in it since a
person's last prompt; over `grapevine.maxWakes` (default 3) a wake is refused. A person's prompt
resets the count. Hops bound a chain; this bounds fan-out.
## Waking an idle conversation
Through stage 3, a message never starts a request. Stage 4 adds one receiver setting,
`grapevine.wake` (default off), read by the wake component, not by core's delivery. When the
receiver allows it and a `prompt` arrives for an idle conversation, the sender spawns `pic run
--session ID` detached, since there is no daemon to do it; `pic run` takes the lease, admits the
prompt, and runs it like any request. If the spawned run dies, the row stays pending and the next
owner delivers it.
Per-sender policy is not a table. `UserPromptSubmit` input gains `origin` (`user`, or the sender),
and a hook that refuses, queues or allows a peer by name is the policy; hooks are already journaled
and already decide whether a prompt runs.
## Security
- **Same user only.** Messages live in files only their owner can write: `~/.pic` is 0700, the
journal's directory and lease directory are 0700. Before inserting into a journal, the narrow open
checks that the journal belongs to its own uid and refuses otherwise, so a group-writable journal
of another user is never written. Anyone who can write the journal could already do anything pic
does; grapevine adds no new door.
- **No network.** Grapevine opens no port and no socket and listens for nothing. Crossing machines
is tether's job, by running `pic attach` at the far end of a connection.
- **Peer text is data.** A message from a session reaches the model inside a harness-written frame
that names the sender and states that the text is a message, not the user's instruction. The
sender is recorded on the request or queued message it made, and hooks see it through `origin`.
Peers cannot act as the user in anything the user alone decides, and a peer's `abort` is refused
for a request the peer did not start.
## Tiers
Grapevine sorts by the keel principle: core records and enforces; components decide.
| Piece | Tier | Why |
|---|---|---|
| `pic_inbox`, its migration, the narrow open, accept and deliver, expiry, key conflicts, hops, limits, retention, `pic check` rules, fault points | core | the record a crash leaves and the rules that keep it true |
| `pic_platform.watch` and the bell | core | an OS seam |
| the response sink in `src/commands.c` | core | the command table already is |
| `pic send` | root | a few lines in `main.c` over core's accept |
| the sender on entries and requests, `origin` for hooks | core | recorded before it takes effect |
| `pic attach` (`src/attach.c`) | bundled, seam: inbox and read view | a protocol client of the journal; core runs without it |
| the peer frame's wording | bundled, seam: prompt assembly | taste; changes with prompting |
| the send tool for peers | bundled | a decision about what the model may do |
| the wake component | bundled | a decision; core records its outcome on the row |
| `grapevine.wake`, `grapevine.maxHops`, `grapevine.maxWakes` | data | settings |
Whether a message may wake a conversation is a decision; core records the decision on the row
(`refused`, with its reason, or the request it made) before it takes effect, and recovery reads the
row and never asks again.
## What tether needs from it
- **One write path.** Every command from a remote client becomes an inbox row with a key, a sender
and an expiry before it acts, exactly as a local one does. Tether adds `remote:DEVICE` senders,
not a second inbox.
- **A resumable read path.** `pic attach --from SEQ` gives a replica that catches up from its last
seq after any disconnect, with no gap and no duplicate.
- **stdio.** `pic attach` speaks Pi's RPC on stdin and stdout, so `ssh host pic attach ...` is the
first remote transport, with no new cryptography. Any socket tether adds sits behind it.
- **Streamed text** from the `.live` file, which a remote screen can sample without the journal
paying for every delta.
Tether owns everything else: relays, pairing, encryption, push notifications, a phone page, and
durable questions a person answers from elsewhere.
## Not goals
- Listening on any socket or port, a broker, or a daemon.
- Two processes advancing one conversation; the lease still decides.
- Sync or merging of journals between machines.
- A general publish-subscribe bus, or Agent2Agent or MCP spoken natively (an adapter can sit on
`pic attach` later).
- Delivery to another user, or across a uid boundary.
- Peers answering approvals or questions meant for the user.
- Subagents (their own note, later).
- A latency promise better than the fallback tick where no watch exists.
## Stages
Each stage is one landing with its manual topic, reference rows and changelog line.
1. **The inbox and `pic send`.** `pic_inbox` with default expiry, key conflicts and the `pic check`
rules; the narrow open; `pic_platform.watch` and the bell, with the stat fallback; the response
sink in `src/commands.c`; the fault points `inbox_accept` and `inbox_deliver`. `pic send
[--session ID] [--key K] [--expires SECS] COMMAND-JSON` takes `steer`, `follow_up` and `abort`,
in the same workspace only. Only a process already running a request delivers, through
`src/commands.c`, at turn boundaries and while it waits; a message to an idle conversation stays
pending until a request runs there or it expires. Left out: `prompt`, idle delivery, waking,
other workspaces. Useful at once: an editor or script steers or aborts any running pic. Tests, in
`test/pic/grapevine.sh` with the scripted provider: a turn that runs `sleep` leaves a window; a
steer, follow-up and abort sent from a second process each reach the run exactly once and in
order; the same key and command sent twice makes one row; the same key with another command is
refused; an expired message and an abort whose request has ended are not run; a full inbox
refuses; a journal of another schema version is refused without being touched; with the watch
disabled, the stat fallback still delivers. `crash.sh` crashes at both fault points and checks
one delivery or a pending row. `shared.sh` races two pics to deliver one row and kills the sender
between commit and bell.
2. **`pic attach` and following.** `pic attach [--session ID] [--from SEQ]`: Pi's RPC on stdio,
queries from the journal, inbox commands through it, events rebuilt from committed rows,
following through `PRAGMA data_version`; `pic send --wait` prints the response line; retention.
Tests: while one pic runs a scripted request, the committed events `pic attach` prints match the
owner's `--json` stream with `message_update` removed; an attach killed mid-run and restarted
with `--from` sees no gap and no duplicate; a pruned row's key still refuses a second delivery.
3. **The terminal attaches; idle delivery.** The session picker offers live conversations; choosing
one runs `pic attach` as the terminal's child. The owner writes the `.live` file, and followers
tail it. `prompt` joins the inbox, and `pic --mode rpc` delivers pending messages when it next
runs a request; nothing is started to deliver them. Tests: the terminal's scripted tests attach
to a run another pic owns, steer it, and see streamed text and the reply; killing the owner
leaves the terminal showing the recovered state.
4. **Peers and waking.** The send tool (replay-safe, key from its effect), the peer frame, hops,
`origin` for hooks, other workspaces through `picu_workspace`, and the wake component with
`grapevine.wake` and `grapevine.maxWakes`. Tests: two scripted conversations, one sends to the
other; a crash between the tool's start and its result sends once; a two-session loop stops at
`maxHops`; a fan-out stops at `maxWakes` and a person's prompt resets it; a `UserPromptSubmit`
hook refuses a peer message; with waking on, a prompt to an idle conversation runs through a
spawned `pic run`, and a killed spawn leaves the row pending; a journal owned by another uid is
refused (skipped where the test cannot make one).
5. **Tether's first stage** builds on stages 1 and 2 with `ssh` as the transport.
## Decisions
These were open when the note was proposed and are settled:
1. **Transport.** The journal delivers, a kernel file watch wakes, and there is no socket; a socket
belongs to tether, behind `pic attach`.
2. **Other workspaces.** A direct insert into the receiver's journal through the narrow open; no
spool in `~/.pic/pic.sqlite`.
3. **Waking.** Never through stage 3; then one receiver setting read by a component, a spawned
`pic run`, hooks with `origin` as per-sender policy, and a wake count alongside hops.
4. **Which commands.** `steer`, `follow_up` and `abort` first, `prompt` in stage 3, the rest when
someone needs them.
5. **Subagents.** Later, in their own design note, on this inbox.