mcp-session-registry 0.2.0__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.
@@ -0,0 +1,10 @@
1
+ version: 2
2
+ updates:
3
+ - package-ecosystem: pip
4
+ directory: /
5
+ schedule:
6
+ interval: weekly
7
+ - package-ecosystem: github-actions
8
+ directory: /
9
+ schedule:
10
+ interval: weekly
@@ -0,0 +1,34 @@
1
+ name: CI
2
+
3
+ on:
4
+ push:
5
+ branches: [main]
6
+ pull_request:
7
+ branches: [main]
8
+
9
+ jobs:
10
+ test:
11
+ runs-on: ubuntu-latest
12
+ strategy:
13
+ matrix:
14
+ python-version: ["3.11", "3.12", "3.13"]
15
+ steps:
16
+ - uses: actions/checkout@v6
17
+ - uses: astral-sh/setup-uv@v7
18
+ - name: Install dependencies
19
+ run: uv venv && uv pip install -e . && uv pip install pytest ruff
20
+ - name: Lint
21
+ run: uv run ruff check src/ tests/
22
+ - name: Test with coverage
23
+ run: |
24
+ uv pip install pytest-cov
25
+ uv run pytest tests/ -v --cov=src/mcp_session_registry --cov-report=term --cov-fail-under=60
26
+
27
+ security:
28
+ runs-on: ubuntu-latest
29
+ steps:
30
+ - uses: actions/checkout@v4
31
+ - name: Security check (bandit)
32
+ run: |
33
+ pip install bandit
34
+ bandit -r src/ -ll -ii --skip B608
@@ -0,0 +1,17 @@
1
+ name: CodeQL
2
+ on:
3
+ push:
4
+ branches: [main]
5
+ pull_request:
6
+ branches: [main]
7
+ jobs:
8
+ analyze:
9
+ runs-on: ubuntu-latest
10
+ permissions:
11
+ security-events: write
12
+ steps:
13
+ - uses: actions/checkout@v4
14
+ - uses: github/codeql-action/init@v4
15
+ with:
16
+ languages: python
17
+ - uses: github/codeql-action/analyze@v4
@@ -0,0 +1,14 @@
1
+ name: Publish to PyPI
2
+ on:
3
+ push:
4
+ tags: ['v*']
5
+ jobs:
6
+ publish:
7
+ runs-on: ubuntu-latest
8
+ permissions:
9
+ id-token: write
10
+ steps:
11
+ - uses: actions/checkout@v6
12
+ - uses: astral-sh/setup-uv@v7
13
+ - run: uv build
14
+ - run: uv publish --trusted-publishing always
@@ -0,0 +1,14 @@
1
+ name: Stale
2
+ on:
3
+ schedule:
4
+ - cron: "0 10 * * 1"
5
+ jobs:
6
+ stale:
7
+ runs-on: ubuntu-latest
8
+ steps:
9
+ - uses: actions/stale@v10
10
+ with:
11
+ days-before-stale: 90
12
+ days-before-close: 30
13
+ stale-issue-message: "Esta issue está inativa há 90 dias"
14
+ stale-pr-message: "Este PR está inativo há 90 dias"
@@ -0,0 +1,11 @@
1
+ __pycache__/
2
+ *.py[cod]
3
+ *.egg-info/
4
+ dist/
5
+ build/
6
+ .venv/
7
+ *.db
8
+ *.db-wal
9
+ *.db-shm
10
+ .pytest_cache/
11
+ .ruff_cache/
@@ -0,0 +1,64 @@
1
+ # AGENTS.md — mcp-session-registry
2
+
3
+ ## Project Overview
4
+
5
+ Lightweight MCP server providing multi-session awareness. Sessions register presence, claim files, and query conflicts. SQLite storage, Streamable HTTP transport, Python.
6
+
7
+ ## Architecture
8
+
9
+ ```
10
+ src/mcp_session_registry/
11
+ ├── __init__.py # Version
12
+ ├── server.py # MCP server setup + main() entrypoint
13
+ ├── db.py # SQLite schema, connection, queries
14
+ ├── models.py # Pydantic models (Session, Claim)
15
+ └── reaper.py # Background task: expire dead sessions
16
+ tests/
17
+ ├── test_db.py # Unit tests for database layer
18
+ ├── test_server.py # Integration tests for MCP tools
19
+ └── conftest.py # Fixtures (temp DB, test client)
20
+ ```
21
+
22
+ ## Data Flow
23
+
24
+ ```
25
+ CLI Hook (AgentSpawn) → session_register → SQLite → session_list ← Other sessions
26
+ → session_conflicts ← Other sessions
27
+ CLI Hook (Stop) → session_end → SQLite (delete)
28
+ Background reaper → every 60s → delete sessions with heartbeat > 5min ago
29
+ ```
30
+
31
+ ## Key Conventions
32
+
33
+ - **Config**: env vars only (`MSR_PORT=3203`, `MSR_DB_PATH=...`, `MCP_TRANSPORT=streamable-http`)
34
+ - **Errors**: raise McpError with human-readable message
35
+ - **IDs**: UUID4 for session_id, string paths for claims
36
+ - **Timestamps**: UTC ISO 8601, stored as TEXT in SQLite
37
+ - **Logging**: stdlib logging, level via `MSR_LOG_LEVEL`
38
+ - **No external deps** beyond mcp SDK + uvicorn
39
+
40
+ ## Adding a New Tool
41
+
42
+ 1. Define Pydantic input model in `models.py`
43
+ 2. Add SQL query in `db.py`
44
+ 3. Register tool in `server.py` with `@mcp.tool()`
45
+ 4. Add test in `tests/test_server.py`
46
+ 5. Update PRD.md tool table
47
+
48
+ ## Tests
49
+
50
+ ```bash
51
+ uv run pytest # all tests
52
+ uv run pytest -x # stop on first failure
53
+ uv run pytest tests/test_db.py # just DB layer
54
+ ```
55
+
56
+ ## Running
57
+
58
+ ```bash
59
+ # Development
60
+ MSR_PORT=3203 uv run mcp-session-registry
61
+
62
+ # Production (systemd)
63
+ systemctl --user start session-registry.service
64
+ ```
@@ -0,0 +1,24 @@
1
+ # Changelog
2
+
3
+ All notable changes documented here. Format: [Keep a Changelog](https://keepachangelog.com/).
4
+
5
+ ## [0.2.0] - 2026-06-23
6
+
7
+ ### Added
8
+ - `/health` endpoint via `@mcp.custom_route` (GET, returns status/version/uptime)
9
+
10
+ ### Fixed
11
+ - Lint E402: moved `import time` to top of module
12
+
13
+ ## [0.1.1] - 2026-06-19
14
+
15
+ ### Added
16
+ - Version bump for /health endpoint (never committed - fixed in 0.2.0)
17
+
18
+ ## [0.1.0] - 2026-05-21
19
+
20
+ ### Added
21
+ - Initial release: session_register, session_list, session_heartbeat, session_end, session_claim, session_release, session_conflicts
22
+ - SQLite storage with heartbeat-based liveness detection
23
+ - Stale session reaping (>5min without heartbeat)
24
+ - StreamableHTTP transport on configurable port (MSR_PORT)
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,22 @@
1
+ # MEMORY.md — mcp-session-registry
2
+
3
+ ## Estado Atual
4
+
5
+ - **Versão**: 0.1.0 (em desenvolvimento)
6
+ - **Criado**: 21/mai/2026
7
+ - **Motivação**: 4 sessões Kiro CLI cegas entre si na DNBSCDC289
8
+
9
+ ## Decisões
10
+
11
+ - Porta 3203 (após task-orch 3201, memory 3202)
12
+ - SQLite WAL mode, DB em ~/.local/share/mcp-session-registry/sessions.db
13
+ - Heartbeat timeout: 5 minutos
14
+ - Claims são advisory (não enforced)
15
+ - Streamable HTTP transport (consistente com outros MCPs)
16
+
17
+ ## Próximo
18
+
19
+ - Implementar schema + models
20
+ - Implementar server com 7 tools
21
+ - Testes
22
+ - Integrar via hooks Kiro CLI
@@ -0,0 +1,140 @@
1
+ Metadata-Version: 2.4
2
+ Name: mcp-session-registry
3
+ Version: 0.2.0
4
+ Summary: MCP server for multi-session awareness and coordination
5
+ Project-URL: Homepage, https://github.com/filhocf/mcp-session-registry
6
+ Project-URL: Repository, https://github.com/filhocf/mcp-session-registry
7
+ Project-URL: Changelog, https://github.com/filhocf/mcp-session-registry/blob/main/CHANGELOG.md
8
+ Author-email: Claudio Ferreira Filho <filhocf@gmail.com>
9
+ License-Expression: Apache-2.0
10
+ License-File: LICENSE
11
+ Keywords: awareness,coordination,mcp,multi-agent,session
12
+ Classifier: Development Status :: 3 - Alpha
13
+ Classifier: License :: OSI Approved :: Apache Software License
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3.11
16
+ Classifier: Programming Language :: Python :: 3.12
17
+ Classifier: Programming Language :: Python :: 3.13
18
+ Requires-Python: >=3.11
19
+ Requires-Dist: mcp>=1.9.0
20
+ Requires-Dist: uvicorn>=0.34.0
21
+ Description-Content-Type: text/markdown
22
+
23
+ # mcp-session-registry
24
+
25
+ [![CI](https://github.com/filhocf/mcp-session-registry/actions/workflows/ci.yml/badge.svg)](https://github.com/filhocf/mcp-session-registry/actions/workflows/ci.yml)
26
+ [![Python 3.11+](https://img.shields.io/badge/python-3.11%2B-blue)](https://www.python.org/downloads/)
27
+ [![License: Apache-2.0](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](LICENSE)
28
+
29
+ Lightweight MCP server for multi-session awareness — lets AI agents know who else is active on the same machine.
30
+
31
+ ## Why
32
+
33
+ When you run multiple AI CLI sessions (Kiro, Claude Code, Gemini CLI) on the same machine, they are blind to each other. This causes:
34
+
35
+ - **File conflicts** — two sessions editing the same file
36
+ - **Duplicated work** — agents picking up the same task
37
+ - **Wasted context** — no way to know what another session is doing
38
+
39
+ **mcp-session-registry** solves this with a shared presence layer:
40
+
41
+ - Sessions register on spawn, declare a theme, and heartbeat every 2-3 minutes
42
+ - Sessions claim files/resources — other sessions see the claim before touching them
43
+ - Stale sessions (no heartbeat >5min) are automatically reaped
44
+ - Everything persists in SQLite — survives individual session crashes
45
+
46
+ ## Quick Start
47
+
48
+ ```bash
49
+ # Run directly
50
+ uvx mcp-session-registry
51
+
52
+ # Or install
53
+ pip install mcp-session-registry
54
+
55
+ # Configure port (default: 8000)
56
+ MSR_PORT=3203 mcp-session-registry
57
+ ```
58
+
59
+ ## MCP Tools
60
+
61
+ | Tool | Description |
62
+ |------|-------------|
63
+ | `session_register` | Register a new session. Returns `session_id` for subsequent calls. |
64
+ | `session_list` | List all active sessions on this machine. |
65
+ | `session_heartbeat` | Send heartbeat to keep session alive (call every 2-3 min). |
66
+ | `session_end` | Gracefully end a session and release all its claims. |
67
+ | `session_claim` | Claim a resource (file, branch, work item). Advisory lock. |
68
+ | `session_release` | Release a previously claimed resource. |
69
+ | `session_conflicts` | Check if resources are claimed by another active session. |
70
+
71
+ ## How It Works
72
+
73
+ ```
74
+ Session A registers → gets session_id
75
+ Session A claims "src/main.py"
76
+ Session B calls session_conflicts(["src/main.py"])
77
+ → returns: claimed by Session A (pid 1234, theme "refactor auth")
78
+ Session B picks a different file
79
+ ```
80
+
81
+ Sessions that stop sending heartbeats are reaped after 5 minutes — their claims are released automatically.
82
+
83
+ ## Configuration
84
+
85
+ | Environment Variable | Default | Description |
86
+ |---------------------|---------|-------------|
87
+ | `MSR_PORT` | `8000` | HTTP port for StreamableHTTP transport |
88
+ | `MSR_DB_PATH` | `~/.local/share/session-registry/sessions.db` | SQLite database path |
89
+
90
+ ## Integration with Kiro CLI
91
+
92
+ Add to your `~/.kiro/settings/mcp.json`:
93
+
94
+ ```json
95
+ {
96
+ "mcpServers": {
97
+ "session-registry": {
98
+ "url": "http://localhost:3203/mcp",
99
+ "autoApprove": ["session_register", "session_list", "session_heartbeat", "session_end", "session_claim", "session_release", "session_conflicts"]
100
+ }
101
+ }
102
+ }
103
+ ```
104
+
105
+ Run as a systemd user service:
106
+
107
+ ```bash
108
+ # ~/.config/systemd/user/session-registry.service
109
+ [Unit]
110
+ Description=MCP Session Registry
111
+
112
+ [Service]
113
+ ExecStart=%h/.local/bin/mcp-session-registry
114
+ Environment=MSR_PORT=3203
115
+ Restart=on-failure
116
+
117
+ [Install]
118
+ WantedBy=default.target
119
+ ```
120
+
121
+ ## Health Check
122
+
123
+ ```bash
124
+ curl http://localhost:3203/health
125
+ # {"status": "healthy", "version": "0.2.0", "uptime_seconds": 3600}
126
+ ```
127
+
128
+ ## Development
129
+
130
+ ```bash
131
+ git clone https://github.com/filhocf/mcp-session-registry
132
+ cd mcp-session-registry
133
+ uv sync
134
+ uv run pytest tests/ -v
135
+ uv tool run ruff check src/ tests/
136
+ ```
137
+
138
+ ## License
139
+
140
+ Apache-2.0
@@ -0,0 +1,66 @@
1
+ # PRD — mcp-session-registry
2
+
3
+ ## Problem
4
+
5
+ Multiple AI CLI sessions (Kiro CLI, Gemini CLI, Claude Code) running on the same machine are blind to each other. They don't know:
6
+ - That other sessions exist
7
+ - What each session is working on
8
+ - Which files are being modified by another session
9
+
10
+ This causes: file conflicts, duplicated work, contradictory decisions, and wasted context.
11
+
12
+ ## Solution
13
+
14
+ A lightweight MCP server that provides a **shared presence layer** for all CLI sessions on a machine. Any session can register itself, declare what it's working on, claim files, and query what others are doing.
15
+
16
+ ## Personas
17
+
18
+ - **Developer** running 2-4 Kiro CLI sessions in parallel on different themes
19
+ - **AI agent** (via hooks) that auto-registers on spawn and cleans up on stop
20
+ - **Cross-CLI user** running Kiro + Gemini + Claude Code on the same project
21
+
22
+ ## Core Concepts
23
+
24
+ ### Session
25
+ A running CLI instance. Has: id, cli type, hostname, PID, theme/description, status, timestamps.
26
+
27
+ ### Claim
28
+ A file or resource that a session declares ownership of. Advisory (not enforced), but visible to all.
29
+
30
+ ### Heartbeat
31
+ Periodic signal that a session is still alive. Sessions without heartbeat for >5 minutes are considered dead and auto-cleaned.
32
+
33
+ ## Tools (MCP)
34
+
35
+ | Tool | Purpose |
36
+ |------|---------|
37
+ | `session_register` | Register a new session (returns session_id) |
38
+ | `session_list` | List all active sessions |
39
+ | `session_heartbeat` | Keep session alive |
40
+ | `session_end` | Gracefully end a session |
41
+ | `session_claim` | Claim a file/resource |
42
+ | `session_release` | Release a claim |
43
+ | `session_conflicts` | Check if current work conflicts with another session |
44
+
45
+ ## Non-Goals (v0.1)
46
+
47
+ - Cross-machine coordination (future: shared DB via network)
48
+ - Enforced file locking (advisory only)
49
+ - Task assignment between sessions (use task-orchestrator for that)
50
+ - Memory sharing (use memory-service for that)
51
+
52
+ ## Technical Decisions
53
+
54
+ - **Storage**: SQLite (single file, zero config, concurrent-safe with WAL)
55
+ - **Transport**: Streamable HTTP (same as memory-service, task-orchestrator)
56
+ - **Language**: Python (consistent with our stack)
57
+ - **Framework**: MCP SDK (mcp>=1.9.0)
58
+ - **Port**: 3203 (next after task-orchestrator 3201, memory-service 3202)
59
+ - **DB location**: `~/.local/share/mcp-session-registry/sessions.db`
60
+
61
+ ## Success Criteria
62
+
63
+ 1. Session 1 registers → Session 2 can see it via `session_list`
64
+ 2. Session 1 claims `~/git/mir/api/` → Session 2 gets warning via `session_conflicts`
65
+ 3. Session 1 dies (kill -9) → after 5min, auto-cleaned from registry
66
+ 4. Works with Kiro CLI hooks (AgentSpawn → register, Stop → end)
@@ -0,0 +1,118 @@
1
+ # mcp-session-registry
2
+
3
+ [![CI](https://github.com/filhocf/mcp-session-registry/actions/workflows/ci.yml/badge.svg)](https://github.com/filhocf/mcp-session-registry/actions/workflows/ci.yml)
4
+ [![Python 3.11+](https://img.shields.io/badge/python-3.11%2B-blue)](https://www.python.org/downloads/)
5
+ [![License: Apache-2.0](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](LICENSE)
6
+
7
+ Lightweight MCP server for multi-session awareness — lets AI agents know who else is active on the same machine.
8
+
9
+ ## Why
10
+
11
+ When you run multiple AI CLI sessions (Kiro, Claude Code, Gemini CLI) on the same machine, they are blind to each other. This causes:
12
+
13
+ - **File conflicts** — two sessions editing the same file
14
+ - **Duplicated work** — agents picking up the same task
15
+ - **Wasted context** — no way to know what another session is doing
16
+
17
+ **mcp-session-registry** solves this with a shared presence layer:
18
+
19
+ - Sessions register on spawn, declare a theme, and heartbeat every 2-3 minutes
20
+ - Sessions claim files/resources — other sessions see the claim before touching them
21
+ - Stale sessions (no heartbeat >5min) are automatically reaped
22
+ - Everything persists in SQLite — survives individual session crashes
23
+
24
+ ## Quick Start
25
+
26
+ ```bash
27
+ # Run directly
28
+ uvx mcp-session-registry
29
+
30
+ # Or install
31
+ pip install mcp-session-registry
32
+
33
+ # Configure port (default: 8000)
34
+ MSR_PORT=3203 mcp-session-registry
35
+ ```
36
+
37
+ ## MCP Tools
38
+
39
+ | Tool | Description |
40
+ |------|-------------|
41
+ | `session_register` | Register a new session. Returns `session_id` for subsequent calls. |
42
+ | `session_list` | List all active sessions on this machine. |
43
+ | `session_heartbeat` | Send heartbeat to keep session alive (call every 2-3 min). |
44
+ | `session_end` | Gracefully end a session and release all its claims. |
45
+ | `session_claim` | Claim a resource (file, branch, work item). Advisory lock. |
46
+ | `session_release` | Release a previously claimed resource. |
47
+ | `session_conflicts` | Check if resources are claimed by another active session. |
48
+
49
+ ## How It Works
50
+
51
+ ```
52
+ Session A registers → gets session_id
53
+ Session A claims "src/main.py"
54
+ Session B calls session_conflicts(["src/main.py"])
55
+ → returns: claimed by Session A (pid 1234, theme "refactor auth")
56
+ Session B picks a different file
57
+ ```
58
+
59
+ Sessions that stop sending heartbeats are reaped after 5 minutes — their claims are released automatically.
60
+
61
+ ## Configuration
62
+
63
+ | Environment Variable | Default | Description |
64
+ |---------------------|---------|-------------|
65
+ | `MSR_PORT` | `8000` | HTTP port for StreamableHTTP transport |
66
+ | `MSR_DB_PATH` | `~/.local/share/session-registry/sessions.db` | SQLite database path |
67
+
68
+ ## Integration with Kiro CLI
69
+
70
+ Add to your `~/.kiro/settings/mcp.json`:
71
+
72
+ ```json
73
+ {
74
+ "mcpServers": {
75
+ "session-registry": {
76
+ "url": "http://localhost:3203/mcp",
77
+ "autoApprove": ["session_register", "session_list", "session_heartbeat", "session_end", "session_claim", "session_release", "session_conflicts"]
78
+ }
79
+ }
80
+ }
81
+ ```
82
+
83
+ Run as a systemd user service:
84
+
85
+ ```bash
86
+ # ~/.config/systemd/user/session-registry.service
87
+ [Unit]
88
+ Description=MCP Session Registry
89
+
90
+ [Service]
91
+ ExecStart=%h/.local/bin/mcp-session-registry
92
+ Environment=MSR_PORT=3203
93
+ Restart=on-failure
94
+
95
+ [Install]
96
+ WantedBy=default.target
97
+ ```
98
+
99
+ ## Health Check
100
+
101
+ ```bash
102
+ curl http://localhost:3203/health
103
+ # {"status": "healthy", "version": "0.2.0", "uptime_seconds": 3600}
104
+ ```
105
+
106
+ ## Development
107
+
108
+ ```bash
109
+ git clone https://github.com/filhocf/mcp-session-registry
110
+ cd mcp-session-registry
111
+ uv sync
112
+ uv run pytest tests/ -v
113
+ uv tool run ruff check src/ tests/
114
+ ```
115
+
116
+ ## License
117
+
118
+ Apache-2.0
@@ -0,0 +1,46 @@
1
+ [build-system]
2
+ requires = ["hatchling"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "mcp-session-registry"
7
+ version = "0.2.0"
8
+ description = "MCP server for multi-session awareness and coordination"
9
+ readme = "README.md"
10
+ license = "Apache-2.0"
11
+ requires-python = ">=3.11"
12
+ authors = [
13
+ { name = "Claudio Ferreira Filho", email = "filhocf@gmail.com" },
14
+ ]
15
+ keywords = ["mcp", "session", "coordination", "multi-agent", "awareness"]
16
+ classifiers = [
17
+ "Development Status :: 3 - Alpha",
18
+ "License :: OSI Approved :: Apache Software License",
19
+ "Programming Language :: Python :: 3",
20
+ "Programming Language :: Python :: 3.11",
21
+ "Programming Language :: Python :: 3.12",
22
+ "Programming Language :: Python :: 3.13",
23
+ ]
24
+ dependencies = [
25
+ "mcp>=1.9.0",
26
+ "uvicorn>=0.34.0",
27
+ ]
28
+
29
+ [project.scripts]
30
+ mcp-session-registry = "mcp_session_registry.server:main"
31
+
32
+ [project.urls]
33
+ Homepage = 'https://github.com/filhocf/mcp-session-registry'
34
+ Repository = 'https://github.com/filhocf/mcp-session-registry'
35
+ Changelog = 'https://github.com/filhocf/mcp-session-registry/blob/main/CHANGELOG.md'
36
+
37
+ [tool.hatch.build.targets.wheel]
38
+ packages = ["src/mcp_session_registry"]
39
+
40
+ [tool.pytest.ini_options]
41
+ testpaths = ["tests"]
42
+ asyncio_mode = "auto"
43
+
44
+ [tool.ruff]
45
+ target-version = "py311"
46
+ line-length = 120
@@ -0,0 +1,3 @@
1
+ """MCP Session Registry — multi-session awareness and coordination."""
2
+
3
+ __version__ = "0.1.0"
@@ -0,0 +1,153 @@
1
+ """SQLite database layer for session registry."""
2
+
3
+ import sqlite3
4
+ import logging
5
+ from datetime import datetime, timezone, timedelta
6
+ from pathlib import Path
7
+ from typing import Optional
8
+
9
+ from .models import Session, Claim, Conflict
10
+
11
+ logger = logging.getLogger(__name__)
12
+
13
+ DEFAULT_DB_PATH = Path.home() / ".local" / "share" / "mcp-session-registry" / "sessions.db"
14
+ HEARTBEAT_TIMEOUT_SECONDS = 300 # 5 minutes
15
+
16
+
17
+ class SessionDB:
18
+ def __init__(self, db_path: Optional[Path] = None):
19
+ self.db_path = db_path or Path(
20
+ __import__("os").environ.get("MSR_DB_PATH", str(DEFAULT_DB_PATH))
21
+ )
22
+ self.db_path.parent.mkdir(parents=True, exist_ok=True)
23
+ self._init_db()
24
+
25
+ def _get_conn(self) -> sqlite3.Connection:
26
+ conn = sqlite3.connect(str(self.db_path), timeout=10)
27
+ conn.row_factory = sqlite3.Row
28
+ conn.execute("PRAGMA journal_mode=WAL")
29
+ conn.execute("PRAGMA busy_timeout=5000")
30
+ return conn
31
+
32
+ def _init_db(self):
33
+ with self._get_conn() as conn:
34
+ conn.executescript("""
35
+ CREATE TABLE IF NOT EXISTS sessions (
36
+ id TEXT PRIMARY KEY,
37
+ cli TEXT NOT NULL,
38
+ hostname TEXT NOT NULL,
39
+ pid INTEGER NOT NULL,
40
+ theme TEXT DEFAULT '',
41
+ status TEXT DEFAULT 'active',
42
+ started_at TEXT NOT NULL,
43
+ heartbeat_at TEXT NOT NULL
44
+ );
45
+
46
+ CREATE TABLE IF NOT EXISTS claims (
47
+ id TEXT PRIMARY KEY,
48
+ session_id TEXT NOT NULL,
49
+ resource TEXT NOT NULL,
50
+ resource_type TEXT DEFAULT 'file',
51
+ claimed_at TEXT NOT NULL,
52
+ FOREIGN KEY (session_id) REFERENCES sessions(id) ON DELETE CASCADE
53
+ );
54
+
55
+ CREATE INDEX IF NOT EXISTS idx_claims_resource ON claims(resource);
56
+ CREATE INDEX IF NOT EXISTS idx_claims_session ON claims(session_id);
57
+ CREATE INDEX IF NOT EXISTS idx_sessions_status ON sessions(status);
58
+ """)
59
+
60
+ def register(self, session: Session) -> Session:
61
+ with self._get_conn() as conn:
62
+ conn.execute(
63
+ "INSERT INTO sessions (id, cli, hostname, pid, theme, status, started_at, heartbeat_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)",
64
+ (session.id, session.cli, session.hostname, session.pid, session.theme, session.status.value, session.started_at.isoformat(), session.heartbeat_at.isoformat()),
65
+ )
66
+ logger.info(f"Session registered: {session.id} ({session.cli}, pid={session.pid}, theme={session.theme!r})")
67
+ return session
68
+
69
+ def list_active(self) -> list[dict]:
70
+ with self._get_conn() as conn:
71
+ rows = conn.execute(
72
+ "SELECT * FROM sessions WHERE status != 'dead' ORDER BY started_at DESC"
73
+ ).fetchall()
74
+ return [dict(r) for r in rows]
75
+
76
+ def heartbeat(self, session_id: str) -> bool:
77
+ now = datetime.now(timezone.utc).isoformat()
78
+ with self._get_conn() as conn:
79
+ cur = conn.execute(
80
+ "UPDATE sessions SET heartbeat_at = ?, status = 'active' WHERE id = ?",
81
+ (now, session_id),
82
+ )
83
+ return cur.rowcount > 0
84
+
85
+ def end(self, session_id: str) -> bool:
86
+ with self._get_conn() as conn:
87
+ conn.execute("DELETE FROM claims WHERE session_id = ?", (session_id,))
88
+ cur = conn.execute("DELETE FROM sessions WHERE id = ?", (session_id,))
89
+ logger.info(f"Session ended: {session_id}")
90
+ return cur.rowcount > 0
91
+
92
+ def claim(self, claim: Claim) -> Claim:
93
+ with self._get_conn() as conn:
94
+ conn.execute(
95
+ "INSERT OR REPLACE INTO claims (id, session_id, resource, resource_type, claimed_at) VALUES (?, ?, ?, ?, ?)",
96
+ (claim.id, claim.session_id, claim.resource, claim.resource_type, claim.claimed_at.isoformat()),
97
+ )
98
+ logger.info(f"Claim: session={claim.session_id} resource={claim.resource}")
99
+ return claim
100
+
101
+ def release(self, session_id: str, resource: str) -> bool:
102
+ with self._get_conn() as conn:
103
+ cur = conn.execute(
104
+ "DELETE FROM claims WHERE session_id = ? AND resource = ?",
105
+ (session_id, resource),
106
+ )
107
+ return cur.rowcount > 0
108
+
109
+ def get_conflicts(self, session_id: str, resources: list[str]) -> list[Conflict]:
110
+ if not resources:
111
+ return []
112
+ placeholders = ",".join("?" * len(resources))
113
+ with self._get_conn() as conn:
114
+ rows = conn.execute(
115
+ f"""
116
+ SELECT c.resource, c.resource_type, c.claimed_at, c.session_id,
117
+ s.cli, s.theme
118
+ FROM claims c
119
+ JOIN sessions s ON c.session_id = s.id
120
+ WHERE c.resource IN ({placeholders})
121
+ AND c.session_id != ?
122
+ AND s.status != 'dead'
123
+ """,
124
+ (*resources, session_id),
125
+ ).fetchall()
126
+ return [
127
+ Conflict(
128
+ resource=r["resource"],
129
+ resource_type=r["resource_type"],
130
+ claimed_by_session=r["session_id"],
131
+ claimed_by_cli=r["cli"],
132
+ claimed_by_theme=r["theme"],
133
+ claimed_at=datetime.fromisoformat(r["claimed_at"]),
134
+ )
135
+ for r in rows
136
+ ]
137
+
138
+ def reap_dead_sessions(self) -> int:
139
+ """Mark sessions with expired heartbeat as dead and clean their claims."""
140
+ cutoff = (datetime.now(timezone.utc) - timedelta(seconds=HEARTBEAT_TIMEOUT_SECONDS)).isoformat()
141
+ with self._get_conn() as conn:
142
+ dead = conn.execute(
143
+ "SELECT id FROM sessions WHERE heartbeat_at < ? AND status != 'dead'",
144
+ (cutoff,),
145
+ ).fetchall()
146
+ if not dead:
147
+ return 0
148
+ dead_ids = [r["id"] for r in dead]
149
+ placeholders = ",".join("?" * len(dead_ids))
150
+ conn.execute(f"DELETE FROM claims WHERE session_id IN ({placeholders})", dead_ids)
151
+ conn.execute(f"DELETE FROM sessions WHERE id IN ({placeholders})", dead_ids)
152
+ logger.info(f"Reaped {len(dead_ids)} dead sessions")
153
+ return len(dead_ids)
@@ -0,0 +1,59 @@
1
+ """Pydantic models for session registry."""
2
+
3
+ from datetime import datetime, timezone
4
+ from enum import Enum
5
+ from typing import Optional
6
+ from pydantic import BaseModel, Field
7
+ import uuid
8
+
9
+
10
+ class SessionStatus(str, Enum):
11
+ active = "active"
12
+ idle = "idle"
13
+ dead = "dead"
14
+
15
+
16
+ class Session(BaseModel):
17
+ id: str = Field(default_factory=lambda: str(uuid.uuid4()))
18
+ cli: str = Field(description="CLI type: kiro, gemini, claude-code, codex")
19
+ hostname: str
20
+ pid: int
21
+ theme: str = Field(default="", description="What this session is working on")
22
+ status: SessionStatus = SessionStatus.active
23
+ started_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
24
+ heartbeat_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
25
+
26
+
27
+ class Claim(BaseModel):
28
+ id: str = Field(default_factory=lambda: str(uuid.uuid4()))
29
+ session_id: str
30
+ resource: str = Field(description="File path, branch name, or item ID")
31
+ resource_type: str = Field(default="file", description="file, branch, item")
32
+ claimed_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
33
+
34
+
35
+ class Conflict(BaseModel):
36
+ resource: str
37
+ resource_type: str
38
+ claimed_by_session: str
39
+ claimed_by_cli: str
40
+ claimed_by_theme: str
41
+ claimed_at: datetime
42
+
43
+
44
+ class RegisterInput(BaseModel):
45
+ cli: str = Field(description="CLI type: kiro, gemini, claude-code, codex")
46
+ pid: int
47
+ theme: Optional[str] = ""
48
+ hostname: Optional[str] = None
49
+
50
+
51
+ class ClaimInput(BaseModel):
52
+ session_id: str
53
+ resource: str
54
+ resource_type: str = "file"
55
+
56
+
57
+ class ConflictCheckInput(BaseModel):
58
+ session_id: str
59
+ resources: list[str] = Field(description="List of resources to check")
@@ -0,0 +1,141 @@
1
+ """MCP server for session registry."""
2
+
3
+ import asyncio
4
+ import logging
5
+ import os
6
+ import socket
7
+ import time as _time
8
+ from datetime import datetime, timezone
9
+
10
+ from mcp.server.fastmcp import FastMCP
11
+
12
+ from .db import SessionDB
13
+ from .models import Claim, Session
14
+
15
+ logger = logging.getLogger(__name__)
16
+
17
+ mcp = FastMCP("session-registry")
18
+
19
+ _start_time = _time.time()
20
+
21
+ @mcp.custom_route("/health", methods=["GET"])
22
+ async def health_check(request):
23
+ from starlette.responses import JSONResponse
24
+ return JSONResponse({"status": "healthy", "version": "0.2.0", "uptime_seconds": int(_time.time() - _start_time)})
25
+
26
+ db: SessionDB | None = None
27
+
28
+
29
+ def get_db() -> SessionDB:
30
+ global db
31
+ if db is None:
32
+ db = SessionDB()
33
+ return db
34
+
35
+
36
+ @mcp.tool()
37
+ def session_register(cli: str, pid: int, theme: str = "", hostname: str = "") -> dict:
38
+ """Register a new session. Returns session_id for use in heartbeat/end/claim calls."""
39
+ session = Session(
40
+ cli=cli,
41
+ hostname=hostname or socket.gethostname(),
42
+ pid=pid,
43
+ theme=theme,
44
+ )
45
+ get_db().register(session)
46
+ return {"session_id": session.id, "registered_at": session.started_at.isoformat()}
47
+
48
+
49
+ @mcp.tool()
50
+ def session_list() -> dict:
51
+ """List all active sessions on this machine."""
52
+ sessions = get_db().list_active()
53
+ return {"sessions": sessions, "count": len(sessions)}
54
+
55
+
56
+ @mcp.tool()
57
+ def session_heartbeat(session_id: str) -> dict:
58
+ """Send heartbeat to keep session alive. Call every 2-3 minutes."""
59
+ ok = get_db().heartbeat(session_id)
60
+ if not ok:
61
+ return {"success": False, "error": "Session not found"}
62
+ return {"success": True, "heartbeat_at": datetime.now(timezone.utc).isoformat()}
63
+
64
+
65
+ @mcp.tool()
66
+ def session_end(session_id: str) -> dict:
67
+ """Gracefully end a session and release all its claims."""
68
+ ok = get_db().end(session_id)
69
+ return {"success": ok}
70
+
71
+
72
+ @mcp.tool()
73
+ def session_claim(session_id: str, resource: str, resource_type: str = "file") -> dict:
74
+ """Claim a resource (file, branch, item). Advisory — visible to other sessions."""
75
+ claim = Claim(session_id=session_id, resource=resource, resource_type=resource_type)
76
+ get_db().claim(claim)
77
+ return {"claim_id": claim.id, "resource": resource}
78
+
79
+
80
+ @mcp.tool()
81
+ def session_release(session_id: str, resource: str) -> dict:
82
+ """Release a previously claimed resource."""
83
+ ok = get_db().release(session_id, resource)
84
+ return {"success": ok}
85
+
86
+
87
+ @mcp.tool()
88
+ def session_conflicts(session_id: str, resources: list[str]) -> dict:
89
+ """Check if any of the given resources are claimed by another active session."""
90
+ conflicts = get_db().get_conflicts(session_id, resources)
91
+ return {
92
+ "has_conflicts": len(conflicts) > 0,
93
+ "conflicts": [c.model_dump() for c in conflicts],
94
+ }
95
+
96
+
97
+ async def _reaper_loop():
98
+ """Background task to clean up dead sessions every 60 seconds."""
99
+ while True:
100
+ await asyncio.sleep(60)
101
+ try:
102
+ reaped = get_db().reap_dead_sessions()
103
+ if reaped:
104
+ logger.info(f"Reaper: cleaned {reaped} dead sessions")
105
+ except Exception as e:
106
+ logger.error(f"Reaper error: {e}")
107
+
108
+
109
+ def main():
110
+ """Entrypoint for the MCP server."""
111
+ port = int(os.environ.get("MSR_PORT", "3203"))
112
+ transport = os.environ.get("MCP_TRANSPORT", "streamable-http")
113
+ log_level = os.environ.get("MSR_LOG_LEVEL", "INFO")
114
+
115
+ logging.basicConfig(level=getattr(logging, log_level.upper(), logging.INFO))
116
+
117
+ # Initialize DB eagerly
118
+ get_db()
119
+ logger.info(f"Session Registry starting on port {port} (transport={transport})")
120
+
121
+ if transport == "streamable-http":
122
+ mcp.settings.port = port
123
+ mcp.settings.streamable_http_path = "/mcp"
124
+
125
+ # Start reaper as background task
126
+ import threading
127
+
128
+ def run_reaper():
129
+ loop = asyncio.new_event_loop()
130
+ loop.run_until_complete(_reaper_loop())
131
+
132
+ reaper_thread = threading.Thread(target=run_reaper, daemon=True)
133
+ reaper_thread.start()
134
+
135
+ mcp.run(transport="streamable-http")
136
+ else:
137
+ mcp.run(transport="stdio")
138
+
139
+
140
+ if __name__ == "__main__":
141
+ main()
File without changes
@@ -0,0 +1,13 @@
1
+ """Test fixtures."""
2
+
3
+
4
+ import pytest
5
+
6
+ from mcp_session_registry.db import SessionDB
7
+
8
+
9
+ @pytest.fixture
10
+ def tmp_db(tmp_path):
11
+ """Create a temporary database for testing."""
12
+ db_path = tmp_path / "test_sessions.db"
13
+ return SessionDB(db_path=db_path)
@@ -0,0 +1,139 @@
1
+ """Tests for the database layer."""
2
+
3
+ from datetime import datetime, timezone, timedelta
4
+
5
+ from mcp_session_registry.db import SessionDB, HEARTBEAT_TIMEOUT_SECONDS
6
+ from mcp_session_registry.models import Claim, Session
7
+
8
+
9
+ def test_register_and_list(tmp_db: SessionDB):
10
+ session = Session(cli="kiro", hostname="test-host", pid=1234, theme="MIR F013")
11
+ tmp_db.register(session)
12
+
13
+ active = tmp_db.list_active()
14
+ assert len(active) == 1
15
+ assert active[0]["cli"] == "kiro"
16
+ assert active[0]["theme"] == "MIR F013"
17
+ assert active[0]["pid"] == 1234
18
+
19
+
20
+ def test_multiple_sessions(tmp_db: SessionDB):
21
+ for i in range(3):
22
+ s = Session(cli="kiro", hostname="test-host", pid=1000 + i, theme=f"theme-{i}")
23
+ tmp_db.register(s)
24
+
25
+ active = tmp_db.list_active()
26
+ assert len(active) == 3
27
+
28
+
29
+ def test_heartbeat(tmp_db: SessionDB):
30
+ session = Session(cli="kiro", hostname="test-host", pid=1234)
31
+ tmp_db.register(session)
32
+
33
+ ok = tmp_db.heartbeat(session.id)
34
+ assert ok is True
35
+
36
+ # Non-existent session
37
+ ok = tmp_db.heartbeat("nonexistent-id")
38
+ assert ok is False
39
+
40
+
41
+ def test_end_session(tmp_db: SessionDB):
42
+ session = Session(cli="kiro", hostname="test-host", pid=1234)
43
+ tmp_db.register(session)
44
+
45
+ ok = tmp_db.end(session.id)
46
+ assert ok is True
47
+
48
+ active = tmp_db.list_active()
49
+ assert len(active) == 0
50
+
51
+
52
+ def test_end_cleans_claims(tmp_db: SessionDB):
53
+ session = Session(cli="kiro", hostname="test-host", pid=1234)
54
+ tmp_db.register(session)
55
+
56
+ claim = Claim(session_id=session.id, resource="/home/user/file.py")
57
+ tmp_db.claim(claim)
58
+
59
+ tmp_db.end(session.id)
60
+
61
+ # Claims should be gone
62
+ conflicts = tmp_db.get_conflicts("other-session", ["/home/user/file.py"])
63
+ assert len(conflicts) == 0
64
+
65
+
66
+ def test_claim_and_conflict(tmp_db: SessionDB):
67
+ s1 = Session(cli="kiro", hostname="test-host", pid=1001, theme="session-1")
68
+ s2 = Session(cli="kiro", hostname="test-host", pid=1002, theme="session-2")
69
+ tmp_db.register(s1)
70
+ tmp_db.register(s2)
71
+
72
+ # s1 claims a file
73
+ claim = Claim(session_id=s1.id, resource="~/git/mir/api/")
74
+ tmp_db.claim(claim)
75
+
76
+ # s2 checks for conflicts
77
+ conflicts = tmp_db.get_conflicts(s2.id, ["~/git/mir/api/"])
78
+ assert len(conflicts) == 1
79
+ assert conflicts[0].claimed_by_session == s1.id
80
+ assert conflicts[0].claimed_by_theme == "session-1"
81
+
82
+ # s1 checks same resource — no conflict (it's their own)
83
+ conflicts = tmp_db.get_conflicts(s1.id, ["~/git/mir/api/"])
84
+ assert len(conflicts) == 0
85
+
86
+
87
+ def test_release(tmp_db: SessionDB):
88
+ session = Session(cli="kiro", hostname="test-host", pid=1234)
89
+ tmp_db.register(session)
90
+
91
+ claim = Claim(session_id=session.id, resource="/tmp/file.txt")
92
+ tmp_db.claim(claim)
93
+
94
+ ok = tmp_db.release(session.id, "/tmp/file.txt")
95
+ assert ok is True
96
+
97
+ # No more conflicts
98
+ conflicts = tmp_db.get_conflicts("other", ["/tmp/file.txt"])
99
+ assert len(conflicts) == 0
100
+
101
+
102
+ def test_reap_dead_sessions(tmp_db: SessionDB):
103
+ # Create session with old heartbeat
104
+ session = Session(cli="kiro", hostname="test-host", pid=1234)
105
+ tmp_db.register(session)
106
+
107
+ # Manually set heartbeat to past
108
+ with tmp_db._get_conn() as conn:
109
+ old_time = (datetime.now(timezone.utc) - timedelta(seconds=HEARTBEAT_TIMEOUT_SECONDS + 60)).isoformat()
110
+ conn.execute("UPDATE sessions SET heartbeat_at = ? WHERE id = ?", (old_time, session.id))
111
+
112
+ # Also add a claim
113
+ claim = Claim(session_id=session.id, resource="/tmp/dead.py")
114
+ tmp_db.claim(claim)
115
+
116
+ # Reap
117
+ reaped = tmp_db.reap_dead_sessions()
118
+ assert reaped == 1
119
+
120
+ # Session and claims gone
121
+ active = tmp_db.list_active()
122
+ assert len(active) == 0
123
+
124
+
125
+ def test_reap_keeps_alive_sessions(tmp_db: SessionDB):
126
+ session = Session(cli="kiro", hostname="test-host", pid=1234)
127
+ tmp_db.register(session)
128
+
129
+ # Fresh heartbeat — should NOT be reaped
130
+ reaped = tmp_db.reap_dead_sessions()
131
+ assert reaped == 0
132
+
133
+ active = tmp_db.list_active()
134
+ assert len(active) == 1
135
+
136
+
137
+ def test_no_conflicts_empty_resources(tmp_db: SessionDB):
138
+ conflicts = tmp_db.get_conflicts("any-session", [])
139
+ assert len(conflicts) == 0