viewable-one 0.12.6 → 0.12.7

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/CHANGELOG.md CHANGED
@@ -13,6 +13,73 @@ package.
13
13
 
14
14
  ## [Unreleased]
15
15
 
16
+ ## [0.12.7] - 2026-11-15
17
+
18
+ ### Fixed
19
+
20
+ - The computer's list of tools now finds Claude Code (and the others) the way
21
+ a run does, not only on the watcher's own PATH. A watcher started by hand
22
+ reported Claude Code as missing, so a card automation on the computer went
23
+ to OpenCode, which was never chosen, and failed (#6646).
24
+ - A scheduled run that could not reach the person's apps (its closing asks
25
+ for Use my computer's apps) now says so on its row (`sidecar.unable`), so
26
+ its automation shows as failed with the reason and a Needs you notice,
27
+ instead of "Ran" (#6552).
28
+ - Merge, delete, clean and new-worktree changes no longer run without the repo
29
+ lock. The lock was a folder under `.git/`, which could not be made in a
30
+ linked worktree, and a failed or timed-out lock was logged and ignored. It
31
+ now lives in Git's shared folder, so a checkout and its linked worktrees take
32
+ the same lock, and a change that cannot get it stops with a message naming
33
+ who holds it, before any stash, merge or reset runs. A run whose repo lock
34
+ cannot be held now does not start at all: it ends with "Nothing was spawned
35
+ and nothing was billed" and asks to run again once the other change has
36
+ finished, instead of falling back to the shared checkout (#6558).
37
+ - Stop, the wall clock and the stall watchdog now end every ordinary
38
+ background command the agent started, not only the agent (#6557). A
39
+ `cmd > log 2>&1 &` used to outlive Stop. The runner ends the agent's private
40
+ group and waits until it is empty, spares the recorded preview server, and
41
+ keeps the run's recovery record when something survives so a later cleanup
42
+ can still find it. Windows is unchanged.
43
+ - A remembered file permission stays inside the project folder (#6556). Always
44
+ allow on a Read, Write, Edit or search used to cover that tool anywhere on
45
+ the computer. Now every file tool must stay inside the run's folder (links
46
+ followed); a path outside or a link pointing out asks again, and so does a
47
+ file tool with no path. Those asks show no Always allow button. Grep and
48
+ Glob with no path are judged against the run's own folder and stay covered.
49
+ The same holds for Claude Code, Codex and ACP agents.
50
+ - Windows uninstall keeps `Path` for both the Viewable and npm removal steps
51
+ (#5414), so a Volta or bundled npm is found and Remove finishes. The two
52
+ spellings of the name no longer both reach the child.
53
+ - The line under an approval question names what a connected app will make
54
+ ("Title" and "Adds"), not a raw argument such as `creation_mode` (#5401). It
55
+ also names the pages a delete acts on and hides the confirmation flags
56
+ `user_confirmed` and `user_confirmation` (#6453); a bare `confirm`, such as
57
+ Stripe's charge-now, still shows. It shows a title or name with a
58
+ number up to 6 digits, such as "Invoice 452199" (#5436). Text with a code or
59
+ credential word, or longer numbers, stays hidden.
60
+ - The reason line under a computer app's approval no longer depends on which
61
+ app it is (#5442). Per-app rules moved into the app catalog, which the
62
+ computer's ask does not have, so it reads each call from its own words:
63
+ money, sending, deleting, publishing, merging and deploying keep their
64
+ lines, but a Stripe tool whose words name no money act (`create_customer`,
65
+ `create_price`) no longer gets "Money moves", and a create or comment tool
66
+ that used to show no line (Linear `create_issue`, Notion `create_pages`,
67
+ GitHub `add_issue_comment`) now reads "Open-ended tools ask every time."
68
+ The ask itself is unchanged.
69
+ - `viewable doctor` says an installed version ahead of npm is "newer than the
70
+ published" one, instead of an update notice, and still passes (#5478).
71
+
72
+ ### Added
73
+
74
+ - A run's question carries the pictures the run saw, with a caption each, into
75
+ Needs you (#5534). The run rules tell the agent to attach what it saw.
76
+
77
+ ### Changed
78
+
79
+ - When `PM_SPAWN_MAX_CONCURRENT` is set, the runner sends it with each claim,
80
+ so the board holds it across every folder on this computer at once. Unset
81
+ is still any number at once (#5732).
82
+
16
83
  ## [0.12.6] - 2026-11-10
17
84
 
18
85
  ### Fixed
package/SPAWN.md CHANGED
@@ -1,5 +1,7 @@
1
1
  # The spawn contract - running a Claude Code session from the board
2
2
 
3
+ Checked against `bridge/lib/runnerApi.mjs`, `supabase/functions/board-runner/` and `src/types.ts` on 2026-11-11.
4
+
3
5
  This is the runner's contract, written for whoever maintains it: every row it
4
6
  reads and writes, every bound it respects, and what happens at each edge. It
5
7
  is not a guide to using Viewable - [README.md](./README.md) is that.
@@ -366,45 +368,36 @@ already has, the one `bridge/lib/ops.mjs` already reads, and the one a session
366
368
  already knows how to look for. Inventing a second shape for the same job would
367
369
  be the drift the sidecar exists to avoid.
368
370
 
369
- ## Two states, and no progress protocol
370
-
371
- The ruling, 2026-08-26 (`q-mt9as5a0`): a run is **running**, then **done**.
372
- There is no third board state, no heartbeat, no liveness channel, and nothing
373
- anywhere infers a session's state from its silence. The record rides the
374
- idea, and its card draws these same two states.
375
-
376
- That ruling deletes a lot, and the deletions are the good part. There is no
377
- `.status.json`, no `STALE_MS`, no reaper, no "waiting on you" state, and no
378
- timeout that guesses whether a quiet session is thinking or dead. A session
379
- that dies without ending leaves its card reading `running`, and he sees that
380
- and presses Rerun or clears the idea. A wrong-looking card he can act on beats a
381
- right-looking state machine he has to trust.
382
-
383
- Since 2026-09-07 (the QA sweep of the runner) the end op says which of the two
384
- endings it was: `endSession` carries `stopped: true` when the run ended because
385
- a stop was asked for, and a `reason` line when it ended without ever starting.
386
- That is not a third state - the board still reads running, then done - it is
387
- the difference between "finished" and "you stopped it", which the card could
388
- not otherwise tell.
389
-
390
- What is NOT a progress protocol, and stays:
391
-
392
- - the **claim file**, which records who owns a request so two runners cannot
393
- both run it. It is written once and never updated, so it says nothing about
394
- liveness and cannot go stale in a way anyone reads.
395
- - the **wall clock**, which kills a child that has run past `maxMs`. That is a
396
- money bound on a process, not a state on the board. When it fires the runner
397
- still calls `endSession`, so the board says `done` like any other ending, and
398
- the reason lives in `inbox/spawn/<id>.result.txt` where a person reads it.
399
- Amended 2026-08-30: for a streaming child whose final result envelope stands,
400
- the firing is the reply window closing, not a timeout - see "A finished
401
- stream is finished" below. The bound itself is unchanged. Amended again
402
- 2026-09-06: there is no reply window any more, so an idle child does not
403
- reach the wall clock at all - the envelope closes its stdin and it exits.
404
- The bound is still unchanged, and it is what a child mid-turn meets.
405
-
406
- The board carries two states. The disk carries the detail. Neither pretends to
407
- carry the other.
371
+ ## Run states and leases
372
+
373
+ Historical reference: the 2026-08-26 ruling `q-mt9as5a0` described the
374
+ file-based runner as running then done, with no heartbeat or timer-based
375
+ reaper. Its local housekeeping constraint still describes
376
+ `bridge/lib/runnerMaintenance.mjs`: sweep orphan processes at lifecycle
377
+ boundaries, not on a timer.
378
+
379
+ The later hosted-row contract supersedes that two-state/no-heartbeat
380
+ description for hosted runs: `20260911170000_runs_as_rows.sql` defines the
381
+ row states, and `20260926093000_runner_leases.sql` adds expiring claims and
382
+ the server reaper. `bridge/lib/runnerLease.mjs` renews those leases. This
383
+ section records that implemented change; it does not change the local
384
+ housekeeping constraint or infer completion from a quiet model.
385
+
386
+ Hosted run rows move from `pending` to `running` when claimed, then to
387
+ `done`, `error` or `stopped`. The idea's `RunStatus` is `idle`, `running`,
388
+ `done` or `error`; stopped outcomes carry the stop detail on the run.
389
+ The row states and the card's display states are different contracts.
390
+
391
+ The runner registers and sends heartbeats. Claims have a five-minute lease,
392
+ renewed every 30 seconds; local execution stops before expiry when renewal
393
+ fails. The server reaps expired claims as errors, never as pending work to
394
+ restart automatically. Completion recovery can reconcile a late durable
395
+ result. See “Admission, leases and completion recovery” above.
396
+
397
+ The wall clock bounds the child process. It is not a progress estimate.
398
+ A quiet model is not assumed finished: completion comes from the child's
399
+ result and the runner's update. The old file-based claim and result receipts
400
+ below describe the earlier transport, not the current hosted lease protocol.
408
401
 
409
402
  ## A finished stream is finished
410
403
 
@@ -1002,7 +995,7 @@ each is enforced in code, not in a comment:
1002
995
  | runner off by default | `PM_SPAWN_RUNNER=on` AND an explicit `watch` command | a runner that starts itself because something imported it |
1003
996
  | per-request approval | `approved: true`, or the request is refused | a row nobody clicked "run" on ever running |
1004
997
  | `claim` is the start | `claim` moving a row to `status:'running'` IS the start - the row exists under RLS the moment `run_request` inserted it, so nothing waits for a receipt | a run that is on the board but not yet accounted for |
1005
- | concurrency | `PM_SPAWN_MAX_CONCURRENT`, **any number by default** since 2026-08-28, counted from `runs {status:'running'}` plus the runner's own in-flight set | ten requests becoming ten sessions |
998
+ | concurrency | `PM_SPAWN_MAX_CONCURRENT`, **any number by default** since 2026-08-28, counted from `runs {status:'running'}` plus the runner's own in-flight set. When set, `claim` also carries it and the database holds it per computer across folders (`guard_run_capacity`, #5732); unset sends nothing and the database counts nothing. Server runs have no cap unless the database setting `glytch.server_run_cap` is set. Two starts that overlap wait for each other; only a full count refuses. A process run's own row is not counted, its steps' runs are; a server process step that meets a full count (waking, moving to running, landing, or filing its run) waits and goes on at a later tick (#6336) | ten requests becoming ten sessions |
1006
999
  | no shared working tree | a session that wanted isolation, could not get a worktree, and finds another session running is refused before it spawns (2026-08-28) | two agents editing one checkout with no branch between them |
1007
1000
  | wall clock | `maxMs`, default 90min (`DEFAULT_WALL_MS`), at most 2h (`MAX_WALL_MS`), both in `spawn.mjs` | a session that hangs billing all night |
1008
1001
  | no retry, ever | a failed request is terminal | paying twice for the same failure |
@@ -1172,7 +1165,7 @@ Kept below: the SHAPE of each signal, named for the file it once travelled as
1172
1165
 
1173
1166
  | signal | shape | what the runner does |
1174
1167
  | --- | --- | --- |
1175
- | stop | `{ worktreePath }` | sends SIGTERM to the child, writes receipt |
1168
+ | stop | `{ worktreePath }` | SIGTERM to the child; a recovery-tracked agent leads its own process group, so everything in it is signalled (except the preview server the session recorded), SIGKILL after the grace, and the receipt waits until the group is empty. A run with no lease generation has no private group and only the child pid is signalled. On Windows `taskkill /t` ends the tree |
1176
1169
  | merge | `{ worktreePath }` | Keep changes: commits the copy's leftovers, merges into the default branch around the person's uncommitted changes, deletes the copy and its branch |
1177
1170
  | delete | `{ worktreePath }` | Throw away: removes the worktree and deletes the branch without merging |
1178
1171
  | relaunch | `{ worktreePath }` (optional, a hint) | re-runs the RECORDED dev server command, detached, in the recorded worktree, or in the linked folder once that worktree is gone |
@@ -1580,8 +1573,8 @@ sits. `bridge/test/runner.test.mjs` has the test.
1580
1573
  `[message from <name>] <text>`, so the session can tell the person from a
1581
1574
  teammate. The contract tells the session to answer through `propose` with an
1582
1575
  `addComment` op and no `id` (it lands as its reply on its own idea), to attach
1583
- pictures with `images` (up to 6, data URLs) and to choose between looks with
1584
- `ask_user` and `images`. It also tells the session not to file a closing reply
1576
+ pictures with `images` (up to 6, data URLs) and to ask about what it saw, or
1577
+ choose between looks, with `ask_user` and `images` as `{image, caption}` (#5534). It also tells the session not to file a closing reply
1585
1578
  of its own, because the runner files one.
1586
1579
 
1587
1580
  The hosted board enforces it (#4153): a run's second reply in its idea's
@@ -1783,7 +1776,9 @@ silently. `lib/permissionAsk.mjs` owns it; `child.mjs` answers Claude's
1783
1776
  `<glytch home>/permissions/<sha256 of the folder path>.json`: a safe-list
1784
1777
  command by its family (`Bash(git status:*)`), any other shell command by the
1785
1778
  sha256 of the whole line as typed (`Bash(exact:...)`), anything else by its
1786
- tool name. A remembered rule is answered without asking; a pipe between
1779
+ tool name. A file tool's rule (Read, Write, Edit, MultiEdit, NotebookEdit, and a Glob or Grep search) applies only when every path
1780
+ the call names lands inside the folder, links followed and relative paths judged from the run's folder; a path outside, through a link that
1781
+ leads out, or missing asks fresh and offers no Always button (#6556). A remembered rule is answered without asking; a pipe between
1787
1782
  safe-list commands is covered when every part's family is saved. Word rules
1788
1783
  saved before #3726 for `ls`, `cat`, `pwd`, `head`, `tail` and `wc` still match
1789
1784
  their family; any other (`Bash(npm:*)`) matches nothing any more.
@@ -1861,21 +1856,37 @@ while a watcher is running. Claim files keep two runners off the same REQUEST;
1861
1856
  they say nothing about two processes running `git checkout main` in the same
1862
1857
  second.
1863
1858
 
1864
- So `withRepoLock` also takes a **lockdir**, `mkdir` being the one atomic
1865
- exclusive create every filesystem agrees on - the same reasoning the claim file
1866
- uses `flag: "wx"`. It lives at `<root>/.git/pm-repo.lock`, and that location is
1867
- load-bearing rather than tidy: a lock `git status` can see would read as the
1868
- person's own change, and Keep sets those aside and puts them back.
1869
- `.git/` is the one directory git never reports, it is exactly per-repo, and it
1870
- is already where git keeps its own locks.
1871
-
1872
- An `owner.json` inside it records pid, host and time, which is how the lock
1873
- survives its holder being killed: a pid that is gone **on this host** frees it
1874
- at once, a lock from another host frees on age (`LOCK_STALE_MS`, 10 minutes).
1875
- Waiting is bounded (`LOCK_WAIT_MS`, 60s) and losing the wait is not fatal - it
1876
- logs loudly and goes ahead, because refusing to clean up a worktree is worse
1877
- than the race that was there all along. A `.git` that is a file (the root is
1878
- itself a linked worktree) or a read-only checkout takes the same path.
1859
+ So `withRepoLock` also takes a **cross-process lock**, the same exclusive
1860
+ hard-link protocol the runner's admission lock uses (`acquireAdmission`,
1861
+ `admission.mjs`). It lives at `<git common dir>/pm-repo-admission/.admission.lock`,
1862
+ where the common dir comes from `git rev-parse --git-common-dir` (#6558). That is
1863
+ the one folder every linked worktree of a repo shares, so a checkout and its
1864
+ linked worktrees contend for the same lock; the old `<root>/.git/pm-repo.lock`
1865
+ could not be made in a linked worktree, where `.git` is a file. The location is
1866
+ still inside `.git/` and that is load-bearing rather than tidy: a lock `git
1867
+ status` can see would read as the person's own change, and Keep sets those aside
1868
+ and puts them back.
1869
+
1870
+ A holder that is gone **on this host** frees the lock at once (the admission
1871
+ protocol checks the pid and its start time). A holder on another host, or one
1872
+ that is alive but wedged, is never stolen from: it needs manual recovery. Once
1873
+ you have confirmed that process is stopped, delete
1874
+ `<git common dir>/pm-repo-admission/.admission.lock` (the refusal prints the full
1875
+ path) and the next change takes the lock.
1876
+ Waiting is bounded (`LOCK_WAIT_MS`, 60s).
1877
+
1878
+ **No lock, no change (#6558).** This section used to say losing the wait was not
1879
+ fatal and the change went ahead. That is the race the lock exists to stop, so it
1880
+ is gone: a lock that cannot be made, or is still held after the wait, throws
1881
+ `RepoLockError` and the callback never runs. Each exported wrapper turns that
1882
+ into its own refusal (`mergeWorktree`/`deleteWorktree` `{ ok: false, detail }`,
1883
+ `cleanWorktree` `{ removed: false, detail }` and the tree is kept,
1884
+ `makeChatWorktree` `{ ok: false, reason }`, `makeWorktree` and `reuseWorktree` a
1885
+ result marked `lockRefused`). The runner turns `lockRefused` into an error that
1886
+ spawns nothing, whether or not another run is on the project: falling back to the
1887
+ linked folder would put the session in the checkout the holder is changing, and
1888
+ "the separate copy is gone" would be untrue of a tree still on disk. The one exception is a folder that is not a git
1889
+ repository: there is nothing to lock.
1879
1890
 
1880
1891
  **No `git pull`.** `mergeWorktreeImpl` used to run `git pull --ff-only` on the
1881
1892
  user's main before merging, best-effort and unexplained. Removed 2026-09-02: it
@@ -1895,7 +1906,9 @@ state and run without the lock.
1895
1906
 
1896
1907
  **Test:** `bridge/test/worktree.test.mjs` proves two concurrent `mergeWorktree`
1897
1908
  calls on the same root serialize (order preserved, second starts after first
1898
- completes, both commits land in main).
1909
+ completes, both commits land in main). `bridge/test/repolock.test.mjs` proves a
1910
+ linked worktree takes the common lock, a held lock blocks a second change, and a
1911
+ lock that cannot be held never runs the callback.
1899
1912
 
1900
1913
  ## The ACP engine
1901
1914
 
package/lib/acp.mjs CHANGED
@@ -510,6 +510,10 @@ export function runAcpChild(opts) {
510
510
  killGraceMs,
511
511
  onChunk,
512
512
  stopPollMs,
513
+ // The adapter leads its own group when it is recovery-tracked: Stop and
514
+ // the wall clock end the whole group, not just the adapter (#6557).
515
+ keepPids: opts.keepPids,
516
+ killProcessGroup: opts.recoveryGroup === true && (opts.platform ?? process.platform) !== "win32",
513
517
  // THE STOP PATH, and the one place this engine has something better
514
518
  // than SIGTERM. `session/cancel` lets the adapter stop its model
515
519
  // request and flush its pending updates; the kill that attachChild does
package/lib/child.mjs CHANGED
@@ -19,6 +19,7 @@ import { createGzip, constants as zlibConstants } from "node:zlib";
19
19
  import { join } from "node:path";
20
20
 
21
21
  import { killTree } from "./kill.mjs";
22
+ import { reapGroup, signalGroup } from "./groupStop.mjs";
22
23
  import { makeAnswerTracker } from "./answerTag.mjs";
23
24
  import { RUNNER_BEAT_MS } from "./spawn.mjs";
24
25
  import { DELIVERED, SKIP, STOP, watchAnswers, watchReplyFiles } from "./followUps.mjs";
@@ -328,6 +329,9 @@ export function attachChild(child, {
328
329
  onChunk,
329
330
  stopCheck,
330
331
  killProcessGroup = false,
332
+ // Pids a group stop must spare: the preview server the session recorded
333
+ // (ruling A). Read at kill time, so a record written late still counts.
334
+ keepPids,
331
335
  flushFinalLine = false,
332
336
  // What the wall clock means for this child. The one-shot answer is "out of
333
337
  // time"; the streaming answer is "out of time ONLY if the turn is still
@@ -562,15 +566,16 @@ export function attachChild(child, {
562
566
 
563
567
  let killTimer;
564
568
  let killing = false;
569
+ let killedAt = 0;
565
570
  /** The one kill path: SIGTERM, then SIGKILL after the grace. A child that
566
571
  * ignores SIGTERM is still billing.
567
572
  *
568
- * IT IS THE CHILD'S PID AND NOT ITS PROCESS GROUP, and since 2026-09-06
569
- * that is load-bearing rather than incidental. `child.kill(sig)` signals
570
- * one pid; `process.kill(-pgid, sig)` would signal everything the child
571
- * started. Recovery-tracked agents now have a private group, but ordinary
572
- * callers can still share the runner's group. Normal agent shutdown
573
- * remains a single-PID signal; orphan recovery verifies members separately.
573
+ * WITHOUT A PRIVATE GROUP IT IS THE CHILD'S PID, NOT ITS PROCESS GROUP, and
574
+ * since 2026-09-06 that is load-bearing rather than incidental.
575
+ * `child.kill(sig)` signals one pid; `process.kill(-pgid, sig)` would signal
576
+ * everything in the group, which for a caller that shares the runner's
577
+ * group includes the runner. A child that leads its own group (see the
578
+ * #6557 paragraph below) is signalled as a group instead.
574
579
  *
575
580
  * Ruling A that day is what makes the distinction matter: a session
576
581
  * with the Browser switch on starts its dev server detached so the browser
@@ -587,15 +592,26 @@ export function attachChild(child, {
587
592
  * agent as a grandchild that survives and keeps billing. `killTree` sends
588
593
  * `taskkill /pid <pid> /t` and then `/t /f` there. The POSIX call it makes
589
594
  * is `child.kill(sig)`, this closure's own, so the paragraph above still
590
- * describes exactly what happens on his Mac. Package checks alone opt into
591
- * killProcessGroup: runChild gives them their OWN group, with no preview
592
- * intended to survive. Agent sessions never enable it. */
595
+ * describes exactly what happens on his Mac.
596
+ *
597
+ * A CHILD WITH ITS OWN GROUP IS STOPPED AS A GROUP (#6557). Package checks
598
+ * and every recovery-tracked agent (streaming, one-shot, ACP, Codex) start
599
+ * `detached`, so the child leads a private process group. Stop, the wall
600
+ * clock and the stall watchdog then signal that group, and `settle` waits
601
+ * until it is empty before it resolves: an ordinary background command the
602
+ * agent left running (`cmd > log &`) ends with the agent, and the runner
603
+ * deletes its recovery record only after that is true. The preview server
604
+ * the session recorded in `.viewable-server.json` is spared by pid (see
605
+ * groupStop.mjs): on macOS `nohup cmd & disown` keeps the agent's group, so
606
+ * the group alone cannot tell it from an ordinary background command. */
593
607
  const kill = () => {
594
608
  if (state.settled || killing) return;
595
609
  killing = true;
610
+ killedAt = Date.now();
596
611
  try { onKill(); } catch { /* cleanup must not prevent termination */ }
597
- const send = (force) =>
598
- killTree(child.pid, { force, signal: (_pid, sig) => killProcessGroup ? process.kill(-child.pid, sig) : child.kill(sig) }).catch(() => {
612
+ const send = (force) => (killProcessGroup
613
+ ? signalGroup(child.pid, force ? "SIGKILL" : "SIGTERM", { keep: keepPids })
614
+ : killTree(child.pid, { force, signal: (_pid, sig) => child.kill(sig) })).catch(() => {
599
615
  /* a child that is already gone is not an error here */
600
616
  });
601
617
  killTimer = setTimeout(() => send(true), killGraceMs);
@@ -632,17 +648,14 @@ export function attachChild(child, {
632
648
  state.settled = true;
633
649
  clearTimeout(wallTimer);
634
650
  clearTimeout(killTimer);
635
- if (killProcessGroup && (state.timedOut || state.stoppedByUser)) {
636
- // The npm parent may close before a script that ignored SIGTERM.
637
- try { process.kill(-child.pid, "SIGKILL"); } catch { /* group already gone */ }
638
- }
639
651
  for (const timer of timers) clearInterval(timer);
640
652
  // Flush and close the gzip trailer so the file on disk is complete and
641
653
  // valid gzip, whichever way this child ended - and only THEN resolve,
642
654
  // so whoever reads the transcript next finds the whole of it (see
643
655
  // openTranscriptSink's close()).
644
- const finish = () => resolve({
656
+ const finish = (survivors) => resolve({
645
657
  ...result,
658
+ ...(survivors?.length ? { descendantsRemain: survivors } : {}),
646
659
  log: ring.text(),
647
660
  stderr: errTail.trim(),
648
661
  truncated: ring.dropped > 0,
@@ -658,8 +671,16 @@ export function attachChild(child, {
658
671
  ...extraFields(state),
659
672
  });
660
673
  const closed = transcriptSink?.close();
661
- if (closed && typeof closed.then === "function") closed.then(finish, finish);
662
- else finish();
674
+ const flushed = closed && typeof closed.then === "function" ? closed.then(() => {}, () => {}) : null;
675
+ if (!(killing && killProcessGroup)) {
676
+ if (flushed) flushed.then(() => finish());
677
+ else finish();
678
+ return;
679
+ }
680
+ // Resolve only when the transcript is whole AND nothing the child started
681
+ // is left in its group (#6557).
682
+ Promise.all([flushed, reapGroup(child.pid, killedAt + killGraceMs, { keep: keepPids })])
683
+ .then(([, left]) => finish(left), () => finish([child.pid]));
663
684
  };
664
685
 
665
686
  child.on("error", (error) => settle({ ok: false, spawnError: error.message }));
@@ -689,7 +710,9 @@ export function attachChild(child, {
689
710
  * The wall clock is not a progress protocol and does not put a third state on
690
711
  * the board. It is the one bound between "a session hung" and "a session
691
712
  * billed all night". */
692
- export function runChild({ bin, args, cwd, env, input, recoveryGroup = false, onProcess, onSession, maxMs, maxLogBytes = DEFAULTS.maxLogBytes, killGraceMs = DEFAULTS.killGraceMs, onChunk, onStdout, stopCheck, stopPollMs = 2000, onSpend, platform = process.platform, transcriptDir, killProcessGroup = false, claudeResult = false }) {
713
+ export function runChild({ bin, args, cwd, env, input, recoveryGroup = false, onProcess, onSession, maxMs, maxLogBytes = DEFAULTS.maxLogBytes, killGraceMs = DEFAULTS.killGraceMs, onChunk, onStdout, stopCheck, stopPollMs = 2000, onSpend, platform = process.platform, transcriptDir, killProcessGroup = false, keepPids, claudeResult = false }) {
714
+ // A private group is a group that is signalled: one flag, not two (#6557).
715
+ const ownGroup = (killProcessGroup || recoveryGroup) && platform !== "win32";
693
716
  return new Promise((resolve) => {
694
717
  let child;
695
718
  try {
@@ -702,7 +725,7 @@ export function runChild({ bin, args, cwd, env, input, recoveryGroup = false, on
702
725
  // `windowsHide: true` is harmless on POSIX (detect.mjs's execProbe has
703
726
  // carried it unconditionally since before this brief) and stops a
704
727
  // console window flashing per session on Windows.
705
- child = spawn(resolved.file, resolved.args, { cwd, env, stdio: [input === undefined ? "ignore" : "pipe", "pipe", "pipe"], shell: resolved.shell, windowsHide: true, detached: (killProcessGroup || recoveryGroup) && platform !== "win32" });
728
+ child = spawn(resolved.file, resolved.args, { cwd, env, stdio: [input === undefined ? "ignore" : "pipe", "pipe", "pipe"], shell: resolved.shell, windowsHide: true, detached: ownGroup });
706
729
  } catch (error) {
707
730
  resolve({ ok: false, spawnError: error instanceof Error ? error.message : String(error), log: "" });
708
731
  return;
@@ -725,7 +748,8 @@ export function runChild({ bin, args, cwd, env, input, recoveryGroup = false, on
725
748
  onChunk,
726
749
  stopCheck,
727
750
  stopPollMs,
728
- killProcessGroup: killProcessGroup && platform !== "win32",
751
+ killProcessGroup: ownGroup,
752
+ keepPids,
729
753
  transcriptDir,
730
754
  flushFinalLine: claudeResult,
731
755
  ...(claudeResult ? { onEvent: observeClaudeModel(args, { ...process.env, ...env }) } : {}),
@@ -809,7 +833,9 @@ export function runChild({ bin, args, cwd, env, input, recoveryGroup = false, on
809
833
  * whole new resume request - the watch loop's 5s poll, the app's receipt, the
810
834
  * worktree, and a cold `claude --resume`. That is tens of seconds and it is a
811
835
  * design decision, not a constant. */
812
- export function runStreamingChild({ bin, args, cwd, env, recoveryGroup = false, onSpawn, onProcess, onSession, maxMs, maxLogBytes = DEFAULTS.maxLogBytes, killGraceMs = DEFAULTS.killGraceMs, stallMs = DEFAULTS.stallMs, onChunk, prompt, images, replyDir, replyPrefix, replyPollMs = 500, onUndeliveredReply, answerPoll, answerPollMs = 4000, askPermission, stopCheck, stopPollMs = 2000, onSpend, platform = process.platform, transcriptDir }) {
836
+ export function runStreamingChild({ bin, args, cwd, env, recoveryGroup = false, onSpawn, onProcess, onSession, maxMs, maxLogBytes = DEFAULTS.maxLogBytes, killGraceMs = DEFAULTS.killGraceMs, stallMs = DEFAULTS.stallMs, onChunk, prompt, images, replyDir, replyPrefix, replyPollMs = 500, onUndeliveredReply, answerPoll, answerPollMs = 4000, askPermission, stopCheck, stopPollMs = 2000, onSpend, platform = process.platform, transcriptDir, keepPids }) {
837
+ // Its private group is signalled on Stop and timeout, not just created (#6557).
838
+ const ownGroup = recoveryGroup && platform !== "win32";
813
839
  return new Promise((resolve) => {
814
840
  try { imageAttachments(images); } catch (error) { resolve({ ok: false, log: "", spawnError: error.message }); return; }
815
841
  let child;
@@ -818,7 +844,7 @@ export function runStreamingChild({ bin, args, cwd, env, recoveryGroup = false,
818
844
  // AND opencode per ruling 5B) - streaming is the path a persistent
819
845
  // Claude Code session takes.
820
846
  const resolved = runnableCommand(bin, args, { platform, env });
821
- child = spawn(resolved.file, resolved.args, { cwd, env, stdio: ["pipe", "pipe", "pipe"], shell: resolved.shell, windowsHide: true, detached: recoveryGroup && platform !== "win32" });
847
+ child = spawn(resolved.file, resolved.args, { cwd, env, stdio: ["pipe", "pipe", "pipe"], shell: resolved.shell, windowsHide: true, detached: ownGroup });
822
848
  } catch (error) {
823
849
  resolve({ ok: false, spawnError: error instanceof Error ? error.message : String(error), log: "" });
824
850
  return;
@@ -842,6 +868,8 @@ export function runStreamingChild({ bin, args, cwd, env, recoveryGroup = false,
842
868
  stopCheck,
843
869
  stopPollMs,
844
870
  transcriptDir,
871
+ killProcessGroup: ownGroup,
872
+ keepPids,
845
873
  // THE WALL CLOCK MEANS SOMETHING ELSE HERE. Closing an IDLE child is
846
874
  // the reply window ending, not a timeout: the work finished when the
847
875
  // envelope landed. Only a child still mid-turn - no envelope since the
package/lib/codex.mjs CHANGED
@@ -252,7 +252,7 @@ function protocolQuestions(method, params) {
252
252
  // The tool's inputs come with it, short and with secrets hidden (#608).
253
253
  const details = toolInputsText(params);
254
254
  questions.push({ question: `${params.serverName}: ${params.message}`, options: ["Allow", "Not this"],
255
- why: `On your computer, ${params.serverName}\n${riskReason(writeRisk(params.serverName.toLowerCase(), params.message, params._meta?.tool_params) ?? "open-ended")}\n${details ? `${details}\n\n` : ""}This answer applies only to this request.` });
255
+ why: `On your computer, ${params.serverName}\n${riskReason(writeRisk(null, params.message, params._meta?.tool_params) ?? "open-ended")}\n${details ? `${details}\n\n` : ""}This answer applies only to this request.` });
256
256
  return { questions };
257
257
  }
258
258
 
@@ -343,6 +343,8 @@ function runCodexAttempt(opts, apps) {
343
343
  kill: (signal) => child.kill(signal), on(event, fn) { child.on(event, fn); return facade; } };
344
344
  const handle = attachChild(facade, {
345
345
  ...opts,
346
+ // The app-server leads its own group when recovery-tracked (#6557).
347
+ killProcessGroup: opts.recoveryGroup === true && (opts.platform ?? process.platform) !== "win32",
346
348
  onSession: undefined, // The native thread/start path awaits this callback before prompting.
347
349
  resolve: (outcome) => { clearTimeout(finishTimer); abortQuestions(); rpc?.close(); resolve({ ...outcome, ...(appsRetry ? { appsRetry } : {}) }); },
348
350
  // Latch admission closed BEFORE SIGTERM. A still-running child may