diff --git a/.github/fork-ci-tests.txt b/.github/fork-ci-tests.txt index 7ff70516a55cd..c7b10d71ed555 100644 --- a/.github/fork-ci-tests.txt +++ b/.github/fork-ci-tests.txt @@ -125,6 +125,10 @@ fork-kit/common/tests/kit_install.test.py ~125s unittest fork-kit/common/tests/machine_file.test.py unittest fork-kit/desk/tests/install.test.py ~103s unittest fork-kit/desk/tests/windows.test.py ~65s unittest +fork-kit/gardener/tests/checks.test.py unittest +fork-kit/gardener/tests/install.test.py unittest +fork-kit/gardener/tests/report.test.py unittest +fork-kit/gardener/tests/run.test.py ~30s unittest fork-kit/golive/tests/back.test.py ~100s unittest fork-kit/golive/tests/check.test.py unittest fork-kit/golive/tests/contract.test.py unittest diff --git a/.github/scripts/fork-ci-release.test.py b/.github/scripts/fork-ci-release.test.py index 270aa5ee149ac..2ee63a5f1262c 100644 --- a/.github/scripts/fork-ci-release.test.py +++ b/.github/scripts/fork-ci-release.test.py @@ -425,7 +425,7 @@ def load(rel, name): loader.exec_module(mod) return mod failed = [] -if how == 'kit_install': # agent-guards, cleaner, golive, schedule-kick, update-policy: check_options' file part +if how == 'kit_install': # agent-guards, cleaner, gardener, golive, schedule-kick, update-policy: check_options' file part m = load(installer, 'kit_installer') inst, missing = m.INSTALLER, [] for rel in inst.source_files(): @@ -469,6 +469,7 @@ def load(rel, name): # passes: the kit's folder or the release's top folder) KITS = {"agent-guards": ("kit_install", "sbin/agent-guards-install", "kit"), "cleaner": ("kit_install", "sbin/fork-cleaner-install", "kit"), + "gardener": ("kit_install", "sbin/gardener-install", "kit"), "golive": ("kit_install", "sbin/t3-golive-install", "kit"), "schedule-kick": ("kit_install", "sbin/schedule-kick-install", "kit"), "update-policy": ("kit_install", "sbin/update-policy-install", "kit"), diff --git a/fork-ci/actions/pr-queue/review_judge.test.py b/fork-ci/actions/pr-queue/review_judge.test.py index c75c622bec678..80cb8405d4a9c 100644 --- a/fork-ci/actions/pr-queue/review_judge.test.py +++ b/fork-ci/actions/pr-queue/review_judge.test.py @@ -549,8 +549,8 @@ def test_a_wrong_list_is_refused(self): # report must say to count), gh-apps keeps the gate App's key and mints its tokens (the gate-trust design). The # other kits run machines and agents, and the merge gate reads none of them. GATE_KITS = ('gh-apps', 'review') -OTHER_KITS = ('.gitignore', 'README.md', 'agent-guards', 'cleaner', 'common', 'desk', 'golive', 'heavy', 'model-guard', - 'pc-agents', 'schedule-kick', 'update-policy') +OTHER_KITS = ('.gitignore', 'README.md', 'agent-guards', 'cleaner', 'common', 'desk', 'gardener', 'golive', 'heavy', + 'model-guard', 'pc-agents', 'schedule-kick', 'update-policy') class ForkConfig(unittest.TestCase): diff --git a/fork-kit/README.md b/fork-kit/README.md index 4937501e6b40d..9458b01c12ae9 100644 --- a/fork-kit/README.md +++ b/fork-kit/README.md @@ -18,6 +18,7 @@ Every kit follows the same pattern: | [agent-guards](agent-guards/README.md) | Claude Code hooks that guard every agent on a machine: no disabling Actions, no piped capacity check, a memory index in budget, no stop with a background command, agent slots (Linux) | | [cleaner](cleaner/README.md) | `fork-cleaner`: free disk space by rules (`worktrees` with merged branches, `tmp`, `agent-scratch`, `docker`; `compress-cold` and `dedupe` delete no content) and never what could be needed; daily timer (Linux, systemd) | | [desk](desk/README.md) | A desktop's side of a fork fleet desk pool: runner users, walls, desk agent; one folder (Linux, WSL2) | +| [gardener](gardener/README.md) | `gardener`: each project's checks once a day (small scripts, JSON-line findings; general ones shipped, project ones by path), one report issue per project updated in place; report only (Linux, systemd) | | [gh-apps](gh-apps/README.md) | GitHub App tokens for agents through `gh-as`, without giving agents the keys (Linux) | | [golive](golive/README.md) | Move a T3 boot service to a new build with a cold copy first, and back; installs from `ci-release` (Linux) | | [heavy](heavy/README.md) | `heavy `: run builds and tests in a capped slice, stop what they leave behind (Linux, systemd) | @@ -29,7 +30,7 @@ Every kit follows the same pattern: [common](common/README.md) is code the kits share, copied into each kit's version folder: the loader of the one private machine file (`/etc/fork-kit/machine.json`) where the facts of one machine live, and the installer and -bootstrap of the agent-guards, cleaner, golive, schedule-kick and update-policy kits. +bootstrap of the agent-guards, cleaner, gardener, golive, schedule-kick and update-policy kits. [review](review/README.md) is the one kit with no installer: a skill, docs and tools an agent uses from a checkout of the fork, beside the merge gate whose parser it imports. diff --git a/fork-kit/common/README.md b/fork-kit/common/README.md index 429760e09a57c..0628361438d58 100644 --- a/fork-kit/common/README.md +++ b/fork-kit/common/README.md @@ -72,7 +72,7 @@ standard library. ## The installer -`kit_install.py` is the installer of the agent-guards, cleaner, golive, schedule-kick and update-policy kits; each kit's `sbin/-install` is a small +`kit_install.py` is the installer of the agent-guards, cleaner, gardener, golive, schedule-kick and update-policy kits; each kit's `sbin/-install` is a small subclass that names its paths, links, files and modules, and adds its own steps. `install --source FOLDER --sha SHA`, as root: @@ -108,7 +108,7 @@ root's `uninstall` can then wait there forever, with both locks held (as it can process whose memory is FUSE-backed). It fails safe: nothing is removed yet, and Ctrl-C ends it and frees the locks. Updates go through the bootstrap. -`bootstrap.sh --kit agent-guards|cleaner|golive|schedule-kick|update-policy --repo OWNER/REPO --sha SHA [kit options]` checks the commit is on the protected +`bootstrap.sh --kit agent-guards|cleaner|gardener|golive|schedule-kick|update-policy --repo OWNER/REPO --sha SHA [kit options]` checks the commit is on the protected release branch, downloads exactly that commit and runs the kit's installer; it passes on only the kit's own options. ## Tests diff --git a/fork-kit/common/bootstrap.sh b/fork-kit/common/bootstrap.sh index f3f0228c98d04..63f9604ddff38 100644 --- a/fork-kit/common/bootstrap.sh +++ b/fork-kit/common/bootstrap.sh @@ -7,6 +7,7 @@ # KIT and its options (each kit's sbin/*-install says what they do): # agent-guards fork-kit/agent-guards/sbin/agent-guards-install [--settings | --no-settings] # cleaner fork-kit/cleaner/sbin/fork-cleaner-install [--timer | --no-timer] +# gardener fork-kit/gardener/sbin/gardener-install [--timer | --no-timer] # golive fork-kit/golive/sbin/t3-golive-install (none) # schedule-kick fork-kit/schedule-kick/sbin/schedule-kick-install [--timer | --no-timer] # update-policy fork-kit/update-policy/sbin/update-policy-install [--timer | --no-timer] [--force] @@ -39,14 +40,15 @@ done case "$kit" in agent-guards) installer='sbin/agent-guards-install' ;; cleaner) installer='sbin/fork-cleaner-install' ;; + gardener) installer='sbin/gardener-install' ;; golive) installer='sbin/t3-golive-install'; [ -z "$opt" ] || die "$opt is not an option of --kit golive" ;; schedule-kick) installer='sbin/schedule-kick-install' ;; update-policy) installer='sbin/update-policy-install' ;; - *) die "--kit must be one of: agent-guards cleaner golive schedule-kick update-policy" ;; + *) die "--kit must be one of: agent-guards cleaner gardener golive schedule-kick update-policy" ;; esac [ -z "$force" ] || [ "$kit" = update-policy ] || die "--force is not an option of --kit $kit" case "$kit:$opt" in - agent-guards:--timer|agent-guards:--no-timer|cleaner:--*settings|schedule-kick:--*settings|update-policy:--*settings) + agent-guards:--timer|agent-guards:--no-timer|cleaner:--*settings|gardener:--*settings|schedule-kick:--*settings|update-policy:--*settings) die "$opt is not an option of --kit $kit" ;; esac printf '%s\n' "$repo" | grep -Eqx '[A-Za-z0-9][A-Za-z0-9-]{0,38}/[A-Za-z0-9._-]{1,100}' || die "--repo must be OWNER/NAME" diff --git a/fork-kit/common/machine.example.json b/fork-kit/common/machine.example.json index 722549c771b20..067fa9a0b437d 100644 --- a/fork-kit/common/machine.example.json +++ b/fork-kit/common/machine.example.json @@ -22,6 +22,36 @@ }, "disk": { "floorGb": 25, "path": "~" } }, + "gardener": { + "stateDir": "~/.local/state/gardener", + "gh": "gh", + "projects": [ + { + "name": "example", + "repo": "example-owner/example-repo", + "reportRepo": "example-owner/example-repo", + "root": "/srv/example/repo", + "schedule": "03:00", + "quietHours": "02:00-07:00", + "timeZone": "Europe/London", + "model": { "endpoint": "http://127.0.0.1:8080/v1", "model": "example-local-model" }, + "checks": [ + { + "name": "context-budget", + "options": { + "files": { "AGENTS.md": 6000 }, + "memoryIndexes": ["~/.claude/memory/MEMORY.md"] + } + }, + { "name": "facts" }, + { "name": "worktrees", "options": { "staleDays": 14 } }, + { "name": "workflows-off", "options": { "ignore": ["old-deploy.yml"] } }, + { "name": "install-drift" }, + { "path": "/srv/example/bin/doc-check", "id": "docs", "timeoutSeconds": 120 } + ] + } + ] + }, "golive": { "home": "/srv/example/t3-home", "targetVersion": "0.0.0-example.fork.1", diff --git a/fork-kit/common/tests/kit_install.test.py b/fork-kit/common/tests/kit_install.test.py index 8922fbfa4059d..bd31692ee7366 100644 --- a/fork-kit/common/tests/kit_install.test.py +++ b/fork-kit/common/tests/kit_install.test.py @@ -15,6 +15,7 @@ KITS = { 'agent-guards': os.path.join(fx.FORK_KIT, 'agent-guards', 'sbin', 'agent-guards-install'), 'cleaner': os.path.join(fx.FORK_KIT, 'cleaner', 'sbin', 'fork-cleaner-install'), + 'gardener': os.path.join(fx.FORK_KIT, 'gardener', 'sbin', 'gardener-install'), 'golive': os.path.join(fx.FORK_KIT, 'golive', 'sbin', 't3-golive-install'), 'schedule-kick': os.path.join(fx.FORK_KIT, 'schedule-kick', 'sbin', 'schedule-kick-install'), 'update-policy': os.path.join(fx.FORK_KIT, 'update-policy', 'sbin', 'update-policy-install'), @@ -615,6 +616,10 @@ class Cleaner(Contract, fx.FakeHost): KIT_DIR, INSTALLER = os.path.join(fx.FORK_KIT, 'cleaner'), KITS['cleaner'] +class Gardener(Contract, fx.FakeHost): + KIT_DIR, INSTALLER = os.path.join(fx.FORK_KIT, 'gardener'), KITS['gardener'] + + class Golive(Contract, fx.FakeHost): KIT_DIR, INSTALLER = os.path.join(fx.FORK_KIT, 'golive'), KITS['golive'] @@ -638,7 +643,7 @@ def refused(self, *args): def test_the_kit_is_one_it_knows(self): self.assertEqual(self.refused('--repo', 'a/b', '--sha', SHA1), 'fork-kit-bootstrap: --kit must be one of: ' - 'agent-guards cleaner golive schedule-kick update-policy') + 'agent-guards cleaner gardener golive schedule-kick update-policy') self.assertIn('--kit must be one of', self.refused('--kit', '../heavy', '--repo', 'a/b', '--sha', SHA1)) self.assertEqual(self.refused('--repo', 'a/b', '--sha', SHA1, '--kit'), 'fork-kit-bootstrap: --kit needs a value') @@ -646,7 +651,7 @@ def test_the_kit_is_one_it_knows(self): def test_only_the_kit_options_are_passed_on(self): """Nothing reaches the installer unchecked: a second --source would install a folder the release check never saw.""" - for kit in ('agent-guards', 'cleaner', 'golive', 'schedule-kick', 'update-policy'): + for kit in ('agent-guards', 'cleaner', 'gardener', 'golive', 'schedule-kick', 'update-policy'): for extra in (['--source', '/elsewhere'], ['--x']): with self.subTest(kit=kit, extra=extra): err = self.refused('--kit', kit, '--repo', 'a/b', '--sha', SHA1, *extra) @@ -659,11 +664,12 @@ def test_only_the_kit_options_are_passed_on(self): self.assertEqual(self.refused(timer, '--kit', 'golive', '--repo', 'a/b', '--sha', SHA1), f'fork-kit-bootstrap: {timer} is not an option of --kit golive') for kit, opt in (('agent-guards', '--timer'), ('agent-guards', '--no-timer'), ('cleaner', '--settings'), - ('schedule-kick', '--no-settings'), ('golive', '--settings'), ('update-policy', '--settings')): + ('schedule-kick', '--no-settings'), ('golive', '--settings'), ('update-policy', '--settings'), + ('gardener', '--settings')): with self.subTest(kit=kit, opt=opt): self.assertEqual(self.refused('--kit', kit, opt, '--repo', 'a/b', '--sha', SHA1), f'fork-kit-bootstrap: {opt} is not an option of --kit {kit}') - for kit in ('agent-guards', 'cleaner', 'golive', 'schedule-kick'): # --force: update-policy's only + for kit in ('agent-guards', 'cleaner', 'gardener', 'golive', 'schedule-kick'): # --force: update-policy's only with self.subTest(kit=kit, opt='--force'): self.assertEqual(self.refused('--kit', kit, '--force', '--repo', 'a/b', '--sha', SHA1), f'fork-kit-bootstrap: --force is not an option of --kit {kit}') @@ -671,6 +677,7 @@ def test_only_the_kit_options_are_passed_on(self): for args in (['--kit', 'cleaner', '--timer'], ['--no-timer', '--kit', 'cleaner'], ['--kit', 'golive'], ['--kit', 'update-policy', '--timer', '--force'], ['--kit', 'schedule-kick', '--timer'], ['--kit', 'update-policy', '--timer'], + ['--kit', 'gardener', '--timer'], ['--kit', 'agent-guards', '--settings'], ['--no-settings', '--kit', 'agent-guards']): with self.subTest(args=args): @@ -782,7 +789,7 @@ def test_only_the_kit_options_are_passed_on(self): 'bootstrap', ' [ -z "$opt" ] || die "$opt is not an option of --kit golive" ;;', ' ;;', 'test_only_the_kit_options_are_passed_on'), 'bootstrap: an unknown kit is refused': ( - 'bootstrap', ' *) die "--kit must be one of: agent-guards cleaner golive schedule-kick update-policy" ;;', ' *) installer=x ;;', + 'bootstrap', ' *) die "--kit must be one of: agent-guards cleaner gardener golive schedule-kick update-policy" ;;', ' *) installer=x ;;', 'test_the_kit_is_one_it_knows'), 'bootstrap: --settings is kept, nothing after it passed on': ( 'bootstrap', ' --settings|--no-settings) opt="$1"; shift ;;', ' --settings|--no-settings) break ;;', diff --git a/fork-kit/gardener/README.md b/fork-kit/gardener/README.md new file mode 100644 index 0000000000000..e6c4300843ce4 --- /dev/null +++ b/fork-kit/gardener/README.md @@ -0,0 +1,272 @@ +# gardener: a daily report of what has drifted, one issue per project + +Agent-run projects drift in small ways nobody is watching: instruction files grow past their budget, a state table +goes stale, merged worktrees and branches pile up, a workflow gets switched off, an installed kit no longer matches +its release. `gardener` runs a list of checks for each project once a day and writes what they find to one report +issue per project, updated in place. It reports; it changes nothing, unless a check's config says `"fix": true` +(and then only what that check documents as its fix). + +Linux, plain Python 3 standard library. A systemd user timer runs it every hour; each project runs once a day, in +its own window. + +## What one run does + +For each project in the config (or the one `--project` names): + +1. **Done today?** The project's state file holds a done marker (the project's day, in its time zone; see + [Window](#window)). If it is today, nothing happens: no check, no API call, unless the day's report issue is + still to be written (then that alone is tried again). `--force` runs it again. +2. **Window** (only with `--timer`, which the timer passes): see [Window](#window). +3. **Checks**, one after another, each with its own timeout. A check that fails in any way becomes exactly one + finding and the next check still runs (see [Checks](#checks)). +4. **Judgment** (optional): with a `model` configured, the findings go to a local model; see + [Judgment](#judgment). +5. **Report**: the full report is saved as `report.md` and the issue's part as `issue.md` in the state folder. + Then the done marker. Then the report issue is written (see [Report issue](#report-issue)); if that fails, only + the issue is tried again on later ticks, at most 3 times a day; the checks and the model do not run again. + +`gardener run --dry-run` runs the checks and prints both reports (the issue's part and the local one) instead. It writes nothing (no issue, no state, no +done marker), ignores the done marker and the window, and runs checks set to fix with fix off. `gardener check` +reads the config and lists each project and its checks; it runs nothing. + +Exit codes: 0 fine (also: skipped, already done), 1 a project's run or report issue failed, 2 the config is +refused. + +### Window + +Without `quietHours` the project's day is its local date, and the timer runs it once a day, after the `schedule` +time if one is set (else at the first tick of the day). With `quietHours` (which may wrap past midnight) the day +starts when they start: with `22:00-06:00`, 01:00 on the 24th still belongs to the 23rd's window, so one window is +one run, and a tick missed at 23:00 runs at 01:00. The timer runs it only inside them, and a `schedule` inside them +holds it until that time (one outside them is not used). + +## Config + +The machine file's `"gardener"` section (`/etc/fork-kit/machine.json`, root-owned; [common](../common/README.md)). +A key it does not know, or a value it cannot use, refuses the whole section: a typo is never ignored. Project facts +(repositories, folders, project checks) live only here, never in the kit. An example with placeholder names: + +```json +"gardener": { + "stateDir": "~/.local/state/gardener", + "gh": "gh", + "projects": [{ + "name": "example", + "repo": "OWNER/REPO", + "reportRepo": "OWNER/REPO", + "root": "/srv/example/repo", + "schedule": "03:00", + "quietHours": "02:00-07:00", + "timeZone": "Europe/London", + "model": { "endpoint": "http://127.0.0.1:8080/v1", "model": "example-local-model" }, + "checks": [ + { "name": "context-budget", "options": { "files": { "AGENTS.md": 6000 } } }, + { "name": "worktrees", "fix": true }, + { "path": "/srv/example/bin/doc-check", "id": "docs", "timeoutSeconds": 120 } + ] + }] +} +``` + +| Key | Default | Meaning | +| ------------------------- | -------------------------- | --------------------------------------------------------------------------------------------------- | +| `stateDir` | `~/.local/state/gardener` | state folder of the user that runs it; one subfolder per project | +| `gh` | `gh` | the `gh` command (a name on PATH or an absolute path), with that user's login | +| `projects[].name` | required | lower case letters, digits, `.`, `_`, `-`; names the state folder and the marker | +| `repo` | none | `OWNER/REPO` the checks look at (workflows-off's default) | +| `reportRepo` | none | `OWNER/REPO` of the report issue; none: `report.md` in the state folder only | +| `root` | none | the project's folder: each check runs in it; relative check options are inside it | +| `schedule` | none | `HH:MM`: the timer runs the project after this local time; none: any time | +| `quietHours` | none | `HH:MM-HH:MM` (may wrap past midnight): the timer runs it only inside them | +| `timeZone` | the machine's | for the day and the window | +| `model` | none | `{endpoint, model, timeoutSeconds 120, maxFiles 5, maxFileBytes 20000}` | +| `checks[].name` | | a general check of this kit (below) | +| `checks[].path` | | a project's own check: an absolute path or `~/...` (exactly one of the two) | +| `checks[].id` | the name, or the file name | names the check in the report; unique per project | +| `checks[].options` | `{}` | given to the check as it is | +| `checks[].fix` | `false` | the check may make its documented fix | +| `checks[].publicText` | `false` | a project's own check: its text and fix (masked) go to the issue; see [Report issue](#report-issue) | +| `checks[].timeoutSeconds` | `300` | 1 to 3600; then the check and everything it started is stopped | + +Paths starting with `~/` are in the home of the user that runs the gardener. + +## Checks + +A check is any executable. It gets one JSON object on stdin: + +```json +{ + "version": 1, + "project": { "name": "example", "repo": "OWNER/REPO", "root": "/srv/example/repo" }, + "check": "docs", + "options": {}, + "fix": false, + "today": "2026-11-23", + "gh": "gh" +} +``` + +It runs in the project root, in a process group of its own. It prints one finding per line on stdout and nothing +else (notes go to stderr), and exits 0: + +```json +{ "id": "docs.stale", "severity": "warn", "where": "docs/setup.md", "text": "...", "fix": "..." } +``` + +`id`, `severity` (`error`, `warn` or `info`) and `text` are required; `where` (a path relative to the root, or +`OWNER/REPO: path`, ...) and `fix` (what a person does about it) are optional. Nothing else. An `id` is a letter or +digit, then up to 99 letters, digits, `.`, `_` or `-`. Python checks can use `gardener.contract.read_context()` +and `emit()`. + +A check that cannot start, exits non-zero, runs past its timeout, prints a line that is not a finding or more than +256 KiB becomes **one** finding `gardener.check-failed` (severity error) naming why; nothing else it printed is +used. Its output is read as it comes: past 256 KiB, or past its timeout, the check and everything it started is +stopped, so a check that prints without end costs no memory. Only the last 4 KiB of its stderr are kept, for the +local report. An error inside the gardener itself on one check is one such finding too, and the next check runs. +More than 200 findings are cut to 200 and one `gardener.more-findings`. + +### General checks + +All report only, and none needs root. Options as in each script's header. + +- **context-budget**: instruction files (`files`: `{path: bytes}`), memory indexes (`memoryIndexes`: size, + `indexMaxChars` 6000, lines over `indexMaxLine` 160, entries whose file is missing, files the index does not + list) and skills (`skillDirs`: each `*/SKILL.md` against `skillMaxBytes` 8000; a missing or broken one is a + warning). Near a budget (`warnRatio` 0.85) + is a note. +- **facts**: `facts --check --no-records` of the [agent-guards](../agent-guards/README.md) kit, in the project + root: the machine's state tables and this project's, never `--all` (other projects' rows may be private). The + issue names rows only of a table inside the repository; the machine's tables are only counted. Not installed: + one note. +- **worktrees**: git worktrees and local branches (`repos`, default the root) that are merged into the base + (`base`, default `origin/HEAD`, else `origin/main`, else `main`) or whose upstream is gone, and unmerged worktrees + whose last commit is older than `staleDays` (14). `ignore`: branch patterns. No fetch: "merged" is as of the + last fetch. A branch with no work of its own yet (a worktree just started, also one whose upstream is the base + itself) is not "merged". Fix hints quote every name and keep a leading `~/` expandable. With `fix`, it runs + `git worktree prune` (records of worktrees whose folder is gone) and nothing + else; removing worktrees and branches is the [cleaner](../cleaner/README.md) kit's job, or a person's. +- **workflows-off**: GitHub Actions workflows of `repos` (default the project's `repo`) that are switched off, by + hand or for inactivity; `ignore` lists workflow files meant to be off. One API call per repository. Never fixes: + a workflow someone switched off is never switched on by a tool. +- **install-drift**: each fork kit's install record (`/etc//installed.tsv`) against the files and links on + the machine, as the user that runs it (paths it cannot read are one note, not drift). With `release` (a commit), + kits on another release. + +## Report issue + +One issue per project in `reportRepo`, titled `Gardener report: NAME`. The report repository may be public, so the +issue is built from an allow-list and the full report stays on the machine (`report.md` in the state folder; the +issue says so): + +- Per finding: its severity, check, id, and its `where` only when that is a path inside the project's repository + (relative) or `OWNER/REPO: path`; its text and fix with what still looks like a local name (a path, also a + Windows drive or `\\server` path, URL, IPv4 or IPv6 address, e-mail or `user@host`, a home folder encoded in a + folder name) masked. The project root and home folder are replaced only as whole folders (`/srv/app` is not + part of `/srv/app2`). +- The text and fix of a project's own check (`path`) are shown only with `"publicText": true`; otherwise the + issue shows its id, count and `where`, and the text stays in the local report. General checks are shown. +- A finding whose `where` is outside the repository, or that has none, is only counted per check + (``), without its id. The gardener's own findings are shown, with its fixed words. +- **Counts only**: when the report repository is another repository and not known to be private, and the project + repository is private (or its visibility cannot be read, or the project has no `repo`), the issue shows only + counts per severity and check, and no judgment. +- A failed check shows its id and why in fixed words (`exited with code 1`); what it printed on stderr goes to the + local report only. +- Notes are the gardener's own words; the model's endpoint is never shown (`model reachable` or `unreachable`). +- The judgment is masked like the rest. + +A check must still not print secrets. Check authors: with `publicText`, everything your check prints in `text` +and `fix` (host names, user names, paths not masked above) may be published in the issue. + +The issue body holds a hidden marker line, ``; everything from the marker down is +rewritten on each run (a table of findings by severity, notes, the judgment), and text a person writes above the +marker is kept. + +- **Missing** (never made, deleted, moved): a search by the title, then by the marker, finds an open one, or a new + one is opened. +- **Closed**: left closed; a new one is opened. Closing the issue is how a person says "start over". +- **Marker edited away by hand**: that issue is no longer the report and is left alone; a new one is opened. +- **Two open issues with the marker**: the oldest is used, always the same one. + +The whole body (a person's text above the marker too) is kept under GitHub's size limit: findings that do not fit +are counted, a person's text is cut with a note when it is too long, and `report.md` has them all. + +API calls per project per run: at most one issue read (the number the state remembers), up to two searches (by +title, then by marker; only when that read does not give the open report issue) and one write; checks make their +own (workflows-off: one per repository). When the report repository is not the project repository, up to two +reads of their visibility (`repos/OWNER/REPO`), also in a dry run; a failed read only means counts only. Any other +GitHub error, a rate limit too, fails that project's report with exit 1. The done marker is already written, so +the checks do not run again: the next ticks try the issue alone, at most 3 times a day; after that, the next day's +run. There are no retries inside a run. + +## Judgment + +Optional, and phase 1 is the interface only. With `model` set, the findings as the issue shows them (nothing from +outside the repository) and a few of the files they name (`maxFiles`, each cut to `maxFileBytes`, only files git +tracks in the root: never an ignored or untracked file such as a local `.env`) go to the endpoint's OpenAI-style +`/chat/completions` in one request. The answer goes into the report under "Judgment", masked like the rest of the +issue. An endpoint that is not reachable, or answers with an error, nonsense or not HTTP at all, is a note +(`model unreachable`) and the run goes on. The endpoint is never shown. There is no fallback to a paid model, and +the model never sees the whole repository. + +## State: runs again, stops half-way, old or empty state + +`//`, mode 700: `state.json` (`doneDay`, the report `issue` number, `lastRun`, the finding count, +`reportPending`, `reportTries` and the `reportRepo` it last reported to), `report.md` (the last full report), +`issue.md` (the last issue part) and +`lock`. Each file is written to a temporary file and renamed into place. + +- **Runs again** the same day: the done marker; nothing runs and no API call. A changed `reportRepo` runs the + day again and writes to the new repository (the old issue number is dropped). `--force` runs it again and updates + the same issue. Two runs at once: the second finds the lock held and skips the project. +- **Stopped half-way**: stopped before the done marker, the run starts again on the next tick. Stopped after it, + the next tick sends the saved `issue.md` alone (`reportPending`). The issue number is saved once the issue is + written, and the title and marker searches find it even if that save was lost, so a stop never makes a second + issue. +- **Old, broken or missing state:** read as empty, with a note in the report; the issue is found again by a + search. A state file of a **newer** version (a downgraded kit) is refused and kept: that project fails with + exit 1 until the kit is upgraded again (`--dry-run` still runs). +- **Host off for days:** one run for today; days missed are not made up. +- **One project fails** (a broken state folder, a GitHub error, any error inside the gardener): the others still + run; the exit code is 1. + +## Install + +As root, from a commit on the fork's protected `ci-release` branch (the shared +[bootstrap](../common/bootstrap.sh) refuses anything else). Placeholders in CAPITALS. + +``` +curl -fsSL https://raw.githubusercontent.com/FORK_OWNER/FORK/RELEASE_SHA/fork-kit/common/bootstrap.sh -o /root/fork-kit-bootstrap.sh +sh /root/fork-kit-bootstrap.sh --kit gardener --repo FORK_OWNER/FORK --sha RELEASE_SHA --timer +``` + +Installing never enables the timer for anyone. Add the `"gardener"` section to the machine file, then as the user +that runs it (with a `gh` login that can write issues to each `reportRepo`): + +``` +gardener check +gardener run --dry-run +systemctl --user daemon-reload && systemctl --user enable --now gardener.timer +loginctl enable-linger "$USER" # as root, if the user is not always logged in: user timers need it +``` + +Files: `/usr/local/libexec/gardener/versions//` (code, checks, with `MANIFEST.sha256`), the link `current`, +`/usr/local/bin/gardener`, `/usr/local/sbin/gardener-install`, `/etc/gardener/config.json` (only whether the timer +units are installed) and `installed.tsv`, and with `--timer` the user units `gardener.service` and `gardener.timer` +in `/etc/systemd/user/` (hourly, `Nice=10`, idle I/O, `UMask=0077`). `gardener-install self-check` reports drift. +Upgrade: the bootstrap with the new sha. Remove: first each user runs `systemctl --user disable --now +gardener.timer` (the uninstall says so before it removes the units), then `gardener-install uninstall` as root. +State folders and report issues stay. + +## Tests + +`tests/*.test.py`, run with `python3 -I -B fork-kit/gardener/tests/NAME.test.py` from the repository root: a fake +GitHub (in the process, and a fake `gh` script), a local fake model over HTTP, a fixed clock, temporary git +repositories and a temporary folder. No root, no systemd, no network. `RedCheck` in each file breaks each rule in a +copy of the code and shows its test then fails. + +## General vs project + +General (this kit): the runner, the check contract, the report issue, the state, the general checks and the timer. +Project (the machine file only): which projects, their repositories and folders, their schedule, their budgets and +their own checks, given by path. The kit never names a project or a project's check. diff --git a/fork-kit/gardener/bin/gardener b/fork-kit/gardener/bin/gardener new file mode 100755 index 0000000000000..0a3874bac2439 --- /dev/null +++ b/fork-kit/gardener/bin/gardener @@ -0,0 +1,8 @@ +#!/usr/bin/python3 -IB +"""gardener: the gardener kit (lib/gardener). Runs each project's checks once a day and keeps one report issue. +-I: no environment variable, user site folder or current folder changes what Python loads. The code is loaded +only from this file's real folder.""" +import os, sys +sys.path.insert(0, os.path.join(os.path.dirname(os.path.dirname(os.path.realpath(__file__))), 'lib')) +from gardener import cli # noqa: E402 +sys.exit(cli.main(sys.argv[1:])) diff --git a/fork-kit/gardener/checks/context-budget b/fork-kit/gardener/checks/context-budget new file mode 100755 index 0000000000000..2daa318e8e9c3 --- /dev/null +++ b/fork-kit/gardener/checks/context-budget @@ -0,0 +1,89 @@ +#!/usr/bin/python3 -IB +"""context-budget: the text every agent session loads, against its budgets (report only; it never edits). + +Options (paths: relative to the project root, absolute, or "~/"): + files {path: byte budget} of instruction files (AGENTS.md, CLAUDE.md, ...); a missing one is a warning + memoryIndexes [path of a memory index (MEMORY.md)]: its size, its long lines, entries whose file is missing, + memory files of its folder that it does not list + indexMaxChars 6000 indexMaxLine 160 + skillDirs [folder]: each /*/SKILL.md against skillMaxBytes (8000) + warnRatio 0.85: at or over this share of a budget is a note +""" +import glob, os, re, sys +sys.path.insert(0, os.path.join(os.path.dirname(os.path.dirname(os.path.realpath(__file__))), 'lib')) +from gardener.contract import emit, read_context # noqa: E402 + +ctx = read_context() +opt = ctx['options'] +root = ctx['project']['root'] or os.getcwd() +ratio = float(opt.get('warnRatio', 0.85)) + + +def full(p): + p = os.path.expanduser(p) if p.startswith('~/') else p + return p if os.path.isabs(p) else os.path.join(root, p) + + +def size_check(kind, path, size, budget): + if size > budget: + emit('context-budget.over', 'warn', f'{kind}: {size} bytes, over its budget of {budget}', path, + 'move what only some tasks need into a skill or a doc, linked by path') + elif size >= budget * ratio: + emit('context-budget.near', 'info', f'{kind}: {size} bytes, {size * 100 // budget}% of its budget of ' + f'{budget}', path) + + +for path, budget in sorted((opt.get('files') or {}).items()): + p = full(path) + try: + size = os.path.getsize(p) + except OSError: + emit('context-budget.missing', 'warn', 'instruction file is missing', path, 'remove it from the options, ' + 'or put it back') + continue + size_check('instruction file', path, size, int(budget)) + +max_chars, max_line = int(opt.get('indexMaxChars', 6000)), int(opt.get('indexMaxLine', 160)) +for path in opt.get('memoryIndexes') or []: + p = full(path) + try: + with open(p, encoding='utf-8', errors='replace') as f: + text = f.read() + except OSError: + emit('context-budget.missing', 'warn', 'memory index is missing', path) + continue + if len(text) > max_chars: + emit('context-budget.over', 'warn', f'memory index: {len(text)} characters, over {max_chars}', path, + 'fold or drop entries; a lesson a tool now enforces is deleted') + elif len(text) >= max_chars * ratio: + emit('context-budget.near', 'info', f'memory index: {len(text)} of {max_chars} characters', path) + long = [i + 1 for i, line in enumerate(text.split('\n')) if len(line) > max_line] + if long: + emit('context-budget.long-line', 'warn', f'memory index lines over {max_line} characters: ' + f'{", ".join(map(str, long[:10]))}', path) + folder = os.path.dirname(p) + linked = set(re.findall(r'\]\(([^)\s]+\.md)\)', text)) + files = {f for f in os.listdir(folder) if f.endswith('.md') and f != os.path.basename(p)} + for f in sorted(x for x in linked - files if '/' not in x): + emit('context-budget.missing-memory', 'warn', f'index entry points to a missing file {f}', path, + 'remove the entry or put the file back') + for f in sorted(files - linked): + emit('context-budget.orphan-memory', 'info', f'memory file {f} is not in the index', + os.path.join(os.path.dirname(path), f), 'add it to the index or delete it') + +skill_max = int(opt.get('skillMaxBytes', 8000)) +seen = set() +for d in opt.get('skillDirs') or []: + for s in sorted(glob.glob(os.path.join(full(d), '*', 'SKILL.md'))): + real = os.path.realpath(s) + if real in seen: + continue + seen.add(real) + rel = os.path.join(d, os.path.basename(os.path.dirname(s)), 'SKILL.md') + try: + size = os.path.getsize(real) + except OSError: # a broken link, or gone since the listing + emit('context-budget.missing', 'warn', 'skill file cannot be read (a broken link?)', rel, + 'fix or remove the skill folder') + continue + size_check('skill', rel, size, skill_max) diff --git a/fork-kit/gardener/checks/facts b/fork-kit/gardener/checks/facts new file mode 100755 index 0000000000000..c61220a3fbd7b --- /dev/null +++ b/fork-kit/gardener/checks/facts @@ -0,0 +1,40 @@ +#!/usr/bin/python3 -IB +"""facts: the state tables of the project root's folder, through the agent-guards kit's `facts --check` +(fork-kit/agent-guards/FACTS.md). Report only. + +It runs `facts --check --no-records` in the project root, so only the machine's tables and this project's are +read; never --all, whose output may name other, private projects. Each problem line is one finding, its `where` +the table file: the report issue counts the findings of a table outside the repository (the machine's) and names +rows only of the project's own tables; the local report names them all. + +Options: + command "facts": the facts command (a name on PATH or an absolute path) +""" +import os, re, shutil, subprocess, sys +sys.path.insert(0, os.path.join(os.path.dirname(os.path.dirname(os.path.realpath(__file__))), 'lib')) +from gardener.contract import emit, read_context # noqa: E402 + +ctx = read_context() +cmd = ctx['options'].get('command') or 'facts' +exe = cmd if os.path.isabs(cmd) else shutil.which(cmd) +if not exe or not os.access(exe, os.X_OK): + emit('facts.not-installed', 'info', f'the facts command ({cmd}) is not installed here: tables not checked', + '', 'install the agent-guards kit, or drop this check') + sys.exit(0) +p = subprocess.run([exe, '--check', '--no-records'], cwd=ctx['project']['root'] or None, capture_output=True, + text=True, timeout=120, stdin=subprocess.DEVNULL) +if p.returncode not in (0, 1): + sys.exit(f'facts --check exited with {p.returncode}: {(p.stderr or p.stdout).strip()[-200:]}') +for line in p.stdout.splitlines(): + m = re.match(r'^facts check: (.*)$', line) + if not m: + continue + text = m.group(1) + if re.match(r'^(OK \(|\d+ finding\(s\)$)', text): + continue + where, sep, rest = text.partition(': ') + if not sep or ' ' in where: + where, rest = '', text + stale = 'days old' in rest or 'in the future' in rest or 'no date' in rest + emit('facts.stale' if stale else 'facts.table', 'warn', rest, where, + 'check the thing, then edit its row (and its Updated date)' if stale else 'fix the table (facts --check)') diff --git a/fork-kit/gardener/checks/install-drift b/fork-kit/gardener/checks/install-drift new file mode 100755 index 0000000000000..05989cf5e26e8 --- /dev/null +++ b/fork-kit/gardener/checks/install-drift @@ -0,0 +1,80 @@ +#!/usr/bin/python3 -IB +"""install-drift: the fork kits installed on this machine against their own install records. Report only. + +Each kit's installer writes //installed.tsv: one row per installed path, `pathkindwant` (a +link and its target, or a file and its sha256; the gh-apps kit's rows have owner, group and mode in between). This +check reads every such record it can (as the user the gardener runs as) and reports, per kit, paths that differ from +it, the way `-install self-check` does without needing root. It also names the release each kit runs (its +`current` link) and, with "release" set, each kit on another one. + +Options: + etc "/etc": the folder of the kits' etc folders + kits [kit etc folder name] to read (default: every folder with an installed.tsv) + release a release commit (40 hex): kits on another release are reported +""" +import glob, hashlib, os, sys +sys.path.insert(0, os.path.join(os.path.dirname(os.path.dirname(os.path.realpath(__file__))), 'lib')) +from gardener.contract import emit, read_context # noqa: E402 + +ctx = read_context() +opt = ctx['options'] +etc = opt.get('etc') or '/etc' +prefix = os.environ.get('GARDENER_TEST_PREFIX', '') # tests only: every recorded path is read under this folder +release = opt.get('release') or '' +kits = opt.get('kits') or sorted(os.path.basename(os.path.dirname(p)) + for p in glob.glob(os.path.join(prefix + etc, '*', 'installed.tsv'))) + + +def sha256(path): + h = hashlib.sha256() + with open(path, 'rb') as f: + for block in iter(lambda: f.read(1 << 20), b''): + h.update(block) + return h.hexdigest() + + +for kit in kits: + record = os.path.join(etc, kit, 'installed.tsv') + try: + with open(prefix + record, encoding='utf-8') as f: + rows = [ln.rstrip('\n').split('\t') for ln in f if ln.strip() and not ln.startswith('#')] + except OSError as e: + emit('install-drift.no-record', 'warn', f'kit {kit}: its install record cannot be read ({e.strerror})', + record, f'install the kit again, or drop {kit} from this check\'s "kits"') + continue + changed, unread, running = [], 0, None + for row in rows: + if len(row) == 3: + path, kind, want = row + elif len(row) == 6: + path, kind, want = row[0], row[1], row[5] + else: + changed.append(f'bad row {"/".join(row)[:80]}') + continue + real = prefix + path + try: + if kind == 'link': + ok = os.readlink(real) == want + if path.endswith('/current') and '/versions/' in want: + running = os.path.basename(want) + elif kind == 'file': + ok = sha256(real) == want + else: + continue + except PermissionError: + unread += 1 + continue + except OSError: + ok = False + if not ok: + changed.append(path) + if changed: + emit('install-drift.changed', 'error', f'kit {kit}: {len(changed)} installed path(s) differ from its install ' + f'record: {", ".join(changed[:5])}' + (' ...' if len(changed) > 5 else ''), record, + f'run its installer\'s self-check as root, then install the release again with the bootstrap') + if unread: + emit('install-drift.unreadable', 'info', f'kit {kit}: {unread} path(s) could not be read as this user ' + '(not checked)', record) + if release and running and running != release: + emit('install-drift.old-release', 'warn', f'kit {kit} runs release {running[:12]}, not {release[:12]}', + record, 'install the release with the bootstrap') diff --git a/fork-kit/gardener/checks/workflows-off b/fork-kit/gardener/checks/workflows-off new file mode 100755 index 0000000000000..49c720f0c3815 --- /dev/null +++ b/fork-kit/gardener/checks/workflows-off @@ -0,0 +1,32 @@ +#!/usr/bin/python3 -IB +"""workflows-off: GitHub Actions workflows that are switched off (by hand or for inactivity). One `gh api` call per +repository. Report only, even with "fix": a workflow someone switched off on purpose is never switched on by a tool. + +Options: + repos [OWNER/REPO] (default: the project's repo) + ignore [workflow file name, e.g. "old-deploy.yml"] that are meant to be off +""" +import json, os, shlex, subprocess, sys +sys.path.insert(0, os.path.join(os.path.dirname(os.path.dirname(os.path.realpath(__file__))), 'lib')) +from gardener.contract import emit, read_context # noqa: E402 + +ctx = read_context() +opt = ctx['options'] +repos = opt.get('repos') or ([ctx['project']['repo']] if ctx['project']['repo'] else []) +ignore = set(opt.get('ignore') or []) +if not repos: + emit('workflows.no-repo', 'info', 'no repository to read: the project has no "repo" and the check no "repos"', + '') +for repo in repos: + p = subprocess.run([ctx['gh'], 'api', f'repos/{repo}/actions/workflows?per_page=100'], capture_output=True, + text=True, timeout=60, stdin=subprocess.DEVNULL) + if p.returncode != 0: + sys.exit(f'gh api repos/{repo}/actions/workflows: {(p.stderr or p.stdout).strip()[-200:]}') + for w in json.loads(p.stdout).get('workflows') or []: + state, path = w.get('state'), w.get('path') or '' + name = os.path.basename(path) + if state == 'active' or name in ignore or not path.startswith('.github/workflows/'): + continue + emit('workflows.off', 'warn', f'workflow {w.get("name") or name} is {state}', f'{repo}: {path}', + f'gh workflow enable {shlex.quote(name)} -R {shlex.quote(repo)} (or add it to this check\'s "ignore" ' + 'if it is meant to be off)') diff --git a/fork-kit/gardener/checks/worktrees b/fork-kit/gardener/checks/worktrees new file mode 100755 index 0000000000000..00b5ee37f9a20 --- /dev/null +++ b/fork-kit/gardener/checks/worktrees @@ -0,0 +1,165 @@ +#!/usr/bin/python3 -IB +"""worktrees: git worktrees and local branches that are merged, gone or stale. Reads git only, with no fetch: +"merged" is as of the repository's last fetch. A branch whose tip is in the base but that shows no work of its own +(no upstream, and a reflog with only its creation: a worktree just started) is not merged; it is a note only when +it was made more than staleDays ago. Fix hints quote every name (a branch name may hold `;`, `$`, ...). +With "fix": true it runs `git worktree prune` (which removes only the records of worktrees whose folder is gone) +and nothing else; removing a worktree or branch is the cleaner kit's job (fork-kit/cleaner), or a person's. + +Options: + repos [path]: the repositories (default: the project root); relative to the root, absolute or "~/" + base the branch merged means merged into (default: origin/HEAD, else origin/main, else main) + staleDays 14: a worktree whose last commit is older than this, and that is not merged, is a note; so is a + branch with no work of its own made longer ago + ignore [branch name patterns (fnmatch)] never reported +""" +import datetime, fnmatch, os, re, shlex, subprocess, sys +sys.path.insert(0, os.path.join(os.path.dirname(os.path.dirname(os.path.realpath(__file__))), 'lib')) +from gardener.contract import emit, read_context # noqa: E402 + +ctx = read_context() +opt = ctx['options'] +root = ctx['project']['root'] or os.getcwd() +today = datetime.date.fromisoformat(ctx['today']) +stale_days = int(opt.get('staleDays', 14)) +ignore = list(opt.get('ignore') or []) +q = shlex.quote + + +def qp(p): + """A path quoted for a shell, its leading ~/ left out of the quotes so the shell still expands it.""" + return '~/' + q(p[2:]) if p.startswith('~/') and len(p) > 2 else q(p) + + +def full(p): + p = os.path.expanduser(p) if p.startswith('~/') else p + return p if os.path.isabs(p) else os.path.join(root, p) + + +def git(repo, *args, ok=(0,)): + p = subprocess.run(['git', '-C', repo, *args], capture_output=True, text=True, timeout=60, + stdin=subprocess.DEVNULL, env=dict(os.environ, GIT_TERMINAL_PROMPT='0', LC_ALL='C')) + if p.returncode not in ok: + raise RuntimeError(f'git {" ".join(args)}: {(p.stderr or p.stdout).strip()[-200:]}') + return p + + +def base_of(repo): + if opt.get('base'): + return opt['base'] + p = git(repo, 'symbolic-ref', '-q', '--short', 'refs/remotes/origin/HEAD', ok=(0, 1)) + if p.returncode == 0 and p.stdout.strip(): + return p.stdout.strip() + for b in ('origin/main', 'main'): + if git(repo, 'rev-parse', '-q', '--verify', f'{b}^{{commit}}', ok=(0, 1)).returncode == 0: + return b + return None + + +def own_work(repo, branch, base_branch): + """(True, None) when the branch shows work of its own: an upstream other than the base branch (it was pushed; + `git worktree add -b NAME PATH origin/main` sets origin/main as the upstream, and that is no work), or a reflog + entry other than its creation (a commit, a reset, ...). Else (False, days since it was made, or None when + unknown).""" + up = git(repo, 'for-each-ref', '--format=%(upstream)', f'refs/heads/{branch}').stdout.strip() + up_branch = re.sub(r'^refs/(?:heads/|remotes/[^/]+/)', '', up) + if up and up_branch not in (base_branch, 'HEAD'): + return True, None + p = git(repo, 'reflog', 'show', '--date=unix', '--format=%gd%x09%gs', f'refs/heads/{branch}', ok=(0, 128)) + entries = [ln.split('\t', 1) for ln in p.stdout.splitlines() if '\t' in ln] + if any(not subject.startswith('branch: Created from') for _, subject in entries): + return True, None + m = re.search(r'@\{(\d+)\}', entries[-1][0]) if entries else None # the oldest entry is last + if not m: + return False, None + return False, (today - datetime.datetime.fromtimestamp(int(m.group(1)), datetime.timezone.utc).date()).days + + +def status(repo, branch, base, base_branch, gone): + """('merged', why), ('empty', days since made or None) or (None, None).""" + if branch in gone: + return 'merged', 'its upstream branch is gone' + if base and git(repo, 'merge-base', '--is-ancestor', f'refs/heads/{branch}', base, ok=(0, 1)).returncode == 0: + has, days = own_work(repo, branch, base_branch) + return ('merged', f'merged into {base}') if has else ('empty', days) + return None, None + + +def no_commits(days): + return days is None or days > stale_days + + +for r in opt.get('repos') or [root]: + repo = full(r) + if not os.path.isdir(repo): + emit('worktrees.repo-missing', 'warn', 'repository folder is missing', r, 'fix the check options') + continue + if git(repo, 'rev-parse', '--git-dir', ok=(0, 128)).returncode != 0: + emit('worktrees.not-a-repo', 'warn', 'not a git repository', r, 'fix the check options') + continue + base = base_of(repo) + base_branch = base.split('/', 1)[1] if base and base.startswith('origin/') else base + gone = set() + for line in git(repo, 'for-each-ref', '--format=%(refname:short)\t%(upstream:track)', 'refs/heads').stdout \ + .splitlines(): + name, _, track = line.partition('\t') + if track.strip() == '[gone]': + gone.add(name) + trees, cur = [], {} + for line in git(repo, 'worktree', 'list', '--porcelain').stdout.splitlines() + ['']: + if not line: + if cur: + trees.append(cur) + cur = {} + continue + key, _, value = line.partition(' ') + cur[key] = value or True + in_trees = set() + prunable = [t for t in trees if t.get('prunable')] + for i, t in enumerate(trees): + branch = t['branch'][len('refs/heads/'):] if isinstance(t.get('branch'), str) else None + if branch: + in_trees.add(branch) + if i == 0 or t.get('prunable') or not branch or branch == base_branch: + continue # the main worktree, a prunable record, a detached head + if any(fnmatch.fnmatchcase(branch, pat) for pat in ignore): + continue + kind, why = status(repo, branch, base, base_branch, gone) + lock = ' (locked)' if t.get('locked') else '' + if kind == 'merged': + emit('worktrees.merged', 'warn', f'worktree of branch {branch}: {why}{lock}', t['worktree'], + f'git -C {qp(r)} worktree remove {q(t["worktree"])} && git -C {qp(r)} branch -d {q(branch)}') + continue + if kind == 'empty': + if no_commits(why): + emit('worktrees.no-commits', 'info', f'worktree of branch {branch}: no commits of its own' + + (f', made {why} days ago' if why is not None else '') + lock, t['worktree'], + 'use it, or remove it if the work is dropped') + continue + p = git(repo, 'log', '-1', '--format=%ct', f'refs/heads/{branch}', ok=(0, 128)) + if p.returncode == 0 and p.stdout.strip(): + age = (today - datetime.datetime.fromtimestamp(int(p.stdout.strip()), datetime.timezone.utc).date()).days + if age > stale_days: + emit('worktrees.stale', 'info', f'worktree of branch {branch}: last commit {age} days ago, not ' + f'merged{lock}', t['worktree'], 'finish it, or remove it if the work is dropped') + if prunable: + if ctx['fix']: + git(repo, 'worktree', 'prune') + emit('worktrees.pruned', 'info', f'pruned {len(prunable)} worktree record(s) whose folder was gone', r) + else: + for t in prunable: + emit('worktrees.prunable', 'info', 'worktree record whose folder is gone', t['worktree'], + f'git -C {qp(r)} worktree prune') + for line in git(repo, 'for-each-ref', '--format=%(refname:short)', 'refs/heads').stdout.splitlines(): + branch = line.strip() + if not branch or branch in in_trees or branch == base_branch: + continue + if any(fnmatch.fnmatchcase(branch, pat) for pat in ignore): + continue + kind, why = status(repo, branch, base, base_branch, gone) + if kind == 'merged': + emit('branches.merged', 'info', f'branch {branch}: {why}', r, f'git -C {qp(r)} branch -d {q(branch)}') + elif kind == 'empty' and no_commits(why): + emit('branches.no-commits', 'info', f'branch {branch}: no commits of its own' + + (f', made {why} days ago' if why is not None else ''), r, + f'git -C {qp(r)} branch -d {q(branch)} (if it is not needed)') diff --git a/fork-kit/gardener/lib/gardener/__init__.py b/fork-kit/gardener/lib/gardener/__init__.py new file mode 100644 index 0000000000000..aa4424d22dd80 --- /dev/null +++ b/fork-kit/gardener/lib/gardener/__init__.py @@ -0,0 +1 @@ +"""gardener: a daily runner of small checks, one rolled-up report issue per project (fork-kit/gardener/README.md).""" diff --git a/fork-kit/gardener/lib/gardener/cli.py b/fork-kit/gardener/lib/gardener/cli.py new file mode 100644 index 0000000000000..45692c58a3685 --- /dev/null +++ b/fork-kit/gardener/lib/gardener/cli.py @@ -0,0 +1,315 @@ +"""gardener: run each project's checks once a day and keep one rolled-up report issue per project +(fork-kit/gardener/README.md). + + gardener run [--project NAME] [--dry-run] [--force] [--timer] + run the checks of every project (or one) and write its report issue. + A project that already ran today (its done marker) is skipped unless --force. + --dry-run: print the report instead; nothing is written (no issue, no done marker, no state), and checks set to + fix are run with fix off. + --timer: what the timer passes: a project runs only once its "schedule" time has passed today and, when it + has "quietHours", only inside them (its day then starts when they start). + gardener check + read the config and print each project and its checks; no check runs, no network. + +The config is the machine file's "gardener" section. Exit codes: 0 fine, 1 a project's run failed (it runs again on +the next tick) or its report issue could not be written (the next ticks try the issue alone, MAX_REPORT_TRIES a +day), 2 the config is refused. +""" +import datetime, errno, fcntl, json, os, sys + +from gardener import config, judge, report, runner + +STATE_VERSION = 1 +MAX_REPORT_TRIES = 3 # writes of one day's report issue: the run's own and two on later ticks + + +def now(): + """The current time, aware; GARDENER_TEST_NOW (ISO, with offset) sets it, for tests.""" + fixed = os.environ.get('GARDENER_TEST_NOW') + if fixed: + return datetime.datetime.fromisoformat(fixed) + return datetime.datetime.now(datetime.timezone.utc) + + +def local(project, t): + if project['timeZone']: + import zoneinfo + return t.astimezone(zoneinfo.ZoneInfo(project['timeZone'])) + return t.astimezone() + + +def _minutes(hhmm): + h, m = hhmm.split(':') + return int(h) * 60 + int(m) + + +def day_and_window(project, t): + """(the project's day at t, 'YYYY-MM-DD'; None when the timer may run it now, else why not). + + Without quietHours the day is the local date and the timer runs the project once the schedule time (if any) has + passed. With quietHours the day starts when they start (22:00-06:00: 01:00 on the 24th is still the 23rd's + window, so a window that wraps past midnight is one run, not two; a tick missed at 23:00 runs at 01:00), the + timer runs only inside them, and a schedule time inside them holds it until then (one outside them is not + used).""" + lt = local(project, t) + m = lt.hour * 60 + lt.minute + s = _minutes(project['schedule']) if project['schedule'] else None + hold = f'not yet: it runs after {project["schedule"]}' + if not project['quietHours']: + return lt.date().isoformat(), (hold if s is not None and m < s else None) + a, b = (_minutes(x) for x in project['quietHours'].split('-')) + length, pos = (b - a) % 1440, (m - a) % 1440 + day = (lt - datetime.timedelta(minutes=pos)).date().isoformat() + if pos >= length: + return day, f'outside its quiet hours {project["quietHours"]}' + if s is not None and (s - a) % 1440 < length and pos < (s - a) % 1440: + return day, hold + return day, None + + +class State: + """//state.json: {"version": 1, "doneDay": "YYYY-MM-DD", "issue": N, "lastRun": ISO, + "findings": N, "reportPending": bool, "reportTries": N, "reportRepo": "OWNER/REPO"}. A reportRepo other + than the config's (changed by hand) is not done today: the day runs again for the new repository, so a part + rendered for one repository never goes to another. Missing, broken or of an older version: read as empty, + with a note in the report. Of a NEWER version (a downgraded kit): `newer` is set and a run refuses, so the newer + state is never overwritten.""" + + def __init__(self, folder): + self.folder = folder + self.path = os.path.join(folder, 'state.json') + self.note = None + self.newer = None + self.data = {} + try: + with open(self.path, encoding='utf-8') as f: + data = json.load(f) + v = data.get('version') if isinstance(data, dict) else None + if isinstance(v, int) and not isinstance(v, bool) and v > STATE_VERSION: + self.newer = v + self.note = f'the state file is of a newer gardener (version {v}): a run refuses until it is upgraded' + return + if v != STATE_VERSION: + raise ValueError(f'not version {STATE_VERSION}') + self.data = data + except FileNotFoundError: + pass + except (OSError, ValueError) as e: + self.note = f'the state file could not be read ({type(e).__name__}): started from empty state' + + def done_day(self): + d = self.data.get('doneDay') + return d if isinstance(d, str) else None + + def count(self, key): + n = self.data.get(key) + return n if isinstance(n, int) and not isinstance(n, bool) and n > 0 else 0 + + def issue(self): + n = self.data.get('issue') + return n if isinstance(n, int) and not isinstance(n, bool) and n > 0 else None + + def save(self, **changes): + self.data.update(changes, version=STATE_VERSION) + write_atomic(self.path, json.dumps(self.data, indent=1, sort_keys=True)) + + +def write_atomic(path, text): + """path holds the old text or the new, never half; a failed write leaves no temporary file.""" + tmp = f'{path}.tmp-{os.getpid()}' + try: + with open(tmp, 'w', encoding='utf-8') as f: + f.write(text) + f.flush() + os.fsync(f.fileno()) + os.replace(tmp, path) + except BaseException: + try: + os.unlink(tmp) + except OSError: + pass + raise + + +def lock(folder): + """An open lock file held by this process, or None when another run holds it.""" + fd = os.open(os.path.join(folder, 'lock'), os.O_RDWR | os.O_CREAT | os.O_CLOEXEC, 0o600) + try: + fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB) + except OSError as e: + os.close(fd) + if e.errno in (errno.EWOULDBLOCK, errno.EAGAIN): + return None + raise + return fd + + +def say(msg): + print(f'gardener: {msg}', flush=True) + + +def run_project(cfg, project, args, t, gh_factory): + """0 done or skipped, 1 failed.""" + name = project['name'] + today, why_not = day_and_window(project, t) + folder = os.path.join(config.expand(cfg['stateDir']), name) + if not args.dry_run: + os.makedirs(folder, mode=0o700, exist_ok=True) + held = lock(folder) + if held is None: + say(f'{name}: another run is going; skipped') + return 0 + else: + held = None + try: + state = State(folder) + if state.newer and not args.dry_run: + say(f'{name}: the state file is of a newer gardener (version {state.newer}); refused, nothing changed: ' + 'upgrade the gardener kit') + return 1 + moved = (state.data.get('reportRepo') or '') != project['reportRepo'] + if moved and state.done_day() == today and not args.dry_run: + say(f'{name}: the report repository changed today; it runs again for the new one') + if moved: + state.data.pop('issue', None) # that number is of the old report repository + if not args.dry_run and not args.force and state.done_day() == today and not moved: + if state.data.get('reportPending') is True and project['reportRepo']: + return send_report(cfg, project, state, folder, gh_factory) + say(f'{name}: ran today already ({today}); nothing to do (--force runs it again)') + return 0 + if args.timer and not args.force and why_not: + say(f'{name}: {why_not}; skipped') + return 0 + notes = [state.note] if state.note else [] + findings = [] + for check in project['checks']: + c = dict(check, fix=check['fix'] and not args.dry_run) + try: + got, ok = runner.run(project, c, today, cfg['gh']) + except Exception as e: # a MemoryError too: one check never stops the run + got, ok = [runner.failed(check, 'the gardener could not run it', type(e).__name__)], False + findings += got + say(f'{name}: check {check["id"]}: ' + (f'{len(got)} finding(s)' if ok else f'failed: {got[0]["text"]}' + + (f' ({got[0]["detail"]})' if got[0].get('detail') else ''))) + root = config.expand(project['root']) if project['root'] else '' + home = report.home_dir() + text_checks = {c['id'] for c in project['checks'] if c['name'] or c['publicText']} + counts = counts_only(cfg, project, gh_factory) + public = report.public_findings(findings, root, home, project['reportRepo'], text_checks, counts) + answer, note = judge.judge(project['model'], public, root) + if note: + notes.append(note) + part = report.render_issue(name, today, findings, notes, answer, root, home, project['reportRepo'], + text_checks, counts) + full = report.render_local(name, today, findings, notes, answer) + if args.dry_run: + say(f'{name}: dry run: the report issue would get:') + print(part, end='') + say(f'{name}: dry run: the local report.md would get:') + print(full, end='') + say(f'{name}: dry run: {len(findings)} finding(s); nothing written') + return 0 + report_path = os.path.join(folder, 'report.md') + write_atomic(report_path, full) + if project['reportRepo']: + write_atomic(os.path.join(folder, 'issue.md'), part) + # The done marker before the issue write: a stop or a GitHub error from here on never runs the checks (and + # their fixes) again today; the next ticks send the saved issue part alone (send_report). + state.save(doneDay=today, lastRun=t.isoformat(timespec='seconds'), findings=len(findings), + reportPending=bool(project['reportRepo']), reportTries=0, reportRepo=project['reportRepo']) + if not project['reportRepo']: + say(f'{name}: {len(findings)} finding(s); report {report_path}') + return 0 + return send_report(cfg, project, state, folder, gh_factory) + finally: + if held is not None: + os.close(held) + + +def counts_only(cfg, project, gh_factory): + """True when the issue may show counts only: the report repository is public and the project's repository is + private, not set, or of a visibility GitHub does not tell (fail closed). Two reads at most; none when the report + goes to the project's own repository or to none.""" + rr, pr = project['reportRepo'], project['repo'] + if not rr or (pr and pr.lower() == rr.lower()): + return False + try: + gh = gh_factory(cfg['gh']) + if gh.private(rr) is True: + return False + return not pr or gh.private(pr) is not False + except report.GitHubError: + return True + + +def send_report(cfg, project, state, folder, gh_factory): + """Write the day's saved issue part (issue.md) to the report issue. 0 written (or no tries left today), 1 not.""" + name = project['name'] + tries = state.count('reportTries') + if tries >= MAX_REPORT_TRIES: + say(f'{name}: the report issue could not be written ({tries} tries today); the next day\'s run tries again. ' + f'The report is in {os.path.join(folder, "report.md")}') + return 0 + try: + with open(os.path.join(folder, 'issue.md'), encoding='utf-8') as f: + part = f.read() + except OSError as e: + state.save(reportPending=False) + say(f'{name}: the saved report part is gone ({type(e).__name__}); the next day\'s run writes the issue') + return 1 + try: + number, how = report.publish(gh_factory(cfg['gh']), project['reportRepo'], name, part, state.issue()) + except report.GitHubError as e: + tries += 1 + state.save(reportTries=tries, reportPending=tries < MAX_REPORT_TRIES) + say(f'{name}: the report issue could not be written: {e}; ' + + (f'the next tick tries the issue again ({MAX_REPORT_TRIES - tries} more today)' if tries < MAX_REPORT_TRIES + else 'no more tries today')) + return 1 + state.save(issue=number, reportPending=False, reportTries=0) + say(f'{name}: {state.count("findings")} finding(s); report {project["reportRepo"]}#{number} ({how})') + return 0 + + +def main(argv, gh_factory=report.GitHub): + import argparse + parser = argparse.ArgumentParser(prog='gardener', description=__doc__.split('\n\n')[0], + formatter_class=argparse.RawDescriptionHelpFormatter, epilog=__doc__) + sub = parser.add_subparsers(dest='cmd', required=True) + r = sub.add_parser('run') + r.add_argument('--project') + r.add_argument('--dry-run', action='store_true') + r.add_argument('--force', action='store_true') + r.add_argument('--timer', action='store_true') + sub.add_parser('check') + args = parser.parse_args(argv) + try: + cfg = config.load() + except config.MachineFileError as e: + print(f'gardener: config refused: {e}', file=sys.stderr) + return 2 + projects = cfg['projects'] + if args.cmd == 'check': + for p in projects: + say(f'{p["name"]}: report to {p["reportRepo"] or "(the state folder only)"}, ' + + (f'after {p["schedule"]}' if p['schedule'] else 'any time of day') + + (f' in {p["quietHours"]}' if p['quietHours'] else '') + + (f', model {p["model"]["model"]}' if p['model'] else '')) + for c in p['checks']: + say(f' {c["id"]}: {c["name"] or c["path"]}' + (' (fix)' if c['fix'] else '') + + f', timeout {c["timeoutSeconds"]} s') + return 0 + if args.project: + projects = [p for p in projects if p['name'] == args.project] + if not projects: + print(f'gardener: no project {args.project!r} in the config', file=sys.stderr) + return 2 + t = now() + code = 0 + for p in projects: + try: + code |= run_project(cfg, p, args, t, gh_factory) + except Exception as e: # anything (a broken state folder, MemoryError) never stops the others + say(f'{p["name"]}: failed: {type(e).__name__}: {e}') + code = 1 + return code diff --git a/fork-kit/gardener/lib/gardener/config.py b/fork-kit/gardener/lib/gardener/config.py new file mode 100644 index 0000000000000..1fa71a9e45f45 --- /dev/null +++ b/fork-kit/gardener/lib/gardener/config.py @@ -0,0 +1,188 @@ +"""gardener.config: the machine file's "gardener" section (fork-kit/gardener/README.md, Config). + + "gardener": { + "stateDir": "~/.local/state/gardener", + "gh": "gh", + "projects": [{ + "name": "example", "repo": "OWNER/REPO", "reportRepo": "OWNER/REPO", "root": "/srv/example/repo", + "schedule": "04:00", "quietHours": "02:00-07:00", "timeZone": "Europe/London", + "model": {"endpoint": "http://127.0.0.1:8080/v1", "model": "example-model"}, + "checks": [{"name": "context-budget", "options": {...}}, + {"path": "/srv/example/bin/doc-check", "id": "docs", "timeoutSeconds": 120}] + }] + } + +A check is a general one shipped with the kit ("name") or a project's own script ("path"); the kit never names a +project's checks. Anything it does not fully understand is refused whole (machine_file's rules): a typo is never +ignored. Paths are absolute or start with "~/" (the home of the user the gardener runs as). Plain Python 3. +""" +import os, re, sys + +_kit = os.path.dirname(os.path.dirname(os.path.dirname(os.path.realpath(__file__)))) +_common = os.path.join(_kit, 'common') +sys.path.insert(0, _common if os.path.isfile(os.path.join(_common, 'machine_file.py')) + else os.path.join(os.path.dirname(_kit), 'common')) +import machine_file # noqa: E402 + +KIT = 'gardener' +MACHINE_PATH = None # tests only; shipped commands read the fixed path +OWNER_UID = 0 # tests only +REQ = machine_file.REQUIRED +MachineFileError = machine_file.MachineFileError + +CHECKS_DIR = os.path.join(_kit, 'checks') +GENERAL_CHECKS = ('context-budget', 'facts', 'install-drift', 'workflows-off', 'worktrees') +NAME_RE = re.compile(r'^[a-z0-9][a-z0-9._-]{0,63}$') +REPO_RE = re.compile(r'^[A-Za-z0-9][A-Za-z0-9-]{0,38}/[A-Za-z0-9._-]{1,100}$') +TIME_RE = re.compile(r'^([01][0-9]|2[0-3]):([0-5][0-9])$') +COMMAND_RE = re.compile(r'^[A-Za-z0-9][A-Za-z0-9._+-]{0,63}$') + + +def _path(value): + if not (os.path.isabs(value) or value.startswith('~/')) or '\0' in value: + return 'must be an absolute path or start with "~/"' + return None + + +def _path_or_empty(value): + return _path(value) if value else None + + +def _name(value): + return None if NAME_RE.match(value) and value not in ('.', '..') else \ + 'must be lower case letters, digits, ".", "_" or "-" (at most 64)' + + +def _repo(value): + return None if not value or (REPO_RE.match(value) and value.split('/')[1] not in ('.', '..')) else \ + 'must be OWNER/REPO' + + +def _time(value): + return None if TIME_RE.match(value) else 'must be HH:MM (24 hours)' + + +def _time_or_empty(value): + return _time(value) if value else None + + +def _quiet(value): + if not value: + return None + parts = value.split('-') + if len(parts) != 2 or not all(TIME_RE.match(p) for p in parts) or parts[0] == parts[1]: + return 'must be "HH:MM-HH:MM" (two different times; it may wrap past midnight)' + return None + + +def _zone(value): + if not value: + return None + try: + import zoneinfo + zoneinfo.ZoneInfo(value) + except Exception: + return 'is not a time zone this machine knows' + return None + + +def _command(value): + return None if COMMAND_RE.match(value) or not _path(value) else \ + 'must be a command name (found on PATH) or an absolute path' + + +def _endpoint(value): + return None if re.match(r'^https?://[^\s/]+(/[^\s]*)?$', value) else 'must be an http:// or https:// URL' + + +def _seconds(lo, hi): + return lambda v: None if lo <= v <= hi else f'must be {lo} to {hi}' + + +def model(obj, where): + return machine_file.fields(obj, { + 'endpoint': (str, REQ, _endpoint), + 'model': (str, REQ, lambda v: None if v.strip() else 'must not be empty'), + 'timeoutSeconds': (int, 120, _seconds(1, 3600)), + 'maxFiles': (int, 5, _seconds(0, 50)), + 'maxFileBytes': (int, 20000, _seconds(0, 200000)), + }, where) + + +def check(obj, where): + c = machine_file.fields(obj, { + 'name': (str, '', None), + 'path': (str, '', _path_or_empty), + 'id': (str, '', lambda v: _name(v) if v else None), + 'options': (dict, None, None), + 'fix': (bool, False, None), + 'timeoutSeconds': (int, 300, _seconds(1, 3600)), + 'publicText': (bool, False, None), + }, where) + if bool(c['name']) == bool(c['path']): + raise MachineFileError(f'{where}: give exactly one of "name" (a general check: {", ".join(GENERAL_CHECKS)}) ' + 'or "path" (a project check)') + if c['name'] and c['name'] not in GENERAL_CHECKS: + raise MachineFileError(f'{where}.name: {c["name"]!r} is not a general check ' + f'(known: {", ".join(GENERAL_CHECKS)}); a project check is given by "path"') + if c['name'] and c['publicText']: + raise MachineFileError(f'{where}.publicText: only for a project check ("path"); a general check\'s text is ' + 'always shown') + c['options'] = c['options'] or {} + c['id'] = c['id'] or c['name'] or _name_from_path(c['path']) + return c + + +def _name_from_path(path): + base = re.sub(r'[^a-z0-9._-]+', '-', os.path.basename(path).lower()).strip('-.') or 'check' + return base[:64] + + +def project(obj, where): + p = machine_file.fields(obj, { + 'name': (str, REQ, _name), + 'repo': (str, '', _repo), + 'reportRepo': (str, '', _repo), + 'root': (str, '', _path_or_empty), + 'schedule': (str, '', _time_or_empty), + 'quietHours': (str, '', _quiet), + 'timeZone': (str, '', _zone), + 'model': (dict, None, None), + 'checks': (list, REQ, None), + }, where) + p['model'] = model(p['model'], f'{where}.model') if p['model'] is not None else None + p['checks'] = [check(c, f'{where}.checks[{i}]') for i, c in enumerate(p['checks'])] + ids = [c['id'] for c in p['checks']] + twice = sorted({i for i in ids if ids.count(i) > 1}) + if twice: + raise MachineFileError(f'{where}.checks: the id {twice[0]!r} is given twice (set "id" on one of them)') + return p + + +def parse(section, where): + """The checked section with defaults filled in. Raises MachineFileError.""" + s = machine_file.fields(section, { + 'stateDir': (str, '~/.local/state/gardener', _path), + 'gh': (str, 'gh', _command), + 'projects': (list, REQ, None), + }, where) + s['projects'] = [project(p, f'{where}.projects[{i}]') for i, p in enumerate(s['projects'])] + names = [p['name'] for p in s['projects']] + twice = sorted({n for n in names if names.count(n) > 1}) + if twice: + raise MachineFileError(f'{where}.projects: the name {twice[0]!r} is given twice') + return s + + +def load(): + """The machine file's gardener section, checked. Raises MachineFileError (a missing file or section too).""" + path = MACHINE_PATH or machine_file.default_path() + section = machine_file.read_section(KIT, path=path, owner_uid=OWNER_UID) + return parse(section, f'{path}: {KIT}') + + +def expand(path, home=None): + """A configured path for the user who runs the gardener ("~/" is that user's home).""" + if path.startswith('~/'): + return os.path.join(home or os.path.expanduser('~'), path[2:]) + return path diff --git a/fork-kit/gardener/lib/gardener/contract.py b/fork-kit/gardener/lib/gardener/contract.py new file mode 100644 index 0000000000000..ae7d7c866ea88 --- /dev/null +++ b/fork-kit/gardener/lib/gardener/contract.py @@ -0,0 +1,69 @@ +"""gardener.contract: the check contract, version 1 (fork-kit/gardener/README.md, Checks). + +A check is a small program. The runner starts it in the project's root folder (when the project has one), in a +process group of its own, and writes one JSON object to its stdin: + + {"version": 1, "project": {"name": "...", "repo": "OWNER/REPO" or "", "root": "/path" or ""}, + "check": "", "options": {...}, "fix": false, "today": "YYYY-MM-DD", "gh": "gh"} + +It prints its findings to stdout, one JSON object per line, and exits 0 (with or without findings): + + {"id": "worktrees.merged", "severity": "warn", "where": "path or thing", "text": "what is wrong", + "fix": "how to fix it (a hint)"} + +`id` (a dotted name: letters, digits, `.`, `_`, `-`, at most 100) and `text` are required, `severity` is one of +error, warn, info, `where` and `fix` are optional strings; no other keys. A check changes nothing unless "fix" is true, and then only what its README says. Empty lines are +ignored; anything else on stdout (a line that is not such an object), an exit code other than 0, more than +MAX_OUTPUT bytes or a run past its timeout makes the whole check one failed-check finding: the runner never trusts +part of a broken check's output. stderr (its last 4 KiB) is kept only for the local report and log, never the issue. + +Check programs written in Python can use read_context() and emit() below. +""" +import json, re, sys + +VERSION = 1 +SEVERITIES = ('error', 'warn', 'info') +KEYS = ('id', 'severity', 'where', 'text', 'fix') +MAX_OUTPUT = 256 << 10 # bytes of stdout; the runner stops reading (and the check) after this +MAX_FINDINGS = 200 # per check; more are folded into one finding +MAX_TEXT = 2000 # per field, in characters +ID = re.compile(r'[A-Za-z0-9][A-Za-z0-9._-]{0,99}') + + +def parse_finding(line): + """A finding dict from one stdout line, or raise ValueError saying why it is not one.""" + obj = json.loads(line) + if not isinstance(obj, dict): + raise ValueError('not a JSON object') + unknown = sorted(set(obj) - set(KEYS)) + if unknown: + raise ValueError(f'unknown key {unknown[0]!r}') + for key in ('id', 'text'): + if not isinstance(obj.get(key), str) or not obj[key].strip(): + raise ValueError(f'"{key}" must be a non-empty string') + if not ID.fullmatch(obj['id']): + raise ValueError('"id" must be a dotted name (letters, digits, ".", "_", "-")') + if obj.get('severity') not in SEVERITIES: + raise ValueError(f'"severity" must be one of {", ".join(SEVERITIES)}') + for key in ('where', 'fix'): + if not isinstance(obj.get(key, ''), str): + raise ValueError(f'"{key}" must be a string') + return {k: (obj.get(k) or '')[:MAX_TEXT] for k in KEYS} + + +def read_context(stream=None): + """The context the runner wrote to stdin (a dict).""" + try: + ctx = json.load(stream or sys.stdin) + except ValueError: + ctx = None + if not isinstance(ctx, dict) or ctx.get('version') != VERSION: + raise SystemExit(f'gardener check: stdin is not a version {VERSION} gardener context') + return ctx + + +def emit(id, severity, text, where='', fix='', out=None): + """Print one finding line.""" + assert severity in SEVERITIES + print(json.dumps({'id': id, 'severity': severity, 'where': where, 'text': text, 'fix': fix}, + ensure_ascii=False), file=out or sys.stdout, flush=True) diff --git a/fork-kit/gardener/lib/gardener/judge.py b/fork-kit/gardener/lib/gardener/judge.py new file mode 100644 index 0000000000000..4f37c823ef757 --- /dev/null +++ b/fork-kit/gardener/lib/gardener/judge.py @@ -0,0 +1,85 @@ +"""gardener.judge: the optional judgment step (phase 1: the interface only). + +When the project's config has "model" {endpoint, model}, the findings as the issue shows them (report. +public_findings: nothing from outside the repository) and a few of the files they name (at most maxFiles, each cut +to maxFileBytes, only files git tracks in the project root: never an ignored or untracked file such as a local +.env) go to that endpoint's OpenAI-style /chat/completions in one request. The answer is added to the report under +"Judgment", masked like the rest of the issue. An endpoint that is not reachable, or answers with an error, +nonsense or not HTTP at all, is a note ("model unreachable") and the run goes on; there is no fallback to a paid +model. The note never names the endpoint. It never sees the whole repository. +""" +import json, os, subprocess, urllib.request + +SYSTEM = ('You review a daily maintenance report of a software project. For each finding, say in one short line ' + 'whether it looks real and what to do first. Use only the findings and files given. Plain English.') +MAX_ANSWER = 8000 + + +def tracked(root, rel): + """True when git tracks the file rel in root.""" + try: + p = subprocess.run(['git', '-C', root, 'ls-files', '--error-unmatch', '--', rel], capture_output=True, + timeout=30, stdin=subprocess.DEVNULL, env=dict(os.environ, GIT_TERMINAL_PROMPT='0')) + except (OSError, subprocess.TimeoutExpired): + return False + return p.returncode == 0 + + +def files_for(findings, root, max_files, max_bytes): + """[(relative path, text)] of the files the (public) findings name: regular files inside root that git + tracks.""" + if not root or max_files <= 0: + return [] + real_root = os.path.realpath(root) + out, seen = [], set() + for f in findings: + where = (f.get('where') or '').strip() + path = where.rsplit(':', 1)[0] if where.rsplit(':', 1)[-1].isdigit() else where + if not path or ': ' in path or os.path.isabs(path): + continue + full = os.path.realpath(os.path.join(real_root, path)) + if full in seen or not full.startswith(real_root + os.sep) or not os.path.isfile(full): + continue + seen.add(full) + rel = os.path.relpath(full, real_root) + if not tracked(real_root, rel): + continue + try: + with open(full, 'rb') as fh: + text = fh.read(max_bytes).decode('utf-8', 'replace') + except OSError: + continue + out.append((rel, text)) + if len(out) >= max_files: + break + return out + + +def judge(model, findings, root): + """(answer text or None, note or None). findings: report.public_findings. Never raises: the step is + optional.""" + if not model: + return None, None + if not findings: + return None, 'judgment: nothing to judge (no findings)' + try: + files = files_for(findings, root, model['maxFiles'], model['maxFileBytes']) + listed = [{k: f[k] for k in ('check', 'id', 'severity', 'where', 'text')} for f in findings] + user = 'Findings (JSON):\n' + json.dumps(listed, indent=1) + for path, text in files: + user += f'\n\nFile {path}:\n```\n{text}\n```' + req = urllib.request.Request( + model['endpoint'].rstrip('/') + '/chat/completions', + data=json.dumps({'model': model['model'], 'temperature': 0, + 'messages': [{'role': 'system', 'content': SYSTEM}, + {'role': 'user', 'content': user}]}).encode(), + headers={'Content-Type': 'application/json'}, method='POST') + with urllib.request.urlopen(req, timeout=model['timeoutSeconds']) as resp: + data = json.loads(resp.read(1 << 20)) + answer = data['choices'][0]['message']['content'] + if not isinstance(answer, str) or not answer.strip(): + raise ValueError('an empty answer') + except Exception as e: # anything at all: an optional step never stops the run + return None, f'judgment: model unreachable or no usable answer ({type(e).__name__}); no judgment today' + return answer.strip()[:MAX_ANSWER], f'judgment: model reachable; it read {len(findings)} finding(s) and ' \ + f'{len(files)} file(s)' diff --git a/fork-kit/gardener/lib/gardener/report.py b/fork-kit/gardener/lib/gardener/report.py new file mode 100644 index 0000000000000..143532eca16d1 --- /dev/null +++ b/fork-kit/gardener/lib/gardener/report.py @@ -0,0 +1,292 @@ +"""gardener.report: the rolled-up report of one project's run, and its one issue on GitHub, updated in place. + +Two reports are written from the same findings: +- The issue part (render_issue) is built from an allow-list, because the report repository may be public: per + finding only its severity, check, id, a `where` that is a path inside the project's repository (relative), and + its text and fix with what still looks like a local name (a path, URL, address, user@host, e-mail, a Windows or + share path) masked. Free text only of the general checks (their words are known), the gardener's own findings + and project checks set to "publicText": true; another project check's findings show id, where and a count. A + finding whose `where` is outside the repository, or that has none, is only counted per check, without its id + (the gardener's own findings excepted: their words are fixed). With counts_only (a private project repository + reporting to a public one) every finding is only counted and there is no judgment. Notes are the gardener's own + words; the judgment is masked like the text. Nothing a check printed on stderr goes there. +- The local report (render_local, report.md in the state folder) holds everything, as it is. + +The issue is found by a hidden marker line, ``. Everything from the marker down is the +gardener's and is written whole on each run; text a person wrote above the marker is kept (cut, with a note, only +when the whole body would pass MAX_BODY). An issue without the marker (edited away by hand) is no longer the +report: the next run looks again and, finding none, opens a new one. A closed report issue is left closed, and a +new one is opened. GitHub calls per run: at most one issue read (the number the state file remembers); only when +that does not give the open report issue, a search by title and, when that finds none, one by marker; and one write +(create or edit). +""" +import json, os, re, subprocess + +SEVERITY_ORDER = {'error': 0, 'warn': 1, 'info': 2} +MAX_PART = 50000 # the gardener's part of the issue +MAX_BODY = 60000 # the whole body, a person's text above the marker too; GitHub's limit is 65536 +CUT_NOTE = '\n\n_(the text above was cut to fit the issue size limit)_\n\n' +OUTSIDE = '' +LOCAL_HINT = ('Full text, notes and paths outside the repository: `report.md` in the gardener\'s state folder on the ' + 'machine that runs it.') + +_SAFE_REL = re.compile(r'[A-Za-z0-9._+-]+(?:/[A-Za-z0-9._+-]+)*') +_REPO_WHERE = re.compile(r'([A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+): (.+)') +_MASKS = ( + (re.compile(r'[A-Za-z][A-Za-z0-9+.-]*://\S+'), ''), + (re.compile(r'[\w.+-]+@[\w-]+(?:\.[\w-]+)*'), ''), # e-mail, ssh user@host + (re.compile(r'\b\d{1,3}(?:\.\d{1,3}){3}\b'), ''), + (re.compile(r'(?'), # IPv6, also with :: + (re.compile(r'(?'), # \\host\share + (re.compile(r'(?'), # C:\Users\..., C:/... + (re.compile(r'\S*-home-\S*'), ''), # a home folder encoded in a folder name + (re.compile(r'(?'), + (re.compile(r'(?'), + (re.compile(r'\b[\w-]+(?:\.[\w-]+)*\.(?:local|lan|internal|localdomain|home\.arpa|ts\.net)\b', re.I), + ''), +) + + +class GitHubError(Exception): + pass + + +def marker(name): + return f'' + + +_END = r'(?=/|$|[\s\'"`|),;:]|\.(?:\s|$))' # a path ends here: not inside a longer folder name + + +def redact(text, root, home): + """The project root becomes ".", the home "~"; each only as a whole folder (/srv/proj2 is not /srv/proj).""" + for path, short in ((root, '.'), (home, '~')): + path = (path or '').rstrip('/') + if path: + text = re.sub(re.escape(path) + _END, short, text) + return text + + +def public_text(text, root, home): + """Text for the issue: the root as ".", then every path outside it, URL, address, e-mail and local host name + masked.""" + text = redact(text or '', root, home) + for rx, sub in _MASKS: + text = rx.sub(sub, text) + return text + + +def public_where(where, root, report_repo=''): + """Where to show in the issue: a path inside the repository, relative (":LINE" kept), "OWNER/REPO: path" of the + report repository, or '' for none. None: outside the repository, or not a plain path.""" + w = (where or '').strip() + if not w: + return '' + m = _REPO_WHERE.fullmatch(w) + if m: + if report_repo and m.group(1).lower() == report_repo.lower(): + rest = public_where(m.group(2), '', '') + return f'{m.group(1)}: {rest}' if rest else None + return None + line = '' + m = re.fullmatch(r'(.+?)(:\d+)', w) + if m: + w, line = m.groups() + if w.startswith('~'): + return None + if os.path.isabs(w): + if not root: + return None + w = os.path.relpath(os.path.normpath(w), os.path.normpath(root)) + w = os.path.normpath(w) + if w == '.': + return '.' + line + if w == '..' or w.startswith('../') or not _SAFE_REL.fullmatch(w): + return None + return w + line + + +def _cell(text): + return text.replace('\\', '\\\\').replace('|', '\\|').replace('\r', ' ').replace('\n', ' ').strip() + + +def _counts(findings): + c = {s: sum(1 for f in findings if f['severity'] == s) for s in SEVERITY_ORDER} + return (f'{c["error"]} error(s), {c["warn"]} warning(s), {c["info"]} note(s). Report only, unless a check is ' + 'set to fix.') if findings else 'No findings.' + + +def _document(name, title, today, counts, rows, notes, judgment, cap, more_hint, extra=()): + rows = sorted(rows, key=lambda r: (SEVERITY_ORDER.get(r[0], 3), r[1], r[2], r[3])) + lines = [marker(name), f'## {title}: {name}, {today}', '', counts, *extra, ''] + tail = [] + if notes: + tail += ['### Notes', ''] + [f'- {_cell(n)}' for n in notes] + if judgment: + tail += ['', '### Judgment (local model)', '', judgment.strip()] + tail += ['', f'Written by the gardener (fork-kit/gardener) on {today}; it rewrites everything below the ' + 'marker on each run.'] + if rows: + lines += ['| Severity | Check | Finding | Where | Fix |', '| --- | --- | --- | --- | --- |'] + shown = 0 + budget = (cap - len('\n'.join(lines)) - len('\n'.join(tail)) - 300) if cap else None + for r in rows: + row = '| ' + ' | '.join(_cell(v) for v in r) + ' |' + if budget is not None: + if len(row) + 1 > budget: + break + budget -= len(row) + 1 + lines.append(row) + shown += 1 + if shown < len(rows): + lines += ['', f'{len(rows) - shown} more row(s) not shown (the issue is full): {more_hint}'] + lines.append('') + return '\n'.join(lines + tail) + '\n' + + +def public_findings(findings, root, home, report_repo='', text_checks=(), counts_only=False): + """The allow-listed view of the findings (module doc): [{severity, check, id, text, where, fix}]. text_checks: + the ids of the checks whose text may be shown (general checks and "publicText" project checks); the gardener's + own findings always. Folded into one counted entry: a finding outside the repository or with no where (per + severity, check and where; no id: a project check's id may name a local thing), and one whose text may not be + shown (per severity, check, id and where). counts_only: every finding, per severity and check.""" + out, hidden = [], {} + for f in findings: + w = public_where(f.get('where'), root, report_repo) + if counts_only: + key = (f['severity'], f['check'], '', '', 'in the local report only') + elif w is None or (w == '' and not f.get('own')): + key = (f['severity'], f['check'], '', OUTSIDE if w is None else '', 'in the local report only') + elif not f.get('own') and f['check'] not in text_checks: + key = (f['severity'], f['check'], f['id'], w, 'text in the local report only (the check is not set to ' + 'publicText)') + else: + out.append({'severity': f['severity'], 'check': f['check'], 'id': f['id'], 'where': w, + 'text': public_text(f['text'], root, home), + 'fix': public_text(f.get('fix') or '', root, home)}) + continue + hidden[key] = hidden.get(key, 0) + 1 + for (severity, check, id_, where, why), n in hidden.items(): + out.append({'severity': severity, 'check': check, 'id': id_, 'where': where, + 'text': f'{n} finding(s), {why}', 'fix': ''}) + return out + + +COUNTS_ONLY = ('Counts only: the project\'s repository is private (or not set, or its visibility could not be read) ' + 'and this report repository is public.') + + +def render_issue(name, today, findings, notes, judgment=None, root='', home='', report_repo='', text_checks=(), + counts_only=False): + """The issue part, from the marker down (markdown), from the allow-list (module doc).""" + rows = [(f['severity'], f['check'], f'{f["id"]}: {f["text"]}' if f['id'] else f['text'], f['where'], f['fix']) + for f in public_findings(findings, root, home, report_repo, text_checks, counts_only)] + return _document(name, 'Gardener report', today, _counts(findings), rows, + [public_text(n, root, home) for n in notes], + public_text(judgment, root, home) if judgment and not counts_only else None, MAX_PART, + 'the local report has them all', ('', LOCAL_HINT) + (('', COUNTS_ONLY) if counts_only else ())) + + +def render_local(name, today, findings, notes, judgment=None): + """The local report (report.md): every finding, its detail and its full where, as they are.""" + rows = [(f['severity'], f['check'], f'{f["id"]}: {f["text"]}' + (f' ({f["detail"]})' if f.get('detail') else ''), + f.get('where') or '', f.get('fix') or '') for f in findings] + return _document(name, 'Gardener report (local, in full)', today, _counts(findings), rows, notes, judgment, + None, '') + + +def body_with(old_body, name, new_part): + """The new issue body: what a person wrote above the marker, then the new report part; at most MAX_BODY (the + person's text is cut, with a note, when it does not fit).""" + head = '' + if old_body and marker(name) in old_body: + head = old_body[:old_body.index(marker(name))] + room = MAX_BODY - len(new_part) + if len(head) > room: + head = head[:max(0, room - len(CUT_NOTE))] + CUT_NOTE + return head + new_part + + +class GitHub: + """GitHub through `gh api` (the configured gh command, with the login of the user who runs the gardener).""" + + def __init__(self, gh, timeout=60): + self.gh, self.timeout = gh, timeout + + def call(self, method, path, fields=None): + args = [self.gh, 'api', '--method', method, path] + data = None + if fields is not None: + args += ['--input', '-'] + data = json.dumps(fields) + try: + p = subprocess.run(args, input=data, capture_output=True, text=True, timeout=self.timeout, + stdin=None if data is not None else subprocess.DEVNULL) + except (OSError, subprocess.TimeoutExpired) as e: + raise GitHubError(f'gh api {method} {path}: {e}') from None + if p.returncode != 0: + msg = (p.stderr or p.stdout).strip().splitlines() + msg = msg[-1] if msg else f'exit {p.returncode}' + if re.search(r'rate limit|HTTP 429|retry-after', msg, re.I): + msg += ' (rate limit: the next run tries again)' + raise GitHubError(f'gh api {method} {path}: {msg}') + try: + return json.loads(p.stdout) if p.stdout.strip() else None + except ValueError: + raise GitHubError(f'gh api {method} {path}: the answer is not JSON') from None + + def issue(self, repo, number): + return self.call('GET', f'repos/{repo}/issues/{number}') + + def private(self, repo): + """True, False, or None when GitHub does not say.""" + got = self.call('GET', f'repos/{repo}') + v = got.get('private') if isinstance(got, dict) else None + return v if isinstance(v, bool) else None + + def search_open(self, repo, text, field='body'): + q = f'repo:{repo} is:issue is:open in:{field} "{text}"' + from urllib.parse import quote + found = self.call('GET', f'search/issues?q={quote(q)}&per_page=10') or {} + return found.get('items') or [] + + def create(self, repo, title, body): + return self.call('POST', f'repos/{repo}/issues', {'title': title, 'body': body}) + + def edit(self, repo, number, body): + return self.call('PATCH', f'repos/{repo}/issues/{number}', {'body': body}) + + +def _ours(issue, name): + return (isinstance(issue, dict) and issue.get('state') == 'open' and 'pull_request' not in issue + and marker(name) in (issue.get('body') or '')) + + +def publish(gh, repo, name, part, known_number=None): + """Write the report part to the project's report issue; returns (issue number, 'created' or 'updated'). + Raises GitHubError.""" + issue = None + if known_number: + try: + got = gh.issue(repo, known_number) + except GitHubError: + got = None # deleted, moved or unreadable: look again + if _ours(got, name): + issue = got + if issue is None: # by title, then (renamed by hand) by the marker; GitHub search may skip comments + for text, field in ((f'Gardener report: {name}', 'title'), (f'gardener-report:{name}', 'body')): + mine = [i for i in gh.search_open(repo, text, field) if _ours(i, name)] + if mine: + issue = min(mine, key=lambda i: i['number']) # the oldest open one, always the same + break + if issue is None: + made = gh.create(repo, f'Gardener report: {name}', part) + return made['number'], 'created' + gh.edit(repo, issue['number'], body_with(issue.get('body') or '', name, part)) + return issue['number'], 'updated' + + +def home_dir(): + return os.path.expanduser('~') diff --git a/fork-kit/gardener/lib/gardener/runner.py b/fork-kit/gardener/lib/gardener/runner.py new file mode 100644 index 0000000000000..a2981cf036639 --- /dev/null +++ b/fork-kit/gardener/lib/gardener/runner.py @@ -0,0 +1,159 @@ +"""gardener.runner: run one check under the contract (gardener.contract) and turn what it did into findings. + +A check that fails in any way (cannot start, exits non-zero, runs past its timeout, prints junk or too much) +becomes exactly one finding, id gardener.check-failed, and never stops the run: the next check still runs. +Its output is read as it comes, never more than contract.MAX_OUTPUT bytes of stdout and the last 4 KiB of stderr, +so a check that prints without end costs no memory: it is stopped at the cap. + +The text and fix of the gardener's own findings are fixed words written here, naming no local thing. What the check +printed on stderr, or why it could not start, is the finding's `detail`: the local report and log only, never the +issue. +""" +import json, os, selectors, signal, subprocess, sys, time + +from gardener import config, contract + +FAILED = 'gardener.check-failed' +ERR_KEEP = 4096 +CHUNK = 65536 + + +def command(check): + if check['name']: + return [sys.executable, '-I', '-B', os.path.join(config.CHECKS_DIR, check['name'])] + return [config.expand(check['path'])] + + +def context(project, check, today, gh): + return {'version': contract.VERSION, + 'project': {'name': project['name'], 'repo': project['repo'], + 'root': config.expand(project['root']) if project['root'] else ''}, + 'check': check['id'], 'options': check['options'], 'fix': check['fix'], 'today': today, 'gh': gh} + + +def failed(check, text, detail='', fix=''): + """The one finding of a failed check. text and fix: fixed words of the gardener (they go to the issue); + detail: what the check or the system said (local report and log only).""" + return {'id': FAILED, 'severity': 'error', 'where': '', 'text': text, 'detail': detail, 'own': True, + 'fix': fix or 'run the check by hand with the same context and fix it, or remove it from the config', + 'check': check['id']} + + +def _last_line(data): + lines = [ln.strip() for ln in bytes(data).decode('utf-8', 'replace').splitlines() if ln.strip()] + return lines[-1][:300] if lines else '' + + +def _kill(proc): + try: + os.killpg(proc.pid, signal.SIGKILL) + except OSError: + pass + try: + proc.kill() + except OSError: + pass + + +def _talk(proc, data, deadline): + """Write data to the check's stdin and read its stdout and stderr until both close, the deadline passes or + stdout passes MAX_OUTPUT. (stdout bytes, last stderr bytes, None, 'timeout' or 'too-much').""" + out, err = bytearray(), bytearray() + sel = selectors.DefaultSelector() + try: + pending = memoryview(data) + os.set_blocking(proc.stdin.fileno(), False) + sel.register(proc.stdin, selectors.EVENT_WRITE, 'in') + sel.register(proc.stdout, selectors.EVENT_READ, 'out') + sel.register(proc.stderr, selectors.EVENT_READ, 'err') + reading = 2 + while reading: + left = deadline - time.monotonic() + if left <= 0: + return out, err, 'timeout' + for key, _ in sel.select(left): + if key.data == 'in': + try: + pending = pending[os.write(key.fd, pending[:CHUNK]):] + except BlockingIOError: + continue + except OSError: # the check closed its stdin: it does not want the rest + pending = pending[len(pending):] + if not len(pending): + sel.unregister(proc.stdin) + proc.stdin.close() + continue + chunk = os.read(key.fd, CHUNK) + if not chunk: + sel.unregister(key.fileobj) + reading -= 1 + elif key.data == 'out': + out += chunk + if len(out) > contract.MAX_OUTPUT: + return out, err, 'too-much' + else: + err += chunk + if len(err) > 2 * ERR_KEEP: + del err[:-ERR_KEEP] + try: + proc.wait(timeout=max(0.01, deadline - time.monotonic())) + except subprocess.TimeoutExpired: # closed its output but runs on + return out, err, 'timeout' + return out, err, None + finally: + sel.close() + + +def run(project, check, today, gh): + """(findings, ok): the check's findings with "check" set to its id; ok is False when it failed.""" + ctx = json.dumps(context(project, check, today, gh)).encode() + root = config.expand(project['root']) if project['root'] else None + if root and not os.path.isdir(root): + return [failed(check, 'the project root is not a folder', f'root {project["root"]}', + 'fix "root" in the config')], False + try: + proc = subprocess.Popen(command(check), stdin=subprocess.PIPE, stdout=subprocess.PIPE, + stderr=subprocess.PIPE, cwd=root, start_new_session=True, close_fds=True) + except OSError as e: + return [failed(check, 'cannot start', str(e.strerror or e))], False + try: + out, err, why = _talk(proc, ctx, time.monotonic() + check['timeoutSeconds']) + finally: + _kill(proc) # nothing the check started outlives it + try: + proc.wait(timeout=5) + except subprocess.TimeoutExpired: + pass + for f in (proc.stdin, proc.stdout, proc.stderr): + try: + f.close() + except OSError: + pass + if why == 'timeout': + return [failed(check, f'stopped after its timeout of {check["timeoutSeconds"]} s (timeoutSeconds)', + _last_line(err), 'make the check faster, or raise timeoutSeconds')], False + if why == 'too-much': + return [failed(check, f'printed more than {contract.MAX_OUTPUT} bytes: stopped', _last_line(err), + 'a check prints only its findings; notes go to stderr')], False + if proc.returncode != 0: + return [failed(check, f'exited with code {proc.returncode}', _last_line(err))], False + findings = [] + for n, line in enumerate(bytes(out).decode('utf-8', 'replace').splitlines(), 1): + if not line.strip(): + continue + try: + f = contract.parse_finding(line) + except ValueError as e: + return [failed(check, f'printed a line that is not a finding (line {n})', + f'{e}: {line.strip()[:120]!r}', + 'a check prints only finding lines on stdout (README, Checks); notes go to stderr')], \ + False + f['check'] = check['id'] + findings.append(f) + if len(findings) > contract.MAX_FINDINGS: + more = len(findings) - contract.MAX_FINDINGS + findings = findings[:contract.MAX_FINDINGS] + [{ + 'id': 'gardener.more-findings', 'severity': 'info', 'where': '', 'own': True, + 'text': f'{more} more finding(s) not shown', 'fix': 'run the check by hand to see them all', + 'check': check['id']}] + return findings, True diff --git a/fork-kit/gardener/sbin/gardener-install b/fork-kit/gardener/sbin/gardener-install new file mode 100755 index 0000000000000..aef21353afb22 --- /dev/null +++ b/fork-kit/gardener/sbin/gardener-install @@ -0,0 +1,127 @@ +#!/usr/bin/python3 -IB +"""gardener-install: install, uninstall or check the gardener kit, as root (fork-kit/gardener/README.md). + + gardener-install install --source KIT_FOLDER --sha RELEASE_SHA [--timer | --no-timer] + gardener-install uninstall + gardener-install self-check + +install copies bin/gardener, sbin/gardener-install, lib/gardener/, checks/, systemd/, README.md and +fork-kit/common/{machine_file,kit_install}.py of one release into /usr/local/libexec/gardener/versions// (with +MANIFEST.sha256), checks the copy, switches the link `current` to it and links /usr/local/bin/gardener and +/usr/local/sbin/gardener-install to it. With --timer it also writes the kit's one timer: the user units +gardener.service and gardener.timer in /etc/systemd/user/, which run `gardener run --timer` every hour for each +user who enables the timer (the machine file's "gardener" section names the projects and their checks); --no-timer +removes them. Installing never enables the timer for anyone. The choice is kept in /etc/gardener/config.json, so +a run without either option keeps it. Safe to run again, and to stop at any step; one installer at a time. The +steps every kit shares are in fork-kit/common/kit_install.py. +""" +import os, sys +_kit = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) +_common = os.path.join(_kit, 'common') +sys.path[:0] = [_common if os.path.isdir(_common) else os.path.join(os.path.dirname(_kit), 'common')] +try: + import kit_install # noqa: E402 +except ImportError as e: # a copy without common/kit_install.py (changed or partly removed by hand) + sys.exit(f'gardener-install: cannot load its installer code ({e}): install again with the bootstrap, as ' + 'root (fork-kit/gardener/README.md, Install)') + +UNIT_DIR = '/etc/systemd/user' +TIMER_UNITS = ('gardener.service', 'gardener.timer') +UNIT_HEADER = '# gardener kit: written by gardener-install.' +ENABLE = 'systemctl --user daemon-reload && systemctl --user enable --now gardener.timer' +DISABLE = 'systemctl --user disable --now gardener.timer' + + +class GardenerInstaller(kit_install.Installer): + PROG = 'gardener-install' + PROGRAM = __file__ + KIT = 'gardener' + ETC = '/etc/gardener' + LIBEXEC = '/usr/local/libexec/gardener' + LINKS = {'/usr/local/bin/gardener': 'bin/gardener', + '/usr/local/sbin/gardener-install': 'sbin/gardener-install'} + CHECKS = ('checks/context-budget', 'checks/facts', 'checks/install-drift', 'checks/workflows-off', + 'checks/worktrees') + SOURCE_FILES = ('bin/gardener', 'sbin/gardener-install', 'README.md', 'common/machine_file.py', + 'common/kit_install.py', 'systemd/gardener.service', 'systemd/gardener.timer') + CHECKS + EXECUTABLE = frozenset({'bin/gardener', 'sbin/gardener-install'} | set(CHECKS)) + PACKAGE = 'gardener' + MODULES = ('__init__', 'cli', 'config', 'contract', 'judge', 'report', 'runner') + HELP = ('bin/gardener', 'gardener run') + HAS_CONFIG = True + KIT_STEPS = ('timer-units',) + + def add_install_options(self, parser): + parser.add_argument('--timer', dest='timer', action='store_true', default=None) + parser.add_argument('--no-timer', dest='timer', action='store_false') + + def unit_paths(self): + return [f'{UNIT_DIR}/{name}' for name in TIMER_UNITS] + + def ours_unit(self, path): + """A unit file this kit wrote (its first line says so), and no link.""" + real = self.p(path) + if os.path.islink(real): + return False + try: + with open(real, encoding='utf-8') as f: + return f.readline().startswith(UNIT_HEADER) + except OSError: + return False + + def plan(self, a): + timer = a.timer if a.timer is not None else bool(self.read_config().get('timer')) + foreign = [u for u in self.unit_paths() if os.path.lexists(self.p(u)) and not self.ours_unit(u)] + if timer and foreign: + raise self.Refused(f'{foreign[0]} exists and was not written by this kit: remove it and run again, or ' + 'run with --no-timer to leave it alone') + return {'timer': timer} + + def config(self, a, plan): + return {'version': 1, 'timer': plan['timer']} + + def kit_step(self, step, a, plan, dest): + # after the links: the timer is only written once the release it runs is the one in use + for name, path in zip(TIMER_UNITS, self.unit_paths()): + if plan['timer']: + if os.path.lexists(self.p(path)) and not self.ours_unit(path): + raise self.Refused(f'{path} exists and was not written by this kit: remove it and run again, ' + 'or run with --no-timer to leave it alone') + self.ensure_dir(UNIT_DIR) + with open(os.path.join(dest, 'systemd', name), encoding='utf-8') as f: + if self.write_file(path, f.read()): + self.say(f'wrote {path}: each user with a config runs `{ENABLE}`') + if not plan['timer']: + self.remove_units() + + def kit_rows(self, plan): + if not plan['timer']: + return [] + return [(path, 'file', kit_install.sha256_file(self.p(path))) for path in self.unit_paths()] + + def remove_units(self): + """Remove our timer units. Users who enabled the timer disable it first: said before anything goes, so + nobody is left with a link in timers.target.wants to a unit that is gone.""" + ours = [path for path in self.unit_paths() if self.ours_unit(path)] + if ours: + self.say(f'the timer goes: each user who enabled it runs `{DISABLE}` first') + for path in ours: + os.unlink(self.p(path)) + self.say(f'removed {path}') + + def kit_uninstall(self): + self.remove_units() + + def installed_summary(self, plan): + return ', timer units written (every hour; each user enables their own)' if plan['timer'] else ', no timer' + + +INSTALLER = GardenerInstaller() + + +def main(argv, stop_after=None): + return INSTALLER.main(argv, stop_after, doc=__doc__) + + +if __name__ == '__main__': + sys.exit(main(sys.argv[1:])) diff --git a/fork-kit/gardener/systemd/gardener.service b/fork-kit/gardener/systemd/gardener.service new file mode 100644 index 0000000000000..e7ab2d5b60e35 --- /dev/null +++ b/fork-kit/gardener/systemd/gardener.service @@ -0,0 +1,14 @@ +# gardener kit: written by gardener-install. Do not edit: run the installer again. +[Unit] +Description=gardener: run each project's checks once a day, report to its issue (fork-kit/gardener) +# runs the release in use; without one (an uninstall half-way) it does nothing +ConditionPathExists=/usr/local/libexec/gardener/current/bin/gardener + +[Service] +Type=oneshot +ExecStart=/usr/bin/python3 -I -B /usr/local/libexec/gardener/current/bin/gardener run --timer +Nice=10 +IOSchedulingClass=idle +TimeoutStartSec=2h +# files it makes are this user's only +UMask=0077 diff --git a/fork-kit/gardener/systemd/gardener.timer b/fork-kit/gardener/systemd/gardener.timer new file mode 100644 index 0000000000000..d20766ecb9d2f --- /dev/null +++ b/fork-kit/gardener/systemd/gardener.timer @@ -0,0 +1,12 @@ +# gardener kit: written by gardener-install. Do not edit: run the installer again. +[Unit] +Description=gardener tick every hour; each project runs once a day, in its own window (fork-kit/gardener) + +[Timer] +OnStartupSec=10min +OnCalendar=hourly +RandomizedDelaySec=5min +Persistent=true + +[Install] +WantedBy=timers.target diff --git a/fork-kit/gardener/tests/checks.test.py b/fork-kit/gardener/tests/checks.test.py new file mode 100644 index 0000000000000..b319f313b81df --- /dev/null +++ b/fork-kit/gardener/tests/checks.test.py @@ -0,0 +1,421 @@ +"""The general checks shipped with the kit, each run the way the runner runs it (the contract context on stdin) on +fixture files, temporary git repositories, a fake `gh` and a fake `facts`. Every line they print must be a finding. +No network, no root. + + python3 -I -B fork-kit/gardener/tests/checks.test.py +""" +import hashlib, json, os, subprocess, sys, unittest +from unittest import mock + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import gardener_fixture as gf # noqa: E402 +from gardener_fixture import contract # noqa: E402 + +GIT_ENV = dict(os.environ, GIT_AUTHOR_NAME='t', GIT_AUTHOR_EMAIL='t@example.invalid', GIT_COMMITTER_NAME='t', + GIT_COMMITTER_EMAIL='t@example.invalid', GIT_CONFIG_GLOBAL=os.devnull, GIT_CONFIG_NOSYSTEM='1') + + +class Check(gf.Temp): + + env = {} + + def run_check(self, name, options=None, fix=False, repo='example-owner/app', gh='gh', code=0): + ctx = {'version': contract.VERSION, 'project': {'name': 'example', 'repo': repo, 'root': self.root}, + 'check': name, 'options': options or {}, 'fix': fix, 'today': '2026-11-23', 'gh': gh} + r = subprocess.run([sys.executable, '-I', '-B', os.path.join(gf.CHECKS, name)], input=json.dumps(ctx), + capture_output=True, text=True, cwd=self.root, timeout=120, + env=dict(os.environ, **self.env)) + self.assertEqual(r.returncode, code, r.stderr) + found = [contract.parse_finding(ln) for ln in r.stdout.splitlines() if ln.strip()] + self.last_stderr = r.stderr + return found + + def ids(self, found): + return sorted(f['id'] for f in found) + + def write(self, rel, text): + path = os.path.join(self.root, rel) + os.makedirs(os.path.dirname(path), exist_ok=True) + with open(path, 'w') as f: + f.write(text) + return path + + def git(self, repo, *args): + return subprocess.run(['git', '-C', repo, *args], check=True, capture_output=True, text=True, + env=GIT_ENV).stdout.strip() + + +class ContextBudget(Check): + + def test_no_options_no_findings(self): + self.assertEqual(self.run_check('context-budget'), []) + + def test_files_over_near_and_missing(self): + self.write('AGENTS.md', 'x' * 1100) + self.write('CLAUDE.md', 'x' * 900) + self.write('small.md', 'x' * 10) + found = self.run_check('context-budget', {'files': {'AGENTS.md': 1000, 'CLAUDE.md': 1000, + 'small.md': 1000, 'gone.md': 1000}}) + by = {f['where']: f['id'] for f in found} + self.assertEqual(by, {'AGENTS.md': 'context-budget.over', 'CLAUDE.md': 'context-budget.near', + 'gone.md': 'context-budget.missing'}) + + def test_memory_index(self): + self.write('mem/MEMORY.md', '- [A](a.md) — ok\n- [Gone](gone.md) — x\n- ' + 'y' * 200 + '\n') + self.write('mem/a.md', 'a') + self.write('mem/orphan.md', 'o') + found = self.run_check('context-budget', {'memoryIndexes': ['mem/MEMORY.md'], 'indexMaxChars': 100}) + self.assertEqual(self.ids(found), ['context-budget.long-line', 'context-budget.missing-memory', + 'context-budget.orphan-memory', 'context-budget.over']) + + def test_skills(self): + self.write('skills/big/SKILL.md', 'x' * 9000) + self.write('skills/ok/SKILL.md', 'x' * 10) + found = self.run_check('context-budget', {'skillDirs': ['skills']}) + self.assertEqual([(f['id'], f['where']) for f in found], + [('context-budget.over', 'skills/big/SKILL.md')]) + + def test_a_skill_file_that_is_a_broken_link_is_missing(self): + self.write('skills/ok/SKILL.md', 'x' * 10) + os.makedirs(os.path.join(self.root, 'skills', 'gone')) + os.symlink(os.path.join(self.tmp, 'nowhere.md'), os.path.join(self.root, 'skills', 'gone', 'SKILL.md')) + found = self.run_check('context-budget', {'skillDirs': ['skills']}) + self.assertEqual([(f['id'], f['where']) for f in found], + [('context-budget.missing', 'skills/gone/SKILL.md')]) + + +class Facts(Check): + + def fake_facts(self, out, code): + return self.script('facts', f''' + import sys + assert sys.argv[1:] == ['--check', '--no-records'], sys.argv + sys.stdout.write({out!r}) + sys.exit({code}) + ''') + + def test_not_installed_is_a_note(self): + found = self.run_check('facts', {'command': os.path.join(self.tmp, 'no-facts')}) + self.assertEqual(self.ids(found), ['facts.not-installed']) + + def test_problem_lines_become_findings_and_summaries_are_skipped(self): + facts = self.fake_facts('facts check: facts/STATE.md: row "Disk": 40 days old\n' + 'facts check: facts/STATE.md: a row without a "Thing" cell\n' + 'unrelated line\nfacts check: 2 finding(s)\n', 1) + found = self.run_check('facts', {'command': facts}) + self.assertEqual([(f['id'], f['where']) for f in found], + [('facts.stale', 'facts/STATE.md'), ('facts.table', 'facts/STATE.md')]) + facts = self.fake_facts('facts check: OK (3 tables)\n', 0) + self.assertEqual(self.run_check('facts', {'command': facts}), []) + + def test_a_facts_crash_fails_the_check(self): + facts = self.fake_facts('Traceback ...\n', 2) + self.run_check('facts', {'command': facts}, code=1) + self.assertIn('exited with 2', self.last_stderr) + + +class Worktrees(Check): + + def setUp(self): + super().setUp() + self.git(self.root, 'init', '-q', '-b', 'main') + self.write('a.txt', 'a') + self.git(self.root, 'add', '.') + self.git(self.root, 'commit', '-q', '-m', 'one') + + def branch_with_commit(self, name, date=None): + self.git(self.root, 'checkout', '-q', '-b', name) + self.write(f'{name}.txt', name) + self.git(self.root, 'add', '.') + env = dict(GIT_ENV, GIT_AUTHOR_DATE=date or '', GIT_COMMITTER_DATE=date or '') if date else GIT_ENV + subprocess.run(['git', '-C', self.root, 'commit', '-q', '-m', name], check=True, env=env) + self.git(self.root, 'checkout', '-q', 'main') + + def test_clean_repo_no_findings(self): + self.assertEqual(self.run_check('worktrees'), []) + + def merged(self, name): + """A branch with a commit of its own, merged into main (fast-forward).""" + self.branch_with_commit(name) + self.git(self.root, 'merge', '-q', '--ff-only', name) + + def test_merged_stale_prunable_and_branches(self): + self.merged('merged-branch') + self.branch_with_commit('old-work', '2026-09-01T12:00:00+00:00') + self.branch_with_commit('fresh-work') + self.merged('merged-no-tree') + self.git(self.root, 'branch', 'keep-me') + self.git(self.root, 'branch', 'gone-tree') + trees = os.path.join(self.tmp, 'trees') + for b in ('merged-branch', 'old-work', 'fresh-work', 'gone-tree'): + self.git(self.root, 'worktree', 'add', '-q', os.path.join(trees, b), b) + import shutil + shutil.rmtree(os.path.join(trees, 'gone-tree')) + found = self.run_check('worktrees', {'ignore': ['keep-*'], 'staleDays': 14}) + got = sorted((f['id'], f['text'].split(':')[0]) for f in found) + self.assertEqual(got, [('branches.merged', 'branch merged-no-tree'), + ('worktrees.merged', 'worktree of branch merged-branch'), + ('worktrees.prunable', 'worktree record whose folder is gone'), + ('worktrees.stale', 'worktree of branch old-work')]) + self.assertTrue(os.path.isdir(os.path.join(trees, 'merged-branch'))) # report only + + def test_fix_prunes_only_records_of_gone_folders(self): + trees = os.path.join(self.tmp, 'trees') + self.git(self.root, 'branch', 'gone-tree') + self.merged('merged-branch') + self.git(self.root, 'worktree', 'add', '-q', os.path.join(trees, 'gone-tree'), 'gone-tree') + self.git(self.root, 'worktree', 'add', '-q', os.path.join(trees, 'merged-branch'), 'merged-branch') + import shutil + shutil.rmtree(os.path.join(trees, 'gone-tree')) + found = self.run_check('worktrees', fix=True) + self.assertIn('worktrees.pruned', self.ids(found)) + self.assertIn('worktrees.merged', self.ids(found)) + listed = self.git(self.root, 'worktree', 'list', '--porcelain') + self.assertNotIn('gone-tree', listed) + self.assertIn('merged-branch', listed) # a merged worktree is never removed + self.assertIn('gone-tree', self.git(self.root, 'branch', '--list')) # nor a branch + + def test_a_fresh_worktree_is_not_merged(self): + """A branch just made from main (a worktree just started) has its tip in main but no work of its own: not + merged. Made longer ago than staleDays it is a note.""" + trees = os.path.join(self.tmp, 'trees') + self.git(self.root, 'worktree', 'add', '-q', '-b', 'just-started', os.path.join(trees, 'just-started')) + self.git(self.root, 'branch', 'new-branch') + self.assertEqual(self.run_check('worktrees'), []) + old = dict(GIT_ENV, GIT_COMMITTER_DATE='2026-09-01T12:00:00+00:00') + subprocess.run(['git', '-C', self.root, 'worktree', 'add', '-q', '-b', 'old-start', + os.path.join(trees, 'old-start')], check=True, capture_output=True, env=old) + subprocess.run(['git', '-C', self.root, 'branch', 'old-branch'], check=True, env=old) + found = self.run_check('worktrees', {'staleDays': 14}) + self.assertEqual(sorted((f['id'], f['text']) for f in found), + [('branches.no-commits', 'branch old-branch: no commits of its own, made 83 days ago'), + ('worktrees.no-commits', + 'worktree of branch old-start: no commits of its own, made 83 days ago')]) + + def test_a_worktree_made_from_origin_main_is_not_merged_until_pushed(self): + """`git worktree add -b NAME PATH origin/main` (how agents start work) sets origin/main as the branch's + upstream: that is not work of its own. Pushed under its own name, it is.""" + origin = os.path.join(self.tmp, 'origin.git') + self.git(self.tmp, 'init', '-q', '--bare', origin) + self.git(self.root, 'remote', 'add', 'origin', origin) + self.git(self.root, 'push', '-q', 'origin', 'main') + self.git(self.root, 'fetch', '-q', 'origin') + self.git(self.root, 'worktree', 'add', '-q', '-b', 'fresh', os.path.join(self.tmp, 'trees', 'fresh'), + 'origin/main') + self.assertEqual(self.git(self.root, 'config', 'branch.fresh.merge').strip(), 'refs/heads/main') + self.assertEqual(self.run_check('worktrees'), []) + self.git(self.root, 'branch', 'pushed', 'main') + self.git(self.root, 'push', '-q', '-u', 'origin', 'pushed') + self.assertEqual([(f['id'], f['text']) for f in self.run_check('worktrees')], + [('branches.merged', 'branch pushed: merged into origin/main')]) + + def test_a_repos_option_under_home_stays_expandable_in_hints(self): + """A repos option given as ~/... is quoted after its ~/, so the hint still works when pasted.""" + import shlex + home = os.path.join(self.tmp, 'home') + os.makedirs(home) + os.rename(self.root, os.path.join(home, 'my repo')) + self.root = os.path.join(home, 'my repo') + self.merged('plain') + with mock.patch.dict(os.environ, {'HOME': home}): + found = {f['id']: f for f in self.run_check('worktrees', {'repos': ['~/my repo']})} + fix = found['branches.merged']['fix'] + self.assertTrue(fix.startswith("git -C ~/'my repo' branch -d plain"), fix) + self.assertEqual(shlex.split(fix)[2], '~/my repo') + + def test_fix_hints_quote_names(self): + """Git allows $, ;, ( and quotes in branch names: a hint is a command a person (or later an agent) may run, + so every name in it is quoted.""" + import shlex + name = "a;b$(c)'d`e`" + self.merged(name) + trees = os.path.join(self.tmp, 'my trees') + self.git(self.root, 'worktree', 'add', '-q', os.path.join(trees, 'x'), name) + self.merged('plain') + found = {f['id']: f for f in self.run_check('worktrees')} + self.assertEqual(shlex.split(found['worktrees.merged']['fix']), + ['git', '-C', self.root, 'worktree', 'remove', os.path.join(trees, 'x'), '&&', 'git', '-C', + self.root, 'branch', '-d', name]) + self.assertEqual(shlex.split(found['branches.merged']['fix']), + ['git', '-C', self.root, 'branch', '-d', 'plain']) + + def test_missing_and_not_a_repo(self): + os.makedirs(os.path.join(self.tmp, 'plain')) + found = self.run_check('worktrees', {'repos': [os.path.join(self.tmp, 'plain'), + os.path.join(self.tmp, 'none')]}) + self.assertEqual(self.ids(found), ['worktrees.not-a-repo', 'worktrees.repo-missing']) + + def test_an_empty_repo_with_no_commits(self): + empty = os.path.join(self.tmp, 'empty') + os.makedirs(empty) + self.git(empty, 'init', '-q', '-b', 'main') + self.assertEqual(self.run_check('worktrees', {'repos': [empty]}), []) + + +class WorkflowsOff(Check): + + def fake_gh(self, workflows, code=0): + return self.script('gh', f''' + import json, sys + assert sys.argv[1:] == ['api', 'repos/example-owner/app/actions/workflows?per_page=100'], sys.argv + if {code}: + sys.stderr.write('HTTP 403: API rate limit exceeded\\n') + sys.exit({code}) + print(json.dumps({{"total_count": 3, "workflows": {workflows!r}}})) + ''') + + def test_off_workflows_are_reported_and_ignored_ones_not(self): + gh = self.fake_gh([{'name': 'CI', 'path': '.github/workflows/ci.yml', 'state': 'active'}, + {'name': 'Old', 'path': '.github/workflows/old.yml', 'state': 'disabled_manually'}, + {'name': 'Nightly', 'path': '.github/workflows/nightly.yml', + 'state': 'disabled_inactivity'}, + {'name': 'Pages', 'path': 'dynamic/pages/pages-build-deployment', 'state': 'disabled'}]) + found = self.run_check('workflows-off', {'ignore': ['old.yml']}, gh=gh) + self.assertEqual([(f['id'], f['text']) for f in found], + [('workflows.off', 'workflow Nightly is disabled_inactivity')]) + self.assertIn('gh workflow enable nightly.yml -R example-owner/app', found[0]['fix']) + + def test_the_fix_hint_quotes_the_workflow_name(self): + import shlex + gh = self.fake_gh([{'name': 'X', 'path': '.github/workflows/$(touch x);y.yml', 'state': 'disabled_manually'}]) + found = self.run_check('workflows-off', gh=gh) + hint = found[0]['fix'].split(' (or ')[0] + self.assertEqual(shlex.split(hint), ['gh', 'workflow', 'enable', '$(touch x);y.yml', '-R', 'example-owner/app']) + + def test_a_gh_failure_fails_the_check(self): + self.run_check('workflows-off', gh=self.fake_gh([], code=1), code=1) + self.assertIn('rate limit', self.last_stderr) + + def test_no_repo_is_a_note(self): + self.assertEqual(self.ids(self.run_check('workflows-off', repo='')), ['workflows.no-repo']) + + +class InstallDrift(Check): + + def setUp(self): + super().setUp() + self.prefix = os.path.join(self.tmp, 'host') + os.makedirs(self.prefix + '/etc/kit-a') + os.makedirs(self.prefix + '/opt/kit-a/versions/' + 'a' * 40) + os.symlink('/opt/kit-a/versions/' + 'a' * 40, self.prefix + '/opt/kit-a/current') + with open(self.prefix + '/opt/kit-a/tool', 'w') as f: + f.write('tool') + good = hashlib.sha256(b'tool').hexdigest() + self.rows = [('/opt/kit-a/current', 'link', '/opt/kit-a/versions/' + 'a' * 40), + ('/opt/kit-a/tool', 'file', good)] + self.record() + + def record(self, extra=()): + with open(self.prefix + '/etc/kit-a/installed.tsv', 'w') as f: + f.write('# path\tkind\twant\n') + for row in list(self.rows) + list(extra): + f.write('\t'.join(row) + '\n') + + self.env = {'GARDENER_TEST_PREFIX': self.prefix} + + def opts(self, **kw): + return dict({'etc': '/etc'}, **kw) + + def test_as_installed_no_findings(self): + self.assertEqual(self.run_check('install-drift', self.opts()), []) + + def test_changed_files_and_links_and_bad_rows(self): + with open(self.prefix + '/opt/kit-a/tool', 'w') as f: + f.write('changed by hand') + self.record([('/opt/kit-a/gone', 'file', '0' * 64), ('a', 'b')]) + found = self.run_check('install-drift', self.opts()) + self.assertEqual(self.ids(found), ['install-drift.changed']) + self.assertIn('3 installed path(s)', found[0]['text']) + self.assertEqual(found[0]['severity'], 'error') + + def test_old_release_and_missing_record(self): + found = self.run_check('install-drift', self.opts(release='b' * 40, kits=['kit-a', 'kit-b'])) + self.assertEqual(self.ids(found), ['install-drift.no-record', 'install-drift.old-release']) + self.assertEqual(self.run_check('install-drift', self.opts(release='a' * 40)), []) + + def test_gh_apps_rows_have_six_columns(self): + self.record([('/opt/kit-a/tool', 'file', 'root', 'root', '0644', + hashlib.sha256(b'tool').hexdigest())]) + self.assertEqual(self.run_check('install-drift', self.opts()), []) + + def test_no_kits_installed(self): + self.env = {'GARDENER_TEST_PREFIX': os.path.join(self.tmp, 'none')} + self.assertEqual(self.run_check('install-drift', {'etc': '/etc'}), []) + + def test_a_prefix_option_is_not_read(self): + """The folder everything is read under is for tests only, so it is an env var, not a check option.""" + self.env = {} + found = self.run_check('install-drift', {'etc': '/etc', 'prefix': self.prefix, + 'kits': ['gardener-test-no-such-kit']}) + self.assertEqual(self.ids(found), ['install-drift.no-record']) + self.env = {'GARDENER_TEST_PREFIX': self.prefix} + self.assertEqual(self.run_check('install-drift', self.opts(kits=['kit-a'])), []) + + @unittest.skipIf(os.geteuid() == 0, 'root reads everything') + def test_unreadable_paths_are_a_note_not_drift(self): + os.makedirs(self.prefix + '/opt/kit-a/private') + with open(self.prefix + '/opt/kit-a/private/key', 'w') as f: + f.write('k') + os.chmod(self.prefix + '/opt/kit-a/private', 0) + self.addCleanup(os.chmod, self.prefix + '/opt/kit-a/private', 0o755) + self.record([('/opt/kit-a/private/key', 'file', '0' * 64)]) + found = self.run_check('install-drift', self.opts()) + self.assertEqual(self.ids(found), ['install-drift.unreadable']) + + +class Contract(unittest.TestCase): + + def test_parse_finding(self): + f = contract.parse_finding('{"id": "a", "severity": "info", "text": "t"}') + self.assertEqual(f, {'id': 'a', 'severity': 'info', 'text': 't', 'where': '', 'fix': ''}) + for bad in ('', 'x', '[]', '{"id": "", "severity": "info", "text": "t"}', + '{"id": "a b", "severity": "info", "text": "t"}', '{"id": "/home/x", "severity": "info", "text": "t"}', + '{"id": "a", "severity": "info", "text": "t", "where": 5}'): + with self.subTest(bad=bad): + with self.assertRaises(ValueError): + contract.parse_finding(bad) + + def test_a_check_without_a_context_exits_with_a_message(self): + r = subprocess.run([sys.executable, '-I', '-B', os.path.join(gf.CHECKS, 'worktrees')], input='junk', + capture_output=True, text=True, timeout=60) + self.assertNotEqual(r.returncode, 0) + self.assertIn('not a version 1 gardener context', r.stderr) + + + +MUTATIONS = { + 'a finding id is a dotted name': ( + 'contract', " if not ID.fullmatch(obj['id']):", " if False:", 'Contract.test_parse_finding'), + 'a branch with no work of its own is not merged': ( + 'checks/worktrees', "return ('merged', f'merged into {base}') if has else ('empty', days)", + "return ('merged', f'merged into {base}')", 'Worktrees.test_a_fresh_worktree_is_not_merged'), + 'worktrees: names in hints are quoted': ( + 'checks/worktrees', 'q = shlex.quote\n', 'q = str\n', 'Worktrees.test_fix_hints_quote_names'), + 'an upstream that is the base branch is no work of its own': ( + 'checks/worktrees', " if up and up_branch not in (base_branch, 'HEAD'):", ' if up:', + 'Worktrees.test_a_worktree_made_from_origin_main_is_not_merged_until_pushed'), + 'worktrees: a ~/ path stays expandable in hints': ( + 'checks/worktrees', " return '~/' + q(p[2:]) if p.startswith('~/') and len(p) > 2 else q(p)", + ' return q(p)', 'Worktrees.test_a_repos_option_under_home_stays_expandable_in_hints'), + 'workflows-off: names in hints are quoted': ( + 'checks/workflows-off', "f'gh workflow enable {shlex.quote(name)} -R {shlex.quote(repo)}", + "f'gh workflow enable {name} -R {repo}", 'WorkflowsOff.test_the_fix_hint_quotes_the_workflow_name'), + 'context-budget: a broken skill link is a finding': ( + 'checks/context-budget', ' except OSError: # a broken link', + ' except ValueError: # a broken link', + 'ContextBudget.test_a_skill_file_that_is_a_broken_link_is_missing'), + 'install-drift: no prefix option': ( + 'checks/install-drift', "prefix = os.environ.get('GARDENER_TEST_PREFIX', '')", + "prefix = opt.get('prefix') or os.environ.get('GARDENER_TEST_PREFIX', '')", + 'InstallDrift.test_a_prefix_option_is_not_read'), +} + + +class RedCheck(unittest.TestCase): + + def test_each_guard_has_a_test_that_fails_without_it(self): + gf.red_check(self, os.path.abspath(__file__), MUTATIONS) + + +if __name__ == '__main__': + unittest.main(verbosity=2) diff --git a/fork-kit/gardener/tests/gardener_fixture.py b/fork-kit/gardener/tests/gardener_fixture.py new file mode 100644 index 0000000000000..e707b9cfddb86 --- /dev/null +++ b/fork-kit/gardener/tests/gardener_fixture.py @@ -0,0 +1,162 @@ +"""Shared by the gardener tests: a machine file of their own, project checks written on the fly, a fake GitHub, and +RedCheck. No root, no systemd, no network. + +The kit reads the machine file at the fixed path; a test points config.MACHINE_PATH at a file in a temporary folder +owned by the user who runs it (config.OWNER_UID). RedCheck copies lib/ to a temporary folder, breaks one text in +one module, and runs one named test against that copy (GARDENER_TEST_LIB names it). The test must then fail. +A module named "checks/NAME" is a general check: it is broken in a copy of checks/ (GARDENER_TEST_CHECKS).""" +import json, os, shutil, subprocess, sys, tempfile, textwrap, unittest +from unittest import mock + +sys.dont_write_bytecode = True + +KIT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +LIB_ENV = 'GARDENER_TEST_LIB' +LIB = os.environ.get(LIB_ENV) or os.path.join(KIT, 'lib') +CHECKS_ENV = 'GARDENER_TEST_CHECKS' +CHECKS = os.environ.get(CHECKS_ENV) or os.path.join(KIT, 'checks') +sys.path.insert(0, LIB) + +from gardener import cli, config, contract, judge, report, runner # noqa: E402,F401 + +NOW = '2026-11-23T03:30:00+00:00' # 03:30 in Europe/London in November (UTC+0) +REPO = 'example-owner/app' # the test projects' repository and report repository + + +class FakeGitHub: + """The calls report.publish and the visibility check make, on an in-memory list of issues (each in a repository; + the projects' default is REPO).""" + + def __init__(self): + self.issues = {} + self.calls = [] + self.fail = None # a call name that raises GitHubError + self.body_search_blind = False # True: a body search finds nothing (search may skip HTML comments) + self.visibility = {} # repository: private True/False; a missing one fails the read + + def _maybe_fail(self, what): + self.calls.append(what) + if self.fail == what: + raise report.GitHubError(f'gh api {what}: HTTP 403: API rate limit exceeded (rate limit: the next run ' + 'tries again)') + + def add(self, body, state='open', title='Gardener report: example', repo=REPO): + n = len(self.issues) + 1 + self.issues[n] = {'number': n, 'title': title, 'body': body, 'state': state, 'repo': repo} + return n + + def private(self, repo): + self._maybe_fail('private') + if repo not in self.visibility: + raise report.GitHubError(f'gh api GET repos/{repo}: HTTP 404: Not Found') + return self.visibility[repo] + + def issue(self, repo, number): + self._maybe_fail('issue') + if number not in self.issues or self.issues[number]['repo'] != repo: + raise report.GitHubError(f'gh api GET repos/{repo}/issues/{number}: HTTP 404: Not Found') + return dict(self.issues[number]) + + def search_open(self, repo, text, field='body'): + self._maybe_fail('search') + if field == 'body' and self.body_search_blind: + return [] + return [dict(i) for i in self.issues.values() if i['state'] == 'open' and i['repo'] == repo + and text in (i[field] or '')] + + def create(self, repo, title, body): + self._maybe_fail('create') + n = self.add(body, title=title, repo=repo) + return dict(self.issues[n]) + + def edit(self, repo, number, body): + self._maybe_fail('edit') + self.issues[number]['body'] = body + return dict(self.issues[number]) + + def writes(self): + return [c for c in self.calls if c in ('create', 'edit')] + + +class Temp(unittest.TestCase): + """A temporary folder, a machine file in it, the clock at NOW and a fake GitHub.""" + + def setUp(self): + self.tmp = os.path.realpath(tempfile.mkdtemp(prefix='gardener-test-')) + self.addCleanup(shutil.rmtree, self.tmp, True) + self.root = os.path.join(self.tmp, 'repo') + os.makedirs(self.root) + self.state_dir = os.path.join(self.tmp, 'state') + self.machine = os.path.join(self.tmp, 'machine.json') + for p in (mock.patch.object(config, 'MACHINE_PATH', self.machine), + mock.patch.object(config, 'OWNER_UID', os.getuid()), + mock.patch.dict(os.environ, {'GARDENER_TEST_NOW': NOW})): + p.start() + self.addCleanup(p.stop) + self.gh = FakeGitHub() + + def script(self, name, body, mode=0o755): + """An executable Python check script in the temporary folder; its path.""" + path = os.path.join(self.tmp, name) + with open(path, 'w') as f: + f.write(f'#!{sys.executable}\n' + textwrap.dedent(body)) + os.chmod(path, mode) + return path + + def finding_script(self, name, *findings): + lines = '\n'.join(f'print({json.dumps(json.dumps(f))})' for f in findings) + return self.script(name, f'import sys\nsys.stdin.read()\n{lines}\n') + + def project(self, checks, **more): + p = {'name': 'example', 'repo': REPO, 'reportRepo': REPO, 'root': self.root, + 'timeZone': 'Europe/London', 'checks': checks} + p.update(more) + return p + + def write_machine(self, *projects, **section): + data = {'version': 1, 'gardener': dict({'stateDir': self.state_dir, 'projects': list(projects)}, **section)} + with open(self.machine, 'w') as f: + json.dump(data, f) + os.chmod(self.machine, 0o644) + + def run_cli(self, *argv): + """(exit code, stdout) of cli.main in this process, with the fake GitHub.""" + import contextlib, io + out = io.StringIO() + with contextlib.redirect_stdout(out), contextlib.redirect_stderr(out): + code = cli.main(list(argv), gh_factory=lambda gh: self.gh) + return code, out.getvalue() + + def state(self, name='example'): + with open(os.path.join(self.state_dir, name, 'state.json')) as f: + return json.load(f) + + +def red_check(case, test_file, mutations): + """mutations: {rule: (module, text, broken text, 'Class.test_name')}.""" + for rule, (module, text, broken, test) in mutations.items(): + with case.subTest(rule=rule): + tmp = tempfile.mkdtemp(prefix='gardener-red-') + try: + lib = os.path.join(tmp, 'lib') + shutil.copytree(os.path.join(KIT, 'lib'), lib, ignore=shutil.ignore_patterns('__pycache__')) + os.makedirs(os.path.join(tmp, 'common')) # where config finds machine_file in an installed copy + shutil.copy(os.path.join(os.path.dirname(KIT), 'common', 'machine_file.py'), + os.path.join(tmp, 'common')) + env = {LIB_ENV: lib} + if module.startswith('checks/'): + shutil.copytree(os.path.join(KIT, 'checks'), os.path.join(tmp, 'checks'), symlinks=True) + path = env[CHECKS_ENV] = os.path.join(tmp, module) + else: + path = os.path.join(lib, 'gardener', f'{module}.py') + with open(path, encoding='utf-8') as f: + source = f.read() + case.assertEqual(source.count(text), 1, f'{rule}: the text is not in {module} exactly once') + with open(path, 'w', encoding='utf-8') as f: + f.write(source.replace(text, broken)) + r = subprocess.run([sys.executable, '-I', '-B', test_file, test], capture_output=True, text=True, + timeout=300, env=dict(os.environ, **env), stdin=subprocess.DEVNULL) + case.assertIn('Ran 1 test', r.stderr, f'{rule}: {test} did not run:\n{r.stderr[-800:]}') + case.assertNotEqual(r.returncode, 0, f'{test} still passes with {rule!r} broken') + finally: + shutil.rmtree(tmp, ignore_errors=True) diff --git a/fork-kit/gardener/tests/install.test.py b/fork-kit/gardener/tests/install.test.py new file mode 100644 index 0000000000000..03cff4684f05f --- /dev/null +++ b/fork-kit/gardener/tests/install.test.py @@ -0,0 +1,204 @@ +"""gardener-install's own part on a fake host in a temporary folder (every fixed path under PREFIX, the current +user as root): the config and the timer units. What every kit's installer does (copy, switch, links, record, +self-check, stops half-way, uninstall) and the shared bootstrap are tested once for every kit in +fork-kit/common/tests/kit_install.test.py. No root, no systemd, no network. RedCheck breaks each guard in a copy of +the installer and shows its test then fails. + + python3 -I -B fork-kit/gardener/tests/install.test.py +""" +import json, os, shutil, sys, unittest +from unittest import mock + +KIT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +sys.path.insert(0, os.path.join(os.path.dirname(KIT), 'common', 'tests')) +import install_fixture as fx # noqa: E402 + +SHA1, SHA2 = fx.SHA1, fx.SHA2 +UNITS = ('/etc/systemd/user/gardener.service', '/etc/systemd/user/gardener.timer') +FOREIGN = '[Timer]\nOnCalendar=daily\n' + + +class Install(fx.FakeHost): + KIT_DIR, INSTALLER = KIT, os.path.join(KIT, 'sbin', 'gardener-install') + + def config(self): + with open(self.path('/etc/gardener/config.json')) as f: + return json.load(f) + + def units(self): + return [os.path.isfile(self.path(u)) for u in UNITS] + + def test_fresh_install_writes_the_config_and_no_timer(self): + code, out, err = self.install() + self.assertEqual(code, 0, err) + self.assertEqual(self.config(), {'version': 1, 'timer': False}) + self.assertEqual(self.units(), [False, False]) # no timer unless asked + self.assertIn(', no timer', out) + self.assertEqual(self.run_main('self-check')[0], 0) + + def test_runs_again_with_the_timer_and_changes_nothing(self): + self.assertEqual(self.install('--timer')[0], 0) + before = self.snapshot() + code, _, err = self.install() + self.assertEqual(code, 0, err) + self.assertEqual(self.snapshot(), before) + + def test_every_stop_half_way_with_the_timer_then_run_again(self): + for step in self.m.STEPS: + with self.subTest(step=step): + shutil.rmtree(self.root) + os.makedirs(self.root) + code, _, _ = self.install('--timer', stop_after=step) + self.assertEqual(code, f'stopped after {step} (test)') + # a timer only once the release it runs is the one in use + if os.path.exists(self.path(UNITS[0])): + current = os.readlink(self.path('/usr/local/libexec/gardener/current')) + self.assertTrue(os.path.isfile(self.path(current + '/bin/gardener'))) + self.assertTrue(os.path.islink(self.path('/usr/local/bin/gardener'))) + code, _, err = self.install('--timer') + self.assertEqual(code, 0, err) + self.assertEqual(self.units(), [True, True]) + self.assertEqual(self.run_main('self-check')[0], 0) + + def test_a_config_it_cannot_read_is_refused(self): + os.makedirs(self.path('/etc/gardener')) + for text in ('{not json', '[]'): + with self.subTest(text=text): + with open(self.path('/etc/gardener/config.json'), 'w') as f: + f.write(text) + code, _, err = self.install() + self.assertEqual(code, 1) + self.assertIn('/etc/gardener/config.json', err) + self.assertFalse(os.path.exists(self.path('/usr/local/libexec/gardener'))) + + def test_the_timer_unit_ticks_every_hour_from_the_release_in_use(self): + code, out, err = self.install('--timer') + self.assertEqual(code, 0, err) + self.assertIn('systemctl --user enable --now gardener.timer', out) + with open(self.path(UNITS[0])) as f: + text = f.read() + self.assertIn('ExecStart=/usr/bin/python3 -I -B /usr/local/libexec/gardener/current/bin/gardener ' + 'run --timer\n', text) + self.assertIn('Type=oneshot\n', text) + self.assertIn('UMask=0077\n', text) # files it makes: this user's only + self.assertIn('IOSchedulingClass=idle\n', text) # report work never competes with builds + with open(self.path(UNITS[1])) as f: + text = f.read() + self.assertIn('OnCalendar=hourly\n', text) + self.assertIn('WantedBy=timers.target\n', text) + names = os.listdir(self.path('/etc/systemd/user')) + self.assertEqual(sorted(n for n in names if n.endswith('.timer')), ['gardener.timer']) # one timer only + self.assertTrue(self.config()['timer']) + self.assertEqual(self.run_main('self-check')[0], 0) + + def test_the_installed_checks_run_from_the_release(self): + """Each general check in the installed copy finds the kit's lib beside it (no source tree needed).""" + import subprocess + self.assertEqual(self.install()[0], 0) + release = self.path(os.readlink(self.path('/usr/local/libexec/gardener/current'))) + ctx = json.dumps({'version': 1, 'project': {'name': 'x', 'repo': '', 'root': self.root}, 'check': 'c', + 'options': {'files': {}}, 'fix': False, 'today': '2026-11-23', 'gh': 'gh'}) + for name in ('context-budget', 'worktrees'): + path = os.path.join(release, 'checks', name) + self.assertTrue(os.access(path, os.X_OK), name) + r = subprocess.run([sys.executable, '-I', '-B', path], input=ctx, capture_output=True, text=True, + cwd=self.root, timeout=60) + self.assertEqual(r.returncode, 0, r.stderr) + + def assert_disable_said_first(self, out): + """Users are told to disable the timer before the units go, not after (no dangling wants link).""" + said = out.find('systemctl --user disable --now gardener.timer') + removed = out.find('removed /etc/systemd/user/') + self.assertGreaterEqual(said, 0, out) + self.assertGreaterEqual(removed, 0, out) + self.assertLess(said, removed, out) + + def test_timer_kept_by_an_upgrade_and_removed_by_no_timer_and_uninstall(self): + self.assertEqual(self.install('--timer')[0], 0) + self.assertEqual(self.install(sha=SHA2)[0], 0) # upgrade without the option: kept + self.assertEqual(self.units(), [True, True]) + self.assertTrue(os.path.isdir(self.path(f'/usr/local/libexec/gardener/versions/{SHA1}'))) + code, out, _ = self.install('--no-timer', sha=SHA2) + self.assertEqual(code, 0) + self.assert_disable_said_first(out) + self.assertEqual(self.units(), [False, False]) + self.assertEqual(self.install(sha=SHA2)[0], 0) # again without the option: still off + self.assertEqual(self.units(), [False, False]) + self.assertEqual(self.run_main('self-check')[0], 0) + self.assertEqual(self.install('--timer', sha=SHA2)[0], 0) + code, out, _ = self.run_main('uninstall') + self.assertEqual(code, 0) + self.assert_disable_said_first(out) + self.assertEqual(self.units(), [False, False]) + for gone in ('/usr/local/libexec/gardener', '/etc/gardener', '/usr/local/bin/gardener', + '/usr/local/sbin/gardener-install'): + self.assertFalse(os.path.lexists(self.path(gone)), gone) + self.assertEqual(self.run_main('uninstall')[0], 0) # again: nothing left, still fine + + def test_units_someone_else_wrote_are_refused_and_kept(self): + os.makedirs(self.path('/etc/systemd/user')) + with open(self.path(UNITS[1]), 'w') as f: + f.write(FOREIGN) + code, _, err = self.install('--timer') + self.assertEqual(code, 1) + self.assertIn('was not written by this kit', err) + self.assertIn('--no-timer', err) + self.assertFalse(os.path.exists(self.path('/usr/local/libexec/gardener'))) + self.assertEqual(self.install()[0], 0) # without the option it is left alone + self.assertEqual(self.run_main('uninstall')[0], 0) + with open(self.path(UNITS[1])) as f: + self.assertEqual(f.read(), FOREIGN) + os.unlink(self.path(UNITS[1])) + with open(self.path('/elsewhere'), 'w') as f: # a link is never ours either, even + f.write('# gardener kit: written by gardener-install.\n') # to a file that says so + os.symlink(self.path('/elsewhere'), self.path(UNITS[1])) + self.assertEqual(self.install('--timer')[0], 1) + + def test_a_unit_someone_writes_during_the_install_is_refused_and_kept(self): + """The units are checked again right before they are written: one written while the installer ran (after + its first check) is not overwritten.""" + real = self.m.switch_link + + def and_a_foreign_unit(path, target): + real(path, target) + if not os.path.lexists(self.path(UNITS[1])): + os.makedirs(self.path('/etc/systemd/user'), exist_ok=True) + with open(self.path(UNITS[1]), 'w') as f: + f.write(FOREIGN) + with mock.patch.object(self.m, 'switch_link', and_a_foreign_unit): + code, _, err = self.install('--timer') + self.assertEqual(code, 1) + self.assertIn('was not written by this kit', err) + with open(self.path(UNITS[1])) as f: + self.assertEqual(f.read(), FOREIGN) + + +MUTATIONS = { + 'units: checked again before they are written': ( + 'installer', ' if os.path.lexists(self.p(path)) and not self.ours_unit(path):\n' + ' raise', ' if False:\n raise', + 'test_a_unit_someone_writes_during_the_install_is_refused_and_kept'), + 'units: a foreign unit is refused before anything is written': ( + 'installer', ' if timer and foreign:', ' if False:', + 'test_units_someone_else_wrote_are_refused_and_kept'), + 'units: a link is never ours': ( + 'installer', ' if os.path.islink(real):\n return False\n', '', + 'test_units_someone_else_wrote_are_refused_and_kept'), + 'timer: kept by a run without the option': ( + 'installer', "bool(self.read_config().get('timer'))", 'False', + 'test_timer_kept_by_an_upgrade_and_removed_by_no_timer_and_uninstall'), + 'units: disable is said before they are removed': ( + 'installer', " if ours:\n self.say(f'the timer goes: each user who enabled it runs `{DISABLE}` first')\n", + '', 'test_timer_kept_by_an_upgrade_and_removed_by_no_timer_and_uninstall'), +} + + +class RedCheck(unittest.TestCase): + BASE = Install + + def test_each_guard_has_a_test_that_fails_without_it(self): + fx.red_check(self, MUTATIONS) + + +if __name__ == '__main__': + unittest.main(verbosity=2) diff --git a/fork-kit/gardener/tests/report.test.py b/fork-kit/gardener/tests/report.test.py new file mode 100644 index 0000000000000..60e8d2e3592de --- /dev/null +++ b/fork-kit/gardener/tests/report.test.py @@ -0,0 +1,456 @@ +"""The report issue (missing, closed, edited by hand, its marker removed, a GitHub error), what goes into it (the +allow-list: nothing local reaches the issue; the size cap) and the judgment step (a fake local model over HTTP, one +that is not there and one that does not speak HTTP). +GitHub is a fake (gardener_fixture.FakeGitHub); the `gh api` wrapper is run against a fake gh script. + + python3 -I -B fork-kit/gardener/tests/report.test.py +""" +import http.server, json, os, socket, subprocess, sys, threading, unittest + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import gardener_fixture as gf # noqa: E402 +from gardener_fixture import judge, report # noqa: E402 + +GOOD = {'id': 'demo.thing', 'severity': 'warn', 'where': 'docs/a.md', 'text': 'a thing', 'fix': ''} +PART = report.marker('example') + '\nnew report\n' + + +class Publish(unittest.TestCase): + + def setUp(self): + self.gh = gf.FakeGitHub() + + def test_missing_issue_is_created(self): + self.assertEqual(report.publish(self.gh, gf.REPO, 'example', PART), (1, 'created')) + self.assertEqual(self.gh.calls, ['search', 'search', 'create']) # by title, then by marker + self.assertEqual(self.gh.issues[1]['title'], 'Gardener report: example') + + def test_the_remembered_issue_is_edited_without_a_search(self): + n = self.gh.add(report.marker('example') + '\nold\n') + self.assertEqual(report.publish(self.gh, gf.REPO, 'example', PART, known_number=n), (n, 'updated')) + self.assertEqual(self.gh.calls, ['issue', 'edit']) + self.assertEqual(self.gh.issues[n]['body'], PART) + + def test_a_forgotten_issue_is_found_by_its_title(self): + """GitHub search may not index the hidden marker (an HTML comment): the title is searched first.""" + self.gh.body_search_blind = True + self.gh.add('another issue') + n = self.gh.add('text\n' + report.marker('example') + '\nold\n') + self.gh.add(report.marker('other-project') + '\n', title='Gardener report: other-project') + self.assertEqual(report.publish(self.gh, gf.REPO, 'example', PART), (n, 'updated')) + self.assertEqual(self.gh.calls, ['search', 'edit']) + + def test_a_forgotten_issue_renamed_by_hand_is_found_by_its_marker(self): + self.gh.add('another issue') + n = self.gh.add('text\n' + report.marker('example') + '\nold\n', title='Docs work this week') + self.assertEqual(report.publish(self.gh, gf.REPO, 'example', PART), (n, 'updated')) + self.assertEqual(self.gh.calls, ['search', 'search', 'edit']) + + def test_two_open_report_issues_always_pick_the_oldest(self): + self.gh.add('x') + first = self.gh.add(report.marker('example')) + self.gh.add(report.marker('example')) + self.assertEqual(report.publish(self.gh, gf.REPO, 'example', PART)[0], first) + + def test_a_closed_report_issue_stays_closed_and_a_new_one_is_opened(self): + n = self.gh.add(report.marker('example') + '\nold\n', state='closed') + number, how = report.publish(self.gh, gf.REPO, 'example', PART, known_number=n) + self.assertEqual((number, how), (2, 'created')) + self.assertEqual(self.gh.issues[n]['body'], report.marker('example') + '\nold\n') + self.assertEqual(self.gh.issues[n]['state'], 'closed') + + def test_an_issue_whose_marker_was_removed_by_hand_is_left_alone(self): + n = self.gh.add('I took this issue over for something else') + self.assertEqual(report.publish(self.gh, gf.REPO, 'example', PART, known_number=n), (2, 'created')) + self.assertEqual(self.gh.issues[n]['body'], 'I took this issue over for something else') + + def test_a_deleted_remembered_issue_falls_back_to_the_search(self): + n = self.gh.add(report.marker('example')) + self.assertEqual(report.publish(self.gh, gf.REPO, 'example', PART, known_number=99), (n, 'updated')) + self.assertEqual(self.gh.calls, ['issue', 'search', 'edit']) + + def test_text_written_above_the_marker_by_hand_is_kept(self): + n = self.gh.add('Owner note: ignore the docs warnings this week.\n\n' + report.marker('example') + + '\nold report\n') + report.publish(self.gh, gf.REPO, 'example', PART, known_number=n) + self.assertEqual(self.gh.issues[n]['body'], + 'Owner note: ignore the docs warnings this week.\n\n' + PART) + + def test_a_long_hand_written_text_is_cut_so_the_body_fits(self): + n = self.gh.add('H' * 70000 + report.marker('example') + '\nold\n') + part = report.marker('example') + '\n' + 'p' * 40000 + '\n' + report.publish(self.gh, gf.REPO, 'example', part, known_number=n) + body = self.gh.issues[n]['body'] + self.assertLessEqual(len(body), report.MAX_BODY) + self.assertTrue(body.endswith(part)) # the gardener's part is whole + self.assertIn('the text above was cut', body) + self.assertTrue(body.startswith('H' * 1000)) + + def test_a_pull_request_with_the_marker_is_not_the_report(self): + n = self.gh.add(report.marker('example')) + self.gh.issues[n]['pull_request'] = {} + self.assertEqual(report.publish(self.gh, gf.REPO, 'example', PART, known_number=n)[1], 'created') + + def test_a_github_error_on_search_or_write_is_raised(self): + for what in ('search', 'create', 'edit'): + with self.subTest(what=what): + self.gh = gf.FakeGitHub() + if what == 'edit': + self.gh.add(report.marker('example')) + self.gh.fail = what + with self.assertRaises(report.GitHubError): + report.publish(self.gh, gf.REPO, 'example', PART) + + +class GhWrapper(gf.Temp): + """report.GitHub runs `gh api` and turns its failures into GitHubError, naming rate limits.""" + + def fake_gh(self, body): + return self.script('gh', body) + + def test_calls_and_answers(self): + log = os.path.join(self.tmp, 'log') + gh = self.fake_gh(f''' + import json, sys + data = sys.stdin.read() + open({log!r}, 'a').write(json.dumps([sys.argv[1:], data]) + '\\n') + print(json.dumps({{"items": [{{"number": 3}}], "number": 4}})) + ''') + g = report.GitHub(gh) + self.assertEqual(g.search_open('o/r', 'gardener-report:x'), [{'number': 3}]) + self.assertEqual(g.search_open('o/r', 'Gardener report: x', 'title'), [{'number': 3}]) + self.assertEqual(g.create('o/r', 'T', 'B')['number'], 4) + self.assertEqual(g.edit('o/r', 4, 'B2')['number'], 4) + with open(log) as f: + calls = [json.loads(ln) for ln in f] + self.assertEqual(calls[0][0][:4], ['api', '--method', 'GET', calls[0][0][3]]) + self.assertIn('is%3Aopen', calls[0][0][3]) + self.assertIn('in%3Abody', calls[0][0][3]) + self.assertIn('in%3Atitle', calls[1][0][3]) + self.assertEqual(calls[2], [['api', '--method', 'POST', 'repos/o/r/issues', '--input', '-'], + json.dumps({'title': 'T', 'body': 'B'})]) + self.assertEqual(calls[3][0][2:4], ['PATCH', 'repos/o/r/issues/4']) + + def test_failures(self): + for body, want in (('import sys\nsys.stderr.write("HTTP 403: API rate limit exceeded\\n")\nsys.exit(1)', + 'rate limit: the next run tries again'), + ('import sys\nsys.stderr.write("HTTP 404: Not Found\\n")\nsys.exit(1)', 'HTTP 404'), + ('print("not json")', 'not JSON')): + with self.subTest(want=want): + with self.assertRaises(report.GitHubError) as e: + report.GitHub(self.fake_gh(body)).issue('o/r', 1) + self.assertIn(want, str(e.exception)) + with self.assertRaises(report.GitHubError): + report.GitHub(os.path.join(self.tmp, 'no-gh')).issue('o/r', 1) + + +class Render(unittest.TestCase): + + def finding(self, **kw): + return dict(dict(GOOD, check='c'), **kw) + + def test_local_paths_are_redacted(self): + root, home = '/srv/u/repo', '/srv/u' + f = self.finding(where='/srv/u/repo/docs/a.md', text='see /srv/u/notes and /srv/u/repo', fix='') + body = report.render_issue('example', '2026-11-23', [f], ['note about /srv/u/repo/x'], 'judge saw /srv/u/x', + root=root, home=home, text_checks={'c'}) + self.assertNotIn('/srv/u', body) + self.assertIn('| docs/a.md |', body) + self.assertIn('see and .', body) + self.assertIn('note about ./x', body) + self.assertIn('judge saw ', body) + + def test_table_cells_are_escaped_and_sorted_by_severity(self): + fs = [self.finding(severity='info', id='i'), self.finding(severity='error', id='e', text='a | b\nc')] + for body in (report.render_issue('example', '2026-11-23', fs, [], text_checks={'c'}), + report.render_local('example', '2026-11-23', fs, [])): + self.assertLess(body.index('| error |'), body.index('| info |')) + self.assertIn('a \\| b c', body) + self.assertIn('1 error(s), 0 warning(s), 1 note(s)', body) + + def test_no_findings(self): + body = report.render_issue('example', '2026-11-23', [], []) + self.assertTrue(body.startswith(report.marker('example') + '\n')) + self.assertIn('No findings.', body) + self.assertNotIn('| Severity', body) + + def test_the_body_stays_under_githubs_limit(self): + fs = [self.finding(id=f'n.{i}', text='x' * 1500) for i in range(200)] + body = report.render_issue('example', '2026-11-23', fs, ['a note'], 'j' * 8000, text_checks={'c'}) + self.assertLess(len(body), report.MAX_PART) + self.assertIn('more row(s) not shown (the issue is full)', body) + self.assertIn('### Judgment', body) + self.assertEqual(report.render_local('example', '2026-11-23', fs, []).count('| warn |'), 200) + + def test_only_paths_inside_the_repository_are_shown(self): + root = '/srv/u/repo' + cases = {'docs/a.md': 'docs/a.md', 'docs/a.md:12': 'docs/a.md:12', '/srv/u/repo/b/c.py:3': 'b/c.py:3', + '.': '.', '': '', '/srv/u/other/x.md': None, '../x': None, '~/notes.md': None, + '/etc/passwd': None, 'docs/a b.md': None, 'example-owner/app: .github/workflows/ci.yml': + 'example-owner/app: .github/workflows/ci.yml', 'someone/private: x.yml': None, + 'example-owner/app: /srv/u/x': None} + for where, want in cases.items(): + with self.subTest(where=where): + self.assertEqual(report.public_where(where, root, 'example-owner/app'), want) + + def test_a_finding_outside_the_repository_is_only_counted(self): + fs = [self.finding(where='/srv/u/.claude/projects/-srv-u--repo/memory/plans.md', text='orphan plans.md'), + self.finding(where='/srv/u/.claude/projects/-srv-u--repo/memory/b.md', text='orphan b.md'), + self.finding(where='', text='private-host is down', id='x.y'), + dict(GOOD, check='c', id='gardener.check-failed', where='', own=True, text='exited with code 1', + detail='ssh: connect to host private-host port 22')] + issue = report.render_issue('example', '2026-11-23', fs, [], root='/srv/u/repo', home='/srv/u') + local = report.render_local('example', '2026-11-23', fs, []) + for secret in ('plans.md', 'b.md', 'private-host', '-srv-u-', '/srv/u'): + self.assertNotIn(secret, issue) + self.assertIn('| warn | c | 2 finding(s), in the local report only | |', issue) + self.assertIn('| warn | c | 1 finding(s), in the local report only | |', issue) + self.assertNotIn('x.y', issue) # a hidden finding's id is not shown + self.assertIn('gardener.check-failed: exited with code 1', issue) + self.assertIn('report.md', issue) # where the rest is + for shown in ('plans.md', 'private-host is down', 'ssh: connect to host private-host'): + self.assertIn(shown, local) + + def test_the_root_is_replaced_only_as_a_whole_folder(self): + for text, want in (('/srv/u/repo2/client-acme-plan.md', ''), ('/srv/u/repo/docs/a.md', './docs/a.md'), + ('in /srv/u/repo.', 'in ..'), ('/srv/u/repo: x', '.: x'), ('/srv/u/repository', ''), + ('a/srv/u/x', 'a')): + with self.subTest(text=text): + self.assertEqual(report.public_text(text, '/srv/u/repo', '/srv/u'), want) + + def test_a_project_checks_text_is_shown_only_with_public_text(self): + fs = [self.finding(check='proj', id='host.box1.down', where='docs/a.md', text='build-box is down', + fix='ssh build-box'), + self.finding(check='proj', id='host.box1.down', where='docs/a.md', text='build-box2 is down'), + self.finding(check='general', id='g.x', where='docs/b.md', text='budget passed')] + issue = report.render_issue('example', '2026-11-23', fs, [], root='/srv/u/repo', home='/srv/u', + text_checks={'general'}) + self.assertNotIn('build-box', issue) + self.assertIn('| warn | proj | host.box1.down: 2 finding(s), text in the local report only (the check is not ' + 'set to publicText) | docs/a.md | |', issue) + self.assertIn('g.x: budget passed', issue) + shown = report.render_issue('example', '2026-11-23', fs, [], root='/srv/u/repo', home='/srv/u', + text_checks={'general', 'proj'}) + self.assertIn('host.box1.down: build-box is down', shown) + + def test_counts_only_shows_no_text_id_where_or_judgment(self): + fs = [self.finding(check='general', id='g.x', where='docs/b.md', text='budget passed'), + self.finding(check='general', id='g.y', where='docs/c.md', text='other'), + dict(GOOD, check='c', id='gardener.check-failed', where='', own=True, text='exited with code 1')] + issue = report.render_issue('example', '2026-11-23', fs, ['a note'], 'the model says x', root='/srv/u/repo', + home='/srv/u', text_checks={'general', 'c'}, counts_only=True) + for gone in ('g.x', 'g.y', 'budget', 'docs/', 'the model says', 'exited with code'): + self.assertNotIn(gone, issue) + self.assertIn('| warn | general | 2 finding(s), in the local report only | | |', issue) + self.assertIn(report.COUNTS_ONLY, issue) + self.assertIn('a note', issue) + + def test_masks(self): + for text, gone in (('see http://100.64.1.2:8080/v1 now', '100.64'), ('mail a.b@example.org', 'a.b@'), + ('host 10.0.0.5 down', '10.0.0.5'), ('at fe80::1:2', 'fe80'), + ('box nas.local and pc.tail1234.ts.net', 'nas'), ('in ~/secret/x', 'secret'), + ('memory -home-user--proj', 'user'), ('file /opt/x/y', '/opt'), + ('ssh admin@build-box failed', 'build-box'), ('ip 2001:db8:a1e0::1 up', '2001'), + ('ip 2001:db8:a1e0::1 up', 'a1e0'), ('bind :: now', '::'), ('lo ::1', '::1'), + (r'C:\Users\alice\secret\plan.txt', 'alice'), ('C:/Users/alice/x', 'alice'), + (r'share \\nas\private\x', 'nas'), ('a/srv/u/x y', '/srv'), ('a~/secret/x', 'secret')): + with self.subTest(text=text): + self.assertNotIn(gone, report.public_text(text, '/srv/u/repo', '/srv/u')) + for kept in ('origin/main is ahead', 'docs/a.md', 'at 12:30:45', 'std::vector', 'a.b c'): + with self.subTest(kept=kept): + self.assertEqual(report.public_text(kept, '/srv/u/repo', '/srv/u'), kept) + + +class Judge(gf.Temp): + + def serve(self, answer, status=200): + seen = [] + + class H(http.server.BaseHTTPRequestHandler): + def do_POST(self): + seen.append((self.path, json.loads(self.rfile.read(int(self.headers['Content-Length']))))) + data = json.dumps(answer).encode() + self.send_response(status) + self.send_header('Content-Type', 'application/json') + self.send_header('Content-Length', str(len(data))) + self.end_headers() + self.wfile.write(data) + + def log_message(self, *a): + pass + server = http.server.HTTPServer(('127.0.0.1', 0), H) + threading.Thread(target=server.serve_forever, daemon=True).start() + self.addCleanup(server.server_close) + self.addCleanup(server.shutdown) + return f'http://127.0.0.1:{server.server_port}/v1', seen + + def model(self, endpoint, **kw): + return dict({'endpoint': endpoint, 'model': 'local-model', 'timeoutSeconds': 10, 'maxFiles': 5, + 'maxFileBytes': 100}, **kw) + + def git(self, *args): + env = dict(os.environ, GIT_AUTHOR_NAME='t', GIT_AUTHOR_EMAIL='t@example.invalid', GIT_COMMITTER_NAME='t', + GIT_COMMITTER_EMAIL='t@example.invalid', GIT_CONFIG_GLOBAL=os.devnull, GIT_CONFIG_NOSYSTEM='1') + subprocess.run(['git', '-C', self.tmp, *args], check=True, capture_output=True, env=env) + + def repo_files(self): + """The project root is a folder of a larger repository: docs/a.md tracked; .env ignored; notes.txt + untracked; secret.txt tracked too, but outside the root.""" + os.makedirs(os.path.join(self.root, 'docs')) + for rel, text in (('docs/a.md', 'A' * 500), ('.gitignore', '.env\n'), ('.env', 'TOKEN=ignored-secret'), + ('notes.txt', 'untracked-secret'), ('../secret.txt', 'outside the root')): + with open(os.path.join(self.root, rel), 'w') as f: + f.write(text) + self.git('init', '-q', '-b', 'main') + self.git('add', 'repo/docs/a.md', 'repo/.gitignore', 'secret.txt') + self.git('commit', '-q', '-m', 'one') + + def test_the_model_gets_findings_and_only_tracked_files_inside_the_root(self): + self.repo_files() + endpoint, seen = self.serve({'choices': [{'message': {'content': ' looks real \n'}}]}) + fs = [dict(GOOD, check='c', where=w) for w in ('docs/a.md:3', '../secret.txt', '/etc/passwd', '.env', + 'notes.txt')] + answer, note = judge.judge(self.model(endpoint), fs, self.root) + self.assertEqual(answer, 'looks real') + self.assertEqual(note, 'judgment: model reachable; it read 5 finding(s) and 1 file(s)') + self.assertNotIn('127.0.0.1', note) + path, req = seen[0] + self.assertEqual(path, '/v1/chat/completions') + self.assertEqual((req['model'], req['temperature']), ('local-model', 0)) + user = req['messages'][1]['content'] + self.assertIn('File docs/a.md:', user) + self.assertIn('A' * 100, user) + self.assertNotIn('A' * 101, user) # cut to maxFileBytes + for secret in ('outside the root', 'root:x:', 'ignored-secret', 'untracked-secret'): + self.assertNotIn(secret, user) + + def test_no_model_no_findings_and_bad_answers(self): + self.assertEqual(judge.judge(None, [GOOD], self.root), (None, None)) + endpoint, seen = self.serve({'choices': []}) + self.assertEqual(judge.judge(self.model(endpoint), [], self.root)[0], None) + self.assertEqual(seen, []) # nothing to judge: no request + for answer, status in (({'choices': []}, 200), ({'error': 'x'}, 500), + ({'choices': [{'message': {'content': ' '}}]}, 200), ([1], 200)): + with self.subTest(answer=answer): + endpoint, _ = self.serve(answer, status) + got, note = judge.judge(self.model(endpoint), [dict(GOOD, check='c')], self.root) + self.assertIsNone(got) + self.assertIn('judgment: model unreachable or no usable answer', note) + self.assertNotIn('127.0.0.1', note) + + def junk_server(self, reply): + """A socket that answers every connection with reply and closes (a wrong port: ssh, not HTTP).""" + srv = socket.socket() + srv.bind(('127.0.0.1', 0)) + srv.listen(4) + self.addCleanup(srv.close) + + def serve(): + while True: + try: + conn, _ = srv.accept() + except OSError: + return + with conn: + conn.recv(65536) + conn.sendall(reply) + threading.Thread(target=serve, daemon=True).start() + return f'http://127.0.0.1:{srv.getsockname()[1]}/v1' + + def test_an_endpoint_that_does_not_speak_http_is_a_note(self): + for reply in (b'SSH-2.0-OpenSSH_9.6\r\n', b'HTTP/1.1 200 OK\r\nContent-Length: 500\r\n\r\n{"cho'): + with self.subTest(reply=reply): + got, note = judge.judge(self.model(self.junk_server(reply)), [dict(GOOD, check='c')], self.root) + self.assertIsNone(got) + self.assertIn('model unreachable', note) + + def test_an_unreachable_model_is_a_note_and_the_run_goes_on(self): + s = socket.socket() + s.bind(('127.0.0.1', 0)) + port = s.getsockname()[1] + s.close() # nothing listens there now + self.write_machine(self.project([{'path': self.finding_script('demo', GOOD)}], + model={'endpoint': f'http://127.0.0.1:{port}/v1', 'model': 'm', + 'timeoutSeconds': 5})) + code, out = self.run_cli('run') + self.assertEqual(code, 0, out) + body = self.gh.issues[1]['body'] + self.assertIn('judgment: model unreachable', body) + self.assertNotIn(str(port), body) # the endpoint is never shown + self.assertNotIn('### Judgment', body) + + def test_the_judgment_goes_into_the_report(self): + endpoint, _ = self.serve({'choices': [{'message': {'content': 'demo.thing: real; fix the doc first'}}]}) + self.write_machine(self.project([{'path': self.finding_script('demo', GOOD)}], + model={'endpoint': endpoint, 'model': 'm'})) + self.assertEqual(self.run_cli('run')[0], 0) + self.assertIn('### Judgment (local model)\n\ndemo.thing: real; fix the doc first', self.gh.issues[1]['body']) + + +MUTATIONS = { + 'a closed issue is not the report': ( + 'report', "issue.get('state') == 'open' and ", '', + 'Publish.test_a_closed_report_issue_stays_closed_and_a_new_one_is_opened'), + 'an issue without the marker is not the report': ( + 'report', " and marker(name) in (issue.get('body') or ''))", ')', + 'Publish.test_an_issue_whose_marker_was_removed_by_hand_is_left_alone'), + 'hand-written text above the marker is kept': ( + 'report', " head = old_body[:old_body.index(marker(name))]", " head = ''", + 'Publish.test_text_written_above_the_marker_by_hand_is_kept'), + 'the root is shown as "."': ( + 'report', " text = re.sub(re.escape(path) + _END, short, text)", ' pass', + 'Render.test_local_paths_are_redacted'), + 'the root is replaced only as a whole folder': ( + 'report', " text = re.sub(re.escape(path) + _END, short, text)", + ' text = text.replace(path, short)', 'Render.test_the_root_is_replaced_only_as_a_whole_folder'), + 'a project check shows its text only with publicText': ( + 'report', " elif not f.get('own') and f['check'] not in text_checks:", ' elif False:', + 'Render.test_a_project_checks_text_is_shown_only_with_public_text'), + 'counts only hides everything but counts': ( + 'report', ' if counts_only:\n key', ' if False:\n key', + 'Render.test_counts_only_shows_no_text_id_where_or_judgment'), + 'counts only drops the judgment': ( + 'report', 'if judgment and not counts_only else None', 'if judgment else None', + 'Render.test_counts_only_shows_no_text_id_where_or_judgment'), + 'a hidden finding shows no id': ( + 'report', " key = (f['severity'], f['check'], '', OUTSIDE if w is None", + " key = (f['severity'], f['check'], f['id'], OUTSIDE if w is None", + 'Render.test_a_finding_outside_the_repository_is_only_counted'), + 'text in the issue is masked': ( + 'report', " for rx, sub in _MASKS:\n text = rx.sub(sub, text)\n", '', + 'Render.test_masks'), + 'a where outside the repository is not shown': ( + 'report', " if w == '..' or w.startswith('../') or not _SAFE_REL.fullmatch(w):\n return None\n", '', + 'Render.test_only_paths_inside_the_repository_are_shown'), + 'a finding outside the repository is only counted': ( + 'report', " elif w is None or (w == '' and not f.get('own')):", + " elif False:", 'Render.test_a_finding_outside_the_repository_is_only_counted'), + 'judge reads only files inside the root': ( + 'judge', 'not full.startswith(real_root + os.sep) or ', '', + 'Judge.test_the_model_gets_findings_and_only_tracked_files_inside_the_root'), + 'judge reads only tracked files': ( + 'judge', ' if not tracked(real_root, rel):\n continue\n', '', + 'Judge.test_the_model_gets_findings_and_only_tracked_files_inside_the_root'), + 'judge: any failure is a note': ( + 'judge', ' except Exception as e:', ' except (OSError, ValueError, KeyError, IndexError, TypeError) as e:', + 'Judge.test_an_endpoint_that_does_not_speak_http_is_a_note'), + 'the issue part is capped': ( + 'report', ' if len(row) + 1 > budget:\n break\n', '', + 'Render.test_the_body_stays_under_githubs_limit'), + 'a long hand-written text is cut': ( + 'report', ' if len(head) > room:', ' if False:', + 'Publish.test_a_long_hand_written_text_is_cut_so_the_body_fits'), + 'the forgotten issue is searched by title first': ( + 'report', "((f'Gardener report: {name}', 'title'), (f'gardener-report:{name}', 'body'))", + "((f'gardener-report:{name}', 'body'),)", 'Publish.test_a_forgotten_issue_is_found_by_its_title'), +} + + +class RedCheck(unittest.TestCase): + + def test_each_guard_has_a_test_that_fails_without_it(self): + gf.red_check(self, os.path.abspath(__file__), MUTATIONS) + + +if __name__ == '__main__': + unittest.main(verbosity=2) diff --git a/fork-kit/gardener/tests/run.test.py b/fork-kit/gardener/tests/run.test.py new file mode 100644 index 0000000000000..53e6ecd2b2be4 --- /dev/null +++ b/fork-kit/gardener/tests/run.test.py @@ -0,0 +1,777 @@ +"""gardener run: the state question (empty, missing, broken, old and newer state; a second run the same day; a run +stopped half-way; a report issue that cannot be written), the check contract (a check that hangs, prints junk or +without end, exits non-zero or cannot start never stops the run; nor does one project's failure stop the next), dry +run, the lock, the timer window, what reaches the public issue, and the config. Project checks are small scripts written by each test; +GitHub is a fake (gardener_fixture.FakeGitHub). No root, no network. + + python3 -I -B fork-kit/gardener/tests/run.test.py +""" +import json, os, subprocess, sys, time, unittest +from unittest import mock + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import gardener_fixture as gf # noqa: E402 +from gardener_fixture import cli, config, contract, report, runner # noqa: E402 + +GOOD = {'id': 'demo.thing', 'severity': 'warn', 'where': 'docs/a.md', 'text': 'a thing to look at', + 'fix': 'look at it'} + + +class State(gf.Temp): + + def setUp(self): + super().setUp() + self.ran = os.path.join(self.tmp, 'ran') + self.check = self.script('demo', f''' + import json, sys + sys.stdin.read() + open({self.ran!r}, 'a').write('x') + print(json.dumps({GOOD!r})) + ''') + self.write_machine(self.project([{'path': self.check, 'publicText': True}])) + + def runs(self): + """How often the check ran.""" + try: + with open(self.ran) as f: + return len(f.read()) + except FileNotFoundError: + return 0 + + def folder(self): + return os.path.join(self.state_dir, 'example') + + def write_state(self, text): + os.makedirs(self.folder(), exist_ok=True) + with open(os.path.join(self.folder(), 'state.json'), 'w') as f: + f.write(text) + + def test_empty_state_runs_creates_the_issue_and_marks_the_day(self): + code, out = self.run_cli('run') + self.assertEqual(code, 0, out) + self.assertEqual(self.gh.writes(), ['create']) + st = self.state() + self.assertEqual((st['version'], st['doneDay'], st['issue'], st['findings'], st['reportPending'], + st['reportTries']), (1, '2026-11-23', 1, 1, False, 0)) + body = self.gh.issues[1]['body'] + self.assertIn(report.marker('example'), body) + self.assertIn('demo.thing: a thing to look at', body) + with open(os.path.join(self.folder(), 'issue.md')) as f: + self.assertEqual(f.read(), body) + with open(os.path.join(self.folder(), 'report.md')) as f: + local = f.read() + self.assertIn('Gardener report (local, in full)', local) + self.assertIn(f'demo.thing: a thing to look at | docs/a.md', local) + self.assertEqual(oct(os.stat(self.folder()).st_mode & 0o777), '0o700') + + def test_second_run_the_same_day_does_nothing_and_force_runs_again(self): + self.assertEqual(self.run_cli('run')[0], 0) + calls = list(self.gh.calls) + code, out = self.run_cli('run') + self.assertEqual(code, 0) + self.assertIn('ran today already (2026-11-23)', out) + self.assertEqual(self.gh.calls, calls) # no GitHub call at all + code, out = self.run_cli('run', '--force') + self.assertEqual(code, 0, out) + self.assertEqual(self.gh.writes(), ['create', 'edit']) # the same issue, updated in place + self.assertEqual(len(self.gh.issues), 1) + + def test_the_next_day_runs_again(self): + self.assertEqual(self.run_cli('run')[0], 0) + with mock.patch.dict(os.environ, {'GARDENER_TEST_NOW': '2026-11-24T03:30:00+00:00'}): + self.assertEqual(self.run_cli('run')[0], 0) + self.assertEqual(self.gh.writes(), ['create', 'edit']) + self.assertEqual(self.state()['doneDay'], '2026-11-24') + + def test_the_day_is_the_projects_local_day(self): + # 23:30 UTC on the 23rd is the 24th in Tokyo + self.write_machine(self.project([{'path': self.check}], timeZone='Asia/Tokyo')) + with mock.patch.dict(os.environ, {'GARDENER_TEST_NOW': '2026-11-23T23:30:00+00:00'}): + self.assertEqual(self.run_cli('run')[0], 0) + self.assertEqual(self.state()['doneDay'], '2026-11-24') + + def test_broken_or_old_state_starts_empty_with_a_note(self): + for text in ('{not json', '[]', json.dumps({'version': 0, 'doneDay': '2026-11-23', 'issue': 1}), + json.dumps({'version': 1, 'doneDay': 5, 'issue': 'x'}), ''): + with self.subTest(text=text): + self.gh = gf.FakeGitHub() + self.write_state(text) + code, out = self.run_cli('run') + self.assertEqual(code, 0, out) + st = self.state() + self.assertEqual((st['doneDay'], st['issue']), ('2026-11-23', 1)) + if text.startswith('{"version": 1'): + continue # right version, wrong values: just ignored + self.assertIn('the state file could not be read', self.gh.issues[1]['body']) + + def test_missing_state_folder_parent_is_made(self): + self.write_machine(self.project([{'path': self.check}]), stateDir=os.path.join(self.tmp, 'a', 'b')) + self.assertEqual(self.run_cli('run')[0], 0) + self.assertTrue(os.path.isfile(os.path.join(self.tmp, 'a', 'b', 'example', 'state.json'))) + + def test_stopped_after_the_issue_write_finds_the_same_issue_and_sends_it_alone(self): + """A stop between the issue write and saving its number: the done marker is already there, so the next tick + runs no check; it finds that issue by its title and edits it (no second issue).""" + real = cli.State.save + + def stop_on_issue_number(st, **changes): + if 'issue' in changes: + raise KeyboardInterrupt('stopped (test)') + return real(st, **changes) + with mock.patch.object(cli.State, 'save', stop_on_issue_number): + with self.assertRaises(KeyboardInterrupt): + self.run_cli('run') + st = self.state() + self.assertEqual((st['doneDay'], st['reportPending']), ('2026-11-23', True)) + self.assertNotIn('issue', st) + self.assertEqual(self.run_cli('run')[0], 0) + self.assertEqual(self.runs(), 1) # the checks ran once + self.assertEqual(self.gh.writes(), ['create', 'edit']) + self.assertEqual(len(self.gh.issues), 1) + self.assertEqual((self.state()['issue'], self.state()['reportPending']), (1, False)) + code, out = self.run_cli('run') + self.assertIn('ran today already', out) + self.assertEqual(self.gh.writes(), ['create', 'edit']) + + def test_stopped_before_the_state_is_written_leaves_no_temp_files(self): + def fail_replace(src, dst): + raise OSError(28, 'No space left on device') + with mock.patch.object(cli.os, 'replace', fail_replace): + code, out = self.run_cli('run') + self.assertEqual(code, 1) + self.assertIn('example: failed', out) + self.assertEqual(os.listdir(self.folder()), ['lock']) # no state, no temporary file + self.assertEqual(self.gh.calls, []) # the files first, then GitHub + self.assertEqual(self.run_cli('run')[0], 0) + self.assertEqual(self.gh.writes(), ['create']) + self.assertEqual(self.state()['doneDay'], '2026-11-23') + + def test_a_github_failure_marks_the_day_and_the_next_tick_sends_the_issue_alone(self): + self.gh.fail = 'create' + code, out = self.run_cli('run') + self.assertEqual(code, 1) + self.assertIn('rate limit', out) + st = self.state() + self.assertEqual((st['doneDay'], st['reportPending'], st['reportTries']), ('2026-11-23', True, 1)) + self.gh.fail = None + self.gh.calls.clear() + self.assertEqual(self.run_cli('run')[0], 0) + self.assertEqual(self.runs(), 1) # no check ran again + self.assertEqual(self.gh.writes(), ['create']) + self.assertEqual((self.state()['reportPending'], self.state()['issue']), (False, 1)) + + def test_a_report_issue_that_cannot_be_written_is_tried_three_times_a_day(self): + self.gh.fail = 'create' + for n in range(cli.MAX_REPORT_TRIES): + self.assertEqual(self.run_cli('run')[0], 1) + self.assertEqual(self.state()['reportTries'], n + 1) + self.assertFalse(self.state()['reportPending']) + calls = len(self.gh.calls) + code, out = self.run_cli('run') + self.assertEqual(code, 0) + self.assertIn('ran today already', out) + self.assertEqual(len(self.gh.calls), calls) # no more GitHub calls today + self.assertEqual(self.runs(), 1) + self.gh.fail = None + with mock.patch.dict(os.environ, {'GARDENER_TEST_NOW': '2026-11-24T03:30:00+00:00'}): + self.assertEqual(self.run_cli('run')[0], 0) # the next day: a whole run again + self.assertEqual(self.runs(), 2) + self.assertEqual((self.state()['reportTries'], self.state()['issue']), (0, 1)) + + def test_a_newer_state_file_is_refused_and_kept(self): + text = json.dumps({'version': 2, 'doneDay': '2026-11-20', 'issue': 7, 'newThing': [1]}) + self.write_state(text) + code, out = self.run_cli('run') + self.assertEqual(code, 1) + self.assertIn('newer gardener (version 2)', out) + with open(os.path.join(self.folder(), 'state.json')) as f: + self.assertEqual(f.read(), text) + self.assertEqual((self.gh.calls, self.runs()), ([], 0)) + + def test_a_held_lock_skips_the_project(self): + os.makedirs(self.folder()) + held = cli.lock(self.folder()) + self.addCleanup(os.close, held) + code, out = self.run_cli('run') + self.assertEqual(code, 0) + self.assertIn('another run is going', out) + self.assertEqual(self.gh.calls, []) + self.assertIsNone(cli.lock(self.folder())) + + def test_no_report_repo_writes_the_report_file_only(self): + self.write_machine(self.project([{'path': self.check}], reportRepo='')) + code, out = self.run_cli('run') + self.assertEqual(code, 0, out) + self.assertEqual(self.gh.calls, []) + self.assertTrue(os.path.isfile(os.path.join(self.folder(), 'report.md'))) + self.assertNotIn('issue', self.state()) + + +class DryRun(gf.Temp): + + def test_dry_run_prints_and_writes_nothing_even_after_a_run(self): + fixer = self.script('fixer', ''' + import json, sys + ctx = json.load(sys.stdin) + print(json.dumps({"id": "demo.fix", "severity": "info", "text": "fix is " + str(ctx["fix"])})) + ''') + self.write_machine(self.project([{'path': fixer, 'fix': True}])) + code, out = self.run_cli('run', '--dry-run') + self.assertEqual(code, 0, out) + self.assertIn('demo.fix: fix is False', out) # a fix check runs with fix off + self.assertIn('nothing written', out) + self.assertFalse(os.path.exists(self.state_dir)) + self.assertEqual(self.gh.calls, []) + self.assertEqual(self.run_cli('run')[0], 0) + with open(os.path.join(self.state_dir, 'example', 'report.md')) as f: + self.assertIn('fix is True', f.read()) # a real run: fix on + snapshot = {n: os.stat(os.path.join(self.state_dir, 'example', n)).st_mtime_ns + for n in os.listdir(os.path.join(self.state_dir, 'example'))} + before = self.state() + code, out = self.run_cli('run', '--dry-run') # after the day's run it still prints + self.assertEqual(code, 0) + self.assertIn(report.marker('example'), out) + self.assertEqual(self.state(), before) + self.assertEqual({n: os.stat(os.path.join(self.state_dir, 'example', n)).st_mtime_ns + for n in os.listdir(os.path.join(self.state_dir, 'example'))}, snapshot) + self.assertEqual(self.gh.writes(), ['create']) + + def test_dry_run_with_a_broken_state_file_does_not_touch_it(self): + os.makedirs(os.path.join(self.state_dir, 'example')) + path = os.path.join(self.state_dir, 'example', 'state.json') + with open(path, 'w') as f: + f.write('{broken') + self.write_machine(self.project([{'path': self.finding_script('demo', GOOD)}])) + code, out = self.run_cli('run', '--dry-run') + self.assertEqual(code, 0) + self.assertIn('the state file could not be read', out) + with open(path) as f: + self.assertEqual(f.read(), '{broken') + + +class Checks(gf.Temp): + """The check contract: any failure is exactly one finding and the next check still runs.""" + + def run_checks(self, *checks): + good = self.finding_script('good', GOOD) + self.write_machine(self.project(list(checks) + [{'path': good, 'id': 'after'}])) + code, out = self.run_cli('run', '--dry-run') + self.assertEqual(code, 0, out) + self.assertIn('| warn | after | demo.thing: a thing to look at', out) # the next check still ran + return out + + def parts(self, out): + """(the issue part, the local report) of a dry run's output.""" + head, _, local = out.partition('dry run: the local report.md would get:') + return head.partition('dry run: the report issue would get:')[2], local + + def failed_rows(self, out): + return [ln for ln in self.parts(out)[1].splitlines() if '| gardener.check-failed:' in ln] + + def test_a_check_that_hangs_is_stopped_with_its_children(self): + pidfile = os.path.join(self.tmp, 'child.pid') + hang = self.script('hang', f''' + import subprocess, sys, time + sys.stdin.read() + child = subprocess.Popen([sys.executable, '-c', 'import time; time.sleep(600)']) + open({pidfile!r}, 'w').write(str(child.pid)) + print('{{"id": "half", "severity": "info", "text": "printed before it hung"}}', flush=True) + time.sleep(600) + ''') + start = time.monotonic() + out = self.run_checks({'path': hang, 'timeoutSeconds': 1}) + self.assertLess(time.monotonic() - start, 10) + rows = self.failed_rows(out) + self.assertEqual(len(rows), 1, out) + self.assertIn('stopped after its timeout of 1 s', rows[0]) + self.assertNotIn('printed before it hung', out) # a stopped check's lines are not trusted + with open(pidfile) as f: + child = int(f.read()) + for _ in range(50): + try: + os.kill(child, 0) + except ProcessLookupError: + break + time.sleep(0.1) + else: + self.fail('the hung check\'s child still runs') + + def test_a_check_that_prints_junk(self): + for name, body in (('text', 'print("hello, I am not JSON")'), + ('list', 'print("[1, 2]")'), + ('no-text', 'print(\'{"id": "x", "severity": "warn"}\')'), + ('bad-severity', 'print(\'{"id": "x", "severity": "fatal", "text": "t"}\')'), + ('extra-key', 'print(\'{"id": "x", "severity": "info", "text": "t", "colour": 1}\')'), + ('binary', 'import sys; sys.stdout.buffer.write(bytes(range(256)))')): + with self.subTest(name=name): + good_then_junk = self.script(name, f''' + import sys + sys.stdin.read() + print('{{"id": "early", "severity": "warn", "text": "before the junk"}}') + {body} + ''') + out = self.run_checks({'path': good_then_junk, 'id': 'junk'}) + rows = self.failed_rows(out) + self.assertEqual(len(rows), 1, out) + self.assertIn('not a finding', rows[0]) + self.assertNotIn('before the junk', out) # one failure finding, not half a report + + def test_a_check_that_prints_without_end_is_stopped_at_the_cap(self): + """Like `yes` as a check, in a process with little memory: read as it comes, stopped at the cap within + seconds (not at its timeout), one finding; the next project still runs.""" + yes = self.script('yes', 'import sys\nsys.stdin.read()\nwhile True:\n sys.stdout.write("y\\n" * 4096)\n') + self.write_machine(self.project([{'path': yes, 'timeoutSeconds': 120}], name='first'), + self.project([{'path': self.finding_script('demo', GOOD)}], name='second')) + code = (f'import resource, sys\n' + f'resource.setrlimit(resource.RLIMIT_AS, (400 << 20, 400 << 20))\n' + f'sys.path.insert(0, {gf.LIB!r})\n' + f'from gardener import cli, config\n' + f'config.MACHINE_PATH, config.OWNER_UID = {self.machine!r}, {os.getuid()}\n' + f'sys.exit(cli.main(["run", "--dry-run"]))\n') + start = time.monotonic() + r = subprocess.run([sys.executable, '-I', '-B', '-c', code], capture_output=True, text=True, timeout=200, + env=dict(os.environ, GARDENER_TEST_NOW=gf.NOW), stdin=subprocess.DEVNULL) + self.assertLess(time.monotonic() - start, 30) + self.assertEqual(r.returncode, 0, r.stdout[-2000:] + r.stderr[-2000:]) + self.assertIn(f'first: check yes: failed: printed more than {contract.MAX_OUTPUT} bytes', r.stdout) + self.assertIn('second: dry run: 1 finding(s)', r.stdout) + + def test_an_error_in_the_gardener_on_one_check_is_one_finding(self): + real = runner.run + + def boom(project, check, *a): + if check['id'] == 'first': + raise MemoryError() + return real(project, check, *a) + with mock.patch.object(runner, 'run', boom): + out = self.run_checks({'path': self.finding_script('one', GOOD), 'id': 'first'}) + rows = self.failed_rows(out) + self.assertEqual(len(rows), 1, out) + self.assertIn('the gardener could not run it (MemoryError)', rows[0]) + + def test_too_much_output_and_too_many_findings(self): + flood = self.script('flood', 'import sys\nsys.stdin.read()\nsys.stdout.write("x" * (2 << 20))\n') + out = self.run_checks({'path': flood}) + self.assertIn(f'printed more than {contract.MAX_OUTPUT} bytes', self.failed_rows(out)[0]) + many = self.script('many', ''' + import json, sys + sys.stdin.read() + for i in range(250): + print(json.dumps({"id": "n.%d" % i, "severity": "info", "text": "t"})) + ''') + out = self.run_checks({'path': many}) + self.assertIn('gardener.more-findings: 50 more finding(s) not shown', out) + self.assertEqual(self.failed_rows(out), []) + + def test_a_check_that_exits_non_zero_or_cannot_start(self): + crash = self.script('crash', 'import sys\nsys.stdin.read()\nraise SystemExit("the database is gone")\n') + not_exec = self.script('not-exec', 'print("never")\n', mode=0o644) + out = self.run_checks({'path': crash}, {'path': not_exec}, + {'path': os.path.join(self.tmp, 'missing')}) + rows = self.failed_rows(out) + self.assertEqual(len(rows), 3, out) + issue, local = self.parts(out) + self.assertIn('gardener.check-failed: exited with code 1 (the database is gone)', local) + self.assertIn('gardener.check-failed: exited with code 1 |', issue) + self.assertNotIn('the database is gone', issue) # stderr: the local report only + self.assertEqual(sum('cannot start' in r for r in rows), 2) + + def test_a_missing_root_is_one_finding_per_check(self): + self.write_machine(self.project([{'path': self.finding_script('good', GOOD)}], + root=os.path.join(self.tmp, 'gone'))) + code, out = self.run_cli('run', '--dry-run') + self.assertEqual(code, 0) + self.assertIn('is not a folder', out) + + def test_the_check_gets_the_contract_context_in_its_root(self): + spy = self.script('spy', f''' + import json, os, sys + ctx = json.load(sys.stdin) + json.dump(dict(ctx, cwd=os.getcwd()), open({os.path.join(self.tmp, 'ctx.json')!r}, 'w')) + ''') + self.write_machine(self.project([{'path': spy, 'id': 'spy', 'options': {'a': 1}}])) + self.assertEqual(self.run_cli('run')[0], 0) + with open(os.path.join(self.tmp, 'ctx.json')) as f: + ctx = json.load(f) + self.assertEqual(ctx, {'version': contract.VERSION, 'check': 'spy', 'options': {'a': 1}, 'fix': False, + 'today': '2026-11-23', 'gh': 'gh', 'cwd': self.root, + 'project': {'name': 'example', 'repo': 'example-owner/app', 'root': self.root}}) + + +class Privacy(gf.Temp): + """The report repository may be public: each general check (and a project check) run on things outside the + repository, with host names, addresses and private names around; none of it reaches the issue. The local + report.md has it all.""" + + def git(self, repo, *args): + env = dict(os.environ, GIT_AUTHOR_NAME='t', GIT_AUTHOR_EMAIL='t@example.invalid', GIT_COMMITTER_NAME='t', + GIT_COMMITTER_EMAIL='t@example.invalid', GIT_CONFIG_GLOBAL=os.devnull, GIT_CONFIG_NOSYSTEM='1') + subprocess.run(['git', '-C', repo, *args], check=True, capture_output=True, env=env) + + def write(self, path, text): + os.makedirs(os.path.dirname(path), exist_ok=True) + with open(path, 'w') as f: + f.write(text) + + def test_nothing_local_reaches_the_issue(self): + t = self.tmp + # context-budget: a memory index in an encoded home folder, outside the repository + mem = os.path.join(t, 'claude', 'projects', '-home-someone--secret-proj', 'memory') + self.write(os.path.join(mem, 'MEMORY.md'), '- [Gone](client-acme-plan.md) — x\n') + self.write(os.path.join(mem, 'acquisition-notes.md'), 'o') + self.write(os.path.join(self.root, 'AGENTS.md'), 'x' * 50) + # facts: the machine's table (outside) and the project's own (inside) + facts = self.script('facts', f''' + print('facts check: {t}/machine-facts/STATE.md:12: "VM900 build-box": Updated 2026-01-01 is 326 days ' + 'old (staleDays 30): check the state, then edit the row') + print('facts check: {self.root}/facts/STATE.md:5: "Report kit": Updated 2026-01-01 is 326 days old ' + '(staleDays 30): check the state, then edit the row') + print('facts check: 2 finding(s)') + raise SystemExit(1) + ''') + # worktrees: a merged branch whose worktree is outside the repository + self.git(self.root, 'init', '-q', '-b', 'main') + self.git(self.root, 'add', 'AGENTS.md') + self.git(self.root, 'commit', '-q', '-m', 'one') + self.git(self.root, 'checkout', '-q', '-b', 'client-acme-merger') + self.write(os.path.join(self.root, 'b.txt'), 'b') + self.git(self.root, 'add', 'b.txt') + self.git(self.root, 'commit', '-q', '-m', 'b') + self.git(self.root, 'checkout', '-q', 'main') + self.git(self.root, 'merge', '-q', '--ff-only', 'client-acme-merger') + self.git(self.root, 'worktree', 'add', '-q', os.path.join(t, 'trees', 'w'), 'client-acme-merger') + # workflows-off: the report repository and a private one + gh = self.script('gh', ''' + import json, sys + print(json.dumps({"workflows": [{"name": "Off", "path": ".github/workflows/off.yml", + "state": "disabled_manually"}]})) + ''') + # install-drift: a kit record under a fake host + host = os.path.join(t, 'host') + self.write(os.path.join(host, 'etc', 'kit-secret', 'installed.tsv'), '/opt/kit-secret/tool\tfile\t' + '0' * 64 + '\n') + # a project check: stderr with a host and address, and findings naming local things + leaky = self.script('leaky', f''' + import json, sys + sys.stdin.read() + for f in [{{"id": "host.payroll-box.down", "severity": "warn", "where": "{t}/elsewhere/payroll.md", + "text": "payroll"}}, + {{"id": "p.in", "severity": "warn", "where": "docs/a.md:3", + "text": "see http://100.64.0.1:8080/v1 and {t}/x and nas.local", + "fix": "ssh admin@10.0.0.7 or mail someone@example.org"}}]: + print(json.dumps(f)) + sys.stderr.write("ssh: connect to host build-box.lan (10.1.2.3) port 22: refused\\n") + sys.exit(255) + ''') + quiet = self.script('quiet', f''' + import json, sys + sys.stdin.read() + print(json.dumps({{"id": "p.in", "severity": "warn", "where": "docs/a.md:3", + "text": "see http://100.64.0.1:8080/v1 and {t}/x and nas.local", + "fix": "ssh admin@10.0.0.7 or mail someone@example.org"}})) + print(json.dumps({{"id": "p.out", "severity": "warn", "where": "{t}/elsewhere/payroll.md", + "text": "payroll"}})) + ''') + sock = __import__('socket').socket() + sock.bind(('127.0.0.1', 0)) + port = sock.getsockname()[1] + sock.close() + self.write_machine(self.project( + [{'name': 'context-budget', 'options': {'files': {'AGENTS.md': 40}, 'memoryIndexes': [ + os.path.join(mem, 'MEMORY.md')]}}, + {'name': 'facts', 'options': {'command': facts}}, + {'name': 'worktrees'}, + {'name': 'workflows-off', 'options': {'repos': ['example-owner/app', 'someone/private-repo']}}, + {'name': 'install-drift', 'options': {'etc': '/etc'}}, + {'path': leaky}, {'path': quiet, 'publicText': True}], + model={'endpoint': f'http://127.0.0.1:{port}/v1', 'model': 'm', 'timeoutSeconds': 5}), gh=gh) + with mock.patch.dict(os.environ, {'GARDENER_TEST_PREFIX': host}): + code, out = self.run_cli('run') + self.assertEqual(code, 0, out) + issue = self.gh.issues[1]['body'] + with open(os.path.join(self.state_dir, 'example', 'report.md')) as f: + local = f.read() + secrets = ('-home-someone', 'secret-proj', 'client-acme', 'acquisition-notes', 'VM900', 'build-box', + 'private-repo', 'kit-secret', 'payroll', '100.64', '10.0.0.7', '10.1.2.3', 'admin@', + 'someone@', 'nas.local', 'refused', str(port), t, os.path.expanduser('~')) + for secret in secrets: + self.assertNotIn(secret, issue) + for kept in ('client-acme', 'VM900', 'build-box.lan', 'private-repo', 'kit-secret', 'payroll', + 'acquisition-notes', '10.0.0.7'): + self.assertIn(kept, local) + for shown in ('| AGENTS.md |', 'facts/STATE.md:5', 'Report kit', 'example-owner/app: .github/workflows/off.yml', + 'docs/a.md:3', 'gardener.check-failed: exited with code 255', 'judgment: model unreachable', + '', 'in the local report only', 'see and and ', + 'ssh or mail '): + self.assertIn(shown, issue) + self.assertNotIn('host.', issue) # no hidden finding's id + + def test_a_private_project_reporting_to_a_public_repository_shows_counts_only(self): + """Visibility is read once per repository; a private project repository (or one not set, or unreadable) + and a public report repository: counts only, no judgment.""" + demo = self.finding_script('demo', GOOD) + cases = (('example-owner/private-app', {'example-owner/reports': False, 'example-owner/private-app': True}, True), + ('example-owner/open-app', {'example-owner/reports': False, 'example-owner/open-app': False}, False), + ('example-owner/unknown-app', {'example-owner/reports': False}, True), + ('', {'example-owner/reports': False}, True), + ('example-owner/private-app', {'example-owner/reports': True}, False)) + for repo, visibility, counts in cases: + with self.subTest(repo=repo, visibility=visibility): + self.gh.visibility = visibility + self.gh.calls.clear() + self.write_machine(self.project([{'path': demo, 'publicText': True}], repo=repo, + reportRepo='example-owner/reports')) + code, out = self.run_cli('run', '--dry-run') + self.assertEqual(code, 0, out) + issue = out.partition('dry run: the report issue would get:')[2].partition('dry run: the local')[0] + self.assertEqual(report.COUNTS_ONLY in issue, counts, issue) + self.assertEqual('a thing to look at' in issue, not counts, issue) + self.assertEqual(self.gh.writes(), []) + self.assertLessEqual(self.gh.calls.count('private'), 2) + + +class Window(gf.Temp): + + def setUp(self): + super().setUp() + self.check = self.finding_script('demo', GOOD) + + def at(self, when, *argv): + with mock.patch.dict(os.environ, {'GARDENER_TEST_NOW': when}): + return self.run_cli('run', *argv) + + def test_the_timer_waits_for_the_schedule_time(self): + self.write_machine(self.project([{'path': self.check}], schedule='04:00')) + code, out = self.at('2026-11-23T03:30:00+00:00', '--timer') + self.assertEqual(code, 0) + self.assertIn('not yet: it runs after 04:00', out) + self.assertEqual(self.gh.calls, []) + self.assertEqual(self.at('2026-11-23T04:10:00+00:00', '--timer')[0], 0) + self.assertEqual(self.gh.writes(), ['create']) + self.assertEqual(self.at('2026-11-23T03:30:00+00:00')[0], 0) # without --timer: the done marker only + self.assertEqual(self.gh.writes(), ['create']) + + def test_quiet_hours_that_wrap_past_midnight(self): + self.write_machine(self.project([{'path': self.check}], quietHours='22:00-06:00')) + for when, runs in (('2026-11-23T12:00:00+00:00', False), ('2026-11-23T21:59:00+00:00', False), + ('2026-11-23T22:00:00+00:00', True), ('2026-11-24T05:59:00+00:00', True), + ('2026-11-24T06:00:00+00:00', False)): + with self.subTest(when=when): + self.gh = gf.FakeGitHub() + code, out = self.at(when, '--timer', '--project', 'example') + self.assertEqual(code, 0) + self.assertEqual(bool(self.gh.writes()), runs, out) + if runs: + os.unlink(os.path.join(self.state_dir, 'example', 'state.json')) + + def test_a_window_past_midnight_is_one_day_and_runs_once(self): + """The day is the window's start: 23:00 and 01:00 are the same window, one run. A schedule inside the window + holds the timer until then; a tick missed in the hour before midnight still runs after it.""" + self.write_machine(self.project([{'path': self.check}], quietHours='22:00-06:00', schedule='23:00')) + self.assertEqual(self.at('2026-11-23T22:30:00+00:00', '--timer')[0], 0) + self.assertEqual(self.gh.writes(), []) # before the schedule + for when in ('2026-11-23T23:10:00+00:00', '2026-11-24T00:10:00+00:00', '2026-11-24T05:10:00+00:00'): + self.assertEqual(self.at(when, '--timer')[0], 0) + self.assertEqual(self.gh.writes(), ['create']) # once in the window + self.assertEqual(self.state()['doneDay'], '2026-11-23') + self.at('2026-11-24T23:10:00+00:00', '--timer') + self.assertEqual(self.gh.writes(), ['create', 'edit']) # the next window + self.assertEqual(self.state()['doneDay'], '2026-11-24') + os.unlink(os.path.join(self.state_dir, 'example', 'state.json')) + self.gh = gf.FakeGitHub() + self.at('2026-11-26T01:00:00+00:00', '--timer') # 23:00-24:00 missed: 01:00 still runs + self.assertEqual(self.gh.writes(), ['create']) + self.assertEqual(self.state()['doneDay'], '2026-11-25') + + def test_force_runs_outside_the_window(self): + self.write_machine(self.project([{'path': self.check}], schedule='23:00')) + self.assertEqual(self.at('2026-11-23T03:30:00+00:00', '--timer', '--force')[0], 0) + self.assertEqual(self.gh.writes(), ['create']) + + +class Config(gf.Temp): + + def test_a_missing_machine_file_or_section_is_refused(self): + code, out = self.run_cli('run') + self.assertEqual(code, 2) + self.assertIn('config refused', out) + with open(self.machine, 'w') as f: + json.dump({'version': 1}, f) + self.assertEqual(self.run_cli('run')[0], 2) + + def test_typos_and_bad_values_are_refused_whole(self): + good = self.finding_script('demo', GOOD) + for bad in ({'checks': [{'path': good, 'timeout': 5}]}, + {'checks': [{'name': 'not-a-general-check'}]}, + {'checks': [{'name': 'facts', 'path': good}]}, + {'checks': [{'name': 'facts', 'publicText': True}]}, + {'checks': [{'path': good, 'publicText': 'yes'}]}, + {'checks': [{'path': 'relative/check'}]}, + {'checks': [{'path': good}, {'path': good}]}, + {'checks': [], 'schedule': '25:00'}, + {'checks': [], 'quietHours': '02:00-02:00'}, + {'checks': [], 'timeZone': 'Nowhere/Town'}, + {'checks': [], 'model': {'endpoint': 'ftp://x', 'model': 'm'}}, + {'checks': [], 'model': {'endpoint': 'http://127.0.0.1:1/v1'}}, + {'checks': [], 'repo': 'not a repo'}, + {'checks': [], 'name': 'Upper Case'}): + with self.subTest(bad=bad): + self.write_machine(self.project(**bad)) + code, out = self.run_cli('run') + self.assertEqual(code, 2, out) + self.assertEqual(self.gh.calls, []) + self.write_machine(self.project([]), self.project([])) + self.assertEqual(self.run_cli('run')[0], 2) # the same name twice + + def test_check_lists_projects_without_running_anything(self): + self.write_machine(self.project([{'name': 'worktrees', 'fix': True}, + {'path': self.finding_script('demo', GOOD)}], + model={'endpoint': 'http://127.0.0.1:9/v1', 'model': 'local'})) + code, out = self.run_cli('check') + self.assertEqual(code, 0, out) + self.assertIn('example: report to example-owner/app, any time of day, model local', out) + self.assertIn('worktrees: worktrees (fix), timeout 300 s', out) + self.assertIn('demo: ', out) + self.assertFalse(os.path.exists(self.state_dir)) + + def test_an_unknown_project_is_refused(self): + self.write_machine(self.project([])) + self.assertEqual(self.run_cli('run', '--project', 'other')[0], 2) + + def test_an_error_of_any_kind_in_one_project_does_not_stop_the_next(self): + real = report.render_issue + + def boom(name, *a, **kw): + if name == 'first': + raise MemoryError() + return real(name, *a, **kw) + self.write_machine(self.project([{'path': self.finding_script('demo', GOOD)}], name='first'), + self.project([{'path': self.finding_script('demo2', GOOD)}], name='second')) + with mock.patch.object(report, 'render_issue', boom): + code, out = self.run_cli('run') + self.assertEqual(code, 1) + self.assertIn('first: failed: MemoryError', out) + self.assertEqual(self.state('second')['doneDay'], '2026-11-23') + + def test_a_report_repository_changed_the_same_day_runs_again_for_the_new_one(self): + """A part rendered (and allow-listed) for one report repository never goes to another; the old repository's + issue number is not used in the new one.""" + demo = self.finding_script('demo', GOOD) + self.gh.fail = 'create' + self.write_machine(self.project([{'path': demo, 'publicText': True}], reportRepo='example-owner/old-reports')) + self.assertEqual(self.run_cli('run')[0], 1) + self.assertTrue(self.state()['reportPending']) + self.gh.fail = None + self.gh.visibility = {'example-owner/new-reports': True} + self.write_machine(self.project([{'path': demo, 'publicText': True}], reportRepo='example-owner/new-reports')) + code, out = self.run_cli('run') + self.assertEqual(code, 0, out) + self.assertIn('the report repository changed today', out) + self.assertEqual([i['repo'] for i in self.gh.issues.values()], ['example-owner/new-reports']) + st = self.state() + self.assertEqual((st['reportRepo'], st['reportPending'], st['issue']), ('example-owner/new-reports', False, 1)) + self.assertIn('ran today already', self.run_cli('run')[1]) + + def test_one_projects_failure_does_not_stop_the_next(self): + bad = self.project([{'path': self.finding_script('demo', GOOD)}], name='first') + good = self.project([{'path': self.finding_script('demo2', GOOD)}], name='second') + self.write_machine(bad, good) + os.makedirs(self.state_dir) + with open(os.path.join(self.state_dir, 'first'), 'w') as f: # a file where its folder should be + f.write('x') + code, out = self.run_cli('run') + self.assertEqual(code, 1) + self.assertIn('first: failed', out) + self.assertEqual(self.state('second')['doneDay'], '2026-11-23') + + def test_the_example_machine_file_section_parses(self): + here = os.path.dirname(gf.KIT) + with open(os.path.join(here, 'common', 'machine.example.json')) as f: + data = json.load(f) + s = config.parse(data['gardener'], 'example') + self.assertTrue(s['projects']) + for p in s['projects']: + for c in p['checks']: + self.assertFalse(c['path'].startswith('/home/'), 'placeholders only in the public example') + + +MUTATIONS = { + 'the done marker skips a second run': ( + 'cli', 'not args.force and state.done_day() == today', 'not args.force and False', + 'State.test_second_run_the_same_day_does_nothing_and_force_runs_again'), + 'a pending report is sent alone on the next tick': ( + 'cli', " if state.data.get('reportPending') is True and project['reportRepo']:", + ' if False:', 'State.test_stopped_after_the_issue_write_finds_the_same_issue_and_sends_it_alone'), + 'the done marker comes before the issue write': ( + 'cli', "reportTries=0, reportRepo=project['reportRepo'])\n", + "reportTries=0, reportRepo=project['reportRepo']) if False else None\n", + 'State.test_a_github_failure_marks_the_day_and_the_next_tick_sends_the_issue_alone'), + 'the issue is tried at most MAX_REPORT_TRIES a day': ( + 'cli', 'reportPending=tries < MAX_REPORT_TRIES)', 'reportPending=True)', + 'State.test_a_report_issue_that_cannot_be_written_is_tried_three_times_a_day'), + 'a newer state is refused': ( + 'cli', ' if state.newer and not args.dry_run:', ' if False:', + 'State.test_a_newer_state_file_is_refused_and_kept'), + 'a dry run writes nothing': ( + 'cli', " if args.dry_run:\n say(f'{name}: dry run", " if False:\n say(f'{name}: dry run", + 'DryRun.test_dry_run_prints_and_writes_nothing_even_after_a_run'), + 'a dry run turns fix off': ( + 'cli', "check['fix'] and not args.dry_run", "check['fix']", + 'DryRun.test_dry_run_prints_and_writes_nothing_even_after_a_run'), + 'a hung check is stopped': ( + 'runner', "time.monotonic() + check['timeoutSeconds']", "time.monotonic() + check['timeoutSeconds'] * 15", + 'Checks.test_a_check_that_hangs_is_stopped_with_its_children'), + 'the hung check\'s group is killed': ( + 'runner', 'start_new_session=True', 'start_new_session=False', + 'Checks.test_a_check_that_hangs_is_stopped_with_its_children'), + 'junk is one failure, not half a report': ( + 'runner', ' except ValueError as e:\n', ' except ValueError as e:\n continue\n', + 'Checks.test_a_check_that_prints_junk'), + 'the window holds the timer': ( + 'cli', ' if args.timer and not args.force and why_not:', ' if False:', + 'Window.test_the_timer_waits_for_the_schedule_time'), + 'output is read up to the cap': ( + 'runner', " if len(out) > contract.MAX_OUTPUT:\n return out, err, 'too-much'\n", + '', 'Checks.test_a_check_that_prints_without_end_is_stopped_at_the_cap'), + 'an error on one check is one finding': ( + 'cli', ' except Exception as e: # a MemoryError too', ' except OSError as e: #', + 'Checks.test_an_error_in_the_gardener_on_one_check_is_one_finding'), + 'an error in one project never stops the next': ( + 'cli', ' except Exception as e: # anything', ' except OSError as e: #', + 'Config.test_an_error_of_any_kind_in_one_project_does_not_stop_the_next'), + 'the issue is built from the allow-list': ( + 'cli', " part = report.render_issue(name, today, findings, notes, answer, root, home, project['reportRepo'],\n" + " text_checks, counts)", + " part = report.render_local(name, today, findings, notes, answer)", + 'Privacy.test_nothing_local_reaches_the_issue'), + 'a project check\'s text is public only with publicText': ( + 'cli', " text_checks = {c['id'] for c in project['checks'] if c['name'] or c['publicText']}", + " text_checks = {c['id'] for c in project['checks']}", 'Privacy.test_nothing_local_reaches_the_issue'), + 'a private project to a public report repository: counts only': ( + 'cli', ' return not pr or gh.private(pr) is not False', ' return False', + 'Privacy.test_a_private_project_reporting_to_a_public_repository_shows_counts_only'), + 'an unreadable visibility is counts only': ( + 'cli', ' except report.GitHubError:\n return True', ' except report.GitHubError:\n return False', + 'Privacy.test_a_private_project_reporting_to_a_public_repository_shows_counts_only'), + 'a changed report repository runs again': ( + 'cli', " moved = (state.data.get('reportRepo') or '') != project['reportRepo']", ' moved = False', + 'Config.test_a_report_repository_changed_the_same_day_runs_again_for_the_new_one'), + 'publicText only for project checks': ( + 'config', " if c['name'] and c['publicText']:", ' if False:', + 'Config.test_typos_and_bad_values_are_refused_whole'), + 'the day of a window past midnight is its start': ( + 'cli', " day = (lt - datetime.timedelta(minutes=pos)).date().isoformat()", " day = lt.date().isoformat()", + 'Window.test_a_window_past_midnight_is_one_day_and_runs_once'), + 'a held lock skips': ( + 'cli', ' if held is None:\n say', ' if False:\n say', + 'State.test_a_held_lock_skips_the_project'), +} + + +class RedCheck(unittest.TestCase): + + def test_each_guard_has_a_test_that_fails_without_it(self): + gf.red_check(self, os.path.abspath(__file__), MUTATIONS) + + +if __name__ == '__main__': + unittest.main(verbosity=2)