typeclaw 0.48.10 → 0.48.11

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.
Files changed (33) hide show
  1. package/package.json +1 -1
  2. package/scripts/apparmor/typeclaw-bwrap +43 -0
  3. package/scripts/verify-apparmor-signals.sh +161 -0
  4. package/scripts/verify-mask-fd-sandbox.sh +86 -16
  5. package/src/agent/live-subagents.ts +98 -0
  6. package/src/agent/session-origin.ts +5 -1
  7. package/src/agent/tools/channel-reply.ts +30 -2
  8. package/src/agent/tools/channel-send.ts +19 -2
  9. package/src/agent/tools/spawn-subagent.ts +37 -1
  10. package/src/bundled-plugins/github-cli-auth/index.ts +1 -0
  11. package/src/channels/adapters/github/inbound.ts +195 -25
  12. package/src/channels/adapters/github/index.ts +16 -18
  13. package/src/channels/adapters/github/reconcile-cooldown-store.ts +15 -1
  14. package/src/channels/adapters/github/recover-failed-deliveries.ts +7 -2
  15. package/src/channels/adapters/github/review-submitter.ts +28 -0
  16. package/src/channels/github-repo.ts +11 -0
  17. package/src/channels/github-review-verdict-coordinator.ts +179 -29
  18. package/src/channels/github-verdict-activity.ts +10 -6
  19. package/src/channels/manager.ts +9 -0
  20. package/src/channels/persistence.ts +28 -2
  21. package/src/channels/router.ts +284 -61
  22. package/src/channels/schema.ts +18 -0
  23. package/src/channels/types.ts +1 -0
  24. package/src/config/config.ts +9 -1
  25. package/src/container/start.ts +33 -24
  26. package/src/doctor/apparmor.ts +101 -0
  27. package/src/doctor/checks.ts +2 -0
  28. package/src/init/dockerfile.ts +7 -6
  29. package/src/init/windows-dev-link.ts +34 -2
  30. package/src/run/index.ts +1 -0
  31. package/src/sandbox/availability.ts +7 -5
  32. package/src/skills/typeclaw-channel-github/SKILL.md +4 -2
  33. package/typeclaw.schema.json +7 -0
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "typeclaw",
3
- "version": "0.48.10",
3
+ "version": "0.48.11",
4
4
  "homepage": "https://github.com/typeclaw/typeclaw#readme",
