claude-session-hub 0.1.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 (32) hide show
  1. claude_session_hub-0.1.1/LICENSE +21 -0
  2. claude_session_hub-0.1.1/PKG-INFO +161 -0
  3. claude_session_hub-0.1.1/README.md +142 -0
  4. claude_session_hub-0.1.1/pyproject.toml +35 -0
  5. claude_session_hub-0.1.1/setup.cfg +4 -0
  6. claude_session_hub-0.1.1/src/claude_session_hub/__init__.py +3 -0
  7. claude_session_hub-0.1.1/src/claude_session_hub/__main__.py +3 -0
  8. claude_session_hub-0.1.1/src/claude_session_hub/cli.py +66 -0
  9. claude_session_hub-0.1.1/src/claude_session_hub/commits.py +204 -0
  10. claude_session_hub-0.1.1/src/claude_session_hub/demo.py +240 -0
  11. claude_session_hub-0.1.1/src/claude_session_hub/fsutil.py +38 -0
  12. claude_session_hub-0.1.1/src/claude_session_hub/limits.py +134 -0
  13. claude_session_hub-0.1.1/src/claude_session_hub/notes.py +130 -0
  14. claude_session_hub-0.1.1/src/claude_session_hub/server.py +103 -0
  15. claude_session_hub-0.1.1/src/claude_session_hub/sessions.py +830 -0
  16. claude_session_hub-0.1.1/src/claude_session_hub/static/app.js +385 -0
  17. claude_session_hub-0.1.1/src/claude_session_hub/static/index.html +82 -0
  18. claude_session_hub-0.1.1/src/claude_session_hub/static/style.css +109 -0
  19. claude_session_hub-0.1.1/src/claude_session_hub/usage.py +316 -0
  20. claude_session_hub-0.1.1/src/claude_session_hub.egg-info/PKG-INFO +161 -0
  21. claude_session_hub-0.1.1/src/claude_session_hub.egg-info/SOURCES.txt +30 -0
  22. claude_session_hub-0.1.1/src/claude_session_hub.egg-info/dependency_links.txt +1 -0
  23. claude_session_hub-0.1.1/src/claude_session_hub.egg-info/entry_points.txt +2 -0
  24. claude_session_hub-0.1.1/src/claude_session_hub.egg-info/top_level.txt +1 -0
  25. claude_session_hub-0.1.1/tests/test_commits.py +93 -0
  26. claude_session_hub-0.1.1/tests/test_demo.py +37 -0
  27. claude_session_hub-0.1.1/tests/test_limits.py +117 -0
  28. claude_session_hub-0.1.1/tests/test_notes.py +66 -0
  29. claude_session_hub-0.1.1/tests/test_server.py +62 -0
  30. claude_session_hub-0.1.1/tests/test_sessions.py +275 -0
  31. claude_session_hub-0.1.1/tests/test_terminal.py +151 -0
  32. claude_session_hub-0.1.1/tests/test_usage.py +136 -0
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 lolloi
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,161 @@
1
+ Metadata-Version: 2.4
2
+ Name: claude-session-hub
3
+ Version: 0.1.1
4
+ Summary: A local dashboard for all your Claude Code sessions: who is working, who is waiting for you.
5
+ Author: lolloi
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/lolloi/claude-session-hub
8
+ Project-URL: Issues, https://github.com/lolloi/claude-session-hub/issues
9
+ Keywords: claude,claude-code,dashboard,sessions,anthropic
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: Environment :: Web Environment
12
+ Classifier: Operating System :: OS Independent
13
+ Classifier: Topic :: Software Development
14
+ Classifier: Intended Audience :: Developers
15
+ Requires-Python: >=3.9
16
+ Description-Content-Type: text/markdown
17
+ License-File: LICENSE
18
+ Dynamic: license-file
19
+
20
+ # Claude Session Hub
21
+
22
+ [![tests](https://github.com/lolloi/claude-session-hub/actions/workflows/tests.yml/badge.svg)](https://github.com/lolloi/claude-session-hub/actions/workflows/tests.yml)
23
+
24
+ **See all your Claude Code sessions in one page, and know at a glance which one is waiting for you.**
25
+
26
+ If you run several Claude Code sessions at once (one per feature, one per role…), it is easy to
27
+ lose track: which one is still working, which one is only running tests, which one finished, and
28
+ **which one has been waiting for your answer for twenty minutes**. Claude Session Hub reads the
29
+ files Claude already writes on your computer and shows it all on a local page, with an optional
30
+ notification when a session needs you.
31
+
32
+ ![Claude Session Hub: a session finishes and asks a question, a handoff note opens, then tokens and commits](https://raw.githubusercontent.com/lolloi/claude-session-hub/main/docs/demo.gif)
33
+
34
+ *The built-in demo (`--demo`): made-up sessions, no real data. Here "Checkout API" finishes its turn
35
+ with a question and moves to the top as "Waiting for you".*
36
+
37
+ ## What you see
38
+
39
+ - **Who is waiting for you**, on top, with the question in the session's own words, and a
40
+ notification if you want one. If a session tells you to answer in another session's window,
41
+ the card says so.
42
+ - **What each session is doing**: working, running checks in the background (tests, a build),
43
+ or done.
44
+ - **Its last handoff note**, if it keeps one (click to read it whole).
45
+ - **Tokens** per session and per day for the last 14 days.
46
+ - **Commits each session landed on the main branch**, even after a rebase.
47
+ - **Plan limits** (5-hour and weekly windows), as last seen by the Claude desktop app, with the
48
+ tokens used this week and an estimate of how many make 100%.
49
+
50
+ It works with sessions in the **Claude desktop app** (Code tab) and with sessions started with
51
+ **`claude` in a terminal**.
52
+
53
+ ## Run it
54
+
55
+ Needs Python 3.9 or newer and git 2.31 or newer. No other dependencies.
56
+
57
+ ```bash
58
+ pipx install claude-session-hub
59
+ claude-session-hub
60
+ ```
61
+
62
+ The page opens at <http://127.0.0.1:4777>. To try it without your own sessions:
63
+
64
+ ```bash
65
+ claude-session-hub --demo
66
+ ```
67
+
68
+ Other ways: `uvx claude-session-hub` runs it without installing; `python3 -m pip install claude-session-hub`
69
+ works too where your Python allows it (inside a virtual environment, for example). From a clone of
70
+ this repository: `PYTHONPATH=src python3 -m claude_session_hub`.
71
+
72
+ Options: `--port 4777`, `--no-open`, `--archived` (also archived desktop sessions), `--demo`,
73
+ `--json` (print one snapshot and exit).
74
+
75
+ ## Privacy
76
+
77
+ - **Read-only.** It only reads files Claude and git already have on your computer, and runs only
78
+ read-only git commands.
79
+ - **Local.** The page is served on `127.0.0.1` only. Nothing is sent anywhere, there are no API
80
+ calls and nothing costs money.
81
+ - **One file of its own**: `~/.cache/claude-session-hub/usage-v1.json`, token counts per
82
+ transcript so the page has numbers as soon as it opens. Delete it any time; set
83
+ `CLAUDE_SESSION_HUB_CACHE` to move it.
84
+
85
+ ## How it works
86
+
87
+ | Source | Where | Used for |
88
+ |---|---|---|
89
+ | Claude desktop app, Code sessions | `~/Library/Application Support/Claude/claude-code-sessions/` | name, model, folder, branch, the app's summary of the last turn |
90
+ | Claude Code transcripts, end of each file | `~/.claude/projects/*/*.jsonl` (last 16 MB the first time, then only new lines) | is a turn running, is a question waiting, background jobs, the session's last words |
91
+ | Transcripts of terminal sessions | `~/.claude/projects/*/*.jsonl` changed in the last 30 days | sessions started with `claude` in a terminal |
92
+ | Running Claude Code sessions | `~/.claude/sessions/<pid>.json` (and whether that process still runs) | a terminal session whose `claude` has exited is Done, not waiting |
93
+ | Transcripts, whole files | `~/.claude/projects/**/*.jsonl` (only new bytes are read) | tokens per session and per day, notes written, `git commit` times |
94
+ | Git history of each session's repository | worktree reflogs and `git log <main branch>` | commits each session landed on the main branch |
95
+ | Shared notes of Code sessions | `~/Library/Application Support/Claude/side-session-notes/` | each session's handoff note |
96
+ | Plan usage seen by the desktop app | `~/Library/Application Support/Claude/plan-usage-history.json` | 5-hour and weekly limits |
97
+
98
+ **States.**
99
+
100
+ - **Waiting for you**: the session asked you something (a question card, the question in the
101
+ desktop app's "next step" box, or, in a terminal, a turn that ends with a question) and you have
102
+ not answered, or the app marked it as blocked on you and its last words are a question. This
103
+ wins over every other state. When the app says "blocked" but nothing was asked ("send me the
104
+ screenshot when they reply"), the card is Done with a "Next step is yours" line instead.
105
+ - **Working**: a turn is running. In a terminal, a turn with no progress for 90 s says it may be
106
+ waiting for your permission.
107
+ - **Running checks**: the turn is over but a job it started in the background has not reported
108
+ back yet, so the work is not finished.
109
+ - **Done**: the turn is over and nothing is pending, with the session's own words on what it did.
110
+ Sessions done for more than 14 days go into a closed "Older sessions" box. (The desktop app also
111
+ labels many finished turns "ready for review"; the hub does not repeat that label, because a
112
+ session that really needs you asks a question, and then it is "Waiting for you".)
113
+ A terminal session whose `claude` has exited is Done too, even if it ended on a question:
114
+ nobody can answer it any more. The card keeps the question ("Closed before you answered").
115
+
116
+ **Handoff notes.** A session's note is the note-like Markdown file it wrote most often: any `.md`
117
+ in the desktop app's shared notes folder, or a file named like a note elsewhere (`HANDOFF.md`,
118
+ `NOTES.md`, `progress.md`…). Writes count whether made with Write/Edit or from the shell; reads
119
+ never count.
120
+
121
+ **Tokens.** Each answer is counted once, even when it is copied into a resumed or forked
122
+ transcript; sub-agents count toward their parent session. Most tokens are usually cache reads
123
+ (Claude re-reading the conversation), which weigh much less on plan limits than new text. The
124
+ "≈ $ at API prices" figure is what Claude Code itself computes; on a Pro or Max plan you do not
125
+ pay it.
126
+
127
+ **Commits.** Git does not record which session wrote a commit, and commits are often rebased
128
+ before they reach `main` (new hash, same subject). The hub reads the commits each session made
129
+ from the reflog of the worktree it works in and matches them to the main branch by subject. When
130
+ several sessions share one checkout, a commit goes to the session that ran `git commit` there just
131
+ before. Merge commits are not counted.
132
+
133
+ **Plan limits.** The desktop app saves them only now and then, so the page always says when the
134
+ reading was taken; a 5-hour reading older than 5 hours is not shown, since that window has reset.
135
+
136
+ **Tokens this week.** Anthropic does not say how many tokens a plan allows, and the app saves only
137
+ percentages. The hub finds when your week starts again from the readings (the weekly percent drops
138
+ at the same time every week), adds up the tokens used since then, and estimates 100% as the median
139
+ of "tokens so far ÷ percent" over the readings of the last 3 weeks. It is an estimate: the limit is
140
+ not counted in plain tokens (models weigh differently), and chats on claude.ai or other devices use
141
+ the same limit without showing up here.
142
+
143
+ ## Limits
144
+
145
+ - Used daily on **macOS** with the Claude desktop app. The tests run on macOS, Linux and Windows
146
+ (Python 3.9 and 3.13), but real use on Linux and Windows is still untested: reports welcome.
147
+ - The desktop app's session files are not a documented format, so an app update may change them.
148
+ Terminal sessions rely on Claude Code transcripts and its running-session files.
149
+ - If something looks wrong, please open an issue with what the page showed and what you expected.
150
+
151
+ ## Development
152
+
153
+ ```bash
154
+ PYTHONPATH=src python3 -m unittest discover -s tests
155
+ ```
156
+
157
+ The tests build small fake transcripts, notes and git repositories; they never read your data.
158
+
159
+ ## License
160
+
161
+ [MIT](LICENSE). Not affiliated with or endorsed by Anthropic. "Claude" is a trademark of Anthropic.
@@ -0,0 +1,142 @@
1
+ # Claude Session Hub
2
+
3
+ [![tests](https://github.com/lolloi/claude-session-hub/actions/workflows/tests.yml/badge.svg)](https://github.com/lolloi/claude-session-hub/actions/workflows/tests.yml)
4
+
5
+ **See all your Claude Code sessions in one page, and know at a glance which one is waiting for you.**
6
+
7
+ If you run several Claude Code sessions at once (one per feature, one per role…), it is easy to
8
+ lose track: which one is still working, which one is only running tests, which one finished, and
9
+ **which one has been waiting for your answer for twenty minutes**. Claude Session Hub reads the
10
+ files Claude already writes on your computer and shows it all on a local page, with an optional
11
+ notification when a session needs you.
12
+
13
+ ![Claude Session Hub: a session finishes and asks a question, a handoff note opens, then tokens and commits](https://raw.githubusercontent.com/lolloi/claude-session-hub/main/docs/demo.gif)
14
+
15
+ *The built-in demo (`--demo`): made-up sessions, no real data. Here "Checkout API" finishes its turn
16
+ with a question and moves to the top as "Waiting for you".*
17
+
18
+ ## What you see
19
+
20
+ - **Who is waiting for you**, on top, with the question in the session's own words, and a
21
+ notification if you want one. If a session tells you to answer in another session's window,
22
+ the card says so.
23
+ - **What each session is doing**: working, running checks in the background (tests, a build),
24
+ or done.
25
+ - **Its last handoff note**, if it keeps one (click to read it whole).
26
+ - **Tokens** per session and per day for the last 14 days.
27
+ - **Commits each session landed on the main branch**, even after a rebase.
28
+ - **Plan limits** (5-hour and weekly windows), as last seen by the Claude desktop app, with the
29
+ tokens used this week and an estimate of how many make 100%.
30
+
31
+ It works with sessions in the **Claude desktop app** (Code tab) and with sessions started with
32
+ **`claude` in a terminal**.
33
+
34
+ ## Run it
35
+
36
+ Needs Python 3.9 or newer and git 2.31 or newer. No other dependencies.
37
+
38
+ ```bash
39
+ pipx install claude-session-hub
40
+ claude-session-hub
41
+ ```
42
+
43
+ The page opens at <http://127.0.0.1:4777>. To try it without your own sessions:
44
+
45
+ ```bash
46
+ claude-session-hub --demo
47
+ ```
48
+
49
+ Other ways: `uvx claude-session-hub` runs it without installing; `python3 -m pip install claude-session-hub`
50
+ works too where your Python allows it (inside a virtual environment, for example). From a clone of
51
+ this repository: `PYTHONPATH=src python3 -m claude_session_hub`.
52
+
53
+ Options: `--port 4777`, `--no-open`, `--archived` (also archived desktop sessions), `--demo`,
54
+ `--json` (print one snapshot and exit).
55
+
56
+ ## Privacy
57
+
58
+ - **Read-only.** It only reads files Claude and git already have on your computer, and runs only
59
+ read-only git commands.
60
+ - **Local.** The page is served on `127.0.0.1` only. Nothing is sent anywhere, there are no API
61
+ calls and nothing costs money.
62
+ - **One file of its own**: `~/.cache/claude-session-hub/usage-v1.json`, token counts per
63
+ transcript so the page has numbers as soon as it opens. Delete it any time; set
64
+ `CLAUDE_SESSION_HUB_CACHE` to move it.
65
+
66
+ ## How it works
67
+
68
+ | Source | Where | Used for |
69
+ |---|---|---|
70
+ | Claude desktop app, Code sessions | `~/Library/Application Support/Claude/claude-code-sessions/` | name, model, folder, branch, the app's summary of the last turn |
71
+ | Claude Code transcripts, end of each file | `~/.claude/projects/*/*.jsonl` (last 16 MB the first time, then only new lines) | is a turn running, is a question waiting, background jobs, the session's last words |
72
+ | Transcripts of terminal sessions | `~/.claude/projects/*/*.jsonl` changed in the last 30 days | sessions started with `claude` in a terminal |
73
+ | Running Claude Code sessions | `~/.claude/sessions/<pid>.json` (and whether that process still runs) | a terminal session whose `claude` has exited is Done, not waiting |
74
+ | Transcripts, whole files | `~/.claude/projects/**/*.jsonl` (only new bytes are read) | tokens per session and per day, notes written, `git commit` times |
75
+ | Git history of each session's repository | worktree reflogs and `git log <main branch>` | commits each session landed on the main branch |
76
+ | Shared notes of Code sessions | `~/Library/Application Support/Claude/side-session-notes/` | each session's handoff note |
77
+ | Plan usage seen by the desktop app | `~/Library/Application Support/Claude/plan-usage-history.json` | 5-hour and weekly limits |
78
+
79
+ **States.**
80
+
81
+ - **Waiting for you**: the session asked you something (a question card, the question in the
82
+ desktop app's "next step" box, or, in a terminal, a turn that ends with a question) and you have
83
+ not answered, or the app marked it as blocked on you and its last words are a question. This
84
+ wins over every other state. When the app says "blocked" but nothing was asked ("send me the
85
+ screenshot when they reply"), the card is Done with a "Next step is yours" line instead.
86
+ - **Working**: a turn is running. In a terminal, a turn with no progress for 90 s says it may be
87
+ waiting for your permission.
88
+ - **Running checks**: the turn is over but a job it started in the background has not reported
89
+ back yet, so the work is not finished.
90
+ - **Done**: the turn is over and nothing is pending, with the session's own words on what it did.
91
+ Sessions done for more than 14 days go into a closed "Older sessions" box. (The desktop app also
92
+ labels many finished turns "ready for review"; the hub does not repeat that label, because a
93
+ session that really needs you asks a question, and then it is "Waiting for you".)
94
+ A terminal session whose `claude` has exited is Done too, even if it ended on a question:
95
+ nobody can answer it any more. The card keeps the question ("Closed before you answered").
96
+
97
+ **Handoff notes.** A session's note is the note-like Markdown file it wrote most often: any `.md`
98
+ in the desktop app's shared notes folder, or a file named like a note elsewhere (`HANDOFF.md`,
99
+ `NOTES.md`, `progress.md`…). Writes count whether made with Write/Edit or from the shell; reads
100
+ never count.
101
+
102
+ **Tokens.** Each answer is counted once, even when it is copied into a resumed or forked
103
+ transcript; sub-agents count toward their parent session. Most tokens are usually cache reads
104
+ (Claude re-reading the conversation), which weigh much less on plan limits than new text. The
105
+ "≈ $ at API prices" figure is what Claude Code itself computes; on a Pro or Max plan you do not
106
+ pay it.
107
+
108
+ **Commits.** Git does not record which session wrote a commit, and commits are often rebased
109
+ before they reach `main` (new hash, same subject). The hub reads the commits each session made
110
+ from the reflog of the worktree it works in and matches them to the main branch by subject. When
111
+ several sessions share one checkout, a commit goes to the session that ran `git commit` there just
112
+ before. Merge commits are not counted.
113
+
114
+ **Plan limits.** The desktop app saves them only now and then, so the page always says when the
115
+ reading was taken; a 5-hour reading older than 5 hours is not shown, since that window has reset.
116
+
117
+ **Tokens this week.** Anthropic does not say how many tokens a plan allows, and the app saves only
118
+ percentages. The hub finds when your week starts again from the readings (the weekly percent drops
119
+ at the same time every week), adds up the tokens used since then, and estimates 100% as the median
120
+ of "tokens so far ÷ percent" over the readings of the last 3 weeks. It is an estimate: the limit is
121
+ not counted in plain tokens (models weigh differently), and chats on claude.ai or other devices use
122
+ the same limit without showing up here.
123
+
124
+ ## Limits
125
+
126
+ - Used daily on **macOS** with the Claude desktop app. The tests run on macOS, Linux and Windows
127
+ (Python 3.9 and 3.13), but real use on Linux and Windows is still untested: reports welcome.
128
+ - The desktop app's session files are not a documented format, so an app update may change them.
129
+ Terminal sessions rely on Claude Code transcripts and its running-session files.
130
+ - If something looks wrong, please open an issue with what the page showed and what you expected.
131
+
132
+ ## Development
133
+
134
+ ```bash
135
+ PYTHONPATH=src python3 -m unittest discover -s tests
136
+ ```
137
+
138
+ The tests build small fake transcripts, notes and git repositories; they never read your data.
139
+
140
+ ## License
141
+
142
+ [MIT](LICENSE). Not affiliated with or endorsed by Anthropic. "Claude" is a trademark of Anthropic.
@@ -0,0 +1,35 @@
1
+ [build-system]
2
+ requires = ["setuptools>=77"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "claude-session-hub"
7
+ version = "0.1.1"
8
+ description = "A local dashboard for all your Claude Code sessions: who is working, who is waiting for you."
9
+ readme = "README.md"
10
+ license = "MIT"
11
+ license-files = ["LICENSE"]
12
+ authors = [{ name = "lolloi" }]
13
+ requires-python = ">=3.9"
14
+ dependencies = []
15
+ keywords = ["claude", "claude-code", "dashboard", "sessions", "anthropic"]
16
+ classifiers = [
17
+ "Programming Language :: Python :: 3",
18
+ "Environment :: Web Environment",
19
+ "Operating System :: OS Independent",
20
+ "Topic :: Software Development",
21
+ "Intended Audience :: Developers",
22
+ ]
23
+
24
+ [project.urls]
25
+ Homepage = "https://github.com/lolloi/claude-session-hub"
26
+ Issues = "https://github.com/lolloi/claude-session-hub/issues"
27
+
28
+ [project.scripts]
29
+ claude-session-hub = "claude_session_hub.cli:main"
30
+
31
+ [tool.setuptools.packages.find]
32
+ where = ["src"]
33
+
34
+ [tool.setuptools.package-data]
35
+ claude_session_hub = ["static/*"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,3 @@
1
+ """Claude Session Hub: a local dashboard for your Claude Code sessions."""
2
+
3
+ __version__ = "0.1.1"
@@ -0,0 +1,3 @@
1
+ from .cli import main
2
+
3
+ raise SystemExit(main())
@@ -0,0 +1,66 @@
1
+ """Command line entry point: ``claude-session-hub``."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import json
7
+ import sys
8
+ import webbrowser
9
+
10
+ from . import __version__, sessions
11
+ from .server import serve
12
+
13
+
14
+ def main(argv=None) -> int:
15
+ p = argparse.ArgumentParser(
16
+ prog="claude-session-hub",
17
+ description="A local dashboard for all your Claude Code sessions. Read-only, nothing leaves your computer.",
18
+ )
19
+ p.add_argument("--port", type=int, default=4777, help="port on 127.0.0.1 (default 4777)")
20
+ p.add_argument("--no-open", action="store_true", help="do not open the browser")
21
+ p.add_argument("--archived", action="store_true", help="also show archived sessions")
22
+ p.add_argument("--json", action="store_true", help="print one snapshot as JSON and exit")
23
+ p.add_argument("--demo", action="store_true", help="show made-up sessions instead of yours (to try it out)")
24
+ p.add_argument("--version", action="version", version=__version__)
25
+ args = p.parse_args(argv)
26
+
27
+ demo_dir = None
28
+ if args.demo:
29
+ from .demo import prepare
30
+
31
+ demo_dir = prepare() # noqa: F841 (kept alive until the program ends)
32
+
33
+ if args.json:
34
+ from .usage import UsageIndex
35
+
36
+ from .usage import refresh_commits
37
+
38
+ index = UsageIndex()
39
+ index.refresh()
40
+ refresh_commits(index)
41
+ text = json.dumps(sessions.snapshot(args.archived, index), ensure_ascii=False, indent=2) + "\n"
42
+ # Bytes, so a Windows console in cp1252 does not fail on "·" or "→".
43
+ sys.stdout.buffer.write(text.encode("utf-8"))
44
+ sys.stdout.flush()
45
+ return 0
46
+
47
+ try:
48
+ httpd = serve(args.port, args.archived)
49
+ except OSError as exc:
50
+ print(f"Cannot use port {args.port}: {exc}. Try --port 4778.", file=sys.stderr)
51
+ return 1
52
+ url = f"http://127.0.0.1:{args.port}/"
53
+ print(f"Claude Session Hub on {url} (Ctrl+C to stop)")
54
+ if not args.no_open:
55
+ webbrowser.open(url)
56
+ try:
57
+ httpd.serve_forever()
58
+ except KeyboardInterrupt:
59
+ pass
60
+ finally:
61
+ httpd.server_close()
62
+ return 0
63
+
64
+
65
+ if __name__ == "__main__":
66
+ raise SystemExit(main())
@@ -0,0 +1,204 @@
1
+ """Which session made each commit that reached the main branch.
2
+
3
+ Git does not record which Claude session wrote a commit, and commits are often
4
+ rebased before they reach ``main`` (new hash, same subject). So:
5
+
6
+ 1. every commit a session made is read from the reflog of the git worktree it
7
+ works in (``.git/worktrees/<name>/logs/HEAD``, or ``.git/logs/HEAD`` for the
8
+ main checkout). A worktree used by one session belongs to it; when several
9
+ sessions share a checkout, the commit goes to the session that ran
10
+ ``git commit`` there shortly before (from the transcripts);
11
+ 2. the commits on ``main`` are matched to those by subject line.
12
+
13
+ Only ``git`` read commands are run; nothing is written.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import os
19
+ import subprocess
20
+ import time
21
+ from functools import lru_cache
22
+ from pathlib import Path
23
+ from typing import Dict, Iterable, List, Optional, Tuple
24
+
25
+ DAYS = 14
26
+ MATCH_WINDOW_S = 20 * 60 # a commit up to 20 min after `git commit` was started (hooks, tests...)
27
+ REFLOG_KINDS = ("commit:", "commit (amend):", "commit (initial):")
28
+
29
+
30
+ def git(args: List[str], cwd: str, timeout: float = 10.0) -> Optional[str]:
31
+ try:
32
+ out = subprocess.run(["git", *args], cwd=cwd, capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=timeout,
33
+ env={**os.environ, "GIT_OPTIONAL_LOCKS": "0", "LC_ALL": "C"})
34
+ except (OSError, subprocess.SubprocessError):
35
+ return None
36
+ return out.stdout if out.returncode == 0 else None
37
+
38
+
39
+ def repo_of(folder: str) -> Optional[Tuple[str, str]]:
40
+ """(main checkout path, common git dir) of the repository containing ``folder``."""
41
+ if not folder or not os.path.isdir(folder):
42
+ return None
43
+ out = git(["rev-parse", "--path-format=absolute", "--git-common-dir", "--show-toplevel"], folder)
44
+ if not out:
45
+ return None
46
+ lines = out.strip().splitlines()
47
+ if len(lines) < 2:
48
+ return None
49
+ common = lines[0]
50
+ root = str(Path(common).parent) if Path(common).name == ".git" else lines[1]
51
+ return root, common
52
+
53
+
54
+ def main_branch(root: str) -> Optional[str]:
55
+ out = git(["symbolic-ref", "--quiet", "--short", "refs/remotes/origin/HEAD"], root)
56
+ if out and out.strip():
57
+ return out.strip().split("/", 1)[-1]
58
+ for name in ("main", "master"):
59
+ if git(["rev-parse", "--verify", "--quiet", f"refs/heads/{name}"], root) is not None:
60
+ return name
61
+ return None
62
+
63
+
64
+ def worktrees(root: str, common: str) -> Dict[str, str]:
65
+ """worktree path -> its reflog file."""
66
+ out = git(["worktree", "list", "--porcelain"], root) or ""
67
+ result = {}
68
+ for block in out.split("\n\n"):
69
+ path = next((ln[9:] for ln in block.splitlines() if ln.startswith("worktree ")), None)
70
+ if not path:
71
+ continue
72
+ if os.path.realpath(path) == os.path.realpath(root):
73
+ result[path] = os.path.join(common, "logs", "HEAD")
74
+ else:
75
+ gitfile = os.path.join(path, ".git")
76
+ try:
77
+ gitdir = Path(gitfile).read_text(encoding="utf-8").split("gitdir:", 1)[1].strip()
78
+ except (OSError, IndexError):
79
+ gitdir = os.path.join(common, "worktrees", os.path.basename(path))
80
+ result[path] = os.path.join(gitdir, "logs", "HEAD")
81
+ return result
82
+
83
+
84
+ def read_reflog(path: str, since: float) -> List[Tuple[float, str]]:
85
+ """(unix time, subject) of the commits made in one worktree."""
86
+ out = []
87
+ try:
88
+ fh = open(path, "r", encoding="utf-8", errors="replace")
89
+ except OSError:
90
+ return out
91
+ with fh:
92
+ for line in fh:
93
+ head, _, msg = line.rstrip("\n").partition("\t")
94
+ kind = next((k for k in REFLOG_KINDS if msg.startswith(k)), None)
95
+ if not kind:
96
+ continue
97
+ parts = head.split()
98
+ try:
99
+ ts = float(parts[-2])
100
+ except (IndexError, ValueError):
101
+ continue
102
+ if ts >= since:
103
+ out.append((ts, msg[len(kind):].strip()))
104
+ return out
105
+
106
+
107
+ @lru_cache(maxsize=4096)
108
+ def _real(path: str) -> str:
109
+ return os.path.realpath(path)
110
+
111
+
112
+ def inside(folder: str, path: str) -> bool:
113
+ a, b = _real(folder), _real(path)
114
+ return a == b or a.startswith(b.rstrip(os.sep) + os.sep)
115
+
116
+
117
+ class CommitIndex:
118
+ def __init__(self, clock=time.time):
119
+ self.clock = clock
120
+ self.result: dict = {"repos": [], "per_session": {}, "today": {}, "unmatched_today": 0}
121
+
122
+ def refresh(self, sessions: Iterable, commit_calls: Dict[str, List[Tuple[float, str]]]) -> dict:
123
+ """``sessions``: objects with ``id`` and ``folder``.
124
+ ``commit_calls``: session id -> [(unix time, cwd)] of ``git commit`` commands it ran."""
125
+ now = self.clock()
126
+ since = now - DAYS * 86400
127
+ today = time.strftime("%Y-%m-%d", time.localtime(now))
128
+ sessions = [s for s in sessions if s.folder]
129
+ repos: Dict[str, str] = {}
130
+ for s in sessions:
131
+ r = repo_of(s.folder)
132
+ if r:
133
+ repos[r[0]] = r[1]
134
+
135
+ per_session: Dict[str, dict] = {}
136
+ today_counts: Dict[str, int] = {}
137
+ unmatched_today = 0
138
+ repo_names = []
139
+ for root, common in repos.items():
140
+ branch = main_branch(root)
141
+ if not branch:
142
+ continue
143
+ repo_names.append({"path": root, "branch": branch})
144
+ claims: Dict[str, List[Tuple[float, str]]] = {}
145
+ wts = worktrees(root, common)
146
+ home: Dict[str, List] = {}
147
+ for s in sessions:
148
+ best = max((w for w in wts if inside(s.folder, w)), key=len, default=None)
149
+ if best:
150
+ home.setdefault(best, []).append(s)
151
+ for wt, reflog in wts.items():
152
+ for ts, subject in read_reflog(reflog, since):
153
+ owner = self._owner(ts, wt, home.get(wt, []), commit_calls)
154
+ if owner:
155
+ claims.setdefault(subject, []).append((ts, owner))
156
+ log = git(["log", branch, "--no-merges", f"--since={int(since)}", "--format=%H%x1f%h%x1f%ct%x1f%s"], root)
157
+ for line in (log or "").splitlines():
158
+ try:
159
+ full, short, ct, subject = line.split("\x1f", 3)
160
+ except ValueError:
161
+ continue
162
+ ts = float(ct)
163
+ owner = self._match(subject, ts, claims)
164
+ day = time.strftime("%Y-%m-%d", time.localtime(ts))
165
+ if not owner:
166
+ if day == today:
167
+ unmatched_today += 1
168
+ continue
169
+ agg = per_session.setdefault(owner, {"today": 0, "week": 0, "recent": []})
170
+ if day == today:
171
+ agg["today"] += 1
172
+ today_counts[owner] = today_counts.get(owner, 0) + 1
173
+ if ts >= now - 7 * 86400:
174
+ agg["week"] += 1
175
+ if len(agg["recent"]) < 3:
176
+ agg["recent"].append({"hash": short, "subject": subject, "time": ts, "repo": os.path.basename(root),
177
+ "branch": branch})
178
+ self.result = {"repos": repo_names, "per_session": per_session, "today": today_counts,
179
+ "unmatched_today": unmatched_today}
180
+ return self.result
181
+
182
+ @staticmethod
183
+ def _owner(ts: float, wt: str, here: list, commit_calls: Dict[str, list]) -> Optional[str]:
184
+ if len(here) == 1:
185
+ return here[0].id
186
+ best = None
187
+ for s in here:
188
+ for call_ts, cwd in commit_calls.get(s.id, []):
189
+ if cwd and not inside(cwd, wt):
190
+ continue
191
+ if call_ts - 5 <= ts <= call_ts + MATCH_WINDOW_S:
192
+ gap = ts - call_ts
193
+ if best is None or gap < best[0]:
194
+ best = (gap, s.id)
195
+ return best[1] if best else None
196
+
197
+ @staticmethod
198
+ def _match(subject: str, ts: float, claims: Dict[str, list]) -> Optional[str]:
199
+ options = claims.get(subject)
200
+ if not options:
201
+ return None
202
+ before = [o for o in options if o[0] <= ts + 60]
203
+ pick = max(before) if before else min(options)
204
+ return pick[1]