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/__init__.py ADDED
@@ -0,0 +1 @@
1
+ """workcrew: run a lead Claude Code session and its workers as one team in tmux."""
workcrew/__main__.py ADDED
@@ -0,0 +1,6 @@
1
+ """`python -m workcrew`, the same entry point as the installed command."""
2
+
3
+ from workcrew.cli import main
4
+
5
+ if __name__ == "__main__":
6
+ main()
workcrew/board.py ADDED
@@ -0,0 +1,555 @@
1
+ """The board: its store, its rules and its view."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ import re
7
+ import time
8
+ from collections.abc import Mapping, Sequence
9
+ from dataclasses import dataclass
10
+ from datetime import UTC, datetime
11
+ from pathlib import Path
12
+ from typing import Literal, get_args
13
+
14
+ from workcrew.state import Notice, Refused, UsageError, crash_point, escape, write_atomic
15
+ from workcrew.width import cols
16
+
17
+ State = Literal["ready", "running", "review", "done"]
18
+ Activity = Literal["idle", "busy", "wait", "exited", "not-started"]
19
+ STATES: tuple[State, ...] = get_args(State)
20
+ LIVE: frozenset[Activity] = frozenset({"idle", "busy", "wait"})
21
+ OWNER = "Tasks are the leader's to create: tell the leader what you want."
22
+ FILE = re.compile(r"([1-9][0-9]{0,8})(?:@([a-z][a-z0-9-]{0,23}))?\.md")
23
+ TYPED = re.compile(r"[Tt]?([1-9][0-9]{0,8})")
24
+
25
+
26
+ @dataclass(frozen=True)
27
+ class Task:
28
+ id: int
29
+ state: State
30
+ holder: str | None
31
+ title: str
32
+ since: float
33
+
34
+
35
+ # Each verb's arguments: the fewest it means anything with, and the most it can use.
36
+ ARITY = {
37
+ "new": (1, 1),
38
+ "close": (1, 1),
39
+ "back": (1, 1),
40
+ "take": (0, 1),
41
+ # Its text may be missing: the task is named first, so the refusal can name it too.
42
+ "report": (1, 2),
43
+ }
44
+ VERBS = (
45
+ "board takes nothing, --loop [SEC], or one of new, close, back, take, report. "
46
+ "Run workcrew board --help for the verbs."
47
+ )
48
+ USAGE = {
49
+ "new": 'board new needs a title, e.g. workcrew board new "fix the parser".',
50
+ "close": "board close needs a task, e.g. workcrew board close 7.",
51
+ "take": "board take takes one task, or nothing for the next in Ready.",
52
+ "back": "board back needs a task, e.g. workcrew board back 7.",
53
+ "report": "board report needs a task and the result text, "
54
+ 'e.g. workcrew board report 7 "what you did".',
55
+ }
56
+
57
+
58
+ # Leaders type `assign`, the natural word, but idle workers empty Ready within seconds: in real
59
+ # runs, 61 of 471 calls to assign a Ready task to one worker found it still there.
60
+ NO_ASSIGN = (
61
+ "there is no 'board assign' — a task for one worker is made with"
62
+ " board new TITLE --to WORKER or given with board back ID --to WORKER."
63
+ )
64
+
65
+
66
+ def task_id(word: str) -> int:
67
+ m = TYPED.fullmatch(word)
68
+ if m is None:
69
+ raise Refused(f"There is no task {word}.")
70
+ return int(m.group(1))
71
+
72
+
73
+ def _path(d: Path, state: State, tid: int, holder: str | None) -> Path:
74
+ return d / "board" / state / (f"{tid}@{holder}.md" if holder else f"{tid}.md")
75
+
76
+
77
+ def tasks(d: Path) -> list[Task]:
78
+ out = []
79
+ for state in STATES:
80
+ folder = d / "board" / state
81
+ if not folder.is_dir():
82
+ continue
83
+ for p in folder.iterdir():
84
+ m = FILE.fullmatch(p.name) # skips write_atomic's ".tmp-*" left by a crash
85
+ if m:
86
+ title = (
87
+ p.read_bytes().decode("utf-8").split("\n", 1)[0]
88
+ ) # LF only: a CR stays, to be escaped
89
+ out.append(Task(int(m.group(1)), state, m.group(2), title, p.stat().st_ctime))
90
+ return sorted(out, key=lambda t: t.id)
91
+
92
+
93
+ def held(d: Path, member: str) -> Task | None:
94
+ return next((t for t in tasks(d) if t.state == "running" and t.holder == member), None)
95
+
96
+
97
+ def counts(d: Path) -> Mapping[State, int]:
98
+ all_ = tasks(d)
99
+ return {s: sum(t.state == s for t in all_) for s in STATES}
100
+
101
+
102
+ def _where(t: Task, names: Mapping[str, str]) -> str:
103
+ who = names.get(t.holder or "", t.holder or "")
104
+ return {
105
+ "ready": f"T{t.id} is Ready.",
106
+ "running": f"T{t.id} is Running, held by {who}.",
107
+ "review": f"T{t.id} is in Review (reported by {who}).",
108
+ "done": f"T{t.id} is Done.",
109
+ }[t.state]
110
+
111
+
112
+ def _stamp() -> str:
113
+ return datetime.now(UTC).strftime("%Y-%m-%dT%H:%M:%SZ")
114
+
115
+
116
+ def ready_text(n: int) -> str:
117
+ return f"Ready has {n} task{'s' * (n != 1)}. Take one with `workcrew board take`."
118
+
119
+
120
+ def _mark(d: Path, t: Task) -> Path:
121
+ """A refusal's mark, beside the task and not in it: what a member writes cannot forge it, it
122
+ is never handed over as the task's text, and the task keeps the time it was taken."""
123
+ return _path(d, "running", t.id, t.holder).with_suffix(".refused")
124
+
125
+
126
+ def refuse_once(d: Path, t: Task) -> bool:
127
+ """Whether the holder's stop is refused for its Running task `t`: once per hold, until the
128
+ task leaves Running. The caller holds the lock."""
129
+ if _mark(d, t).exists():
130
+ return False
131
+ write_atomic(_mark(d, t), b"")
132
+ return True
133
+
134
+
135
+ def wait_once(d: Path, t: Task) -> bool:
136
+ """Whether the leader is told that `t`'s holder stopped with its own background work still
137
+ running: once per hold. A mark of its own, so the stop after that work ends is still sent
138
+ back once."""
139
+ mark = _mark(d, t).with_suffix(".waiting")
140
+ if mark.exists():
141
+ return False
142
+ write_atomic(mark, b"")
143
+ return True
144
+
145
+
146
+ def tell_once(d: Path, t: Task) -> bool:
147
+ """Whether the leader is told that `t`'s holder stopped and was let go: once per hold, and
148
+ never before the refusal. The caller holds the lock and has had `refuse_once` answer False,
149
+ so the mark is already there."""
150
+ if _mark(d, t).read_bytes() == b"told":
151
+ return False
152
+ write_atomic(_mark(d, t), b"told")
153
+ return True
154
+
155
+
156
+ def ready_notices(
157
+ d: Path, workers: Sequence[str], activity: Mapping[str, Activity], skip: str | None = None
158
+ ) -> list[Notice]:
159
+ """Ready's count, to as many idle workers holding nothing as Ready has tasks, in roster
160
+ order: every idle worker told wastes half the wakes, 121 of 240 in real runs finding the
161
+ task taken. A told worker stops being the one that takes when it exits, is removed or is
162
+ given a task with `--to`, so each of those tells again; without that, the board model
163
+ leaves a Ready task untold beside an idle worker in nine steps."""
164
+ all_ = tasks(d)
165
+ n = sum(t.state == "ready" for t in all_)
166
+ holders = {t.holder for t in all_ if t.state == "running"}
167
+ idle = [w for w in workers if activity.get(w) == "idle" and w not in holders and w != skip]
168
+ return [Notice(w, ready_text(n)) for w in idle[:n]]
169
+
170
+
171
+ def task_text(d: Path, tid: int, holder: str) -> str:
172
+ """Earlier reports stay: they say why a task came back. The leader wrote the brief, so the
173
+ text goes out as the leader's: inside the tool's own notice, a notice-shaped line in a brief
174
+ passed for one."""
175
+ return _path(d, "running", tid, holder).read_bytes().decode("utf-8")
176
+
177
+
178
+ def _sync(folder: Path) -> None:
179
+ fd = os.open(folder, os.O_RDONLY)
180
+ try:
181
+ os.fsync(fd)
182
+ finally:
183
+ os.close(fd)
184
+
185
+
186
+ def _mkdir(folder: Path) -> None:
187
+ """A new folder survives a power loss only once the folder above it is synced."""
188
+ if not folder.is_dir():
189
+ _mkdir(folder.parent)
190
+ folder.mkdir()
191
+ _sync(folder.parent)
192
+
193
+
194
+ def _move(d: Path, t: Task, state: State, holder: str | None) -> None:
195
+ dst = _path(d, state, t.id, holder)
196
+ _mkdir(dst.parent)
197
+ if state == "running":
198
+ # A crash or a power loss after an earlier move can leave that hold's marks, and a hold
199
+ # that found them would stop with nobody told: each hold starts without them.
200
+ for stale in (dst.with_suffix(".refused"), dst.with_suffix(".waiting")):
201
+ stale.unlink(missing_ok=True)
202
+ _sync(dst.parent)
203
+ src = _path(d, t.state, t.id, t.holder)
204
+ src.rename(dst)
205
+ for folder in {dst.parent, src.parent}: # a rename is durable only once both folders are
206
+ _sync(folder)
207
+ _mark(d, t).unlink(missing_ok=True)
208
+ _mark(d, t).with_suffix(".waiting").unlink(missing_ok=True)
209
+
210
+
211
+ def act( # noqa: PLR0911, PLR0912, PLR0915 - one function: each verb's rules read in turn
212
+ d: Path,
213
+ verb: str,
214
+ args: Sequence[str],
215
+ caller: str,
216
+ workers: Sequence[str],
217
+ activity: Mapping[str, Activity],
218
+ names: Mapping[str, str],
219
+ brief: str = "",
220
+ to: str | None = None,
221
+ ) -> tuple[str, list[Notice]]:
222
+ if verb not in ARITY:
223
+ raise UsageError(VERBS)
224
+ least, most = ARITY[verb]
225
+ if not least <= len(args) <= most:
226
+ raise UsageError(USAGE[verb])
227
+ role = "owner" if caller == "owner" else "leader" if caller == "leader" else "worker"
228
+ if role == "owner":
229
+ raise Refused(OWNER)
230
+ if verb in ("new", "close", "back") and role != "leader":
231
+ raise Refused(f"`board {verb}` is the leader's; ask the leader.")
232
+ if verb == "take" and role != "worker":
233
+ raise Refused(
234
+ "`board take` is a worker's; the leader gives a task to one worker with"
235
+ " `board new TITLE --to WORKER`."
236
+ )
237
+ if verb == "report" and role != "worker":
238
+ # A leader runs it to read a report it was sent; pointed elsewhere, a real one asked the
239
+ # worker to send the report again.
240
+ raise Refused(
241
+ "`board report` is a worker's. A worker's report reaches you as its message"
242
+ ' right after the tool\'s "reported" notice.'
243
+ )
244
+ all_ = {t.id: t for t in tasks(d)}
245
+ if verb == "new":
246
+ title = args[0].strip()
247
+ if not title:
248
+ raise UsageError(USAGE["new"])
249
+ if "\n" in title:
250
+ raise Refused(
251
+ "A task's title is one line; put the rest in the brief (`board new TITLE -f FILE`)."
252
+ )
253
+ # Checked before anything is written: a refused --to makes no task and uses no id.
254
+ # Given empty, as an unset shell variable gives it, it still names a worker: none.
255
+ w = (
256
+ _target(to, all_, workers, activity, names, " No task was made.")
257
+ if to is not None
258
+ else None
259
+ )
260
+ tid = max(all_, default=0) + 1
261
+ p = _path(d, "running" if w else "ready", tid, w)
262
+ _mkdir(p.parent)
263
+ write_atomic(p, f"{title}\n\n{brief}".encode())
264
+ crash_point("board.write")
265
+ if w:
266
+ given = _given(d, tid, w) + ready_notices(d, workers, activity)
267
+ return f"Created T{tid} and gave it to {to}; it is Running.", given
268
+ return f"Created T{tid}.", ready_notices(d, workers, activity)
269
+ mine = next((t for t in all_.values() if t.state == "running" and t.holder == caller), None)
270
+ if verb == "take" and mine:
271
+ raise Refused(f"You hold T{mine.id}; report it before you take another.")
272
+ if not args:
273
+ ready = [t for t in all_.values() if t.state == "ready"]
274
+ if not ready:
275
+ # An answer, not a refusal: as a failed command it sent half the workers measured
276
+ # straight back to `take` (5 in 10; 1 in 10 as an answer).
277
+ return "Ready is empty; end your turn. You will be told.", []
278
+ t = ready[0]
279
+ else:
280
+ tid = task_id(args[0])
281
+ if tid not in all_:
282
+ raise Refused(f"There is no task T{tid}.")
283
+ t = all_[tid]
284
+ if verb == "take":
285
+ if t.state != "ready":
286
+ raise Refused(_where(t, names) + " Only a Ready task can be taken.")
287
+ _move(d, t, "running", caller)
288
+ return f"Took T{t.id}. It is yours and Running. Its text, from leader:\n\n" + task_text(
289
+ d, t.id, caller
290
+ ), []
291
+ if verb == "report":
292
+ if len(args) < 2 or not args[1].strip():
293
+ raise Refused(
294
+ f"`board report T{t.id}` needs the result text: "
295
+ f'board report T{t.id} "what you did".'
296
+ )
297
+ if t.state != "running":
298
+ raise Refused(_where(t, names) + " Only a Running task can be reported.")
299
+ if t.holder != caller:
300
+ raise Refused(f"T{t.id} is held by {names.get(t.holder or '', t.holder)}.")
301
+ p = _path(d, "running", t.id, caller)
302
+ stamp = _stamp()
303
+ write_atomic(p, p.read_bytes() + f"\n--- report {caller} {stamp}\n{args[1]}\n".encode())
304
+ crash_point("board.write")
305
+ _move(d, t, "review", caller)
306
+ who = names.get(caller, caller)
307
+ return (
308
+ f"Reported T{t.id}; it is in Review.",
309
+ [
310
+ Notice(
311
+ "leader",
312
+ f"{who} reported T{t.id}. It is in Review. Its report follows, from {who}.",
313
+ ),
314
+ # Its text goes out as the worker's: no leader opened a task file to read it.
315
+ Notice("leader", args[1], who),
316
+ ],
317
+ )
318
+ if verb == "close":
319
+ # From Ready too: a postponed task left there is taken (15 in 15). Nobody holds it, so
320
+ # nobody is told; a Running task has a holder working on it, and `back` tells it.
321
+ if t.state not in ("ready", "review"):
322
+ raise Refused(_where(t, names) + " Only a Ready or Review task can be closed.")
323
+ _move(d, t, "done", t.holder)
324
+ return f"Closed T{t.id}.", []
325
+ # back: the arity check left no other verb. A Ready task too, given with --to: making it
326
+ # again would cost its id, its brief and a true Done count.
327
+ if t.state == "ready" and to is None:
328
+ raise Refused(
329
+ f"T{t.id} is already in Ready; `workcrew board back {t.id} --to WORKER` gives it to"
330
+ " one worker."
331
+ )
332
+ if t.state not in ("running", "review", "ready"):
333
+ raise Refused(
334
+ _where(t, names)
335
+ + " Only a Running or Review task goes back, and a Ready one with --to."
336
+ )
337
+ if to is not None:
338
+ # A task handed to one worker keeps its whole file, earlier reports included.
339
+ w = _target(to, all_, workers, activity, names, f" T{t.id} stays where it is.")
340
+ _move(d, t, "running", w)
341
+ notices = _given(d, t.id, w)
342
+ was = (
343
+ t.holder
344
+ if t.state == "running" and t.holder and activity.get(t.holder) in LIVE
345
+ else None
346
+ )
347
+ if was:
348
+ notices.append(
349
+ Notice(was, f"T{t.id} went to {to}; stop work on it. Take the next Ready task.")
350
+ )
351
+ return f"Gave T{t.id} to {to}; it is Running.", notices + ready_notices(
352
+ d, workers, activity, was
353
+ )
354
+ _move(d, t, "ready", None)
355
+ if t.state == "running" and t.holder and activity.get(t.holder) in LIVE:
356
+ told = Notice(
357
+ t.holder, f"T{t.id} went back to Ready; stop work on it. Take the next Ready task."
358
+ )
359
+ return f"T{t.id} is back in Ready.", [
360
+ *ready_notices(d, workers, activity, t.holder),
361
+ told,
362
+ ]
363
+ return f"T{t.id} is back in Ready.", ready_notices(d, workers, activity)
364
+
365
+
366
+ def _target(
367
+ to: str,
368
+ all_: Mapping[int, Task],
369
+ workers: Sequence[str],
370
+ activity: Mapping[str, Activity],
371
+ names: Mapping[str, str],
372
+ nothing: str,
373
+ ) -> str:
374
+ """The worker a task is given to: live and holding nothing, or refused saying who holds what
375
+ and what was not done."""
376
+ ids = {names.get(w, w): w for w in workers}
377
+ w = ids.get(to)
378
+ if w is None:
379
+ # An empty one, as an unset shell variable gives it, is shown, or the sentence has none.
380
+ shown = to or '""'
381
+ raise Refused(f"{shown} is not a worker of this team." + nothing)
382
+ if activity.get(w) == "not-started":
383
+ raise Refused(f"{to} has not started yet; `resume` starts it." + nothing)
384
+ if activity.get(w) not in LIVE:
385
+ raise Refused(f"{to} is EXITED; `resume` brings it back." + nothing)
386
+ busy = next((x for x in all_.values() if x.state == "running" and x.holder == w), None)
387
+ if busy:
388
+ raise Refused(f"{to} holds T{busy.id}." + nothing)
389
+ return w
390
+
391
+
392
+ def _given(d: Path, tid: int, w: str) -> list[Notice]:
393
+ return [
394
+ Notice(w, f"T{tid} is assigned to you and Running. Its text follows, from leader."),
395
+ Notice(w, task_text(d, tid, w), "leader"),
396
+ ]
397
+
398
+
399
+ def release(
400
+ d: Path,
401
+ member: str,
402
+ workers_after: Sequence[str],
403
+ activity: Mapping[str, Activity],
404
+ names: Mapping[str, str],
405
+ ) -> tuple[list[int], list[Notice]]:
406
+ t = held(d, member)
407
+ if t is not None:
408
+ _move(d, t, "ready", None)
409
+ # Told even when it held nothing: it may have been the worker told of a Ready task.
410
+ return ([t.id] if t else []), ready_notices(d, workers_after, activity)
411
+
412
+
413
+ def cut(s: str, n: int) -> str:
414
+ """The longest prefix of `s` within `n` columns, ending in `...`; zero-width marks stay."""
415
+ if cols(s) <= n:
416
+ return s
417
+ keep, used = [], 0
418
+ for c in s:
419
+ w = cols(c)
420
+ if used + w > n - 3:
421
+ break
422
+ keep.append(c)
423
+ used += w
424
+ return "".join(keep) + "..."
425
+
426
+
427
+ def _age(since: float, now: float) -> str:
428
+ s = int(now - since)
429
+ for unit, size in (("d", 86400), ("h", 3600), ("m", 60)):
430
+ if s >= size:
431
+ return f"{s // size}{unit}"
432
+ return f"{s}s"
433
+
434
+
435
+ def view(
436
+ d: Path,
437
+ members: Sequence[tuple[str, Activity]],
438
+ names: Mapping[str, str],
439
+ size: tuple[int, int] | None,
440
+ ) -> str:
441
+ now = time.time()
442
+ all_ = tasks(d)
443
+ holding = {t.holder: t for t in all_ if t.state == "running"}
444
+ workers = [(m, a) for m, a in members if m != "leader"]
445
+ tally = {
446
+ a: sum(x == a for _, x in workers)
447
+ for a in ("busy", "wait", "idle", "exited", "not-started")
448
+ }
449
+ review = sorted((t for t in all_ if t.state == "review"), key=lambda t: t.since)
450
+ ready = [t for t in all_ if t.state == "ready"]
451
+ done = sorted((t for t in all_ if t.state == "done"), key=lambda t: t.since)[-3:]
452
+ oldest = f" (oldest {_age(review[0].since, now)})" if review else ""
453
+ head = [
454
+ f"{len(workers)} worker{'s' * (len(workers) != 1)}:"
455
+ f" {tally['busy']} busy, {tally['wait']} waiting, "
456
+ f"{tally['idle']} idle, {tally['exited']} exited, {tally['not-started']} not started",
457
+ f"ready {len(ready)} review {len(review)}{oldest} "
458
+ f"done {sum(t.state == 'done' for t in all_)}",
459
+ ]
460
+ word = {
461
+ "busy": "busy",
462
+ "wait": "WAITING",
463
+ "idle": "IDLE",
464
+ "exited": "EXITED",
465
+ "not-started": "not started",
466
+ }
467
+ name_w = max((cols(escape(names.get(m, m))) for m, _ in members), default=0)
468
+
469
+ def row(cells: Sequence[tuple[str, int]], title: str) -> str:
470
+ text = " " + " ".join(c + " " * (w - cols(c)) for c, w in cells)
471
+ # A tab would pass the column check as 1 and draw up to 8 wide.
472
+ return text + (" " + escape(title).replace("\t", " ") if title else "")
473
+
474
+ def task_row(t: Task, who: str | None = None) -> str:
475
+ cells = [(f"T{t.id}", 6), (_age(t.since, now), 4)]
476
+ if who is not None:
477
+ cells.append((escape(names.get(who, who)), name_w))
478
+ return row(cells, t.title)
479
+
480
+ sections: list[tuple[str, list[str], int]] = [
481
+ (
482
+ "MEMBERS",
483
+ [
484
+ row(
485
+ [(escape(names.get(m, m)), name_w), (word[a], 11)]
486
+ + (
487
+ [(f"T{holding[m].id}", 6), (_age(holding[m].since, now), 4)]
488
+ if m in holding
489
+ else []
490
+ ),
491
+ holding[m].title if m in holding else "",
492
+ )
493
+ for m, a in members
494
+ ],
495
+ len(members),
496
+ ),
497
+ ("REVIEW, oldest first", [task_row(t, t.holder) for t in review], len(review)),
498
+ (
499
+ f"READY {len(ready)}",
500
+ [task_row(t) for t in (ready if size is None else ready[:5])],
501
+ len(ready),
502
+ ),
503
+ ("DONE, last 3", [task_row(t, t.holder) for t in done], len(done)),
504
+ ]
505
+ shown = [list(rows) for _, rows, _ in sections]
506
+
507
+ def lines() -> list[str]:
508
+ out = list(head)
509
+ for (title, _, total), rows in zip(sections, shown, strict=True):
510
+ out.append(title)
511
+ out += rows
512
+ if total > len(rows):
513
+ out.append(f" +{total - len(rows)} more")
514
+ return out
515
+
516
+ if size is None:
517
+ return "\n".join(lines())
518
+ width, height = size
519
+ for i in reversed(
520
+ range(1, len(sections))
521
+ ): # lower sections first; members and the headline stay
522
+ total = sections[i][2]
523
+ # A section's last row popped becomes "+N more": no line saved when it held them all.
524
+ while len(lines()) > height and shown[i] and total > 1:
525
+ shown[i].pop()
526
+ return "\n".join(cut(x, width) for x in lines()[:height])
527
+
528
+
529
+ def status_line(
530
+ leader_exited: bool,
531
+ waiting: Sequence[str],
532
+ counts: Mapping[State, int],
533
+ idle: int,
534
+ exited: int,
535
+ link_stopped: bool,
536
+ width: int,
537
+ ) -> str:
538
+ fields = []
539
+ if leader_exited:
540
+ fields.append("leader EXITED: resume")
541
+ if waiting:
542
+ more = f" +{len(waiting) - 3}" if len(waiting) > 3 else ""
543
+ fields.append("waiting " + " ".join(waiting[:3]) + more)
544
+ tail = f" exited {exited}" if exited else ""
545
+ fields.append(f"ready {counts['ready']} review {counts['review']} idle {idle}{tail}")
546
+ if link_stopped:
547
+ fields.append("link stopped: resume")
548
+ line = ""
549
+ # Whole fields only: tmux cuts at a column, and `exited 2` read as `exited 0`.
550
+ for f in fields:
551
+ nxt = f if not line else f"{line} · {f}"
552
+ if cols(nxt) > width:
553
+ break
554
+ line = nxt
555
+ return line