5
5
  "bugs": {
6
6
  "url": "https://github.com/typeclaw/typeclaw/issues"
@@ -0,0 +1,43 @@
1
+ # TypeClaw's per-tool bwrap sandbox needs userns and mount. Moby's
2
+ # docker-default profile denies mount, while Ubuntu 23.10+'s unprivileged_userns
3
+ # catch-all restricts unconfined processes, so the host must load this profile.
4
+ abi <abi/4.0>,
5
+ include <tunables/global>
6
+
7
+ profile typeclaw-bwrap flags=(attach_disconnected,mediate_deleted) {
8
+ userns,
9
+ mount,
10
+ umount,
11
+ pivot_root,
12
+ capability,
13
+ file,
14
+ network,
15
+ # AF_UNIX is a separately mediated class under the pinned 4.0 ABI, not a
16
+ # subset of `network`. Xvfb's /tmp/.X11-unix socket and the runtime's local
17
+ # IPC both need it, and omitting it would fail only at runtime.
18
+ unix,
19
+
20
+ # Signals are mediated too, so every peer that must reach a container process
21
+ # is named here — mirroring moby's docker-default template
22
+ # (profiles/apparmor/template.go), which exists because container processes
23
+ # became unsignalable without it.
24
+ #
25
+ # - unconfined: an unconfined dockerd, and privileged host processes.
26
+ # - runc / crun: Ubuntu 23.10+ ships an AppArmor-confined OCI runtime, and
27
+ # `docker stop` reaches PID 1 through `runc kill`, not always through the
28
+ # daemon. `peer=unconfined` alone does not cover that hop.
29
+ # - snap.docker.dockerd: snap-packaged Docker runs its daemon confined.
30
+ # - typeclaw-bwrap: the runtime cancelling its own sandboxed bash call. Every
31
+ # process in the container carries this profile, bwrap children included,
32
+ # so timeout/abort kills are same-profile sends.
33
+ #
34
+ # A peer profile that is not loaded on this host is inert, not an error. An
35
+ # operator running a differently-labelled daemon or OCI runtime must add that
36
+ # label here; `scripts/verify-apparmor-signals.sh` is the check that a given
37
+ # host's stop/restart and cancellation paths actually survive this policy.
38
+ signal (receive) peer=unconfined,
39
+ signal (receive) peer=runc,
40
+ signal (receive) peer=crun,
41
+ signal (receive) peer=snap.docker.dockerd,
42
+ signal (send,receive) peer=typeclaw-bwrap,
43
+ }
@@ -0,0 +1,161 @@
1
+ #!/usr/bin/env bash
2
+ # Acceptance check for signal delivery under the shipped AppArmor profile
3
+ # (scripts/apparmor/typeclaw-bwrap). Companion to verify-mask-fd-sandbox.sh,
4
+ # which only proves bwrap can START — its sandboxed command exits naturally, so
5
+ # it covers neither of the two paths that need a signal to cross the profile:
6
+ #
7
+ # 1. Cancellation. The agent kills its own sandboxed bash on timeout/abort.
8
+ # Every process in the container carries the container profile, bwrap
9
+ # children included, so that is a SAME-PROFILE send and needs an explicit
10
+ # `signal (send,receive) peer=typeclaw-bwrap`.
11
+ # 2. Lifecycle. `typeclaw stop`/`restart` are `docker stop`/`docker restart`
12
+ # (src/container/start.ts), whose SIGTERM originates outside the profile —
13
+ # from an unconfined dockerd, or from `runc kill` where the OCI runtime
14
+ # itself is confined on Ubuntu 23.10+. That needs `signal (receive)` rules
15
+ # naming those peers.
16
+ #
17
+ # Both failures are silent-ish in production: a denied cancellation leaves a
18
+ # runaway sandbox, and a denied SIGTERM turns every stop into a 10s wait for
19
+ # dockerd's SIGKILL. Neither shows up as a bwrap error, which is why this runs
20
+ # as its own release gate rather than as an extra assertion in the mask lane.
21
+ #
22
+ # The container is deliberately NOT run with --rm: the stop/start/restart legs
23
+ # need its filesystem (and the counters below) to survive exit.
24
+ #
25
+ # Usage: scripts/verify-apparmor-signals.sh [image] [platform]
26
+ # image defaults to ghcr.io/typeclaw/typeclaw-base:<version-from-package.json>
27
+ # platform e.g. linux/amd64; defaults to the daemon's native platform
28
+ # TYPECLAW_APPARMOR_PROFILE selects the profile, defaulting to the product
29
+ # default (unconfined) so a plain local run still exercises the script.
30
+ set -euo pipefail
31
+
32
+ IMAGE="${1:-}"
33
+ PLATFORM="${2:-}"
34
+ APPARMOR_PROFILE="${TYPECLAW_APPARMOR_PROFILE:-unconfined}"
35
+ STOP_GRACE=5
36
+ if [ -z "$IMAGE" ]; then
37
+ version="$(node -p "require('./package.json').version" 2>/dev/null || echo latest)"
38
+ IMAGE="ghcr.io/typeclaw/typeclaw-base:${version}"
39
+ fi
40
+
41
+ NAME="typeclaw-signal-check-$$"
42
+ cleanup() { docker rm -f "$NAME" >/dev/null 2>&1 || true; }
43
+ trap cleanup EXIT
44
+
45
+ # PID 1 counts the SIGTERMs it actually handled, in a file that outlives each
46
+ # container exit. A counter — not `docker inspect`'s exit code — is the oracle:
47
+ # a PID 1 relying on SIGTERM's DEFAULT disposition dies identically whether the
48
+ # signal arrived or dockerd's post-grace SIGKILL did, and `--init` rewrites the
49
+ # propagated status anyway. Only an installed handler proves receipt.
50
+ #
51
+ # `boots` is the readiness marker and is bumped AFTER the trap is installed, so
52
+ # the caller can never observe a container that is up but not yet trap-armed —
53
+ # and, unlike a `ready` file, it cannot be confused with a stale one left behind
54
+ # by the previous run's filesystem.
55
+ read -r -d '' PID1_PAYLOAD <<'PAYLOAD' || true
56
+ set -u
57
+ state=/tmp/typeclaw-signal-state
58
+ mkdir -p "$state"
59
+ [ -f "$state/terms" ] || printf '0\n' > "$state/terms"
60
+ trap 'printf "%s\n" "$(( $(cat "$state/terms") + 1 ))" > "$state/terms"; exit 0' TERM
61
+ printf '%s\n' "$(( $(cat "$state/boots" 2>/dev/null || echo 0) + 1 ))" > "$state/boots"
62
+ while :; do
63
+ sleep 0.2 &
64
+ wait "$!"
65
+ done
66
+ PAYLOAD
67
+
68
+ # Mirrors the sandbox shape verify-mask-fd-sandbox.sh renders (buildArgv() in
69
+ # src/sandbox/build.ts) minus the masks, which are not what is under test here.
70
+ # An AppArmor signal denial surfaces as EPERM from kill(2), so the send is
71
+ # checked separately from the death — otherwise a denied send and an ignored
72
+ # signal would report identically. The watchdog bounds the wait so a wedged
73
+ # sandbox fails the gate instead of hanging it.
74
+ read -r -d '' ABORT_PAYLOAD <<'PAYLOAD' || true
75
+ set -u
76
+ bwrap --unshare-all --share-net \
77
+ --new-session --die-with-parent --clearenv \
78
+ --setenv PATH /usr/local/bin:/usr/bin:/bin --setenv HOME /tmp --setenv LANG C.UTF-8 \
79
+ --ro-bind /usr /usr --ro-bind /etc /etc --dev /dev --tmpfs /tmp \
80
+ --ro-bind-try /bin /bin --ro-bind-try /sbin /sbin --ro-bind-try /lib /lib --ro-bind-try /lib64 /lib64 \
81
+ -- sleep 300 &
82
+ pid=$!
83
+ sleep 0.5
84
+ if ! kill -0 "$pid" 2>/dev/null; then
85
+ wait "$pid" || true
86
+ echo "CANCEL_SANDBOX_DIED_EARLY: bwrap exited before it could be aborted"
87
+ exit 1
88
+ fi
89
+ if ! kill -TERM "$pid" 2>/tmp/cancel.err; then
90
+ echo "CANCEL_SEND_DENIED: kill -TERM refused: $(cat /tmp/cancel.err)"
91
+ exit 1
92
+ fi
93
+ ( sleep 5; kill -KILL "$pid" 2>/dev/null ) &
94
+ watchdog=$!
95
+ set +e
96
+ wait "$pid"
97
+ rc=$?
98
+ set -e
99
+ kill "$watchdog" 2>/dev/null || true
100
+ if [ "$rc" -ne 143 ]; then
101
+ echo "CANCEL_NOT_DELIVERED: sandbox exited $rc, expected 143 (SIGTERM)"
102
+ exit 1
103
+ fi
104
+ echo "CANCEL_OK: same-profile SIGTERM aborted the sandboxed command"
105
+ PAYLOAD
106
+
107
+ boots() { docker exec "$NAME" cat /tmp/typeclaw-signal-state/boots 2>/dev/null || true; }
108
+ terms() { docker exec "$NAME" cat /tmp/typeclaw-signal-state/terms 2>/dev/null || true; }
109
+
110
+ wait_for_boot() {
111
+ local expected="$1" i=0
112
+ while [ "$i" -lt 300 ]; do
113
+ if [ "$(boots)" = "$expected" ]; then return 0; fi
114
+ sleep 0.1
115
+ i=$((i + 1))
116
+ done
117
+ echo "SIGNAL_GATE_FAILED: container did not reach boot $expected" >&2
118
+ docker logs "$NAME" >&2 || true
119
+ return 1
120
+ }
121
+
122
+ assert_terms() {
123
+ local expected="$1" label="$2" actual
124
+ actual="$(terms)"
125
+ if [ "$actual" != "$expected" ]; then
126
+ echo "SIGNAL_NOT_RECEIVED: $label — PID 1 handled $actual SIGTERM(s), expected $expected."
127
+ echo " The AppArmor profile ($APPARMOR_PROFILE) is not permitting signal receipt from"
128
+ echo " the daemon or OCI runtime. Add the missing 'signal (receive) peer=<label>' rule;"
129
+ echo " see scripts/apparmor/typeclaw-bwrap."
130
+ exit 1
131
+ fi
132
+ }
133
+
134
+ echo "Image: $IMAGE${PLATFORM:+ ($PLATFORM)}"
135
+ echo "AppArmor profile: $APPARMOR_PROFILE"
136
+
137
+ # --init, --user, and --cap-drop mirror the production container: `docker stop`
138
+ # reaches PID 1 through tini there too, and a root/capable payload could pass
139
+ # this gate on kill permissions the real agent process does not hold.
140
+ run_args=(-d --name "$NAME" --pull=always --init --user 1001:1001 --cap-drop ALL -e HOME=/tmp)
141
+ run_args+=(--security-opt seccomp=unconfined --security-opt "apparmor=$APPARMOR_PROFILE")
142
+ if [ -n "$PLATFORM" ]; then
143
+ run_args+=(--platform "$PLATFORM")
144
+ fi
145
+
146
+ docker run "${run_args[@]}" "$IMAGE" bash -c "$PID1_PAYLOAD" >/dev/null
147
+ wait_for_boot 1
148
+ assert_terms 0 'fresh container'
149
+
150
+ docker exec "$NAME" bash -c "$ABORT_PAYLOAD"
151
+
152
+ docker stop --time "$STOP_GRACE" "$NAME" >/dev/null
153
+ docker start "$NAME" >/dev/null
154
+ wait_for_boot 2
155
+ assert_terms 1 'docker stop'
156
+
157
+ docker restart --time "$STOP_GRACE" "$NAME" >/dev/null
158
+ wait_for_boot 3
159
+ assert_terms 2 'docker restart'
160
+
161
+ echo "SIGNAL_CONTRACT_OK: cancellation, stop, and restart all delivered under $APPARMOR_PROFILE"
@@ -29,24 +29,79 @@ set -euo pipefail
29
29
 
30
30
  IMAGE="${1:-}"
31
31
  PLATFORM="${2:-}"
32
+ # production | diagnostic. They answer DIFFERENT questions and the release runs
33
+ # both, because one lane alone is misleading in each direction:
34
+ # production - can bwrap run at all under the flags an agent container gets?
35
+ # Authoritative. A failure here means the model bash surface is
36
+ # dead on this host, which is the outage this gate exists to stop.
37
+ # diagnostic - is the --ro-bind-data mask/fd contract still honoured by the
38
+ # shipped bwrap? Runs with AppArmor lifted so it can reach the
39
+ # masks even where host policy blocks bwrap outright. It can
40
+ # NEVER authorize a release on its own; it only distinguishes
41
+ # "the mask argv regressed" from "this host forbids bwrap".
42
+ MODE="${3:-production}"
43
+ APPARMOR_PROFILE="${TYPECLAW_APPARMOR_PROFILE:-unconfined}"
32
44
  if [ -z "$IMAGE" ]; then
33
45
  version="$(node -p "require('./package.json').version" 2>/dev/null || echo latest)"
34
46
  IMAGE="ghcr.io/typeclaw/typeclaw-base:${version}"
35
47
  fi
48
+ case "$MODE" in
49
+ production | diagnostic) ;;
50
+ *)
51
+ echo "unknown mode: $MODE (expected 'production' or 'diagnostic')" >&2
52
+ exit 2
53
+ ;;
54
+ esac
36
55
 
