diff --git a/CHANGELOG.md b/CHANGELOG.md index 5b9ea4b2..8f83b2f9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,20 @@ All notable changes to devkit. Versions follow CalVer `YY.MM.PATCH` (PATCH restarts at 0 each month); tags are `vYY.MM.PATCH`. Sections follow [Keep a Changelog](https://keepachangelog.com/). +## [26.11.25] - 2026-11-18 + +### Fixed + +- `dev pr merge` works again: 26.11.24 asked `gh repo view` for an auto-merge field it does not have, so every merge + failed with `Unknown JSON field: "autoMergeAllowed"`. Only `--auto` now reads the setting, from GitHub's REST API. +- `dev ci --run` blocks the evidence for a check piped into the home folder through `sudo tee`, or into a dotfile or + dot folder there (`pytest | tee ~/log ~/.bashrc`, whatever the order of the targets), instead of skipping the step + as setup or overwriting the developer's settings; the same writes with no check beside them are still the runner's + setup. +- `dev docs check` no longer applies the diagram rules to images in test fixture folders (`fixtures`, `__fixtures__`, + `testdata`), which tests load rather than readers see, and judges only the folders inside the checkout, so a + managed worktree, or a checkout under a folder named `build`, `dist` or `testdata`, has its images checked again. + ## [26.11.24] - 2026-11-18 ### Fixed diff --git a/VERSION b/VERSION index 159a7c26..302f12b6 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -26.11.24 +26.11.25 diff --git a/desktop/manifest.json b/desktop/manifest.json index 48ab1ded..8a2b1c42 100644 --- a/desktop/manifest.json +++ b/desktop/manifest.json @@ -2,7 +2,7 @@ "manifest_version": "0.4", "name": "devkit", "display_name": "devkit", - "version": "26.11.24", + "version": "26.11.25", "description": "Every repo in its place. Every agent on the same page. Your devkit portfolio, project status, tasks, CI and team, in Claude Desktop chat and Cowork.", "long_description": "devkit connects Claude Desktop to **devkit** from Firefly Software Solutions Inc.: every repository in its place under ~/Development, one handoff repository that keeps each project's status, tasks, plans, lessons and session log, and the same rules for Claude Code, Codex and the team. Claude Code already uses devkit through its plugin; this extension brings it to Desktop chat and Cowork.\n\n**What you can ask**\n\n- **Where things stand:** the portfolio overview, one project's status, its tasks, a standup of the last days, and a status report for the team or management.\n- **Delivery:** live CI/CD runs with job progress and an ETA, and a project's delivery policy (versioning, test gate, release flow) with its gaps.\n- **Team and history:** who is working on what, devkit's crew of specialist agents and the decisions waiting for you, lessons learned, devkit's audit trail, its scheduled jobs, and a health check of the whole setup.\n- **Tasks:** add a task, or start, finish, block, unblock or release one. Changes go through the `dev` command, so devkit's audit trail applies exactly as it does in the terminal.\n\nWhen Claude reports a project's status, it starts with the devkit status block (**[Firefly> DevKit]**), the same one Claude Code and Codex use.\n\n**Setting it up.** devkit must be installed on this Mac: run `./install.sh` in the devkit repository, which runs `dev setup`. The extension finds devkit on its own; set the devkit folder only if devkit is not where `dev setup` put it. At startup, the extension selects the configured devkit folder or the installed `dev` link. Install or update devkit through its supported policy, then restart Claude Desktop or turn the extension off and on to load the new tools. A running server keeps the version it started with. It needs Python 3.9 or later, which comes with the macOS Command Line Tools.\n\n**Privacy.** Everything runs on your Mac through the `dev` command and reads your workspace and handoff repository. The project status, CI status and doctor tools ask GitHub or your CI provider through your existing sign-in (for example `gh auth login`); task changes are pushed to your own handoff repository. No token is stored by the extension.", "author": { diff --git a/docs/commands.md b/docs/commands.md index 1f3b1504..ca542f08 100644 --- a/docs/commands.md +++ b/docs/commands.md @@ -631,7 +631,7 @@ Local CI evidence: proof that what CI runs passed on your Mac, on exactly the fi | Option | Effect | | --- | --- | -| `--run` | Runs the `run:` steps of the workflows that run on pushes and pull requests, in order, and records the evidence when all pass. Setup actions, dependency installs, side effects, a hosted runner's own setup (deletions outside the checkout, Docker prunes, setup run with `sudo`, OS package installs, `playwright install`, `git config --global`, Linux-only system setup such as `fc-cache`, `ldconfig`, or `locale-gen`, and `mkdir`, `cp`, `mv`, `ln`, `install`, `touch`, `tee`, or `rsync` writes into the home folder outside the checkout, unless the same pipeline runs a check, as `pytest \| tee ~/pytest.log` does), and steps that need CI secrets are skipped, each with a line that says why. In a step that sets up a tool and runs it (`brew install gitleaks && gitleaks detect`), only the setup is left out and the check runs, so a tool missing on this Mac fails the evidence. A script run with `source` or `.`, and a command or process substitution, count as checks. A check that cannot be separated from its setup (a nested shell, a subshell, a substitution, a heredoc, a `case`), a check run with `sudo` (including `sudo test`, `sudo [`, and a reporting command with a substitution, such as `sudo echo "$(…)"`), and a step that names a Docker context this Mac lacks block the evidence (see [Git and GitHub › Local CI evidence](git-and-github.md#local-ci-evidence)) | +| `--run` | Runs the `run:` steps of the workflows that run on pushes and pull requests, in order, and records the evidence when all pass. Setup actions, dependency installs, side effects, a hosted runner's own setup (deletions outside the checkout, Docker prunes, setup run with `sudo`, OS package installs, `playwright install`, `git config --global`, Linux-only system setup such as `fc-cache`, `ldconfig`, or `locale-gen`, and `mkdir`, `cp`, `mv`, `ln`, `install`, `touch`, `tee`, or `rsync` writes into the home folder outside the checkout, unless the same pipeline runs a check, as `pytest \| tee ~/pytest.log` does; a check piped into the home folder through `sudo tee`, or into a dotfile such as `~/.bashrc`, blocks the evidence instead), and steps that need CI secrets are skipped, each with a line that says why. In a step that sets up a tool and runs it (`brew install gitleaks && gitleaks detect`), only the setup is left out and the check runs, so a tool missing on this Mac fails the evidence. A script run with `source` or `.`, and a command or process substitution, count as checks. A check that cannot be separated from its setup (a nested shell, a subshell, a substitution, a heredoc, a `case`), a check run with `sudo` (including `sudo test`, `sudo [`, and a reporting command with a substitution, such as `sudo echo "$(…)"`), and a step that names a Docker context this Mac lacks block the evidence (see [Git and GitHub › Local CI evidence](git-and-github.md#local-ci-evidence)) | | `--dry-run` | With `--run`: the plan, without running anything | | `--keep-going` | With `--run`: do not stop at the first failure | | `--step-timeout MIN` | With `--run`: minutes per step (default 30) | @@ -886,7 +886,8 @@ checks before using the result as security evidence. ### `dev docs check […] [--online] [--fix] [--no-prose]` Checks documentation in one pass, covering Markdown structure (markdownlint), links and anchors (lychee), prose (Vale with the -Google and write-good styles) and, when no paths are given, every SVG in the repository. The repository's own +Google and write-good styles) and, when no paths are given, every SVG in the repository except those in test fixture +folders (`fixtures`, `__fixtures__`, `testdata`), which tests load rather than readers see. The repository's own configuration files win over devkit's defaults. | Option | Effect | diff --git a/docs/git-and-github.md b/docs/git-and-github.md index 0349d675..83f79f31 100644 --- a/docs/git-and-github.md +++ b/docs/git-and-github.md @@ -334,7 +334,7 @@ Steps that cannot or must not run on your Mac are skipped, with the reason: | Setup actions (`uses:`) | Your local toolchain stands in for them | | Dependency installs (`npm ci`, `pip install`, `uv sync`, …) | Your local environment is used; nothing is reinstalled | | Side effects: publishing, deploying, pushing, system installs, coverage uploads | They change things outside your Mac | -| A hosted runner's own setup: a step that deletes a path not inside the checkout (`rm -rf /opt/hostedtoolcache/…`), `docker` or `podman … prune`, setup run with `sudo` (`sudo systemctl …`), OS package installs and updates (`apt-get`, `brew`, `dnf`, `apk`, `choco`, …), `playwright install` and `install-deps`, `git config --global` or `--system`, a Linux runner's own system setup (`fc-cache`, `ldconfig`, `locale-gen`, `update-ca-certificates`, …), and `mkdir`, `cp`, `mv`, `ln`, `install`, `touch`, `tee`, or `rsync` writing into the home folder outside the checkout (`mkdir -p ~/.local/share/fonts`), unless the same pipeline runs a check (`pytest \| tee ~/pytest.log` runs) | They would delete your caches and images, install system packages, rewrite your settings, or fill your home folder; a Mac has no use for a Linux runner's system caches. Each skipped step gets a line that says why. devkit also reads the script a step hands to a shell with `-c` (`xvfb-run bash -c …`) | +| A hosted runner's own setup: a step that deletes a path not inside the checkout (`rm -rf /opt/hostedtoolcache/…`), `docker` or `podman … prune`, setup run with `sudo` (`sudo systemctl …`), OS package installs and updates (`apt-get`, `brew`, `dnf`, `apk`, `choco`, …), `playwright install` and `install-deps`, `git config --global` or `--system`, a Linux runner's own system setup (`fc-cache`, `ldconfig`, `locale-gen`, `update-ca-certificates`, …), and `mkdir`, `cp`, `mv`, `ln`, `install`, `touch`, `tee`, or `rsync` writing into the home folder outside the checkout (`mkdir -p ~/.local/share/fonts`), unless the same pipeline runs a check (`pytest \| tee ~/pytest.log` runs; into the home folder through `sudo tee`, or into a dotfile such as `~/.bashrc`, it blocks the evidence) | They would delete your caches and images, install system packages, rewrite your settings, or fill your home folder; a Mac has no use for a Linux runner's system caches. Each skipped step gets a line that says why. devkit also reads the script a step hands to a shell with `-c` (`xvfb-run bash -c …`) | | Steps that need CI secrets or write CI plumbing (`$GITHUB_ENV`, `$GITHUB_OUTPUT`) | They only make sense on the runner | | Jobs that deploy or publish, run on Windows, or only on other events | They are not part of the check of a change | diff --git a/lib/devkit/docs.py b/lib/devkit/docs.py index 6e6eee17..58a9884c 100644 --- a/lib/devkit/docs.py +++ b/lib/devkit/docs.py @@ -19,6 +19,9 @@ VALE_STYLES = HOME / ".local" / "share" / "devkit" / "vale" / "styles" VALE_INI = HOME / ".local" / "share" / "devkit" / "vale" / ".vale.ini" MD_SKIP = ("node_modules", ".venv", "vendor", "dist", ".git", "build", "target", ".worktrees") +# Folders of test fixtures: the images there are what a test loads, not a picture a reader sees, so the diagram rules +# (a title, no scripts, readable type) do not apply to them. +FIXTURE_DIRS = ("fixtures", "__fixtures__", "testdata") VALE_WARNINGS_SHOWN = 40 # Vale's errors are all listed; its warnings up to this many, then a count and the command @@ -125,7 +128,9 @@ def check(root: Path, paths=None, online=False, fix=False, prose=True) -> int: else: print(f" {ui.WARN} vale not available (brew install vale)") - svgs = [p for p in root.rglob("*.svg") if not any(s in p.parts for s in MD_SKIP)] if not paths else [] + # only the folders inside the checkout count: a checkout under testdata/ or .worktrees/ still has its images checked + svgs = [p for p in root.rglob("*.svg") if not any(s in p.relative_to(root).parts for s in MD_SKIP + FIXTURE_DIRS)] \ + if not paths else [] if svgs: print(ui.section(f"Diagrams · {len(svgs)} SVG(s)")) try: diff --git a/lib/devkit/gitx.py b/lib/devkit/gitx.py index 95c55dac..2d449f9a 100644 --- a/lib/devkit/gitx.py +++ b/lib/devkit/gitx.py @@ -2374,10 +2374,14 @@ def _informational(argv, words) -> bool: return os.path.basename(words[0]) in _INFO or words[1:] in _VERSION_ARGS +_HOME_KINDS = ("home", "home-dot", "home-root") # a write into the home folder, least to most severe + + def _prep_one(argv, words, as_root: bool, state: dict): """("setup", why) when this one command only sets up a hosted runner, ("home", why) when it writes into the home - folder outside the checkout (setup unless its piece runs a check), ("root", why) when it is a check that runs as - root, or None. `state` carries the folder `cd` went to ("here"), the checkout ("top") and the variables.""" + folder outside the checkout (setup unless its piece runs a check), ("home-dot", why) or ("home-root", why) when + that write goes into a dotfile or a dot folder, or runs as root (setup with no check beside it, and a block next + to one), ("root", why) when it is a check that runs as root, or None. `state` carries the folder `cd` went to ("here"), the checkout ("top") and the variables.""" if not words: return None env, top = state["env"], state["top"] @@ -2417,12 +2421,19 @@ def _prep_one(argv, words, as_root: bool, state: dict): return "setup", f"runner prep ({name} sets up the Linux runner's own system; a Mac has no use for it)" elif name in _WRITERS: home = os.path.realpath(env.get("HOME") or os.path.expanduser("~")) + found = None # the most severe of its targets: one command can write several (tee ~/log ~/.bashrc) for w in _written(words, _WRITERS[name]): p = _shell_path(w, state["here"], env) if p and (p == home or p.startswith(home + os.sep)) and p != top and not p.startswith(top + os.sep): - # "home": setup only when its piece runs no check (_classify); a check's log piped to tee still runs - return ("setup" if as_root else "home"), \ - f"runner prep (writes {w} into the home folder, outside the checkout)" + # "home": setup only when its piece runs no check (_classify); a check's log piped to tee still runs. + # A dotfile or dot folder holds the developer's own settings, and a write as root cannot run here: + # next to a check, either one blocks the step instead. + dot = any(part.startswith(".") and part != "." for part in os.path.relpath(p, home).split(os.sep)) + kind = "home-root" if as_root else "home-dot" if dot else "home" + if found is None or _HOME_KINDS.index(kind) > _HOME_KINDS.index(found[0]): + found = (kind, f"runner prep (writes {w} into the home folder, outside the checkout)") + if found: + return found if as_root: # setup the runner does as root, or a check that runs as root, which cannot run here if _informational(argv, words) and (name in ("test", "[", "[[") or any("$(" in w or "`" in w for w in words[1:])): @@ -2527,14 +2538,21 @@ def _classify(piece: dict, state: dict, installs: bool) -> dict: piped = _PIPED_INSTALLER.search(code) setup = "runner prep (curl … | sh runs an installer downloaded from the internet)" if piped else None first = "curl … | sh" if piped else None - install, checks, roots, nested, home = None, [], [], False, None + install, checks, roots, nested, home, held = None, [], [], False, None, None for argv, words, as_root, container in _commands(code, state=state): nested = nested or container if container: continue got = _prep_one(argv, words, as_root, state) - if got and got[0] == "home": + if got and got[0] in ("home", "home-dot", "home-root"): home = home or (got[1], " ".join(words[:2])) + target = got[1].split("writes ", 1)[1].split(" into the home folder", 1)[0] + if got[0] == "home-root": + held = held or ("root", f"runs {os.path.basename(words[0])} as root (sudo), which dev ci --run does " + f"not do on this Mac") + elif got[0] == "home-dot": + held = held or ("tangled", f"writes {target} into a dotfile of the home folder next to a check, which " + f"would change this Mac's own settings: write the log inside the checkout") elif got and got[0] == "setup": setup = setup or got[1] first = first or " ".join(words[:2]) @@ -2545,6 +2563,8 @@ def _classify(piece: dict, state: dict, installs: bool) -> dict: roots.append(got[1]) elif not _informational(argv, words): checks.append(words) + if held and (checks or roots): # a check whose output goes into a dotfile or through sudo: it cannot run here + return {"kind": held[0], "why": held[1]} if home and not (checks or roots): # it only writes into the home folder and reports: the runner's setup setup, first = setup or home[0], first or home[1] for script in _substitutions(shellparse.strip_heredocs(code)): @@ -2555,7 +2575,7 @@ def _classify(piece: dict, state: dict, installs: bool) -> dict: inside = dict(state) # it runs in a subshell of its own: a `cd` in it holds for the rest of it only for argv, words, as_root, container in _commands(script, state=inside): got = None if container else _prep_one(argv, words, as_root, inside) - if got and got[0] in ("setup", "home"): + if got and got[0] in ("setup", "home", "home-dot", "home-root"): setup, first, nested = setup or got[1], first or " ".join(words[:2]), True why = setup or install if why and (checks or roots) and (nested or piece["subshell"]): @@ -4171,7 +4191,7 @@ def _pr_merge(c, a) -> int: if why: return refuse(f"not merging #{n}: " + "; ".join(why)) repo, err = gh_json(["repo", "view", c.slug, "--json", "squashMergeAllowed,mergeCommitAllowed,rebaseMergeAllowed," - "deleteBranchOnMerge,viewerDefaultMergeMethod,autoMergeAllowed"], c) + "deleteBranchOnMerge,viewerDefaultMergeMethod"], c) if repo is None: return fail(f"cannot read the repository's merge settings: {err}") method, err = merge_method(repo, a.method) @@ -4181,9 +4201,14 @@ def _pr_merge(c, a) -> int: if auto and (p.get("mergeStateStatus") or "") in MERGEABLE_NOW: # merge_gate refused it with checks running auto = False # gh merges it at once anyway: a plain merge, with the branch deleted and its items closed info(f"#{n} can be merged now (its checks passed and nothing on GitHub holds it): merging it, no auto-merge") - elif auto and repo.get("autoMergeAllowed") is False: - return refuse(f"not merging #{n}: the repository does not allow auto-merge", - f"wait for the checks (dev pr checks {n} --watch), then dev pr merge {n}") + elif auto: + # gh's repo view has no auto-merge field: the REST API's allow_auto_merge says whether GitHub takes the request + settings, err = gh_json(["api", f"repos/{c.slug}"], c) + if not isinstance(settings, dict) or "allow_auto_merge" not in settings: + return fail(f"cannot tell whether the repository allows auto-merge: {err or 'no allow_auto_merge field'}") + if settings["allow_auto_merge"] is not True: + return refuse(f"not merging #{n}: the repository does not allow auto-merge", + f"wait for the checks (dev pr checks {n} --watch), then dev pr merge {n}") args = ["pr", "merge", str(n), "-R", c.slug, f"--{method}", "--match-head-commit", p.get("headRefOid", "")] if method == "squash": conv = title_convention(c) diff --git a/plugin/.claude-plugin/plugin.json b/plugin/.claude-plugin/plugin.json index 881efa36..06d2d409 100644 --- a/plugin/.claude-plugin/plugin.json +++ b/plugin/.claude-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "devkit", - "version": "26.11.24", + "version": "26.11.25", "description": "Every repo in its place, every agent on the same page: project context and handoff notes, tasks, a portfolio overview, local-first delivery (one push, one CI run), backend methodology, and managed worktrees.", "icon": "./assets/icon.png", "author": { diff --git a/plugin/.codex-plugin/plugin.json b/plugin/.codex-plugin/plugin.json index 4ba3a89c..8d097ae8 100644 --- a/plugin/.codex-plugin/plugin.json +++ b/plugin/.codex-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "devkit", - "version": "26.11.24", + "version": "26.11.25", "description": "Every repo in its place, every agent on the same page: project context and handoff notes, tasks, a portfolio overview, local-first delivery (one push, one CI run), backend methodology, and managed worktrees.", "author": { "name": "Firefly Software Solutions Inc.", diff --git a/tests/test_docs_check.py b/tests/test_docs_check.py index 0962ea06..7809bbec 100644 --- a/tests/test_docs_check.py +++ b/tests/test_docs_check.py @@ -74,5 +74,33 @@ def alert(line, severity, check): r"--minAlertLevel warning A\.md C\.md") +class SvgTests(unittest.TestCase): + # The diagram rules (a title for people who cannot see the picture, no scripts) are for the images a reader sees. + # A test fixture is a deliberately plain image a test loads, so the check fails a page's diagram without a title + # and passes the same image under a test fixtures folder. + def test_a_docs_image_without_a_title_fails_and_a_test_fixture_image_does_not(self): + plain = '' + saved = core.have + core.have = lambda tool: False # no markdownlint, link checker or vale: only the image rules run + try: + # the folders above the checkout never count: a checkout under testdata/ or a managed worktree + # (.worktrees/) still has its docs images checked + for checkout, where, failing in (("", "docs/images/a.svg", True), ("", "tests/fixtures/visual/b.svg", False), + ("", "test/fixtures/c.svg", False), ("", "src/__fixtures__/d.svg", False), + ("", "pkg/testdata/e.svg", False), ("testdata/repo", "docs/f.svg", True), + (".worktrees/repo/feat-x", "docs/g.svg", True)): + with self.subTest(checkout=checkout, where=where), tempfile.TemporaryDirectory() as d: + root = Path(d, checkout) + root.mkdir(parents=True, exist_ok=True) + Path(root, "README.md").write_text("# Title\n\nText.\n") + Path(root, where).parent.mkdir(parents=True) + Path(root, where).write_text(plain) + with redirect_stdout(io.StringIO()) as out: + rc = docs.check(root) + self.assertEqual((rc != 0, "no " in out.getvalue()), (failing, failing), out.getvalue()) + finally: + core.have = saved + + if __name__ == "__main__": unittest.main() diff --git a/tests/test_gitx.py b/tests/test_gitx.py index b156b96c..8b04f200 100644 --- a/tests/test_gitx.py +++ b/tests/test_gitx.py @@ -30,8 +30,32 @@ REAL_TEMPLATE_DIR = gitx.TEMPLATE_DIR +# The JSON fields `gh repo view --json` and `gh pr view --json` accept (gh 2.103): gh refuses any other with +# "Unknown JSON field", so the fake refuses them too. dev pr merge once asked for autoMergeAllowed, which gh's repo +# view does not have, and every merge failed while the tests, which accepted any field, passed. +GH_JSON_FIELDS = { + ("repo", "view"): set("""archivedAt assignableUsers codeOfConduct contactLinks createdAt defaultBranchRef + deleteBranchOnMerge description diskUsage forkCount fundingLinks hasDiscussionsEnabled hasIssuesEnabled + hasProjectsEnabled hasWikiEnabled homepageUrl id isArchived isBlankIssuesEnabled isEmpty isFork + isInOrganization isMirror isPrivate isSecurityPolicyEnabled isTemplate isUserConfigurationRepository + issueTemplates issues labels languages latestRelease licenseInfo mentionableUsers mergeCommitAllowed + milestones mirrorUrl name nameWithOwner openGraphImageUrl owner parent primaryLanguage projects projectsV2 + pullRequestTemplates pullRequests pushedAt rebaseMergeAllowed repositoryTopics securityPolicyUrl + squashMergeAllowed sshUrl stargazerCount templateRepository updatedAt url usesCustomOpenGraphImage + viewerCanAdminister viewerDefaultCommitEmail viewerDefaultMergeMethod viewerHasStarred viewerPermission + viewerPossibleCommitEmails viewerSubscription visibility watchers""".split()), + ("pr", "view"): set("""additions assignees author autoMergeRequest baseRefName baseRefOid body changedFiles closed + closedAt closingIssuesReferences comments commits createdAt deletions files fullDatabaseId headRefName + headRefOid headRepository headRepositoryOwner id isCrossRepository isDraft labels latestReviews + maintainerCanModify mergeCommit mergeStateStatus mergeable mergedAt mergedBy milestone number + potentialMergeCommit projectCards projectItems reactionGroups reviewDecision reviewRequests reviews state + statusCheckRollup title updatedAt url""".split()), +} + + class FakeGH: - """Canned `gh`: the newest matching route wins; every call is recorded.""" + """Canned `gh`: the newest matching route wins; every call is recorded. Like gh, it refuses a JSON field that + `repo view` or `pr view` does not have.""" def __init__(self): self.calls, self.routes = [], [] @@ -42,6 +66,11 @@ def on(self, prefix, out="", rc=0, err="", when=None): def __call__(self, args, cwd=None, timeout=60): args = list(args) self.calls.append(args) + known = GH_JSON_FIELDS.get(tuple(args[:2])) + if known and "--json" in args: + unknown = [f for f in args[args.index("--json") + 1].split(",") if f not in known] + if unknown: + return 1, "", f'Unknown JSON field: "{unknown[0]}"' for prefix, rc, out, err, when in self.routes: if args[:len(prefix)] == prefix and (when is None or when(args)): return rc, out, err @@ -1140,6 +1169,31 @@ def test_a_test_run_as_root_blocks_and_a_here_string_keeps_its_check(self): (None, False, 'jq . <<< "$X"', ["brew install jq"])) self.assertRegex(got["Root setup"]["skip"] or "", r"^runner prep \(sudo mkdir -p runs as root") + # A check piped into a home-folder file runs as written, since its log is all the write is. Two pipelines must not: + # `sudo tee` cannot run here, so skipping the step would record evidence for tests that never ran; and a write + # into a dotfile (`~/.bashrc`, `~/.npmrc`) would change the developer's own settings. Both block the evidence. + # The same writes with no check beside them are still the runner's setup. + def test_a_check_piped_to_sudo_tee_or_into_a_home_dotfile_blocks_the_evidence(self): + with Sandbox() as s, mock.patch.dict(os.environ, {"HOME": str(s.root)}): + got = self.plan_steps(s, {"Root log": "python -m pytest 2>&1 | sudo tee ~/pytest.log", + "Root log beside": "pytest | sudo tee -a /tmp/x.log ~/ci/pytest.log", + "Bashrc": "pytest | tee ~/.bashrc", + "Npmrc": 'npm test | tee -a "$HOME/.npmrc"', + "Dot folder": "pytest | tee ~/.config/tool/log.txt", + "Dotfile second": "pytest | tee ~/log ~/.bashrc", + "Root setup": "echo token | sudo tee ~/.npmrc", + "Dot setup": "echo registry=https://example.test | tee ~/.npmrc", + "Log": "pytest | tee ~/pytest.log"}) + for name in ("Root log", "Root log beside", "Bashrc", "Npmrc", "Dot folder", "Dotfile second"): + with self.subTest(step=name): + self.assertTrue(got[name]["blocking"], got[name]["skip"]) + self.assertIsNotNone(got[name]["skip"]) + for name in ("Root setup", "Dot setup"): + with self.subTest(step=name): + self.assertRegex(got[name]["skip"] or "", r"^runner prep \(") + self.assertFalse(got[name]["blocking"]) + self.assertEqual((got["Log"]["skip"], got["Log"]["blocking"]), (None, False)) + def fake_tools(self, d: Path) -> Path: """A bin folder with a `brew` that leaves a marker when it runs and a `fakescan` that records its arguments and exits with the code in fakescan.rc.""" @@ -1656,8 +1710,9 @@ def merge(self, s, *flags): def auto_merge(self, s, after, repo=None, pr=None, code=0): """`dev pr merge 7 --auto` on a PR whose checks still run and that the base branch's protection holds (merge state BLOCKED); `after`: what GitHub says of the PR once gh returned. -> (stdout, stderr)""" - s.gh.on(["repo", "view"], dict({"squashMergeAllowed": True, "viewerDefaultMergeMethod": "SQUASH", - "autoMergeAllowed": True, "deleteBranchOnMerge": False}, **(repo or {}))) + s.gh.on(["repo", "view"], {"squashMergeAllowed": True, "viewerDefaultMergeMethod": "SQUASH", + "deleteBranchOnMerge": False}) + s.gh.on(["api", "repos/acme/widget"], dict({"allow_auto_merge": True}, **(repo or {}))) s.gh.on(["pr", "merge"], "") s.gh.on(["pr", "view"], dict(_pr(statusCheckRollup=[{"status": "IN_PROGRESS"}], mergeStateStatus="BLOCKED", mergeCommit={"oid": "abc1234" + "0" * 33}), **(pr or {}))) @@ -1673,8 +1728,7 @@ def auto_merge(self, s, after, repo=None, pr=None, code=0): def test_auto_merge_refuses_running_checks_that_nothing_on_github_waits_for(self): with Sandbox() as s: s.branch("feat/invoice") - s.gh.on(["repo", "view"], {"squashMergeAllowed": True, "viewerDefaultMergeMethod": "SQUASH", - "autoMergeAllowed": True}) + s.gh.on(["repo", "view"], {"squashMergeAllowed": True, "viewerDefaultMergeMethod": "SQUASH"}) s.gh.on(["pr", "merge"], "") for state in ("CLEAN", "UNSTABLE", "HAS_HOOKS", "UNKNOWN"): with self.subTest(state): @@ -1687,10 +1741,24 @@ def test_auto_merge_refuses_running_checks_that_nothing_on_github_waits_for(self self.assertEqual(s.gh.called("pr", "merge"), []) self.assertEqual(s.execs, []) # the gh gate ran no gh pr merge either + # gh's repo view has no auto-merge field, so devkit reads the REST API's allow_auto_merge; when it cannot, it + # says so and merges nothing rather than guessing. + def test_auto_merge_reads_the_rest_setting_and_merges_nothing_when_it_cannot(self): + with Sandbox() as s: + s.branch("feat/invoice") + self.auto_merge(s, after={"state": "OPEN", "autoMergeRequest": {"enabledAt": "2026-11-18T00:00:00Z"}}) + self.assertTrue(s.gh.called("api", "repos/acme/widget")) + s.gh.routes = [r for r in s.gh.routes if r[0] != ["api", "repos/acme/widget"]] + s.gh.calls.clear() + rc, out, err = dev("pr", "merge", "7", "--auto") + self.assertEqual(rc, 1, out + err) + self.assertIn("cannot tell whether the repository allows auto-merge", err) + self.assertEqual(s.gh.called("pr", "merge"), []) + def test_auto_merge_refuses_a_repository_that_does_not_allow_it(self): with Sandbox() as s: s.branch("feat/invoice") - _, err = self.auto_merge(s, after={"state": "OPEN"}, repo={"autoMergeAllowed": False}, code=2) + _, err = self.auto_merge(s, after={"state": "OPEN"}, repo={"allow_auto_merge": False}, code=2) self.assertIn("the repository does not allow auto-merge", err) self.assertEqual(s.gh.called("pr", "merge"), [])