cc-continuity 0.3.0__tar.gz → 0.3.1__tar.gz

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 (115) hide show
  1. {cc_continuity-0.3.0 → cc_continuity-0.3.1}/PKG-INFO +1 -1
  2. {cc_continuity-0.3.0 → cc_continuity-0.3.1}/README.md +16 -20
  3. {cc_continuity-0.3.0 → cc_continuity-0.3.1}/cc_continuity/__init__.py +1 -1
  4. cc_continuity-0.3.1/cc_continuity/blink.py +552 -0
  5. cc_continuity-0.3.1/cc_continuity/blink_watch.py +304 -0
  6. {cc_continuity-0.3.0 → cc_continuity-0.3.1}/cc_continuity/cli.py +69 -5
  7. {cc_continuity-0.3.0 → cc_continuity-0.3.1}/cc_continuity/config.py +31 -0
  8. {cc_continuity-0.3.0 → cc_continuity-0.3.1}/cc_continuity/hooks/session_start.py +32 -2
  9. {cc_continuity-0.3.0 → cc_continuity-0.3.1}/cc_continuity/hooks/stop.py +33 -2
  10. cc_continuity-0.3.1/cc_continuity/ledger.py +119 -0
  11. {cc_continuity-0.3.0 → cc_continuity-0.3.1}/cc_continuity/progress_pane.py +290 -17
  12. {cc_continuity-0.3.0 → cc_continuity-0.3.1}/cc_continuity/statusline.py +44 -30
  13. {cc_continuity-0.3.0 → cc_continuity-0.3.1}/cc_continuity.egg-info/PKG-INFO +1 -1
  14. {cc_continuity-0.3.0 → cc_continuity-0.3.1}/cc_continuity.egg-info/SOURCES.txt +2 -0
  15. {cc_continuity-0.3.0 → cc_continuity-0.3.1}/pyproject.toml +1 -1
  16. cc_continuity-0.3.1/tests/test_blink.py +698 -0
  17. cc_continuity-0.3.1/tests/test_blink_watch.py +587 -0
  18. {cc_continuity-0.3.0 → cc_continuity-0.3.1}/tests/test_checkpoint.py +54 -6
  19. {cc_continuity-0.3.0 → cc_continuity-0.3.1}/tests/test_cli.py +31 -2
  20. {cc_continuity-0.3.0 → cc_continuity-0.3.1}/tests/test_config.py +16 -0
  21. {cc_continuity-0.3.0 → cc_continuity-0.3.1}/tests/test_hooks_session_start.py +49 -0
  22. {cc_continuity-0.3.0 → cc_continuity-0.3.1}/tests/test_hooks_stop.py +141 -1
  23. cc_continuity-0.3.1/tests/test_ledger.py +156 -0
  24. {cc_continuity-0.3.0 → cc_continuity-0.3.1}/tests/test_progress_pane.py +480 -10
  25. {cc_continuity-0.3.0 → cc_continuity-0.3.1}/tests/test_statusline.py +152 -0
  26. {cc_continuity-0.3.0 → cc_continuity-0.3.1}/tests/test_watchdog_integration.py +39 -15
  27. cc_continuity-0.3.0/cc_continuity/blink.py +0 -278
  28. cc_continuity-0.3.0/cc_continuity/ledger.py +0 -67
  29. cc_continuity-0.3.0/tests/test_blink.py +0 -349
  30. cc_continuity-0.3.0/tests/test_ledger.py +0 -83
  31. {cc_continuity-0.3.0 → cc_continuity-0.3.1}/LICENSE +0 -0
  32. {cc_continuity-0.3.0 → cc_continuity-0.3.1}/cc_continuity/__main__.py +0 -0
  33. {cc_continuity-0.3.0 → cc_continuity-0.3.1}/cc_continuity/atomic.py +0 -0
  34. {cc_continuity-0.3.0 → cc_continuity-0.3.1}/cc_continuity/bootstrap.py +0 -0
  35. {cc_continuity-0.3.0 → cc_continuity-0.3.1}/cc_continuity/checkpoint.py +0 -0
  36. {cc_continuity-0.3.0 → cc_continuity-0.3.1}/cc_continuity/daemon_supervisor.py +0 -0
  37. {cc_continuity-0.3.0 → cc_continuity-0.3.1}/cc_continuity/doctor.py +0 -0
  38. {cc_continuity-0.3.0 → cc_continuity-0.3.1}/cc_continuity/gitsnap.py +0 -0
  39. {cc_continuity-0.3.0 → cc_continuity-0.3.1}/cc_continuity/hooks/__init__.py +0 -0
  40. {cc_continuity-0.3.0 → cc_continuity-0.3.1}/cc_continuity/hooks/common.py +0 -0
  41. {cc_continuity-0.3.0 → cc_continuity-0.3.1}/cc_continuity/hooks/pre_compact.py +0 -0
  42. {cc_continuity-0.3.0 → cc_continuity-0.3.1}/cc_continuity/hooks/pre_tool_use.py +0 -0
  43. {cc_continuity-0.3.0 → cc_continuity-0.3.1}/cc_continuity/hooks/session_end.py +0 -0
  44. {cc_continuity-0.3.0 → cc_continuity-0.3.1}/cc_continuity/hooks/task.py +0 -0
  45. {cc_continuity-0.3.0 → cc_continuity-0.3.1}/cc_continuity/hooks/tool_use.py +0 -0
  46. {cc_continuity-0.3.0 → cc_continuity-0.3.1}/cc_continuity/hooks/user_prompt.py +0 -0
  47. {cc_continuity-0.3.0 → cc_continuity-0.3.1}/cc_continuity/hosting.py +0 -0
  48. {cc_continuity-0.3.0 → cc_continuity-0.3.1}/cc_continuity/install.py +0 -0
  49. {cc_continuity-0.3.0 → cc_continuity-0.3.1}/cc_continuity/launch.py +0 -0
  50. {cc_continuity-0.3.0 → cc_continuity-0.3.1}/cc_continuity/lock.py +0 -0
  51. {cc_continuity-0.3.0 → cc_continuity-0.3.1}/cc_continuity/managed.py +0 -0
  52. {cc_continuity-0.3.0 → cc_continuity-0.3.1}/cc_continuity/naming.py +0 -0
  53. {cc_continuity-0.3.0 → cc_continuity-0.3.1}/cc_continuity/notify.py +0 -0
  54. {cc_continuity-0.3.0 → cc_continuity-0.3.1}/cc_continuity/paths.py +0 -0
  55. {cc_continuity-0.3.0 → cc_continuity-0.3.1}/cc_continuity/power_plug.py +0 -0
  56. {cc_continuity-0.3.0 → cc_continuity-0.3.1}/cc_continuity/project.py +0 -0
  57. {cc_continuity-0.3.0 → cc_continuity-0.3.1}/cc_continuity/redact.py +0 -0
  58. {cc_continuity-0.3.0 → cc_continuity-0.3.1}/cc_continuity/rotator.py +0 -0
  59. {cc_continuity-0.3.0 → cc_continuity-0.3.1}/cc_continuity/settings_merge.py +0 -0
  60. {cc_continuity-0.3.0 → cc_continuity-0.3.1}/cc_continuity/skills.py +0 -0
  61. {cc_continuity-0.3.0 → cc_continuity-0.3.1}/cc_continuity/state.py +0 -0
  62. {cc_continuity-0.3.0 → cc_continuity-0.3.1}/cc_continuity/thresholds.py +0 -0
  63. {cc_continuity-0.3.0 → cc_continuity-0.3.1}/cc_continuity/transcript.py +0 -0
  64. {cc_continuity-0.3.0 → cc_continuity-0.3.1}/cc_continuity/validate.py +0 -0
  65. {cc_continuity-0.3.0 → cc_continuity-0.3.1}/cc_continuity/watchdog.py +0 -0
  66. {cc_continuity-0.3.0 → cc_continuity-0.3.1}/cc_continuity/watchdog_digest.py +0 -0
  67. {cc_continuity-0.3.0 → cc_continuity-0.3.1}/cc_continuity/watchdogd.py +0 -0
  68. {cc_continuity-0.3.0 → cc_continuity-0.3.1}/cc_continuity.egg-info/dependency_links.txt +0 -0
  69. {cc_continuity-0.3.0 → cc_continuity-0.3.1}/cc_continuity.egg-info/entry_points.txt +0 -0
  70. {cc_continuity-0.3.0 → cc_continuity-0.3.1}/cc_continuity.egg-info/top_level.txt +0 -0
  71. {cc_continuity-0.3.0 → cc_continuity-0.3.1}/setup.cfg +0 -0
  72. {cc_continuity-0.3.0 → cc_continuity-0.3.1}/tests/test_atomic.py +0 -0
  73. {cc_continuity-0.3.0 → cc_continuity-0.3.1}/tests/test_bootstrap.py +0 -0
  74. {cc_continuity-0.3.0 → cc_continuity-0.3.1}/tests/test_daemon_supervisor.py +0 -0
  75. {cc_continuity-0.3.0 → cc_continuity-0.3.1}/tests/test_doctor.py +0 -0
  76. {cc_continuity-0.3.0 → cc_continuity-0.3.1}/tests/test_gitsnap.py +0 -0
  77. {cc_continuity-0.3.0 → cc_continuity-0.3.1}/tests/test_hooks_common.py +0 -0
  78. {cc_continuity-0.3.0 → cc_continuity-0.3.1}/tests/test_hooks_pre_compact.py +0 -0
  79. {cc_continuity-0.3.0 → cc_continuity-0.3.1}/tests/test_hooks_pre_tool_use.py +0 -0
  80. {cc_continuity-0.3.0 → cc_continuity-0.3.1}/tests/test_hooks_session_end.py +0 -0
  81. {cc_continuity-0.3.0 → cc_continuity-0.3.1}/tests/test_hooks_task.py +0 -0
  82. {cc_continuity-0.3.0 → cc_continuity-0.3.1}/tests/test_hooks_tool_use.py +0 -0
  83. {cc_continuity-0.3.0 → cc_continuity-0.3.1}/tests/test_hooks_user_prompt.py +0 -0
  84. {cc_continuity-0.3.0 → cc_continuity-0.3.1}/tests/test_hosting.py +0 -0
  85. {cc_continuity-0.3.0 → cc_continuity-0.3.1}/tests/test_hygiene.py +0 -0
  86. {cc_continuity-0.3.0 → cc_continuity-0.3.1}/tests/test_install.py +0 -0
  87. {cc_continuity-0.3.0 → cc_continuity-0.3.1}/tests/test_integration_phase5.py +0 -0
  88. {cc_continuity-0.3.0 → cc_continuity-0.3.1}/tests/test_integration_phase6.py +0 -0
  89. {cc_continuity-0.3.0 → cc_continuity-0.3.1}/tests/test_integration_phase7.py +0 -0
  90. {cc_continuity-0.3.0 → cc_continuity-0.3.1}/tests/test_launch.py +0 -0
  91. {cc_continuity-0.3.0 → cc_continuity-0.3.1}/tests/test_lock.py +0 -0
  92. {cc_continuity-0.3.0 → cc_continuity-0.3.1}/tests/test_managed.py +0 -0
  93. {cc_continuity-0.3.0 → cc_continuity-0.3.1}/tests/test_naming.py +0 -0
  94. {cc_continuity-0.3.0 → cc_continuity-0.3.1}/tests/test_notify.py +0 -0
  95. {cc_continuity-0.3.0 → cc_continuity-0.3.1}/tests/test_notify_integration.py +0 -0
  96. {cc_continuity-0.3.0 → cc_continuity-0.3.1}/tests/test_paths.py +0 -0
  97. {cc_continuity-0.3.0 → cc_continuity-0.3.1}/tests/test_power_plug.py +0 -0
  98. {cc_continuity-0.3.0 → cc_continuity-0.3.1}/tests/test_project.py +0 -0
  99. {cc_continuity-0.3.0 → cc_continuity-0.3.1}/tests/test_redact.py +0 -0
  100. {cc_continuity-0.3.0 → cc_continuity-0.3.1}/tests/test_rotator.py +0 -0
  101. {cc_continuity-0.3.0 → cc_continuity-0.3.1}/tests/test_settings_merge.py +0 -0
  102. {cc_continuity-0.3.0 → cc_continuity-0.3.1}/tests/test_skills.py +0 -0
  103. {cc_continuity-0.3.0 → cc_continuity-0.3.1}/tests/test_state.py +0 -0
  104. {cc_continuity-0.3.0 → cc_continuity-0.3.1}/tests/test_status.py +0 -0
  105. {cc_continuity-0.3.0 → cc_continuity-0.3.1}/tests/test_thresholds.py +0 -0
  106. {cc_continuity-0.3.0 → cc_continuity-0.3.1}/tests/test_tmux_host.py +0 -0
  107. {cc_continuity-0.3.0 → cc_continuity-0.3.1}/tests/test_transcript.py +0 -0
  108. {cc_continuity-0.3.0 → cc_continuity-0.3.1}/tests/test_transcript_finalize.py +0 -0
  109. {cc_continuity-0.3.0 → cc_continuity-0.3.1}/tests/test_uninstall.py +0 -0
  110. {cc_continuity-0.3.0 → cc_continuity-0.3.1}/tests/test_validate.py +0 -0
  111. {cc_continuity-0.3.0 → cc_continuity-0.3.1}/tests/test_watchdog.py +0 -0
  112. {cc_continuity-0.3.0 → cc_continuity-0.3.1}/tests/test_watchdog_digest.py +0 -0
  113. {cc_continuity-0.3.0 → cc_continuity-0.3.1}/tests/test_watchdogd.py +0 -0
  114. {cc_continuity-0.3.0 → cc_continuity-0.3.1}/tests/test_wsl_doctor.py +0 -0
  115. {cc_continuity-0.3.0 → cc_continuity-0.3.1}/tests/test_wsl_install.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: cc-continuity
