# Loops, monitors and goals
Status: signed off 2026-11-24 (the proposal, with the owner's answers, is at
https://artifacts.craftdesign.group/v/JPi1WSWo57ggWxSnlNBtW#55b0e7bfbb4fe47e8b1ba9a173a7749e230ed87432e0dacceb5570c0dfb079b2).
Built 2026-11-24 in four steps: the record and `/loop`; pic remote and the phone; `/monitor`;
`/goal` with the stop policy and the model's `wake` tool.
## The shape
One journaled record, a wake: "send this conversation this prompt when that happens". A loop fires
on the clock, a monitor on new output from a command, a goal when a request ends with the goal
unmet. People see loop, monitor and goal; "wake" is the internal word.
Tier: core (`src/wake.c`). Clock: durability. Record: a `pic_wake` row per wake, a `pic_inbox` row
per fire. Default: no wakes; nothing fires.
The commands (`/loop`, `pic loop`), the list and the footer are clients of the RPC commands
`get_wakes`, `create_wake`, `pause_wake`, `resume_wake`, `stop_wake` and `pause_wakes`, which are
core's, as the record is. Tier: client (`src/tui/`) and root (`main.c`). Clock: taste. Record: none
of their own. Default: on.
## The fire
One `IMMEDIATE` transaction: the wake is read again (still active, its time come, no fire of it
waiting), its fire count, last fire and next due time advance, and the inbox row is inserted with
`msg_key` `wake:ID:N` and sender `wake:ID`. A crash before the commit leaves nothing; after it the
inbox row is pending and [the inbox](../dev/inbox.md) delivers it once. Two processes that both see
a due wake queue on SQLite's write lock; the second finds it advanced. The bell is rung after the
commit.
A fire is a prompt with `streamingBehavior` `followUp`: with a request running it is a follow-up
and becomes the next request; with none, a pic run takes it up as a request keyed
`inbox:wake:ID:N`. Its text is the prompt, then one bracketed line naming the loop, its interval
and its run, and saying it was not typed just now (after the prompt, so a conversation a loop
began is titled by the prompt); a fire that stands for missed runs says how many, and the last
says it is the last.
## Who keeps time
No timer. Whoever has the journal open asks what is due (`pic_wake_due`): a read first, then a fire
per due wake. The terminal interface asks through `get_wakes` with `fire: true`, every 2 seconds
while its conversation has loops and every 15 otherwise; a running request's inbox poll asks for
its own conversation, so a due loop becomes its follow-up without starting anything; `pic loop
fire` asks once; `pic remote` asks for every journal it serves every 5 seconds, so loops fire with
the terminal closed. With no pic running, nothing fires, and the list says "not firing" once a
wake is 90 seconds overdue.
After firing, a conversation with a fire pending and no lease held gets a `pic run --session` in a
session of its own (`pic_peer_start` in `src/peer.c`, registered by the composition root as the
wake starter), with every descriptor past stderr closed so it holds nothing of its starter's. One
start per conversation per 30 seconds per process, so a run that cannot take the fire up (its
model has no key) is not started on every look.
## Monitors
Tier: bundled (`src/monitor.c`, seam `pic_wake_monitor_ops` in `src/wake.h`). Clock: os. Record:
the monitor's `pic_wake` row: `command`, `spool`, `read_offset`, `pid`, `pid_started_ms` (the
process's start token, procs.h), `exit_code`. Default: on.
Making a monitor commits its row, with its spool `<journal>.pic-monitors/ID.log`, then starts the
command (fault point `monitor_started`), then records its process in a second transaction. The
runner starts `/bin/sh -c` in a session of its own, with every descriptor past stderr closed (it
inherits no lease), under a wrapper that writes its own pid to `SPOOL.pid` first, appends the
command's output to the spool, and writes its exit status to `SPOOL.exit` last.
Each look at an active monitor, outside any transaction until it fires: a row with no pid adopts
the process `SPOOL.pid` names when it is alive, and after 30 seconds with none ends as "did not
start"; a process gone with no status is started again with `--restart`; otherwise the bytes past
`read_offset` up to the last newline are its new lines. The fire is one transaction that checks
the offset and fire count it read from are still the row's, inserts the inbox row, and moves the
offset to where it read, so a line is sent once whoever looks and however a crash falls. A fire
sends the newest 8 KB from a line's start, counting the lines left out. While a fire waits, the
offset stays and the lines gather. A command that has exited (its status in `SPOOL.exit`) or is
gone, or a monitor past its 7 days, fires once more with the rest and ends; `--done` fires only
then, with the newest 8 KB. Stopping a monitor, or its expiry, signals the command's process group,
only while its pid still has its recorded start token.
## Goals
The stop policy seam. Tier: core (`src/policy.h`). Clock: durability. Record: a `pic_hook_run`
row per answer (event `StopPolicy`, `ref` the goal). Default: no policy; requests end as they do
now. The goal component and the wake tool. Tier: bundled (`src/goal.c`, registered by the
composition root). Clock: taste. Record: none of their own. Default: on; `loops.tool` false takes
the tool away.
A goal is due once, when it is made or resumed (`due_ms`); its first round is a fire like a loop's.
While a goal is active, a finished reply in its conversation stays an assistant turn so the stop
gate sees it. At the gate, once the Stop hooks and any verdict let the reply stand,
`pic_wake_goal_judge` runs the check, if there is one, as a hook run of event `GoalCheck`: committed
as started before the command runs (fault point `after-goal-check-started`) and done with its exit
status and the last 8 KB of its output after; recovery turns a started one interrupted, it is never
run again, and its exit status is unknown. Then the policy is asked with facts from the journal
alone (the round, the stalls, whether a file changed or a command ran in the request, the check's
status and output and whether they equal the last round's, and what the model declared with the
tool during the request), through `pic_hooks_ask`, so the first answer for a request stands.
`pic_wake_goal_apply` acts in the transaction that makes the reply the answer: done ends the goal,
needs pauses it for the person, continue raises the stall count or clears it and inserts the next
round as the inbox row `wake:ID:N`, unless core's bounds (50 rounds, 3 stalls in a row) say it
needs the person instead. The process that ran the round takes the next one up at once
(`pic_inbox_wake`), as it holds the lease. Each round is a request of its own: its own usage, its
own notification, its own clean stopping point; Esc on one pauses the goal. Resuming clears the
stalls and gives a goal at its limit 10 more rounds.
The bundled policy: a check that exits 0 meets the goal; without a check, the model's `goal_done`
does, and the end says "declared done, not checked"; `goal_blocked` needs the person; otherwise
continue, a stall when the request changed no file and ran no command, or the check said what it
said last time or was cut off.
The `wake` tool (not replay-safe: a call cut off by a crash may have started its monitor) starts a
monitor freely. A loop or a goal it makes is created waiting for the person's OK: state `needs`,
why "waiting for your OK", `options.approval` `asked`; nothing fires and resume refuses it. The
person answers in the terminal's one-line prompt, `/loop approve|decline`, the phone's Start and
No, or `pic loop approve|decline`; `pic_wake_decide` is one transaction that makes it active (due
now) or ended "declined", sets `options.approval`, and inserts a steer from `approval:ID` (key
`approval:ID`, kept 7 days) that tells the model at its next request (fault point `wake_decide`,
arrivals 1 and 2 around the commit). A repeat of the same answer changes nothing. The tool also paces a loop given no interval (`loop_next`, 60 to 3600 seconds; every
such loop's fire says so, and without it the loop runs again in 10 minutes); and records
`goal_done` or `goal_blocked` with a reason in the goal's `options`, read by that request's policy
answer.
## Missed and overlapping ticks
A loop is due when its due time has passed, or when its last fire is ahead of the clock (the clock
stepped back: it fires once and is anchored anew). Missed runs fire once: the next due time is the
first slot after now on the loop's own grid, and the fire says how many runs came due. While a fire
waits (its inbox row pending, or delivered as a follow-up still queued) the loop does not fire
again; it fires once when the waiting one has been taken up.
## Bounds
A wake expires 7 days after it was made: the fire that finds it expired is its last and says so,
and it ends. Eight wakes a conversation that have not ended. The shortest interval is one minute; a
loop given none runs every 10 minutes. There is no dollar cap: spend is shown, summed from the
journal's usage rows of the requests a wake started (`PIC_WAKE_OF_SQL`), never a counter. Rounds
(50) and stalls (3) bound goals (step 4).
A wake's fires are exempt from `grapevine.maxWakes`, which bounds messages between conversations.
## Stopping
Cancelling a request a wake started (Esc, Ctrl-C, an inbox abort from a phone or attach) pauses
that wake, in the cancel's own transaction (`pic_wake_cancelled`). `/stop` pauses every wake of the
conversation and opens the list. Paused is never deleted: a mistaken Esc costs one resume.
Resuming keeps the due time, so a loop paused past it fires at once, once.
## The record
`pic_wake(id, session_id, kind, prompt, every_ms, command, options, state, why, creator, fires,
due_ms, fired_ms, created_ms, expires_ms, updated_ms, spool, read_offset, pid, pid_started_ms,
exit_code, rounds, max_rounds, stalls, max_stalls)`, schema 21, with every column the three kinds
need so later steps take no schema step. `state` is `active`, `paused`, `needs` (a person has to
look) or `ended`; `why` says why for any but active. `pic check` adds: a wake's conversation
exists; its fire count equals its inbox rows, keyed `wake:ID:1` to `wake:ID:N`; an active loop has
an interval and a due time; a wake not active has a reason. Fault point `wake_fire`: arrival 1 just
before the fire's commit, 2 just after. `test/pic/wake.sh` crashes at both and at `inbox_wake`,
and counts the provider's requests to show each fire ran once.
## The phone
[The protocol](remote-protocol.md) (amendment "Loops") carries `get_wakes`, `pause_wake`,
`resume_wake`, `stop_wake` and `pause_wakes` as pic's own commands to a conversation, answered by
`pic remote` from the journal; the list of conversations carries each one's `loops`; a loop that
comes to need the person is one notification, found by the change time of its row past the newest
`pic remote` had seen when it started, so a restart repeats nothing.
## Not built here
A judge model for goals with no check (the seam takes one as a second component), `pic send
--wake`, the cost estimate from the price (the confirming line says the context's tokens),
the cache-lifetime note on intervals, the notification's own Resume and Stop actions (a tap opens
the conversation, where they are), and the mock-up round for the list and the phone.