# Shared journal store

Several pic processes may open one workspace journal at once, each working
its own conversation. This replaces the rule "one pic process owns the
journal" (durability contract D18) with "one pic process owns a
conversation at a time".

Status: in force. Built as described; `docs/dev/durability.md` is the standing description, this
file the reasoning.

## What the user gets

- While one pic runs a long task, a second pic in the same project can ask a
  side question in a new conversation, work another conversation, or look at
  the live one (`pic dump`, `pic sessions`, `pic log`, `pic check`,
  `pic tui -c`).
- A conversation is worked by one process at a time. A second process that
  tries to advance it is told who has it:
  `conversation ab12cd34 is in use by another pic process (pid 4711)`.
- `pic run` finishes the requests nobody is running and leaves the others
  to their owners.
- When `edit` cannot find its text, or `write` would replace a file, and the
  journal shows another conversation changed that file since this one last
  saw it, the tool result says so and carries the current text.
- `pic sessions` marks the conversations another pic is working.

Not offered: merging, two processes in one conversation, sync between
machines.

## The problem

The exclusive lock did two jobs. It kept writers apart, which SQLite can do
by itself. And it was the proof that the previous owner was dead: at open,
every `started` effect, generation and hook run was known to be abandoned,
so recovery could mark it `unknown` or run it again. With two live
processes that proof is gone. Recovery that treats a live process's
`started` effect as abandoned would mark a running command `unknown`, or
run a replay-safe tool twice at once.

So the design question is liveness, not locking: how does a process know
that the owner of some unfinished work is gone, and how do two processes
never run the same request.

## Model

Two locks, both `flock`, both released by the kernel when their holder and
the children it forked have all exited.

### 1. The journal lock (shared)

`<journal>.pic-lock`, the file that exists today. Every open store holds it
**shared** for its lifetime. It is taken **exclusive** only to create or
migrate the schema.

- A migration needs every other pic out of the journal. If the exclusive
  lock is not free within two seconds, open fails:
  `this journal needs migrating to schema N and another pic process has it open`.
- A pic built before this change takes the same file exclusive. It is
  refused while a sharing pic is open, and a sharing pic is refused while it
  runs (`database is owned by another pic process`). No schema bump is
  needed to keep old and new apart.
