orrin 1.0.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.
orrin/__init__.py ADDED
@@ -0,0 +1,7 @@
1
+ """orrin: run several coding agents on one machine without them tripping over each other.
2
+
3
+ Detached jobs with completion markers, a fair machine lock, short blocking waits, a lane board,
4
+ a one-screen status, state tidying and a protected-data registry. Standard library only.
5
+ """
6
+
7
+ __version__ = "1.0.0"
orrin/__main__.py ADDED
@@ -0,0 +1,3 @@
1
+ from .cli import main
2
+
3
+ raise SystemExit(main())
orrin/board.py ADDED
@@ -0,0 +1,96 @@
1
+ """The lane board: who is working where, on what, and what heavy job comes next.
2
+
3
+ Information only. A board entry never blocks anyone and grants nothing; decisions and approvals go
4
+ through the coordinator. Entries go stale (and are ignored) when they are older than ``stale_h``
5
+ hours, their PID is gone, or the job they are bound to has finished.
6
+
7
+ One JSON file per lane under ``<home>/board/``; ``done`` moves the file to ``board/archive/``.
8
+ """
9
+ from __future__ import annotations
10
+
11
+ import time
12
+ from pathlib import Path
13
+
14
+ from . import jobs, procs
15
+ from .home import check_name, home, human_age, mutex, read_json, write_json
16
+
17
+ FIELDS = ("worktree", "branch", "model", "activity", "next", "eta", "job")
18
+
19
+
20
+ def board_dir(root=None) -> Path:
21
+ path = home(root) / "board"
22
+ path.mkdir(parents=True, exist_ok=True)
23
+ return path
24
+
25
+
26
+ def update(lane: str, fields: dict | None = None, note: str | None = None, pid: int | None = None, root=None) -> dict:
27
+ check_name(lane, "lane")
28
+ base = board_dir(root)
29
+ with mutex(base / ".mutex"):
30
+ path = base / f"{lane}.json"
31
+ row = read_json(path) or {"lane": lane, "notes": [], "started": time.time()}
32
+ row.update({k: v for k, v in (fields or {}).items() if v is not None})
33
+ if pid:
34
+ row["pid"], row["pid_ident"] = pid, procs.identity(pid)
35
+ if note:
36
+ row["notes"].append({"time": time.time(), "text": note})
37
+ row["notes"] = row["notes"][-50:]
38
+ row["updated"] = time.time()
39
+ write_json(path, row)
40
+ return row
41
+
42
+
43
+ def done(lane: str, root=None) -> Path | None:
44
+ check_name(lane, "lane")
45
+ base = board_dir(root)
46
+ with mutex(base / ".mutex"):
47
+ path = base / f"{lane}.json"
48
+ if not path.exists():
49
+ return None
50
+ (base / "archive").mkdir(exist_ok=True)
51
+ target = base / "archive" / f"{lane}-{time.strftime('%Y%m%d-%H%M%S')}.json"
52
+ path.replace(target)
53
+ return target
54
+
55
+
56
+ def read(root=None, stale_h: float = 2.0, jobs_out=None, now: float | None = None) -> list[dict]:
57
+ now = now or time.time()
58
+ rows = []
59
+ for path in sorted(board_dir(root).glob("*.json")):
60
+ row = read_json(path)
61
+ if not isinstance(row, dict):
62
+ continue
63
+ reasons = []
64
+ if now - row.get("updated", 0) > stale_h * 3600:
65
+ reasons.append(f"not updated for {human_age(now - row.get('updated', 0))}")
66
+ if row.get("pid") and not procs.alive(row["pid"], row.get("pid_ident")):
67
+ reasons.append("process gone")
68
+ if row.get("job"):
69
+ try:
70
+ state = jobs.status(jobs.resolve(row["job"], jobs_out, root))["state"]
71
+ except ValueError:
72
+ state = "missing"
73
+ if state not in ("running", "waiting-lock", "waiting-ram", "starting"):
74
+ reasons.append(f"bound job {state}")
75
+ rows.append(dict(row, stale=bool(reasons), stale_reasons=reasons))
76
+ return rows
77
+
78
+
79
+ def render(rows: list[dict], now: float | None = None) -> str:
80
+ now = now or time.time()
81
+ if not rows:
82
+ return "LANE BOARD: empty"
83
+ out = ["LANE BOARD (information only; decisions go through the coordinator)"]
84
+ for row in rows:
85
+ bits = [row.get("model", "?"), row.get("activity", "-")]
86
+ if row.get("next"):
87
+ bits.append(f"next {row['next']}" + (f" eta {row['eta']}" if row.get("eta") else ""))
88
+ out.append(f"{row['lane']}: {'STALE' if row['stale'] else 'live'} | " + " | ".join(bits)
89
+ + f" | updated {human_age(now - row.get('updated', now))} ago")
90
+ if row.get("worktree"):
91
+ out.append(f" worktree {row['worktree']}" + (f" ({row['branch']})" if row.get("branch") else ""))
92
+ if row["stale"]:
93
+ out.append(" stale: " + ", ".join(row["stale_reasons"]))
94
+ for note in row.get("notes", [])[-3:]:
95
+ out.append(f" note {time.strftime('%m-%d %H:%M', time.localtime(note['time']))}: {note['text']}")
96
+ return "\n".join(out)
orrin/checkin.py ADDED
@@ -0,0 +1,258 @@
1
+ """The heartbeat: one call that tells the coordinator what needs attention now.
2
+
3
+ A coordinator that runs for days doesn't need a fixed plan. It needs to look at the same few
4
+ things on a regular beat and act on what changed:
5
+
6
+ * **usage**: the output of each configured usage command (any provider). A line showing
7
+ ``NN% used`` at or above ``models.checkpoint_usage_percent`` becomes an attention item. A failing
8
+ command is "unavailable", never zero.
9
+ * **jobs**: failed, stopped or stalled jobs stay on the list until handled (relaunched, or
10
+ ``orrin jobs ack``), so a check-in that crashed before acting loses nothing. Successful jobs
11
+ are reported once.
12
+ * **lanes**: quiet longer than ``silent_lane_minutes``, unless their bound job is still running
13
+ (waiting on a job is not silence); stale (process or job gone); or running longer than
14
+ ``fresh_start_hours``, where a checkpoint and a fresh relaunch beats a degrading context.
15
+ * **the lock**: jobs waiting more than 30 minutes.
16
+ * **the anchor**: the status file missing, or behind by ``status_stale_commits`` commits.
17
+ * **tasks**: claimed, ready and blocked counts from ``tasks.json``, if there is one.
18
+
19
+ Run it from a scheduler with the prompt in ``HEARTBEAT.md``. ``--quiet`` prints one line when
20
+ nothing needs attention.
21
+ """
22
+ from __future__ import annotations
23
+
24
+ import hashlib
25
+ import re
26
+ import subprocess
27
+ import time
28
+
29
+ import json
30
+
31
+ from . import board, jobs, lead, lock, procs, settled, tasks
32
+ from .config import Config
33
+ from .home import home, human_age, read_json, write_json
34
+
35
+ NO_WINDOW = procs.NO_WINDOW if procs.WINDOWS else 0
36
+ USED_RE = re.compile(r"(\d{1,3}(?:\.\d+)?)\s*%\s*used", re.I)
37
+ ACTIVE = ("running", "waiting-lock", "waiting-ram", "starting")
38
+
39
+
40
+ def _usage(cfg: Config, timeout: float = 30) -> list[dict]:
41
+ out = []
42
+ for cmd in cfg["usage_commands"]:
43
+ try:
44
+ r = subprocess.run(cmd, shell=isinstance(cmd, str), capture_output=True, text=True, timeout=timeout,
45
+ cwd=cfg.root, creationflags=NO_WINDOW)
46
+ text = (r.stdout or r.stderr).strip().splitlines()
47
+ out.append({"command": cmd, "ok": r.returncode == 0, "lines": text[-6:]})
48
+ except (OSError, subprocess.SubprocessError) as e:
49
+ out.append({"command": cmd, "ok": False, "lines": [f"unavailable: {e}"]})
50
+ return out
51
+
52
+
53
+ def _git(cfg: Config, *args) -> str | None:
54
+ try:
55
+ r = subprocess.run(["git", "-C", str(cfg.root), *args], capture_output=True, text=True, timeout=20,
56
+ creationflags=NO_WINDOW)
57
+ except (OSError, subprocess.SubprocessError):
58
+ return None
59
+ return r.stdout.strip() if r.returncode == 0 else None
60
+
61
+
62
+ def _anchor(cfg: Config) -> dict:
63
+ status = cfg.status_file
64
+ info = {"file": str(status), "exists": status.exists(), "commits_since": None}
65
+ if not status.exists():
66
+ return info
67
+ rel = status.relative_to(cfg.root).as_posix()
68
+ last = _git(cfg, "log", "-1", "--format=%H", "--", rel)
69
+ if last:
70
+ count = _git(cfg, "rev-list", "--count", f"{last}..HEAD")
71
+ info["commits_since"] = int(count) if count and count.isdigit() else None
72
+ return info
73
+
74
+
75
+ def _commits_since(cfg: Config, path) -> int | None:
76
+ try:
77
+ rel = path.resolve().relative_to(cfg.root).as_posix()
78
+ except ValueError:
79
+ return None
80
+ last = _git(cfg, "log", "-1", "--format=%H", "--", rel)
81
+ if not last:
82
+ return None
83
+ count = _git(cfg, "rev-list", "--count", f"{last}..HEAD")
84
+ return int(count) if count and count.isdigit() else None
85
+
86
+
87
+ def _epoch(value) -> float | None:
88
+ if value is None:
89
+ return None
90
+ if isinstance(value, (int, float)):
91
+ return float(value)
92
+ try:
93
+ from datetime import datetime
94
+ return datetime.fromisoformat(str(value).replace("Z", "+00:00")).timestamp()
95
+ except ValueError:
96
+ return None
97
+
98
+
99
+ def _agents(cfg: Config, timeout: float = 30) -> tuple[list[dict] | None, str | None]:
100
+ cmd = cfg.data.get("agents_command")
101
+ if not cmd:
102
+ return None, None
103
+ try:
104
+ r = subprocess.run(cmd, shell=isinstance(cmd, str), capture_output=True, text=True, timeout=timeout,
105
+ cwd=cfg.root, creationflags=NO_WINDOW)
106
+ except (OSError, subprocess.SubprocessError) as e:
107
+ return None, f"agents command unavailable: {e}"
108
+ text = r.stdout.strip()
109
+ try:
110
+ rows = json.loads(text) if text.startswith("[") else [json.loads(x) for x in text.splitlines() if x.strip()]
111
+ except ValueError:
112
+ return None, "agents command printed something that is not JSON"
113
+ return [x for x in rows if isinstance(x, dict)], None
114
+
115
+
116
+ def _agent_attention(cfg: Config, rows: list[dict], now: float) -> list[str]:
117
+ hb, m = cfg["heartbeat"], cfg["models"]
118
+ out = []
119
+ active = [a for a in rows if str(a.get("state", "running")).lower() not in ("idle", "done", "stopped", "finished")]
120
+ for a in active:
121
+ name = a.get("name", "?")
122
+ updated = _epoch(a.get("updated"))
123
+ if updated and now - updated > hb["silent_lane_minutes"] * 60:
124
+ out.append(f"agent {name} quiet for {human_age(now - updated)}: check that it is working; nudge or resume it")
125
+ ctx, limit = a.get("context_tokens"), m.get("relaunch_context_tokens")
126
+ if ctx and limit and ctx >= limit:
127
+ out.append(f"agent {name} at {ctx:,} tokens of context (limit {limit:,}): checkpoint and relaunch it fresh")
128
+ if m.get("one_strong_per_account") and m.get("strong"):
129
+ per: dict[str, list[str]] = {}
130
+ for a in active:
131
+ model = str(a.get("model", ""))
132
+ if any(s in model for s in m["strong"]):
133
+ per.setdefault(str(a.get("account", "?")), []).append(a.get("name", "?"))
134
+ for account, names in per.items():
135
+ if len(names) > 1:
136
+ out.append(f"{len(names)} strong-model agents on account {account} ({', '.join(names)}): "
137
+ "move one to another account or to the cheaper model")
138
+ return out
139
+
140
+
141
+ def _mark_path(cfg: Config, root):
142
+ key = hashlib.sha1(str(cfg.root).lower().encode()).hexdigest()[:12]
143
+ return home(root) / "checkins" / f"{key}.json"
144
+
145
+
146
+ def collect(cfg: Config, root=None, jobs_out=None, run_usage: bool = True, mark: bool = True) -> dict:
147
+ """``mark=False`` peeks without moving the last-check-in time (used by ``stop-check``)."""
148
+ now = time.time()
149
+ hb = cfg["heartbeat"]
150
+ mark_path = _mark_path(cfg, root)
151
+ mark_path.parent.mkdir(parents=True, exist_ok=True)
152
+ last = (read_json(mark_path) or {}).get("time", 0)
153
+ rows = jobs.list_jobs(jobs_out, root)
154
+ by_name = {r["name"]: r for r in rows}
155
+ finished_ok = [r for r in rows if r["state"] == "done" and r.get("finished", 0) > last]
156
+ unhandled = [r for r in rows if r["state"] in ("failed", "stopped", "stalled") and not r.get("acked")]
157
+ running = [r for r in rows if r["state"] in ACTIVE]
158
+ lanes = board.read(root, jobs_out=jobs_out, now=now)
159
+ attention = []
160
+
161
+ usage = _usage(cfg) if run_usage else []
162
+ threshold = cfg["models"].get("checkpoint_usage_percent")
163
+ for u in usage:
164
+ for line in u["lines"]:
165
+ values = [float(v) for v in USED_RE.findall(line)]
166
+ if threshold and values and max(values) >= threshold:
167
+ attention.append(f"usage at {max(values):g}% ({line.strip()[:120]}): checkpoint the agents on it, "
168
+ "plan around the reset or move work to another account")
169
+ for r in unhandled:
170
+ what = "runner gone, no marker" if r["state"] == "stalled" else f"{r.get('reason')}, exit {r.get('exit_code')}"
171
+ attention.append(f"job {r['name']} {r['state']} ({what}): read its log, fix and relaunch, "
172
+ f"then `orrin jobs ack {r['name']}`")
173
+ for r in lanes:
174
+ job = by_name.get(r.get("job") or "")
175
+ waiting_on_job = job is not None and job["state"] in ACTIVE
176
+ if r["stale"]:
177
+ attention.append(f"lane {r['lane']} stale ({', '.join(r['stale_reasons'])}): "
178
+ "resume it from its handoff, or close it with `board done`")
179
+ elif not waiting_on_job and now - r.get("updated", now) > hb["silent_lane_minutes"] * 60:
180
+ attention.append(f"lane {r['lane']} quiet for {human_age(now - r['updated'])}: check that it is working; "
181
+ "nudge or resume it")
182
+ fresh = hb.get("fresh_start_hours")
183
+ if fresh and not r["stale"] and now - r.get("started", now) > fresh * 3600:
184
+ attention.append(f"lane {r['lane']} running for {human_age(now - r['started'])}: checkpoint it "
185
+ "(commit, handoff) and relaunch fresh before its context degrades")
186
+ base = home(root) / "locks"
187
+ if base.exists():
188
+ for p in base.iterdir():
189
+ if p.is_dir():
190
+ for q in lock.state(p.name, root)["queue"]:
191
+ if now - q["since"] > 30 * 60:
192
+ attention.append(f"{q['label'] or q['pid']} waiting {human_age(now - q['since'])} "
193
+ f"for lock {p.name}: check the holder is making progress")
194
+ anchor = _anchor(cfg)
195
+ if not anchor["exists"]:
196
+ attention.append(f"status file {anchor['file']} missing: create it; every check-in re-reads it")
197
+ elif (anchor["commits_since"] or 0) >= hb["status_stale_commits"]:
198
+ attention.append(f"status file not updated in the last {anchor['commits_since']} commits: make it true again")
199
+ handoff = lead.handoff_path(cfg)
200
+ if not handoff.exists():
201
+ attention.append(f"lead handoff {handoff} missing: write it (what runs, what waits on the user, next step) "
202
+ "so a resume after compaction starts from state, not memory")
203
+ else:
204
+ behind = _commits_since(cfg, handoff)
205
+ if behind is not None and behind >= hb["status_stale_commits"]:
206
+ attention.append(f"lead handoff not updated in the last {behind} commits: bring it up to date")
207
+ agents, agents_error = _agents(cfg)
208
+ if agents_error:
209
+ attention.append(agents_error)
210
+ if agents:
211
+ attention += _agent_attention(cfg, agents, now)
212
+ task_summary = tasks.summary(cfg) if tasks.path(cfg).exists() else None
213
+ if task_summary:
214
+ for t in task_summary["ready"] + task_summary["claimed"]:
215
+ hit = settled.matches(cfg, t["title"])
216
+ if hit:
217
+ attention.append(f"task {t['id']} ({t['title'][:50]}) looks like settled {hit[0]['id']} "
218
+ f"[{hit[0]['verdict']}]: {hit[0]['result'][:80]}. Skip it, or reopen the settled item "
219
+ "and say what changed")
220
+ if task_summary and not running and not task_summary["claimed"] and task_summary["ready"]:
221
+ attention.append(f"{len(task_summary['ready'])} ready task(s) and nothing running: start "
222
+ f"{task_summary['ready'][0]['id']} ({task_summary['ready'][0]['title'][:60]})")
223
+ data = {"time": now, "last_checkin": last or None, "usage": usage, "finished": finished_ok,
224
+ "running": running, "attention": attention, "anchor": anchor, "lanes": len(lanes),
225
+ "agents": agents,
226
+ "tasks": task_summary}
227
+ if mark:
228
+ write_json(mark_path, {"time": now, "project": str(cfg.root)})
229
+ return data
230
+
231
+
232
+ def render(data: dict, quiet: bool = False) -> str:
233
+ t = data.get("tasks")
234
+ task_bits = (f"tasks {t['done']}/{t['total']} done, {len(t['claimed'])} claimed, {len(t['ready'])} ready"
235
+ if t else None)
236
+ if quiet and not data["attention"]:
237
+ bits = [f"{len(data['running'])} running", f"{len(data['finished'])} finished OK since last check-in"]
238
+ if task_bits:
239
+ bits.append(task_bits)
240
+ return "CHECK-IN: nothing needs attention (" + ", ".join(bits) + ")"
241
+ now = data["time"]
242
+ since = f" (last {human_age(now - data['last_checkin'])} ago)" if data.get("last_checkin") else ""
243
+ out = [f"CHECK-IN{since}"]
244
+ for u in data["usage"]:
245
+ out.append(f"USAGE {u['command'] if isinstance(u['command'], str) else ' '.join(u['command'])}"
246
+ + ("" if u["ok"] else " [unavailable]"))
247
+ out += [f" {line}" for line in u["lines"]]
248
+ out.append("NEEDS ATTENTION:" if data["attention"] else "NEEDS ATTENTION: nothing")
249
+ out += [f" - {a}" for a in data["attention"]]
250
+ for r in data["finished"]:
251
+ out.append(f"FINISHED OK: {r['name']}")
252
+ for r in data["running"]:
253
+ p = r.get("progress")
254
+ out.append(f"RUNNING: {r['name']} {r['state']}" + (f" {p['done']}/{p['total']}" if p else "")
255
+ + (f" eta {human_age(r['eta_s'])}" if r.get("eta_s") is not None else ""))
256
+ if task_bits:
257
+ out.append("TASKS: " + task_bits)
258
+ return "\n".join(out)