37
56
  # Mirrors CANONICAL_AGENT_SECRET_FILES + CANONICAL_AGENT_RUNTIME_PRIVATE_FILES.
38
57
  # The count is what matters here (one fd per mask); keep in sync if that grows.
39
58
  runner='
40
59
  set -u
60
+ # Production hands the agent a non-root UID with an EMPTY capability set:
61
+ # `setpriv --reuid --regid --clear-groups --bounding-set=-all --inh-caps=-all
62
+ # --ambient-caps=-all` in buildEntrypointShim() (src/init/dockerfile.ts). The
63
+ # published base image carries no ENTRYPOINT, so this container never replays
64
+ # that handoff — the flags below stand in for it, and these assertions are what
65
+ # stop the gate from certifying a root/full-bounding-set shape production never
66
+ # runs. Fail before bwrap so a privilege regression is never mistaken for a
67
+ # bwrap verdict either way.
68
+ uid="$(id -u)"
69
+ gid="$(id -g)"
70
+ if [ "$uid" != 1001 ] || [ "$gid" != 1001 ]; then
71
+ echo "PRIVILEGE_UNEXPECTED: uid=$uid gid=$gid (expected 1001:1001)"
72
+ exit 1
73
+ fi
74
+ seen=0
75
+ while read -r field value; do
76
+ case "$field" in
77
+ CapInh: | CapPrm: | CapEff: | CapBnd: | CapAmb:)
78
+ seen=$((seen + 1))
79
+ if [ "$value" != 0000000000000000 ]; then
80
+ echo "PRIVILEGE_CAPS_PRESENT: $field $value (expected 0000000000000000)"
81
+ exit 1
82
+ fi
83
+ ;;
84
+ esac
85
+ done < /proc/self/status
86
+ if [ "$seen" -ne 5 ]; then
87
+ echo "PRIVILEGE_CAPS_UNREADABLE: found $seen of 5 capability masks in /proc/self/status"
88
+ exit 1
89
+ fi
90
+ echo "PRIVILEGE_OK: uid=$uid gid=$gid, all five capability masks empty"
91
+
41
92
  d=/tmp/maskcheck
