@miroshnik/elves 2026.1026.4 → 2026.1027.0

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.
@@ -78,8 +78,8 @@ function fieldAliases() {
78
78
  }
79
79
  var BUILTIN_FIELDS = new Set(["TITLE", "ASSIGNEES", "LABELS", "LINKED_PULL_REQUESTS", "MILESTONE", "REPOSITORY", "REVIEWERS", "PARENT_ISSUE", "SUB_ISSUES_PROGRESS", "CREATED", "UPDATED", "CLOSED", "TRACKS", "TRACKED_BY", "ISSUE_TYPE"]);
80
80
  var NOT_DONE_REASONS = new Set(["NOT_PLANNED", "DUPLICATE"]);
81
- function realRun(cmd, args, cwd) {
82
- const r = spawnSync(cmd, args, { cwd, encoding: "utf8", maxBuffer: 64 * 1024 * 1024 });
81
+ function realRun(cmd, args, cwd, env) {
82
+ const r = spawnSync(cmd, args, { cwd, encoding: "utf8", maxBuffer: 64 * 1024 * 1024, ...env ? { env: { ...process.env, ...env } } : {} });
83
83
  return { status: r.error ? null : r.status, stdout: r.stdout ?? "", stderr: r.error ? String(r.error.message) : r.stderr ?? "" };
84
84
  }
85
85
  function git(io, cwd, ...args) {
@@ -1912,6 +1912,10 @@ function cmdTaskShow(io, slug, number) {
1912
1912
  io.out(line);
1913
1913
  return 0;
1914
1914
  }
1915
+ function itemValues(i, name) {
1916
+ const items = i?.projectItems?.nodes ?? [];
1917
+ return (items.find((it) => it.project?.title === name) ?? items[0])?.fieldValues?.nodes ?? [];
1918
+ }
1915
1919
  function showTask(io, slug, number) {
1916
1920
  const [owner, name] = slug.split("/");
1917
1921
  const cloud = inCloud(io);
@@ -1922,7 +1926,7 @@ function showTask(io, slug, number) {
1922
1926
  const type = i.issueType?.name ?? (labels.includes(EPIC_LABEL) ? N.issueTypes.epic : null);
1923
1927
  const epic = type !== null && locale_default.every((n) => n.issueTypes.epic).includes(type);
1924
1928
  const items = i.projectItems?.nodes ?? [];
1925
- const values = (items.find((it) => it.project?.title === name) ?? items[0])?.fieldValues?.nodes ?? [];
1929
+ const values = itemValues(i, name);
1926
1930
  const num = (field) => values.find((v) => v?.__typename === "ProjectV2ItemFieldNumberValue" && locale_default.every(field).includes(v.field?.name));
1927
1931
  const status = values.find((v) => v?.field?.name === STATUS && v.name)?.name ?? null;
1928
1932
  const estimate = num((n) => n.fields.estimate);
@@ -3573,8 +3577,13 @@ function cmdTaskFinish(io, slug, number, o) {
3573
3577
  const stop = (code, why, next) => (io.out(why), io.out(`Next: ${next}`), code);
3574
3578
  const outOfTime = (what) => stop(5, `○ out of time (--timeout ${o.timeout}) — ${what}`, `${again} — it goes on from here`);
3575
3579
  const issue = loadIssue(io, slug, number);
3576
- if (issue.state !== "OPEN")
3577
- return io.out(`= #${number} is closed — nothing to finish`), 0;
3580
+ if (issue.state !== "OPEN") {
3581
+ const closer = issue.stateReason === "COMPLETED" ? issue.prs.find((p) => p.merged && !isBatchBranch(p.base)) ?? null : null;
3582
+ if (!closer || tailOver(io, slug, number))
3583
+ return io.out(`= #${number} is closed — nothing to finish`), 0;
3584
+ 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`);
3585
+ return finishMerged(io, slug, number, issue.parent?.number ?? null, closer, { left, again, stop, outOfTime });
3586
+ }
3578
3587
  if (!checkoutOfRepo(io, originUrl(io), slug))
3579
3588
  throw new GhError(`task finish runs from a checkout of ${slug}: the current directory is not one`);
3580
3589
  const found = unlinkedPrs(io, slug, number);
@@ -3652,6 +3661,15 @@ function cmdTaskFinish(io, slug, number, o) {
3652
3661
  const yes = locale_default.autoProject(io.cwd ?? process.cwd()) ? "" : "the owner's «yes» (the project is without auto) — then ";
3653
3662
  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"}`);
3654
3663
  }
3664
+ function tailOver(io, slug, number) {
3665
+ if (inCloud(io))
3666
+ return true;
3667
+ const [owner, name] = slug.split("/");
3668
+ const values = itemValues(graphql(io, Q.IssueShow, { owner, name, number })?.repository?.issue, name);
3669
+ const done = values.some((v) => v?.field?.name === STATUS && locale_default.every((n) => n.status.done).includes(v.name));
3670
+ const actual = values.some((v) => v?.__typename === "ProjectV2ItemFieldNumberValue" && locale_default.every((n) => n.fields.actual).includes(v.field?.name));
3671
+ return done && actual;
3672
+ }
3655
3673
  function finishMerged(io, slug, number, epicNumber, merged, f) {
3656
3674
  if (isBatchBranch(merged.base)) {
3657
3675
  io.out(`✅ PR #${merged.number} is merged into ${merged.base} — #${number} stays ${q(N.status.inProgress)} till the batch's release`);
@@ -4152,6 +4170,8 @@ function missingPrLabels(io, slug, number) {
4152
4170
  return out;
4153
4171
  }
4154
4172
  var PREMERGE_SCRIPTS = ["typecheck", "test:spec"];
4173
+ var STACK_TASK_VAR = "ELVES_TASK";
4174
+ var STACK_FAILED_VAR = "ELVES_TASK_ENV_FAILED";
4155
4175
  var SPEC_ROOTS = ["tests/standards", "tests/architecture"];
4156
4176
  var specRoots = (dir) => SPEC_ROOTS.filter((d) => statSync(path.join(dir, d), { throwIfNoEntry: false })?.isDirectory());
4157
4177
  var MERGE_REF_SLACK_MS = 60000;
@@ -4194,7 +4214,7 @@ function scriptsOf(dir) {
4194
4214
  const pkg = path.join(dir, "package.json");
4195
4215
  return existsSync(pkg) ? JSON.parse(readFileSync(pkg, "utf8")).scripts ?? {} : {};
4196
4216
  }
4197
- function checkTree(io, dir, steps) {
4217
+ function checkTree(io, dir, steps, env) {
4198
4218
  const run = io.run ?? realRun;
4199
4219
  const cmds = projectCommands(dir);
4200
4220
  const install = cmds.install ? { cmd: cmds.install.join(" "), result: run(cmds.install[0], cmds.install.slice(1), dir) } : null;
@@ -4204,7 +4224,7 @@ function checkTree(io, dir, steps) {
4204
4224
  for (const s of steps) {
4205
4225
  const args = s.args ?? [];
4206
4226
  const argv = [...cmds.run(s.script), ...args.length && packageManager(dir).name === "npm" ? ["--"] : [], ...args];
4207
- const result = run(argv[0], argv.slice(1), dir);
4227
+ const result = env ? run(argv[0], argv.slice(1), dir, env) : run(argv[0], argv.slice(1), dir);
4208
4228
  ran.push(s.script);
4209
4229
  if (result.status !== 0)
4210
4230
  return { install, ran, red: { script: s.script, cmd: argv.join(" "), result } };
@@ -4476,12 +4496,22 @@ function cmdPrPremerge(io, slug, number) {
4476
4496
  io.out(`${base} moved on past the head of PR #${number} (origin/${base} — ${tip.slice(0, 7) || "not read"}) — checking the merge with origin/${base}`);
4477
4497
  }
4478
4498
  const ON_MERGE = "on the merge";
4499
+ const task = taskBranch(String(pr.head?.ref ?? ""))?.issue;
4500
+ const failedFile = path.join(mkdtempSync(path.join(os.tmpdir(), "elves-premerge-stack-")), "failed");
4501
+ const stackEnv = { [STACK_FAILED_VAR]: failedFile, ...task ? { [STACK_TASK_VAR]: String(task) } : {} };
4502
+ const stackFailed = () => existsSync(failedFile) ? readFileSync(failedFile, "utf8").split(`
4503
+ `).filter(Boolean) : null;
4504
+ const unchecked = (where, script, lines) => {
4505
+ io.out(`❌ couldn't check: the stack of ${task ? `task #${task}` : "the PR's task (its branch has no task number)"} didn't come up for ${script} ${where} — ${lines.join("; ")}`);
4506
+ io.out(`the red ${script} isn't counted against ${base} or the PR: bring the stack up (task-env up${task ? ` ${task}` : " <N>"}) and pr premerge ${number} again`);
4507
+ return 2;
4508
+ };
4479
4509
  const checks = (dir, where, scripts) => {
4480
4510
  const defined = scriptsOf(dir);
4481
4511
  const present = scripts.filter((s) => defined[s]);
4482
4512
  if (!present.length)
4483
4513
  return null;
4484
- const { install, ran, red } = checkTree(io, dir, present.map((script) => ({ script })));
4514
+ const { install, ran, red } = checkTree(io, dir, present.map((script) => ({ script })), stackEnv);
4485
4515
  if (install) {
4486
4516
  if (install.result.status !== 0)
4487
4517
  throw new GhError(`installing dependencies ${where} failed (${install.cmd}): ${tail(install.result, 5).join(" / ")}`);
@@ -4495,57 +4525,67 @@ ${red.result.stderr}`).split(`
4495
4525
  return { ran, red: { ...red, failed } };
4496
4526
  };
4497
4527
  const breaks = (script) => `❌ don't merge: ${script} is red on the merge with origin/${base} — fix the root cause in the PR: rebase onto origin/${base}, edit, push --force-with-lease, ${recheck}`;
4498
- return inTempWorktree(io, "premerge", `origin/${base}`, (dir) => {
4499
- const short = (ref) => git(io, dir, "rev-parse", "--short=7", ref).stdout.trim();
4500
- const merge = git(io, dir, "-c", "user.name=elves", "-c", "user.email=elves@localhost", "-c", "commit.gpgsign=false", "merge", "-q", "--no-ff", "--no-verify", "--no-edit", head);
4501
- if (merge.status !== 0) {
4502
- const files = git(io, dir, "diff", "--name-only", "--diff-filter=U").stdout.split(`
4528
+ try {
4529
+ return inTempWorktree(io, "premerge", `origin/${base}`, (dir) => {
4530
+ const short = (ref) => git(io, dir, "rev-parse", "--short=7", ref).stdout.trim();
4531
+ const merge = git(io, dir, "-c", "user.name=elves", "-c", "user.email=elves@localhost", "-c", "commit.gpgsign=false", "merge", "-q", "--no-ff", "--no-verify", "--no-edit", head);
4532
+ if (merge.status !== 0) {
4533
+ const files = git(io, dir, "diff", "--name-only", "--diff-filter=U").stdout.split(`
4503
4534
  `).filter(Boolean);
4504
- if (!files.length)
4505
- throw new GhError(`git merge: ${merge.stderr.trim()}`);
4506
- io.out(`❌ don't merge: a merge conflict with origin/${base} — ${files.join(", ")}; rebase onto origin/${base}, push --force-with-lease, ${recheck}`);
4507
- return 1;
4508
- }
4509
- io.out(`+ merge of ${head.slice(0, 7)} with origin/${base} ${short("HEAD^1")} — no conflicts`);
4510
- const roots = specRoots(dir);
4511
- if (roots.length && !scriptsOf(dir)["test:spec"])
4512
- io.out(`○ ${roots.join(", ")} aren't checked on the merge: the merge's package.json has no test:spec script — the project's check names the line to add (bunx github:miroshnik/elves check)`);
4513
- const merged = checks(dir, ON_MERGE, PREMERGE_SCRIPTS);
4514
- if (!merged) {
4515
- io.out(`○ no fast checks: the merge's package.json has no ${PREMERGE_SCRIPTS.join(" or ")} scripts — step skipped`);
4516
- io.out(`✅ merge: the merge with origin/${base} has no conflicts`);
4517
- return 0;
4518
- }
4519
- const red = merged.red;
4520
- if (!red) {
4521
- io.out(`✅ merge: ${merged.ran.join(" and ")} ${merged.ran.length > 1 ? "are" : "is"} green on the merge with origin/${base}`);
4522
- return 0;
4523
- }
4524
- io.out(`${red.cmd} failed:`);
4525
- for (const l of red.failed.length ? red.failed.slice(0, 20) : tail(red.result))
4526
- io.out(` ${l.trim()}`);
4527
- io.out(`checking bare origin/${base}: is it red by itself`);
4528
- const bare = inTempWorktree(io, "premerge", `origin/${base}`, (bareDir) => checks(bareDir, `on origin/${base}`, [red.script])?.red);
4529
- if (!bare) {
4530
- io.out(breaks(red.script));
4531
- return 1;
4532
- }
4533
- const onMain = new Set(bare.failed.map(failure));
4534
- const own = red.failed.filter((l) => !onMain.has(failure(l)));
4535
- if (own.length && bare.failed.length) {
4536
- io.out(`${base} is red by itself, the PR breaks beyond it:`);
4537
- for (const l of own.slice(0, 20))
4538
- io.out(` ${l}`);
4535
+ if (!files.length)
4536
+ throw new GhError(`git merge: ${merge.stderr.trim()}`);
4537
+ io.out(`❌ don't merge: a merge conflict with origin/${base} — ${files.join(", ")}; rebase onto origin/${base}, push --force-with-lease, ${recheck}`);
4538
+ return 1;
4539
+ }
4540
+ io.out(`+ merge of ${head.slice(0, 7)} with origin/${base} ${short("HEAD^1")} — no conflicts`);
4541
+ const roots = specRoots(dir);
4542
+ if (roots.length && !scriptsOf(dir)["test:spec"])
4543
+ io.out(`○ ${roots.join(", ")} aren't checked on the merge: the merge's package.json has no test:spec script — the project's check names the line to add (bunx github:miroshnik/elves check)`);
4544
+ const merged = checks(dir, ON_MERGE, PREMERGE_SCRIPTS);
4545
+ if (!merged) {
4546
+ io.out(`○ no fast checks: the merge's package.json has no ${PREMERGE_SCRIPTS.join(" or ")} scripts — step skipped`);
4547
+ io.out(`✅ merge: the merge with origin/${base} has no conflicts`);
4548
+ return 0;
4549
+ }
4550
+ const red = merged.red;
4551
+ if (!red) {
4552
+ io.out(`✅ merge: ${merged.ran.join(" and ")} ${merged.ran.length > 1 ? "are" : "is"} green on the merge with origin/${base}`);
4553
+ return 0;
4554
+ }
4555
+ io.out(`${red.cmd} failed:`);
4556
+ for (const l of red.failed.length ? red.failed.slice(0, 20) : tail(red.result))
4557
+ io.out(` ${l.trim()}`);
4558
+ const down = stackFailed();
4559
+ if (down)
4560
+ return unchecked(ON_MERGE, red.script, down);
4561
+ io.out(`checking bare origin/${base}: is it red by itself`);
4562
+ const bare = inTempWorktree(io, "premerge", `origin/${base}`, (bareDir) => checks(bareDir, `on origin/${base}`, [red.script])?.red);
4563
+ const bareDown = stackFailed();
4564
+ if (bareDown)
4565
+ return unchecked(`on origin/${base}`, red.script, bareDown);
4566
+ if (!bare) {
4567
+ io.out(breaks(red.script));
4568
+ return 1;
4569
+ }
4570
+ const onMain = new Set(bare.failed.map(failure));
4571
+ const own = red.failed.filter((l) => !onMain.has(failure(l)));
4572
+ if (own.length && bare.failed.length) {
4573
+ io.out(`${base} is red by itself, the PR breaks beyond it:`);
4574
+ for (const l of own.slice(0, 20))
4575
+ io.out(` ${l}`);
4576
+ io.out(breaks(red.script));
4577
+ return 1;
4578
+ }
4579
+ const reason = `${red.script} is red on bare origin/${base} too, with the same failures`;
4580
+ const code = mainRed(`${base} is red by itself: ${reason}`, reason, git(io, dir, "rev-parse", `origin/${base}`).stdout.trim(), [red.script], (names) => names.join(", "));
4581
+ if (code !== null)
4582
+ return code;
4539
4583
  io.out(breaks(red.script));
4540
4584
  return 1;
4541
- }
4542
- const reason = `${red.script} is red on bare origin/${base} too, with the same failures`;
4543
- const code = mainRed(`${base} is red by itself: ${reason}`, reason, git(io, dir, "rev-parse", `origin/${base}`).stdout.trim(), [red.script], (names) => names.join(", "));
4544
- if (code !== null)
4545
- return code;
4546
- io.out(breaks(red.script));
4547
- return 1;
4548
- });
4585
+ });
4586
+ } finally {
4587
+ rmSync(path.dirname(failedFile), { recursive: true, force: true });
4588
+ }
4549
4589
  }
4550
4590
  var HELP = {
4551
4591
  "project check": `github project check [--repo owner/repo]
@@ -4794,8 +4834,9 @@ Examples:
4794
4834
 
4795
4835
  Before gh pr merge, after ci-wait PASS: the default branch moved after the PR's CI — the PR head merged with it in a
4796
4836
  temporary worktree and ${PREMERGE_SCRIPTS.join(", then ")} from package.json (those that exist, as in CI). Code 0 —
4797
- merge, 1 — don't merge (red, conflict), 2 — couldn't check, 3 — main is red by itself (the same check on bare main, a
4798
- red check on its last commit): don't merge, one bug for it — wait for it to close. A PR into a batch branch runs no
4837
+ merge, 1 — don't merge (red, conflict), 2 — couldn't check (the stack of the PR's task didn't come up: the checks get
4838
+ ELVES_TASK — the number of the PR's branch — for task-env up on the detached HEAD), 3 — main is red by itself (the same
4839
+ check on bare main, a red check on its last commit): don't merge, one bug for it — wait for it to close. A PR into a batch branch runs no
4799
4840
  CI, so no ci-wait before it: the head on a fresh origin/<batch> — code 0 without checks (the checks before a commit
4800
4841
  checked this tree), the batch moved on — the fast checks on the merge with it. The
4801
4842
  batch's release PR open — code 1 and the wait for its close, but red with the PR of one of its tasks — the guilty task's
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@miroshnik/elves",
3
- "version": "2026.1026.4",
3
+ "version": "2026.1027.0",
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": "79d15cd5bf6ff9cf0b270485b6d115fd53079110"
75
+ "gitHead": "c8aefea287e10052ba441d63042d2981c1e025f5"
76
76
  }
@@ -184,8 +184,11 @@ export interface Io {
184
184
  env: Record<string, string | undefined>;
185
185
  /** A pause before re-reading (GitHub doesn't show additions right away); in tests — no waiting. */
186
186
  sleep?: (ms: number) => void;
187
- /** A subprocess (`est`, `git` of `task close`) — an external edge: replaced in tests. */
188
- run?: (cmd: string, args: string[], cwd?: string) => RunResult;
187
+ /**
188
+ * A subprocess (`est`, `git` of `task close`) — an external edge: replaced in tests; `env` — variables on top of the
189
+ * process's.
190
+ */
191
+ run?: (cmd: string, args: string[], cwd?: string, env?: Record<string, string>) => RunResult;
189
192
  /**
190
193
  * The project checkout: its language (`.agents/elves.json`) is the language of names, `task close` runs its git
191
194
  * steps in it; the current directory by default.
@@ -199,8 +202,8 @@ export interface RunResult {
199
202
  stderr: string;
200
203
  }
201
204
 
202
- export function realRun(cmd: string, args: string[], cwd?: string): RunResult {
203
- const r = spawnSync(cmd, args, { cwd, encoding: "utf8", maxBuffer: 64 * 1024 * 1024 });
205
+ export function realRun(cmd: string, args: string[], cwd?: string, env?: Record<string, string>): RunResult {
206
+ const r = spawnSync(cmd, args, { cwd, encoding: "utf8", maxBuffer: 64 * 1024 * 1024, ...(env ? { env: { ...process.env, ...env } } : {}) });
204
207
  return { status: r.error ? null : r.status, stdout: r.stdout ?? "", stderr: r.error ? String(r.error.message) : (r.stderr ?? "") };
205
208
  }
206
209
 
@@ -2675,6 +2678,12 @@ interface ShownTask {
2675
2678
  prs: ShownPr[];
2676
2679
  }
2677
2680
 
2681
+ /** The field values of the task's item in the repository's project (IssueShow) — or of its first item. */
2682
+ function itemValues(i: Any, name: string): Any[] {
2683
+ const items: Any[] = i?.projectItems?.nodes ?? [];
2684
+ return (items.find((it) => it.project?.title === name) ?? items[0])?.fieldValues?.nodes ?? [];
2685
+ }
2686
+
2678
2687
  function showTask(io: Io, slug: string, number: number): ShownTask {
2679
2688
  const [owner, name] = slug.split("/");
2680
2689
  const cloud = inCloud(io);
@@ -2685,7 +2694,7 @@ function showTask(io: Io, slug: string, number: number): ShownTask {
2685
2694
  const type: string | null = i.issueType?.name ?? (labels.includes(EPIC_LABEL) ? N.issueTypes.epic : null);
2686
2695
  const epic = type !== null && locale.every((n) => n.issueTypes.epic).includes(type);
2687
2696
  const items: Any[] = i.projectItems?.nodes ?? [];
2688
- const values: Any[] = (items.find((it) => it.project?.title === name) ?? items[0])?.fieldValues?.nodes ?? [];
2697
+ const values = itemValues(i, name!);
2689
2698
  const num = (field: (n: Names) => string) => values.find((v) => v?.__typename === "ProjectV2ItemFieldNumberValue" && locale.every(field).includes(v.field?.name));
2690
2699
  const status: string | null = values.find((v) => v?.field?.name === STATUS && v.name)?.name ?? null;
2691
2700
  const estimate = num((n) => n.fields.estimate);
@@ -4898,7 +4907,8 @@ function pushTaskBranch(io: Io, branch: string): string | null {
4898
4907
  * `--title`, otherwise the branch type's first commit; the body — spec-diff and `Closes #N`; an existing PR — its body
4899
4908
  * updated), decision labels (`pr labels`), the CI wait (ci-wait), `pr premerge` — then the merge command, code 4: the
4900
4909
  * merge stays a separate `gh pr merge <N> --rebase` call — the owner's permission rule in auto mode matches it
4901
- * (claude/CLAUDE.md). After the merge: the deploy wait on the merge SHA, the epic refresh's mechanics and its subagent's
4910
+ * (claude/CLAUDE.md). After the merge (the task is open or already closed by «Closes #N» — the tail is over only by
4911
+ * `task close`'s Status Done and actual, #761): the deploy wait on the merge SHA, the epic refresh's mechanics and its subagent's
4902
4912
  * prompt (code 4), `task close` once its report is on the epic. A PR into a batch branch (#676): no CI to wait for, and
4903
4913
  * after its merge — nothing, the release does the rest. Codes: 0 — finished (closed; merged into a batch), 1 — stopped
4904
4914
  * on something to fix (red CI, a conflict, a push refused, premerge red), 3 — the base is red (premerge), 4 — the agent's
@@ -4911,7 +4921,13 @@ export function cmdTaskFinish(io: Io, slug: string, number: number, o: { timeout
4911
4921
  const stop = (code: number, why: string, next: string) => (io.out(why), io.out(`Next: ${next}`), code);
4912
4922
  const outOfTime = (what: string) => stop(5, `○ out of time (--timeout ${o.timeout}) — ${what}`, `${again} — it goes on from here`);
4913
4923
  const issue = loadIssue(io, slug, number);
4914
- if (issue.state !== "OPEN") return io.out(`= #${number} is closed — nothing to finish`), 0;
4924
+ if (issue.state !== "OPEN") {
4925
+ // «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
4926
+ const closer = issue.stateReason === "COMPLETED" ? (issue.prs.find((p) => p.merged && !isBatchBranch(p.base)) ?? null) : null;
4927
+ if (!closer || tailOver(io, slug, number)) return io.out(`= #${number} is closed — nothing to finish`), 0;
4928
+ 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`);
4929
+ return finishMerged(io, slug, number, issue.parent?.number ?? null, closer, { left, again, stop, outOfTime });
4930
+ }
4915
4931
  if (!checkoutOfRepo(io, originUrl(io), slug)) throw new GhError(`task finish runs from a checkout of ${slug}: the current directory is not one`);
4916
4932
  const found = unlinkedPrs(io, slug, number);
4917
4933
  const prs = [...issue.prs, ...found.prs, ...found.batched].filter((p, k, all) => all.findIndex((x) => x.number === p.number) === k);
@@ -4972,6 +4988,19 @@ export function cmdTaskFinish(io: Io, slug: string, number: number, o: { timeout
4972
4988
  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"}`);
4973
4989
  }
4974
4990
 
4991
+ /**
4992
+ * The tail is over — what `task close` leaves (#761, question 1): Status Done and the actual written, not the issue's
4993
+ * state, which «Closes #N» sets at the merge. In the cloud there is no project to read — over, as before.
4994
+ */
4995
+ function tailOver(io: Io, slug: string, number: number): boolean {
4996
+ if (inCloud(io)) return true;
4997
+ const [owner, name] = slug.split("/");
4998
+ const values = itemValues(graphql(io, Q.IssueShow, { owner, name, number })?.repository?.issue, name!);
4999
+ const done = values.some((v) => v?.field?.name === STATUS && locale.every((n) => n.status.done).includes(v.name));
5000
+ const actual = values.some((v) => v?.__typename === "ProjectV2ItemFieldNumberValue" && locale.every((n) => n.fields.actual).includes(v.field?.name));
5001
+ return done && actual;
5002
+ }
5003
+
4975
5004
  /** `task finish` after the merge: the batch's — nothing; the default branch's — the deploy, the epic refresh, `task close`. */
4976
5005
  function finishMerged(
4977
5006
  io: Io,
@@ -5623,6 +5652,14 @@ function missingPrLabels(io: Io, slug: string, number: number): string[] {
5623
5652
  * of two PRs, seconds), then standards and architecture — minutes, not the whole `test`.
5624
5653
  */
5625
5654
  export const PREMERGE_SCRIPTS = ["typecheck", "test:spec"];
5655
+ /**
5656
+ * The PR's task for task-env in the temporary worktree (#759) — a copy of `TASK_VAR` and `FAILED_VAR` of the task-env
5657
+ * script: the github skill imports no other skill (tests/standards/scripts/skill-imports). `ELVES_TASK` — the number of the
5658
+ * PR's branch: `up` on a detached HEAD takes that task's stack; `ELVES_TASK_ENV_FAILED` — the file a stack that didn't
5659
+ * come up appends its reason to.
5660
+ */
5661
+ const STACK_TASK_VAR = "ELVES_TASK";
5662
+ const STACK_FAILED_VAR = "ELVES_TASK_ENV_FAILED";
5626
5663
  /**
5627
5664
  * Spec roots whose checks `test:spec` runs — standards and architecture (the spec skill): there two green PRs break
5628
5665
  * main. A tree with them and without the script — premerge names what isn't checked on the merge, the project's
@@ -5728,10 +5765,10 @@ interface TreeRed {
5728
5765
  /**
5729
5766
  * A tree's check — `pr premerge` on the merge and on bare origin/<base>, the bisect of a red release at a boundary:
5730
5767
  * dependencies by its lockfile (`projectCommands`), then the steps — a project script with its arguments (the test
5731
- * files; npm — after `--`) — in order, up to the first red one. `install` — its command and result, no lockfile — null;
5732
- * failed — no step ran.
5768
+ * files; npm — after `--`) — in order, up to the first red one, `env` — on top of the process's. `install` — its command
5769
+ * and result, no lockfile — null; failed — no step ran.
5733
5770
  */
5734
- function checkTree(io: Io, dir: string, steps: { script: string; args?: string[] }[]): { install: { cmd: string; result: RunResult } | null; ran: string[]; red: TreeRed | null } {
5771
+ function checkTree(io: Io, dir: string, steps: { script: string; args?: string[] }[], env?: Record<string, string>): { install: { cmd: string; result: RunResult } | null; ran: string[]; red: TreeRed | null } {
5735
5772
  const run = io.run ?? realRun;
5736
5773
  const cmds = projectCommands(dir);
5737
5774
  const install = cmds.install ? { cmd: cmds.install.join(" "), result: run(cmds.install[0]!, cmds.install.slice(1), dir) } : null;
@@ -5740,7 +5777,7 @@ function checkTree(io: Io, dir: string, steps: { script: string; args?: string[]
5740
5777
  for (const s of steps) {
5741
5778
  const args = s.args ?? [];
5742
5779
  const argv = [...cmds.run(s.script), ...(args.length && packageManager(dir).name === "npm" ? ["--"] : []), ...args];
5743
- const result = run(argv[0]!, argv.slice(1), dir);
5780
+ const result = env ? run(argv[0]!, argv.slice(1), dir, env) : run(argv[0]!, argv.slice(1), dir);
5744
5781
  ran.push(s.script);
5745
5782
  if (result.status !== 0) return { install, ran, red: { script: s.script, cmd: argv.join(" "), result } };
5746
5783
  }
@@ -6109,6 +6146,18 @@ export function cmdPrPremerge(io: Io, slug: string, number: number): number {
6109
6146
 
6110
6147
  const ON_MERGE = "on the merge";
6111
6148
  type Red = TreeRed & { failed: string[] };
6149
+ // the database of the PR's task stack (#759): the temporary worktree is on a detached HEAD, task-env takes the task
6150
+ // from ELVES_TASK — the number of the PR's branch — and appends a stack that didn't come up to ELVES_TASK_ENV_FAILED
6151
+ const task = taskBranch(String(pr.head?.ref ?? ""))?.issue;
6152
+ const failedFile = path.join(mkdtempSync(path.join(os.tmpdir(), "elves-premerge-stack-")), "failed");
6153
+ const stackEnv: Record<string, string> = { [STACK_FAILED_VAR]: failedFile, ...(task ? { [STACK_TASK_VAR]: String(task) } : {}) };
6154
+ /** A stack that didn't come up during a check — its reasons; none — null. */
6155
+ const stackFailed = () => (existsSync(failedFile) ? readFileSync(failedFile, "utf8").split("\n").filter(Boolean) : null);
6156
+ const unchecked = (where: string, script: string, lines: string[]) => {
6157
+ io.out(`❌ couldn't check: the stack of ${task ? `task #${task}` : "the PR's task (its branch has no task number)"} didn't come up for ${script} ${where} — ${lines.join("; ")}`);
6158
+ io.out(`the red ${script} isn't counted against ${base} or the PR: bring the stack up (task-env up${task ? ` ${task}` : " <N>"}) and pr premerge ${number} again`);
6159
+ return 2;
6160
+ };
6112
6161
  /**
6113
6162
  * The tree's fast checks (`scripts` — those that exist) with dependencies from its lockfile, up to the first red one;
6114
6163
  * none — null.
@@ -6117,7 +6166,7 @@ export function cmdPrPremerge(io: Io, slug: string, number: number): number {
6117
6166
  const defined = scriptsOf(dir);
6118
6167
  const present = scripts.filter((s) => defined[s]);
6119
6168
  if (!present.length) return null;
6120
- const { install, ran, red } = checkTree(io, dir, present.map((script) => ({ script })));
6169
+ const { install, ran, red } = checkTree(io, dir, present.map((script) => ({ script })), stackEnv);
6121
6170
  if (install) {
6122
6171
  if (install.result.status !== 0) throw new GhError(`installing dependencies ${where} failed (${install.cmd}): ${tail(install.result, 5).join(" / ")}`);
6123
6172
  io.out(`+ dependencies${where === ON_MERGE ? "" : ` ${where}`}: ${install.cmd}`);
@@ -6127,57 +6176,65 @@ export function cmdPrPremerge(io: Io, slug: string, number: number): number {
6127
6176
  return { ran, red: { ...red, failed } };
6128
6177
  };
6129
6178
  const breaks = (script: string) => `❌ don't merge: ${script} is red on the merge with origin/${base} — fix the root cause in the PR: rebase onto origin/${base}, edit, push --force-with-lease, ${recheck}`;
6130
- return inTempWorktree(io, "premerge", `origin/${base}`, (dir) => {
6131
- const short = (ref: string) => git(io, dir, "rev-parse", "--short=7", ref).stdout.trim();
6132
- // like GitHub's merge-ref; a rebase merge without conflicts gives the same tree. A temporary merge doesn't need the
6133
- // project's hooks
6134
- const merge = git(io, dir, "-c", "user.name=elves", "-c", "user.email=elves@localhost", "-c", "commit.gpgsign=false", "merge", "-q", "--no-ff", "--no-verify", "--no-edit", head);
6135
- if (merge.status !== 0) {
6136
- const files = git(io, dir, "diff", "--name-only", "--diff-filter=U").stdout.split("\n").filter(Boolean);
6137
- if (!files.length) throw new GhError(`git merge: ${merge.stderr.trim()}`);
6138
- io.out(`❌ don't merge: a merge conflict with origin/${base} — ${files.join(", ")}; rebase onto origin/${base}, push --force-with-lease, ${recheck}`);
6139
- return 1;
6140
- }
6141
- io.out(`+ merge of ${head.slice(0, 7)} with origin/${base} ${short("HEAD^1")} — no conflicts`);
6142
- // standards without test:spec don't stop the merge: the project's check holds the script, here — that they weren't run
6143
- const roots = specRoots(dir);
6144
- if (roots.length && !scriptsOf(dir)["test:spec"]) io.out(`○ ${roots.join(", ")} aren't checked on the merge: the merge's package.json has no test:spec script — the project's check names the line to add (bunx github:miroshnik/elves check)`);
6145
- const merged = checks(dir, ON_MERGE, PREMERGE_SCRIPTS);
6146
- if (!merged) {
6147
- io.out(`○ no fast checks: the merge's package.json has no ${PREMERGE_SCRIPTS.join(" or ")} scripts — step skipped`);
6148
- io.out(`✅ merge: the merge with origin/${base} has no conflicts`);
6149
- return 0;
6150
- }
6151
- const red = merged.red;
6152
- if (!red) {
6153
- io.out(`✅ merge: ${merged.ran.join(" and ")} ${merged.ran.length > 1 ? "are" : "is"} green on the merge with origin/${base}`);
6154
- return 0;
6155
- }
6156
- io.out(`${red.cmd} failed:`);
6157
- for (const l of (red.failed.length ? red.failed.slice(0, 20) : tail(red.result))) io.out(` ${l.trim()}`);
6158
-
6159
- // a red merge — is bare main red by the same thing: then it's not this PR that breaks it
6160
- io.out(`checking bare origin/${base}: is it red by itself`);
6161
- const bare = inTempWorktree(io, "premerge", `origin/${base}`, (bareDir) => checks(bareDir, `on origin/${base}`, [red.script])?.red);
6162
- if (!bare) {
6163
- io.out(breaks(red.script));
6164
- return 1;
6165
- }
6166
- const onMain = new Set(bare.failed.map(failure));
6167
- const own = red.failed.filter((l) => !onMain.has(failure(l)));
6168
- // can't tell what failed — can't tell them apart: main is red, after its fix premerge checks the PR again
6169
- if (own.length && bare.failed.length) {
6170
- io.out(`${base} is red by itself, the PR breaks beyond it:`);
6171
- for (const l of own.slice(0, 20)) io.out(` ${l}`);
6179
+ try {
6180
+ return inTempWorktree(io, "premerge", `origin/${base}`, (dir) => {
6181
+ const short = (ref: string) => git(io, dir, "rev-parse", "--short=7", ref).stdout.trim();
6182
+ // like GitHub's merge-ref; a rebase merge without conflicts gives the same tree. A temporary merge doesn't need the
6183
+ // project's hooks
6184
+ const merge = git(io, dir, "-c", "user.name=elves", "-c", "user.email=elves@localhost", "-c", "commit.gpgsign=false", "merge", "-q", "--no-ff", "--no-verify", "--no-edit", head);
6185
+ if (merge.status !== 0) {
6186
+ const files = git(io, dir, "diff", "--name-only", "--diff-filter=U").stdout.split("\n").filter(Boolean);
6187
+ if (!files.length) throw new GhError(`git merge: ${merge.stderr.trim()}`);
6188
+ io.out(`❌ don't merge: a merge conflict with origin/${base} — ${files.join(", ")}; rebase onto origin/${base}, push --force-with-lease, ${recheck}`);
6189
+ return 1;
6190
+ }
6191
+ io.out(`+ merge of ${head.slice(0, 7)} with origin/${base} ${short("HEAD^1")} — no conflicts`);
6192
+ // standards without test:spec don't stop the merge: the project's check holds the script, here — that they weren't run
6193
+ const roots = specRoots(dir);
6194
+ if (roots.length && !scriptsOf(dir)["test:spec"]) io.out(`○ ${roots.join(", ")} aren't checked on the merge: the merge's package.json has no test:spec script — the project's check names the line to add (bunx github:miroshnik/elves check)`);
6195
+ const merged = checks(dir, ON_MERGE, PREMERGE_SCRIPTS);
6196
+ if (!merged) {
6197
+ io.out(`○ no fast checks: the merge's package.json has no ${PREMERGE_SCRIPTS.join(" or ")} scripts — step skipped`);
6198
+ io.out(`✅ merge: the merge with origin/${base} has no conflicts`);
6199
+ return 0;
6200
+ }
6201
+ const red = merged.red;
6202
+ if (!red) {
6203
+ io.out(`✅ merge: ${merged.ran.join(" and ")} ${merged.ran.length > 1 ? "are" : "is"} green on the merge with origin/${base}`);
6204
+ return 0;
6205
+ }
6206
+ io.out(`${red.cmd} failed:`);
6207
+ for (const l of (red.failed.length ? red.failed.slice(0, 20) : tail(red.result))) io.out(` ${l.trim()}`);
6208
+ const down = stackFailed();
6209
+ if (down) return unchecked(ON_MERGE, red.script, down);
6210
+
6211
+ // a red merge — is bare main red by the same thing: then it's not this PR that breaks it
6212
+ io.out(`checking bare origin/${base}: is it red by itself`);
6213
+ const bare = inTempWorktree(io, "premerge", `origin/${base}`, (bareDir) => checks(bareDir, `on origin/${base}`, [red.script])?.red);
6214
+ const bareDown = stackFailed();
6215
+ if (bareDown) return unchecked(`on origin/${base}`, red.script, bareDown);
6216
+ if (!bare) {
6217
+ io.out(breaks(red.script));
6218
+ return 1;
6219
+ }
6220
+ const onMain = new Set(bare.failed.map(failure));
6221
+ const own = red.failed.filter((l) => !onMain.has(failure(l)));
6222
+ // can't tell what failed — can't tell them apart: main is red, after its fix premerge checks the PR again
6223
+ if (own.length && bare.failed.length) {
6224
+ io.out(`${base} is red by itself, the PR breaks beyond it:`);
6225
+ for (const l of own.slice(0, 20)) io.out(` ${l}`);
6226
+ io.out(breaks(red.script));
6227
+ return 1;
6228
+ }
6229
+ const reason = `${red.script} is red on bare origin/${base} too, with the same failures`;
6230
+ const code = mainRed(`${base} is red by itself: ${reason}`, reason, git(io, dir, "rev-parse", `origin/${base}`).stdout.trim(), [red.script], (names) => names.join(", "));
6231
+ if (code !== null) return code;
6172
6232
  io.out(breaks(red.script));
6173
6233
  return 1;
6174
- }
6175
- const reason = `${red.script} is red on bare origin/${base} too, with the same failures`;
6176
- const code = mainRed(`${base} is red by itself: ${reason}`, reason, git(io, dir, "rev-parse", `origin/${base}`).stdout.trim(), [red.script], (names) => names.join(", "));
6177
- if (code !== null) return code;
6178
- io.out(breaks(red.script));
6179
- return 1;
6180
- });
6234
+ });
6235
+ } finally {
6236
+ rmSync(path.dirname(failedFile), { recursive: true, force: true });
6237
+ }
6181
6238
  }
6182
6239
 
6183
6240
  // ----------------------------------------------------------------------------
@@ -6436,8 +6493,9 @@ Examples:
6436
6493
 
6437
6494
  Before gh pr merge, after ci-wait PASS: the default branch moved after the PR's CI — the PR head merged with it in a
6438
6495
  temporary worktree and ${PREMERGE_SCRIPTS.join(", then ")} from package.json (those that exist, as in CI). Code 0 —
6439
- merge, 1 — don't merge (red, conflict), 2 — couldn't check, 3 — main is red by itself (the same check on bare main, a
6440
- red check on its last commit): don't merge, one bug for it — wait for it to close. A PR into a batch branch runs no
6496
+ merge, 1 — don't merge (red, conflict), 2 — couldn't check (the stack of the PR's task didn't come up: the checks get
6497
+ ELVES_TASK — the number of the PR's branch — for task-env up on the detached HEAD), 3 — main is red by itself (the same
6498
+ check on bare main, a red check on its last commit): don't merge, one bug for it — wait for it to close. A PR into a batch branch runs no
6441
6499
  CI, so no ci-wait before it: the head on a fresh origin/<batch> — code 0 without checks (the checks before a commit
6442
6500
  checked this tree), the batch moved on — the fast checks on the merge with it. The
6443
6501
  batch's release PR open — code 1 and the wait for its close, but red with the PR of one of its tasks — the guilty task's
@@ -43,7 +43,7 @@ task's own Compose project, and nothing of it is shared with other tasks.
43
43
 
44
44
  | what | value |
45
45
  |---|---|
46
- | task | the number from the branch `[<area>/]<type>/<N>-<slug>`; in the middle of a rebase — the branch being rebased (`rebase-merge/head-name`); no number — the main checkout's stack, but never from a linked worktree: there `up` and `down` without a number refuse (give `up <N>` or finish the rebase) |
46
+ | task | the number from the branch `[<area>/]<type>/<N>-<slug>`; in the middle of a rebase — the branch being rebased (`rebase-merge/head-name`); no number — the main checkout's stack, but never from a linked worktree: there `up` and `down` without a number take `ELVES_TASK=<N>` (`pr premerge` gives the PR's task to the checks on its detached HEAD), without it refuse (give `up <N>` or finish the rebase); a stack that didn't come up appends its reason to the file of `ELVES_TASK_ENV_FAILED` |
47
47
  | `<project>` | the repository of `origin` (the last part of its URL without `.git`), no remote — the main checkout's directory; lowercase letters, digits and `-`. Not the directory Compose takes by default — a worktree's is random |
48
48
  | stack | Compose project `<project>-<N>`, e2e — `<project>-<N>-e2e`, without a task — `<project>`, `<project>-e2e` |
49
49
  | profiles | `--profile <name>` (repeated) goes to Compose: a heavy service in `profiles` runs only in a task that asks for it |
@@ -43,7 +43,7 @@
43
43
  * unsandboxed call — an `excludedCommands` entry for it doesn't take it out (SKILL.md, «Docker and the sandbox»).
44
44
  */
45
45
  import { spawnSync } from "node:child_process";
46
- import { existsSync, readFileSync } from "node:fs";
46
+ import { appendFileSync, existsSync, readFileSync } from "node:fs";
47
47
  import path from "node:path";
48
48
  import { fileURLToPath } from "node:url";
49
49
 
@@ -58,11 +58,12 @@ export const HELP: Record<string, string> = {
58
58
  up: `task-env up [<N>] [--profile <p>]...
59
59
 
60
60
  Brings the task's stack up — the Compose project <project>-<N> by the branch <type>/<N>-slug, <project> without a
61
- number (in the middle of a rebase — the branch being rebased; a linked worktree without a task branch is
62
- refused: give N) — and prints its addresses: env.http services of .agents/elves.json through the proxy, published ports on
61
+ number (in the middle of a rebase — the branch being rebased; a linked worktree without a task branch — the task of
62
+ ELVES_TASK=<N>, without it refused: give N) — and prints its addresses: env.http services of .agents/elves.json through the proxy, published ports on
63
63
  127.0.0.1; the HTTP addresses go to the compose file's interpolation in TASK_ENV_<SERVICE>_URL; --profile — Compose
64
64
  profiles. The bring-up takes a place in the machine queue (slot) until the containers are healthy. Code 0 — up, 1 — a
65
- service failed (its state and log), 2 — not tried.
65
+ service failed (its state and log), 2 — not tried; not up — the reason is appended to the file of
66
+ ELVES_TASK_ENV_FAILED, if given (pr premerge of the github skill: «couldn't check», not a red check).
66
67
 
67
68
  Examples:
68
69
  task-env up
@@ -879,7 +880,7 @@ function shown(addresses: Address[], withVar: boolean): string[] {
879
880
  function stackUp(project: Project, profiles: string[], env: NodeJS.ProcessEnv): number {
880
881
  const stack = stackOf(project.name, project.task);
881
882
  const r = inSlot(`up ${stack.name}`, () => upStack(project, stack, profiles, env));
882
- if (r.code) return console.log(r.lines.join("\n")), r.code;
883
+ if (r.code) return console.log(r.lines.join("\n")), stackFailed(env, "up", r.code, r.lines);
883
884
  const addresses = addressesOf(project, stack, env);
884
885
  console.log([...r.lines, `stack ${stack.name}: up${addresses.length ? "" : " — no HTTP service in env.http and no published port"}`, ...shown(addresses, false)].join("\n"));
885
886
  console.log(`logs: docker compose -p ${stack.name} logs <service>; down: bun --no-env-file ${fileURLToPath(import.meta.url)} down${project.task === undefined ? "" : ` ${project.task}`}`);
@@ -894,9 +895,9 @@ function stackUp(project: Project, profiles: string[], env: NodeJS.ProcessEnv):
894
895
  function stackE2e(project: Project, profiles: string[], command: string[], env: NodeJS.ProcessEnv): number {
895
896
  const stack = stackOf(project.name, project.task, true);
896
897
  const clean = downStack(stack.name, env);
897
- if (!clean.ok) return console.log(clean.line), 2;
898
+ if (!clean.ok) return console.log(clean.line), stackFailed(env, "e2e", 2, [clean.line]);
898
899
  const r = inSlot(`e2e ${stack.name}`, () => upStack(project, stack, profiles, env));
899
- if (r.code) return console.log(r.lines.join("\n")), r.code;
900
+ if (r.code) return console.log(r.lines.join("\n")), stackFailed(env, "e2e", r.code, r.lines);
900
901
  const addresses = addressesOf(project, stack, env);
901
902
  console.log([...r.lines, `stack ${stack.name}: up, clean volumes — TASK_ENV_PROJECT=${stack.name}`, ...shown(addresses, true)].join("\n"));
902
903
  if (!command.length) return 0;
@@ -1008,6 +1009,28 @@ function profilesOf(args: string[]): { profiles: string[]; rest: string[] } | un
1008
1009
  return { profiles, rest: args.slice(i + 1) };
1009
1010
  }
1010
1011
 
1012
+ /**
1013
+ * The task of a checkout without a task branch — `ELVES_TASK=<N>`: `pr premerge` of the github skill checks the merge
1014
+ * in a temporary worktree on a detached HEAD and gives the PR's task (#759) — `up`, `e2e` and `down` without a number
1015
+ * take its stack instead of refusing. A task branch comes first; not a positive number — none.
1016
+ */
1017
+ export const TASK_VAR = "ELVES_TASK";
1018
+ /**
1019
+ * The file a stack command that didn't bring the stack up appends its reason to — `ELVES_TASK_ENV_FAILED=<file>`:
1020
+ * `pr premerge` tells «couldn't check» from a red check by it (#759) — a test that failed on the connection says
1021
+ * nothing about the stack.
1022
+ */
1023
+ export const FAILED_VAR = "ELVES_TASK_ENV_FAILED";
1024
+ const taskOfEnv = (env: NodeJS.ProcessEnv) => (/^[1-9]\d*$/.test(env[TASK_VAR] ?? "") ? Number(env[TASK_VAR]) : undefined);
1025
+
1026
+ /** A stack that didn't come up — its reason into FAILED_VAR, if given; the code as is. */
1027
+ function stackFailed(env: NodeJS.ProcessEnv, group: string, code: number, lines: string[]): number {
1028
+ const file = env[FAILED_VAR];
1029
+ const why = lines.filter((l) => l.trim()).slice(-3).join(" / ") || `code ${code}`;
1030
+ if (file && code !== 0) appendFileSync(file, `${why.startsWith("task-env ") ? "" : `task-env ${group}: `}${why}\n`);
1031
+ return code;
1032
+ }
1033
+
1011
1034
  /** The stack commands: undefined — not one of them or wrong arguments. */
1012
1035
  function stackCommand(group: string, args: string[], env: NodeJS.ProcessEnv): number | undefined {
1013
1036
  if (group !== "up" && group !== "e2e" && group !== "down" && group !== "prune") return undefined;
@@ -1016,21 +1039,24 @@ function stackCommand(group: string, args: string[], env: NodeJS.ProcessEnv): nu
1016
1039
  // the stacks are found by the Compose project: the task's worktree may be gone already
1017
1040
  const root = git(process.cwd(), "rev-parse", "--show-toplevel") || process.cwd();
1018
1041
  if (group === "prune") return prune(root, env);
1019
- if (!args[0]) {
1042
+ const branch = taskBranch(currentBranch(root))?.issue ?? taskOfEnv(env);
1043
+ if (!args[0] && branch === undefined) {
1020
1044
  const refusal = noTaskRefusal(root, "down");
1021
1045
  if (refusal) return console.log(refusal), 2;
1022
1046
  }
1023
- return stackDown(root, args[0] ? Number(args[0]) : taskBranch(currentBranch(root))?.issue, env);
1047
+ return stackDown(root, args[0] ? Number(args[0]) : branch, env);
1024
1048
  }
1025
- const number = group === "up" && /^\d+$/.test(args[0] ?? "") ? Number(args[0]) : undefined;
1026
- const opts = profilesOf(number === undefined ? args : args.slice(1));
1049
+ const given = group === "up" && /^\d+$/.test(args[0] ?? "") ? Number(args[0]) : undefined;
1050
+ const opts = profilesOf(given === undefined ? args : args.slice(1));
1027
1051
  if (!opts || (group === "up" && opts.rest.length)) return undefined;
1052
+ const root = git(process.cwd(), "rev-parse", "--show-toplevel") || process.cwd();
1053
+ const number = given ?? (taskBranch(currentBranch(root)) ? undefined : taskOfEnv(env));
1028
1054
  if (number === undefined) {
1029
- const refusal = noTaskRefusal(git(process.cwd(), "rev-parse", "--show-toplevel") || process.cwd(), group);
1030
- if (refusal) return console.log(refusal), 2;
1055
+ const refusal = noTaskRefusal(root, group);
1056
+ if (refusal) return console.log(refusal), stackFailed(env, group, 2, [refusal]);
1031
1057
  }
1032
1058
  const project = projectOf(process.cwd(), number);
1033
- if (typeof project === "string") return console.log(`task-env ${group}: ${project}`), 2;
1059
+ if (typeof project === "string") return console.log(`task-env ${group}: ${project}`), stackFailed(env, group, 2, [project]);
1034
1060
  return group === "up" ? stackUp(project, opts.profiles, env) : stackE2e(project, opts.profiles, opts.rest, env);
1035
1061
  }
1036
1062