workcrew 0.1.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.
workcrew/state.py ADDED
@@ -0,0 +1,516 @@
1
+ """The team on disk: where it lives, its names, the lock, and safe writes."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import contextlib
6
+ import dataclasses
7
+ import errno
8
+ import fcntl
9
+ import json
10
+ import os
11
+ import re
12
+ import secrets
13
+ import stat
14
+ import tempfile
15
+ import unicodedata
16
+ import uuid
17
+ from collections.abc import Iterator, Mapping, Sequence
18
+ from dataclasses import dataclass, field, fields
19
+ from datetime import UTC, datetime
20
+ from pathlib import Path
21
+ from typing import Any, Literal
22
+
23
+ ENV = "WORKCREW_CRASH_AT"
24
+ EXIT = 137
25
+ VERSION = 2
26
+ RESERVED = frozenset({"leader", "all", "workers"})
27
+ # What arrives under each of these names: a worker so named would speak as the tool or the owner.
28
+ # A team's name is no one's sender, so a team may take them.
29
+ _SENDERS = {"workcrew": "the tool's notices", "owner": "the owner's link messages"}
30
+ _NAME = re.compile(r"[a-z][a-z0-9-]{0,23}")
31
+ _WORKER_ID = re.compile(r"w[0-9]+")
32
+
33
+
34
+ class Refused(Exception):
35
+ """A refusal the caller can fix (exit 1)."""
36
+
37
+
38
+ class UsageError(Exception):
39
+ """A command written wrong (exit 2)."""
40
+
41
+
42
+ class StateError(Exception):
43
+ """State on disk the tool will not touch (exit 2)."""
44
+
45
+
46
+ @dataclass(frozen=True)
47
+ class Notice:
48
+ to: str
49
+ text: str
50
+ sender: str = "workcrew" # text a member wrote arrives under that member's name
51
+
52
+
53
+ @dataclass
54
+ class Member:
55
+ id: str
56
+ name: str
57
+ harness: str
58
+ session_id: str
59
+ inbox: str | None
60
+ # `exit` stopped it, and no command has started it since. Kept here, not on the server: a
61
+ # server that ends takes its marks with it, and no pass may start a member the owner stopped.
62
+ stopping: bool = False
63
+ # This member's own flags and when they were set, mirroring the team's pair. A resumed
64
+ # Claude Code session loses the effort it ran on (ran: 2.1.332), so they are passed again at
65
+ # every start, and a roster written before they existed loads without them.
66
+ flags: list[str] = field(default_factory=list)
67
+ flags_at: str = ""
68
+
69
+
70
+ @dataclass(frozen=True)
71
+ class Arrangement:
72
+ """The team window as the owner left it: tmux's layout string, the member in each pane in
73
+ pane-index order ("" for an owner's pane), the member whose pane is zoomed, and the members
74
+ the owner had moved out of it into windows of their own."""
75
+
76
+ layout: str
77
+ order: tuple[str, ...]
78
+ zoomed: str | None
79
+ out: tuple[str, ...] = ()
80
+
81
+
82
+ @dataclass
83
+ class Roster:
84
+ version: int
85
+ key: str
86
+ name: str
87
+ cwd: str
88
+ host: str
89
+ flags: list[str]
90
+ flags_at: str
91
+ cap: bool
92
+ side: Literal["left", "right", "middle"]
93
+ link_id: str
94
+ next_worker: int
95
+ members: list[Member]
96
+ arrangement: Arrangement | None = None
97
+
98
+ def workers(self) -> list[Member]:
99
+ return [m for m in self.members if m.id != "leader"]
100
+
101
+ def by_name(self, name: str) -> Member | None:
102
+ return next((m for m in self.members if m.name == name), None)
103
+
104
+ def by_id(self, mid: str) -> Member | None:
105
+ return next((m for m in self.members if m.id == mid), None)
106
+
107
+ def names(self) -> dict[str, str]:
108
+ return {m.id: m.name for m in self.members}
109
+
110
+
111
+ def check_name(s: str) -> str:
112
+ # fullmatch, not match with `$`: `$` also matches before a final newline.
113
+ if _NAME.fullmatch(s) is None:
114
+ raise Refused(
115
+ f"{s!r} is not a name: use a\u2013z, 0\u20139 and -, starting with a letter,"
116
+ " at most 24."
117
+ )
118
+ return s
119
+
120
+
121
+ def check_team_name(new: str) -> str:
122
+ """Every rule a team's name keeps wherever it is set, whether the team is being made or
123
+ renamed. A command word is refused in cli.py, where the command words are."""
124
+ return _rules(new, None)
125
+
126
+
127
+ def _rules(new: str, member: Member | None) -> str:
128
+ check_name(new)
129
+ if new in RESERVED:
130
+ raise Refused(
131
+ f"'{new}' is reserved: leader, all and workers cannot name a team or a worker."
132
+ )
133
+ if member is not None and new in _SENDERS:
134
+ raise Refused(f"'{new}' is the name {_SENDERS[new]} come from, so no worker can take it.")
135
+ # `w<n>` is the id space: a name there could equal another member's present or future id.
136
+ if _WORKER_ID.fullmatch(new) and (member is None or new != member.id):
137
+ own = f", here {member.id}" if member is not None else ""
138
+ raise Refused(f"'{new}' is kept for worker ids: a worker can take only its own{own}.")
139
+ return new
140
+
141
+
142
+ def check_new_name(new: str, r: Roster, member: Member | None) -> str:
143
+ _rules(new, member)
144
+ if member is None:
145
+ if r.by_name(new) is not None:
146
+ raise Refused(f"'{new}' is taken: a team's name must differ from its members' names.")
147
+ return new
148
+ other = r.by_name(new)
149
+ if (other is not None and other is not member) or new == r.name:
150
+ raise Refused(
151
+ f"'{new}' is taken: a worker's name must differ from the other members' and the team's."
152
+ )
153
+ return new
154
+
155
+
156
+ def names_a_team(words: Sequence[str]) -> bool:
157
+ """`-r NAME …`: the word after `-r` is a team's name only when it is not an option. It lives
158
+ here, and not with the rest of the grammar, because `prompt` cannot import `cli`."""
159
+ return words[:1] == ["-r"] and len(words) > 1 and not words[1].startswith("-")
160
+
161
+
162
+ def slug(folder: str) -> str:
163
+ s = re.sub(r"[^a-z0-9-]", "-", folder.lower()).strip("-")[:15]
164
+ if not s:
165
+ return "team"
166
+ # The slug is the team's first name, so it keeps the name rules.
167
+ if not s[0].isalpha() or s in RESERVED or _WORKER_ID.fullmatch(s):
168
+ s = "t" + s[:14]
169
+ return s
170
+
171
+
172
+ def new_key(name: str, cwd: Path) -> str:
173
+ """A new team's directory name. Drawn, not derived: a folder holds any number of teams, and
174
+ a team outlives its folder's path."""
175
+ real = os.path.realpath(cwd)
176
+ try:
177
+ real.encode()
178
+ except UnicodeEncodeError:
179
+ # A team is made here, before anything is written.
180
+ raise Refused(
181
+ f"{shown(Path(real))} is not a UTF-8 path, and each member's note names its folder,"
182
+ " so no team can run here.\nRename the folder, or use another."
183
+ ) from None
184
+ return f"{slug(name)}-{secrets.token_hex(4)}"
185
+
186
+
187
+ # A team's directory name, as new_key draws it.
188
+ KEY = r"[a-z][a-z0-9-]*-[0-9a-f]{8}"
189
+ # A member's note, as `ps` prints it within its harness's argv: the team key and the member id.
190
+ # Only as the value of the flag the harness gives it (harness/claude.py, which imports this module):
191
+ # a shell that merely names a note, to read it or pass it on, is not that member. The path may hold
192
+ # spaces, which `ps` prints as it prints the gaps between arguments.
193
+ _NOTED = re.compile(
194
+ r"--append-system-prompt-file .*?"
195
+ rf"/workcrew/({KEY})/note-(leader|{_WORKER_ID.pattern})\.md"
196
+ )
197
+
198
+
199
+ def note(d: Path, mid: str) -> Path:
200
+ """A member's note. The harness puts its path in the member's argv, which is how a process
201
+ that has lost its environment is still known by its ancestors."""
202
+ return d / f"note-{mid}.md"
203
+
204
+
205
+ def noted(args: str) -> tuple[str, str] | None:
206
+ """(team key, member id) of the note its harness was given, if a process's argv holds one."""
207
+ m = _NOTED.search(args)
208
+ return (m[1], m[2]) if m else None
209
+
210
+
211
+ def shown(p: Path) -> str:
212
+ home = str(Path.home())
213
+ s = str(p)
214
+ return "~" + s[len(home) :] if s == home or s.startswith(home + "/") else s
215
+
216
+
217
+ def team_dir(key: str, env: Mapping[str, str]) -> Path:
218
+ base = env.get("XDG_STATE_HOME", "")
219
+ # A relative XDG_STATE_HOME is invalid and ignored, as the XDG Base Directory spec says.
220
+ root = (
221
+ Path(base) if Path(base).is_absolute() else Path(env.get("HOME", "")) / ".local" / "state"
222
+ )
223
+ if not root.is_absolute():
224
+ raise StateError(
225
+ "HOME is not an absolute path, so workcrew cannot place the team's state.\n"
226
+ "Set HOME, or XDG_STATE_HOME, to an absolute path."
227
+ )
228
+ return root / "workcrew" / key
229
+
230
+
231
+ def root_dir(env: Mapping[str, str]) -> Path:
232
+ return team_dir("x", env).parent
233
+
234
+
235
+ @contextlib.contextmanager
236
+ def root_locked(env: Mapping[str, str]) -> Iterator[None]:
237
+ """Held while the bare command looks for this folder's teams and makes one. It is dropped
238
+ before any team's lock is taken, so a first start in one folder never waits on another
239
+ team's command."""
240
+ root = root_dir(env)
241
+ root.mkdir(mode=0o700, parents=True, exist_ok=True)
242
+ fd = os.open(root / "lock", os.O_RDWR | os.O_CREAT, 0o600)
243
+ try:
244
+ fcntl.flock(fd, fcntl.LOCK_EX)
245
+ yield
246
+ finally:
247
+ os.close(fd)
248
+
249
+
250
+ def identity(d: Path) -> tuple[str, str, str] | None:
251
+ """The name, folder and host of the team a state directory holds, or None where it holds
252
+ none. A roster from a newer workcrew still answers all three, so its name is still taken."""
253
+ try:
254
+ _private(d)
255
+ except FileNotFoundError:
256
+ return None
257
+ except StateError as e:
258
+ raise _opaque(d) from e
259
+ try:
260
+ raw: Any = json.loads((d / "roster.json").read_bytes())
261
+ except FileNotFoundError:
262
+ return None
263
+ except (ValueError, OSError) as e:
264
+ raise _opaque(d) from e
265
+ if not isinstance(raw, dict):
266
+ raise _opaque(d)
267
+ got = [raw.get(f) for f in ("key", "name", "cwd", "host")]
268
+ if not all(isinstance(x, str) for x in got):
269
+ raise _opaque(d)
270
+ key, name, cwd, host = (str(x) for x in got)
271
+ # A forgotten team keeps its roster under `forget`'s name for the folder, and holds its name
272
+ # no more. Any other folder whose roster names another key still holds the name, so the
273
+ # command that names it reaches `load`, which says what is wrong.
274
+ return None if d.name.startswith(f"{key}.forgotten-") else (name, cwd, host)
275
+
276
+
277
+ def _opaque(d: Path) -> StateError:
278
+ return StateError(
279
+ f"{shown(d)} gives no team's name or folder, so no team was made:"
280
+ " a new team's name is checked against every team.\n"
281
+ "Repair it, or give it back mode 0700 and your ownership, or move it aside."
282
+ )
283
+
284
+
285
+ def make(d: Path) -> None:
286
+ """A new team's directory. One that exists already would mean two teams in one state."""
287
+ d.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
288
+ d.mkdir(mode=0o700)
289
+ _private(d)
290
+ _sync_dir(d.parent)
291
+
292
+
293
+ @contextlib.contextmanager
294
+ def locked(d: Path) -> Iterator[None]:
295
+ # Only `make` creates the directory: a command that waited while `forget` moved it away
296
+ # must not make a new one and run beside the command that still holds the old lock.
297
+ path = d / "lock"
298
+ while True:
299
+ try:
300
+ _private(d)
301
+ fd = os.open(path, os.O_RDWR | os.O_CREAT, 0o600)
302
+ except FileNotFoundError:
303
+ raise Refused(
304
+ f"no team at {shown(d)}: it was forgotten while this command waited.\n"
305
+ "To start a new one, run workcrew --name NAME in its folder, in a shell outside"
306
+ " any team."
307
+ ) from None
308
+ try:
309
+ fcntl.flock(fd, fcntl.LOCK_EX)
310
+ except OSError as e:
311
+ os.close(fd)
312
+ # ENOTSUP or EOPNOTSUPP (one number on Linux, two on macOS): a filesystem with no
313
+ # flock. ENOLCK: an NFS mount whose server runs no lock manager.
314
+ if e.errno in (errno.ENOTSUP, errno.EOPNOTSUPP, errno.ENOLCK):
315
+ raise StateError(
316
+ "this filesystem does not support locking, and workcrew needs it to keep"
317
+ " two members off one task.\n"
318
+ "Put the state on a local filesystem: set XDG_STATE_HOME to one."
319
+ ) from e
320
+ raise
321
+ # `forget` may have renamed the directory while we waited: the lock we hold is then
322
+ # not the team's, and writing under it would race the next team.
323
+ held = os.fstat(fd)
324
+ try:
325
+ now = path.stat()
326
+ except FileNotFoundError:
327
+ now = None
328
+ if now is None or (held.st_dev, held.st_ino) != (now.st_dev, now.st_ino):
329
+ os.close(fd)
330
+ continue
331
+ try:
332
+ yield
333
+ finally:
334
+ os.close(fd)
335
+ return
336
+
337
+
338
+ def write_atomic(p: Path, data: bytes) -> None:
339
+ fd, tmp = tempfile.mkstemp(dir=p.parent, prefix=".tmp-")
340
+ with os.fdopen(fd, "wb") as f:
341
+ f.write(data)
342
+ f.flush()
343
+ os.fsync(f.fileno())
344
+ crash_point("state.replace")
345
+ Path(tmp).replace(p)
346
+ _sync_dir(p.parent)
347
+
348
+
349
+ def _sync_dir(d: Path) -> None:
350
+ fd = os.open(d, os.O_RDONLY)
351
+ try:
352
+ os.fsync(fd)
353
+ finally:
354
+ os.close(fd)
355
+
356
+
357
+ def write_if_changed(p: Path, data: bytes) -> bool:
358
+ with contextlib.suppress(FileNotFoundError):
359
+ if p.read_bytes() == data:
360
+ return False
361
+ write_atomic(p, data)
362
+ return True
363
+
364
+
365
+ def _member(mid: str) -> Member:
366
+ return Member(id=mid, name=mid, harness="claude", session_id=str(uuid.uuid4()), inbox=None)
367
+
368
+
369
+ def create(
370
+ d: Path, cwd: Path, host: str, name: str, flags: list[str], cap: bool, workers: int
371
+ ) -> Roster:
372
+ real = os.path.realpath(cwd)
373
+ r = Roster(
374
+ version=VERSION,
375
+ key=d.name,
376
+ name=name,
377
+ cwd=real,
378
+ host=host,
379
+ flags=flags,
380
+ flags_at=datetime.now(UTC).isoformat(timespec="milliseconds").replace("+00:00", "Z"),
381
+ cap=cap,
382
+ side="right",
383
+ link_id=secrets.token_hex(16),
384
+ next_worker=workers + 1,
385
+ members=[_member("leader")] + [_member(f"w{i}") for i in range(1, workers + 1)],
386
+ )
387
+ save(d, r)
388
+ return r
389
+
390
+
391
+ def _known_fields(cls: type, raw: Any) -> dict[str, Any]:
392
+ """A roster or member written by a workcrew that had a field this one dropped: the field is
393
+ passed over, as a field it has not added yet is simply absent and takes its default."""
394
+ known = {f.name for f in fields(cls)}
395
+ return {k: v for k, v in raw.items() if k in known} if isinstance(raw, dict) else {}
396
+
397
+
398
+ def _unparseable(p: Path) -> StateError:
399
+ return StateError(
400
+ f"{shown(p)} does not parse, and workcrew will not reset it.\n"
401
+ "It holds your members' session ids. Repair it, or move it aside: no new team can be made"
402
+ " until then, since each new name is checked against every team."
403
+ )
404
+
405
+
406
+ def _private(d: Path) -> None:
407
+ st = d.lstat()
408
+ if not stat.S_ISDIR(st.st_mode):
409
+ raise StateError(
410
+ f"{shown(d)} is not a folder, and workcrew needs a folder there with mode 0700 and"
411
+ " your ownership.\nMove it aside and run workcrew again."
412
+ )
413
+ if st.st_uid != os.getuid() or st.st_mode & 0o777 != 0o700:
414
+ raise StateError(
415
+ f"{shown(d)} is mode {st.st_mode & 0o777:04o}, and workcrew needs 0700 and your"
416
+ " ownership."
417
+ )
418
+
419
+
420
+ def load(d: Path) -> Roster | None:
421
+ try:
422
+ _private(d)
423
+ except FileNotFoundError:
424
+ return None
425
+ p = d / "roster.json"
426
+ try:
427
+ raw: Any = json.loads(p.read_bytes())
428
+ except FileNotFoundError:
429
+ return None
430
+ except ValueError as e:
431
+ raise _unparseable(p) from e
432
+ if isinstance(raw, dict) and isinstance(raw.get("version"), int) and raw["version"] > VERSION:
433
+ raise StateError(
434
+ f"this team was written by a newer workcrew (roster version {raw['version']};"
435
+ f" this is {VERSION}).\nUpgrade workcrew, or start a new team in another folder."
436
+ )
437
+ try:
438
+ members = [Member(**_known_fields(Member, m)) for m in raw["members"]]
439
+ a = raw.get("arrangement")
440
+ kept = (
441
+ Arrangement(a["layout"], tuple(a["order"]), a["zoomed"], tuple(a.get("out", ())))
442
+ if a
443
+ else None
444
+ )
445
+ r = Roster(**{**_known_fields(Roster, raw), "members": members, "arrangement": kept})
446
+ except (TypeError, KeyError) as e:
447
+ raise _unparseable(p) from e
448
+ # Every command takes the team's tmux server from the key: a roster copied or repaired by
449
+ # hand with another key would act on that other team's server.
450
+ if r.key != d.name:
451
+ raise StateError(
452
+ f"{p} is another team's: it names the key {r.key!r}, and its folder is {d.name!r}.\n"
453
+ "Put back that folder's own roster.json."
454
+ )
455
+ return r
456
+
457
+
458
+ FORGOTTEN = (
459
+ "this team was forgotten, so nothing was changed.\n"
460
+ "To start a new one, run workcrew --name NAME in its folder, in a shell outside any team."
461
+ )
462
+
463
+
464
+ def fresh(d: Path) -> Roster:
465
+ """The roster under the lock. None of it means the team was forgotten while the command
466
+ waited; the folder may already hold a new team, whose roster is not this command's."""
467
+ r = load(d)
468
+ if r is None:
469
+ raise Refused(FORGOTTEN)
470
+ return r
471
+
472
+
473
+ def save(d: Path, r: Roster) -> None:
474
+ # This tool's version, whatever the roster was read as: an older tool refuses it from now on,
475
+ # where it would load it and drop at its next save every field it does not know.
476
+ data = {**dataclasses.asdict(r), "version": VERSION}
477
+ write_atomic(d / "roster.json", (json.dumps(data, indent=1) + "\n").encode())
478
+
479
+
480
+ def forget(d: Path) -> Path:
481
+ new = d.with_name(f"{d.name}.forgotten-{datetime.now(UTC).strftime('%Y%m%dT%H%M%S.%fZ')}")
482
+ d.rename(new)
483
+ _sync_dir(d.parent)
484
+ return new
485
+
486
+
487
+ # The nine that reorder what a reader sees: the embeddings, overrides and isolates and their ends,
488
+ # which Trojan Source (CVE-2021-42574) uses and rustc's text_direction_codepoint_in_literal lint
489
+ # flags. The marks (LRM, RLM, ALM) pass, as joiners do: right-to-left writing needs them.
490
+ _REORDER = frozenset("\u202a\u202b\u202c\u202d\u202e\u2066\u2067\u2068\u2069")
491
+ # Unicode's tag block: a model reads these, and no font draws them.
492
+ _TAGS = range(0xE0000, 0xE0080)
493
+
494
+
495
+ def escape(s: str) -> str:
496
+ """Shows, as an escape, what would mislead a reader: a control character but a line break or
497
+ a tab, a reordering one, a tag, and a lone surrogate, which no terminal can write."""
498
+ out = []
499
+ for c in s:
500
+ shown = (
501
+ (c not in "\n\t" and unicodedata.category(c) in ("Cc", "Cs"))
502
+ or c in _REORDER
503
+ or ord(c) in _TAGS
504
+ )
505
+ if not shown:
506
+ out.append(c)
507
+ elif ord(c) < 0x100:
508
+ out.append(f"\\x{ord(c):02x}")
509
+ else:
510
+ out.append(f"\\u{ord(c):04x}")
511
+ return "".join(out)
512
+
513
+
514
+ def crash_point(step: str) -> None:
515
+ if os.environ.get(ENV) == step:
516
+ os._exit(EXIT)