Skip to content

Commit 263d1ea

Browse files
committed
Fix opencode row tracking: wrong-state replies, a dropped busy signal, and a race
permission.replied/question.replied/question.rejected aliased to stop (done) instead of posttooluse (working), so answering a prompt read as the turn ending rather than resuming. question.asked had no alias at all, so a question never raised the alarm the way a permission ask did. session.status (the one event that could mark ordinary generation as "working") was forwarded but filtered on the wrong field — properties.type instead of properties.status.type per @opencode-ai/sdk's own type — so the busy filter always failed silently and the event never got through. With that fixed, a second bug surfaced: opencode reliably emits one stray session.status busy in the same second as the real session.idle, on every turn (tracked upstream as anomalyco/opencode#35472, still open as of 1.18.23). Unfiltered, that stranded finished rows on "working" forever. Added a 2s cooldown after a session's own idle to absorb it, then found the cooldown itself was racy: two hook events close together run as two independent cc-notify subprocesses with no locking, so the second could read the first's pre-write state and act on stale data. Serialised with a per-session flock (session_lock()) so concurrent invocations can't interleave — verified with concurrent-launch stress tests. PurgeService now also sweeps the .lock files that locking leaves behind, on the same mtime rule as everything else. Verified end to end against real opencode 1.17.8 and 1.18.23 sessions, and smoke-tested Claude, Grok, and Cursor payloads through the same code path to confirm none of this touches their event handling.
1 parent 6df09c4 commit 263d1ea

4 files changed

Lines changed: 190 additions & 87 deletions

File tree

‎Scripts/cc-notify‎