42
93
  mkdir -p "$d"
43
94
  for f in env secrets.json auth.json incidents.json; do printf CANARY > "$d/$f"; done
44
95
 
45
96
  # The argv shape mirrors buildArgv()/appendMasks() in src/sandbox/build.ts:
46
97
  # masks render after the broad parent bind, and the rendered commandString
47
- # self-opens one /dev/null fd per masked file. Keep in sync if that changes.
98
+ # self-opens one /dev/null fd per masked file. `--share-net` is part of that
99
+ # shape — production sets network:'inherit' (src/agent/plugin-tools.ts), which
100
+ # build.ts turns into --share-net, so omitting it made bwrap bring up a loopback
101
+ # production never asks it to and failed for a reason production cannot hit.
102
+ # Keep in sync if that changes.
48
103
  set +e
49
- out="$(bwrap --unshare-all \
104
+ out="$(bwrap --unshare-all --share-net \
50
105
  --new-session --die-with-parent --clearenv \
51
106
  --setenv PATH /usr/local/bin:/usr/bin:/bin --setenv HOME /tmp --setenv LANG C.UTF-8 \
52
107
  --ro-bind /usr /usr --ro-bind /etc /etc --dev /dev --tmpfs /tmp \
@@ -84,21 +139,36 @@ echo "Image: $IMAGE${PLATFORM:+ ($PLATFORM)}"
84
139
  # no QEMU registered that dies on exec format, failing the release for a reason
