@miroshnik/elves 2026.1109.0 → 2026.1112.1

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.
@@ -332,6 +332,7 @@ var M = {
332
332
  RemoveBlockedBy: ["removeBlockedBy", "RemoveBlockedByInput", "issue { id }"],
333
333
  SetIssueField: ["setIssueFieldValue", "SetIssueFieldValueInput", "issue { id }"],
334
334
  CloseIssue: ["closeIssue", "CloseIssueInput", "issue { id state }"],
335
+ ReopenIssue: ["reopenIssue", "ReopenIssueInput", "issue { id state }"],
335
336
  UpdateIssue: ["updateIssue", "UpdateIssueInput", "issue { id }"],
336
337
  AddComment: ["addComment", "AddCommentInput", "subject { id }"],
337
338
  CreateRuleset: ["createRepositoryRuleset", "CreateRepositoryRulesetInput", "ruleset { id }"],
@@ -2878,6 +2879,45 @@ function pruneAgentWorktrees(io, slug, kept, closed = () => false) {
2878
2879
  `).filter((l) => l.startsWith("+")).length;
2879
2880
  return n ? `${plural(n, "commit", "commits")} not in ${upstream}` : null;
2880
2881
  };
2882
+ const releases = new Map;
2883
+ const releasedBy = (batch) => {
2884
+ if (!releases.has(batch)) {
2885
+ let pr = null;
2886
+ try {
2887
+ const release = releasePrOf(batchPrs(io, slug, batch), batch);
2888
+ pr = release?.merged ? release.number : null;
2889
+ } catch (e) {
2890
+ if (!(e instanceof GhError))
2891
+ throw e;
2892
+ }
2893
+ releases.set(batch, pr);
2894
+ }
2895
+ return releases.get(batch);
2896
+ };
2897
+ const mergedByPr = (sha) => {
2898
+ let pulls;
2899
+ try {
2900
+ pulls = rest(io, `repos/${slug}/commits/${sha}/pulls`) ?? [];
2901
+ } catch (e) {
2902
+ if (!(e instanceof GhError))
2903
+ throw e;
2904
+ return null;
2905
+ }
2906
+ for (const p of pulls) {
2907
+ const r = prRef(p);
2908
+ const tasks = prTasks(p);
2909
+ if (!r.merged || !r.sha || !tasks.length || !tasks.every(closed))
2910
+ continue;
2911
+ if (r.sha !== sha && git(io, io.cwd, "merge-base", "--is-ancestor", sha, r.sha).status !== 0)
2912
+ continue;
2913
+ const release = isBatchBranch(r.base) ? releasedBy(r.base) : null;
2914
+ if (r.base !== base && release === null)
2915
+ continue;
2916
+ const into = release === null ? r.base : `${r.base} (released by PR #${release})`;
2917
+ return `its HEAD is in PR #${r.number} merged into ${into}, ${tasks.map((n) => `#${n}`).join(", ")} closed`;
2918
+ }
2919
+ return null;
2920
+ };
2881
2921
  const deleteBranch = (branch) => {
2882
2922
  const d = git(io, io.cwd, "branch", "-D", branch);
2883
2923
  if (d.status !== 0)
@@ -2903,7 +2943,9 @@ function pruneAgentWorktrees(io, slug, kept, closed = () => false) {
2903
2943
  }
2904
2944
  const dirty = status.stdout.split(`
2905
2945
  `).filter((l) => l.trim()).length;
2906
- const reasons = [dirty ? `${plural(dirty, "uncommitted file", "uncommitted files")}` : null, unmerged(w.head)].filter((r) => r !== null);
2946
+ const cherry = unmerged(w.head);
2947
+ const byPr = !dirty && cherry !== null ? mergedByPr(w.head) : null;
2948
+ const reasons = [dirty ? `${plural(dirty, "uncommitted file", "uncommitted files")}` : null, byPr ? null : cherry].filter((r) => r !== null);
2907
2949
  if (reasons.length) {
2908
2950
  io.out(`○ worktree ${w.path} left: ${reasons.join(", ")}`);
2909
2951
  continue;
@@ -2916,7 +2958,7 @@ function pruneAgentWorktrees(io, slug, kept, closed = () => false) {
2916
2958
  continue;
2917
2959
  }
2918
2960
  const withBranch = w.branch !== null && deleteBranch(w.branch) ? ` with branch ${w.branch}` : "";
2919
- io.out(`+ worktree ${w.path} removed${withBranch}: clean, nothing outside ${upstream}`);
2961
+ io.out(`+ worktree ${w.path} removed${withBranch}: clean, ${byPr ?? `nothing outside ${upstream}`}`);
2920
2962
  }
2921
2963
  const checkedOut = new Set(all.map((w) => w.branch).filter(Boolean));
2922
2964
  const loose = git(io, io.cwd, "for-each-ref", "--format=%(refname:short)", "refs/heads/worktree-agent-*").stdout.split(`
@@ -3646,7 +3688,19 @@ function cmdTaskFinish(io, slug, number, o) {
3646
3688
  const outOfTime = (what) => stop(5, `○ out of time (--timeout ${o.timeout}) — ${what}`, `${again} — it goes on from here`);
3647
3689
  const issue = loadIssue(io, slug, number);
3648
3690
  if (issue.state !== "OPEN") {
3649
- const closer = issue.stateReason === "COMPLETED" ? issue.prs.find((p) => p.merged && !isBatchBranch(p.base)) ?? null : null;
3691
+ const closer = issue.stateReason === "COMPLETED" ? lastMerged(issue.prs.filter((p) => !isBatchBranch(p.base))) ?? null : null;
3692
+ const work = workPastMerge(io, slug, number, issue, closer);
3693
+ if (work) {
3694
+ if (issue.stateReason !== "COMPLETED")
3695
+ return stop(1, `! #${number} is closed as ${issue.stateReason ?? "not planned"}, but ${work}`, `gh issue reopen ${number} --repo ${slug}, then ${again}`);
3696
+ mutate(io, { op: "ReopenIssue", input: { issueId: issue.id } });
3697
+ if (!inCloud(io)) {
3698
+ const ctx = taskContext(io, slug);
3699
+ setStatus(io, ctx, ensureItem(io, ctx, issue).id, N.status.inProgress);
3700
+ }
3701
+ io.out(`+ #${number} reopened, ${STATUS} ${q(N.status.inProgress)}: ${work} — the task's merged PR isn't its finish`);
3702
+ return cmdTaskFinish(io, slug, number, { ...o, timeout: Math.max(0, left()) });
3703
+ }
3650
3704
  if (!closer || tailOver(io, slug, number))
3651
3705
  return io.out(`= #${number} is closed — nothing to finish`), 0;
3652
3706
  io.out(`○ #${number} is closed by the merge of PR #${closer.number}, the tail isn't over (no ${q(N.status.done)} with the actual) — going on`);
@@ -3656,8 +3710,9 @@ function cmdTaskFinish(io, slug, number, o) {
3656
3710
  throw new GhError(`task finish runs from a checkout of ${slug}: the current directory is not one`);
3657
3711
  const found = unlinkedPrs(io, slug, number);
3658
3712
  const prs = [...issue.prs, ...found.prs, ...found.batched].filter((p, k, all) => all.findIndex((x) => x.number === p.number) === k);
3659
- const merged = prs.find((p) => p.merged);
3660
- if (merged)
3713
+ const merged = lastMerged(prs);
3714
+ const pending = prs.some((p) => p.state === "OPEN") || merged && unmergedBranch(io, number, merged.base, merged.head);
3715
+ if (merged && !pending)
3661
3716
  return finishMerged(io, slug, number, issue.parent?.number ?? null, merged, { left, again, stop, outOfTime });
3662
3717
  const branch = git(io, io.cwd, "branch", "--show-current").stdout.trim();
3663
3718
  const open = prs.find((p) => p.state === "OPEN");
@@ -3734,6 +3789,36 @@ function cmdTaskFinish(io, slug, number, o) {
3734
3789
  const yes = locale_default.autoProject(io.cwd ?? process.cwd()) ? "" : "the owner's «yes» (the project is without auto) — then ";
3735
3790
  return stop(4, `✅ PR #${pr} is ready to merge`, `${yes}gh pr merge ${pr} --rebase — a separate call, no cd or pipeline (the owner's permission rule matches it); then ${again}${isBatchBranch(base) ? "" : " — in the background: it waits for the deploy"}`);
3736
3791
  }
3792
+ function lastMerged(prs) {
3793
+ return prs.filter((p) => p.merged).sort((a, b) => b.number - a.number)[0];
3794
+ }
3795
+ function unmergedBranch(io, number, base, mergedHead) {
3796
+ const branch = git(io, io.cwd, "branch", "--show-current").stdout.trim();
3797
+ if (!isTaskBranch(branch, number))
3798
+ return null;
3799
+ if (branch === mergedHead) {
3800
+ git(io, io.cwd, "fetch", "-q", "origin", `+refs/heads/${branch}:refs/remotes/origin/${branch}`);
3801
+ const past = git(io, io.cwd, "rev-list", "--count", `refs/remotes/origin/${branch}..HEAD`);
3802
+ if (past.status === 0)
3803
+ return Number(past.stdout.trim()) > 0 ? branch : null;
3804
+ }
3805
+ if (git(io, io.cwd, "fetch", "-q", "origin", `+refs/heads/${base}:refs/remotes/origin/${base}`).status !== 0)
3806
+ return null;
3807
+ const cherry = git(io, io.cwd, "cherry", `origin/${base}`, "HEAD");
3808
+ return cherry.status === 0 && cherry.stdout.split(`
3809
+ `).some((l) => l.startsWith("+")) ? branch : null;
3810
+ }
3811
+ function workPastMerge(io, slug, number, issue, closer) {
3812
+ const open = issue.prs.find((p) => p.state === "OPEN");
3813
+ if (open)
3814
+ return `its PR #${open.number} is open`;
3815
+ const current = git(io, io.cwd, "branch", "--show-current").stdout.trim();
3816
+ if (!isTaskBranch(current, number) || !checkoutOfRepo(io, originUrl(io), slug))
3817
+ return null;
3818
+ const base = closer?.base ?? unlinkedPrs(io, slug, number).base;
3819
+ const branch = unmergedBranch(io, number, base, closer?.head);
3820
+ return branch ? `branch ${branch} has commits that aren't in origin/${base}` : null;
3821
+ }
3737
3822
  function finishBase(io, slug, number, found) {
3738
3823
  const batch = handedPastBatch(io, slug, number) ? null : batchOf(io, slug);
3739
3824
  if (!batch)
@@ -4829,7 +4914,7 @@ label's — from the latest «External blocker: …» comment). Marks the sessio
4829
4914
  with the session's id; a session with a pinned task keeps it. Before the queue, in the repository's checkout —
4830
4915
  finished agents' worktrees (.claude/worktrees/agent-*, detached or on worktree-agent-*, not locked by a live process,
4831
4916
  not an executor's whose handed-out task is open; on a task branch — when its task is closed): clean and merged (git
4832
- cherry) — removed with the branch (+),
4917
+ cherry, or its HEAD in a merged PR of its closed task into the default branch or a released batch) — removed with the branch (+),
4833
4918
  otherwise left (○ with the reason), and so is one a subagent works in without a worktree of its own (its transcript
4834
4919
  written in the last ${QUIET_MINUTES} min); loose worktree-agent-* branches — the same. --type and --priority — in an
4835
4920
  organization. --assignment N (the executor's first call; read-only on GitHub) — its whole assignment; in a session
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@miroshnik/elves",
3
- "version": "2026.1109.0",
3
+ "version": "2026.1112.1",
4
4
  "type": "module",
5
5
  "description": "Elves — a development flow with AI agents: shared rules and skills for any agent; install — bunx @miroshnik/elves install -g; the installer and skill scripts — TypeScript under Bun, tests — bun test in tests/",
6
6
  "repository": {
@@ -72,5 +72,5 @@
72
72
  "eslint-plugin-boundaries": "^7.2.0",
73
73
  "knip": "^6.41.0"
74
74
  },
75
- "gitHead": "a09166687dccfad2f880d3f299812d5d9fd04de6"
75
+ "gitHead": "0dab46d135df7aac0fa7c5155a47ed19ab185740"
76
76
  }
@@ -691,7 +691,12 @@ or 3. Then the merge command, code 4: the merge stays a separate `gh pr merge
691
691
  into a batch — code 0, nothing more (the release does it); otherwise
692
692
  `ci-wait merged`, the refresh's mechanics and its prompt (code 4 — the
693
693
  subagent), and `task close` once its report is on the epic (no epic or no
694
- other open tasks — right away). Code 5 — out of time: the same command
694
+ other open tasks — right away). A task reopened after its merge (#813): an
695
+ open PR of the task or the checkout's task branch with commits not in the
696
+ base (`git cherry`; the merged PR's own branch — commits past its pushed
697
+ head) is the tail, not the merged PR — the latest merged PR is the one
698
+ awaited after the merge; closed with such work — reopened and «In progress»
699
+ (not planned — code 1 with `gh issue reopen`). Code 5 — out of time: the same command
695
700
  again. A session runs it in the background — once before the merge and once
696
701
  after; a subagent — `--timeout 240` (540 with the hour cache,
697
702
  `docs/pr-checks.md`), again on code 5. The separate commands stay for manual
@@ -936,9 +941,21 @@ it removes what finished executors left (#515): an agent's worktree
936
941
  (`.claude/worktrees/agent-*`) detached or on a `worktree-agent-*` branch, not
937
942
  locked by a live process (Claude Code locks a running agent's worktree; a lock
938
943
  whose pid is gone doesn't hold), clean and without commits outside
939
- `origin/<base>` by `git cherry` — removed with its branch, a `+` line;
940
- uncommitted changes or unmerged commits — left, an `○` line with the reason; a
941
- `worktree-agent-*` branch without a worktree — the same by its commits. A
944
+ `origin/<base>` by `git cherry`, or clean with its HEAD in a merged PR of its
945
+ closed task — removed with its branch, a `+` line; uncommitted changes or
946
+ unmerged commits — left, an `○` line with the reason; a `worktree-agent-*`
947
+ branch without a worktree — the same by its commits (`git cherry`). "Merged by
948
+ the PR" (#816): a batch's release rebases the batch onto a fresh
949
+ `origin/<base>`, a task's commit reaches it rewritten twice and differs there by
950
+ context — `git cherry` counts it unmerged, and the executors' worktrees piled
951
+ up with each batch. For a clean worktree `git cherry` counts unmerged, the
952
+ queue asks GitHub for the PRs of its HEAD (`commits/<sha>/pulls`): one counts
953
+ when it is merged, its head is the HEAD or a descendant of it (a commit a
954
+ force-push dropped from the PR doesn't count), its tasks are closed and its
955
+ base is the default branch or a batch branch its merged release PR shipped; a
956
+ commit on top of the PR's head, no such PR, or GitHub not read — `git cherry`
957
+ decides, as before. The `+` line names the PR (`its HEAD is in PR #77 merged
958
+ into batch/… (released by PR #80), #47 closed`). A
942
959
  session's worktree, an agent's on an open task's branch and an executor's whose
943
960
  handed-out task is open or awaits `task close` after its merge — untouched,
944
961
  no line (#533, #769); an agent's on a closed
@@ -1039,8 +1056,18 @@ machine's executors in subagents and 5 cloud sessions at once, the owner's
1039
1056
  number replaces either (subagents share the machine: `Next:` names the
1040
1057
  executors of its capacity — `slot --capacity`, `machine.json` or the cores and
1041
1058
  memory, without the slot skill — 3; a cloud session has its own container); a task in work (`=`) isn't launched again.
1042
- Before each launch — `get_usage`: the 5-hour limit at 85% and more — no new
1043
- executors, the running ones finish, then `Remaining: N tasks, the limit`. An
1059
+ Before each launch — `get_usage` (#815): a window of `plan.windows` at 85% and
1060
+ more — any but the window of a model the executors don't run on (`Weekly ·
1061
+ <model>`; theirs — the dispatcher's own unless the launch names another) — no
1062
+ new executors, the running ones finish, then `Remaining: N tasks, the limit:
1063
+ <its label> <percent>%, extra usage <percent>% of <monthly limit>` (or `extra
1064
+ usage off`). Extra usage doesn't lift the stop: money past the plan is the
1065
+ owner's decision; after the owner's «yes» to it — launches until
1066
+ `plan.extraUsage.percentUsed` is at 85%, then `Remaining: N tasks, the limit:
1067
+ extra usage <percent>%`. `not_applicable` (an API key, Bedrock, Vertex, a
1068
+ gateway) — no plan limits: executors by the machine's capacity; `unavailable`
1069
+ — asked again if its note says that helps, otherwise no new executors, the
1070
+ running ones finish, `Remaining: N tasks, limits unavailable`. An
1044
1071
  answer arrives as the subagent's notification; after each — `task queue`
1045
1072
  again. A question — to the owner in text; the answer — ✅ in the task's
1046
1073
  questions section and to the same executor with `SendMessage` (its context is
@@ -641,6 +641,7 @@ const M: Record<string, [field: string, inputType: string, select: string]> = {
641
641
  RemoveBlockedBy: ["removeBlockedBy", "RemoveBlockedByInput", "issue { id }"],
642
642
  SetIssueField: ["setIssueFieldValue", "SetIssueFieldValueInput", "issue { id }"],
643
643
  CloseIssue: ["closeIssue", "CloseIssueInput", "issue { id state }"],
644
+ ReopenIssue: ["reopenIssue", "ReopenIssueInput", "issue { id state }"],
644
645
  UpdateIssue: ["updateIssue", "UpdateIssueInput", "issue { id }"],
645
646
  AddComment: ["addComment", "AddCommentInput", "subject { id }"],
646
647
  CreateRuleset: ["createRepositoryRuleset", "CreateRepositoryRulesetInput", "ruleset { id }"],
@@ -3929,8 +3930,9 @@ function openOf(io: Io, slug: string): (n: number) => boolean {
3929
3930
  * Executors' worktrees go away with the dispatcher's next queue (#515): an executor can't remove its own — it works in it,
3930
3931
  * and `task close` leaves it detached on origin/<base>; its subagents leave theirs on `worktree-agent-*` branches.
3931
3932
  * Only agents' worktrees (`AGENT_WORKTREE`), detached or on a `worktree-agent-*` branch, not locked by a live process
3932
- * (a running agent): clean and without commits outside origin/<base> (`git cherry` — a rebase merge gives new SHAs) —
3933
- * removed with their branch, a `+` line each; uncommitted changes or unmerged commits — left, a `○` line with the
3933
+ * (a running agent): clean and without commits outside origin/<base> (`git cherry` — a rebase merge gives new SHAs), or
3934
+ * clean with its HEAD in a merged PR of its closed task (`mergedByPr`, #816: a batch's release rewrites the commits
3935
+ * past `git cherry`) — removed with their branch, a `+` line each; uncommitted changes or unmerged commits — left, a `○` line with the
3934
3936
  * reason. A `worktree-agent-*` branch without a worktree — the same by its commits. A session's worktree, an agent's on
3935
3937
  * a task branch of an open task (`closed` — #698: a closed one's goes with its branch, as above), an executor's whose handed-out task is open (`kept`, #533: Claude Code unlocks
3936
3938
  * an agent's worktree when it ends its answer — a question too — and doesn't lock it again when the agent is continued
@@ -3953,6 +3955,48 @@ function pruneAgentWorktrees(io: Io, slug: string, kept: (dir: string) => boolea
3953
3955
  const n = r.stdout.split("\n").filter((l) => l.startsWith("+")).length;
3954
3956
  return n ? `${plural(n, "commit", "commits")} not in ${upstream}` : null;
3955
3957
  };
3958
+ /** A batch branch's merged release PR (`releasePrOf`), read once per batch; not released or not read — null. */
3959
+ const releases = new Map<string, number | null>();
3960
+ const releasedBy = (batch: string): number | null => {
3961
+ if (!releases.has(batch)) {
3962
+ let pr: number | null = null;
3963
+ try {
3964
+ const release = releasePrOf(batchPrs(io, slug, batch), batch);
3965
+ pr = release?.merged ? release.number : null;
3966
+ } catch (e) {
3967
+ if (!(e instanceof GhError)) throw e;
3968
+ }
3969
+ releases.set(batch, pr);
3970
+ }
3971
+ return releases.get(batch)!;
3972
+ };
3973
+ /**
3974
+ * Merged by its PR (#816): a batch's release rebases the batch onto a fresh origin/<base>, and a task's commit reaches
3975
+ * the default branch rewritten twice — its patch differs there by context, and `git cherry` counts it unmerged. GitHub
3976
+ * names the PRs of a commit (`commits/<sha>/pulls`); one counts when it is merged, its head is the HEAD or a descendant
3977
+ * of it, its tasks are closed (`closed`), and its base is the default branch or a batch branch its merged release PR
3978
+ * shipped. The reason for the `+` line; none, or not read — null: `git cherry` decides.
3979
+ */
3980
+ const mergedByPr = (sha: string): string | null => {
3981
+ let pulls: Any[];
3982
+ try {
3983
+ pulls = rest(io, `repos/${slug}/commits/${sha}/pulls`) ?? [];
3984
+ } catch (e) {
3985
+ if (!(e instanceof GhError)) throw e;
3986
+ return null;
3987
+ }
3988
+ for (const p of pulls) {
3989
+ const r = prRef(p);
3990
+ const tasks = prTasks(p);
3991
+ if (!r.merged || !r.sha || !tasks.length || !tasks.every(closed)) continue;
3992
+ if (r.sha !== sha && git(io, io.cwd, "merge-base", "--is-ancestor", sha, r.sha).status !== 0) continue;
3993
+ const release = isBatchBranch(r.base) ? releasedBy(r.base) : null;
3994
+ if (r.base !== base && release === null) continue;
3995
+ const into = release === null ? r.base : `${r.base} (released by PR #${release})`;
3996
+ return `its HEAD is in PR #${r.number} merged into ${into}, ${tasks.map((n) => `#${n}`).join(", ")} closed`;
3997
+ }
3998
+ return null;
3999
+ };
3956
4000
  const deleteBranch = (branch: string) => {
3957
4001
  const d = git(io, io.cwd, "branch", "-D", branch);
3958
4002
  if (d.status !== 0) io.out(`! git branch -D ${branch}: ${why(d)}`);
@@ -3981,7 +4025,10 @@ function pruneAgentWorktrees(io: Io, slug: string, kept: (dir: string) => boolea
3981
4025
  continue;
3982
4026
  }
3983
4027
  const dirty = status.stdout.split("\n").filter((l) => l.trim()).length;
3984
- const reasons = [dirty ? `${plural(dirty, "uncommitted file", "uncommitted files")}` : null, unmerged(w.head)].filter((r): r is string => r !== null);
4028
+ const cherry = unmerged(w.head);
4029
+ // git cherry first — local; the PR only for a clean worktree it counts unmerged: the API call is for the doubt alone
4030
+ const byPr = !dirty && cherry !== null ? mergedByPr(w.head) : null;
4031
+ const reasons = [dirty ? `${plural(dirty, "uncommitted file", "uncommitted files")}` : null, byPr ? null : cherry].filter((r): r is string => r !== null);
3985
4032
  if (reasons.length) {
3986
4033
  io.out(`○ worktree ${w.path} left: ${reasons.join(", ")}`);
3987
4034
  continue;
@@ -3994,7 +4041,7 @@ function pruneAgentWorktrees(io: Io, slug: string, kept: (dir: string) => boolea
3994
4041
  continue;
3995
4042
  }
3996
4043
  const withBranch = w.branch !== null && deleteBranch(w.branch) ? ` with branch ${w.branch}` : "";
3997
- io.out(`+ worktree ${w.path} removed${withBranch}: clean, nothing outside ${upstream}`);
4044
+ io.out(`+ worktree ${w.path} removed${withBranch}: clean, ${byPr ?? `nothing outside ${upstream}`}`);
3998
4045
  }
3999
4046
  // a branch checked out anywhere — a locked worktree's included — isn't loose
4000
4047
  const checkedOut = new Set(all.map((w) => w.branch).filter(Boolean));
@@ -5029,7 +5076,19 @@ export function cmdTaskFinish(io: Io, slug: string, number: number, o: { timeout
5029
5076
  const issue = loadIssue(io, slug, number);
5030
5077
  if (issue.state !== "OPEN") {
5031
5078
  // «Closes #N» of the PR closes the task at the merge (#761): a closed issue isn't a finished tail — task close's marks are
5032
- const closer = issue.stateReason === "COMPLETED" ? (issue.prs.find((p) => p.merged && !isBatchBranch(p.base)) ?? null) : null;
5079
+ const closer = issue.stateReason === "COMPLETED" ? (lastMerged(issue.prs.filter((p) => !isBatchBranch(p.base))) ?? null) : null;
5080
+ // a task reopened after its merge (#813): its open PR or its branch's unmerged work is the tail, not the merged PR
5081
+ const work = workPastMerge(io, slug, number, issue, closer);
5082
+ if (work) {
5083
+ if (issue.stateReason !== "COMPLETED") return stop(1, `! #${number} is closed as ${issue.stateReason ?? "not planned"}, but ${work}`, `gh issue reopen ${number} --repo ${slug}, then ${again}`);
5084
+ mutate(io, { op: "ReopenIssue", input: { issueId: issue.id } });
5085
+ if (!inCloud(io)) {
5086
+ const ctx = taskContext(io, slug);
5087
+ setStatus(io, ctx, ensureItem(io, ctx, issue).id, N.status.inProgress);
5088
+ }
5089
+ io.out(`+ #${number} reopened, ${STATUS} ${q(N.status.inProgress)}: ${work} — the task's merged PR isn't its finish`);
5090
+ return cmdTaskFinish(io, slug, number, { ...o, timeout: Math.max(0, left()) });
5091
+ }
5033
5092
  if (!closer || tailOver(io, slug, number)) return io.out(`= #${number} is closed — nothing to finish`), 0;
5034
5093
  io.out(`○ #${number} is closed by the merge of PR #${closer.number}, the tail isn't over (no ${q(N.status.done)} with the actual) — going on`);
5035
5094
  return finishMerged(io, slug, number, issue.parent?.number ?? null, closer, { left, again, stop, outOfTime });
@@ -5037,8 +5096,11 @@ export function cmdTaskFinish(io: Io, slug: string, number: number, o: { timeout
5037
5096
  if (!checkoutOfRepo(io, originUrl(io), slug)) throw new GhError(`task finish runs from a checkout of ${slug}: the current directory is not one`);
5038
5097
  const found = unlinkedPrs(io, slug, number);
5039
5098
  const prs = [...issue.prs, ...found.prs, ...found.batched].filter((p, k, all) => all.findIndex((x) => x.number === p.number) === k);
5040
- const merged = prs.find((p) => p.merged);
5041
- if (merged) return finishMerged(io, slug, number, issue.parent?.number ?? null, merged, { left, again, stop, outOfTime });
5099
+ // the latest merged PR is the task's finish only without an open PR and without unmerged work on its branch (#813):
5100
+ // a task reopened after the merge goes on with its new branch — its push, its PR, its merge
5101
+ const merged = lastMerged(prs);
5102
+ const pending = prs.some((p) => p.state === "OPEN") || (merged && unmergedBranch(io, number, merged.base, merged.head));
5103
+ if (merged && !pending) return finishMerged(io, slug, number, issue.parent?.number ?? null, merged, { left, again, stop, outOfTime });
5042
5104
 
5043
5105
  const branch = git(io, io.cwd, "branch", "--show-current").stdout.trim();
5044
5106
  const open = prs.find((p) => p.state === "OPEN");
@@ -5103,6 +5165,43 @@ export function cmdTaskFinish(io: Io, slug: string, number: number, o: { timeout
5103
5165
  return stop(4, `✅ PR #${pr} is ready to merge`, `${yes}gh pr merge ${pr} --rebase — a separate call, no cd or pipeline (the owner's permission rule matches it); then ${again}${isBatchBranch(base) ? "" : " — in the background: it waits for the deploy"}`);
5104
5166
  }
5105
5167
 
5168
+ /** The task's latest merged PR — the highest number: a task reopened after a merge has several (#813). */
5169
+ function lastMerged<T extends { number: number; merged: boolean }>(prs: T[]): T | undefined {
5170
+ return prs.filter((p) => p.merged).sort((a, b) => b.number - a.number)[0];
5171
+ }
5172
+
5173
+ /**
5174
+ * The checkout's branch of the task with commits that aren't in `origin/<base>` by their changes (`git cherry`: a
5175
+ * rebase merge gives other SHAs) — the work of a task reopened after its merge (#813); none — null. The merged PR's own
5176
+ * branch — by the commits past its pushed head while it is on origin: a squash merge has no commit-for-commit match.
5177
+ */
5178
+ function unmergedBranch(io: Io, number: number, base: string, mergedHead?: string): string | null {
5179
+ const branch = git(io, io.cwd, "branch", "--show-current").stdout.trim();
5180
+ if (!isTaskBranch(branch, number)) return null;
5181
+ if (branch === mergedHead) {
5182
+ git(io, io.cwd, "fetch", "-q", "origin", `+refs/heads/${branch}:refs/remotes/origin/${branch}`);
5183
+ const past = git(io, io.cwd, "rev-list", "--count", `refs/remotes/origin/${branch}..HEAD`);
5184
+ if (past.status === 0) return Number(past.stdout.trim()) > 0 ? branch : null;
5185
+ }
5186
+ if (git(io, io.cwd, "fetch", "-q", "origin", `+refs/heads/${base}:refs/remotes/origin/${base}`).status !== 0) return null;
5187
+ const cherry = git(io, io.cwd, "cherry", `origin/${base}`, "HEAD");
5188
+ return cherry.status === 0 && cherry.stdout.split("\n").some((l) => l.startsWith("+")) ? branch : null;
5189
+ }
5190
+
5191
+ /**
5192
+ * What a closed task still has after its merged PR (#813): an open PR of the task, or the checkout's task branch with
5193
+ * work its base hasn't got. Nothing — null; the checkout isn't the repository's — only the PR counts.
5194
+ */
5195
+ function workPastMerge(io: Io, slug: string, number: number, issue: Issue, closer: Issue["prs"][number] | null): string | null {
5196
+ const open = issue.prs.find((p) => p.state === "OPEN");
5197
+ if (open) return `its PR #${open.number} is open`;
5198
+ const current = git(io, io.cwd, "branch", "--show-current").stdout.trim();
5199
+ if (!isTaskBranch(current, number) || !checkoutOfRepo(io, originUrl(io), slug)) return null;
5200
+ const base = closer?.base ?? unlinkedPrs(io, slug, number).base;
5201
+ const branch = unmergedBranch(io, number, base, closer?.head);
5202
+ return branch ? `branch ${branch} has commits that aren't in origin/${base}` : null;
5203
+ }
5204
+
5106
5205
  /**
5107
5206
  * The base of the task's new PR: the dispatcher's batch branch (#648); a task past the batch (#697) — the default branch,
5108
5207
  * as outside a batch; the batch released (#768: its release PR merged, or its branch gone from origin) — the default
@@ -6536,7 +6635,7 @@ label's — from the latest «External blocker: …» comment). Marks the sessio
6536
6635
  with the session's id; a session with a pinned task keeps it. Before the queue, in the repository's checkout —
6537
6636
  finished agents' worktrees (.claude/worktrees/agent-*, detached or on worktree-agent-*, not locked by a live process,
6538
6637
  not an executor's whose handed-out task is open; on a task branch — when its task is closed): clean and merged (git
6539
- cherry) — removed with the branch (+),
6638
+ cherry, or its HEAD in a merged PR of its closed task into the default branch or a released batch) — removed with the branch (+),
6540
6639
  otherwise left (○ with the reason), and so is one a subagent works in without a worktree of its own (its transcript
6541
6640
  written in the last ${QUIET_MINUTES} min); loose worktree-agent-* branches — the same. --type and --priority — in an
6542
6641
  organization. --assignment N (the executor's first call; read-only on GitHub) — its whole assignment; in a session