- The lock path is derived from the journal's real path, so a symlink to
  the journal reaches the same locks. (Hard links to a journal are not
  supported; today's SQLite exclusive mode caught them, this does not.)

### 2. The conversation lease (exclusive)

`<journal>.pic-leases/<conversation id>`, one small file per conversation
being worked. Holding its exclusive `flock` is the right to advance that
conversation: to run its request, journal `started` rows under it, cancel
it, compact it. The file holds the owner's pid, for messages only; the lock
is the truth.

    lease held      the conversation has a live owner; leave its work alone
    lease free      nobody is working it; whatever is `started` under it
                    was abandoned and may be recovered by whoever takes it

One mechanism answers both questions. Liveness is "can I take the lease".
Claiming a request is "I took the lease". There is no owner table, no
heartbeat, no timeout, no pid check, and no schema change: every `started`
row already maps to a conversation (effect and generation through their
request, hook run through `session_id`).

A lease cannot go stale. A process that dies by any means drops it. A
running command's supervisor is a forked child and holds it too, so the
lease outlives a killed pic exactly until its command has been killed,
which is what recovery needs before it writes `unknown`.

Lease files are never removed: they hold no state (as the journal lock's
file holds none), and a child the owner forked may still hold the lock.
An unlocked file is a free lease, whoever left it. Looking at who holds a
lease (`pic sessions`, error messages) takes the lock shared for an
instant; a taker tries a few times a millisecond apart even when it does
not wait, so a look is never mistaken for an owner.

### Rules

1. **Lease before work.** A process takes a conversation's lease before it
   journals anything recovery interprets (`started` effects, generations,
   hook runs) and before it changes the state of the conversation's
   request. It holds it until its store closes. `pic run` gives back the
   lease of each leftover conversation as it finishes it.
2. **Taking a lease recovers.** The first thing the new owner does, in one
   transaction, is today's recovery restricted to that conversation:
   replay-safe `started` effects back to `intent`, the others to `unknown`,
   `started` generations to `failed`, `started` hook runs to `interrupted`,
   waiting results flushed.
3. **Read after you hold.** A claimer re-reads the request's status after
   it has the lease. Everything that changes a request happens under its
   lease, so what it reads then is stable.
4. **Admission stays a transaction.** "One unfinished request per
   conversation" is still decided inside `BEGIN IMMEDIATE`. The lease adds
   who runs it.
5. **No write transaction across provider or tool I/O.** Unchanged. A lease
   is held across I/O; a write transaction never is.

### Open

    lock journal (shared)  ->  open SQLite  ->  schema current?
       no: swap to exclusive, create or migrate, swap back to shared
    for each conversation with `started` rows: try its lease without waiting
       taken: recover it (rule 2), release
       held:  a live owner; skip
    check invariants

So an open still settles everything the dead left behind, as it does today,
and touches nothing the living hold.

### Waiting

A lease held by a dying process (its supervisor is still killing a command)
frees within moments. Whoever wants a specific conversation waits up to one
second for it, as open waits for the journal lock today. `pic run`, which
wants any free request, never waits on one while another is free; when
nothing is free but something is held, it waits once, up to a second, then
returns 0 and says what it left:
`pic: request KEY is being run by another pic process (pid N); left to it`.
`pic hooks end OWNER` waits up to 60 seconds per conversation, as it does
today for the journal, because the holder is normally that owner's own
dying child.

## SQLite

- `locking_mode=NORMAL` replaces `EXCLUSIVE`. WAL, `synchronous=FULL` and
  `fullfsync` stay. Writers queue on the WAL write lock. A read never
  waits, but every open does: it runs the (idempotent) schema transaction,
  which takes the write lock for a moment. So a write transaction held for
  long stalls every pic that starts, readers included, which is why the
  next rule has no exceptions.
- No write transaction spans anything outside the journal. `pic import`
  reads all of its input, and `pic import --claude` loads the transcript
  into temporary tables, before beginning.
- Every write transaction already starts with `BEGIN IMMEDIATE`, so there
  is no read-to-write upgrade and no deadlock.
- Busy handling: the fair jittered handler `~/.pic/pic.sqlite` already uses
  (userdb.c), shared, with a longer deadline for the journal (30 s; write
  transactions are a few statements and one fsync). Past the deadline a
  statement fails with `database is locked`; the process stops as on any
  storage error, its lease drops, and the request is finished by the next
  `pic run`. That is a crash as far as the journal is concerned, and the
  crash rules cover it.
- `SQLITE_BUSY_SNAPSHOT` (a write begun under a read cursor that another
  process has since overtaken) cannot be waited out. The rule is "no write
  while one of this connection's statements is mid-row". Dev builds assert
  it in `pic_begin`, so the existing suite finds every place that breaks it.
- A platform that supplies its own VFS (pic as the whole guest of a
  microVM) keeps exclusive mode: there is one process and maybe no shared
  memory.
- Forked children (parallel tools, command supervisors) inherit the
  connection and never use it, as today.

## What changes, by module

The lease lives in the store. Callers outside `store.c`, `loop.c` and
`hooks.c` do not learn about it.

**store.c**
- The journal lock becomes shared, with the exclusive swap around create
  and migrate. With the version current the schema transaction still runs
  (it is idempotent and writes nothing), under the shared lock.
- `pic_lease(s, session, wait_ms)`: 0 held (idempotent; recovers on first
  take), 1 in use by another process (`s->err` names it), -1 error.
  `pic_unlease(s, session)`. `pic_lease_holder(s, session)`: the pid of a
  live owner, or 0. `pic_close` drops every lease.
- The fair busy handler is userdb.c's, exported as `pic_busy_wait(db, ms)`.
- SQL function `pic_leased(session_id)`: this store holds it. Lets the
  loop's SQL say "mine" without C at each call site.
- `pic_open`: the recovery pass above; normal locking mode; the busy
  handler.
- `pic_check`: `effect left started` and `generation left started` become
  "started under a finished request": a `started` call or reply under an
  unfinished request is a legal journal state now (live, or awaiting
  recovery). `hook run left started` goes: a hook runs outside requests too
  (SessionStart, SessionEnd), and one left by a dead process is settled by
  its conversation's next owner. All other invariants are unchanged. The
  check runs in one read transaction, so it sees one state of a journal
  another process is writing.

**platform.h / platform.c**
- `lock(path, shared)`: the one change to the seam.

**loop.c**
- `pic_recover(s)` becomes `pic_recover_session(s, session)`, called by
  `pic_lease`.
- `pic_run` picks the oldest admitted request whose conversation it holds
  or can take, skips the rest, and gives leftovers' leases back. The
  conversation it was asked to run (`s->running`) is already held.
- `pic_submit_hooked`, `pic_bash_record`, `pic_cancel`, `pic_compact_now`
  and `pic_branch_summarize` (the source conversation, and the one whose
  request its summary is journaled under: an ancestor after a fork) take
  the lease first. A lease taken inside the admitting transaction settles
  a dead owner's work within that transaction. A request `pic run` passes
  over because its model cannot be had gives its lease back at once. `pic cancel` of a request a live process is running is refused
  with that process's pid; today it is refused too, by the journal lock.
- `pic_hooks_run_pending` runs only the pending rows of leased
  conversations.
- `pic_bash_record` names its kept output by the entry's sequence number,
  guessed before the entry exists. Another process can take the number;
  the record then journals nothing and returns the number the entry will
  have, and `pic_bash_run` renames the output and records again.
- `pic_dump` runs in one read transaction.
- The stale-file result (below).

**hooks.c**
- Firing an event for a conversation takes its lease (already held inside
  a run; this covers SessionStart, UserPromptSubmit before admission, and
  SessionEnd).

**main.c**
- The retry loop for `hooks end` goes (the wait is in the lease). `ask`
  takes the lease of a named conversation before its hooks run, so a
  refused prompt runs none. Nothing else: `ask`,
  `submit`, `run`, `chat`, RPC and the terminal interface already open the
  journal only while they handle one input.

**toolpar.c, tools.c, the TUI, `pic ps`**
- No change. Tool children talk only to their parent. The interface's
  children are ordinary `pic ask` processes, each leasing its conversation.
  `pic ps` already records per workspace and conversation in
  `~/.pic/pic.sqlite`.

**Schema.** No table changes and no migration. (If review wants `pic
sessions` to show owners without probing leases, that would be the first
schema change; not proposed.)

## The stale-file tool result

Two conversations in one workspace can change the same file. pic does not
merge. It tells the agent what happened, with what it needs to redo the
work.

The journal knows which conversation wrote what: every `edit` and `write`
is an effect with its path. A file is **stale for a conversation** when
another conversation has a finished, successful `edit` or `write` of that
file later than both this conversation's last finished `read`, `edit` or
`write` of it and the moment this process took the request up (paths
compared by `pic_tool_path_key`; "this conversation" is the path to its
head, so a fork inherits what its parent saw). The second bound is what
makes a lone pic behave exactly as before: one process runs one request at
a time, so anything another conversation journaled since this process took
the request up was another process's doing. An earlier conversation's
write, a parent's write after a fork point, a fork's write before its
parent resumes: none of them is "changed since". The price is that a
change made while this conversation was idle is not reported; the edit
gets Pi's plain error and the agent reads the file.

- **edit** whose text is not found, or is no longer unique, in a stale
  file: the usual error, then

      PATH was changed by another pic conversation (ID) after this one last
      read it. Its current text follows; redo the edit against it.

  and the file as `read` would return it (same line and byte caps, same
  truncation notice).
- **write** to a stale file is not performed. The result is an error with
  the same note and current text, ending `write again to replace it`. That
  result counts as this conversation seeing the file, so a second write
  goes through, as does a write after an edit result that showed it.
  Without this, a write silently discards the other conversation's work;
  this is the one place pic departs from Pi's unconditional write, and only
  when the journal proves the overlap. It is journaled as hook denials
  are: the effect goes from `intent` to `skipped` with the result.
- An edit that still matches is applied, as today: it replaces exactly the
  text the agent named.
- Changes made through `bash` are not tracked; such an edit gets the usual
  error.

It is computed in the loop, in the parent process, when the call's result
is journaled (edit) or before the call is started (write); tools.c does not
change beyond exporting the path key it already has.

## Failure cases

**kill -9 of A while B works.** A's lease drops (once its command
supervisor has killed the command). B is not disturbed: it never looks at
A's conversation. The next process to open the journal takes A's lease in
its recovery pass and settles A's `started` rows; the next `pic run` (or
`ask --session`) finishes the request. B's own `started` rows are under B's
lease and are skipped by everyone.