85
140
  # that has nothing to do with bwrap. Re-resolving the tag here keeps the check
86
141
  # honest on both the classic and containerd image stores.
87
- # --privileged so `bwrap --unshare-all` can actually build its namespaces here.
88
- # The runners restrict namespace creation in layers, and each one aborts the
89
- # invocation before a single mask is evaluated — so the step fails for reasons
90
- # that say nothing about the contract under test: docker-default AppArmor denies
91
- # the opening mount(NULL, "/", MS_SLAVE|MS_REC) ("Failed to make / slave"), and
92
- # the loopback bring-up in the new netns fails RTM_NEWADDR "Operation not
93
- # permitted" even with seccomp and AppArmor unconfined and NET_ADMIN added,
94
- # because the restriction is on the user namespace that would confer it.
142
+ # seccomp=unconfined plus the configured AppArmor profile are what agent
143
+ # containers actually get (`runArgs` in src/container/start.ts), so production
144
+ # mirrors both. TYPECLAW_APPARMOR_PROFILE lets release CI select the shipped,
145
+ # host-loaded profile exactly as an Ubuntu operator does; it defaults to the
146
+ # product default, unconfined. Diagnostic always uses apparmor=unconfined after
147
+ # the caller has explicitly relaxed the host sysctl.
148
+ #
149
+ # Measured on Ubuntu 24.04: docker-default denies bwrap's opening
150
+ # mount(NULL, "/", MS_SLAVE|MS_REC), while apparmor=unconfined reaches Ubuntu's
151
+ # unprivileged_userns catch-all and loses the uid_map write at the stock sysctl
152
+ # value of 1. The shipped typeclaw-bwrap profile is the supported production
153
+ # path on that host; never make this lane green by relaxing the sysctl first.
95
154
  #
96
- # This is scaffolding for a throwaway container running a known image inside the
97
- # release pipeline, NOT a runtime capability grant — agent containers get
98
- # seccomp=unconfined and nothing more. What the gate certifies is unchanged: the
99
- # bwrap argv still mirrors buildArgv()/appendMasks(), and MASK_BWRAP_FAILED,
100
- # MASK_LEAKED and MASK_CONTRACT_OK all still fail the release on a real break.
101
- run_args=(--rm --pull=always --privileged)
155
+ # Anything beyond these production flags (NET_ADMIN, --privileged, or
156
+ # SYS_ADMIN) is unnecessary; SYS_ADMIN is also empty after the production
157
+ # entrypoint drops to a non-root UID, so do not add it here.
158
+ #
159
+ # --user/--cap-drop stand in for that entrypoint handoff, which this image
160
+ # cannot replay (no ENTRYPOINT in the published base). 1001:1001 is hardcoded
161
+ # rather than taken from `id -u`: a root or self-hosted runner would otherwise
162
+ # silently downgrade the gate to the root posture it exists to reject. The UID
163
+ # has no passwd entry in the base image, so HOME is set explicitly — without it
164
+ # bash falls back to `/` and the failure reads like a bwrap fault. Both lanes
165
+ # get this: the lanes differ only in AppArmor/sysctl treatment, never privilege.
166
+ run_args=(--rm --pull=always --user 1001:1001 --cap-drop ALL -e HOME=/tmp --security-opt seccomp=unconfined)
167
+ if [ "$MODE" = diagnostic ]; then
168
+ run_args+=(--security-opt apparmor=unconfined)
169
+ else
170
+ run_args+=(--security-opt "apparmor=$APPARMOR_PROFILE")
171
+ fi
102
172
  if [ -n "$PLATFORM" ]; then
