nodehop 0.2.0__py3-none-any.whl

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/core.py ADDED
@@ -0,0 +1,642 @@
1
+ """The relay itself: handoff, receive, hand back, pre-sync."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import shutil
7
+ import threading
8
+ import time
9
+ from pathlib import Path
10
+ from typing import Callable, Dict, Iterable, List, Optional
11
+
12
+ from nodehop import gui
13
+ from nodehop.config import Config, Peer, Project, home_dir
14
+ from nodehop.modules import get_module
15
+ from nodehop.modules.base import Module
16
+ from nodehop.runner import Runner
17
+ from nodehop.state import State, locked
18
+ from nodehop.transport import SSHTransport
19
+
20
+ TransportFactory = Callable[..., SSHTransport]
21
+
22
+
23
+ class NodeHop:
24
+ def __init__(
25
+ self,
26
+ config: Config,
27
+ runner: Runner,
28
+ state: Optional[State] = None,
29
+ transport_factory: TransportFactory = SSHTransport,
30
+ ):
31
+ self.config = config
32
+ self.runner = runner
33
+ self.state = state or State()
34
+ self.transport_factory = transport_factory
35
+
36
+ # ---- helpers ------------------------------------------------------------
37
+ @property
38
+ def me(self) -> str:
39
+ return self.config.machine
40
+
41
+ def module(self, project: Project) -> Module:
42
+ return get_module(project.module)(self.config, self.runner)
43
+
44
+ def transport(self, machine: str) -> SSHTransport:
45
+ return self.transport_factory(
46
+ self.config.peer(machine), self.runner, self.config.extra_path, ssh_key=self.config.ssh_key_path()
47
+ )
48
+
49
+ def owner(self, name: str) -> str:
50
+ return self.state.owner(name, default=self.config.primary)
51
+
52
+ def _record(self, name: str, **fields) -> None:
53
+ if self.runner.dry_run:
54
+ self.runner.log(f"[dry-run] would record {name}: {fields}")
55
+ return
56
+ self.state.update(name, **fields)
57
+
58
+ @staticmethod
59
+ def inbox(name: str) -> Path:
60
+ return home_dir() / "inbox" / name
61
+
62
+ def owned_here(self) -> List[str]:
63
+ return [name for name in self.config.projects if self.owner(name) == self.me]
64
+
65
+ def in_conflict(self, name: str) -> bool:
66
+ return bool(self.state.get(name).get("conflict"))
67
+
68
+ def active_here(self) -> List[str]:
69
+ """Projects NodeHop protects right now: owned here, switched on, no pending conflict."""
70
+ return [
71
+ name for name in self.owned_here()
72
+ if self.config.projects[name].active and not self.in_conflict(name)
73
+ ]
74
+
75
+ # ---- local agent control -----------------------------------------------
76
+ def start(self, name: str, resume: bool = False) -> None:
77
+ project = self.config.project(name)
78
+ owner = self.owner(name)
79
+ if owner != self.me:
80
+ raise RuntimeError(f"{name} is owned by {owner}: run `nodehop pull {name}` to take it back first")
81
+ module = self.module(project)
82
+ meta = module.snapshot(project) if resume else {}
83
+ module.start(project, meta, resume=resume)
84
+
85
+ def stop(self, name: str) -> bool:
86
+ project = self.config.project(name)
87
+ return self.module(project).stop(project)
88
+
89
+ # ---- handoff (sender side) ----------------------------------------------
90
+ def handoff(self, names: Iterable[str], target: str, reason: str = "manual", force: bool = False,
91
+ deadline: Optional[float] = None) -> List[str]:
92
+ """Stop each project here, copy it to `target`, and resume it there.
93
+
94
+ `deadline` (time.monotonic()) bounds the copies: going to sleep, a
95
+ transfer that would not finish in time is cut short and the target
96
+ resumes from the last complete pre-sync copy it already has.
97
+ """
98
+ if target == self.me:
99
+ raise ValueError("cannot hand off to this machine itself")
100
+ done = []
101
+ with locked(preempt=reason == "sleep"):
102
+ transport = self.transport(target)
103
+ for name in names:
104
+ project = self.config.project(name)
105
+ if self.owner(name) != self.me and not force:
106
+ self.runner.log(f"{name}: skipped, owned by {self.owner(name)}")
107
+ continue
108
+ if self._handoff_one(project, transport, target, reason, deadline):
109
+ done.append(name)
110
+ return done
111
+
112
+ def _handoff_one(self, project: Project, transport: SSHTransport, target: str, reason: str,
113
+ deadline: Optional[float] = None) -> bool:
114
+ module = self.module(project)
115
+ self.runner.log(f"{project.name}: handoff to {target} ({reason})")
116
+ was_busy = module.is_running(project) and module.is_busy(project)
117
+ was_running = module.stop(project)
118
+ meta = module.snapshot(project)
119
+ meta.update({"was_running": was_running, "was_busy": was_busy, "reason": reason})
120
+ if was_running:
121
+ self.runner.log(f"{project.name}: agent was {'working' if was_busy else 'idle'}")
122
+ try:
123
+ self._push(project, module, meta, transport, deadline)
124
+ transport.nodehop("receive", project.name, "--from", self.me, "--meta", json.dumps(meta))
125
+ if self.runner.dry_run:
126
+ self.runner.log(f"{project.name}: [dry-run] would now run on {target}")
127
+ return True
128
+ except Exception as exc: # leave the work where it was rather than lose it
129
+ self.runner.log(f"{project.name}: handoff to {target} failed: {exc}")
130
+ if reason == "sleep" and self._resume_from_last_copy(project, transport, target, meta):
131
+ return True
132
+ if was_running and reason != "sleep":
133
+ module.start(project, meta, resume=True)
134
+ elif was_running:
135
+ self._record(project.name, paused_for_sleep=True) # restarted here on wake-up
136
+ return False
137
+ self._record(project.name, owner=target, origin=self.me, reason=reason,
138
+ session_id=meta.get("session_id"), paused_for_sleep=False)
139
+ self.runner.log(f"{project.name}: now running on {target}")
140
+ return True
141
+
142
+ def _resume_from_last_copy(self, project: Project, transport: SSHTransport, target: str, meta: dict) -> bool:
143
+ """Going to sleep, the newest state did not get through: let the target go on from its last full copy."""
144
+ copied_at = self.state.get(project.name).get("copied_at")
145
+ if not copied_at or not meta.get("was_running"):
146
+ return False
147
+ when = time.strftime("%H:%M", time.localtime(copied_at))
148
+ meta = dict(meta, failover=True, copy_time=when, partial=True)
149
+ try:
150
+ transport.nodehop("receive", project.name, "--from", self.me, "--meta", json.dumps(meta), timeout=15)
151
+ except Exception as exc:
152
+ self.runner.log(f"{project.name}: could not reach {target} either: {exc}")
153
+ self._record(project.name, paused_for_sleep=True)
154
+ return False
155
+ self._record(project.name, owner=target, origin=self.me, reason="sleep", paused_for_sleep=False)
156
+ self.runner.log(f"{project.name}: newest state did not fit in the time before sleep; "
157
+ f"{target} resumes from the copy of {when}")
158
+ return True
159
+
160
+ def _push(self, project: Project, module: Module, meta: dict, transport: SSHTransport,
161
+ deadline: Optional[float] = None) -> None:
162
+ def budget() -> float:
163
+ if deadline is None:
164
+ return 1800
165
+ left = deadline - time.monotonic()
166
+ if left <= 1:
167
+ raise TimeoutError("no time left before sleep")
168
+ return left
169
+
170
+ where = transport.prepare(project.name, project.module, project.path, str(Path.home()))
171
+ remote_path, remote_inbox = where["path"], where["inbox"]
172
+ if remote_path != project.path:
173
+ self.runner.log(f"{project.name}: {project.path} here -> {remote_path} on {transport.peer.name}")
174
+ transport.push_dir(Path(project.path), remote_path, delete=True, excludes=self.config.excludes, timeout=budget())
175
+ for label, local in module.payload(project, meta):
176
+ # --delete keeps the inbox an exact copy, so nothing stale gets re-imported.
177
+ transport.push_dir(local, f"{remote_inbox}/{label}", delete=True, timeout=budget())
178
+
179
+ # ---- prepare (target side, called over SSH before files are sent) --------
180
+ def prepare(self, name: str, module: str, origin_path: str, origin_home: Optional[str]) -> dict:
181
+ """Say where `name` lives on this machine, registering it if it is new here."""
182
+ path = self.config.local_path_for(name, origin_path, origin_home)
183
+ if name not in self.config.projects:
184
+ self.config.projects[name] = Project(name=name, path=path, module=module)
185
+ if self.runner.dry_run:
186
+ self.runner.log(f"[dry-run] would track {name} at {path}")
187
+ else:
188
+ self.config.save()
189
+ self.runner.log(f"{name}: new project here, tracked at {path}")
190
+ return {"path": path, "inbox": str(self.inbox(name)), "machine": self.me}
191
+
192
+ # ---- receive (target side, called over SSH) -----------------------------
193
+ def receive(self, name: str, origin: str, meta: Dict) -> None:
194
+ with locked():
195
+ self._take(name, origin, meta)
196
+ self.runner.log(f"{name}: received from {origin}")
197
+
198
+ def _take(self, name: str, origin: str, meta: Dict, reason: str = "received") -> None:
199
+ """Put what arrived in the inbox in place, become the owner, resume if it was running."""
200
+ project = self.config.project(name)
201
+ if meta.get("command") and project.command != meta["command"] and not self.runner.dry_run:
202
+ project.command = meta["command"] # the command travels with the project
203
+ self.config.save()
204
+ module = self.module(project)
205
+ module.stop(project) # never leave a stale copy running next to the new one
206
+ module.accept_payload(project, self.inbox(name), meta)
207
+ self._record(name, owner=self.me, origin=origin, reason=reason, session_id=meta.get("session_id"))
208
+ if meta.get("was_running") and module.should_resume(meta):
209
+ module.start(project, meta, resume=True)
210
+
211
+ # ---- pull: fetch a project back from its current owner ---------------------
212
+ # Only this machine opens connections: the other one never needs to reach it,
213
+ # so a laptop needs no SSH server of its own (only the always-on machine does).
214
+ def pull(self, names: Iterable[str]) -> List[str]:
215
+ done = []
216
+ with locked():
217
+ self.state.reload() # another process (on-wake, sync) may have pulled it meanwhile
218
+ for name in names:
219
+ owner = self.owner(name)
220
+ if owner == self.me:
221
+ self.runner.log(f"{name}: already here")
222
+ continue
223
+ if self._pull_one(name, owner):
224
+ done.append(name)
225
+ return done
226
+
227
+ def _pull_one(self, name: str, owner: str) -> bool:
228
+ transport = self.transport(owner)
229
+ self.runner.log(f"{name}: taking it back from {owner}")
230
+ try:
231
+ result = transport.nodehop("release", name, "--to", self.me, "--json", timeout=120, mutating=not self.runner.dry_run)
232
+ except Exception as exc:
233
+ self.runner.log(f"{name}: {owner} could not release it: {exc}")
234
+ return False
235
+ if self.runner.dry_run:
236
+ self.runner.log(f"{name}: [dry-run] would copy it back from {owner} and resume it here")
237
+ return True
238
+ meta = json.loads(result.stdout.strip().splitlines()[-1])
239
+ if name not in self.config.projects: # started over there: give it a home here
240
+ path = self.config.local_path_for(name, meta["path"], meta.get("home"))
241
+ self.config.projects[name] = Project(name=name, path=path, module=meta.get("module", "claude-code"))
242
+ self.config.save()
243
+ project = self.config.project(name)
244
+ module = self.module(project)
245
+ try:
246
+ transport.pull_dir(meta["path"], Path(project.path), delete=True, excludes=self.config.excludes)
247
+ for label, remote in module.payload(project, meta):
248
+ transport.pull_dir(str(remote), self.inbox(name) / label, delete=True)
249
+ transport.nodehop("released", name, "--to", self.me)
250
+ except Exception as exc: # the work stays over there: restart it where it was
251
+ self.runner.log(f"{name}: pulling from {owner} failed: {exc}")
252
+ if meta.get("was_running"):
253
+ transport.nodehop("start", name, "--resume", check=False)
254
+ return False
255
+ self._take(name, "", meta, reason="pulled")
256
+ self.runner.log(f"{name}: back on {self.me}")
257
+ return True
258
+
259
+ # ---- release (owner side, called over SSH by the machine pulling) ---------------
260
+ def release(self, name: str, to: str) -> dict:
261
+ """Stop the agent and describe the project so `to` can copy it. Ownership moves on `released`."""
262
+ project = self.config.project(name)
263
+ if self.owner(name) != self.me:
264
+ raise RuntimeError(f"{name} is not on {self.me} (owner: {self.owner(name)})")
265
+ module = self.module(project)
266
+ with locked():
267
+ was_busy = module.is_running(project) and module.is_busy(project)
268
+ was_running = module.stop(project)
269
+ meta = module.snapshot(project)
270
+ meta.update({"was_running": was_running, "was_busy": was_busy, "home": str(Path.home()),
271
+ "module": project.module, "reason": "pull"})
272
+ state = ("working" if was_busy else "idle") if was_running else "not running"
273
+ self.runner.log(f"{name}: released for {to} (agent was {state})")
274
+ return meta
275
+
276
+ def released(self, name: str, to: str) -> None:
277
+ self._record(name, owner=to, origin="", reason="pulled", conflict=None)
278
+ self.runner.log(f"{name}: now on {to}")
279
+
280
+ def away_from_home(self) -> List[str]:
281
+ """Projects this machine sent away when it went to sleep, to take back now it is awake."""
282
+ return [
283
+ name
284
+ for name in self.config.projects
285
+ if self.owner(name) != self.me
286
+ and self.state.get(name).get("origin") == self.me
287
+ and self.state.get(name).get("reason") == "sleep"
288
+ ]
289
+
290
+ def reclaim(self, attempts: int = 1, wait: float = 10.0) -> List[str]:
291
+ """Settle fallbacks and pull back what went away at sleep, retrying while the network comes back."""
292
+ back: List[str] = []
293
+ pending = set(self.config.peers)
294
+ for attempt in range(attempts):
295
+ for peer in sorted(pending):
296
+ if not self.transport(peer).is_up():
297
+ continue
298
+ back += self.reconcile(peer)
299
+ due = [n for n in self.away_from_home() if self.owner(n) == peer]
300
+ if due:
301
+ back += self.pull(due)
302
+ pending.discard(peer)
303
+ if not pending:
304
+ break
305
+ if attempt < attempts - 1:
306
+ self.runner.sleep(wait)
307
+ return back
308
+
309
+ # ---- pre-sync: keep the target warm so the sleep handoff is fast -----------
310
+ def sync(self, target: str, force_copy: bool = False) -> None:
311
+ """Primary, every 30 s: settle conflicts, take back what is due, say "alive",
312
+ and every `presync_seconds` also pre-copy the active projects."""
313
+ if self.me == self.config.primary:
314
+ self.reclaim() # awake again: anything sent away at sleep comes home first
315
+ transport = self.transport(target)
316
+ if not transport.is_up():
317
+ self.runner.log(f"sync: {target} unreachable, skipped")
318
+ return
319
+ now = time.time()
320
+ copy_due = force_copy or now - self.state.local().get("last_copy", 0) >= self.config.presync_seconds
321
+ metas: Dict[str, dict] = {}
322
+ light = {}
323
+ for name in self.active_here():
324
+ project = self.config.project(name)
325
+ module = self.module(project)
326
+ running = module.is_running(project)
327
+ light[name] = {"was_running": running, "was_busy": running and module.is_busy(project), "copied": False}
328
+ # A copy can take minutes on a slow link: keep saying "alive" meanwhile, or the
329
+ # server would think this machine is gone and start a fallback.
330
+ stop_beating = threading.Event()
331
+
332
+ def keep_beating() -> None:
333
+ while not stop_beating.wait(self.config.beat_seconds):
334
+ transport.nodehop("heartbeat", "--from", self.me, "--meta", json.dumps(light),
335
+ check=False, timeout=20)
336
+
337
+ beater = threading.Thread(target=keep_beating, daemon=True)
338
+ if copy_due:
339
+ beater.start()
340
+ with locked(role="sync"):
341
+ for name in self.active_here():
342
+ project = self.config.project(name)
343
+ module = self.module(project)
344
+ running = module.is_running(project)
345
+ busy = running and module.is_busy(project)
346
+ if copy_due:
347
+ meta = module.snapshot(project)
348
+ meta.update({"was_running": running, "was_busy": busy, "copied": True})
349
+ self._push(project, module, meta, transport)
350
+ else:
351
+ meta = {"was_running": running, "was_busy": busy, "copied": False}
352
+ metas[name] = meta
353
+ stop_beating.set()
354
+ if copy_due and not self.runner.dry_run:
355
+ self.state.update_local(last_copy=now)
356
+ # The heartbeat comes last: it vouches that the copies above are complete.
357
+ transport.nodehop("heartbeat", "--from", self.me, "--meta", json.dumps(metas), timeout=60)
358
+ if not self.runner.dry_run:
359
+ for name, meta in metas.items():
360
+ if meta.get("copied"):
361
+ self.state.update(name, copied_at=now)
362
+
363
+ # ---- fallback: the primary vanished without going to sleep -------------------
364
+ def heartbeat(self, origin: str, metas: Dict[str, dict]) -> None:
365
+ """Server side: the primary is alive, and here is what it was doing at its last pre-sync."""
366
+ now = time.time()
367
+ if self.runner.dry_run:
368
+ return
369
+ if Config.path().exists():
370
+ self.config = Config.load()
371
+ self.state.update_peer(origin, last_seen=now)
372
+ for name in self.config.projects:
373
+ entry = self.state.get(name)
374
+ meta = metas.get(name)
375
+ if meta is None:
376
+ if entry.get("presync"): # switched off, or no longer on the primary: nothing to cover
377
+ self.state.update(name, presync=None)
378
+ elif meta.get("copied"):
379
+ self.state.update(name, presync=meta, presync_at=now)
380
+ elif entry.get("presync"):
381
+ self.state.update(name, presync=dict(entry["presync"], was_busy=meta.get("was_busy")))
382
+
383
+ def failover_tick(self, now: Optional[float] = None) -> List[str]:
384
+ """Server side: resume, from the last pre-sync, the work of a primary that went silent."""
385
+ now = now or time.time()
386
+ self.state.reload()
387
+ if Config.path().exists():
388
+ self.config = Config.load() # projects registered since the watcher started
389
+ primary = self.config.primary
390
+ limit = self.config.failover_minutes * 60
391
+ if not primary or primary == self.me or limit <= 0:
392
+ return []
393
+ seen = self.state.peer(primary).get("last_seen")
394
+ if not seen or now - seen < limit:
395
+ return []
396
+ taken = []
397
+ for name in list(self.config.projects):
398
+ entry = self.state.get(name)
399
+ presync = entry.get("presync") or {}
400
+ if self.owner(name) != primary or not presync.get("was_busy"):
401
+ continue # not the primary's, or nothing was in progress there
402
+ minutes = int((now - seen) // 60)
403
+ self.runner.log(f"{name}: no news from {primary} for {minutes} min, taking over from its last pre-sync")
404
+ meta = dict(presync, was_running=True, failover=True,
405
+ copy_time=time.strftime("%H:%M", time.localtime(entry.get("presync_at", seen))))
406
+ with locked():
407
+ self._take(name, primary, meta, reason="failover")
408
+ self._record(name, failover_at=now)
409
+ taken.append(name)
410
+ return taken
411
+
412
+ def claims(self) -> Dict[str, dict]:
413
+ """What this machine runs on behalf of others after a fallback (asked by the primary)."""
414
+ self.state.reload()
415
+ out = {}
416
+ for name, project in self.config.projects.items():
417
+ entry = self.state.get(name)
418
+ if self.owner(name) != self.me or entry.get("reason") != "failover":
419
+ continue
420
+ since = entry.get("failover_at") or 0
421
+ copied = entry.get("presync_at")
422
+ out[name] = {"owner": self.me, "reason": "failover", "origin": entry.get("origin"),
423
+ "since": since, "copy_time": time.strftime("%H:%M", time.localtime(copied)) if copied else None,
424
+ "progress": self.module(project).progress(project, since)}
425
+ return out
426
+
427
+ def backup(self, name: str, why: str) -> Optional[Path]:
428
+ """Keep this machine's copy of a project (files + conversation) before it is overwritten."""
429
+ project = self.config.project(name)
430
+ dest = home_dir() / "backups" / f"{name}-{time.strftime('%Y%m%d-%H%M%S')}"
431
+ n = 2
432
+ while dest.exists(): # two backups in the same second
433
+ dest = dest.with_name(f"{name}-{time.strftime('%Y%m%d-%H%M%S')}-{n}")
434
+ n += 1
435
+ if self.runner.dry_run:
436
+ self.runner.log(f"[dry-run] would back up {name} to {dest}")
437
+ return dest
438
+ source = Path(project.path)
439
+ if source.is_dir():
440
+ shutil.copytree(source, dest / "project", symlinks=True,
441
+ ignore=shutil.ignore_patterns(*self.config.excludes))
442
+ module = self.module(project)
443
+ for label, local in module.payload(project, module.snapshot(project)):
444
+ if Path(local).is_dir():
445
+ shutil.copytree(local, dest / label)
446
+ (dest / "WHY.txt").parent.mkdir(parents=True, exist_ok=True)
447
+ (dest / "WHY.txt").write_text(why + "\n")
448
+ self.runner.log(f"{name}: kept a copy of this machine's version in {dest}")
449
+ # Backups hold full copies of the project (secrets included): do not let them pile up.
450
+ others = sorted((p for p in dest.parent.glob(f"{name}-*") if p.is_dir() and p != dest),
451
+ key=lambda p: p.stat().st_mtime)
452
+ keep_others = max(0, self.config.backups_keep - 1)
453
+ for stale in others[:len(others) - keep_others]:
454
+ shutil.rmtree(stale, ignore_errors=True)
455
+ return dest
456
+
457
+ def ask_person(self, name: str) -> None:
458
+ """Show the conflict window on this desktop (falls back to a plain notification)."""
459
+ if self.runner.dry_run:
460
+ return
461
+ try:
462
+ shown = gui.ask_conflict(self.conflict_report(name))
463
+ except Exception as exc:
464
+ self.runner.log(f"{name}: could not open the conflict window: {exc}")
465
+ shown = False
466
+ if not shown:
467
+ gui.notify(f"Two agents on {name}", f"Two agents worked in parallel. Run: nodehop resolve {name}")
468
+
469
+ def pause(self, name: str) -> None:
470
+ """Server side: stop our copy of the agent while the person decides (files and conversation stay)."""
471
+ project = self.config.project(name)
472
+ with locked():
473
+ self.module(project).stop(project)
474
+ self._record(name, conflict=True)
475
+ self.runner.log(f"{name}: agent paused, waiting for the person to choose which version to keep")
476
+
477
+ def progress(self, name: str, since: float) -> dict:
478
+ project = self.config.project(name)
479
+ return self.module(project).progress(project, since)
480
+
481
+ def conflict_report(self, name: str) -> dict:
482
+ """Primary: both sides' progress since the server took over."""
483
+ conflict = self.state.get(name).get("conflict") or {}
484
+ if not conflict:
485
+ raise RuntimeError(f"{name}: no conflict to resolve")
486
+ peer, since = conflict["peer"], conflict.get("since") or 0
487
+ project = self.config.project(name)
488
+ here = self.module(project).progress(project, since)
489
+ result = self.transport(peer).nodehop("progress", name, "--since", str(since), timeout=60, mutating=False)
490
+ there = json.loads(result.stdout.strip().splitlines()[-1])
491
+ return {"project": name, "since": since, "copy_time": conflict.get("copy_time"), "here": dict(here, machine=self.me),
492
+ "there": dict(there, machine=peer)}
493
+
494
+ def resolve(self, name: str, keep: str) -> dict:
495
+ """Primary: settle a conflict. keep = here | there | merge (here, briefed on the other's work)."""
496
+ conflict = self.state.get(name).get("conflict") or {}
497
+ if not conflict:
498
+ raise RuntimeError(f"{name}: no conflict to resolve")
499
+ peer = conflict["peer"]
500
+ project = self.config.project(name)
501
+ module = self.module(project)
502
+ transport = self.transport(peer)
503
+ result = {"project": name, "kept": keep}
504
+ if keep in ("here", "merge"):
505
+ if keep == "merge":
506
+ # Fetch the other version next to the project before the server sets it aside.
507
+ there = home_dir() / "backups" / f"{name}-from-{peer}-{time.strftime('%Y%m%d-%H%M%S')}"
508
+ meta = json.loads(transport.nodehop("release", name, "--to", self.me, "--json", timeout=120)
509
+ .stdout.strip().splitlines()[-1])
510
+ transport.pull_dir(meta["path"], there / "project", delete=False, excludes=self.config.excludes)
511
+ for label, remote in module.payload(project, meta):
512
+ transport.pull_dir(str(remote), there / label, delete=False)
513
+ result["other_version"] = str(there)
514
+ transport.nodehop("abandon", name, "--to", self.me, timeout=120)
515
+ self._record(name, conflict=None, reason="kept")
516
+ if keep == "merge":
517
+ report = self.conflict_brief(name, peer, conflict.get("since"), result["other_version"])
518
+ result["briefed"] = module.send_message(project, report)
519
+ self.runner.log(f"{name}: kept {self.me}'s version" + (" and briefed it on " + peer + "'s work" if keep == "merge" else ""))
520
+ elif keep == "there":
521
+ was_running = module.is_running(project)
522
+ module.stop(project)
523
+ result["backup"] = str(self.backup(name, f"version on {self.me}, set aside: the person kept {peer}'s"))
524
+ self._record(name, owner=peer, origin=self.me, reason="failover", conflict=None)
525
+ self.pull([name])
526
+ if was_running and not module.is_running(project):
527
+ self.start(name, resume=True)
528
+ self.runner.log(f"{name}: kept {peer}'s version")
529
+ else:
530
+ raise ValueError("keep must be here, there or merge")
531
+ return result
532
+
533
+ @staticmethod
534
+ def conflict_brief(name: str, peer: str, since, other: str) -> str:
535
+ when = time.strftime("%H:%M", time.localtime(since)) if since else "a while"
536
+ return (
537
+ f"NodeHop: while this machine was unreachable, another copy of you kept working on this task on "
538
+ 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 and its conversation in {other}/claude. Compare it with this "
540
+ f"project (for example: diff -ru --exclude=.git {other}/project .), bring in what is useful without "
541
+ f"redoing what is already done here, then carry on with the task."
542
+ )
543
+
544
+ def abandon(self, name: str, to: str) -> None:
545
+ """Server side: the primary came back with the agent still alive there; its version wins."""
546
+ project = self.config.project(name)
547
+ with locked():
548
+ self.module(project).stop(project)
549
+ self.backup(name, f"work done on {self.me} during a fallback, set aside because {to} came back "
550
+ f"with its agent still running")
551
+ self._record(name, owner=to, origin="", reason="abandoned", conflict=None)
552
+ self.runner.log(f"{name}: handed back to {to}, fallback work set aside")
553
+
554
+ def reconcile(self, peer: str) -> List[str]:
555
+ """Primary, when it reaches the server: settle projects the server took over while it was silent.
556
+
557
+ Rule: the machine whose agent is still alive wins (the primary was only
558
+ offline); otherwise the server's version wins (the primary had crashed or
559
+ lost power). The losing version is always kept in a backup folder.
560
+ """
561
+ transport = self.transport(peer)
562
+ result = transport.nodehop("claims", "--json", check=False, timeout=60, mutating=False)
563
+ if result.returncode != 0:
564
+ return []
565
+ try:
566
+ claims = json.loads(result.stdout.strip().splitlines()[-1])
567
+ except (ValueError, IndexError):
568
+ return []
569
+ back = []
570
+ for name, claim in claims.items():
571
+ if name not in self.config.projects or self.owner(name) != self.me or self.in_conflict(name):
572
+ continue
573
+ project = self.config.project(name)
574
+ if self.module(project).is_running(project):
575
+ # Two agents worked in parallel. Pause the server's (the person is here) and ask.
576
+ self.runner.log(f"{name}: {peer} took over while this machine was unreachable and both agents "
577
+ f"kept working: pausing {peer}'s, waiting for `nodehop resolve`")
578
+ transport.nodehop("pause", name, timeout=120)
579
+ self._record(name, conflict={"peer": peer, "since": claim.get("since"), "copy_time": claim.get("copy_time"),
580
+ "detected": time.time()})
581
+ self.ask_person(name)
582
+ continue
583
+ self.runner.log(f"{name}: {peer} took over while this machine was down: its version wins")
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])
587
+ return back
588
+
589
+ # ---- lid events ------------------------------------------------------------
590
+ def on_sleep(self, target: Optional[str] = None) -> List[str]:
591
+ names = self.active_here()
592
+ if not names or self.me != self.config.primary:
593
+ return []
594
+ deadline = time.monotonic() + self.config.sleep_budget_seconds
595
+ return self.handoff(names, self.config.target(target), reason="sleep", deadline=deadline)
596
+
597
+ def on_wake(self, attempts: int = 12, wait: float = 10.0) -> List[str]:
598
+ """Kill stale local copies, then take back what was sent away at sleep (retrying ~2 min)."""
599
+ for name, project in self.config.projects.items():
600
+ if self.owner(name) != self.me:
601
+ self.module(project).stop(project)
602
+ if self.me != self.config.primary:
603
+ return []
604
+ back = self.reclaim(attempts=attempts, wait=wait)
605
+ # Work stopped for a sleep handoff that never went through: start it again here.
606
+ for name, project in self.config.projects.items():
607
+ if self.owner(name) == self.me and self.state.get(name).get("paused_for_sleep"):
608
+ self._record(name, paused_for_sleep=False)
609
+ self.start(name, resume=True)
610
+ self.runner.log(f"{name}: the handoff at sleep did not happen, resumed here")
611
+ back.append(name)
612
+ return back
613
+
614
+ # ---- watcher (server): fallback when the primary goes silent --------------------
615
+ def watch(self, once: bool = False) -> None:
616
+ self.runner.log(f"watch: started on {self.me}, checking every {self.config.poll_seconds}s "
617
+ f"(fallback after {self.config.failover_minutes} min of silence)")
618
+ while True:
619
+ try:
620
+ self.failover_tick()
621
+ except Exception as exc:
622
+ self.runner.log(f"watch: error: {exc}")
623
+ if once:
624
+ return
625
+ self.runner.sleep(self.config.poll_seconds)
626
+
627
+ # ---- status -------------------------------------------------------------------
628
+ def status(self) -> List[dict]:
629
+ rows = []
630
+ for name, project in self.config.projects.items():
631
+ entry = self.state.get(name)
632
+ owner = self.owner(name)
633
+ rows.append(
634
+ {
635
+ "project": name,
636
+ "owner": owner,
637
+ "running_here": owner == self.me and self.module(project).is_running(project),
638
+ "session_id": entry.get("session_id"),
639
+ "updated": entry.get("updated"),
640
+ }
641
+ )
642
+ return rows