cc-continuity 0.3.1__tar.gz → 0.3.3__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 (111) hide show
  1. {cc_continuity-0.3.1 → cc_continuity-0.3.3}/PKG-INFO +1 -1
  2. {cc_continuity-0.3.1 → cc_continuity-0.3.3}/README.md +17 -10
  3. {cc_continuity-0.3.1 → cc_continuity-0.3.3}/cc_continuity/__init__.py +1 -1
  4. {cc_continuity-0.3.1 → cc_continuity-0.3.3}/cc_continuity/checkpoint.py +6 -1
  5. {cc_continuity-0.3.1 → cc_continuity-0.3.3}/cc_continuity/hooks/pre_tool_use.py +30 -9
  6. {cc_continuity-0.3.1 → cc_continuity-0.3.3}/cc_continuity/thresholds.py +24 -0
  7. {cc_continuity-0.3.1 → cc_continuity-0.3.3}/cc_continuity/transcript.py +152 -14
  8. {cc_continuity-0.3.1 → cc_continuity-0.3.3}/cc_continuity.egg-info/PKG-INFO +1 -1
  9. {cc_continuity-0.3.1 → cc_continuity-0.3.3}/pyproject.toml +1 -1
  10. {cc_continuity-0.3.1 → cc_continuity-0.3.3}/tests/test_hooks_pre_tool_use.py +72 -7
  11. {cc_continuity-0.3.1 → cc_continuity-0.3.3}/tests/test_integration_phase5.py +11 -5
  12. {cc_continuity-0.3.1 → cc_continuity-0.3.3}/tests/test_transcript.py +120 -0
  13. {cc_continuity-0.3.1 → cc_continuity-0.3.3}/tests/test_transcript_finalize.py +17 -0
  14. {cc_continuity-0.3.1 → cc_continuity-0.3.3}/LICENSE +0 -0
  15. {cc_continuity-0.3.1 → cc_continuity-0.3.3}/cc_continuity/__main__.py +0 -0
  16. {cc_continuity-0.3.1 → cc_continuity-0.3.3}/cc_continuity/atomic.py +0 -0
  17. {cc_continuity-0.3.1 → cc_continuity-0.3.3}/cc_continuity/blink.py +0 -0
  18. {cc_continuity-0.3.1 → cc_continuity-0.3.3}/cc_continuity/blink_watch.py +0 -0
  19. {cc_continuity-0.3.1 → cc_continuity-0.3.3}/cc_continuity/bootstrap.py +0 -0
  20. {cc_continuity-0.3.1 → cc_continuity-0.3.3}/cc_continuity/cli.py +0 -0
  21. {cc_continuity-0.3.1 → cc_continuity-0.3.3}/cc_continuity/config.py +0 -0
  22. {cc_continuity-0.3.1 → cc_continuity-0.3.3}/cc_continuity/daemon_supervisor.py +0 -0
  23. {cc_continuity-0.3.1 → cc_continuity-0.3.3}/cc_continuity/doctor.py +0 -0
  24. {cc_continuity-0.3.1 → cc_continuity-0.3.3}/cc_continuity/gitsnap.py +0 -0
  25. {cc_continuity-0.3.1 → cc_continuity-0.3.3}/cc_continuity/hooks/__init__.py +0 -0
  26. {cc_continuity-0.3.1 → cc_continuity-0.3.3}/cc_continuity/hooks/common.py +0 -0
  27. {cc_continuity-0.3.1 → cc_continuity-0.3.3}/cc_continuity/hooks/pre_compact.py +0 -0
  28. {cc_continuity-0.3.1 → cc_continuity-0.3.3}/cc_continuity/hooks/session_end.py +0 -0
  29. {cc_continuity-0.3.1 → cc_continuity-0.3.3}/cc_continuity/hooks/session_start.py +0 -0
  30. {cc_continuity-0.3.1 → cc_continuity-0.3.3}/cc_continuity/hooks/stop.py +0 -0
  31. {cc_continuity-0.3.1 → cc_continuity-0.3.3}/cc_continuity/hooks/task.py +0 -0
  32. {cc_continuity-0.3.1 → cc_continuity-0.3.3}/cc_continuity/hooks/tool_use.py +0 -0
  33. {cc_continuity-0.3.1 → cc_continuity-0.3.3}/cc_continuity/hooks/user_prompt.py +0 -0
  34. {cc_continuity-0.3.1 → cc_continuity-0.3.3}/cc_continuity/hosting.py +0 -0
  35. {cc_continuity-0.3.1 → cc_continuity-0.3.3}/cc_continuity/install.py +0 -0
  36. {cc_continuity-0.3.1 → cc_continuity-0.3.3}/cc_continuity/launch.py +0 -0
  37. {cc_continuity-0.3.1 → cc_continuity-0.3.3}/cc_continuity/ledger.py +0 -0
  38. {cc_continuity-0.3.1 → cc_continuity-0.3.3}/cc_continuity/lock.py +0 -0
  39. {cc_continuity-0.3.1 → cc_continuity-0.3.3}/cc_continuity/managed.py +0 -0
  40. {cc_continuity-0.3.1 → cc_continuity-0.3.3}/cc_continuity/naming.py +0 -0
  41. {cc_continuity-0.3.1 → cc_continuity-0.3.3}/cc_continuity/notify.py +0 -0
  42. {cc_continuity-0.3.1 → cc_continuity-0.3.3}/cc_continuity/paths.py +0 -0
  43. {cc_continuity-0.3.1 → cc_continuity-0.3.3}/cc_continuity/power_plug.py +0 -0
  44. {cc_continuity-0.3.1 → cc_continuity-0.3.3}/cc_continuity/progress_pane.py +0 -0
  45. {cc_continuity-0.3.1 → cc_continuity-0.3.3}/cc_continuity/project.py +0 -0
  46. {cc_continuity-0.3.1 → cc_continuity-0.3.3}/cc_continuity/redact.py +0 -0
  47. {cc_continuity-0.3.1 → cc_continuity-0.3.3}/cc_continuity/rotator.py +0 -0
  48. {cc_continuity-0.3.1 → cc_continuity-0.3.3}/cc_continuity/settings_merge.py +0 -0
  49. {cc_continuity-0.3.1 → cc_continuity-0.3.3}/cc_continuity/skills.py +0 -0
  50. {cc_continuity-0.3.1 → cc_continuity-0.3.3}/cc_continuity/state.py +0 -0
  51. {cc_continuity-0.3.1 → cc_continuity-0.3.3}/cc_continuity/statusline.py +0 -0
  52. {cc_continuity-0.3.1 → cc_continuity-0.3.3}/cc_continuity/validate.py +0 -0
  53. {cc_continuity-0.3.1 → cc_continuity-0.3.3}/cc_continuity/watchdog.py +0 -0
  54. {cc_continuity-0.3.1 → cc_continuity-0.3.3}/cc_continuity/watchdog_digest.py +0 -0
  55. {cc_continuity-0.3.1 → cc_continuity-0.3.3}/cc_continuity/watchdogd.py +0 -0
  56. {cc_continuity-0.3.1 → cc_continuity-0.3.3}/cc_continuity.egg-info/SOURCES.txt +0 -0
  57. {cc_continuity-0.3.1 → cc_continuity-0.3.3}/cc_continuity.egg-info/dependency_links.txt +0 -0
  58. {cc_continuity-0.3.1 → cc_continuity-0.3.3}/cc_continuity.egg-info/entry_points.txt +0 -0
  59. {cc_continuity-0.3.1 → cc_continuity-0.3.3}/cc_continuity.egg-info/top_level.txt +0 -0
  60. {cc_continuity-0.3.1 → cc_continuity-0.3.3}/setup.cfg +0 -0
  61. {cc_continuity-0.3.1 → cc_continuity-0.3.3}/tests/test_atomic.py +0 -0
  62. {cc_continuity-0.3.1 → cc_continuity-0.3.3}/tests/test_blink.py +0 -0
  63. {cc_continuity-0.3.1 → cc_continuity-0.3.3}/tests/test_blink_watch.py +0 -0
  64. {cc_continuity-0.3.1 → cc_continuity-0.3.3}/tests/test_bootstrap.py +0 -0
  65. {cc_continuity-0.3.1 → cc_continuity-0.3.3}/tests/test_checkpoint.py +0 -0
  66. {cc_continuity-0.3.1 → cc_continuity-0.3.3}/tests/test_cli.py +0 -0
  67. {cc_continuity-0.3.1 → cc_continuity-0.3.3}/tests/test_config.py +0 -0
  68. {cc_continuity-0.3.1 → cc_continuity-0.3.3}/tests/test_daemon_supervisor.py +0 -0
  69. {cc_continuity-0.3.1 → cc_continuity-0.3.3}/tests/test_doctor.py +0 -0
  70. {cc_continuity-0.3.1 → cc_continuity-0.3.3}/tests/test_gitsnap.py +0 -0
  71. {cc_continuity-0.3.1 → cc_continuity-0.3.3}/tests/test_hooks_common.py +0 -0
  72. {cc_continuity-0.3.1 → cc_continuity-0.3.3}/tests/test_hooks_pre_compact.py +0 -0
  73. {cc_continuity-0.3.1 → cc_continuity-0.3.3}/tests/test_hooks_session_end.py +0 -0
  74. {cc_continuity-0.3.1 → cc_continuity-0.3.3}/tests/test_hooks_session_start.py +0 -0
  75. {cc_continuity-0.3.1 → cc_continuity-0.3.3}/tests/test_hooks_stop.py +0 -0
  76. {cc_continuity-0.3.1 → cc_continuity-0.3.3}/tests/test_hooks_task.py +0 -0
  77. {cc_continuity-0.3.1 → cc_continuity-0.3.3}/tests/test_hooks_tool_use.py +0 -0
  78. {cc_continuity-0.3.1 → cc_continuity-0.3.3}/tests/test_hooks_user_prompt.py +0 -0
  79. {cc_continuity-0.3.1 → cc_continuity-0.3.3}/tests/test_hosting.py +0 -0
  80. {cc_continuity-0.3.1 → cc_continuity-0.3.3}/tests/test_hygiene.py +0 -0
  81. {cc_continuity-0.3.1 → cc_continuity-0.3.3}/tests/test_install.py +0 -0
  82. {cc_continuity-0.3.1 → cc_continuity-0.3.3}/tests/test_integration_phase6.py +0 -0
  83. {cc_continuity-0.3.1 → cc_continuity-0.3.3}/tests/test_integration_phase7.py +0 -0
  84. {cc_continuity-0.3.1 → cc_continuity-0.3.3}/tests/test_launch.py +0 -0
  85. {cc_continuity-0.3.1 → cc_continuity-0.3.3}/tests/test_ledger.py +0 -0
  86. {cc_continuity-0.3.1 → cc_continuity-0.3.3}/tests/test_lock.py +0 -0
  87. {cc_continuity-0.3.1 → cc_continuity-0.3.3}/tests/test_managed.py +0 -0
  88. {cc_continuity-0.3.1 → cc_continuity-0.3.3}/tests/test_naming.py +0 -0
  89. {cc_continuity-0.3.1 → cc_continuity-0.3.3}/tests/test_notify.py +0 -0
  90. {cc_continuity-0.3.1 → cc_continuity-0.3.3}/tests/test_notify_integration.py +0 -0
  91. {cc_continuity-0.3.1 → cc_continuity-0.3.3}/tests/test_paths.py +0 -0
  92. {cc_continuity-0.3.1 → cc_continuity-0.3.3}/tests/test_power_plug.py +0 -0
  93. {cc_continuity-0.3.1 → cc_continuity-0.3.3}/tests/test_progress_pane.py +0 -0
  94. {cc_continuity-0.3.1 → cc_continuity-0.3.3}/tests/test_project.py +0 -0
  95. {cc_continuity-0.3.1 → cc_continuity-0.3.3}/tests/test_redact.py +0 -0
  96. {cc_continuity-0.3.1 → cc_continuity-0.3.3}/tests/test_rotator.py +0 -0
  97. {cc_continuity-0.3.1 → cc_continuity-0.3.3}/tests/test_settings_merge.py +0 -0
  98. {cc_continuity-0.3.1 → cc_continuity-0.3.3}/tests/test_skills.py +0 -0
  99. {cc_continuity-0.3.1 → cc_continuity-0.3.3}/tests/test_state.py +0 -0
  100. {cc_continuity-0.3.1 → cc_continuity-0.3.3}/tests/test_status.py +0 -0
  101. {cc_continuity-0.3.1 → cc_continuity-0.3.3}/tests/test_statusline.py +0 -0
  102. {cc_continuity-0.3.1 → cc_continuity-0.3.3}/tests/test_thresholds.py +0 -0
  103. {cc_continuity-0.3.1 → cc_continuity-0.3.3}/tests/test_tmux_host.py +0 -0
  104. {cc_continuity-0.3.1 → cc_continuity-0.3.3}/tests/test_uninstall.py +0 -0
  105. {cc_continuity-0.3.1 → cc_continuity-0.3.3}/tests/test_validate.py +0 -0
  106. {cc_continuity-0.3.1 → cc_continuity-0.3.3}/tests/test_watchdog.py +0 -0
  107. {cc_continuity-0.3.1 → cc_continuity-0.3.3}/tests/test_watchdog_digest.py +0 -0
  108. {cc_continuity-0.3.1 → cc_continuity-0.3.3}/tests/test_watchdog_integration.py +0 -0
  109. {cc_continuity-0.3.1 → cc_continuity-0.3.3}/tests/test_watchdogd.py +0 -0
  110. {cc_continuity-0.3.1 → cc_continuity-0.3.3}/tests/test_wsl_doctor.py +0 -0
  111. {cc_continuity-0.3.1 → cc_continuity-0.3.3}/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.1