103
173
  run_args+=(--platform "$PLATFORM")
104
174
  fi
@@ -19,6 +19,7 @@ export type LiveSubagent = {
19
19
  sessionId: string
20
20
  subagentName: string
21
21
  parentSessionId?: string
22
+ workKey?: string
22
23
  // Role that resolved at spawn time, captured for the provenance cap on
23
24
  // subagent_output/subagent_cancel. Absent when no permission service was
24
25
  // active at spawn, in which case the cap fails closed.
@@ -35,6 +36,11 @@ export type LiveSubagent = {
35
36
  releaseCoalesceKey?: () => void
36
37
  }
37
38
 
39
+ export type PendingWorkKeyRegistration = {
40
+ readonly workKey: string
41
+ cancelled: boolean
42
+ }
43
+
38
44
  export const MAX_EVENTS_PER_SUBAGENT = 100
39
45
  export const MESSAGE_PREVIEW_CHARS = 200
40
46
 
@@ -112,6 +118,7 @@ export class LiveSubagentRegistry {
112
118
  private readonly entries = new Map<string, LiveSubagent>()
113
119
  private readonly events = new Map<string, SubagentProgressEvent[]>()
114
120
  private readonly capturedFinalMessages = new Map<string, string>()
121
+ private readonly pendingWorkKeyRegistrations = new Map<string, Set<PendingWorkKeyRegistration>>()
115
122
 
116
123
  register(live: LiveSubagent): void {
117
124
  if (this.entries.has(live.taskId)) {
@@ -121,6 +128,28 @@ export class LiveSubagentRegistry {
121
128
  this.events.set(live.taskId, [{ kind: 'started', ts: live.startedAt }])
122
129
  }
123
130
 
131
+ beginWorkKeyRegistration(workKey: string): PendingWorkKeyRegistration {
132
+ const registration: PendingWorkKeyRegistration = { workKey, cancelled: false }
133
+ const pending = this.pendingWorkKeyRegistrations.get(workKey) ?? new Set<PendingWorkKeyRegistration>()
134
+ pending.add(registration)
135
+ this.pendingWorkKeyRegistrations.set(workKey, pending)
136
+ return registration
137
+ }
138
+
139
+ abandonWorkKeyRegistration(registration: PendingWorkKeyRegistration): void {
140
+ this.removePendingWorkKeyRegistration(registration)
141
+ }
142
+
143
+ registerIfWorkKeyActive(live: LiveSubagent, registration: PendingWorkKeyRegistration): boolean {
144
+ this.removePendingWorkKeyRegistration(registration)
145
+ if (live.workKey !== registration.workKey) {
146
+ throw new Error(`task ${live.taskId} work key changed before registration`)
147
+ }
148
+ if (registration.cancelled) return false
149
+ this.register(live)
150
+ return true
151
+ }
152
+
124
153
  unregister(taskId: string): void {
125
154
  this.entries.delete(taskId)
126
155
  this.events.delete(taskId)
@@ -189,6 +218,52 @@ export class LiveSubagentRegistry {
189
218
  return true
190
219
  }
191
220
 
221
+ async cancelRunningByWorkKey(
222
+ workKey: string,
223
+ reason: string,
224
+ ): Promise<{ matched: number; cancelled: number; failures: number }> {
225
+ const pending = this.pendingWorkKeyRegistrations.get(workKey)
226
+ if (pending !== undefined) {
227
+ for (const registration of pending) registration.cancelled = true
228
+ this.pendingWorkKeyRegistrations.delete(workKey)
229
+ }
230
+ const all = Array.from(this.entries.values())
231
+ const roots = all.filter((entry) => entry.status === 'running' && entry.workKey === workKey)
232
+ if (roots.length === 0) return { matched: 0, cancelled: 0, failures: 0 }
233
+
234
+ const rootsBySessionId = new Set(roots.map((entry) => entry.sessionId))
235
+ const entriesBySessionId = new Map(all.map((entry) => [entry.sessionId, entry]))
236
+ const rootTaskIds = new Set(roots.map((entry) => entry.taskId))
237
+ const matched = all.filter(
238
+ (entry) =>
239
+ entry.status === 'running' &&
240
+ (rootTaskIds.has(entry.taskId) || isDescendantOfAny(entry, rootsBySessionId, entriesBySessionId)),
241
+ )
242
+
243
+ const settledAt = Date.now()
244
+ for (const entry of matched) {
245
+ this.recordCompletionIfRunning(entry.taskId, {
246
+ ok: false,
247
+ error: `cancelled: ${reason}`,
248
+ durationMs: Math.max(0, settledAt - entry.startedAt),
249
+ })
250
+ }
251
+ for (const entry of matched) entry.releaseCoalesceKey?.()
252
+
253
+ const outcomes = await Promise.all(
254
+ matched.map(async (entry): Promise<boolean> => {
255
+ try {
256
+ await entry.abort()
257
+ return true
258
+ } catch {
259
+ return false
260
+ }
261
+ }),
262
+ )
263
+ const cancelled = outcomes.filter(Boolean).length
264
+ return { matched: matched.length, cancelled, failures: matched.length - cancelled }
265
+ }
266
+
192
267
  snapshot(taskId: string, now: number = Date.now()): StatusSnapshot | undefined {
193
268
  const entry = this.entries.get(taskId)
194
269
  if (entry === undefined) return undefined
@@ -215,7 +290,30 @@ export class LiveSubagentRegistry {
215
290
  this.entries.clear()
216
291
  this.events.clear()
217
292
  this.capturedFinalMessages.clear()
293
+ this.pendingWorkKeyRegistrations.clear()
294
+ }
295
+
296
+ private removePendingWorkKeyRegistration(registration: PendingWorkKeyRegistration): void {
297
+ const pending = this.pendingWorkKeyRegistrations.get(registration.workKey)
298
+ if (pending === undefined) return
299
+ pending.delete(registration)
300
+ if (pending.size === 0) this.pendingWorkKeyRegistrations.delete(registration.workKey)
301
+ }
302
+ }
303
+
304
+ function isDescendantOfAny(
305
+ entry: LiveSubagent,
306
+ rootSessionIds: ReadonlySet<string>,
307
+ entriesBySessionId: ReadonlyMap<string, LiveSubagent>,
308
+ ): boolean {
309
+ let parentSessionId = entry.parentSessionId
310
+ const visited = new Set<string>()
311
+ while (parentSessionId !== undefined && !visited.has(parentSessionId)) {
312
+ if (rootSessionIds.has(parentSessionId)) return true
313
+ visited.add(parentSessionId)
314
+ parentSessionId = entriesBySessionId.get(parentSessionId)?.parentSessionId
218
315
  }
316
+ return false
219
317
  }
220
318
 
221
319
  function renderStatusSummary(
@@ -443,6 +443,10 @@ function renderChannelOrigin(
443
443
  'One verdict, one surface. After submitting the review, use',
444
444
  '`skip_response({ reason: "verdict posted as review" })`.',
445
445
  '',
446
+ '**Never post your own coordination state.** Write only what a PR',
447
+ 'participant needs. Do not narrate carriers, review rounds, sessions,',
448
+ 'a verdict not yet being registered, or sticky review state.',
449
+ '',
446
450
  'GitHub renders real Markdown; use it freely.',
447
451
  'The GitHub adapter cannot send file attachments.',
448
452
  'GitHub has no typing indicator.',
@@ -454,7 +458,7 @@ function renderChannelOrigin(
454
458
  '',
455
459
  isCarrier
456
460
  ? '**This session is the review-round carrier.** Perform one whole-PR re-review and post the verdict.'
457
- : "**This session is not the review-round carrier.** Do not spawn a reviewer, review, or publish findings; when the carrier's verdict lands, close out only this thread.",
461
+ : '**This session is not the review-round carrier.** Do not spawn a reviewer, review, or publish findings. While waiting, the correct action is silence via `skip_response`; posting a "waiting for the verdict" or "I\'ll tidy this up later" status comment is a defect. When the verdict lands, close out only this thread in one message.',
458
462
  )
459
463
  }
460
464
 
@@ -157,6 +157,17 @@ export function createChannelReplyTool({
157
157
  }
158
158
  }
159
159
 
160
+ if (keepTurnAlive && params.resolve_review_thread !== undefined) {
161
+ const error =
162
+ '`resolve_review_thread` is a terminal close-out decision and cannot be combined with ' +
163
+ '`more_work_this_turn: true`. Send a status without the decision, then close out the thread in a terminal reply.'
164
+ logger.warn(formatChannelToolFailure('channel_reply', error))
165
+ return {
166
+ content: [{ type: 'text' as const, text: `channel_reply denied: ${error}` }],
167
+ details: { ok: false, error },
168
+ }
169
+ }
170
+
160
171
  // Required-choice guard: a terminal github review-thread text reply must
161
172
  // make an explicit resolve_review_thread choice. The model kept silently
162
173
  // omitting the flag after acknowledging a fix, leaving the thread open;
@@ -252,11 +263,12 @@ export function createChannelReplyTool({
252
263
  }
253
264
  }
254
265
  if (resolve.kind === 'already-resolved') {
255
- router.finishGithubReviewRoundCloseout?.({
266
+ router.finishGithubReviewThreadCloseout?.({
256
267
  sessionId,
257
268
  workspace: origin.workspace,
258
269
  prNumber: parseGithubPrNumber(origin.chat),
259
270
  thread: origin.thread,
271
+ decision: 'resolved',
260
272
  })
261
273
  return {
262
274
  content: [{ type: 'text' as const, text: alreadyResolvedHint(origin.thread) }],
@@ -269,11 +281,12 @@ export function createChannelReplyTool({
269
281
  if (resolve.kind === 'no-match') {
270
282
  resolveMissNotice = resolveMissHint(origin.thread)
271
283
  } else {
272
- router.finishGithubReviewRoundCloseout?.({
284
+ router.finishGithubReviewThreadCloseout?.({
273
285
  sessionId,
274
286
  workspace: origin.workspace,
275
287
  prNumber: parseGithubPrNumber(origin.chat),
276
288
  thread: origin.thread,
289
+ decision: 'resolved',
277
290
  })
278
291
  }
279
292
  }
@@ -295,6 +308,21 @@ export function createChannelReplyTool({
295
308
  ),
296
309
  )
297
310
  }
311
+ if (
312
+ result.ok &&
313
+ params.resolve_review_thread === false &&
314
+ origin.adapter === 'github' &&
315
+ origin.thread !== null &&
316
+ /^pr:\d+$/.test(origin.chat)
317
+ ) {
318
+ router.finishGithubReviewThreadCloseout?.({
319
+ sessionId,
320
+ workspace: origin.workspace,
321
+ prNumber: parseGithubPrNumber(origin.chat),
322
+ thread: origin.thread,
323
+ decision: 'left-open',
324
+ })
325
+ }
298
326
  // `more_work_this_turn` is read by the router's terminal hook (installChannelReplyTerminalHook),
299
327
  // not by this tool — it suppresses the post-reply abort so a multi-step turn
300
328
  // keeps going. Success-only: a denied reply never ran, so there is no turn to keep.
@@ -272,11 +272,12 @@ export function createChannelSendTool({
272
272
  }
273
273
  }
274
274
  if (resolve.kind === 'already-resolved') {
275
- router.finishGithubReviewRoundCloseout?.({
275
+ router.finishGithubReviewThreadCloseout?.({
276
276
  sessionId,
277
277
  workspace: params.workspace,
278
278
  prNumber: parseGithubPrNumber(params.chat),
279
279
  thread: params.thread ?? null,
280
+ decision: 'resolved',
280
281
  })
281
282
  return {
282
283
  content: [{ type: 'text' as const, text: alreadyResolvedHint(params.thread ?? null) }],
@@ -293,11 +294,12 @@ export function createChannelSendTool({
293
294
  resolveMissNotice = resolveMissHint(params.thread ?? null)
294
295
  } else {
295
296
  recordResolvedThreadFromSend(sessionId, params.workspace, params.chat, params.thread ?? null)
296
- router.finishGithubReviewRoundCloseout?.({
297
+ router.finishGithubReviewThreadCloseout?.({
297
298
  sessionId,
298
299
  workspace: params.workspace,
299
300
  prNumber: parseGithubPrNumber(params.chat),
300
301
  thread: params.thread ?? null,
302
+ decision: 'resolved',
301
303
  })
302
304
  }
303
305
  }
@@ -319,6 +321,21 @@ export function createChannelSendTool({
319
321
  ),
320
322
  )
321
323
  }
324
+ if (
325
+ result.ok &&
326
+ params.resolve_review_thread === false &&
327
+ adapter === 'github' &&
328
+ params.thread != null &&
329
+ /^pr:\d+$/.test(params.chat)
330
+ ) {
331
+ router.finishGithubReviewThreadCloseout?.({
332
+ sessionId,
333
+ workspace: params.workspace,
334
+ prNumber: parseGithubPrNumber(params.chat),
335
+ thread: params.thread ?? null,
336
+ decision: 'left-open',
337
+ })
338
+ }
322
339
  const details: { ok: boolean; error?: string; messageId?: string; messageIds?: readonly string[] } = result.ok
323
340
  ? {
324
341
  ok: true,