Lines changed: 145 additions & 80 deletions
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,9 @@ Contract with the app: the LAST line of a file is that row's current state.
3131
This script must never block Claude. Every failure path exits 0 silently.
3232
"""
3333

34+
import contextlib
3435
import datetime
36+
import fcntl
3537
import json
3638
import os
3739
import shutil
@@ -87,13 +89,29 @@ def source_of(payload):
8789
# real Cursor session, not read off its docs: three of its events — sessionStart,
8890
# preToolUse and stop — already normalise to our spelling and need nothing here.
8991
ALIASES = {
90-
"beforesubmitprompt": "userpromptsubmit", # Cursor: carries `prompt`, as ours does
91-
# opencode names its lifecycle differently and splits "waiting for you" into
92-
# asked/replied, which maps onto our notification/stop pair exactly.
93-
"session.created": "sessionstart",
94-
"session.idle": "stop",
95-
"permission.asked": "notification",
96-
"permission.replied": "stop",
92+
# Cursor. Its other events — sessionStart, preToolUse, stop — already
93+
# normalise to our spelling and need no entry here at all.
94+
"beforesubmitprompt": "userpromptsubmit", # Cursor -> working (carries `prompt`)
95+
96+
# opencode. It names its lifecycle differently and splits "waiting for you"
97+
# into asked/replied. Replying does not end the turn — it resumes it, same
98+
# as a tool call finishing — so it maps to posttooluse, not stop. Only
99+
# session.idle, opencode's real "I am done" event, maps to stop.
100+
"session.created": "sessionstart", # opencode -> idle (row appears)
101+
"session.idle": "stop", # opencode -> done (real completion)
102+
"permission.asked": "notification", # opencode -> needsInput (red, shows the command)
103+
"permission.replied": "posttooluse", # opencode -> working (resumes, does not finish)
104+
"question.asked": "notification", # opencode -> needsInput (red, shows the question)
105+
"question.replied": "posttooluse", # opencode -> working
106+
"question.rejected": "posttooluse", # opencode -> working
107+
108+
# opencode. The plugin only ever forwards the busy half of session.status —
109+
# see its own comment — so this always means "generation just started".
110+
"session.status": "posttooluse", # opencode -> working
111+
112+
# Claude Code and Grok need no entries: both already speak in the spelling
113+
# (flattened, lowercased) that interpret() reads directly — see source_of()
114+
# and the Grok spelling table in docs/HOOK-PAYLOADS.md.
97115
}
98116

99117

@@ -473,6 +491,29 @@ def handle_session_end(session_id, root):
473491
pass
474492

475493

494+
@contextlib.contextmanager
495+
def session_lock(path):
496+
"""Serialises read-previous-then-append for one session's jsonl.
497+
498+
Hooks fire from independent subprocesses — one `cc-notify` per event — and
499+
two events close enough together (opencode's stray trailing session.status
500+
is exactly this: it lands within the same second as session.idle) start
501+
two of them at once. Without a lock, the second can read `previous` before
502+
the first has appended, so it never sees the state it should have been
503+
filtered against — the busy-suppression check above passed a payload it
504+
should have caught, because the write it needed to see hadn't landed yet.
505+
Confirmed live 2026-08-26: exactly this race let a stray through.
506+
"""
507+
os.makedirs(os.path.dirname(path), exist_ok=True)
508+
lock_path = path + ".lock"
509+
with open(lock_path, "a") as handle:
510+
fcntl.flock(handle, fcntl.LOCK_EX)
511+
try:
512+
yield
513+
finally:
514+
fcntl.flock(handle, fcntl.LOCK_UN)
515+
516+
476517
def main():
477518
raw = sys.stdin.read()
478519
payload = json.loads(raw)
@@ -503,80 +544,104 @@ def main():
503544
return
504545

505546
path = os.path.join(root, "%s.jsonl" % session_id)
506-
previous = last_line(path) or {}
507-
# Cursor sends `cwd` as an empty string and puts the real answer in
508-
# `workspace_roots`. Falling through to os.getcwd() would name every Cursor
509-
# row after ~/.cursor, which is where its hooks run from.
510-
roots = get(payload, "workspace_roots", "workspaceRoots")
511-
root = roots[0] if isinstance(roots, list) and roots else None
512-
cwd = (get(payload, "cwd", "workspaceRoot") or root
513-
or previous.get("cwd") or os.getcwd())
514-
515-
# session_title is the name you gave the session in Claude and is the better
516-
# label when it differs from the folder ("spacyapps" vs "fluffy-carnival").
517-
# It only ships on UserPromptSubmit, so latch it from the previous line.
518-
title = get(payload, "session_title", "sessionTitle")
519-
folder = os.path.basename(cwd.rstrip("/"))
520-
source = source_of(payload)
521-
name = title or previous.get("name") or folder
522-
523-
# Cursor keeps several chats open against one workspace, so the folder names
524-
# them all the same thing. It titles them itself — "Free service inquiry" —
525-
# but that title is app state reached through an internal MCP tool, absent
526-
# from both the hook payload and the transcript on disk.
527-
#
528-
# The opening prompt is what Cursor derives its own title from, and it is
529-
# right there in the payload. Latched, so the row keeps the question it
530-
# started from rather than following the conversation.
531-
# Cursor only. Claude and Grok give one session per terminal, where the
532-
# folder is the useful label and a first prompt would be noise — replacing
533-
# "avaterm" with "hello" was caught by a test rather than by taste.
534-
if source == "cursor":
535-
# "workspace: empty" rather than "empty" while nothing better is known:
536-
# a row can be created by a tool event long before any prompt is seen,
537-
# and a bare folder name there reads as the name of one chat when it is
538-
# really the container several of them share.
539-
placeholder = "workspace: %s" % folder
540-
if name in (folder, placeholder):
541-
name = opening_line(payload) or placeholder
542-
543-
interpreted = interpret(payload)
544-
if interpreted is None:
545-
return
546-
state, message, needs_action = interpreted
547-
548-
# The question and the alarm arrive on different events, six seconds apart:
549-
# PreToolUse carries the words, Notification turns the row red with a
550-
# generic "Claude needs your permission". Last line wins, so without this
551-
# the words are overwritten by the moment they matter most. Latched the same
552-
# way tty and host_app are.
553-
asked = asked_question(payload) or previous.get("asked") or ""
554-
if state == "needsInput" and asked:
555-
message = asked
556-
557-
tree = ProcessTree()
558-
tty = resolve_tty(tree) or previous.get("tty")
559-
host_app = resolve_host_app(tree) or previous.get("host_app")
560-
host_id = resolve_host_id() or previous.get("host_id")
561547

562-
emit(path, {
563-
"schema": SCHEMA,
564-
"source": source,
565-
"session_id": session_id,
566-
"name": name,
567-
"cwd": cwd,
568-
"tty": tty,
569-
"host_app": host_app,
570-
"host_id": host_id,
571-
"event": get(payload, "hook_event_name", "hookEventName") or "",
572-
"state": state,
573-
"message": message,
574-
"asked": asked,
575-
"needs_action": needs_action,
576-
"notification_type": get(payload, "notification_type", "notificationType") or "",
577-
"transcript_path": get(payload, "transcript_path", "transcriptPath") or "",
578-
"ts": now,
579-
})
548+
# Everything from here on reads the last line, decides from it, and
549+
# appends a new one — a read-modify-write that two `cc-notify` processes
550+
# for the same session can otherwise interleave. See session_lock().
551+
with session_lock(path):
552+
previous = last_line(path) or {}
553+
554+
# opencode reliably emits one trailing session.status busy in the same
555+
# second as session.idle, on every turn — measured 2026-08-26, twice,
556+
# both times at identical timestamps. It is not a rare race to wait
557+
# out; left alone it strands a finished row on "working" forever,
558+
# since nothing else ever follows it. A real next turn needs a human
559+
# to type first, so 2s of cooldown after that session's own idle
560+
# silently absorbs the stray without meaningfully delaying a genuine
561+
# new prompt.
562+
raw_event = get(payload, "hook_event_name", "hookEventName") or ""
563+
if (raw_event == "session.status"
564+
and previous.get("event") == "session.idle"
565+
and now - previous.get("ts", 0) <= 2):
566+
return
567+
568+
# Cursor sends `cwd` as an empty string and puts the real answer in
569+
# `workspace_roots`. Falling through to os.getcwd() would name every
570+
# Cursor row after ~/.cursor, which is where its hooks run from.
571+
roots = get(payload, "workspace_roots", "workspaceRoots")
572+
root = roots[0] if isinstance(roots, list) and roots else None
573+
cwd = (get(payload, "cwd", "workspaceRoot") or root
574+
or previous.get("cwd") or os.getcwd())
575+
576+
# session_title is the name you gave the session in Claude and is the
577+
# better label when it differs from the folder ("spacyapps" vs
578+
# "fluffy-carnival"). It only ships on UserPromptSubmit, so latch it
579+
# from the previous line.
580+
title = get(payload, "session_title", "sessionTitle")
581+
folder = os.path.basename(cwd.rstrip("/"))
582+
source = source_of(payload)
583+
name = title or previous.get("name") or folder
584+
585+
# Cursor keeps several chats open against one workspace, so the folder
586+
# names them all the same thing. It titles them itself — "Free
587+
# service inquiry" — but that title is app state reached through an
588+
# internal MCP tool, absent from both the hook payload and the
589+
# transcript on disk.
590+
#
591+
# The opening prompt is what Cursor derives its own title from, and
592+
# it is right there in the payload. Latched, so the row keeps the
593+
# question it started from rather than following the conversation.
594+
# Cursor only. Claude and Grok give one session per terminal, where
595+
# the folder is the useful label and a first prompt would be noise —
596+
# replacing "avaterm" with "hello" was caught by a test rather than
597+
# by taste.
598+
if source == "cursor":
599+
# "workspace: empty" rather than "empty" while nothing better is
600+
# known: a row can be created by a tool event long before any
601+
# prompt is seen, and a bare folder name there reads as the name
602+
# of one chat when it is really the container several of them
603+
# share.
604+
placeholder = "workspace: %s" % folder
605+
if name in (folder, placeholder):
606+
name = opening_line(payload) or placeholder
607+
608+
interpreted = interpret(payload)
609+
if interpreted is None:
610+
return
611+
state, message, needs_action = interpreted
612+
613+
# The question and the alarm arrive on different events, six seconds
614+
# apart: PreToolUse carries the words, Notification turns the row red
615+
# with a generic "Claude needs your permission". Last line wins, so
616+
# without this the words are overwritten by the moment they matter
617+
# most. Latched the same way tty and host_app are.
618+
asked = asked_question(payload) or previous.get("asked") or ""
619+
if state == "needsInput" and asked:
620+
message = asked
621+
622+
tree = ProcessTree()
623+
tty = resolve_tty(tree) or previous.get("tty")
624+
host_app = resolve_host_app(tree) or previous.get("host_app")
625+
host_id = resolve_host_id() or previous.get("host_id")
626+
627+
emit(path, {
628+
"schema": SCHEMA,
629+
"source": source,
630+
"session_id": session_id,
631+
"name": name,
632+
"cwd": cwd,
633+
"tty": tty,
634+
"host_app": host_app,
635+
"host_id": host_id,
636+
"event": get(payload, "hook_event_name", "hookEventName") or "",
637+
"state": state,
638+
"message": message,
639+
"asked": asked,
640+
"needs_action": needs_action,
641+
"notification_type": get(payload, "notification_type", "notificationType") or "",
642+
"transcript_path": get(payload, "transcript_path", "transcriptPath") or "",
643+
"ts": now,
644+
})
580645

581646

582647
if __name__ == "__main__":

‎Scripts/opencode-plugin.ts‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,13 @@ const FORWARD = new Set([
3535
"question.asked",
3636
"question.replied",
3737
"question.rejected",
38+
// session.created and session.idle only bracket a turn — nothing in between
39+
// ever said "working", so a row parked on its opening "idle" for the whole
40+
// reply and never moved. session.status carries {"type":"busy"|"idle"} and
41+
// fires the moment generation actually starts; only the busy half is
42+
// forwarded below, since the idle half is a between-tool-calls blip, not
43+
// a real state change, and session.idle already reports true completion.
44+
"session.status",
3845
])
3946

4047
export const GroundControl = async ({ $, directory, worktree }: any) => {
@@ -63,6 +70,13 @@ export const GroundControl = async ({ $, directory, worktree }: any) => {
6370
const properties = event.properties ?? {}
6471
const sessionID: string | undefined = properties.sessionID
6572
if (!sessionID) return
73+
// Nested one level deeper than it looks: properties.status.type, not
74+
// properties.type. Confirmed against @opencode-ai/sdk's own
75+
// EventSessionStatus type — the first version of this check read
76+
// properties.type, which is always undefined, so every session.status
77+
// event was silently dropped and "working" never fired outside a
78+
// permission reply.
79+
if (event.type === "session.status" && properties.status?.type !== "busy") return
6680

6781
// opencode splits "waiting for you" into asked and replied, which is
6882
// exactly our alarm going up and coming down.

‎Sources/GroundControl/Monitoring/PurgeService.swift‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -51,7 +51,12 @@ final class PurgeService {
5151
)) ?? []
5252

5353
var removed = 0
54-
for file in files where file.pathExtension == "jsonl" {
54+
// "lock" alongside "jsonl": cc-notify's session_lock() leaves one
55+
// <session>.jsonl.lock per session to serialise concurrent writers
56+
// (see Scripts/cc-notify) and never deletes it itself — deleting a
57+
// lock file out from under a live flock is its own hazard, so it
58+
// ages out on the same mtime rule as everything else instead.
59+
for file in files where ["jsonl", "lock"].contains(file.pathExtension) {
5560
let modified = (try? file.resourceValues(forKeys: [.contentModificationDateKey]))?
5661
.contentModificationDate
5762
guard let modified, now.timeIntervalSince(modified) > window else { continue }

‎docs/HOOK-PAYLOADS.md‎

Lines changed: 25 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -101,10 +101,28 @@ touched. A single turn emits well over a hundred events; all but four are noise
101101
| `session.created` | `sessionstart` | `sessionID`, `info.directory`, `info.title` |
102102
| `session.idle` | `stop` | `sessionID` |
103103
| `permission.asked` | `notification` | `sessionID`, `permission`, `metadata.command`, `metadata.description` |
104-
| `permission.replied` | `stop` | `sessionID`, `reply` (`accept` / `reject`) |
105-
106-
`session.status` also arrives with `{"type": "busy"}` and `{"type": "idle"}`, and
107-
is not used: `session.created` and `session.idle` already bracket the work.
104+
| `permission.replied` | `posttooluse` | `sessionID`, `reply` (`accept` / `reject`) |
105+
| `session.status` (`status.type === "busy"` only) | `posttooluse` | `sessionID`, `status: {type}` |
106+
107+
**`session.created`/`session.idle` do not bracket the work — corrected
108+
2026-08-26.** The original note here said they did and that `session.status`
109+
was therefore unneeded; live testing showed a session sits on whatever the
110+
last event said for the entire reply, with nothing marking the busy middle.
111+
`session.status` is now forwarded, filtered to the busy half only (the idle
112+
half is a between-tool-calls blip, not real completion — `session.idle` still
113+
owns that).
114+
115+
**The status flag is nested one level deeper than it looks.** The payload is
116+
`properties: { sessionID, status: { type: "idle" | "retry" | "busy" } }` —
117+
per `@opencode-ai/sdk`'s own `EventSessionStatus` type — not `properties.type`
118+
directly. The first version of this integration checked `properties.type`,
119+
which is always `undefined`, so the busy filter always failed and no
120+
`session.status` event ever reached `cc-notify`. Confirmed live 2026-08-26.
121+
122+
Also corrected: `permission.replied` does not mean the turn ended — it means
123+
opencode is about to resume, same as a tool call finishing. It used to alias
124+
to `stop` (done); it now aliases to `posttooluse` (working), same as
125+
`session.status` busy. Only `session.idle` means real completion.
108126

109127
### The one that matters
110128

@@ -143,7 +161,7 @@ So the row says *"Echo hello to terminal"* rather than "needs your permission".
143161
| one entry in the `"plugin"` array | `~/.config/opencode/opencode.json` | tells opencode to load it |
144162
| `cc-notify` | `~/.groundcontrol/bin/` | the same emitter every agent uses |
145163

146-
**What it listens for** — seven events; everything else is ignored, and a turn
164+
**What it listens for** — eight events; everything else is ignored, and a turn
147165
emits well over a hundred.
148166

149167
| Event | The row | What it says |
@@ -152,7 +170,8 @@ emits well over a hundred.
152170
| `session.idle` | done | — |
153171
| `permission.asked` | **red** | the command, e.g. "List files with details…" |
154172
| `question.asked` | **red** | the question |
155-
| `permission.replied` · `question.replied` · `question.rejected` | clears | — |
173+
| `permission.replied` · `question.replied` · `question.rejected` | working | — |
174+
| `session.status`, busy only | working | — |
156175

157176
**The chain, end to end**
158177

0 commit comments

Comments
 (0)