3
+ Version: 0.3.3
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,6 +26,23 @@ 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-09**: Routine rotations no longer print a red error: at the
30
+ hard context limit the in-flight tool call now passes and the handoff
31
+ instruction arrives as a neutral notice, so the pane stays clean
32
+ ([commit](https://github.com/pqant/claude-continuity/commit/d8e015c)).
33
+ - **2026-11-09**: When the gate does deny a tool (only after the model
34
+ was told to write the handoff and kept working), the full guidance
35
+ shows as an informational message instead of a red error line
36
+ ([commit](https://github.com/pqant/claude-continuity/commit/f8a6cc9)).
37
+ - **2026-11-09**: Exported transcript pages now carry a session
38
+ switcher: a header dropdown lists the newest exports of the project
39
+ (the top ten plus the current page) and loads them over plain
40
+ `file://`
41
+ ([commit](https://github.com/pqant/claude-continuity/commit/e22f4ac)).
42
+ - **2026-11-09**: The transcript header was rebuilt on a single grid:
43
+ the Sessions label sits under Session Time, the search box keeps a
44
+ fixed width, and labels read bold and high-contrast
45
+ ([commit](https://github.com/pqant/claude-continuity/commit/18af742)).
29
46
  - **2026-11-08**: An interactive architecture diagram of the whole system
30
47
  (modules, dependencies and data flows) now ships in `docs/diagrams` as a
31
48
  self-contained HTML page with guided views and export
@@ -33,16 +50,6 @@ log:
33
50
  - **2026-11-08**: The waiting tab blink now starts after a 5 s settle
34
51
  window instead of 15 s, so a finished turn reaches your tab faster
35
52
  ([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)).
45
-
46
53
  ## How it works
47
54
 
48
55
  The whole flow in one picture: the automatic session loop, the optional
@@ -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.1"
7
+ __version__ = "0.3.3"
@@ -590,7 +590,8 @@ def finalize(key: str, nnn: int, *, cfg: dict, root: Path,
590
590
  metric, root, (metric or {}).get("session_id") or None)
591
591
  if tpath is not None:
592
592
  stem = transcript.export_session(
593
- tpath, tmp, _transcript_meta(snapshot, metric))
593
+ tpath, tmp, _transcript_meta(snapshot, metric),
594
+ final_dir=pdir / "checkpoint")
594
595
  except Exception:
595
596
  stem = None
596
597
  transcript.debug_log("export aborted: finalize guard")
@@ -633,6 +634,10 @@ def finalize(key: str, nnn: int, *, cfg: dict, root: Path,
633
634
  shutil.rmtree(final)
634
635
  os.rename(tmp, final)
635
636
  atomic.fsync_dir(pdir)
637
+ # Issue #16: the switcher manifest lives at the project root;
638
+ # refresh it once the pair has landed (never raises, P9-D7).
639
+ if stem:
640
+ transcript.update_sessions_manifest(final)
636
641
  step(8)
637
642
  state._transition_unlocked(key, nnn, "CHECKPOINT_VERIFIED",
638
643
  degraded=degraded)
@@ -1,8 +1,10 @@
1
1
  """PreToolUse hook (PRD §9) — the hard ceiling (Phase 5).
2
2
 
3
3
  Ratio gate: fresh ratio >= hard_ratio with a pre-handoff state ->
4
- ``advance`` to HANDOFF_REQUESTED first, then the deny decision. State gate
5
- (no metric needed): HANDOFF_REQUESTED/HANDOFF_FAILED deny with C.3;
4
+ ``advance`` to HANDOFF_REQUESTED, let the in-flight call through and inject
5
+ the C.2 handoff instruction as neutral additionalContext (issue #25: CC
6
+ renders denials as red Errors; routine rotation is not an error). State
7
+ gate (no metric needed): HANDOFF_REQUESTED/HANDOFF_FAILED deny with C.3;
6
8
  CHECKPOINT_WRITING/VERIFIED/ROTATING (handoff accepted) deny with C.9, so
7
9
  the model cannot keep working and make the handoff stale. AWAITING_MANUAL_
8
10
  CLEAR / ROTATED allow (checkpoint final, user in control). The allowlist
@@ -38,21 +40,40 @@ def handle(ctx: HookContext) -> dict | None:
38
40
  if s in PRE_HANDOFF:
39
41
  ratio = thresholds.read_ratio(ctx)
40
42
  if ratio is not None and ratio >= cfg["hard_ratio"]:
41
- rec, _ = thresholds.advance(key, nnn, "HANDOFF_REQUESTED",
42
- ratio=ratio, cfg=cfg)
43
- s = rec["state"]
43
+ thresholds.advance(key, nnn, "HANDOFF_REQUESTED", ratio=ratio,
44
+ cfg=cfg)
45
+ # Guidance-first (issue #25): this call was queued before the
46
+ # model could learn rotation started, and CC renders any denial
47
+ # as a red "Error:" line - routine rotation is not an error.
48
+ # Let the in-flight call through and inject the C.2 instruction
49
+ # as neutral context instead; denial is reserved for calls the
50
+ # model makes AFTER seeing the guidance.
51
+ return {"systemMessage": thresholds.c2_note(ratio),
52
+ "hookSpecificOutput": {
53
+ "hookEventName": "PreToolUse",
54
+ "additionalContext": thresholds.c2_text(
55
+ ratio, draft_path,
56
+ blocked=ledger.blocked_reason(ctx.session_dir)),
57
+ }}
44
58
  if s in DENY_C3:
45
- reason = thresholds.c3_text(ratio, cfg["hard_ratio"], draft_path,
46
- blocked=ledger.blocked_reason(ctx.session_dir))
59
+ blocked = ledger.blocked_reason(ctx.session_dir)
60
+ guidance = thresholds.c3_text(ratio, cfg["hard_ratio"], draft_path,
61
+ blocked=blocked)
62
+ reason = thresholds.c3_brief(ratio, cfg["hard_ratio"], draft_path,
63
+ blocked=blocked)
47
64
  elif s in DENY_C9:
48
- reason = thresholds.c9_text()
65
+ guidance = thresholds.c9_text()
66
+ reason = thresholds.c9_brief()
49
67
  else:
50
68
  return None
51
69
  tool = ctx.payload.get("tool_name")
52
70
  tool_input = _dict(ctx.payload.get("tool_input"))
53
71
  if thresholds.is_allowed_tool(tool, tool_input, draft_path):
54
72
  return None
55
- return {"hookSpecificOutput": {
73
+ # The full gate guidance rides in systemMessage so the UI shows an
74
+ # informational note, not a red error; the model still acts on the
75
+ # brief deny reason.
76
+ return {"systemMessage": guidance, "hookSpecificOutput": {
56
77
  "hookEventName": "PreToolUse",
57
78
  "permissionDecision": "deny",
58
79
  "permissionDecisionReason": reason,
@@ -103,6 +103,14 @@ def c2_text(ratio: float, draft_path: str,
103
103
  "turn." + _blocked_suffix(blocked))
104
104
 
105
105
 
106
+ def c2_note(ratio: float) -> str:
107
+ """User-facing neutral note for a hard-ratio crossing (issue #25):
108
+ informational only - routine rotation is never rendered as an error."""
109
+ return (f"cc-continuity: context at {pct_of(ratio)}% - rotation handoff "
110
+ "requested. The model finishes the current step, writes the "
111
+ "handoff, and ends its turn.")
112
+
113
+
106
114
  def c3_text(ratio: float | None, hard_ratio: float, draft_path: str,
107
115
  blocked: str | None = None) -> str:
108
116
  shown = ratio if ratio is not None else hard_ratio
@@ -114,6 +122,17 @@ def c3_text(ratio: float | None, hard_ratio: float, draft_path: str,
114
122
  + _blocked_suffix(blocked))
115
123
 
116
124
 
125
+ def c3_brief(ratio: float | None, hard_ratio: float, draft_path: str,
126
+ blocked: str | None = None) -> str:
127
+ """Model-facing short reason for the C.3 deny (full guidance travels
128
+ in the hook's systemMessage, not the red deny reason)."""
129
+ shown = ratio if ratio is not None else hard_ratio
130
+ return (f"CONTINUITY: context at {pct_of(shown)}% (hard limit). Write the "
131
+ f"handoff to {draft_path} with the required level-2 headings "
132
+ f"(format '## Heading'), then end your turn."
133
+ + _blocked_suffix(blocked))
134
+
135
+
117
136
  def c6_text(problems: list, draft_path: str) -> str:
118
137
  return ("CONTINUITY: handoff draft invalid: " + "; ".join(problems)
119
138
  + f". Fix {draft_path} and end your turn.")
@@ -126,6 +145,11 @@ def c9_text() -> str:
126
145
  "this session. End your turn now.")
127
146
 
128
147
 
148
+ def c9_brief() -> str:
149
+ """Model-facing short reason for the C.9 deny (full text in systemMessage)."""
150
+ return "CONTINUITY: handoff accepted. End your turn now."
151
+
152
+
129
153
  # -------------------------------------------------------------- state walk
130
154
 
131
155
  #: Path to ROTATION_PENDING, by current state (each step is
@@ -153,13 +153,16 @@ _CSS = """
153
153
  *{box-sizing:border-box}
154
154
  body{margin:0;background:var(--bg);color:var(--fg);font:15.5px/1.6 -apple-system,system-ui,"Segoe UI",Roboto,sans-serif}
155
155
  header{position:sticky;top:0;background:var(--hdr);border-bottom:1px solid var(--line);padding:10px 22px;z-index:9;box-shadow:0 1px 4px rgba(0,0,0,.06)}
156
- .meta{font-size:13px;color:var(--muted);display:grid;grid-template-columns:max-content 1fr max-content 1fr;gap:2px 14px}
157
- .meta .v{color:var(--fg);font-weight:600;padding-left:2px}
158
- .controls{display:flex;gap:12px;align-items:center;margin-top:8px}
159
- input[type=search]{flex:1;max-width:520px;padding:7px 12px;border:1px solid var(--line);border-radius:8px;background:var(--bg);color:var(--fg);font-size:14px}
160
- label{font-size:13px;color:var(--muted);white-space:nowrap}
156
+ .hd{font-size:13px;color:var(--muted);display:grid;grid-template-columns:max-content 1fr max-content 1fr;gap:6px 14px;align-items:center}
157
+ .hd .k{font-weight:600;color:var(--fg)}
158
+ .hd .v{color:var(--fg);font-weight:600;padding-left:2px}
159
+ .row2{display:flex;gap:12px;align-items:center;margin-top:6px;grid-column:1/3;flex-wrap:wrap}
160
+ .qbox{width:360px;max-width:100%;padding:7px 12px;border:1px solid var(--line);border-radius:8px;background:var(--bg);color:var(--fg);font-size:14px}
161
+ label{font-size:13px;color:var(--fg);font-weight:600;white-space:nowrap}
161
162
  button{padding:6px 12px;border:1px solid var(--line);border-radius:8px;background:var(--bg);color:var(--fg);cursor:pointer;font-size:13px}
162
163
  button:hover{border-color:var(--muted)}
164
+ select{padding:6px 10px;border:1px solid var(--line);border-radius:8px;background:var(--bg);color:var(--fg);font-size:13px;max-width:340px}
165
+ select:disabled{opacity:.55}
163
166
  #stats{font-size:12px;color:var(--muted);min-width:140px}
164
167
  main{max-width:1160px;margin:0 auto;padding:10px 28px 80px}
165
168
  section.block{padding:6px 14px 12px;margin:10px 0;border-radius:10px}
@@ -210,6 +213,107 @@ bt.onclick=()=>{i=(i+1)%3;root.dataset.theme=modes[i];localStorage.setItem('th',
210
213
  """
211
214
 
212
215
 
216
+ #: Manual month names for switcher labels: ``strftime("%b")`` follows the
217
+ #: machine locale and could emit a non-English month (hygiene requires
218
+ #: ASCII/English template strings).
219
+ _MONTHS = ("Jan", "Feb", "Mar", "Apr", "May", "Jun",
220
+ "Jul", "Aug", "Sep", "Oct", "Nov", "Dec")
221
+ _STEM_DT_RE = re.compile(r"_(\d{4})-(\d{2})-(\d{2})-(\d{2})(\d{2})$")
222
+
223
+ #: Switcher client script: populate the ``#s`` select from the manifest
224
+ #: global (newest first, first ten plus the current page when it falls
225
+ #: outside), switch by navigating the SAME viewer template over file://
226
+ #: (XHR is blocked there; the loaded page re-runs search/theme itself).
227
+ _SWITCH_JS = r"""
228
+ (function(){var sel=document.getElementById('s');if(!sel)return;
229
+ var all=(window.CC_SESSIONS||[]),cur=sel.getAttribute('data-cur')||'',up=sel.getAttribute('data-up')||'';
230
+ function find(a,h){for(var i=0;i<a.length;i++){if(a[i].href===h)return a[i];}return null;}
231
+ var top=all.slice(0,10);
232
+ if(cur&&!find(top,cur)){top.push(find(all,cur)||{href:cur,label:'(current session)'});}
233
+ for(var k=0;k<top.length;k++){var o=document.createElement('option');
234
+ o.value=top[k].href;o.textContent=top[k].label;sel.appendChild(o);}
235
+ if(cur)sel.value=cur;
236
+ sel.disabled=all.length<2;
237
+ var lbl=document.getElementById('slbl');
238
+ if(lbl)lbl.textContent=all.length>1?'Sessions':'Session';
239
+ sel.onchange=function(){if(this.value)location.href=up+this.value;};})();
240
+ """
241
+
242
+
243
+ def _session_entry(html_path: Path, project_dir: Path) -> dict:
244
+ """One manifest entry; ``_k`` is the private sort key (datetime)."""
245
+ stem = html_path.stem
246
+ m = _STEM_DT_RE.search(stem)
247
+ dt = None
248
+ if m:
249
+ try:
250
+ dt = datetime(*[int(g) for g in m.groups()])
251
+ except ValueError:
252
+ dt = None
253
+ if dt is None:
254
+ dt = datetime.fromtimestamp(html_path.stat().st_mtime)
255
+ label = stem
256
+ else:
257
+ label = f"{stem[:m.start()]} - {dt:%d} {_MONTHS[dt.month - 1]} {dt:%H:%M}"
258
+ return {"href": html_path.relative_to(project_dir).as_posix(),
259
+ "label": label, "_k": dt}
260
+
261
+
262
+ def collect_sessions(project_dir: Path) -> list[dict]:
263
+ """Every exported session HTML of one project, newest first.
264
+
265
+ Scans ``<project>/sessions/*/checkpoint/*.html``. Labels come from the
266
+ stem's ``_YYYY-MM-DD-HHMM`` tail (``name - DD Mon HH:MM``); a stem
267
+ without a parseable tail falls back to the raw stem with file mtime.
268
+ Unreadable files are skipped.
269
+ """
270
+ entries = []
271
+ for p in project_dir.glob("sessions/*/checkpoint/*.html"):
272
+ try:
273
+ entries.append(_session_entry(p, project_dir))
274
+ except OSError:
275
+ continue
276
+ entries.sort(key=lambda e: e["_k"], reverse=True)
277
+ return [{"href": e["href"], "label": e["label"]} for e in entries]
278
+
279
+
280
+ def render_manifest(entries: list[dict]) -> str:
281
+ """``sessions.js`` body: one global assignment, ASCII JSON only."""
282
+ return ("window.CC_SESSIONS="
283
+ + json.dumps(entries, ensure_ascii=True, separators=(",", ":")) + ";\n")
284
+
285
+
286
+ def _checkpoint_project(dest_dir: Path) -> tuple[Path, str] | None:
287
+ """``(project_dir, '../' prefix)`` when dest_dir is a real checkpoint
288
+ dir (``<project>/sessions/<NNN>/checkpoint``); ``None`` otherwise.
289
+ The page sits three levels under the project, hence ``../../../``."""
290
+ try:
291
+ if dest_dir.name != "checkpoint":
292
+ return None
293
+ if dest_dir.parents[1].name != "sessions" or not dest_dir.parents[0].name.isdigit():
294
+ return None
295
+ return dest_dir.parents[2], "../../../"
296
+ except IndexError:
297
+ return None
298
+
299
+
300
+ def update_sessions_manifest(dest_dir: Path) -> None:
301
+ """Best-effort refresh of ``<project>/sessions.js`` after one export.
302
+
303
+ Never raises (P9-D7): a manifest problem is one debug line; the export
304
+ pair stands on its own.
305
+ """
306
+ try:
307
+ ctx = _checkpoint_project(dest_dir)
308
+ if ctx is None:
309
+ return
310
+ project, _up = ctx
311
+ body = render_manifest(collect_sessions(project))
312
+ atomic.write_bytes_fsync(project / "sessions.js", body.encode("utf-8"))
313
+ except Exception:
314
+ debug_log(f"manifest skipped: sessions.js for {dest_dir}")
315
+
316
+
213
317
  def _ts_hms(ts: str | None) -> str:
214
318
  """Local HH:MM:SS for an ISO-8601 timestamp; empty when absent or bad."""
215
319
  if not ts:
@@ -238,6 +342,17 @@ def render_html(blocks: list[Block], meta: dict) -> str:
238
342
  """
239
343
  ratio = meta.get("ratio")
240
344
  ratio_s = "n/a" if ratio is None else f"{float(ratio):.1%}"
345
+ ext = switch_js = ""
346
+ # Unwired pages keep empty grid cells so auto-flow columns stay aligned.
347
+ switch = "<span></span><span></span>"
348
+ if meta.get("manifest_src"):
349
+ src = html.escape(str(meta["manifest_src"]), quote=True)
350
+ cur = html.escape(str(meta.get("self_href") or ""), quote=True)
351
+ up = src[:src.rfind("/") + 1]
352
+ ext = f'<script src="{src}"></script>\n'
353
+ switch = (f'<label for="s" id="slbl">Sessions</label>'
354
+ f'<select id="s" data-cur="{cur}" data-up="{up}"></select>')
355
+ switch_js = _SWITCH_JS
241
356
  sections = []
242
357
  for role, text, ts in blocks:
243
358
  cls = "user" if role == "user" else "asst"
@@ -251,20 +366,22 @@ def render_html(blocks: list[Block], meta: dict) -> str:
251
366
  '<meta name="viewport" content="width=device-width,initial-scale=1">\n'
252
367
  f'<title>{_meta_val(meta, "stem")} - session transcript</title>'
253
368
  f'<style>{_CSS}</style></head><body>\n'
254
- '<header><div class="meta">\n'
369
+ '<header><div class="hd">\n'
255
370
  f'<span class="k">Session Name</span><span class="v">{_meta_val(meta, "name")} (cp-{_meta_val(meta, "nnn")})</span>\n'
256
371
  f'<span class="k">Model</span><span class="v">{_meta_val(meta, "model")}</span>\n'
257
372
  f'<span class="k">Project</span><span class="v">{_meta_val(meta, "project")}</span>\n'
258
373
  f'<span class="k">Ratio at rotation</span><span class="v">{ratio_s}</span>\n'
259
374
  f'<span class="k">Branch</span><span class="v">{_meta_val(meta, "branch")} @ {_meta_val(meta, "head")}</span>\n'
260
375
  f'<span class="k">Session Time</span><span class="v">{_meta_val(meta, "span")}</span>\n'
261
- '</div>\n'
262
- '<div class="controls"><input type="search" id="q" '
263
- 'placeholder="search - marks all matches, optional block filter">\n'
264
- '<label><input type="checkbox" id="f"> matching blocks only</label>\n'
265
- '<button id="t">theme</button><span id="stats"></span></div></header>\n'
376
+ '<label for="q">Search</label>\n'
377
+ '<input type="search" id="q" class="qbox" '
378
+ 'placeholder="marks all matches, optional block filter">\n'
379
+ f'{switch}\n'
380
+ '<div class="row2"><label><input type="checkbox" id="f"> '
381
+ 'matching blocks only</label>\n'
382
+ '<button id="t">theme</button><span id="stats"></span></div></div></header>\n'
266
383
  f'<main>{"".join(sections)}</main>\n'
267
- f'<script>{_JS}</script></body>')
384
+ f'{ext}<script>{_JS}{switch_js}</script></body>')
268
385
 
269
386
 
270
387
  def resolve_transcript_path(metric: dict | None, root: Path, sid: str | None,
@@ -327,7 +444,8 @@ def render_markdown(blocks: list[Block], meta: dict) -> str:
327
444
 
328
445
 
329
446
  def export_session(jsonl_path: Path, dest_dir: Path, meta: dict,
330
- *, cap_bytes: int = 5 * 1024 * 1024) -> str | None:
447
+ *, cap_bytes: int = 5 * 1024 * 1024,
448
+ final_dir: Path | None = None) -> str | None:
331
449
  """Best-effort readable export of one session JSONL (B3/B4).
332
450
 
333
451
  Reads at most ``cap_bytes`` (past the cap the trailing partial line is
@@ -335,7 +453,11 @@ def export_session(jsonl_path: Path, dest_dir: Path, meta: dict,
335
453
  ``<stem>.md`` and ``<stem>.html`` into ``dest_dir`` with fsync'd plain
336
454
  writes and returns the stem. ``span``/``stem`` are derived from the
337
455
  first/last block timestamps (local; ``stem`` falls back to now) and
338
- added to a meta copy. Never raises: unreadable source, empty parse, or
456
+ added to a meta copy. ``final_dir`` (issue #16): where the pair will
457
+ live when ``dest_dir`` is only a staging dir (finalize's
458
+ ``checkpoint.tmp-*``); the switcher wiring uses it and the in-place
459
+ manifest refresh is skipped (the mover refreshes at the final dir).
460
+ Never raises: unreadable source, empty parse, or
339
461
  any write failure logs one debug line, leaves no half-written pair,
340
462
  and returns ``None``.
341
463
  """
@@ -373,6 +495,14 @@ def export_session(jsonl_path: Path, dest_dir: Path, meta: dict,
373
495
  export_meta = dict(meta)
374
496
  export_meta["stem"] = stem
375
497
  export_meta["span"] = span
498
+ eff = final_dir or dest_dir
499
+ ctx = _checkpoint_project(eff)
500
+ if ctx is not None:
501
+ project, up = ctx
502
+ export_meta["manifest_src"] = up + "sessions.js"
503
+ export_meta["manifest_up"] = up
504
+ export_meta["self_href"] = (eff.relative_to(project).as_posix()
505
+ + "/" + stem + ".html")
376
506
  dest_dir.mkdir(parents=True, exist_ok=True)
377
507
  written: list[Path] = []
378
508
  try:
@@ -392,6 +522,14 @@ def export_session(jsonl_path: Path, dest_dir: Path, meta: dict,
392
522
  pass
393
523
  debug_log(f"export skipped: write failed for {stem}")
394
524
  return None
525
+ # Issue #16: refresh the per-project manifest the switcher reads.
526
+ # When exporting into a staging dir the mover refreshes at the
527
+ # final dir instead. Guarded belt-and-braces; never raises.
528
+ if final_dir is None:
529
+ try:
530
+ update_sessions_manifest(dest_dir)
531
+ except Exception:
532
+ debug_log(f"manifest skipped: refresh failed for {stem}")
395
533
  return stem
396
534
  except Exception:
397
535
  debug_log(f"export skipped: unexpected error for {jsonl_path}")
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: cc-continuity
3
- Version: 0.3.1
3
+ Version: 0.3.3
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
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "cc-continuity"
7
- version = "0.3.1"
7
+ version = "0.3.3"
8
8
  description = "Zero-touch session rotation for Claude Code (local large-context model)"
9
9
  requires-python = ">=3.11"
10
10
  dependencies = [] # stdlib only at runtime (PRD §0.5)
@@ -1,9 +1,12 @@
1
1
  """hooks/pre_tool_use.py: hard ceiling (PRD §9, spec §6.3).
2
2
 
3
3
  Ratio gate: ratio >= hard with a pre-handoff state -> walk to
4
- HANDOFF_REQUESTED, then deny. State gate: pre-checkpoint states deny C.3,
5
- handoff-accepted states deny C.9, always with the same allowlist. Silent
6
- allow otherwise.
4
+ HANDOFF_REQUESTED, let the in-flight call through and inject the C.2
5
+ handoff instruction as neutral additionalContext (CC renders denials as
6
+ red "Error:" lines; routine rotation is not an error - issue #25).
7
+ State gate: handoff-requested states deny C.3 (only after the model saw
8
+ the guidance), handoff-accepted states deny C.9, always with the same
9
+ allowlist. Silent allow otherwise.
7
10
  """
8
11
 
9
12
  import pytest
@@ -33,6 +36,10 @@ def _reason(out):
33
36
  return out["hookSpecificOutput"]["permissionDecisionReason"]
34
37
 
35
38
 
39
+ def _system(out):
40
+ return out.get("systemMessage", "")
41
+
42
+
36
43
  def test_below_hard_allows_silently(cc_home, capsys, tmp_path):
37
44
  repo, key, nnn = _setup(cc_home, tmp_path, s="ACTIVE", ratio=0.60)
38
45
  _pretool(repo, "Bash", {"command": "rm -rf x"})
@@ -40,20 +47,78 @@ def test_below_hard_allows_silently(cc_home, capsys, tmp_path):
40
47
  assert state.load_state(key, nnn)["state"] == "ACTIVE"
41
48
 
42
49
 
43
- def test_hard_ratio_walks_to_handoff_and_denies(cc_home, capsys, tmp_path):
50
+ def test_hard_ratio_crossing_guides_without_denying(cc_home, capsys, tmp_path):
51
+ # Routine crossing (issue #25): CC renders denials as red "Error:"
52
+ # lines, but rotation is routine - the in-flight call passes and the
53
+ # handoff instruction arrives as neutral additionalContext.
44
54
  repo, key, nnn = _setup(cc_home, tmp_path, s="ROTATION_PENDING", ratio=0.73)
45
55
  _pretool(repo, "Bash", {"command": "rm -rf x"})
46
56
  out = stdout_json(capsys)
47
57
  assert out["hookSpecificOutput"]["hookEventName"] == "PreToolUse"
48
- assert out["hookSpecificOutput"]["permissionDecision"] == "deny"
49
- assert "hard limit" in _reason(out)
58
+ assert "permissionDecision" not in out["hookSpecificOutput"]
59
+ assert "Rotation pending" in out["hookSpecificOutput"]["additionalContext"]
60
+ assert "handoff.draft.md" in out["hookSpecificOutput"]["additionalContext"]
61
+ assert "cc-continuity" in _system(out)
50
62
  assert state.load_state(key, nnn)["state"] == "HANDOFF_REQUESTED"
51
63
 
52
64
 
65
+ def test_second_work_tool_after_crossing_denies(cc_home, capsys, tmp_path):
66
+ # Only AFTER the model saw the guidance may a work tool be denied.
67
+ repo, key, nnn = _setup(cc_home, tmp_path, s="ROTATION_PENDING", ratio=0.73)
68
+ _pretool(repo, "Bash", {"command": "rm -rf x"}) # crossing: allow + guide
69
+ stdout_json(capsys)
70
+ _pretool(repo, "Bash", {"command": "pytest"})
71
+ out = stdout_json(capsys)
72
+ assert out["hookSpecificOutput"]["permissionDecision"] == "deny"
73
+ assert "hard limit" in _system(out)
74
+
75
+
76
+ def test_handoff_requested_deny_routes_guidance_to_system_message(cc_home,
77
+ capsys,
78
+ tmp_path):
79
+ # A post-guidance denial renders its full guidance as an informational
80
+ # systemMessage, not only as the red error in the deny reason.
81
+ repo, key, nnn = _setup(cc_home, tmp_path, s="HANDOFF_REQUESTED")
82
+ _pretool(repo, "Bash", {"command": "rm -rf x"})
83
+ out = stdout_json(capsys)
84
+ assert "hard limit" in _system(out)
85
+ assert "Allowed now" in _system(out)
86
+
87
+
88
+ def test_handoff_requested_deny_reason_omits_allowed_tools_guidance(cc_home,
89
+ capsys,
90
+ tmp_path):
91
+ repo, key, nnn = _setup(cc_home, tmp_path, s="HANDOFF_REQUESTED")
92
+ _pretool(repo, "Bash", {"command": "rm -rf x"})
93
+ out = stdout_json(capsys)
94
+ assert "Allowed now" not in _reason(out)
95
+ assert "handoff.draft.md" in _reason(out)
96
+ assert "end your turn" in _reason(out)
97
+
98
+
99
+ def test_handoff_accepted_deny_routes_guidance_to_system_message(cc_home,
100
+ capsys,
101
+ tmp_path):
102
+ repo, key, nnn = _setup(cc_home, tmp_path, s="CHECKPOINT_WRITING")
103
+ _pretool(repo, "Bash", {"command": "pytest"})
104
+ out = stdout_json(capsys)
105
+ assert "Do not start any more work" in _system(out)
106
+
107
+
108
+ def test_handoff_accepted_deny_reason_is_brief(cc_home, capsys, tmp_path):
109
+ repo, key, nnn = _setup(cc_home, tmp_path, s="CHECKPOINT_WRITING")
110
+ _pretool(repo, "Bash", {"command": "pytest"})
111
+ out = stdout_json(capsys)
112
+ assert "handoff accepted" in _reason(out)
113
+ assert "Do not start any more work" not in _reason(out)
114
+
115
+
53
116
  def test_hard_ratio_walks_even_when_tool_allowed(cc_home, capsys, tmp_path):
54
117
  repo, key, nnn = _setup(cc_home, tmp_path, s="ACTIVE", ratio=0.75)
55
118
  _pretool(repo, "Read", {"file_path": "/x"})
56
- assert stdout_json(capsys) is None # Read passes the allowlist
119
+ # The allowlisted call also receives the crossing guidance.
120
+ out = stdout_json(capsys)
121
+ assert "Rotation pending" in out["hookSpecificOutput"]["additionalContext"]
57
122
  assert state.load_state(key, nnn)["state"] == "HANDOFF_REQUESTED"
58
123
 
59
124
 
@@ -1,7 +1,7 @@
1
1
  """Phase 5 end-to-end chain without a model (spec §8/§9): warn ->
2
- pending -> hard (PreToolUse ceiling) -> deny -> draft -> C.9 -> Stop ->
3
- finalized checkpoint -> AMCL. Locks the cross-hook sequence; a failure
4
- here is an integration regression (all parts land in Tasks 4-9)."""
2
+ pending -> hard (PreToolUse ceiling) -> guide -> deny -> draft -> C.9 ->
3
+ Stop -> finalized checkpoint -> AMCL. Locks the cross-hook sequence; a
4
+ failure here is an integration regression (all parts land in Tasks 4-9)."""
5
5
 
6
6
  from cc_continuity import config, ledger, paths, state, validate
7
7
  from cc_continuity.hooks import stop
@@ -67,10 +67,16 @@ def test_full_threshold_to_checkpoint_chain(cc_home, capsys, tmp_path,
67
67
 
68
68
  set_metric(0.73) # >= hard_ratio 0.72
69
69
  out = pretool("Bash", {"command": "rm -rf /tmp/whatever"})
70
- # The PreToolUse ratio gate (spec 6.3) walks RP -> HR, then denies.
70
+ # Guidance-first (issue #25): the PreToolUse ratio gate (spec 6.3)
71
+ # walks RP -> HR, lets the in-flight call through and injects C.2 as
72
+ # neutral context - no red "Error:" denial for a routine crossing.
73
+ assert "permissionDecision" not in out["hookSpecificOutput"]
74
+ assert "Rotation pending" in out["hookSpecificOutput"]["additionalContext"]
75
+ assert state.load_state(key, nnn)["state"] == "HANDOFF_REQUESTED"
76
+ # Only AFTER the guidance may a work call be denied.
77
+ out = pretool("Bash", {"command": "echo more"})
71
78
  assert out["hookSpecificOutput"]["permissionDecision"] == "deny"
72
79
  assert "hard limit" in out["hookSpecificOutput"]["permissionDecisionReason"]
73
- assert state.load_state(key, nnn)["state"] == "HANDOFF_REQUESTED"
74
80
  assert pretool("Read", {"file_path": "/x"}) is None # allowlist passes
75
81
 
76
82
  draft.write_text(_draft_text(), encoding="utf-8")
@@ -158,3 +158,123 @@ def test_export_failures_never_raise(tmp_path, cc_home, monkeypatch):
158
158
  monkeypatch.setattr(transcript.atomic, "write_bytes_fsync", boom)
159
159
  assert transcript.export_session(_fixture(tmp_path), tmp_path / "o2", _meta()) is None
160
160
  assert not (tmp_path / "o2").exists() or not list((tmp_path / "o2").iterdir())
161
+
162
+
163
+ # --- issue #16: session switcher (per-project sessions.js manifest) ---
164
+
165
+ def _proj_tree(tmp_path, nnn_stems):
166
+ """Fake project dir holding sessions/<nnn>/checkpoint/<stem>.html files."""
167
+ proj = tmp_path / "projects" / "proj-abc12345"
168
+ for nnn, stem in nnn_stems:
169
+ d = proj / "sessions" / nnn / "checkpoint"
170
+ d.mkdir(parents=True, exist_ok=True)
171
+ (d / f"{stem}.html").write_text("<html></html>", encoding="utf-8")
172
+ return proj
173
+
174
+
175
+ def test_collect_sessions_newest_first(tmp_path):
176
+ proj = _proj_tree(tmp_path, [("166", "claude-continuity-166_2026-11-08-1000"),
177
+ ("167", "claude-continuity-167_2026-11-08-1815")])
178
+ e = transcript.collect_sessions(proj)
179
+ assert [x["href"] for x in e] == ["sessions/167/checkpoint/claude-continuity-167_2026-11-08-1815.html",
180
+ "sessions/166/checkpoint/claude-continuity-166_2026-11-08-1000.html"]
181
+ assert e[0]["label"] == "claude-continuity-167 - 08 Nov 18:15"
182
+ assert all(x["href"].isascii() and x["label"].isascii() for x in e)
183
+
184
+
185
+ def test_collect_sessions_ignores_noise_and_falls_back_to_mtime(tmp_path):
186
+ proj = _proj_tree(tmp_path, [("001", "sess_a")]) # stem without a date part
187
+ (proj / "sessions" / "001" / "checkpoint" / "handoff.md").write_text("x", encoding="utf-8")
188
+ (proj / "sessions" / "002" / "checkpoint").mkdir(parents=True) # no export yet
189
+ e = transcript.collect_sessions(proj)
190
+ assert len(e) == 1
191
+ assert e[0]["href"] == "sessions/001/checkpoint/sess_a.html"
192
+ assert e[0]["label"] == "sess_a" # bad stem: label falls back to the stem
193
+
194
+
195
+ def test_render_manifest_shape(tmp_path):
196
+ entries = [{"href": "sessions/001/checkpoint/a.html", "label": "a - 01 Jan 02:03"}]
197
+ s = transcript.render_manifest(entries)
198
+ assert s.startswith("window.CC_SESSIONS=") and s.isascii()
199
+ assert json.loads(s[s.index("["):s.rindex("]") + 1]) == entries
200
+
201
+
202
+ def test_update_sessions_manifest_writes_project_file(tmp_path):
203
+ proj = _proj_tree(tmp_path, [("166", "s-166_2026-11-08-1000"),
204
+ ("167", "s-167_2026-11-08-1815")])
205
+ transcript.update_sessions_manifest(proj / "sessions" / "166" / "checkpoint")
206
+ js = (proj / "sessions.js").read_text(encoding="utf-8")
207
+ assert js.startswith("window.CC_SESSIONS=")
208
+ assert "sessions/167/checkpoint/s-167_2026-11-08-1815.html" in js
209
+ assert "sessions/166/checkpoint/s-166_2026-11-08-1000.html" in js
210
+
211
+
212
+ def test_update_sessions_manifest_wrong_shape_is_noop(tmp_path, cc_home):
213
+ # cc_home: the skip path logs through debug_log, never the real store.
214
+ out = tmp_path / "out"
215
+ out.mkdir()
216
+ transcript.update_sessions_manifest(out) # not <proj>/sessions/<nnn>/checkpoint
217
+ assert not list(tmp_path.rglob("sessions.js"))
218
+
219
+
220
+ def test_render_html_switcher_when_wired():
221
+ meta = dict(META, manifest_src="../../sessions.js",
222
+ self_href="sessions/166/checkpoint/x.html")
223
+ d = transcript.render_html([("user", "hi", None)], meta)
224
+ assert '<select id="s"' in d and 'data-cur="sessions/166/checkpoint/x.html"' in d
225
+ assert 'src="../../sessions.js"' in d
226
+ assert d.isascii()
227
+ # User polish (2026-11-08): switcher shares the search row, both groups
228
+ # carry visible capitalized labels; the plural is resolved client-side.
229
+ # User polish round 3 (2026-11-08): ONE shared header grid so the
230
+ # Sessions label sits directly below Session Time (same column, always);
231
+ # the search box is a fixed short width, no greedy stretching.
232
+ assert d.count('class="hd"') == 1 and '<div class="controls">' not in d
233
+ assert "grid-template-columns:max-content 1fr max-content 1fr" in d
234
+ assert ".qbox{width:360px" in d
235
+ assert d.index('id="slbl"') > d.index("Session Time")
236
+ assert '<div class="row2">' in d and d.index('id="f"') > d.index('id="slbl"')
237
+ assert "'Sessions'" in d and "'Session'" in d # plural-aware JS
238
+ # User polish round 4 (2026-11-09): the header labels read bold and
239
+ # dark (key labels, Search, Sessions), not faded grey.
240
+ assert ".hd .k{font-weight:600;color:var(--fg)}" in d
241
+ assert "label{font-size:13px;color:var(--fg);font-weight:600" in d
242
+
243
+
244
+ def test_render_html_no_switcher_when_unwired():
245
+ d = _doc() # META has no manifest keys (legacy call shape)
246
+ assert 'id="s"' not in d and "sessions.js" not in d
247
+ assert '<label for="q">Search</label>' in d # Search label is unconditional
248
+
249
+
250
+ def test_export_session_writes_manifest(tmp_path):
251
+ proj = tmp_path / "proj"
252
+ dest = proj / "sessions" / "001" / "checkpoint"
253
+ stem = transcript.export_session(_fixture(tmp_path), dest, _meta())
254
+ assert stem
255
+ js = (proj / "sessions.js").read_text(encoding="utf-8")
256
+ assert f"sessions/001/checkpoint/{stem}.html" in js
257
+
258
+
259
+ def test_export_relative_depth_matches_checkpoint_dirs(tmp_path):
260
+ # Browser-verified integration rule: the page lives at
261
+ # sessions/<NNN>/checkpoint/x.html (three levels under the project),
262
+ # so the manifest must resolve with ../../../ from the checkpoint dir.
263
+ proj = tmp_path / "proj"
264
+ dest = proj / "sessions" / "007" / "checkpoint"
265
+ stem = transcript.export_session(_fixture(tmp_path), dest, _meta())
266
+ page = (dest / f"{stem}.html").read_text(encoding="utf-8")
267
+ assert 'src="../../../sessions.js"' in page
268
+ assert 'data-up="../../../"' in page
269
+ assert 'data-cur="sessions/007/checkpoint/' in page
270
+ # and the resolved target must actually exist
271
+ assert (dest / "../../../sessions.js").resolve() == (proj / "sessions.js").resolve()
272
+
273
+
274
+ def test_export_session_survives_manifest_failure(tmp_path, cc_home, monkeypatch):
275
+ def boom(dest_dir):
276
+ raise RuntimeError("simulated manifest loss")
277
+ monkeypatch.setattr(transcript, "update_sessions_manifest", boom)
278
+ dest = tmp_path / "proj" / "sessions" / "001" / "checkpoint"
279
+ assert transcript.export_session(_fixture(tmp_path), dest, _meta())
280
+ assert list(dest.glob("*.html"))
@@ -72,3 +72,20 @@ def test_insert_transcript_line_position():
72
72
  i = next(i for i, l in enumerate(lines) if l.startswith("Transcript: "))
73
73
  assert lines[i - 1].startswith("- ") and lines[i + 1] == ""
74
74
  assert checkpoint.headings_in_order(out)
75
+
76
+
77
+ def test_finalize_writes_sessions_manifest(cc_home, tmp_path):
78
+ # Issue #16: the export also refreshes the per-project sessions.js so
79
+ # every viewer page can offer the session switcher over file://.
80
+ repo, key, nnn = _registered(tmp_path, draft=DRAFT_TEXT)
81
+ checkpoint.finalize(
82
+ key, nnn, cfg=_cfg_for(repo), root=repo,
83
+ metric={"session_id": SID, "transcript_path": str(_conv(tmp_path)),
84
+ "model": "m", "ratio": 0.5})
85
+ proj = paths.session_dir(key, nnn).parent.parent
86
+ js = (proj / "sessions.js").read_text(encoding="utf-8")
87
+ assert js.startswith("window.CC_SESSIONS=")
88
+ assert f"sessions/{nnn:03d}/checkpoint/" in js
89
+ # the checkpoint dir itself must stay manifest-free (SHA256SUMS shape)
90
+ final = paths.session_dir(key, nnn) / "checkpoint"
91
+ assert "sessions.js" not in {p.name for p in final.iterdir()}
File without changes
File without changes