**A crashes between "started" and the tool's effect, or after it.** Same
as today, per conversation: replay-safe runs again from its journaled plan,
unsafe becomes `unknown` and is never run again.

**Two processes race to claim one admitted request.** Both `flock`; the
kernel picks one. The loser skips it. If the winner finishes and releases
before the loser tries, the loser takes the lease, re-reads the request
(rule 3), finds it finished, and gives the lease back.

**Two processes race to admit into one conversation.** The lease orders
them; behind it, the admission transaction still refuses a second
unfinished request.

**Two processes create or migrate the journal at once.** One gets the
journal lock exclusive; the other waits up to a second, retakes it shared
and finds the schema current, or is refused.

**A lease file left by a crash.** Unlocked, so free. The next taker
recovers the conversation.

**A lease holder that hangs** (alive, not progressing) keeps its
conversation, as a hung pic keeps the whole journal today. Kill it.

**Writer starvation or a stuck fsync.** After 30 s the waiting statement
fails and its process stops; see Busy handling.

**Process dies holding the journal lock exclusive** (mid-migration). The
migration is one transaction; SQLite rolls it back; the lock drops.

## Tests

New `test/pic/shared.sh` (Makefile `PIC_SCRIPTS`, `tools/remote/payload.sh`),
using the suite's `await`/`HOLD` so nothing depends on timing:

