@@ -31,7 +31,9 @@ Contract with the app: the LAST line of a file is that row's current state.
3131This script must never block Claude. Every failure path exits 0 silently.
3232"""
3333
34+ import contextlib
3435import datetime
36+ import fcntl
3537import json
3638import os
3739import 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.
8991ALIASES = {
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+
476517def 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
582647if __name__ == "__main__" :
0 commit comments