nodehop 0.2.0__tar.gz → 0.2.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.
- {nodehop-0.2.0 → nodehop-0.2.1}/PKG-INFO +15 -14
- {nodehop-0.2.0 → nodehop-0.2.1}/README.md +13 -11
- {nodehop-0.2.0 → nodehop-0.2.1}/nodehop/__init__.py +1 -1
- {nodehop-0.2.0 → nodehop-0.2.1}/nodehop/cli.py +5 -5
- {nodehop-0.2.0 → nodehop-0.2.1}/nodehop/config.py +28 -0
- {nodehop-0.2.0 → nodehop-0.2.1}/nodehop/core.py +123 -32
- {nodehop-0.2.0 → nodehop-0.2.1}/nodehop/gui.py +1 -2
- {nodehop-0.2.0 → nodehop-0.2.1}/nodehop/modules/base.py +3 -2
- {nodehop-0.2.0 → nodehop-0.2.1}/nodehop/onboard.py +1 -1
- {nodehop-0.2.0 → nodehop-0.2.1}/nodehop/pairing.py +1 -1
- {nodehop-0.2.0 → nodehop-0.2.1}/nodehop/state.py +1 -1
- {nodehop-0.2.0 → nodehop-0.2.1}/nodehop/transport.py +13 -5
- {nodehop-0.2.0 → nodehop-0.2.1}/nodehop.egg-info/PKG-INFO +15 -14
- {nodehop-0.2.0 → nodehop-0.2.1}/pyproject.toml +7 -4
- {nodehop-0.2.0 → nodehop-0.2.1}/tests/test_nodehop.py +161 -1
- {nodehop-0.2.0 → nodehop-0.2.1}/LICENSE +0 -0
- {nodehop-0.2.0 → nodehop-0.2.1}/nodehop/__main__.py +0 -0
- {nodehop-0.2.0 → nodehop-0.2.1}/nodehop/deploy.py +0 -0
- {nodehop-0.2.0 → nodehop-0.2.1}/nodehop/doctor.py +0 -0
- {nodehop-0.2.0 → nodehop-0.2.1}/nodehop/hooks.py +0 -0
- {nodehop-0.2.0 → nodehop-0.2.1}/nodehop/icon.py +0 -0
- {nodehop-0.2.0 → nodehop-0.2.1}/nodehop/modules/__init__.py +0 -0
- {nodehop-0.2.0 → nodehop-0.2.1}/nodehop/modules/claude_code.py +0 -0
- {nodehop-0.2.0 → nodehop-0.2.1}/nodehop/modules/codex.py +0 -0
- {nodehop-0.2.0 → nodehop-0.2.1}/nodehop/modules/command.py +0 -0
- {nodehop-0.2.0 → nodehop-0.2.1}/nodehop/runner.py +0 -0
- {nodehop-0.2.0 → nodehop-0.2.1}/nodehop/system.py +0 -0
- {nodehop-0.2.0 → nodehop-0.2.1}/nodehop/train.py +0 -0
- {nodehop-0.2.0 → nodehop-0.2.1}/nodehop/ui.py +0 -0
- {nodehop-0.2.0 → nodehop-0.2.1}/nodehop/uninstall.py +0 -0
- {nodehop-0.2.0 → nodehop-0.2.1}/nodehop.egg-info/SOURCES.txt +0 -0
- {nodehop-0.2.0 → nodehop-0.2.1}/nodehop.egg-info/dependency_links.txt +0 -0
- {nodehop-0.2.0 → nodehop-0.2.1}/nodehop.egg-info/entry_points.txt +0 -0
- {nodehop-0.2.0 → nodehop-0.2.1}/nodehop.egg-info/top_level.txt +0 -0
- {nodehop-0.2.0 → nodehop-0.2.1}/setup.cfg +0 -0
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: nodehop
|
|
3
|
-
Version: 0.2.
|
|
3
|
+
Version: 0.2.1
|
|
4
4
|
Summary: Close your laptop, your agents keep working: hand off Claude Code sessions and training jobs between your machines.
|
|
5
|
-
License: MIT
|
|
5
|
+
License-Expression: MIT
|
|
6
6
|
Project-URL: Homepage, https://github.com/BuildRunnerFr/NodeHop
|
|
7
7
|
Project-URL: Issues, https://github.com/BuildRunnerFr/NodeHop/issues
|
|
8
8
|
Project-URL: Changelog, https://github.com/BuildRunnerFr/NodeHop/blob/main/CHANGELOG.md
|
|
@@ -10,7 +10,6 @@ Keywords: claude-code,ai-agents,handoff,tmux,ssh,tailscale,machine-learning,chec
|
|
|
10
10
|
Classifier: Development Status :: 3 - Alpha
|
|
11
11
|
Classifier: Environment :: Console
|
|
12
12
|
Classifier: Intended Audience :: Developers
|
|
13
|
-
Classifier: License :: OSI Approved :: MIT License
|
|
14
13
|
Classifier: Operating System :: MacOS
|
|
15
14
|
Classifier: Operating System :: POSIX :: Linux
|
|
16
15
|
Classifier: Programming Language :: Python :: 3
|
|
@@ -28,7 +27,7 @@ License-File: LICENSE
|
|
|
28
27
|
Dynamic: license-file
|
|
29
28
|
|
|
30
29
|
<p align="center">
|
|
31
|
-
<img src="
|
|
30
|
+
<img src="docs/logo.png" width="112" alt="NodeHop logo">
|
|
32
31
|
</p>
|
|
33
32
|
|
|
34
33
|
<h1 align="center">NodeHop</h1>
|
|
@@ -40,6 +39,7 @@ Dynamic: license-file
|
|
|
40
39
|
|
|
41
40
|
<p align="center">
|
|
42
41
|
<a href="https://github.com/BuildRunnerFr/NodeHop/actions/workflows/tests.yml"><img src="https://github.com/BuildRunnerFr/NodeHop/actions/workflows/tests.yml/badge.svg" alt="Tests"></a>
|
|
42
|
+
<a href="https://pypi.org/project/nodehop/"><img src="https://img.shields.io/pypi/v/nodehop" alt="PyPI"></a>
|
|
43
43
|
<img src="https://img.shields.io/badge/python-3.9%2B-blue" alt="Python 3.9+">
|
|
44
44
|
<img src="https://img.shields.io/badge/platform-macOS%20%7C%20Linux-lightgrey" alt="macOS | Linux">
|
|
45
45
|
<img src="https://img.shields.io/badge/dependencies-none-brightgreen" alt="No dependencies">
|
|
@@ -54,15 +54,12 @@ session is stopped, copied to your Mac mini or Linux box, and resumed there with
|
|
|
54
54
|
the same conversation. Open the lid: your laptop takes it back. Training jobs work the
|
|
55
55
|
same way, resuming from their last checkpoint at the other machine's pace.
|
|
56
56
|
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
lid closes
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
copy everything back ◄─────────────
|
|
64
|
-
resume it here
|
|
65
|
-
```
|
|
57
|
+
<p align="center">
|
|
58
|
+
<picture>
|
|
59
|
+
<source media="(prefers-color-scheme: dark)" srcset="docs/handoff-dark.svg">
|
|
60
|
+
<img src="docs/handoff-light.svg" width="860" alt="When the lid closes, the laptop stops the agent, copies the project and conversation to the always-on machine and resumes it there; when the lid opens, everything comes back. Every 30 s a heartbeat, every 5 min a copy; if the laptop is silent for 2 min, the server resumes from the last copy.">
|
|
61
|
+
</picture>
|
|
62
|
+
</p>
|
|
66
63
|
|
|
67
64
|
## Highlights
|
|
68
65
|
|
|
@@ -120,11 +117,15 @@ that needs `sudo`. Details for agents: [AGENT_SETUP.md](AGENT_SETUP.md).
|
|
|
120
117
|
|
|
121
118
|
### By hand
|
|
122
119
|
|
|
120
|
+
NodeHop is on [PyPI](https://pypi.org/project/nodehop/):
|
|
121
|
+
|
|
123
122
|
```sh
|
|
124
|
-
pipx install
|
|
123
|
+
pipx install nodehop
|
|
125
124
|
nodehop onboard # the same questions, with arrow-key menus
|
|
126
125
|
```
|
|
127
126
|
|
|
127
|
+
For the latest changes not yet released: `pipx install git+https://github.com/BuildRunnerFr/NodeHop`.
|
|
128
|
+
|
|
128
129
|
## Daily use
|
|
129
130
|
|
|
130
131
|
```sh
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
<p align="center">
|
|
2
|
-
<img src="
|
|
2
|
+
<img src="docs/logo.png" width="112" alt="NodeHop logo">
|
|
3
3
|
</p>
|
|
4
4
|
|
|
5
5
|
<h1 align="center">NodeHop</h1>
|
|
@@ -11,6 +11,7 @@
|
|
|
11
11
|
|
|
12
12
|
<p align="center">
|
|
13
13
|
<a href="https://github.com/BuildRunnerFr/NodeHop/actions/workflows/tests.yml"><img src="https://github.com/BuildRunnerFr/NodeHop/actions/workflows/tests.yml/badge.svg" alt="Tests"></a>
|
|
14
|
+
<a href="https://pypi.org/project/nodehop/"><img src="https://img.shields.io/pypi/v/nodehop" alt="PyPI"></a>
|
|
14
15
|
<img src="https://img.shields.io/badge/python-3.9%2B-blue" alt="Python 3.9+">
|
|
15
16
|
<img src="https://img.shields.io/badge/platform-macOS%20%7C%20Linux-lightgrey" alt="macOS | Linux">
|
|
16
17
|
<img src="https://img.shields.io/badge/dependencies-none-brightgreen" alt="No dependencies">
|
|
@@ -25,15 +26,12 @@ session is stopped, copied to your Mac mini or Linux box, and resumed there with
|
|
|
25
26
|
the same conversation. Open the lid: your laptop takes it back. Training jobs work the
|
|
26
27
|
same way, resuming from their last checkpoint at the other machine's pace.
|
|
27
28
|
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
lid closes
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
copy everything back ◄─────────────
|
|
35
|
-
resume it here
|
|
36
|
-
```
|
|
29
|
+
<p align="center">
|
|
30
|
+
<picture>
|
|
31
|
+
<source media="(prefers-color-scheme: dark)" srcset="docs/handoff-dark.svg">
|
|
32
|
+
<img src="docs/handoff-light.svg" width="860" alt="When the lid closes, the laptop stops the agent, copies the project and conversation to the always-on machine and resumes it there; when the lid opens, everything comes back. Every 30 s a heartbeat, every 5 min a copy; if the laptop is silent for 2 min, the server resumes from the last copy.">
|
|
33
|
+
</picture>
|
|
34
|
+
</p>
|
|
37
35
|
|
|
38
36
|
## Highlights
|
|
39
37
|
|
|
@@ -91,11 +89,15 @@ that needs `sudo`. Details for agents: [AGENT_SETUP.md](AGENT_SETUP.md).
|
|
|
91
89
|
|
|
92
90
|
### By hand
|
|
93
91
|
|
|
92
|
+
NodeHop is on [PyPI](https://pypi.org/project/nodehop/):
|
|
93
|
+
|
|
94
94
|
```sh
|
|
95
|
-
pipx install
|
|
95
|
+
pipx install nodehop
|
|
96
96
|
nodehop onboard # the same questions, with arrow-key menus
|
|
97
97
|
```
|
|
98
98
|
|
|
99
|
+
For the latest changes not yet released: `pipx install git+https://github.com/BuildRunnerFr/NodeHop`.
|
|
100
|
+
|
|
99
101
|
## Daily use
|
|
100
102
|
|
|
101
103
|
```sh
|
|
@@ -12,7 +12,7 @@ from pathlib import Path
|
|
|
12
12
|
from typing import Dict, List, Optional
|
|
13
13
|
|
|
14
14
|
from nodehop import __version__, deploy, doctor, hooks, pairing, ui
|
|
15
|
-
from nodehop.config import DEFAULT_EXTRA_PATH, Config, ConfigError, Peer
|
|
15
|
+
from nodehop.config import DEFAULT_EXTRA_PATH, Config, ConfigError, Peer
|
|
16
16
|
from nodehop.core import NodeHop
|
|
17
17
|
from nodehop.modules import MODULES
|
|
18
18
|
from nodehop.modules.base import tmux as tmux_argv
|
|
@@ -228,7 +228,7 @@ def cmd_project(args, cfg: Config) -> int:
|
|
|
228
228
|
if path in (Path("/"), Path.home()) or len(path.parts) < 3:
|
|
229
229
|
raise ConfigError(f"refusing to track {path}: pick a project folder, not a top-level one")
|
|
230
230
|
name = args.name or path.name
|
|
231
|
-
cfg.
|
|
231
|
+
cfg.add_project(name, str(path), module=args.module)
|
|
232
232
|
print(f"tracking {name} -> {path} ({args.module})")
|
|
233
233
|
else:
|
|
234
234
|
cfg.projects.pop(args.name, None)
|
|
@@ -253,7 +253,7 @@ def cmd_on_off(args, cfg: Config, runner: Runner) -> int:
|
|
|
253
253
|
if not path.is_dir() or path in (Path("/"), Path.home()) or len(path.parts) < 3:
|
|
254
254
|
raise ConfigError(f"{args.target}: not a project of NodeHop, nor a project folder")
|
|
255
255
|
name = args.name or path.name
|
|
256
|
-
cfg.
|
|
256
|
+
cfg.add_project(name, str(path))
|
|
257
257
|
if name is None:
|
|
258
258
|
raise ConfigError(f"{args.target}: not a project of NodeHop")
|
|
259
259
|
cfg.projects[name].active = args.command == "on"
|
|
@@ -274,7 +274,7 @@ def cmd_on_off(args, cfg: Config, runner: Runner) -> int:
|
|
|
274
274
|
try: # tell the server now: first copy, or "stop covering this one"
|
|
275
275
|
hop.sync(cfg.target(), force_copy=args.command == "on")
|
|
276
276
|
except Exception as exc:
|
|
277
|
-
print(f"(
|
|
277
|
+
print(f"(not copied to the server yet: {exc}; the next sync tries again)")
|
|
278
278
|
return 0
|
|
279
279
|
|
|
280
280
|
|
|
@@ -315,7 +315,7 @@ def cmd_resolve(args, hop: NodeHop) -> int:
|
|
|
315
315
|
"Which one do you keep?",
|
|
316
316
|
[f"Keep {here}", f"Keep {there}", f"Keep {here} + give it {there}'s work", "Decide later"],
|
|
317
317
|
[f"{there}'s version is set aside in a backup", f"{here}'s version is set aside in a backup",
|
|
318
|
-
|
|
318
|
+
"the agent compares both and brings in what is useful", "both stay paused/as they are"],
|
|
319
319
|
)
|
|
320
320
|
keep = ["here", "there", "merge", None][pick]
|
|
321
321
|
if not keep:
|
|
@@ -43,6 +43,20 @@ class ConfigError(Exception):
|
|
|
43
43
|
pass
|
|
44
44
|
|
|
45
45
|
|
|
46
|
+
def session_key(name: str) -> str:
|
|
47
|
+
"""The part of a project's name tmux keeps in a session name: it turns "." and ":" into "_"
|
|
48
|
+
when it creates a session, and reads them as window/pane separators in a target."""
|
|
49
|
+
return name.replace(".", "_").replace(":", "_")
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def check_project_name(name: str) -> str:
|
|
53
|
+
"""A project's name is also a folder name (inbox, backups) and an argument on the other machine."""
|
|
54
|
+
if (not name or name in (".", "..") or name.startswith("-")
|
|
55
|
+
or any(c in "/\\" or ord(c) < 32 for c in name)):
|
|
56
|
+
raise ConfigError(f"'{name}' cannot be a project name: pass --name with a plain one (letters, digits, - _ .)")
|
|
57
|
+
return name
|
|
58
|
+
|
|
59
|
+
|
|
46
60
|
@dataclass
|
|
47
61
|
class Peer:
|
|
48
62
|
name: str
|
|
@@ -123,6 +137,20 @@ class Config:
|
|
|
123
137
|
raise ConfigError(f"unknown project '{name}' (known projects: {known})")
|
|
124
138
|
return self.projects[name]
|
|
125
139
|
|
|
140
|
+
def add_project(self, name: str, path: str, module: str = "claude-code") -> Project:
|
|
141
|
+
"""Register a folder under `name`, refusing to take the name of another folder's project."""
|
|
142
|
+
check_project_name(name)
|
|
143
|
+
known = self.projects.get(name)
|
|
144
|
+
if known is not None and os.path.normpath(known.path) != os.path.normpath(path):
|
|
145
|
+
raise ConfigError(f"a project named '{name}' already exists ({known.path}): "
|
|
146
|
+
f"pass --name to give {path} another name")
|
|
147
|
+
for other in self.projects:
|
|
148
|
+
if other != name and session_key(other) == session_key(name):
|
|
149
|
+
raise ConfigError(f"'{name}' is too close to the project '{other}' (same tmux session name): "
|
|
150
|
+
f"pass --name to give {path} another name")
|
|
151
|
+
self.projects[name] = Project(name=name, path=path, module=module)
|
|
152
|
+
return self.projects[name]
|
|
153
|
+
|
|
126
154
|
def ssh_key_path(self) -> Path:
|
|
127
155
|
return Path(os.path.expanduser(self.ssh_key))
|
|
128
156
|
|
|
@@ -3,6 +3,7 @@
|
|
|
3
3
|
from __future__ import annotations
|
|
4
4
|
|
|
5
5
|
import json
|
|
6
|
+
import re
|
|
6
7
|
import shutil
|
|
7
8
|
import threading
|
|
8
9
|
import time
|
|
@@ -10,10 +11,10 @@ from pathlib import Path
|
|
|
10
11
|
from typing import Callable, Dict, Iterable, List, Optional
|
|
11
12
|
|
|
12
13
|
from nodehop import gui
|
|
13
|
-
from nodehop.config import Config,
|
|
14
|
+
from nodehop.config import Config, Project, check_project_name, home_dir
|
|
14
15
|
from nodehop.modules import get_module
|
|
15
16
|
from nodehop.modules.base import Module
|
|
16
|
-
from nodehop.runner import Runner
|
|
17
|
+
from nodehop.runner import CommandError, Runner
|
|
17
18
|
from nodehop.state import State, locked
|
|
18
19
|
from nodehop.transport import SSHTransport
|
|
19
20
|
|
|
@@ -119,14 +120,23 @@ class NodeHop:
|
|
|
119
120
|
meta.update({"was_running": was_running, "was_busy": was_busy, "reason": reason})
|
|
120
121
|
if was_running:
|
|
121
122
|
self.runner.log(f"{project.name}: agent was {'working' if was_busy else 'idle'}")
|
|
123
|
+
asked = False
|
|
122
124
|
try:
|
|
123
125
|
self._push(project, module, meta, transport, deadline)
|
|
126
|
+
asked = True
|
|
124
127
|
transport.nodehop("receive", project.name, "--from", self.me, "--meta", json.dumps(meta))
|
|
125
128
|
if self.runner.dry_run:
|
|
126
129
|
self.runner.log(f"{project.name}: [dry-run] would now run on {target}")
|
|
127
130
|
return True
|
|
128
131
|
except Exception as exc: # leave the work where it was rather than lose it
|
|
129
132
|
self.runner.log(f"{project.name}: handoff to {target} failed: {exc}")
|
|
133
|
+
if asked and self._no_answer(exc) and self._took_it(project, transport, target):
|
|
134
|
+
# Only the answer got lost: restarting here, or sending the work again,
|
|
135
|
+
# would put a second agent next to the one already running over there.
|
|
136
|
+
self._record(project.name, owner=target, origin=self.me, reason=reason,
|
|
137
|
+
session_id=meta.get("session_id"), paused_for_sleep=False)
|
|
138
|
+
self.runner.log(f"{project.name}: {target} did receive it, now running there")
|
|
139
|
+
return True
|
|
130
140
|
if reason == "sleep" and self._resume_from_last_copy(project, transport, target, meta):
|
|
131
141
|
return True
|
|
132
142
|
if was_running and reason != "sleep":
|
|
@@ -139,6 +149,22 @@ class NodeHop:
|
|
|
139
149
|
self.runner.log(f"{project.name}: now running on {target}")
|
|
140
150
|
return True
|
|
141
151
|
|
|
152
|
+
@staticmethod
|
|
153
|
+
def _no_answer(exc: Exception) -> bool:
|
|
154
|
+
"""The connection dropped or timed out (ssh: 255, our timeout: 124), as opposed to the
|
|
155
|
+
other machine answering that it could not do it."""
|
|
156
|
+
return isinstance(exc, CommandError) and exc.result.returncode in (124, 255)
|
|
157
|
+
|
|
158
|
+
def _took_it(self, project: Project, transport: SSHTransport, target: str) -> bool:
|
|
159
|
+
"""After a `receive` that failed from here: did the target become the owner all the same?"""
|
|
160
|
+
if self.runner.dry_run:
|
|
161
|
+
return False
|
|
162
|
+
try:
|
|
163
|
+
where = transport.prepare(project.name, project.module, project.path, str(Path.home()), timeout=15)
|
|
164
|
+
except Exception:
|
|
165
|
+
return False
|
|
166
|
+
return where.get("owner") == target
|
|
167
|
+
|
|
142
168
|
def _resume_from_last_copy(self, project: Project, transport: SSHTransport, target: str, meta: dict) -> bool:
|
|
143
169
|
"""Going to sleep, the newest state did not get through: let the target go on from its last full copy."""
|
|
144
170
|
copied_at = self.state.get(project.name).get("copied_at")
|
|
@@ -171,6 +197,9 @@ class NodeHop:
|
|
|
171
197
|
remote_path, remote_inbox = where["path"], where["inbox"]
|
|
172
198
|
if remote_path != project.path:
|
|
173
199
|
self.runner.log(f"{project.name}: {project.path} here -> {remote_path} on {transport.peer.name}")
|
|
200
|
+
if where.get("backup"):
|
|
201
|
+
self.runner.log(f"{project.name}: {remote_path} already held files on {transport.peer.name}: "
|
|
202
|
+
f"kept there in {where['backup']}")
|
|
174
203
|
transport.push_dir(Path(project.path), remote_path, delete=True, excludes=self.config.excludes, timeout=budget())
|
|
175
204
|
for label, local in module.payload(project, meta):
|
|
176
205
|
# --delete keeps the inbox an exact copy, so nothing stale gets re-imported.
|
|
@@ -179,7 +208,9 @@ class NodeHop:
|
|
|
179
208
|
# ---- prepare (target side, called over SSH before files are sent) --------
|
|
180
209
|
def prepare(self, name: str, module: str, origin_path: str, origin_home: Optional[str]) -> dict:
|
|
181
210
|
"""Say where `name` lives on this machine, registering it if it is new here."""
|
|
211
|
+
check_project_name(name)
|
|
182
212
|
path = self.config.local_path_for(name, origin_path, origin_home)
|
|
213
|
+
where = {"path": path, "inbox": str(self.inbox(name)), "machine": self.me}
|
|
183
214
|
if name not in self.config.projects:
|
|
184
215
|
self.config.projects[name] = Project(name=name, path=path, module=module)
|
|
185
216
|
if self.runner.dry_run:
|
|
@@ -187,7 +218,23 @@ class NodeHop:
|
|
|
187
218
|
else:
|
|
188
219
|
self.config.save()
|
|
189
220
|
self.runner.log(f"{name}: new project here, tracked at {path}")
|
|
190
|
-
|
|
221
|
+
kept = self._set_aside_existing(name, f"what was in {path} on {self.me} before NodeHop first copied "
|
|
222
|
+
f"the project '{name}' there")
|
|
223
|
+
if kept:
|
|
224
|
+
where["backup"] = str(kept)
|
|
225
|
+
where["owner"] = self.owner(name)
|
|
226
|
+
return where
|
|
227
|
+
|
|
228
|
+
def _set_aside_existing(self, name: str, why: str) -> Optional[Path]:
|
|
229
|
+
"""A project new to this machine is about to be copied over a folder that already
|
|
230
|
+
holds files (another clone, an unrelated folder of the same name): keep them."""
|
|
231
|
+
folder = Path(self.config.project(name).path)
|
|
232
|
+
try:
|
|
233
|
+
if not folder.is_dir() or not any(folder.iterdir()):
|
|
234
|
+
return None
|
|
235
|
+
except OSError:
|
|
236
|
+
return None
|
|
237
|
+
return self.backup(name, why)
|
|
191
238
|
|
|
192
239
|
# ---- receive (target side, called over SSH) -----------------------------
|
|
193
240
|
def receive(self, name: str, origin: str, meta: Dict) -> None:
|
|
@@ -240,6 +287,8 @@ class NodeHop:
|
|
|
240
287
|
path = self.config.local_path_for(name, meta["path"], meta.get("home"))
|
|
241
288
|
self.config.projects[name] = Project(name=name, path=path, module=meta.get("module", "claude-code"))
|
|
242
289
|
self.config.save()
|
|
290
|
+
self._set_aside_existing(name, f"what was in {path} on {self.me} before NodeHop first copied "
|
|
291
|
+
f"the project '{name}' there from {owner}")
|
|
243
292
|
project = self.config.project(name)
|
|
244
293
|
module = self.module(project)
|
|
245
294
|
try:
|
|
@@ -337,20 +386,30 @@ class NodeHop:
|
|
|
337
386
|
beater = threading.Thread(target=keep_beating, daemon=True)
|
|
338
387
|
if copy_due:
|
|
339
388
|
beater.start()
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
meta.update({"was_running": running, "was_busy": busy, "copied": True})
|
|
349
|
-
self._push(project, module, meta, transport)
|
|
350
|
-
else:
|
|
389
|
+
failed: Dict[str, str] = {}
|
|
390
|
+
try:
|
|
391
|
+
with locked(role="sync"):
|
|
392
|
+
for name in self.active_here():
|
|
393
|
+
project = self.config.project(name)
|
|
394
|
+
module = self.module(project)
|
|
395
|
+
running = module.is_running(project)
|
|
396
|
+
busy = running and module.is_busy(project)
|
|
351
397
|
meta = {"was_running": running, "was_busy": busy, "copied": False}
|
|
352
|
-
|
|
353
|
-
|
|
398
|
+
if copy_due:
|
|
399
|
+
try:
|
|
400
|
+
full = module.snapshot(project)
|
|
401
|
+
full.update({"was_running": running, "was_busy": busy, "copied": True})
|
|
402
|
+
self._push(project, module, full, transport)
|
|
403
|
+
meta = full
|
|
404
|
+
except Exception as exc:
|
|
405
|
+
# One project that cannot be copied (folder gone, unreadable file) must not
|
|
406
|
+
# keep the others from being copied, nor this machine from saying "alive":
|
|
407
|
+
# the server would start a fallback while we are awake and working.
|
|
408
|
+
failed[name] = str(exc).strip().splitlines()[0] if str(exc).strip() else type(exc).__name__
|
|
409
|
+
self.runner.log(f"{name}: not copied to {target}: {exc}")
|
|
410
|
+
metas[name] = meta
|
|
411
|
+
finally:
|
|
412
|
+
stop_beating.set()
|
|
354
413
|
if copy_due and not self.runner.dry_run:
|
|
355
414
|
self.state.update_local(last_copy=now)
|
|
356
415
|
# The heartbeat comes last: it vouches that the copies above are complete.
|
|
@@ -359,6 +418,9 @@ class NodeHop:
|
|
|
359
418
|
for name, meta in metas.items():
|
|
360
419
|
if meta.get("copied"):
|
|
361
420
|
self.state.update(name, copied_at=now)
|
|
421
|
+
if failed:
|
|
422
|
+
raise RuntimeError("not copied to " + target + ": "
|
|
423
|
+
+ "; ".join(f"{name} ({why})" for name, why in sorted(failed.items())))
|
|
362
424
|
|
|
363
425
|
# ---- fallback: the primary vanished without going to sleep -------------------
|
|
364
426
|
def heartbeat(self, origin: str, metas: Dict[str, dict]) -> None:
|
|
@@ -447,7 +509,9 @@ class NodeHop:
|
|
|
447
509
|
(dest / "WHY.txt").write_text(why + "\n")
|
|
448
510
|
self.runner.log(f"{name}: kept a copy of this machine's version in {dest}")
|
|
449
511
|
# Backups hold full copies of the project (secrets included): do not let them pile up.
|
|
450
|
-
|
|
512
|
+
# (Only this project's: "app-*" would also match the backups of "app-web".)
|
|
513
|
+
mine = re.compile(re.escape(name) + r"-\d{8}-\d{6}(-\d+)?")
|
|
514
|
+
others = sorted((p for p in dest.parent.iterdir() if p.is_dir() and p != dest and mine.fullmatch(p.name)),
|
|
451
515
|
key=lambda p: p.stat().st_mtime)
|
|
452
516
|
keep_others = max(0, self.config.backups_keep - 1)
|
|
453
517
|
for stale in others[:len(others) - keep_others]:
|
|
@@ -514,7 +578,8 @@ class NodeHop:
|
|
|
514
578
|
transport.nodehop("abandon", name, "--to", self.me, timeout=120)
|
|
515
579
|
self._record(name, conflict=None, reason="kept")
|
|
516
580
|
if keep == "merge":
|
|
517
|
-
|
|
581
|
+
labels = [label for label, _ in module.payload(project, meta)]
|
|
582
|
+
report = self.conflict_brief(name, peer, conflict.get("since"), result["other_version"], labels)
|
|
518
583
|
result["briefed"] = module.send_message(project, report)
|
|
519
584
|
self.runner.log(f"{name}: kept {self.me}'s version" + (" and briefed it on " + peer + "'s work" if keep == "merge" else ""))
|
|
520
585
|
elif keep == "there":
|
|
@@ -531,12 +596,13 @@ class NodeHop:
|
|
|
531
596
|
return result
|
|
532
597
|
|
|
533
598
|
@staticmethod
|
|
534
|
-
def conflict_brief(name: str, peer: str, since, other: str) -> str:
|
|
599
|
+
def conflict_brief(name: str, peer: str, since, other: str, labels: Iterable[str] = ("claude",)) -> str:
|
|
535
600
|
when = time.strftime("%H:%M", time.localtime(since)) if since else "a while"
|
|
601
|
+
talk = "".join(f" and its conversation in {other}/{label}" for label in list(labels)[:1])
|
|
536
602
|
return (
|
|
537
603
|
f"NodeHop: while this machine was unreachable, another copy of you kept working on this task on "
|
|
538
604
|
f"{peer} since {when}. The person chose to keep your version and give you the other one's work. "
|
|
539
|
-
f"Its full project is in {other}/project
|
|
605
|
+
f"Its full project is in {other}/project{talk}. Compare it with this "
|
|
540
606
|
f"project (for example: diff -ru --exclude=.git {other}/project .), bring in what is useful without "
|
|
541
607
|
f"redoing what is already done here, then carry on with the task."
|
|
542
608
|
)
|
|
@@ -568,22 +634,33 @@ class NodeHop:
|
|
|
568
634
|
return []
|
|
569
635
|
back = []
|
|
570
636
|
for name, claim in claims.items():
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
|
|
637
|
+
# on-wake and the 30 s sync both come here: decide under the lock, on the state as it
|
|
638
|
+
# is now, so the second one sees what the first one did instead of doing it again.
|
|
639
|
+
with locked():
|
|
640
|
+
self.state.reload()
|
|
641
|
+
if name not in self.config.projects or self.owner(name) != self.me or self.in_conflict(name):
|
|
642
|
+
continue
|
|
643
|
+
project = self.config.project(name)
|
|
644
|
+
both_alive = self.module(project).is_running(project)
|
|
645
|
+
if both_alive:
|
|
646
|
+
self._record(name, conflict={"peer": peer, "since": claim.get("since"),
|
|
647
|
+
"copy_time": claim.get("copy_time"), "detected": time.time()})
|
|
648
|
+
else:
|
|
649
|
+
self.runner.log(f"{name}: {peer} took over while this machine was down: its version wins")
|
|
650
|
+
self.backup(name, f"version on {self.me} when {peer} had taken over (fallback)")
|
|
651
|
+
self._record(name, owner=peer, origin=self.me, reason="failover")
|
|
652
|
+
if both_alive:
|
|
575
653
|
# Two agents worked in parallel. Pause the server's (the person is here) and ask.
|
|
576
654
|
self.runner.log(f"{name}: {peer} took over while this machine was unreachable and both agents "
|
|
577
655
|
f"kept working: pausing {peer}'s, waiting for `nodehop resolve`")
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
|
|
656
|
+
try:
|
|
657
|
+
transport.nodehop("pause", name, timeout=120)
|
|
658
|
+
except Exception:
|
|
659
|
+
self._record(name, conflict=None) # not paused: the next sync tries again
|
|
660
|
+
raise
|
|
581
661
|
self.ask_person(name)
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
self.backup(name, f"version on {self.me} when {peer} had taken over (fallback)")
|
|
585
|
-
self._record(name, owner=peer, origin=self.me, reason="failover")
|
|
586
|
-
back += self.pull([name])
|
|
662
|
+
else:
|
|
663
|
+
back += self.pull([name]) # takes the lock itself
|
|
587
664
|
return back
|
|
588
665
|
|
|
589
666
|
# ---- lid events ------------------------------------------------------------
|
|
@@ -605,12 +682,26 @@ class NodeHop:
|
|
|
605
682
|
# Work stopped for a sleep handoff that never went through: start it again here.
|
|
606
683
|
for name, project in self.config.projects.items():
|
|
607
684
|
if self.owner(name) == self.me and self.state.get(name).get("paused_for_sleep"):
|
|
685
|
+
target = self._default_target()
|
|
686
|
+
if target and self._took_it(project, self.transport(target), target):
|
|
687
|
+
# The handoff did go through and only its answer was lost when this machine
|
|
688
|
+
# fell asleep: the work is over there, bring it home like any other.
|
|
689
|
+
self._record(name, owner=target, origin=self.me, reason="sleep", paused_for_sleep=False)
|
|
690
|
+
self.runner.log(f"{name}: {target} had received it at sleep after all")
|
|
691
|
+
back += self.pull([name])
|
|
692
|
+
continue
|
|
608
693
|
self._record(name, paused_for_sleep=False)
|
|
609
694
|
self.start(name, resume=True)
|
|
610
695
|
self.runner.log(f"{name}: the handoff at sleep did not happen, resumed here")
|
|
611
696
|
back.append(name)
|
|
612
697
|
return back
|
|
613
698
|
|
|
699
|
+
def _default_target(self) -> Optional[str]:
|
|
700
|
+
try:
|
|
701
|
+
return self.config.target()
|
|
702
|
+
except Exception:
|
|
703
|
+
return None
|
|
704
|
+
|
|
614
705
|
# ---- watcher (server): fallback when the primary goes silent --------------------
|
|
615
706
|
def watch(self, once: bool = False) -> None:
|
|
616
707
|
self.runner.log(f"watch: started on {self.me}, checking every {self.config.poll_seconds}s "
|
|
@@ -262,7 +262,7 @@ def dialog_text(report: dict) -> str:
|
|
|
262
262
|
for label, value in side_lines(p, report["since"], now):
|
|
263
263
|
out.append(f"{label}: {value}")
|
|
264
264
|
out.append("")
|
|
265
|
-
out.append(
|
|
265
|
+
out.append("The version you do not keep is saved in a backup folder, nothing is deleted.")
|
|
266
266
|
return "\n".join(out)
|
|
267
267
|
|
|
268
268
|
|
|
@@ -295,7 +295,6 @@ def window_request(report: dict) -> dict:
|
|
|
295
295
|
|
|
296
296
|
def ask_conflict(report: dict) -> bool:
|
|
297
297
|
"""Show the conflict window (macOS app, or Linux notification/zenity). Non-blocking."""
|
|
298
|
-
title = f"Two agents on {report['project']}"
|
|
299
298
|
try:
|
|
300
299
|
if os_name() == "macos":
|
|
301
300
|
app = ensure_app()
|
|
@@ -21,7 +21,7 @@ import shutil
|
|
|
21
21
|
from pathlib import Path
|
|
22
22
|
from typing import List, Tuple
|
|
23
23
|
|
|
24
|
-
from nodehop.config import Config, Project
|
|
24
|
+
from nodehop.config import Config, Project, session_key
|
|
25
25
|
from nodehop.runner import Runner
|
|
26
26
|
from nodehop.system import has_systemd_run, os_name
|
|
27
27
|
|
|
@@ -89,7 +89,8 @@ class Module:
|
|
|
89
89
|
# ---- shared tmux lifecycle --------------------------------------------
|
|
90
90
|
@staticmethod
|
|
91
91
|
def session(project: Project) -> str:
|
|
92
|
-
|
|
92
|
+
# Not the bare name: `-t =nh-example.com` would never be found (see session_key).
|
|
93
|
+
return "nh-" + session_key(project.name)
|
|
93
94
|
|
|
94
95
|
def is_running(self, project: Project) -> bool:
|
|
95
96
|
result = self.runner.run(tmux("has-session", "-t", f"={self.session(project)}"), check=False, mutating=False)
|
|
@@ -152,7 +152,7 @@ def plan(runner: Runner, cfg: Optional[Config] = None, checks: Optional[List[dic
|
|
|
152
152
|
{"value": "acceptEdits", "label": "Accept file edits only: anything else waits for you"},
|
|
153
153
|
{"value": "default", "label": "Ask as usual: the agent waits for you"}]),
|
|
154
154
|
_q("remote", "Also make NodeHop's Claude Code sessions visible in the Claude app (Remote Control), "
|
|
155
|
-
"to follow them and answer from your phone?", "
|
|
155
|
+
"to follow them and answer from your phone?", "no",
|
|
156
156
|
[{"value": "yes", "label": "Yes"}, {"value": "no", "label": "No"}]),
|
|
157
157
|
],
|
|
158
158
|
"command": "nodehop config set unattended {mode} && nodehop config set remote_control {remote_bool}",
|
|
@@ -186,7 +186,7 @@ def parse_token(token: str) -> dict:
|
|
|
186
186
|
try:
|
|
187
187
|
info = json.loads(base64.urlsafe_b64decode(body + "=" * (-len(body) % 4)))
|
|
188
188
|
except ValueError as exc:
|
|
189
|
-
raise ConfigError(f"damaged token: {exc}")
|
|
189
|
+
raise ConfigError(f"damaged token: {exc}") from exc
|
|
190
190
|
for field in ("name", "user", "hosts", "key"):
|
|
191
191
|
if not info.get(field):
|
|
192
192
|
raise ConfigError(f"damaged token: missing {field}")
|
|
@@ -97,7 +97,7 @@ def locked(timeout: float = 120.0, role: str = "work", preempt: bool = False) ->
|
|
|
97
97
|
if preempt and not preempted:
|
|
98
98
|
preempted = _stop_sync_holder(owner_path)
|
|
99
99
|
if time.monotonic() > deadline:
|
|
100
|
-
raise TimeoutError("another NodeHop operation is still running")
|
|
100
|
+
raise TimeoutError("another NodeHop operation is still running") from None
|
|
101
101
|
time.sleep(0.2)
|
|
102
102
|
try:
|
|
103
103
|
owner_path.write_text(f"{os.getpid()} {role}\n")
|
|
@@ -9,6 +9,7 @@ the receiver where each project lives there (`nodehop prepare`).
|
|
|
9
9
|
from __future__ import annotations
|
|
10
10
|
|
|
11
11
|
import json
|
|
12
|
+
import os
|
|
12
13
|
import shlex
|
|
13
14
|
from pathlib import Path
|
|
14
15
|
from typing import List, Optional, Sequence
|
|
@@ -72,7 +73,7 @@ class SSHTransport:
|
|
|
72
73
|
result = self.nodehop("ping", check=False, timeout=20, mutating=False)
|
|
73
74
|
return result.returncode == 0
|
|
74
75
|
|
|
75
|
-
def prepare(self, name: str, module: str, origin_path: str, origin_home: str) -> dict:
|
|
76
|
+
def prepare(self, name: str, module: str, origin_path: str, origin_home: str, timeout: float = 60) -> dict:
|
|
76
77
|
"""Ask the peer where `name` lives there (registering it if new) and where its inbox is.
|
|
77
78
|
|
|
78
79
|
Runs even in dry-run (passing -n along) so the plan shows real paths.
|
|
@@ -80,9 +81,16 @@ class SSHTransport:
|
|
|
80
81
|
args = ["prepare", name, "--module", module, "--origin-path", origin_path, "--origin-home", origin_home]
|
|
81
82
|
if self.runner.dry_run:
|
|
82
83
|
args = ["-n", *args]
|
|
83
|
-
result = self.nodehop(*args, timeout=
|
|
84
|
+
result = self.nodehop(*args, timeout=timeout, mutating=False)
|
|
84
85
|
return json.loads(result.stdout.strip().splitlines()[-1])
|
|
85
86
|
|
|
87
|
+
def _rsync(self, argv: Sequence[str], timeout: float) -> None:
|
|
88
|
+
# The remote paths below are quoted for the remote shell, which is what rsync before
|
|
89
|
+
# 3.2.4 and openrsync (macOS) need. Newer rsync escapes them itself, and the quotes
|
|
90
|
+
# would then end up in the path: ask it for the old behaviour, so one form works everywhere.
|
|
91
|
+
os.environ["RSYNC_OLD_ARGS"] = "1"
|
|
92
|
+
self.runner.run(argv, timeout=timeout)
|
|
93
|
+
|
|
86
94
|
def push_dir(self, local: Path, remote: str, delete: bool, excludes: Sequence[str] = (),
|
|
87
95
|
timeout: float = 1800) -> None:
|
|
88
96
|
if not local.is_dir():
|
|
@@ -92,9 +100,9 @@ class SSHTransport:
|
|
|
92
100
|
if delete:
|
|
93
101
|
argv.append("--delete-after")
|
|
94
102
|
argv += [f"--exclude={pattern}" for pattern in excludes]
|
|
95
|
-
# The remote
|
|
103
|
+
# The remote shell splits paths on spaces: quote them (see _rsync).
|
|
96
104
|
argv += ["-e", shlex.join(["ssh", *self.opts]), f"{local}/", f"{self.peer.destination}:{shlex.quote(remote + '/')}"]
|
|
97
|
-
self.
|
|
105
|
+
self._rsync(argv, timeout)
|
|
98
106
|
|
|
99
107
|
def pull_dir(self, remote: str, local: Path, delete: bool, excludes: Sequence[str] = ()) -> None:
|
|
100
108
|
"""Copy a directory of the peer into `local` (the reverse of push_dir)."""
|
|
@@ -104,4 +112,4 @@ class SSHTransport:
|
|
|
104
112
|
argv.append("--delete-after")
|
|
105
113
|
argv += [f"--exclude={pattern}" for pattern in excludes]
|
|
106
114
|
argv += ["-e", shlex.join(["ssh", *self.opts]), f"{self.peer.destination}:{shlex.quote(remote + '/')}", f"{local}/"]
|
|
107
|
-
self.
|
|
115
|
+
self._rsync(argv, 1800)
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: nodehop
|
|
3
|
-
Version: 0.2.
|
|
3
|
+
Version: 0.2.1
|
|
4
4
|
Summary: Close your laptop, your agents keep working: hand off Claude Code sessions and training jobs between your machines.
|
|
5
|
-
License: MIT
|
|
5
|
+
License-Expression: MIT
|
|
6
6
|
Project-URL: Homepage, https://github.com/BuildRunnerFr/NodeHop
|
|
7
7
|
Project-URL: Issues, https://github.com/BuildRunnerFr/NodeHop/issues
|
|
8
8
|
Project-URL: Changelog, https://github.com/BuildRunnerFr/NodeHop/blob/main/CHANGELOG.md
|
|
@@ -10,7 +10,6 @@ Keywords: claude-code,ai-agents,handoff,tmux,ssh,tailscale,machine-learning,chec
|
|
|
10
10
|
Classifier: Development Status :: 3 - Alpha
|
|
11
11
|
Classifier: Environment :: Console
|
|
12
12
|
Classifier: Intended Audience :: Developers
|
|
13
|
-
Classifier: License :: OSI Approved :: MIT License
|
|
14
13
|
Classifier: Operating System :: MacOS
|
|
15
14
|
Classifier: Operating System :: POSIX :: Linux
|
|
16
15
|
Classifier: Programming Language :: Python :: 3
|
|
@@ -28,7 +27,7 @@ License-File: LICENSE
|
|
|
28
27
|
Dynamic: license-file
|
|
29
28
|
|
|
30
29
|
<p align="center">
|
|
31
|
-
<img src="
|
|
30
|
+
<img src="docs/logo.png" width="112" alt="NodeHop logo">
|
|
32
31
|
</p>
|
|
33
32
|
|
|
34
33
|
<h1 align="center">NodeHop</h1>
|
|
@@ -40,6 +39,7 @@ Dynamic: license-file
|
|
|
40
39
|
|
|
41
40
|
<p align="center">
|
|
42
41
|
<a href="https://github.com/BuildRunnerFr/NodeHop/actions/workflows/tests.yml"><img src="https://github.com/BuildRunnerFr/NodeHop/actions/workflows/tests.yml/badge.svg" alt="Tests"></a>
|
|
42
|
+
<a href="https://pypi.org/project/nodehop/"><img src="https://img.shields.io/pypi/v/nodehop" alt="PyPI"></a>
|
|
43
43
|
<img src="https://img.shields.io/badge/python-3.9%2B-blue" alt="Python 3.9+">
|
|
44
44
|
<img src="https://img.shields.io/badge/platform-macOS%20%7C%20Linux-lightgrey" alt="macOS | Linux">
|
|
45
45
|
<img src="https://img.shields.io/badge/dependencies-none-brightgreen" alt="No dependencies">
|
|
@@ -54,15 +54,12 @@ session is stopped, copied to your Mac mini or Linux box, and resumed there with
|
|
|
54
54
|
the same conversation. Open the lid: your laptop takes it back. Training jobs work the
|
|
55
55
|
same way, resuming from their last checkpoint at the other machine's pace.
|
|
56
56
|
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
lid closes
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
copy everything back ◄─────────────
|
|
64
|
-
resume it here
|
|
65
|
-
```
|
|
57
|
+
<p align="center">
|
|
58
|
+
<picture>
|
|
59
|
+
<source media="(prefers-color-scheme: dark)" srcset="docs/handoff-dark.svg">
|
|
60
|
+
<img src="docs/handoff-light.svg" width="860" alt="When the lid closes, the laptop stops the agent, copies the project and conversation to the always-on machine and resumes it there; when the lid opens, everything comes back. Every 30 s a heartbeat, every 5 min a copy; if the laptop is silent for 2 min, the server resumes from the last copy.">
|
|
61
|
+
</picture>
|
|
62
|
+
</p>
|
|
66
63
|
|
|
67
64
|
## Highlights
|
|
68
65
|
|
|
@@ -120,11 +117,15 @@ that needs `sudo`. Details for agents: [AGENT_SETUP.md](AGENT_SETUP.md).
|
|
|
120
117
|
|
|
121
118
|
### By hand
|
|
122
119
|
|
|
120
|
+
NodeHop is on [PyPI](https://pypi.org/project/nodehop/):
|
|
121
|
+
|
|
123
122
|
```sh
|
|
124
|
-
pipx install
|
|
123
|
+
pipx install nodehop
|
|
125
124
|
nodehop onboard # the same questions, with arrow-key menus
|
|
126
125
|
```
|
|
127
126
|
|
|
127
|
+
For the latest changes not yet released: `pipx install git+https://github.com/BuildRunnerFr/NodeHop`.
|
|
128
|
+
|
|
128
129
|
## Daily use
|
|
129
130
|
|
|
130
131
|
```sh
|
|
@@ -1,13 +1,14 @@
|
|
|
1
1
|
[build-system]
|
|
2
|
-
requires = ["setuptools>=
|
|
2
|
+
requires = ["setuptools>=77"]
|
|
3
3
|
build-backend = "setuptools.build_meta"
|
|
4
4
|
|
|
5
5
|
[project]
|
|
6
6
|
name = "nodehop"
|
|
7
|
-
|
|
7
|
+
dynamic = ["version"]
|
|
8
8
|
description = "Close your laptop, your agents keep working: hand off Claude Code sessions and training jobs between your machines."
|
|
9
9
|
readme = "README.md"
|
|
10
|
-
license =
|
|
10
|
+
license = "MIT"
|
|
11
|
+
license-files = ["LICENSE"]
|
|
11
12
|
requires-python = ">=3.9"
|
|
12
13
|
dependencies = []
|
|
13
14
|
keywords = ["claude-code", "ai-agents", "handoff", "tmux", "ssh", "tailscale", "machine-learning", "checkpoint"]
|
|
@@ -15,7 +16,6 @@ classifiers = [
|
|
|
15
16
|
"Development Status :: 3 - Alpha",
|
|
16
17
|
"Environment :: Console",
|
|
17
18
|
"Intended Audience :: Developers",
|
|
18
|
-
"License :: OSI Approved :: MIT License",
|
|
19
19
|
"Operating System :: MacOS",
|
|
20
20
|
"Operating System :: POSIX :: Linux",
|
|
21
21
|
"Programming Language :: Python :: 3",
|
|
@@ -37,5 +37,8 @@ Changelog = "https://github.com/BuildRunnerFr/NodeHop/blob/main/CHANGELOG.md"
|
|
|
37
37
|
[project.scripts]
|
|
38
38
|
nodehop = "nodehop.cli:main"
|
|
39
39
|
|
|
40
|
+
[tool.setuptools.dynamic]
|
|
41
|
+
version = { attr = "nodehop.__version__" } # the one place the version is written
|
|
42
|
+
|
|
40
43
|
[tool.setuptools.packages.find]
|
|
41
44
|
include = ["nodehop*"]
|
|
@@ -531,6 +531,145 @@ class SleepBudgetTests(Base):
|
|
|
531
531
|
proc.kill()
|
|
532
532
|
|
|
533
533
|
|
|
534
|
+
class ReviewFixTests(Base):
|
|
535
|
+
"""Bugs found before the public launch: each one would lose, strand or duplicate work."""
|
|
536
|
+
|
|
537
|
+
def two_projects(self):
|
|
538
|
+
gone = self.tmp / "code" / "gone" # protected, then deleted without `nodehop off`
|
|
539
|
+
self.cfg.projects["gone"] = Project(name="gone", path=str(gone), module="command", command="true")
|
|
540
|
+
return self.hop()
|
|
541
|
+
|
|
542
|
+
def test_a_project_that_cannot_be_copied_does_not_silence_the_heartbeat(self):
|
|
543
|
+
hop = self.two_projects()
|
|
544
|
+
with self.assertRaises(RuntimeError) as failure:
|
|
545
|
+
hop.sync("macmini")
|
|
546
|
+
self.assertIn("gone", str(failure.exception))
|
|
547
|
+
self.assertNotIn("app (", str(failure.exception))
|
|
548
|
+
self.assertEqual(len(self.runner.find(["rsync"])), 2) # app was copied all the same
|
|
549
|
+
beat = [c[-1] for c in self.runner.find(["ssh"]) if " heartbeat " in c[-1]][-1]
|
|
550
|
+
metas = json.loads(shlex.split(beat.split("; ", 1)[1])[-1])
|
|
551
|
+
self.assertTrue(metas["app"]["copied"])
|
|
552
|
+
self.assertFalse(metas["gone"]["copied"])
|
|
553
|
+
self.assertIn("copied_at", hop.state.get("app"))
|
|
554
|
+
self.assertNotIn("copied_at", hop.state.get("gone"))
|
|
555
|
+
hop.sync("macmini") # 30 s later: a plain heartbeat, no error
|
|
556
|
+
|
|
557
|
+
def test_rsync_failure_on_one_project_still_beats(self):
|
|
558
|
+
hop = self.hop()
|
|
559
|
+
self.runner.fail_rsync = True
|
|
560
|
+
with self.assertRaises(RuntimeError):
|
|
561
|
+
hop.sync("macmini")
|
|
562
|
+
self.assertTrue(any(" heartbeat " in c[-1] for c in self.runner.find(["ssh"])))
|
|
563
|
+
|
|
564
|
+
def test_dotted_names_get_the_session_name_tmux_really_uses(self):
|
|
565
|
+
from nodehop.modules.base import Module
|
|
566
|
+
|
|
567
|
+
site = Project(name="example.com", path=str(self.proj))
|
|
568
|
+
self.assertEqual(Module.session(site), "nh-example_com")
|
|
569
|
+
self.cfg.projects = {"example.com": site}
|
|
570
|
+
hop = self.hop()
|
|
571
|
+
hop.start("example.com")
|
|
572
|
+
self.assertEqual(self.runner.sessions, {"nh-example_com"})
|
|
573
|
+
self.assertTrue(hop.stop("example.com"))
|
|
574
|
+
self.assertEqual(self.runner.sessions, set())
|
|
575
|
+
|
|
576
|
+
def test_names_that_would_share_a_session_or_escape_a_folder_are_refused(self):
|
|
577
|
+
self.cfg.add_project("my.site", "/Users/a/my.site")
|
|
578
|
+
with self.assertRaises(ConfigError):
|
|
579
|
+
self.cfg.add_project("my_site", "/Users/a/my_site")
|
|
580
|
+
for bad in ("", "..", "a/b", "-x"):
|
|
581
|
+
with self.assertRaises(ConfigError):
|
|
582
|
+
self.cfg.add_project(bad, "/Users/a/x")
|
|
583
|
+
with self.assertRaises(ConfigError):
|
|
584
|
+
self.hop("macmini").prepare("../x", "claude-code", "/Users/a/x", "/Users/a")
|
|
585
|
+
|
|
586
|
+
def test_remote_paths_are_quoted_the_way_every_rsync_understands(self):
|
|
587
|
+
with mock.patch.dict(os.environ):
|
|
588
|
+
os.environ.pop("RSYNC_OLD_ARGS", None)
|
|
589
|
+
self.runner.remote_path = "/Users/alice/My Code/été"
|
|
590
|
+
self.hop().handoff(["app"], "macmini")
|
|
591
|
+
self.assertEqual(os.environ.get("RSYNC_OLD_ARGS"), "1") # rsync >= 3.2.4 would keep the quotes
|
|
592
|
+
self.assertEqual(self.runner.find(["rsync"])[0][-1], "mac-mini:'/Users/alice/My Code/été/'")
|
|
593
|
+
|
|
594
|
+
def test_first_copy_keeps_what_the_folder_already_held(self):
|
|
595
|
+
self.cfg.workspace = str(self.tmp / "ws")
|
|
596
|
+
there = self.tmp / "ws" / "fresh"
|
|
597
|
+
there.mkdir(parents=True)
|
|
598
|
+
(there / "unpushed.txt").write_text("only on the mini")
|
|
599
|
+
where = self.hop("macmini").prepare("fresh", "claude-code", "/Users/a/fresh", "/Users/a")
|
|
600
|
+
self.assertEqual((Path(where["backup"]) / "project" / "unpushed.txt").read_text(), "only on the mini")
|
|
601
|
+
again = self.hop("macmini").prepare("fresh", "claude-code", "/Users/a/fresh", "/Users/a")
|
|
602
|
+
self.assertNotIn("backup", again) # known now: later copies are the normal flow
|
|
603
|
+
empty = self.hop("macmini").prepare("other", "claude-code", "/Users/a/other", "/Users/a")
|
|
604
|
+
self.assertNotIn("backup", empty)
|
|
605
|
+
|
|
606
|
+
def test_backups_of_similar_names_are_left_alone(self):
|
|
607
|
+
hop = self.hop()
|
|
608
|
+
self.cfg.backups_keep = 1
|
|
609
|
+
backups = self.tmp / "nh" / "backups"
|
|
610
|
+
for other in ("app-web-20260101-000000", "app-from-macmini-20260101-000000"):
|
|
611
|
+
(backups / other).mkdir(parents=True)
|
|
612
|
+
hop.backup("app", "one")
|
|
613
|
+
hop.backup("app", "two")
|
|
614
|
+
left = sorted(p.name for p in backups.iterdir())
|
|
615
|
+
self.assertEqual(len(left), 3)
|
|
616
|
+
self.assertIn("app-web-20260101-000000", left)
|
|
617
|
+
self.assertIn("app-from-macmini-20260101-000000", left)
|
|
618
|
+
|
|
619
|
+
def lost_answer(self):
|
|
620
|
+
"""`receive` worked over there, but its answer never came back."""
|
|
621
|
+
where = {"path": str(self.proj), "inbox": self.runner.remote_inbox, "owner": "macmini"}
|
|
622
|
+
self.runner.answers += [(" receive ", 255, ""), (" prepare ", 0, json.dumps(where) + "\n")]
|
|
623
|
+
|
|
624
|
+
def test_a_lost_answer_is_not_a_failed_handoff(self):
|
|
625
|
+
self.runner.sessions.add("nh-app")
|
|
626
|
+
self.lost_answer()
|
|
627
|
+
hop = self.hop()
|
|
628
|
+
self.assertEqual(hop.handoff(["app"], "macmini"), ["app"])
|
|
629
|
+
self.assertEqual(hop.owner("app"), "macmini")
|
|
630
|
+
self.assertNotIn("nh-app", self.runner.sessions) # no second agent here
|
|
631
|
+
self.assertEqual(sum(" receive " in c[-1] for c in self.runner.find(["ssh"])), 1) # not sent twice
|
|
632
|
+
|
|
633
|
+
def test_a_refusal_from_the_other_machine_is_still_a_failed_handoff(self):
|
|
634
|
+
self.runner.sessions.add("nh-app")
|
|
635
|
+
self.lost_answer()
|
|
636
|
+
self.runner.answers[-2] = (" receive ", 1, "") # it answered: no
|
|
637
|
+
hop = self.hop()
|
|
638
|
+
self.assertEqual(hop.handoff(["app"], "macmini"), [])
|
|
639
|
+
self.assertEqual(hop.owner("app"), "macbook")
|
|
640
|
+
self.assertIn("nh-app", self.runner.sessions) # restarted here, as before
|
|
641
|
+
|
|
642
|
+
def test_a_handoff_that_went_through_at_sleep_is_pulled_back_on_wake(self):
|
|
643
|
+
self.runner.sessions.add("nh-app")
|
|
644
|
+
hop = self.hop()
|
|
645
|
+
self.runner.fail_rsync = True
|
|
646
|
+
hop.on_sleep()
|
|
647
|
+
self.assertTrue(hop.state.get("app")["paused_for_sleep"])
|
|
648
|
+
self.runner.fail_rsync = False
|
|
649
|
+
self.lost_answer()
|
|
650
|
+
meta = {"path": str(self.proj), "session_id": "abc-123", "was_running": True, "was_busy": True}
|
|
651
|
+
self.runner.answers.append((" release app ", 0, json.dumps(meta) + "\n"))
|
|
652
|
+
self.assertEqual(hop.on_wake(attempts=1, wait=0), ["app"])
|
|
653
|
+
self.assertTrue(any(" release app " in c[-1] for c in self.runner.find(["ssh"]))) # taken back, not restarted over it
|
|
654
|
+
self.assertEqual(hop.owner("app"), "macbook")
|
|
655
|
+
self.assertFalse(hop.state.get("app")["paused_for_sleep"])
|
|
656
|
+
|
|
657
|
+
def test_a_fallback_is_settled_once_by_two_processes(self):
|
|
658
|
+
claim = (" claims ", 0, json.dumps({"app": {"owner": "macmini", "reason": "failover"}}) + "\n")
|
|
659
|
+
self.runner.answers.append(claim)
|
|
660
|
+
first, second = self.hop(), self.hop() # on-wake and the 30 s sync, each with its own view
|
|
661
|
+
# The first one has decided "the server's version wins" and is pulling it back.
|
|
662
|
+
first._record("app", owner="macmini", origin="macbook", reason="failover")
|
|
663
|
+
self.assertEqual(second.owner("app"), "macbook") # what the second one read before that
|
|
664
|
+
self.assertEqual(second.reconcile("macmini"), []) # it looks again before acting
|
|
665
|
+
self.assertFalse((self.tmp / "nh" / "backups").exists()) # no backup of a half-copied tree
|
|
666
|
+
self.assertFalse(any(" release " in c[-1] or " pause " in c[-1] for c in self.runner.find(["ssh"])))
|
|
667
|
+
|
|
668
|
+
def test_merge_brief_names_the_right_conversation_folder(self):
|
|
669
|
+
self.assertIn("/b/codex", NodeHop.conflict_brief("app", "macmini", None, "/b", ["codex"]))
|
|
670
|
+
self.assertNotIn("conversation", NodeHop.conflict_brief("app", "macmini", None, "/b", []))
|
|
671
|
+
|
|
672
|
+
|
|
534
673
|
class SleepTests(Base):
|
|
535
674
|
def test_on_sleep_only_on_primary(self):
|
|
536
675
|
self.assertEqual(self.hop().on_sleep(), ["app"])
|
|
@@ -679,7 +818,10 @@ class OnboardTests(Base):
|
|
|
679
818
|
self.cfg.projects["app"].active = False
|
|
680
819
|
self.assertEqual(self.plan(checks=ok)["next"]["id"], "projects")
|
|
681
820
|
self.cfg.projects["app"].active = True
|
|
682
|
-
self.
|
|
821
|
+
step = self.plan(checks=ok)["next"]
|
|
822
|
+
self.assertEqual(step["id"], "unattended")
|
|
823
|
+
remote = next(q for q in step["questions"] if q["id"] == "remote")
|
|
824
|
+
self.assertEqual(remote["default"], "no") # Remote Control stays off unless the person says yes
|
|
683
825
|
self.cfg.unattended = "acceptEdits"
|
|
684
826
|
done = self.plan(checks=ok)
|
|
685
827
|
self.assertTrue(done["complete"])
|
|
@@ -966,6 +1108,24 @@ class CliTests(unittest.TestCase):
|
|
|
966
1108
|
self.assertFalse(Config.load().project("proj").active)
|
|
967
1109
|
self.assertEqual(cli.main(["off", "/nowhere"]), 1)
|
|
968
1110
|
|
|
1111
|
+
def test_two_folders_with_the_same_name_stay_two_projects(self):
|
|
1112
|
+
with tempfile.TemporaryDirectory() as d, mock.patch.dict(os.environ, {"NODEHOP_HOME": d}):
|
|
1113
|
+
first, second = Path(d) / "clientA" / "api", Path(d) / "clientB" / "api"
|
|
1114
|
+
first.mkdir(parents=True)
|
|
1115
|
+
second.mkdir(parents=True)
|
|
1116
|
+
cli.main(["init", "--name", "mini"])
|
|
1117
|
+
with contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(io.StringIO()) as err:
|
|
1118
|
+
self.assertEqual(cli.main(["on", str(first)]), 0)
|
|
1119
|
+
self.assertEqual(cli.main(["on", str(second)]), 1)
|
|
1120
|
+
self.assertIn("--name", err.getvalue())
|
|
1121
|
+
self.assertEqual(Config.load().project("api").path, str(first.resolve()))
|
|
1122
|
+
self.assertEqual(cli.main(["project", "add", str(second)]), 1)
|
|
1123
|
+
self.assertEqual(cli.main(["on", str(second), "--name", "api-b"]), 0)
|
|
1124
|
+
self.assertEqual(cli.main(["on", str(first)]), 0) # the same folder again: fine
|
|
1125
|
+
cfg = Config.load()
|
|
1126
|
+
self.assertEqual(cfg.project("api").path, str(first.resolve()))
|
|
1127
|
+
self.assertEqual(cfg.project("api-b").path, str(second.resolve()))
|
|
1128
|
+
|
|
969
1129
|
def test_refuses_home_as_project(self):
|
|
970
1130
|
with tempfile.TemporaryDirectory() as d, mock.patch.dict(os.environ, {"NODEHOP_HOME": d}):
|
|
971
1131
|
cli.main(["init", "--name", "macbook"])
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|