3
- Version: 0.3.0
3
+ Version: 0.3.1
4
4
  Summary: Zero-touch session rotation for Claude Code (local large-context model)
5
5
  Requires-Python: >=3.11
6
6
  License-File: LICENSE
@@ -26,26 +26,22 @@ The five most recent updates, newest first. Each line links to its
26
26
  commit, so you can see what changed lately without digging through the
27
27
  log:
28
28
 
29
- - **2026-11-06** — Handoffs export the session transcript as a readable
30
- HTML page (search, theme toggle) plus raw JSONL, and the successor
31
- session echoes a clickable `Transcript:` link in its navigator panel
32
- ([issue #8](https://github.com/pqant/claude-continuity/commit/a5a8b36)).
33
- - **2026-11-05** — Notification pushes got richer: project, host, model
34
- and context ratio plus the session's objective, next step and what the
35
- agent last said, with secrets scrubbed on the way out
36
- ([issue #7](https://github.com/pqant/claude-continuity/commit/393d083)).
37
- - **2026-11-05** — The first output of a rotated session is now a
38
- Done/Next navigator panel rendered from the handoff, so you always see
39
- where the work picked up
40
- ([issue #6](https://github.com/pqant/claude-continuity/commit/67f189b)).
41
- - **2026-11-03** — Rotation resume guarantee: the rotator retries until
42
- the successor genuinely resumes (ack-driven keystrokes) instead of
43
- giving up after two blind attempts
44
- ([commit](https://github.com/pqant/claude-continuity/commit/4592b12)).
45
- - **2026-11-03** — Session index stability: a restart after a stalled
46
- rotation reuses the orphaned successor and its number instead of
47
- minting a new session index
48
- ([commit](https://github.com/pqant/claude-continuity/commit/27f4d1a)).
29
+ - **2026-11-08**: An interactive architecture diagram of the whole system
30
+ (modules, dependencies and data flows) now ships in `docs/diagrams` as a
31
+ self-contained HTML page with guided views and export
32
+ ([commit](https://github.com/pqant/claude-continuity/commit/5ae9011)).
33
+ - **2026-11-08**: The waiting tab blink now starts after a 5 s settle
34
+ window instead of 15 s, so a finished turn reaches your tab faster
35
+ ([commit](https://github.com/pqant/claude-continuity/commit/a9a295d)).
36
+ - **2026-11-08**: Progress frames are padded by rendered cells, so wide
37
+ glyphs never wrap into the next line
38
+ ([commit](https://github.com/pqant/claude-continuity/commit/581fe93)).
39
+ - **2026-11-08**: The animator blink key carries the unconsumed reply ts,
40
+ so a reply arriving mid-blink is still delivered
41
+ ([commit](https://github.com/pqant/claude-continuity/commit/54494b4)).
42
+ - **2026-11-08**: The reply flag is held through the settle window instead
43
+ of being cleared early
44
+ ([commit](https://github.com/pqant/claude-continuity/commit/581ff6f)).
49
45
 
50
46
  ## How it works
51
47
 
@@ -4,4 +4,4 @@ Spec: docs/PRD.md (v1.0). Platform facts verified in docs/VERIFICATION.md.
4
4
  Standard library only at runtime; pytest is dev-only.
5
5
  """
6
6
 
7
- __version__ = "0.3.0"
7
+ __version__ = "0.3.1"
@@ -0,0 +1,552 @@
1
+ """Waiting-blink primitives (issue #11).
2
+
3
+ Thin, self-contained layer: the OSC 6 tab-color escape sequences (spike
4
+ proven on iTerm2 3.7.6 and Terminal.app), the gate markers the blink
5
+ reacts to, and the tmux/tty helpers the ``Blinker`` state machine uses.
6
+
7
+ Import direction rule: ``progress_pane`` and ``statusline`` import from
8
+ here; this module only leans on leaf modules (``config``, ``paths``) and
9
+ never on ``progress_pane`` or ``statusline``, so a blink failure can
10
+ never drag the animator down.
11
+ """
12
+
13
+ import json
14
+ import os
15
+ import re
16
+ import subprocess
17
+ import time
18
+
19
+ from . import config, paths
20
+
21
+ OSC6_RESET = b"\x1b]6;1;bg;*;default\x07"
22
+
23
+ RED_FILL = (235, 20, 20)
24
+ BLACK_FILL = (0, 0, 0)
25
+
26
+ # Single source of truth for the gate markers. statusline.py composes its
27
+ # suffixes from these constants (composing its own leading spaces) so the
28
+ # writer and the gate can never drift apart silently.
29
+ MARKER_BLOCKED = "⛔ BLOCKED"
30
+ MARKER_ASK = "⚠ ASK"
31
+ MARKER_REPLY = "🕐 REPLY"
32
+ GATE_MARKERS = (MARKER_BLOCKED, MARKER_ASK, MARKER_REPLY)
33
+
34
+ # "User input needed" detection from raw pane text (live bug 2026-11-07:
35
+ # AskUserQuestion sat unanswered for 46 min without a blink). Permission
36
+ # prompts match the exact wording only, so ordinary chat containing
37
+ # "allow"/"yes" can never strand the marker; selection prompts (permission
38
+ # AND AskUserQuestion) are pinned by the footer phrase PAIR on ONE line
39
+ # (the dot never crosses newlines), which agent output cannot reproduce in
40
+ # the input-box region.
41
+ ASK_RE_PERMISSION = re.compile(r"Do you want to allow", re.IGNORECASE)
42
+ ASK_RE_SELECTION = re.compile(r"Enter to select.*Esc to cancel")
43
+
44
+ #: CC's input box bottom border is a line of these (verified live, 014).
45
+ INPUT_BORDER = "─"
46
+
47
+
48
+ def ask_visible(text: str | None) -> bool:
49
+ """True while the pane shows a permission or selection prompt."""
50
+ if not text:
51
+ return False
52
+ return bool(ASK_RE_PERMISSION.search(text)
53
+ or ASK_RE_SELECTION.search(text))
54
+
55
+
56
+ def input_box_region_from_lines(lines: list[str]) -> list[str] | None:
57
+ """The input-box/dialog region: last ``❯``-prefixed line through the
58
+ next line consisting solely of the border glyph (None when no ``❯``).
59
+
60
+ Scrollback is never part of the region, so a quoted footer above the
61
+ box cannot strand ASK; while a selection prompt is open the option
62
+ cursor is the ``❯`` line and the footer sits inside the region.
63
+ """
64
+ start = None
65
+ for i, line in enumerate(lines):
66
+ if line.lstrip().startswith("❯"):
67
+ start = i
68
+ if start is None:
69
+ return None
70
+ region = []
71
+ for line in lines[start:]:
72
+ region.append(line)
73
+ stripped = line.strip()
74
+ if stripped and set(stripped) == {INPUT_BORDER}:
75
+ break
76
+ return region
77
+
78
+
79
+ def osc6_fill(rgb: tuple[int, int, int]) -> bytes:
80
+ """One write carrying the three OSC 6 background-channel fills.
81
+
82
+ ``ESC ] 6 ; 1 ; bg ; <chan> ; brightness ; N BEL`` for red, green and
83
+ blue in order (byte order pinned by tests; spike-proven format).
84
+ """
85
+ red, green, blue = rgb
86
+ out = bytearray()
87
+ for chan, val in (("red", red), ("green", green), ("blue", blue)):
88
+ out += (b"\x1b]6;1;bg;" + chan.encode("ascii")
89
+ + b";brightness;" + str(int(val)).encode("ascii") + b"\x07")
90
+ return bytes(out)
91
+
92
+
93
+ def blink_gate(text: str | None) -> bool:
94
+ """True when the per-window progress text carries a listed gate marker."""
95
+ if not text:
96
+ return False
97
+ return any(marker in text for marker in GATE_MARKERS)
98
+
99
+
100
+ def _tmux(runner, bin_: str, argv_tail: list, timeout: float = 2.0):
101
+ """Run one tmux command via ``runner``; stripped stdout or None on failure."""
102
+ try:
103
+ proc = runner([bin_, *argv_tail], capture_output=True, timeout=timeout)
104
+ except Exception:
105
+ return None
106
+ if proc.returncode != 0:
107
+ return None
108
+ return proc.stdout.decode("utf-8", "replace").strip()
109
+
110
+
111
+ def list_client_ttys(runner, bin_: str, target: str) -> list[str]:
112
+ """ttys of the clients attached to ``target`` ([] when none/unreachable).
113
+
114
+ tmux prints the literal ``not a tty`` for clients without a tty; those
115
+ lines (and blanks) are dropped. One tty per line, never whitespace
116
+ split inside a path.
117
+ """
118
+ out = _tmux(runner, bin_, ["list-clients", "-t", target,
119
+ "-F", "#{client_tty}"])
120
+ if out is None:
121
+ return []
122
+ return [line.strip() for line in out.splitlines()
123
+ if line.strip() and line.strip() != "not a tty"]
124
+
125
+
126
+ def get_window_name(runner, bin_: str, target: str) -> str | None:
127
+ """Current window name for ``target``, None when unreadable."""
128
+ return _tmux(runner, bin_, ["display-message", "-p", "-t", target,
129
+ "#{window_name}"])
130
+
131
+
132
+ def rename_window(runner, bin_: str, target: str, name: str) -> bool:
133
+ """Rename the window at ``target``; False on any tmux failure."""
134
+ return _tmux(runner, bin_, ["rename-window", "-t", target, name]) is not None
135
+
136
+
137
+ def capture_pane(runner, bin_: str, target: str | None = None) -> str | None:
138
+ """Visible pane text via ``capture-pane -p``; None on any failure.
139
+
140
+ No target captures the pane this process lives in (``$TMUX_PANE``
141
+ default); a target captures a sibling (the animator self-poll and
142
+ the session-resident poller read the CC pane this way). Feed the
143
+ result to ``ask_visible`` only through ``input_box_region_from_lines``
144
+ so scrollback can never false-positive.
145
+ """
146
+ argv = ["capture-pane", "-p"]
147
+ if target is not None:
148
+ argv += ["-t", target]
149
+ return _tmux(runner, bin_, argv)
150
+
151
+
152
+ def window_id_of_pane(runner, bin_: str, pane: str) -> str | None:
153
+ """The tmux window id (``@N``) owning ``pane``, or None."""
154
+ out = _tmux(runner, bin_, ["display-message", "-p", "-t", pane,
155
+ "#{window_id}"])
156
+ return out if out and out.startswith("@") else None
157
+
158
+
159
+ def server_token(env=os.environ.get) -> str:
160
+ """The ``$TMUX`` server token used for per-server artifact names.
161
+
162
+ Duplicated from ``progress_pane._tmux_server_token`` (three lines)
163
+ because the import rule keeps this module leaf-only; a drift between
164
+ the two would split a reply flag from its animator the way the
165
+ frozen-pane bug once split progress data across servers.
166
+ """
167
+ tmux = env("TMUX", "") or ""
168
+ parts = tmux.split(",")
169
+ if len(parts) >= 2 and parts[1].isdigit():
170
+ return f"s{parts[1]}"
171
+ return ""
172
+
173
+
174
+ def _reply_flag_path(window_id, env=os.environ.get):
175
+ token = server_token(env)
176
+ if not token or not window_id:
177
+ return None
178
+ return paths.runtime_dir() / f"reply-flag-{token}{window_id}.json"
179
+
180
+
181
+ def write_reply_flag(session_dir, *, settle=5.0, runner=subprocess.run,
182
+ bin_: str = "tmux", env=os.environ.get,
183
+ now=time.time):
184
+ """Arm the animator-side reply marker for THIS window (Stop hook side).
185
+
186
+ The idle status line never re-renders (measured live 2026-11-08), so
187
+ the settle marker can never reach the progress-data file on its own.
188
+ The hook drops this tiny flag; the animator then consults the LEDGER
189
+ through it (single source of truth, settle honored there). Silent on
190
+ every failure: the Stop hook must never block on the blink layer.
191
+ """
192
+ try:
193
+ pane = env("TMUX_PANE")
194
+ if not pane:
195
+ return None
196
+ win = window_id_of_pane(runner, bin_, pane)
197
+ if not win:
198
+ return None
199
+ p = _reply_flag_path(win, env)
200
+ if p is None:
201
+ return None
202
+ data = {"session_dir": str(session_dir), "ts": float(now()),
203
+ "settle": float(settle)}
204
+ p.parent.mkdir(parents=True, exist_ok=True)
205
+ tmp = p.with_suffix(p.suffix + ".tmp")
206
+ tmp.write_text(json.dumps(data), encoding="utf-8")
207
+ tmp.replace(p)
208
+ return data
209
+ except Exception:
210
+ return None
211
+
212
+
213
+ def read_reply_flag(window_id, *, env=os.environ.get):
214
+ """The armed reply flag for ``window_id`` (dict), or None."""
215
+ try:
216
+ p = _reply_flag_path(window_id, env)
217
+ if p is None:
218
+ return None
219
+ return json.loads(p.read_text(encoding="utf-8"))
220
+ except Exception:
221
+ return None
222
+
223
+
224
+ def clear_reply_flag(window_id, *, env=os.environ.get) -> None:
225
+ """Drop the reply flag (the ledger consumed the reply, or it vanished)."""
226
+ try:
227
+ p = _reply_flag_path(window_id, env)
228
+ if p is not None:
229
+ p.unlink(missing_ok=True)
230
+ except Exception:
231
+ pass
232
+
233
+
234
+ def write_tty(path: str, data: bytes, *, _open=open) -> bool:
235
+ """Write raw bytes to a client tty; False (never raise) on OSError.
236
+
237
+ tmux never sees these bytes: the OSC sequences bypass the pane and go
238
+ straight to the terminal emulator on the client's own tty.
239
+ """
240
+ try:
241
+ fh = _open(path, "wb")
242
+ except OSError:
243
+ return False
244
+ try:
245
+ fh.write(data)
246
+ return True
247
+ except OSError:
248
+ return False
249
+ finally:
250
+ try:
251
+ fh.close()
252
+ except OSError:
253
+ pass
254
+
255
+
256
+ def _debug_line(msg: str) -> None:
257
+ """Append one diagnostic line to the blink log (never raises).
258
+
259
+ The package has no stdlib logging module; the rotator/watchdogd
260
+ file-line pattern is its convention, and the pane stdout is occupied
261
+ by animation frames. One file keeps a non-blinking tab diagnosable.
262
+ """
263
+ try:
264
+ log_path = paths.logs_dir() / "blink.log"
265
+ log_path.parent.mkdir(parents=True, exist_ok=True)
266
+ with open(log_path, "a", encoding="utf-8") as fh:
267
+ fh.write(f"{time.strftime('%Y-%m-%dT%H:%M:%S')} {msg}\n")
268
+ except Exception:
269
+ pass
270
+
271
+
272
+ class Blinker:
273
+ """Waiting-blink state machine driven by the animator's frame tick.
274
+
275
+ ``on_text(text, now)`` arrives every animator frame with the current
276
+ progress text and clock; ``on_exit()`` runs when the animator
277
+ returns. The clock rides in on the call so tests fake it per tick.
278
+ Every tmux/tty path swallows failures: the blink is decoration and
279
+ must never break the progress animation.
280
+ """
281
+
282
+ def __init__(self, window_id: str, cfg: dict, *, store,
283
+ runner=subprocess.run, bin_: str = "tmux", tty_open=open,
284
+ log=None):
285
+ self.window_id = window_id
286
+ self._store = store
287
+ self._runner = runner
288
+ self._bin_ = bin_
289
+ self._tty_open = tty_open
290
+ self._log = log if log is not None else _debug_line
291
+ self.enabled = config.blink_enabled(cfg)
292
+ self._interval = config.blink_interval(cfg)
293
+ self._fill = osc6_fill(
294
+ RED_FILL if config.blink_no_color(cfg) else BLACK_FILL)
295
+ self._blinking = False
296
+ self._phase_own = True # True: own color + original name showing
297
+ self._last_toggle = 0.0
298
+ self._original = None
299
+ self._ttys: list[str] = []
300
+ self._restored_logged = False
301
+ # the sweep is deliberately NOT gated on enabled: a blink stranded
302
+ # by a crash must heal even if blink was turned off since. With an
303
+ # empty store it is a zero-call no-op, so "disabled restores
304
+ # today's behavior exactly" still holds.
305
+ self._startup_sweep()
306
+
307
+ # -- internals ------------------------------------------------------
308
+
309
+ def _startup_sweep(self) -> None:
310
+ """Self-heal a blink stranded by a crashed animator (once per start)."""
311
+ try:
312
+ stored = self._store("blink_name")
313
+ if not stored:
314
+ return
315
+ current = get_window_name(self._runner, self._bin_, self.window_id)
316
+ if current and current.startswith("WAIT"):
317
+ restored = rename_window(self._runner, self._bin_,
318
+ self.window_id, stored)
319
+ for tty in list_client_ttys(self._runner, self._bin_,
320
+ self.window_id):
321
+ write_tty(tty, OSC6_RESET, _open=self._tty_open)
322
+ if restored:
323
+ # keep the stored name on failure: the next animator
324
+ # start sweeps again
325
+ self._store("blink_name", None)
326
+ self._log(f"blink sweep window={self.window_id} "
327
+ f"restored stranded '{current}'")
328
+ except Exception:
329
+ pass
330
+
331
+ def _start(self, now: float) -> None:
332
+ name = get_window_name(self._runner, self._bin_, self.window_id)
333
+ if name is None:
334
+ self._log(f"blink skip window={self.window_id} "
335
+ f"reason=window name unreadable")
336
+ return
337
+ self._original = name
338
+ self._store("blink_name", name)
339
+ # Resolved per blink START (never cached across blinks): clients
340
+ # attach and detach between waits.
341
+ self._ttys = list_client_ttys(self._runner, self._bin_,
342
+ self.window_id)
343
+ self._blinking = True
344
+ self._phase_own = True
345
+ self._last_toggle = now
346
+ self._restored_logged = False
347
+ if self._ttys:
348
+ self._log(f"blink start window={self.window_id} "
349
+ f"ttys={len(self._ttys)}")
350
+ else:
351
+ self._log(f"blink skip window={self.window_id} "
352
+ f"reason=no attached clients")
353
+
354
+ def _wait_name(self, count: int) -> str:
355
+ return "WAIT" if count <= 1 else f"WAIT[{count}]"
356
+
357
+ def _apply(self, count: int) -> None:
358
+ if self._phase_own:
359
+ rename_window(self._runner, self._bin_, self.window_id,
360
+ self._original)
361
+ for tty in self._ttys:
362
+ write_tty(tty, OSC6_RESET, _open=self._tty_open)
363
+ else:
364
+ rename_window(self._runner, self._bin_, self.window_id,
365
+ self._wait_name(count))
366
+ for tty in self._ttys:
367
+ write_tty(tty, self._fill, _open=self._tty_open)
368
+
369
+ def _restore(self) -> None:
370
+ if self._original is not None:
371
+ restored = rename_window(self._runner, self._bin_,
372
+ self.window_id, self._original)
373
+ for tty in self._ttys:
374
+ write_tty(tty, OSC6_RESET, _open=self._tty_open)
375
+ if restored:
376
+ # Ownership released: a window rename the user makes
377
+ # afterwards must survive animator exit. A FAILED rename
378
+ # keeps both the name and the stored value: the store is
379
+ # the only handle the startup sweep needs to heal the
380
+ # stranded WAIT later.
381
+ self._store("blink_name", None)
382
+ self._original = None
383
+ if not self._restored_logged:
384
+ self._log(f"blink restore window={self.window_id}")
385
+ self._restored_logged = True
386
+ self._blinking = False
387
+
388
+ # -- animator surface -------------------------------------------------
389
+
390
+ def on_text(self, text: str | None, now: float,
391
+ pane_text: str | None = None) -> None:
392
+ """One animator tick: gate check, phase flip on the interval.
393
+
394
+ ``pane_text`` is the caller's optional raw pane capture (the
395
+ sibling pane in the animator, the CC pane in the watcher): a live
396
+ selection prompt counts as a gate source even when the progress
397
+ data file carries no marker: the status line is not invoked while
398
+ CC waits on a question, so the file would stay stale (live bug
399
+ 2026-11-07).
400
+ """
401
+ if not self.enabled:
402
+ return
403
+ try:
404
+ count = sum((text or "").count(m) for m in GATE_MARKERS)
405
+ if pane_text is not None and ask_visible(pane_text):
406
+ count += 1
407
+ gated = count > 0
408
+ if gated and not self._blinking:
409
+ self._start(now)
410
+ return
411
+ if not self._blinking:
412
+ return
413
+ if not gated:
414
+ self._restore()
415
+ return
416
+ if now - self._last_toggle >= self._interval:
417
+ self._last_toggle = now
418
+ self._phase_own = not self._phase_own
419
+ self._apply(count)
420
+ except Exception:
421
+ pass
422
+
423
+ def on_exit(self) -> None:
424
+ """Animator is leaving: restore name and tab color (idempotent)."""
425
+ if not self.enabled:
426
+ return
427
+ try:
428
+ if self._blinking or self._original is not None:
429
+ # covers the mid-blink exit AND the retry of a falling-edge
430
+ # rename that tmux refused; _restore releases ownership on
431
+ # success, so repeat calls are no-ops
432
+ self._restore()
433
+ except Exception:
434
+ pass
435
+
436
+
437
+ class FocusWatcher:
438
+ """Focus-dwell suppression shared by the poller and the animator.
439
+
440
+ User directive 2026-11-07: any blink falls silent once the user has
441
+ looked at the tab for ``dwell_ticks`` consecutive ticks; answering is
442
+ not required. The caller ticks once per ~1 s with a composite key
443
+ describing the waiting situation (blocked reason, reply ts, region
444
+ text); a changed key (new needs-human reason, new dialog, new reply)
445
+ reads as unread again and the blink re-arms. The read state persists
446
+ in the caller's store (``read`` key, window-namespaced by the store)
447
+ so a runner restart does not re-blink a situation the user already
448
+ saw.
449
+
450
+ ``frontmost``/``clients`` default to None, which DISABLES dwell: the
451
+ test suite and any non-focusable context must never exec the real
452
+ osascript/tmux probes; a reply blink then self-fades (poller rule)
453
+ and blocking states keep blinking (builder call).
454
+ """
455
+
456
+ def __init__(self, store, *, frontmost=None, clients=None,
457
+ dwell_ticks: int = 3, label: str | None = None,
458
+ log=_debug_line):
459
+ self._store = store
460
+ self._frontmost = frontmost
461
+ self._clients = clients
462
+ self._dwell_ticks = dwell_ticks
463
+ self._dwell = 0
464
+ self._last_key = None
465
+ # Decision diagnostics (2026-11-07 live incident: a blink stayed
466
+ # lit while the user watched and nothing in blink.log said why).
467
+ # Edge-triggered only: one line per STATE change, never per poll.
468
+ self._label = f" {label}" if label else ""
469
+ self._log = log
470
+ self._outcome = None
471
+
472
+ def _note(self, event: str, key: str, extra: str = "") -> None:
473
+ if self._log is None:
474
+ return
475
+ try:
476
+ self._log(f"focus {event}{self._label} key={key[:60]!r}{extra}")
477
+ except Exception:
478
+ pass
479
+
480
+ def tick(self, t: float, key: str, on_read=None) -> bool:
481
+ """One poll tick; True means the blink must be suppressed now.
482
+
483
+ ``t`` rides in with the caller's clock (one ``_now()`` per tick
484
+ stays the poller's single-clock rule); ``on_read(key)`` runs
485
+ exactly once when the dwell is reached (never on a stored hit),
486
+ letting the caller consume the ledger entry behind the blink.
487
+ """
488
+ if not key:
489
+ self._dwell = 0
490
+ self._last_key = None
491
+ return False
492
+ try:
493
+ stored = self._store("read")
494
+ except Exception:
495
+ stored = None
496
+ if stored == key:
497
+ if self._outcome != "read":
498
+ self._note("suppress-stored", key)
499
+ self._outcome = "read"
500
+ self._dwell = 0
501
+ return True
502
+ if self._frontmost is None or self._clients is None:
503
+ self._dwell = 0
504
+ return False
505
+ front = None
506
+ focused = False
507
+ outcome = "error"
508
+ try:
509
+ front = self._frontmost()
510
+ if front is None:
511
+ outcome = "none"
512
+ else:
513
+ focused = front in self._clients()
514
+ outcome = "focus" if focused else "idle"
515
+ except Exception:
516
+ outcome = "error"
517
+ if outcome != self._outcome:
518
+ self._note(f"probe-{outcome}", key,
519
+ f" front={front!r}" if front is not None else "")
520
+ self._outcome = outcome
521
+ if not focused:
522
+ self._dwell = 0
523
+ self._last_key = key
524
+ return False
525
+ if key != self._last_key:
526
+ # USER DIRECTIVE 2026-11-08 (screen recordings 06:19/06:33):
527
+ # a fresh situation that lands while the user ALREADY looks at
528
+ # the tab is read on the spot (dwell armed so this same tick
529
+ # suppresses) - the old grace flashed the foreground tab for
530
+ # 2-3 s before the dwell caught up. The dwell still measures
531
+ # continuous focus on an already-known key (the short-glance
532
+ # guard survives), and a watcher that never observed any key
533
+ # yet (respawn mid-blink: last_key None) still blinks first.
534
+ self._note("rearm", key)
535
+ self._dwell = (self._dwell_ticks - 1
536
+ if self._last_key is not None else 0)
537
+ self._last_key = key
538
+ self._dwell += 1
539
+ if self._dwell < self._dwell_ticks:
540
+ return False
541
+ self._dwell = 0
542
+ self._note("suppress", key, f" front={front!r}")
543
+ try:
544
+ self._store("read", key)
545
+ except Exception:
546
+ pass
547
+ if on_read is not None:
548
+ try:
549
+ on_read(key)
550
+ except Exception:
551
+ pass
552
+ return True