1. Side question: A holds in a tool; B asks in a new conversation and is
   answered; `dump`, `sessions`, `log`, `check` succeed meanwhile; A then
   finishes; both answered.
2. Recovery leaves the living alone: while A holds a `started` unsafe
   effect, B opens, runs and exits; A's effect is still `started`, then
   `done`, and its command ran once.
3. kill -9 A mid-command while B is mid-run: B finishes untouched; `pic
   run` then settles A (`unknown`, command not run again, not left
   running).
4. Crash matrix with a live neighbour (fault builds): for every
   `PIC_CRASH_AT` point of crash.sh, crash A there while B holds a
   `started` effect; `pic run` finishes A with the same ledger counts as
   the one-process matrix; B is unaffected and `pic check` passes at every
   step.
5. Claim race: one admitted request, four `pic run` at once; its command
   ran exactly once; all exit 0.
6. `pic run` beside a live owner: returns 0, names the request it left,
   changes nothing.
7. Admission race: two submits to one conversation; exactly one admitted.
8. Same conversation: `ask --session X` while X is live is refused naming
   the pid; no hooks ran for it.
9. `cancel`: refused for a live request; works once its owner is killed.
10. A leftover lease file does not block; a symlinked journal path meets
    the same leases.
11. Stale file: edit miss with another conversation's edit in between
    carries the note and current text; write is refused once, then goes
    through; with one conversation the Pi messages are unchanged.
12. Load: four processes, several tool calls each; no `database is locked`.
13. An import waiting on a pipe keeps no other pic waiting.
14. A request passed over for its model is taken by a second pic while the
    first still runs.
15. One pic and a fork: the parent's later write is not reported.
16. The matrix again for two calls in one turn.

Changed: crash.sh `fence` and `alias` (a second `pic run` now returns 0 and
leaves the request, instead of being refused); an old-style exclusive
holder of `.pic-lock` still gets `owned by another pic process`.
migrate.sh: a migration is refused while another process holds the journal
lock, and runs once it is released.

## Out of scope

- Merging concurrent edits, or any conflict resolution beyond the tool
  result.
- Sync between machines. The lease is a local `flock`; a journal on a
  network filesystem is not supported by this.
- Two processes in one conversation (watching a live conversation is
  reading the journal; steering it from a second process is not offered).
- Cancelling another process's request from outside (the message gives its
  pid; Ctrl-C or SIGINT there cancels it).
- Tracking file changes made by `bash`.
- Hard-linked journal paths.
