@srobroek/pi-delivery 0.0.0-stage → 0.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,3 +1,571 @@
1
- # Temporary Holding Version
1
+ # delivery
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Lands pull requests with proof, cleans up after them, and ships the delivery
4
+ agents and instructions for fanning work out to subagents.
5
+
6
+ Ported from the omp-plugins `delivery` plugin (1.4.3 plus the land-fetch fix).
7
+ `delivery_hygiene_report` and the `worktree-reaper` agent were not ported: use
8
+ `git worktree list` for an inventory. A receipt for a branch whose worktree still exists
9
+ means `delivery_cleanup` has not run yet (or `delivery_land` could not finish it).
10
+
11
+ ## Install
12
+
13
+ ```sh
14
+ opencode plugin add 'github:srobroek/harness-plugins::path:plugins/delivery/opencode'
15
+ ```
16
+
17
+ The implementer agents spawn `explore`, `operator` and `researcher`. Nested
18
+ subagents need `experimental.subagent_depth` of at least 2 in your config.
19
+
20
+ ## Tools
21
+
22
+ | Tool | What it does |
23
+ | --- | --- |
24
+ | `delivery_land` | Proves a pull or merge request landed (merging it at most once) and writes one landing receipt. |
25
+ | `delivery_cleanup` | Removes the receipt's worktree and local branch after proving the landing and the bead close-out, then writes a continuation receipt. |
26
+
27
+ Both tools take JSON Schema input and declare an output schema, so Code Mode
28
+ callers get typed results. The same fields (without the full receipt) are stored
29
+ in the tool result's `metadata`. Both tools honour cancellation: an interrupt ends
30
+ the running `git`, `gh` or `glab` command. `delivery_cleanup` stops honouring it
31
+ once `git worktree remove` starts, so a removal is never left half done.
32
+
33
+ ### delivery_land
34
+
35
+ Inputs: `pr`, and when needed `merge_method` (`squash` by default, `merge`,
36
+ `rebase`), `repo`, `repoPath`, `remote`, `expectHeadSha`, `worktree`, `beadId`,
37
+ `setupAutoDelete`, `requireApproval`, `requireGreenChecks`, `queueWaitSeconds`.
38
+
39
+ Requires Git 2.38 or newer: the content proof compares the landed tree with
40
+ `git merge-tree --write-tree`. An older or unreadable Git refuses before any merge is issued.
41
+
42
+ - `expectHeadSha` is required whenever the call would merge. The merge is bound to
43
+ that head (`gh pr merge --match-head-commit`, `glab mr merge --sha`), so a push
44
+ between the read and the merge fails at the forge.
45
+ - `worktree` is recorded for cleanup, and its HEAD must be the PR head. Without
46
+ it, the linked worktree that has the PR's branch checked out at the PR head is
47
+ recorded; if none does, no worktree is recorded.
48
+ - `repo` selects, among the session repository's own remotes, the one whose URL
49
+ names `repo`; it must still match that remote.
50
+ - A pull request of another repository needs `repo` (`<owner>/<name>`) and a local
51
+ clone of it: `repoPath` (any checkout) or a `worktree` of that repository.
52
+ - The tool runs in that clone's checkout root, not the session directory.
53
+ - It refuses unless one of the clone's own remotes names `repo`.
54
+ - The bead ledger and every other check read that clone. The tool writes the receipt
55
+ under the clone's repository key and canonical root.
56
+ - The cleanup after such a landing uses that repository's own coordination: its lane
57
+ claims, landing records, holds and removal lock live under its git common directory.
58
+ `next` scopes the bead close-out commands to the clone and ends with
59
+ `delivery_cleanup repo=<owner>/<name> repoPath=<root>`.
60
+ - A cleanup that does not finish is retried at the turn end of the session that landed
61
+ it. The session lists such clones in `<receipts root>/.clones/<session repo key>.json`,
62
+ so a restart finds them. An entry is dropped once its receipts are cleaned or
63
+ superseded and that repository's landing records are collected.
64
+ - Name only clones you control. The tool trusts the clone like the session directory.
65
+ - With no `repo`, or the session's own, a `worktree` must belong to the session
66
+ repository. Any other `worktree` fails before Git runs in it.
67
+ Local reads also run with `GIT_NO_LAZY_FETCH=1` and `log.showSignature=false`.
68
+ The network operations are the explicit fetch of the landed commits and the check
69
+ that the remote branch is gone. On GitHub the tool reads both branch refs (the head
70
+ branch's absence and the base branch's tip) through the GraphQL API with your `gh`
71
+ login. It fetches the commits over HTTPS from `https://github.com/<owner>/<repo>.git`,
72
+ with `gh auth git-credential` as the only credential helper. The fetch runs as a
73
+ throwaway bare repository whose only config is its own two `core` lines, and it writes
74
+ into the session repository's object directory. No SSH runs, and no checkout, home or
75
+ system `http.*`, `credential.*` or `url.*` setting reaches the request that carries
76
+ your token. On GitLab both use the selected remote's own transport
77
+ (`git ls-remote` and `git fetch`, with plain `ssh` on SSH remotes). A `worktree` that
78
+ passes the ownership check is pinned (`GIT_DIR`, `GIT_WORK_TREE`, `GIT_COMMON_DIR`), so Git does
79
+ not rediscover it through a `.git` marker that changes afterwards.
80
+ - `requireApproval` reads the approval from the PR. On GitHub that is an
81
+ `APPROVED` review whose commit is the head. If reviewer and author share one
82
+ account, it can instead be a comment by that account whose first line is
83
+ `VERDICT: APPROVE` and whose body names the head SHA. On GitLab the approvals
84
+ API must report `approved: true` at the head. GitLab does not tie an approval
85
+ to a commit.
86
+ - `requireGreenChecks` requires every `gh pr checks` entry to pass (or be
87
+ skipped), with at least one check present. On GitLab the head pipeline must have
88
+ succeeded on the head.
89
+ - A squash uses the PR title as the commit subject.
90
+ - Merge queues need a paid GitHub plan or a public repository. On a private repository
91
+ whose plan has none, the rules read fails with `(HTTP 403)` and "Upgrade to GitHub Pro or
92
+ make this repository public to enable this feature"; the tool then takes that as "no
93
+ merge queue possible", lands directly through the proofs below, and records the plan gate
94
+ in the receipt notes. Any other failed rules read, including a 403 with another message,
95
+ still refuses.
96
+ - A GitHub base branch with a merge queue (an active `merge_queue` rule, read from
97
+ `GET /repos/{owner}/{repo}/rules/branches/{branch}`) takes no direct merge. The tool
98
+ checks approval and checks as above, then enqueues the reviewed head with the
99
+ `enqueuePullRequest` mutation and `expectedHeadOid`, so GitHub refuses a head that is
100
+ not `expectHeadSha`. It never runs a direct merge or auto-merge there. It polls the
101
+ pull request's `mergeQueueEntry` (5 s, doubling to 60 s) for up to `queueWaitSeconds`
102
+ (default 600, at most 3600).
103
+ - Merged: the tool re-reads the PR, requires the same head and base, and proves the
104
+ merge commit GitHub names (`mergeCommit`) by shape and by base containment (the
105
+ compare API must report it in the base branch's history). The queue builds on its own
106
+ integration branch, so the shape is judged per the queue's method (`merge_method`
107
+ must be omitted or match it): squash is one parent, any parent (a grouped entry
108
+ follows its predecessor); merge is two parents with the reviewed head an ancestor
109
+ (not necessarily the second parent); rebase is ordered `git patch-id --stable`
110
+ equivalence. Then it writes the receipt. The queue entry's `headCommit` is the
111
+ integration commit and is never compared with the reviewed head.
112
+ - Every queue read must be for the authorized repository, PR number and base, and the
113
+ enqueue only follows a read whose `headRefOid` is `expectHeadSha`.
114
+ - Still queued when the wait ends: the result is `ok: false, queued: true`, which is
115
+ not final. Call again with the same inputs; an entry for that head is waited on and
116
+ not enqueued twice, and a PR that has merged is proved as usual. A small
117
+ `pending-queue-<pr>-<head>.json` record next to the receipts remembers the enqueue.
118
+ The tool writes it before it sends the mutation, to a temporary file that it then
119
+ links into place, so it never replaces a record another call made. GitHub may queue
120
+ the PR even when the answer is lost (a timeout, an exit without GraphQL errors, an
121
+ unreadable reply), so the record stays then. A resumed
122
+ call that finds no entry refuses as removed and does not enqueue again. It clears
123
+ the record, so the next call decides afresh. A GraphQL rejection clears the record
124
+ at once. That decision and the enqueue run under a per-head `.lock` file, and the call
125
+ reads the queue again once it holds the lock, so an entry another call made in the
126
+ meantime is waited on, not taken for a removal. A call that overlaps another call's
127
+ enqueue refuses and leaves its record alone. Each record carries a generation, and a
128
+ call deletes a record only under the lock and only while it still carries the
129
+ generation that call wrote or read, so an older call never deletes a newer enqueue's
130
+ record. A queue that merged the PR before this call saw an entry also gets a record,
131
+ written before the proof, so a retry after a failed proof still judges the queue's
132
+ shape. No call removes another call's lock; a lock an interrupted call left is named
133
+ in the refusal, to delete after checking the queue.
134
+ - A record that exists but does not parse, or that names another landing, refuses.
135
+ The tool never reads it as "never enqueued". Check the queue on GitHub, delete the
136
+ file the refusal names, and call again.
137
+ - A call that finds the PR already MERGED takes the queue's method from the record.
138
+ After the receipt is written, it takes the method from that validated receipt. A
139
+ re-proof (to record a worktree, say) then uses the queue's proof again.
140
+ - Removed from the queue (failed checks, conflict, closed) or a changed head: refused,
141
+ with no other merge attempted.
142
+ - A failed rules read, or a rules response with a malformed element, refuses, because a
143
+ direct merge into a queue branch would enqueue the PR on its own. A 404 counts as no
144
+ rule only when the repository itself reads back. A branch without a queue rule is
145
+ merged directly, as before.
146
+ - After the merge the tool reads the PR again and fetches the landed commits by id
147
+ (falling back to the base branch, with three attempts over about 7 seconds). It
148
+ then checks the commit shape for the method:
149
+ - squash: one parent;
150
+ - merge: two parents, with the reviewed head second;
151
+ - rebase: ordered `git patch-id --stable` equivalence with the reviewed commits.
152
+ The landed commit must also be in the history of the base branch tip, which the tool
153
+ reads (through the API on GitHub, with `git ls-remote` on GitLab) and fetches by id.
154
+ Its tree must equal the reviewed head
155
+ merged onto its first parent, or for a rebase onto the commit the chain starts from.
156
+ These checks run for direct merges, queue landings, resumed
157
+ calls and already-MERGED PRs alike. An already-MERGED PR names no method, so one
158
+ parent passes as a squash or, if that fails, as a rebase chain proved by patch id.
159
+ - The tool never writes the Beads ledger. When the receipt's `beads.ledgerActive`
160
+ is true, `next` lists the `bd update` / `bd close` commands to run, children
161
+ first, before `delivery_cleanup`.
162
+ - With the `autoCleanup` option (default true) and no active ledger, `delivery_land`
163
+ then runs the same cleanup in-process with the receipt it just wrote: the same
164
+ proofs, and a non-force removal through OpenCode's registry when it tracks the
165
+ worktree. The result gains `cleanup: { ok, reason?, removed?, localRefDeleted? }`.
166
+ A cleanup refusal never turns the landing into an error; `next` keeps
167
+ `delivery_cleanup` until cleanup finishes. With an active ledger cleanup is not
168
+ attempted (`cleanup.skipped`), because it proves the beads are closed and those
169
+ closes come first. `autoCleanup: false` keeps the two-call flow.
170
+ Cleanup still refuses a worktree that moved past the landed head (`worktree.HEAD`,
171
+ `worktree.branch`) or that is not clean (changes, an operation in progress, a stash).
172
+ - **One remover per worktree.** A worktree that `subagent-worktree` created as a lane is
173
+ claimed by a file under the git common directory
174
+ (`<common>/opencode/lane-claims/<sha1 of the directory>.json`, which every worktree of
175
+ the repository shares and neither plugin has to import the other to read). While a claim
176
+ exists, or cannot be read, delivery never removes that worktree, inline or in the
177
+ background. It writes what it knows to `<common>/opencode/landings/<receiptId>.json`
178
+ (the landed head, the landing session, a denial) for the owner to read, and the result
179
+ reports `cleanup: { ok: false, deferred: "owned by subagent-worktree lane" }`.
180
+ - With an active ledger inline cleanup cannot run, so delivery retries it itself for
181
+ worktrees nothing owns: after each `session.execution.succeeded`,
182
+ `session.execution.failed` and `session.idle` (debounced 2 s per session, plus the
183
+ `experimental.idle` hook when the host has it) it re-runs `delivery_cleanup`'s proofs
184
+ for this repository's receipts whose worktree is still there, at most once per receipt
185
+ every 5 s and at most 20 receipts per pass, least recently looked at first (receipts that
186
+ are denied or owned take no slot). Open beads make the proof refuse and the retry is
187
+ silent; once they close, the next turn end removes the worktree. Immediately before the
188
+ removal, after the proofs, it checks ownership again (the claim file, and every page of
189
+ the sessions in the directory; a lookup that fails or is incomplete holds). The session
190
+ that ran `delivery_land` gets one reminder, when it goes idle with beads still open,
191
+ naming the beads and their close commands. The retry runs only while `autoCleanup` is
192
+ on, and no prompt is shown for it.
193
+ - An explicit `delivery_cleanup` of a worktree a lane owns, or whose claim cannot be read,
194
+ is authorized and re-arms any earlier denial on disk, then stops: it returns
195
+ `{ ok: true, deferred: "owned by subagent-worktree lane; removed by its owner once finished" }`
196
+ and removes nothing. The owner removes it when the lane is finished and landed.
197
+ - The coordination files (landing records, denials, claim checks) are written whatever
198
+ `autoCleanup` says; the option turns off only delivery's own inline cleanup and retry.
199
+ The last check before any removal delivery makes on its own also re-reads the landing
200
+ records for that directory: a denial, or a record that cannot be read, blocks it.
201
+ - The idle hook also records the `background` list as holds on disk
202
+ (`<common>/opencode/holds/…`, the same format `subagent-worktree` writes): a shell that names the
203
+ worktree, or any job of a session working in it. The last check before a removal reads them, so
204
+ running background work keeps the worktree. The jobs are written before the lock wait as well
205
+ (`recordHold`, as `subagent-worktree` writes them), for every worktree before any lock is taken.
206
+ A write whose lock wait times out behind a long removal hold therefore still blocks every
207
+ remover until that session's next write. A refusal caused by such a pending hold says
208
+ "recorded before its lock was taken", with its age, the time after which it is ignored, and its
209
+ file. Delete the named file only after that session's listed jobs have finished and that
210
+ session has ended. Until then, wait for its next turn or for the time given.
211
+ Landing records are dropped only on positive evidence
212
+ (their own receipt readable and cleaned or superseded); a denial is never dropped by cleanup of
213
+ stale records, and a missing or unreadable receipt directory deletes nothing.
214
+ - The lock is the Beads embedded write lock's protocol (a leased, token-owned file with a steal
215
+ lock), shared through `plugins/lib/src/lease-lock.ts`. Delivery's coordination writes (holds,
216
+ landing records, denials) take it too. The last look (claims, holds, sessions, denials) runs
217
+ inside the removal section after the final tree, ref and host reads, immediately before the
218
+ removal call.
219
+ - Every removal delivery makes (explicit, inline, retry) runs its last step inside
220
+ `lockedWorktreeRemoval`: the same on-disk lock `subagent-worktree` takes, then, under it and after
221
+ every proof, a final look at claims, background holds, running sessions and denials, then the
222
+ removal. The reads that prove the target (its identity, the PR read from inside it, a clean tree,
223
+ a pushed tip) run first without the lock, so the lock is held only for the removal section, which
224
+ proves them again. A refusal is read again under the same lock (`lockedWorktreeRead`), so it is
225
+ never the sight of another remover's removal part-way: a half-deleted tree would read as dirty.
226
+ The prompt, if any, comes before the removal section and outside the lock. If the coordination
227
+ store cannot be written, or a hold could not be recorded, the worktree is treated as unsafe and kept.
228
+ - After the worktree is removed and its absence is proven, delivery moves the lane's own sessions
229
+ to the repository's canonical checkout, so none is left pointing at a directory that is gone
230
+ (`Location not found`). The lane is the session that called the tool (for the background retry,
231
+ the session whose turn ended), plus the session of each landing record for the worktree, and
232
+ everything below them whose location is the worktree or any directory inside it. Delivery lists
233
+ only those sessions' children (`session.list` with `parentID`), never the whole project. It does
234
+ this after the removal, because the host still lists and reads sessions whose directory is gone,
235
+ so a session created while the worktree was being removed is found too. It runs even when a
236
+ later step (branch deletion, a ref probe) cannot finish. Other sessions are not touched. A
237
+ running session in the worktree or below it still refuses the removal (see the final look
238
+ above). Moving never fails the cleanup: a session that could not be moved or read, or an
239
+ incomplete listing, is listed under `skipped` in the result, with the session id and the reason.
240
+ A session that no longer exists is dropped silently.
241
+ - **A refusal sticks.** If the inline cleanup is refused at its prompt, the landing record
242
+ keeps `denied` and nothing retries it. A later explicit `delivery_cleanup` call that is
243
+ authorized clears it; one that is refused records a fresh denial and leaves the old one
244
+ in place until then.
245
+ Limitation: the plugin API cannot ask what a permission rule for `delivery_cleanup` resolves to without prompting (the context only offers `assert`, which prompts, and the `evaluate` hook, which cannot be called), so a deny rule is recorded as a denial only when the inline cleanup's own prompt hits it, not when a rule blocks an explicit call before the tool runs.
246
+ - If the forge accepted the merge but a later step refused, the result has
247
+ `mergeIssued: true` and no receipt. Run the tool again with the same inputs: it
248
+ sees the PR as MERGED, merges nothing, and writes the receipt.
249
+
250
+ Supported forges: `github.com` (including `ssh.github.com`), `gitlab.com`
251
+ (`altssh.gitlab.com`) and self-hosted GitLab at `gitlab.example.com`
252
+ (`ssh.gitlab.example.com`). Other unconfigured hosts are refused.
253
+
254
+ ### delivery_cleanup
255
+
256
+ Inputs: `receipt`, `pr`, `branch`, `worktree`, `remote` and `repo`. Any input you pass must
257
+ match the selected receipt. Without `receipt`, the tool picks the receipt by `pr`,
258
+ `branch` or `worktree`. When two or more landings are open in one repository it also
259
+ reads the named worktree's HEAD, matching the receipt's reviewed head OID first and
260
+ its branch name second. It never falls back to the newest receipt: with no match, or
261
+ more than one, it refuses and lists each candidate's PR, branch and receipt path.
262
+ With no input at all it picks the only uncleaned landing, or refuses and lists them.
263
+
264
+ Given only `repo`, it looks at that repository's landings alone. It picks the only uncleaned
265
+ one, else the only cleaned one, so an open landing in another repository does not hide it.
266
+
267
+ A receipt or worktree of another repository fails before any Git command runs in it.
268
+ So does a `repo` of another repository: once a remote of the clone you name with
269
+ `repoPath` or `worktree` is shown to name `repo`, the tool refuses. That repository's
270
+ lane claims, holds and bead ledger can't be read from this session. Run
271
+ `delivery_cleanup` from a session in that repository instead.
272
+
273
+ A `repo` also narrows the receipt in the session's own repository: it must equal the
274
+ receipt's `repo.nameWithOwner`, whether the receipt is named by `receipt`, `pr`, `branch`
275
+ or `worktree`, or found by `repo` alone. A clone with two remotes (an `upstream` for A and
276
+ an `origin` for B) therefore refuses to clean B's receipt when asked for A.
277
+
278
+ The receipt's beads are read with `bd show` run at the verified repository root, with
279
+ `BEADS_DIR`, `BEADS_DB`, `BD_DB`, `BD_SOCKET`, `BEADS_DOLT_SHARED_SERVER` and
280
+ `HARNESS_BEADS_PIN` removed from its environment. Sessions started before the upgrade keep
281
+ the old marker until restarted. A ledger the session pinned never decides whether the
282
+ target's beads are closed.
283
+
284
+ A listed worktree is also checked first: its `.git` must be a
285
+ regular file (never a symlink or FIFO, read with bounded no-follow reads) naming a
286
+ directory under this repository's `worktrees/` whose `commondir` is this repository. The values are read as Git reads them: `gitdir: `
287
+ is stripped exactly (a leading blank makes the path relative), `..` is resolved through
288
+ symlinks, and a blank-prefixed `commondir` is a relative name. Once verified, every Git
289
+ command in that worktree, and in the worktree the removal runs from, is pinned with
290
+ `GIT_DIR`, `GIT_WORK_TREE` and `GIT_COMMON_DIR`, so a marker swapped after the check
291
+ cannot redirect it. They also run with `core.fsmonitor=false`,
292
+ `core.hooksPath=/dev/null` and `--no-optional-locks`. `git worktree remove` itself
293
+ re-reads the target's marker; the re-verification just before it narrows that window
294
+ but cannot close it.
295
+
296
+ The tool refuses in these cases:
297
+
298
+ - it was called from inside the worktree it would remove;
299
+ - the worktree is not a live, listed, non-symlink linked worktree;
300
+ - the worktree's HEAD is not the receipt's reviewed head (its branch may have another
301
+ name, or none);
302
+ - the tree is dirty, an operation is in progress, or a stash exists on the receipt's
303
+ branch or on the branch the worktree sits on;
304
+ - the branch is ahead of its upstream;
305
+ - the PR, read from the receipt's own remote, is not MERGED at the recorded head,
306
+ base and merge commit;
307
+ - on an active ledger, a receipt bead is not closed with `metadata.merge_sha`
308
+ equal to the merge.
309
+
310
+ A refusal means that the call removed nothing. After the removal command runs, the call
311
+ does not refuse. It succeeds and lists what it removed (`removed`) and what it could not
312
+ finish or prove (`skipped`). Examples are a branch that Git could not delete, or a
313
+ worktree that reappeared at the path.
314
+
315
+ A removal that stops part-way reports `partlyRemoved: true` and the headline "removal
316
+ attempted, partly removed, unverified", with nothing in `removed`. Examples are a file
317
+ Git cannot delete, or a kill at the time bound. `git worktree remove` only deletes. A
318
+ failed removal counts as stopped part-way only when it left one of these signs:
319
+
320
+ - a deleted tracked file in `git status`;
321
+ - a `.git` marker that does not bind the tree to its admin directory;
322
+ - a status that cannot be read, or a missing registration;
323
+ - a command that ended with no exit status.
324
+
325
+ Such a call keeps the local branch and the landing receipt, which stays the receipt of
326
+ record. Delivery's own retry tells the session once, keeps the landing record and does
327
+ not retry it.
328
+
329
+ A failed removal without such a sign stays a refusal. A tree that changed after the last
330
+ proof is why Git refused it, for example an untracked file or an edit. The refusal then
331
+ lists the changed paths and says to save them.
332
+
333
+ Git's refusal at its clean check ("contains modified or untracked files") is a refusal
334
+ too, even when the status shows deleted files. Git makes that check before it deletes
335
+ anything, so those deletions come from another process. Git runs the removal in the C
336
+ locale, so its message is the English one. Any other message falls back to the signs above.
337
+
338
+ Every unverified or partly removed result names the path to inspect and says to save any
339
+ changes there. No result of a failed removal or branch deletion names a command that
340
+ forces a deletion. It quotes the command that ran (`git worktree remove`, `git branch -d`),
341
+ which never forces. Git runs those two calls in the C locale, and the result quotes only
342
+ the first line of its message, without the hint ("use --force to delete it",
343
+ "remove -f -f", "branch -D"). The expected outcome reads "exit 0".
344
+
345
+ A deleted file in the status may be the user's own work. The status does not list ignored
346
+ files either. So no status proves that what is left belongs to the interrupted removal.
347
+
348
+ A tree whose only changes are deleted tracked files is a removal that is running or
349
+ stopped part-way. The cause can be another process that takes no delivery lock, such as
350
+ a delivery plugin in another harness or `wt remove`. It can also be an earlier cleanup
351
+ that failed. The refusal says so, names the path to inspect and says to save any changes.
352
+
353
+ Cleanup deletes the receipt's branch ref only while it still points at the reviewed
354
+ head. It leaves a ref that is gone or points elsewhere, and it keeps the differently
355
+ named branch a worktree sits on. The result lists what it removed (`removed`) and
356
+ what it left (`skipped`).
357
+
358
+ Cleanup treats a worktree that is already gone as done, whether an earlier cleanup
359
+ finished, another remover took it during this call's checks, or someone removed
360
+ it by hand. The call succeeds with `alreadyCleaned: true`,
361
+ changes nothing and writes no receipt. If a worktree or directory has reappeared at the
362
+ recorded path since, cleanup refuses instead: it reports the path and the worktree's
363
+ HEAD, and removes nothing.
364
+
365
+ A branch with no upstream (for example, the forge deleted it on merge and a fetch
366
+ pruned it) counts as pushed. Its HEAD has already been checked against the merged
367
+ PR's `headRefOid`. The receipt records this as `proof.evidence.pushed: "pr-head"`.
368
+
369
+ Removal never forces and uses `git branch -d`, never `-D`. A worktree that
370
+ OpenCode tracks (one made by `opencode_worktree_create` or a subagent-worktree
371
+ lane) is removed through the host's `worktree.remove`, so OpenCode's registry
372
+ drops the entry; the host refuses a dirty tree and cleanup reports its reason
373
+ without falling back to git. Any other worktree is removed with
374
+ `git worktree remove`.
375
+
376
+ A registry entry goes stale only when a removal bypasses the host (a manual
377
+ `git worktree remove` or a deleted folder). `worktree.list` still returns such
378
+ entries, and the host's `remove` then fails because the directory is gone. The
379
+ plugin leaves them alone: OpenCode's `worktree.refresh` drops registry entries
380
+ whose directory no longer exists. Upstream, `remove` could drop the entry when
381
+ the directory is already gone.
382
+
383
+ ## Permissions
384
+
385
+ `delivery_land` asks permission for action `delivery_land` with resource
386
+ `<owner>/<name>#<number>`. It asks after every read has passed and before the
387
+ first write. `delivery_cleanup` asks for action `delivery_cleanup` with the
388
+ worktree path, right before the removal. Your permission rules decide: an
389
+ allowed request runs without a prompt, and a deny or ask rule always wins. Set the
390
+ `confirm` option to `true` to make the plugin turn an allowed request into `ask`
391
+ in a root session; a subagent session (one with a parent) keeps its allow, because it
392
+ cannot answer, and a failed session lookup keeps the prompt. A subagent is still gated by its own `delivery_land` and
393
+ `delivery_cleanup` permission, and by `delivery_land`'s own checks: a call that
394
+ would merge must pass `expectHeadSha` naming the PR head, and it merges at most
395
+ once. Approval and green checks are required only when the call sets
396
+ `requireApproval` and `requireGreenChecks`; the `shepherd` agent always sets both.
397
+
398
+ ## Receipts
399
+
400
+ Receipts are JSON files under `~/.omp/receipts/<repo-key>/<receiptId>.json`. That
401
+ is the same directory, file name, schema (`omp.receipt.landing` v1) and repository
402
+ key that the Oh My Pi delivery plugin uses, so either plugin can clean up the
403
+ other's landings. `delivery.receipt.landing` is accepted on read as well. To use a
404
+ different root, set `DELIVERY_RECEIPTS_DIR` or the `receiptsDirectory` option.
405
+ `PI_CODING_AGENT_DIR` is not read. A directory scan reads at most 1000 receipts
406
+ per repository.
407
+
408
+ ## pi and OMP
409
+
410
+ The pi package (`@srobroek/pi-delivery`, `plugins/delivery/pi`) ships one tool:
411
+ `delivery_cleanup`, for an explicit call. It takes the same input and returns the
412
+ same text as the OpenCode tool, and runs the same `cleanupDelivery`. It holds the
413
+ same worktree lock as every other delivery remover and as `subagent-worktree`. Under
414
+ that lock it reads the lane claim and the background-work records.
415
+
416
+ It differs from the OpenCode tool in these ways:
417
+
418
+ - It cleans up only the session's own repository. It refuses a `repo` and `repoPath`
419
+ that name another clone, and a receipt or worktree of another repository.
420
+ - It has no retry and no background cleanup. It does not clean up after a land and
421
+ keeps no clone registry. It does not see OpenCode sessions running in the worktree.
422
+ - Its `authorize` step defers a lane-owned worktree and calls no UI, so a session
423
+ without a UI (a subagent) runs it the same way. The OMP approval mode gates it as
424
+ an `exec` tool.
425
+ - The pi package ships neither `delivery_land` nor the hygiene report. The agents and
426
+ the two skills are OpenCode variants (`<id>.opencode.md`, `SKILL.opencode.md`),
427
+ because they name tools and agents that pi lacks, so pi gets none of them.
428
+
429
+ OMP loads pi extensions unchanged. To load this tool in OMP, add the bundle's file
430
+ path (`plugins/delivery/pi/extensions/delivery-cleanup.js`) to `extensions:` in
431
+ `~/.omp/agent/config.yml`. A file entry loads no sibling skills or agents. Only one
432
+ `delivery_cleanup` may load, so disable any other one. For the omp-plugins `delivery`
433
+ package, add `extension-module:delivery-cleanup-tool` to `disabledExtensions`. Its
434
+ `delivery_land` and hygiene report stay loaded.
435
+
436
+ ## Agents
437
+
438
+ The plugin registers these subagents from `agents/*.md` through
439
+ `ctx.agent.transform`, so they need no files in your project:
440
+
441
+ | Agent | Job | Model tier | Fallback model |
442
+ | --- | --- | --- | --- |
443
+ | `implementer` (steps 150) | One bead or task in its own worktree; `DONE`/`BLOCKED`/`SPLIT` | `standard` | `amazon-bedrock/global.anthropic.claude-sonnet-5-5#medium` |
444
+ | `implementer-high` (steps 200) | Root cause, concurrency, contracts, precision, design judgment | `strong` | `amazon-bedrock/global.anthropic.claude-opus-5-5#high` |
445
+ | `researcher` (steps 80) | One cited answer; no product edits (fallback copy, see below) | `standard` | `amazon-bedrock/global.anthropic.claude-sonnet-5-5#medium` |
446
+ | `pr-reviewer` (steps 80) | Read-only diff review through `gh pr view` / `gh pr diff`; `VERDICT:` first line (fallback copy, see below) | `reviewer` | `amazon-bedrock/global.anthropic.claude-opus-5-5#high` |
447
+ | `operator` (steps 30) | One exact bounded command | `cheap` | `amazon-bedrock/global.anthropic.claude-haiku-5-5` |
448
+ | `shepherd` (steps 60) | Lands one approved PR with `delivery_land` (approval and checks required), closes beads, cleans up | `standard` | `amazon-bedrock/global.anthropic.claude-sonnet-5-5#medium` |
449
+
450
+ - `researcher` belongs to the [`agent-researcher`](../agent-researcher/README.md)
451
+ plugin. Delivery ships the same agent as a fallback, so `execution_agent_type=researcher`
452
+ beads still have an agent without that plugin. Delivery skips its copy when
453
+ `plugin.list` reports `srobroek.agent-researcher` or an earlier plugin already
454
+ registered `researcher`; if delivery's copy loads first anyway, the owner replaces
455
+ it, so either order leaves one agent. The logic is
456
+ `@srobroek/opencode-lib/agent-fallback` and `FALLBACK_AGENTS` in `src/agents.ts`;
457
+ `plugins/agent-researcher` tests keep the two files in sync.
458
+ - `pr-reviewer` belongs to the [`agent-reviewer`](../agent-reviewer/README.md) plugin
459
+ the same way, and is `hidden: true`: the fan-out and git-workflow skills name it, so
460
+ it stays out of the subagent catalog. Its prompt is composed from
461
+ `agents.src/pr-reviewer.md` and the shared review core by `bun run build`; edit the
462
+ source, not `agents/pr-reviewer.md`. Only this copy carries the fallback model.
463
+ - Every agent names its tier in the `x-opencode-model-role` request header. With
464
+ the model-roles plugin installed (detected through `plugin.list`), the tier picks
465
+ the model and the plugin sets no model of its own.
466
+ - Without model-roles, the agent uses its fallback model when it is available on
467
+ this machine, and otherwise inherits the session's model. The fallback is marked
468
+ in the `x-opencode-model-fallback` request header: if model-roles is installed
469
+ but was not detected, its tier still replaces the fallback. A model you pin in
470
+ config (`agents.<id>.model`) wins over the tier either way. Delivery keeps these
471
+ fallbacks, unlike the other plugins' agents, so `operator` stays on a cheap model
472
+ and the reviewer on a strong one for users without model-roles.
473
+ The Bedrock IDs in the table are examples. The `models` option accepts any provider/model
474
+ ID available to your host.
475
+
476
+ - The `models` option overrides a model per agent (`"provider/model#variant"`),
477
+ with or without model-roles; `false` means no model.
478
+ - Your own markdown or config agent with the same id loads after the plugin and
479
+ overrides it field by field, including the tier header.
480
+ - `agents/roles.json` (`common/agents/roles.opencode.json` in the source) holds the same mapping as the headers, as a model-roles
481
+ `agents` fragment, for hosts that set tiers in config instead.
482
+
483
+ The agents were converted with
484
+ `bun scripts/convert-agent.ts --roles plugins/delivery/common/agents/roles.source.opencode.json`,
485
+ then edited by hand. The roles file is keyed by model-roles tier (`cheap`, `standard`,
486
+ `strong`, `reviewer`); the omp names `smol`, `task` and `slow` resolve to the same keys. The edits removed omp-only references, slimmed the
487
+ shepherd, and limited the reviewer's shell to `gh pr view` and `gh pr diff`.
488
+
489
+ Each agent's permissions are a tool allowlist: a deny on every action, then allows
490
+ for what the agent needs, so other tools are left out of its requests. The
491
+ implementers get read, grep, glob, edit, shell, the `lsp_*` tools and the coding skill
492
+ families (`lang-*`, `quality-*`, `toolchain-*`, `architecture-*`, `trunk-dev-*`,
493
+ `worktrunk-*`, `aws-guidance` and a few toolchain skills by id); their prompts carry the
494
+ coding core's `standards` part (research first, compare with the `lang-<language>-libraries`
495
+ standards, middleware, Powertools, OpenTelemetry); `operator` read, grep, glob, edit and
496
+ shell, no skills; `researcher` read-only tools, shell, the `repomix` skill, Code Mode for
497
+ `repomix_pack`, webfetch and websearch; `shepherd` read-only tools, shell, the
498
+ `delivery-*` skills and Code Mode for `delivery_land` / `delivery_cleanup`;
499
+ `pr-reviewer` the `quality-*` and `review-*` skills and its two `gh pr` commands. Only
500
+ `researcher` and `shepherd` call Code Mode tools, so only they get `execute`.
501
+
502
+ `implementer`, `implementer-high`, `operator`, `shepherd` and `pr-reviewer` are hidden
503
+ from the subagent catalog: the fan-out and git-workflow skills and the Beads routing
504
+ name them, so the parent spawns them by id. `researcher` stays listed. Reads
505
+ outside the workspace (`external_directory`) still ask, and your own rules still
506
+ apply after the agent's.
507
+
508
+ ### Verdicts
509
+
510
+ Every delivery agent starts its reply with `VERDICT: <WORD>`. A verdict line that
511
+ slips below a preamble or into a code fence still counts, marked `late: true`. Every agent except
512
+ `pr-reviewer` ends it with one fenced `json` block. An `execute.after` hook on the
513
+ `subagent` tool parses that into the result's `metadata.delivery`
514
+ (`{ verdict, agent, summary?, late?, fields? }`).
515
+
516
+ If a delivery agent's reply has no verdict line or otherwise breaks this format, the verdict is `MALFORMED` and the
517
+ result gets a note naming the session to continue. Other agents' results are left
518
+ alone. Background subagent completions arrive as synthetic messages rather than
519
+ tool results, so the hook does not see them.
520
+
521
+ ## MCP tools
522
+
523
+ `implementer`, `implementer-high` and the fallback `researcher` cannot call MCP tools unless a rule allows them. The `tools` option adds allow rules for MCP tool patterns after the agent's own rules. OpenCode names an MCP tool's permission action `<server>_<tool>`, so `context7_*` allows every tool of the `context7` server and `context7_query-docs` allows one. Characters outside letters, digits, `_` and `-` become `_`.
524
+
525
+ | Option | Default | Effect |
526
+ | --- | --- | --- |
527
+ | `tools` | `["context7_*"]` | An array of patterns replaces the defaults. Add `aws-mcp_*` only when you have that server and want to allow its tools. `false` or `[]` adds no rules; the agent keeps its fixed allowlist. |
528
+
529
+ ```jsonc
530
+ "options": { "tools": ["context7_*", "<server>_<tool>"] }
531
+ ```
532
+ Patterns must name MCP server tools only (`<server>_<tool>`). The option refuses a pattern that could match a tool from a plugin in this repository or from OpenCode itself, such as `dep_*`, `delivery_*`, `quality_*`, `lsp_*` or `opencode_*`, and a pattern that starts with a wildcard, and logs a warning. Only add read-only tools: an allowed MCP tool runs without a prompt. The option refuses a pattern that matches a built-in action (`shell`, `edit`, `write`, `patch`, `external_directory`, `subagent`, `*` and the like) and logs a warning, so it cannot widen file or shell access. `pr-reviewer`, `operator` and `shepherd` get no MCP rules.
533
+
534
+ This agent denies `execute`, so OpenCode lists its allowed MCP tools directly, even for a server configured for Code Mode: with `execute` wholly denied, every tool left active becomes a direct tool (`packages/core/src/tool.ts:260-264`, OpenCode v2.2.6; an MCP tool's `codemode` flag is set at `packages/core/src/tool/mcp.ts:57`).
535
+
536
+ ## Instructions and skill
537
+
538
+ - **Fan-out rules.** `instructions/delivery-fan-out.md` is a short summary
539
+ (under 250 tokens) of the lead's fan-out rules. A `session.hook("context")` adds
540
+ it to the system prompt of every primary session whose agent can call
541
+ `subagent`, but not to subagent sessions or the delivery agents. The text is
542
+ static, so provider prompt caching keeps working. To manage it yourself, set
543
+ `fanOut: false` and copy the file into your `AGENTS.md`.
544
+ - **Skill `delivery-fan-out`.** The full rules the summary points at: splitting
545
+ work into units, batched background dispatch, self-contained briefs, tier
546
+ routing, one worktree per writer, and verifying once after integration. It sets
547
+ `metadata: opencode/autoinvoke: false`, so it stays out of the skill listing and
548
+ loads by id when the summary sends the lead to it.
549
+ - **Skill `delivery-git-workflow`.** Covers PR shipping, the review-loop owner,
550
+ squash titles, external-repository hygiene, merge-method choice, approval
551
+ artifacts, the land/close/cleanup order, and Beads linkage. Load it for PR or
552
+ landing work.
553
+
554
+ ## Options
555
+
556
+ ```jsonc
557
+ {
558
+ "plugins": [{
559
+ "package": "github:srobroek/harness-plugins::path:plugins/delivery/opencode",
560
+ "options": {
561
+ "confirm": false, // true: prompt for every land and cleanup (default false)
562
+ "autoCleanup": true, // delivery_land runs cleanup itself
563
+ "receiptsDirectory": null, // default $DELIVERY_RECEIPTS_DIR, then ~/.omp/receipts
564
+ "agents": true, // register the delivery agents
565
+ "models": { "operator": false },
566
+ "fanOut": true, // fan-out instructions for primary sessions
567
+ "verdicts": true // parse subagent verdicts into metadata
568
+ }
569
+ }]
570
+ }
571
+ ```
@@ -0,0 +1,39 @@
1
+ {
2
+ "plugin": "delivery",
3
+ "prerequisites": [
4
+ {
5
+ "bin": "git",
6
+ "for": "delivery_cleanup's worktree, ref and remote proofs, git worktree remove and git branch -d",
7
+ "required": true,
8
+ "install": {
9
+ "url": "https://git-scm.com/downloads"
10
+ }
11
+ },
12
+ {
13
+ "bin": "gh",
14
+ "for": "delivery_cleanup's pull-request read (gh pr view) for a GitHub receipt",
15
+ "required": false,
16
+ "install": {
17
+ "mise": "aqua:cli/cli",
18
+ "url": "https://cli.github.com"
19
+ }
20
+ },
21
+ {
22
+ "bin": "glab",
23
+ "for": "delivery_cleanup's merge-request read (glab mr view) for a GitLab receipt",
24
+ "required": false,
25
+ "install": {
26
+ "url": "https://gitlab.com/gitlab-org/cli#installation"
27
+ }
28
+ },
29
+ {
30
+ "bin": "bd",
31
+ "for": "delivery_cleanup's read-only bd show of a receipt's beads when the repository's Beads ledger is active",
32
+ "required": false,
33
+ "install": {
34
+ "mise": "aqua:gastownhall/beads",
35
+ "url": "https://github.com/gastownhall/beads/blob/main/docs/getting-started/installation.md"
36
+ }
37
+ }
38
+ ]
39
+ }