chewcw-work-queue 0.3.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.
work_queue/commands.py ADDED
@@ -0,0 +1,623 @@
1
+ """The subcommand bodies.
2
+
3
+ Kept in one module so the dispatch table in cli.py stays a table.
4
+ """
5
+
6
+ import json
7
+ import os
8
+ import re
9
+ import socket
10
+ from datetime import date, datetime, timezone
11
+ from pathlib import Path
12
+
13
+ from . import artefacts, gates, gh, labels
14
+
15
+
16
+ def _opt(args, name, default=None):
17
+ """Value of --name, or default. The last occurrence wins, as in the shell script."""
18
+ value = default
19
+ i = 0
20
+ while i < len(args):
21
+ if args[i] == name:
22
+ value = args[i + 1] if i + 1 < len(args) else None
23
+ i += 2
24
+ continue
25
+ i += 1
26
+ return value
27
+
28
+
29
+ def _unknown(args, known):
30
+ """Raise on the first argument the subcommand does not know."""
31
+ for a in args:
32
+ if a not in known:
33
+ gh.die(f"unknown option: {a}")
34
+
35
+
36
+ def _deps(body, open_numbers):
37
+ """Issue numbers named in a `Depends on` section of the body."""
38
+ inside = False
39
+ found = []
40
+ for line in body.split("\n"):
41
+ if re.match(r"^#+ *(Depends on|Blocked by)", line, re.I):
42
+ inside = True
43
+ elif re.match(r"^#+", line):
44
+ inside = False
45
+ elif inside:
46
+ found += [int(m[1:]) for m in re.findall(r"#[0-9]+", line)]
47
+ return found
48
+
49
+
50
+ def cmd_list(args, dry):
51
+ stage = _opt(args, "--stage")
52
+ as_json = "--json" in args
53
+ _unknown([a for a in args if a != "--json"], {"--stage", stage})
54
+ if not stage:
55
+ gh.die("usage: work-queue list --stage <label>")
56
+ if not labels.is_queue(stage):
57
+ gh.die(f"'{stage}' is not a queue label")
58
+ gh.need_gh()
59
+
60
+ issues = gh.list_json(state="open", fields="number,title,body,labels,assignees")
61
+ open_numbers = [i["number"] for i in issues]
62
+ for issue in issues:
63
+ names = [l["name"] for l in issue.get("labels", [])]
64
+ if stage not in names:
65
+ continue
66
+ deps = _deps(issue.get("body") or "", open_numbers)
67
+ # An issue with an open blocker is not in the frontier, so it is not listed.
68
+ if [d for d in deps if d in open_numbers]:
69
+ continue
70
+ if as_json:
71
+ print(
72
+ json.dumps(
73
+ {
74
+ "number": issue["number"],
75
+ "title": issue["title"],
76
+ "assignees": [a["login"] for a in issue.get("assignees", [])],
77
+ "blocked_by": deps,
78
+ },
79
+ separators=(",", ":"),
80
+ )
81
+ )
82
+ else:
83
+ print(
84
+ "{}\t{}\t{}".format(
85
+ issue["number"],
86
+ issue["title"],
87
+ ",".join(a["login"] for a in issue.get("assignees", [])),
88
+ )
89
+ )
90
+ return 0
91
+
92
+
93
+ def _claim_body(stage, me, harness, session, artefact):
94
+ lines = [f"claim: {me}", "", f"- work: {stage.split(':', 1)[1]}"]
95
+ if artefact:
96
+ lines.append(f"- artefact: {artefact}")
97
+ lines.append(f"- harness: {harness}")
98
+ if session:
99
+ lines.append(f"- session: {session}")
100
+ lines.append("- started: " + datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"))
101
+ lines.append("- host: " + (socket.gethostname().split(".")[0] or "host"))
102
+ return "\n".join(lines)
103
+
104
+
105
+ def _claim_artefact_path(stage, target):
106
+ """The file a reader of the claim should open, or "" while it does not exist."""
107
+ if stage == "agent:build":
108
+ directory = artefacts.plan_dir_for(target)
109
+ if not directory:
110
+ return ""
111
+ return f"{directory}/{artefacts.plan_index_name()}"
112
+ return artefacts.spec_path_for(target)
113
+
114
+
115
+ def _claim_artefact(stage, target):
116
+ """The artefact line and the next-skill line for a claimed issue."""
117
+ if stage == "agent:spec":
118
+ path = artefacts.spec_path_for(target)
119
+ if not path:
120
+ art = f"issue #{target} (no spec file yet)"
121
+ else:
122
+ status = artefacts.frontmatter_field(path, "status") or "missing"
123
+ gate = artefacts.frontmatter_field(path, "gate")
124
+ art = f"spec {path} (status: {status}" + (f", gate: {gate})" if gate else ")")
125
+ nxt = "grill-to-spec (ask the human to run /skill:grill-to-spec) or spec-from-issue"
126
+ elif stage == "agent:plan":
127
+ art = artefacts.spec_path_for(target)
128
+ nxt = "writing-plans"
129
+ elif stage == "agent:build":
130
+ art = artefacts.plan_dir_for(target)
131
+ nxt = "executing-plans"
132
+ else:
133
+ art = f"issue #{target}"
134
+ nxt = "triage"
135
+ return art or "none found — see work-queue verify", nxt
136
+
137
+
138
+ ARTEFACT_LINE = "- artefact: "
139
+
140
+
141
+ def _with_artefact(body, path):
142
+ """The claim body with one artefact line: replaced in place, or inserted after the work line."""
143
+ lines = body.split("\n")
144
+ for i, line in enumerate(lines):
145
+ if line.startswith(ARTEFACT_LINE):
146
+ lines[i] = ARTEFACT_LINE + path
147
+ return "\n".join(lines)
148
+ for i, line in enumerate(lines):
149
+ if line.startswith("- work: "):
150
+ lines.insert(i + 1, ARTEFACT_LINE + path)
151
+ return "\n".join(lines)
152
+ return body + "\n" + ARTEFACT_LINE + path
153
+
154
+
155
+ def _claim_comment(n, me):
156
+ """(id, body) of the newest claim comment by me on #n, or (0, "") when there is none."""
157
+ r = gh.run(
158
+ [
159
+ "api",
160
+ "--paginate",
161
+ f"repos/{gh.QUEUE_REPO}/issues/{n}/comments?per_page=100",
162
+ "-q",
163
+ ".[] | {id: .id, body: .body, user: .user} | @json",
164
+ ]
165
+ )
166
+ if r.returncode != 0:
167
+ gh.envfail(f"could not read the comments on #{n}")
168
+ mine = []
169
+ for line in r.stdout.splitlines():
170
+ line = line.strip()
171
+ if not line:
172
+ continue
173
+ try:
174
+ c = json.loads(line)
175
+ except ValueError:
176
+ gh.envfail(f"could not read the comments on #{n}")
177
+ if (c.get("user") or {}).get("login") != me:
178
+ continue
179
+ if str(c.get("body") or "").startswith("claim: "):
180
+ mine.append(c)
181
+ if not mine:
182
+ return 0, ""
183
+ return mine[-1].get("id", 0), mine[-1].get("body", "")
184
+
185
+
186
+ def cmd_record(args, dry):
187
+ n = _opt(args, "--issue")
188
+ path = _opt(args, "--artefact")
189
+ _unknown(args, {"--issue", n, "--artefact", path})
190
+ if not n or not path:
191
+ gh.die("usage: work-queue record --issue N --artefact PATH")
192
+ gh.need_gh()
193
+ stage = next((x for x in labels.labels_of(n).split() if labels.is_queue(x)), "")
194
+ if not stage:
195
+ gh.die(f"#{n} carries no queue label")
196
+ if not Path(path).is_file():
197
+ gh.die(f"no such file: {path}")
198
+ owned = artefacts.frontmatter_field(path, "issue")
199
+ if owned and owned != str(n):
200
+ gh.die(f"{path} names issue {owned}, not #{n}")
201
+ me = gh.out(["api", "user", "--jq", ".login"])
202
+ if not me:
203
+ gh.envfail("cannot determine the logged-in account")
204
+ cid, body = _claim_comment(n, me)
205
+ if not cid:
206
+ gh.die(f"no claim comment by {me} on #{n}; run claim first")
207
+ claimed = ""
208
+ for line in body.split("\n"):
209
+ if line.startswith("- work: "):
210
+ claimed = line[len("- work: "):].strip()
211
+ break
212
+ rung = stage.split(":", 1)[1]
213
+ if claimed and claimed != rung:
214
+ gh.die(f"the claim on #{n} is for {claimed}, and the issue is at {stage}")
215
+ new_body = _with_artefact(body, path)
216
+ gh.ghm(
217
+ ["api", "-X", "PATCH", f"repos/{gh.QUEUE_REPO}/issues/comments/{cid}", "-f", "body=" + new_body],
218
+ dry,
219
+ )
220
+ if dry:
221
+ print(f"would record {path} on #{n}")
222
+ return 0
223
+ again = gh.out(["api", f"repos/{gh.QUEUE_REPO}/issues/comments/{cid}", "-q", ".body"])
224
+ if again.strip() != new_body.strip():
225
+ gh.drift(f"the artefact line did not land on #{n}")
226
+ print(f"recorded {path} on #{n}")
227
+ return 0
228
+
229
+
230
+ def cmd_claim(args, dry):
231
+ stage = _opt(args, "--stage")
232
+ want = _opt(args, "--issue")
233
+ harness = _opt(args, "--harness")
234
+ session = _opt(args, "--session")
235
+ if not stage:
236
+ gh.die("usage: work-queue claim --stage <label> [--issue N] [--harness NAME] [--session NAME]")
237
+ if not labels.is_queue(stage):
238
+ gh.die(f"'{stage}' is not a queue label")
239
+ gh.need_gh()
240
+ labels.ensure_labels(dry)
241
+
242
+ me = gh.out(["api", "user", "--jq", ".login"])
243
+ if not me:
244
+ gh.envfail("cannot determine the logged-in account")
245
+ if not harness:
246
+ harness = gh.detect_harness()
247
+ if not session:
248
+ session = os.environ.get("PI_SESSION_ID") or ""
249
+
250
+ if want:
251
+ target = want
252
+ current = labels.labels_of(target)
253
+ if not labels.has_label(current, stage):
254
+ gh.die(f"#{target} is not at {stage}")
255
+ else:
256
+ target = ""
257
+ for row in _frontier_rows(stage):
258
+ if not row["assignees"]:
259
+ target = row["number"]
260
+ break
261
+ if not target:
262
+ print(f"nothing claimable at {stage}")
263
+ return 0
264
+
265
+ body = _claim_body(stage, me, harness, session, _claim_artefact_path(stage, target))
266
+
267
+ gh.ghm(["issue", "edit", str(target), "--add-assignee", "@me"], dry)
268
+ gh.ghm(["issue", "comment", str(target), "--body", body], dry)
269
+
270
+ if dry:
271
+ print(f"would claim #{target}")
272
+ return 0
273
+
274
+ # The first line is the only part of the comment the race check parses.
275
+ newest = gh.out(
276
+ [
277
+ "issue",
278
+ "view",
279
+ str(target),
280
+ "--json",
281
+ "comments",
282
+ "--jq",
283
+ '[.comments[].body | select(startswith("claim:"))] | last // ""',
284
+ ]
285
+ )
286
+ first = newest.split("\n")[0]
287
+ if not (first == f"claim: {me}" or first.startswith(f"claim: {me} ")):
288
+ gh.run(["issue", "edit", str(target), "--remove-assignee", "@me"])
289
+ gh.die(f"lost the claim on #{target} to: {newest or 'another runner'}")
290
+
291
+ art, nxt = _claim_artefact(stage, target)
292
+ print(f"claimed #{target}")
293
+ print(f"artefact: {art}")
294
+ print(f"next: {nxt}")
295
+ return 0
296
+
297
+
298
+ def _frontier_rows(stage):
299
+ """The same frontier cmd_list prints, as dicts, without printing."""
300
+ issues = gh.list_json(state="open", fields="number,title,body,labels,assignees")
301
+ open_numbers = [i["number"] for i in issues]
302
+ rows = []
303
+ for issue in issues:
304
+ if stage not in [l["name"] for l in issue.get("labels", [])]:
305
+ continue
306
+ deps = _deps(issue.get("body") or "", open_numbers)
307
+ if [d for d in deps if d in open_numbers]:
308
+ continue
309
+ rows.append(
310
+ {
311
+ "number": issue["number"],
312
+ "title": issue["title"],
313
+ "assignees": [a["login"] for a in issue.get("assignees", [])],
314
+ "blocked_by": deps,
315
+ }
316
+ )
317
+ return rows
318
+
319
+
320
+ def cmd_move(args, dry):
321
+ n = _opt(args, "--issue")
322
+ to = _opt(args, "--to")
323
+ spec = _opt(args, "--spec")
324
+ plan = _opt(args, "--plan")
325
+ reason = _opt(args, "--reason")
326
+ _unknown(args, {"--issue", n, "--to", to, "--spec", spec, "--plan", plan, "--reason", reason})
327
+ if not n or not to:
328
+ gh.die("usage: work-queue move --issue N --to <label>")
329
+ if not labels.is_vocab(to):
330
+ gh.die(f"'{to}' is not in the vocabulary (see: work-queue init --help)")
331
+ gh.need_gh()
332
+
333
+ # One precondition for every rung, separate from the evidence each rung demands.
334
+ if to.startswith("agent:"):
335
+ gates.gate_kind(n)
336
+
337
+ if to == "agent:spec":
338
+ gates.gate_scope(n)
339
+ elif to == "agent:plan":
340
+ gates.gate_spec(spec, n)
341
+ elif to == "agent:build":
342
+ gates.gate_plan(plan, n)
343
+ elif to.startswith("human:"):
344
+ if not reason:
345
+ gh.die(f"--reason is required to move to {to}")
346
+
347
+ if labels.is_queue(to):
348
+ labels.apply_queue_label(n, to, dry)
349
+ labels.clear_assignees(n, dry)
350
+ if reason:
351
+ gh.ghm(["issue", "comment", str(n), "--body", f"Moved to {to}: {reason}"], dry)
352
+ else:
353
+ labels.ensure_labels(dry)
354
+ labels.add_label(n, to, dry)
355
+ print(f"#{n} → {to}")
356
+ return 0
357
+
358
+
359
+ def slug_of(title):
360
+ import re as _re
361
+
362
+ text = _re.sub(r"^(bug|idea|scope|spec|intent):\s*", "", title or "")
363
+ text = text.lower()
364
+ text = _re.sub(r"[^a-z0-9]+", "-", text)
365
+ return text.strip("-")
366
+
367
+
368
+ def record_rejection(n, slug, note, dry):
369
+ path = Path(artefacts.out_of_scope_dir()) / f"{slug}.md"
370
+ if dry:
371
+ print(f"would: write {path}")
372
+ return
373
+ path.parent.mkdir(parents=True, exist_ok=True)
374
+ today = date.today().isoformat()
375
+ if not path.exists():
376
+ path.write_text(
377
+ f"# {slug}\n\n## Decision\nRejected on {today}, from #{n}. {note}\n\n## Issues\n"
378
+ )
379
+ with path.open("a") as handle:
380
+ handle.write(f"- #{n}: {today}, {note}\n")
381
+ print(f"recorded in {path}")
382
+
383
+
384
+ def cmd_close(args, dry):
385
+ states = {"done": "completed", "wontfix": "not planned", "dup": "duplicate", "deferred": "not planned"}
386
+ n = _opt(args, "--issue")
387
+ reason = _opt(args, "--reason")
388
+ note = _opt(args, "--note")
389
+ of = _opt(args, "--of")
390
+ concept = _opt(args, "--concept")
391
+ if not n:
392
+ gh.die("--issue N is required")
393
+ if reason not in states:
394
+ gh.die("--reason must be done, wontfix, dup or deferred")
395
+ gh.need_gh()
396
+
397
+ folded = reason
398
+ if reason == "dup" and of:
399
+ folded = f"dup of #{of}"
400
+ elif note:
401
+ folded = f"{reason}: {note}"
402
+ body = f"Closing: {folded}"
403
+
404
+ if reason == "wontfix":
405
+ slug = concept or slug_of(gh.out(["issue", "view", str(n), "--json", "title", "--jq", ".title"]))
406
+ if not slug:
407
+ gh.die(f"could not derive a concept name for #{n}, pass --concept SLUG")
408
+ record_rejection(n, slug, note or "no reason given", dry)
409
+ body += f"\n- recorded in {Path(artefacts.out_of_scope_dir(), slug + '.md').as_posix()}"
410
+
411
+ gh.ghm(["issue", "comment", str(n), "--body", body], dry)
412
+ gh.ghm(["issue", "close", str(n), "--reason", states[reason]], dry)
413
+ labels.clear_assignees(n, dry)
414
+
415
+ current = labels.labels_of(n)
416
+ for name in labels.vocab_names():
417
+ if labels.is_queue(name) and labels.has_label(current, name):
418
+ labels.remove_label(n, name, dry)
419
+ if reason == "deferred":
420
+ labels.ensure_labels(dry)
421
+ labels.add_label(n, "deferred", dry)
422
+ else:
423
+ labels.remove_label(n, "deferred", dry)
424
+ print(f"#{n} closed ({reason})")
425
+ return 0
426
+
427
+
428
+ def cmd_reopen(args, dry):
429
+ n = _opt(args, "--issue")
430
+ reason = _opt(args, "--reason")
431
+ if not n:
432
+ gh.die("--issue N is required")
433
+ if not reason:
434
+ gh.die("--reason TEXT is required")
435
+ gh.need_gh()
436
+ r = gh.ghm(["issue", "reopen", str(n)], dry)
437
+ if r is not None and r.returncode != 0:
438
+ gh.drift(f"could not reopen #{n}")
439
+ labels.remove_label(n, "deferred", dry)
440
+ labels.apply_queue_label(n, "human:triage", dry)
441
+ gh.ghm(["issue", "comment", str(n), "--body", f"Reopened: {reason}"], dry)
442
+ labels.clear_assignees(n, dry)
443
+ return 0
444
+
445
+
446
+ def cmd_park(args, dry):
447
+ n = _opt(args, "--issue")
448
+ to = _opt(args, "--to")
449
+ reason = _opt(args, "--reason")
450
+ if not n:
451
+ gh.die("--issue N is required")
452
+ if to not in ("human:triage", "human:info"):
453
+ gh.die("--to must be human:triage or human:info")
454
+ if not reason:
455
+ gh.die("--reason TEXT is required")
456
+ gh.need_gh()
457
+ gh.ghm(["issue", "comment", str(n), "--body", f"Parked at {to}: {reason}"], dry)
458
+ labels.apply_queue_label(n, to, dry)
459
+ labels.clear_assignees(n, dry)
460
+ return 0
461
+
462
+
463
+ def cmd_kind(args, dry):
464
+ n = _opt(args, "--issue")
465
+ to = _opt(args, "--to")
466
+ if not n:
467
+ gh.die("--issue N is required")
468
+ if not labels.is_item_kind(to):
469
+ gh.die("--to must be one of: " + " ".join(labels.ITEM_KINDS))
470
+ gh.need_gh()
471
+ labels.ensure_labels(dry)
472
+ current = labels.labels_of(n)
473
+ # The axis holds one value, so the previous answer is removed rather than stacked.
474
+ for name in labels.ITEM_KINDS:
475
+ if name != to and labels.has_label(current, name):
476
+ labels.remove_label(n, name, dry)
477
+ labels.add_label(n, to, dry)
478
+ print(f"#{n} kind: {to.split(':', 1)[1]}")
479
+ return 0
480
+
481
+
482
+ def promote_file(path, n):
483
+ """Record the promotion in the capture file itself, so it cannot be drained twice."""
484
+ p = Path(path)
485
+ lines = p.read_text().splitlines(keepends=True)
486
+ if not lines or lines[0].strip() != "---":
487
+ return
488
+ out = ["---\n", f"status: promoted\n", f"issue: {n}\n"]
489
+ for line in lines[1:]:
490
+ if line.strip() == "---":
491
+ out.append(line)
492
+ break
493
+ if line.startswith("status:") or line.startswith("issue:"):
494
+ continue
495
+ out.append(line)
496
+ rest_start = len(out)
497
+ out += lines[rest_start:]
498
+ p.write_text("".join(out))
499
+
500
+
501
+ def cmd_promote(args, dry):
502
+ path = _opt(args, "--file")
503
+ if not path:
504
+ gh.die("usage: work-queue promote --file <inbox file>")
505
+ if not Path(path).is_file():
506
+ gh.die(f"no such file: {path}")
507
+ if not artefacts.frontmatter_field(path, "captured"):
508
+ gh.die(f"{path} has no 'captured:' frontmatter, so it is not a capture")
509
+ if artefacts.frontmatter_field(path, "issue"):
510
+ gh.die(f"{path} is already promoted, its frontmatter names an issue")
511
+ title = artefacts.frontmatter_field(path, "title")
512
+ if not title:
513
+ gh.die(f"{path} has no 'title:' frontmatter")
514
+ # Checked before the issue exists, so a bad value leaves no half-made issue behind.
515
+ kind = artefacts.frontmatter_field(path, "kind")
516
+ if kind and not labels.is_item_kind("kind:" + kind):
517
+ gh.die(f"{path} records 'kind: {kind}', which is not one of: " + " ".join(k.split(':', 1)[1] for k in labels.ITEM_KINDS))
518
+ gh.need_gh()
519
+ if dry:
520
+ print(f"would: gh issue create --title {title} --body-file {path}")
521
+ print(f"would: park the new issue at human:triage and write issue: into {path}")
522
+ if kind:
523
+ print(f"would: record kind: {kind} on the new issue")
524
+ return 0
525
+
526
+ import tempfile
527
+
528
+ with tempfile.NamedTemporaryFile("w", suffix=".md", delete=False) as handle:
529
+ handle.write(artefacts.body_without_frontmatter(path))
530
+ body_path = handle.name
531
+ url = gh.out(["issue", "create", "--title", title, "--body-file", body_path])
532
+ Path(body_path).unlink()
533
+ if not url:
534
+ gh.die(f"could not create an issue from {path}")
535
+ num = url.rstrip("/").split("/")[-1]
536
+ if not num.isdigit():
537
+ gh.die(f"could not read an issue number from: {url}")
538
+ labels.apply_queue_label(num, "human:triage", dry)
539
+ if kind:
540
+ labels.add_label(num, "kind:" + kind, dry)
541
+ promote_file(path, num)
542
+ print(f"#{num} promoted from {path}")
543
+ return 0
544
+
545
+
546
+ def cmd_icebox(args, dry):
547
+ gh.need_gh()
548
+ for issue in gh.list_json(state="closed", labels="deferred", fields="number,title"):
549
+ print(f"#{issue['number']}\t{issue['title']}")
550
+ return 0
551
+
552
+
553
+ def cmd_triage(args, dry):
554
+ n = _opt(args, "--issue")
555
+ if not n:
556
+ gh.die("usage: work-queue triage --issue N")
557
+ gh.need_gh()
558
+ body = gh.out(["issue", "view", str(n), "--json", "body", "--jq", ".body"])
559
+ current = labels.labels_of(n)
560
+ tri = gh.out(
561
+ [
562
+ "issue",
563
+ "view",
564
+ str(n),
565
+ "--json",
566
+ "comments",
567
+ "--jq",
568
+ '[.comments[].body | select(startswith("%s"))] | last // ""' % gates.TRIAGE_MARK,
569
+ ]
570
+ )
571
+ spec = artefacts.spec_path_for(n)
572
+ plan = artefacts.plan_dir_for(n)
573
+ headings = ",".join(m.strip("# ").strip() for m in re.findall(r"^#+ *[A-Za-z ]+", body, re.M))
574
+ print(f"#{n} labels: {current or 'none'}")
575
+ print(f"body headings: {headings}")
576
+ print("outcome/boundary: " + ("yes" if gates._has_heading_text(body, ["Outcome", "Boundary"]) else "no"))
577
+ print(f"spec: {spec or 'none'}")
578
+ print(f"plan: {plan or 'none'}")
579
+ print(f"last triage marker: {tri or 'none'}")
580
+ print("exits: agent:spec | agent:plan | human:info | close")
581
+ print("this command decides nothing; the skill does.")
582
+ return 0
583
+
584
+
585
+ def cmd_migrate(args, dry):
586
+ path = _opt(args, "--map")
587
+ if not path:
588
+ gh.die("usage: work-queue migrate --map FILE (lines: old->new, or old->- to drop)")
589
+ if not Path(path).is_file():
590
+ gh.die(f"no such map file: {path}")
591
+ gh.need_gh()
592
+ labels.ensure_labels(dry)
593
+ for raw in Path(path).read_text().splitlines():
594
+ line = raw.split("#", 1)[0].strip()
595
+ if not line:
596
+ continue
597
+ if "->" not in line:
598
+ gh.die(f"map line needs old->new: {line}")
599
+ old, new = line.split("->", 1)
600
+ old, new = old.strip(), new.strip()
601
+ if not old:
602
+ continue
603
+ numbers = [i["number"] for i in gh.list_json(state="all", labels=old, fields="number")]
604
+ for n in numbers:
605
+ if new != "-":
606
+ r = gh.ghm(["issue", "edit", str(n), "--add-label", new], dry)
607
+ if r is not None and r.returncode != 0:
608
+ gh.warn(f"could not add {new} to #{n}")
609
+ r = gh.ghm(["issue", "edit", str(n), "--remove-label", old], dry)
610
+ if r is not None and r.returncode != 0:
611
+ gh.warn(f"could not remove {old} from #{n}")
612
+ print(f"#{n}: {old} → {new}")
613
+ gh.ghm(["label", "delete", old, "--yes"], dry)
614
+ if dry:
615
+ print(f"label '{old}' would be deleted")
616
+ else:
617
+ remaining = gh.out(["label", "list", "--limit", "500", "--json", "name", "--jq", ".[].name"])
618
+ if old in remaining.split("\n"):
619
+ gh.warn(f"could not delete label '{old}'")
620
+ else:
621
+ print(f"label '{old}' gone")
622
+ print("migrate done. Next: work-queue verify")
623
+ return 0